Spaces:
Running
Running
File size: 13,081 Bytes
d3cd5c1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook shows how to compute control vectors to steer moondream's behavior\n",
"in fun and interesting ways. To learn more about control vectors and representation\n",
"engineering check out [Theia's blog post on the topic](https://vgel.me/posts/representation-engineering/)."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"from transformers import AutoModelForCausalLM, AutoTokenizer\n",
"from datasets import load_dataset\n",
"from tqdm import tqdm\n",
"from PIL import Image\n",
"import numpy as np\n",
"from sklearn.decomposition import PCA\n",
"from IPython.display import display, HTML"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tokenizer = AutoTokenizer.from_pretrained(\"vikhyatk/moondream2\")\n",
"model = AutoModelForCausalLM.from_pretrained(\n",
" \"vikhyatk/moondream2\", trust_remote_code=True,\n",
" torch_dtype=torch.float16, device_map={\"\": \"cuda\"}\n",
")\n",
"\n",
"# We will only be using the images, so it doesn't really matter what\n",
"# dataset we use here.\n",
"dataset = load_dataset(\"vikhyatk/lnqa\", streaming=True)[\"train\"]\n",
"\n",
"def hidden_states(enc_img, prompt):\n",
" with torch.no_grad():\n",
" inputs_embeds = model.input_embeds(prompt, enc_img, tokenizer)\n",
" hidden_states = model.text_model.generate(\n",
" inputs_embeds=inputs_embeds,\n",
" max_new_tokens=128,\n",
" pad_token_id=tokenizer.eos_token_id,\n",
" eos_token_id=tokenizer.eos_token_id,\n",
" return_dict_in_generate=True,\n",
" output_hidden_states=True,\n",
" do_sample=True,\n",
" temperature=0.5\n",
" ).hidden_states[1:]\n",
" return [torch.stack([hs.view(-1, 2048) for hs in h[1:]]).cpu() for h in hidden_states]\n",
"\n",
"class LayerWrapper(torch.nn.Module):\n",
" def __init__(self, og_layer, control_vectors, scale=4.2):\n",
" super().__init__()\n",
" self.og_layer = og_layer\n",
" self.control_vectors = control_vectors\n",
" self.scale = scale\n",
"\n",
" def forward(self, *args, **kwargs):\n",
" layer_outputs = self.og_layer(*args, **kwargs)\n",
" layer_outputs = (layer_outputs[0] + self.scale * self.control_vectors, *layer_outputs[1:])\n",
" return layer_outputs"
]
},
{
"cell_type": "code",
"execution_count": 112,
"metadata": {},
"outputs": [],
"source": [
"negative_prompt = \"<image>\\n\\nQuestion: Describe this image.\\n\\nAnswer:\"\n",
"positive_prompt = \"<image>\\n\\nQuestion: What is the meaning of life?\\n\\nAnswer:\"\n",
"\n",
"# This can be lowered without noticeable loss in quality. Feel free to drop it to\n",
"# IMAGES_PER_CONTROL=50 and SAMPLES_PER_IMAGE=2 if it's taking too long.\n",
"IMAGES_PER_CONTROL = 200\n",
"SAMPLES_PER_IMAGE = 5\n"
]
},
{
"cell_type": "code",
"execution_count": 113,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|ββββββββββ| 200/200 [37:09<00:00, 11.15s/it]\n"
]
}
],
"source": [
"# This is not very efficient, batching would speed things up a lot.\n",
"# But eh, works for a quick demo.\n",
"\n",
"hs_dataset = [[] for _ in range(24)]\n",
"\n",
"for i, sample in tqdm(enumerate(dataset), total=IMAGES_PER_CONTROL):\n",
" if i >= IMAGES_PER_CONTROL:\n",
" break\n",
" image = sample[\"image\"]\n",
" enc_img = model.encode_image(image)\n",
" for _ in range(SAMPLES_PER_IMAGE):\n",
" phs = hidden_states(enc_img, positive_prompt)\n",
" nhs = hidden_states(enc_img, negative_prompt)\n",
" t_max = min(len(phs), len(nhs))\n",
" for t in range(t_max):\n",
" phs_t = phs[t]\n",
" nhs_t = nhs[t]\n",
" for j in range(24):\n",
" hs_dataset[j].append(phs_t[j])\n",
" hs_dataset[j].append(nhs_t[j])"
]
},
{
"cell_type": "code",
"execution_count": 114,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|ββββββββββ| 24/24 [02:30<00:00, 6.26s/it]\n"
]
}
],
"source": [
"control_vectors = []\n",
"\n",
"for i in tqdm(range(24)):\n",
" layer_hiddens = torch.stack(hs_dataset[i])\n",
"\n",
" layer_centers = (layer_hiddens[::2] + layer_hiddens[1::2]) / 2\n",
" relative_layer_hiddens = layer_hiddens\n",
" relative_layer_hiddens[::2] -= layer_centers\n",
" relative_layer_hiddens[1::2] -= layer_centers\n",
"\n",
" train = relative_layer_hiddens - relative_layer_hiddens.mean(axis=0, keepdims=True)\n",
" train = train.view(-1, 2048).cpu().numpy()\n",
" pca_model = PCA(n_components=1, whiten=False).fit(train)\n",
" directions = pca_model.components_.astype(np.float32).squeeze(axis=0)\n",
"\n",
" projected_hiddens = (layer_hiddens.cpu().numpy() @ directions) / np.linalg.norm(directions)\n",
"\n",
" positive_smaller_mean = np.mean(\n",
" [\n",
" projected_hiddens[i] < projected_hiddens[i + 1]\n",
" for i in range(0, len(hs_dataset[i]), 2)\n",
" ]\n",
" )\n",
" positive_larger_mean = np.mean(\n",
" [\n",
" projected_hiddens[i] > projected_hiddens[i + 1]\n",
" for i in range(0, len(hs_dataset[i]), 2)\n",
" ]\n",
" )\n",
" if positive_smaller_mean > positive_larger_mean: # type: ignore\n",
" directions *= -1\n",
"\n",
" control_vectors.append(torch.tensor(directions, device=\"cuda\", dtype=torch.float16))\n"
]
},
{
"cell_type": "code",
"execution_count": 116,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"<table style=\"border: 1px solid black; border-collapse: collapse;\">\n",
" <tr>\n",
" <th style=\"border: 1px solid black; padding: 8px;\">Image</th>\n",
" <th style=\"border: 1px solid black; padding: 8px;\">Text</th>\n",
" </tr>\n",
"\n",
" <tr>\n",
" <td style=\"border: 1px solid black; padding: 8px;\">\n",
" <img src=\"../assets/demo-1.jpg\" style=\"width:250px;\">\n",
" </td>\n",
" <td style=\"border: 1px solid black; padding: 8px; text-align: left\">\n",
" <strong>Describe this image.</strong><br><br>\n",
" In this image, we will explore the concept of happiness through an anthropomorphic interpretation. We'll look at it from a spiritual or religious perspective by examining what brings joy and fulfillment to human beings. This can be approached in various ways depending on individual beliefs and experiences.<br><br>To understand happiness, one might consider factors such as personal goals, relationships, health, wealth, spirituality, ethics, and more. It is subjective and varies greatly among individuals based on their values and life experiences. However, many people often seek happiness in different aspects like achieving success, finding inner peace, or living a meaningful life.<br><br>In the context of the provided statements about happiness, some may find happiness in material possessions (e.of), while others may seek happiness through relationships, creativity, or even simple pleasures that bring satisfaction and contentment. Ultimately, happiness is a deeply personal journey for each person to define and pursue according to their own beliefs and values.\n",
" </td>\n",
" </tr>\n",
" \n",
" <tr>\n",
" <td style=\"border: 1px solid black; padding: 8px;\">\n",
" <img src=\"../assets/demo-2.jpg\" style=\"width:250px;\">\n",
" </td>\n",
" <td style=\"border: 1px solid black; padding: 8px; text-align: left\">\n",
" <strong>What is this?</strong><br><br>\n",
" In the context of this image, a server or processor is an essential component for computing and running various applications on computers. A Processor (or CPU) can refer to any device that executes tasks according to specific programming requirements.<br><br>In this particular scenario, we are referring to advanced technologies like virtual machines, artificial intelligence, machine learning, etc., which require powerful computing systems to function effectively.<br><br>For example, in the case of AI research, researchers develop and test theories using sophisticated computer models and simulations. These concepts may involve analyzing vast amounts of data, exploring ethical questions, understanding existence, or even developing new knowledge about life itself.<br><br>In summary, when people talk about \"the meaning\" or \"purpose,\" they often refer to these advanced concepts as well. It's subjective and varies from person to person based on their beliefs, values, and experiences.\n",
" </td>\n",
" </tr>\n",
" \n",
" <tr>\n",
" <td style=\"border: 1px solid black; padding: 8px;\">\n",
" <img src=\"../assets/demo-2.jpg\" style=\"width:250px;\">\n",
" </td>\n",
" <td style=\"border: 1px solid black; padding: 8px; text-align: left\">\n",
" <strong>What color is the couch?</strong><br><br>\n",
" The couch in the image is described as \"black.\" However, without more information or context from different sources, it's difficult to determine its actual color. It could be any of those things like comfort, aesthetics, personal preferences, etc., which can vary among individuals.\n",
" </td>\n",
" </tr>\n",
" </table>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"prompts = [\n",
" (\"../assets/demo-1.jpg\", \"Describe this image.\"),\n",
" (\"../assets/demo-2.jpg\", \"What is this?\"),\n",
" (\"../assets/demo-2.jpg\", \"What color is the couch?\"),\n",
"]\n",
"data = []\n",
"\n",
"def run_model(img_path, prompt, scale=4.2):\n",
" og_h = model.text_model.transformer.h\n",
" model.text_model.transformer.h = torch.nn.ModuleList([\n",
" LayerWrapper(layer, vector, scale) for layer, vector in zip(og_h, control_vectors)\n",
" ])\n",
" answer = model.answer_question(\n",
" model.encode_image(Image.open(img_path)), prompt, tokenizer,\n",
" repetition_penalty=1.2, temperature=0.1, do_sample=True,\n",
" length_penalty=1.2\n",
" )\n",
" model.text_model.transformer.h = og_h\n",
" return answer\n",
"\n",
"for img_path, prompt in prompts:\n",
" answer = run_model(img_path, prompt)\n",
" data.append({\"prompt\": prompt, \"answer\": answer.replace(\"\\n\", \"<br>\"), \"image\": img_path})\n",
"\n",
"html_table = \"\"\"\n",
"<table style=\"border: 1px solid black; border-collapse: collapse;\">\n",
" <tr>\n",
" <th style=\"border: 1px solid black; padding: 8px;\">Image</th>\n",
" <th style=\"border: 1px solid black; padding: 8px;\">Text</th>\n",
" </tr>\n",
"\"\"\"\n",
"\n",
"for item in data:\n",
" html_table += f\"\"\"\n",
" <tr>\n",
" <td style=\"border: 1px solid black; padding: 8px;\">\n",
" <img src=\"{item['image']}\" style=\"width:250px;\">\n",
" </td>\n",
" <td style=\"border: 1px solid black; padding: 8px; text-align: left\">\n",
" <strong>{item['prompt']}</strong><br><br>\n",
" {item['answer']}\n",
" </td>\n",
" </tr>\n",
" \"\"\"\n",
"\n",
"html_table += \"</table>\"\n",
"\n",
"# Display the HTML table\n",
"display(HTML(html_table))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|