Spaces:
Running
on
Zero
Running
on
Zero
File size: 18,129 Bytes
b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 bc61ed1 b874271 |
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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Intel MKL WARNING: Support of Intel(R) Streaming SIMD Extensions 4.2 (Intel(R) SSE4.2) enabled only processors has been deprecated. Intel oneAPI Math Kernel Library 2025.0 will require Intel(R) Advanced Vector Extensions (Intel(R) AVX) instructions.\n",
"Intel MKL WARNING: Support of Intel(R) Streaming SIMD Extensions 4.2 (Intel(R) SSE4.2) enabled only processors has been deprecated. Intel oneAPI Math Kernel Library 2025.0 will require Intel(R) Advanced Vector Extensions (Intel(R) AVX) instructions.\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/shreshth/anaconda3/envs/llm-test/lib/python3.11/site-packages/threadpoolctl.py:1214: RuntimeWarning: \n",
"Found Intel OpenMP ('libiomp') and LLVM OpenMP ('libomp') loaded at\n",
"the same time. Both libraries are known to be incompatible and this\n",
"can cause random crashes or deadlocks on Linux when loaded in the\n",
"same Python program.\n",
"Using threadpoolctl may cause crashes or deadlocks. For more\n",
"information and possible workarounds, please see\n",
" https://github.com/joblib/threadpoolctl/blob/master/multiple_openmp.md\n",
"\n",
" warnings.warn(msg, RuntimeWarning)\n"
]
},
{
"data": {
"text/plain": [
"{'name': 'nq',\n",
" 't_bmodel': LogisticRegression(),\n",
" 't_amodel': LogisticRegression(),\n",
" 'sep_layer_range': (27, 32),\n",
" 'ap_layer_range': (17, 22)}"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# test probe loading \n",
"import pickle as pkl\n",
"import numpy as np\n",
"import sklearn \n",
"from sklearn import linear_model\n",
"import os\n",
"os.environ[\"PYTORCH_ENABLE_MPS_FALLBACK\"] = \"1\"\n",
"\n",
"# load the probe data\n",
"with open(\"./model/20240625-131035_demo.pkl\", \"rb\") as f:\n",
" probe_data = pkl.load(f)\n",
"# take the NQ open one\n",
"probe_data = probe_data[-2]\n",
"probe_data"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"se_probe = probe_data['t_bmodel']\n",
"se_layer_range = probe_data['sep_layer_range']\n",
"acc_probe = probe_data['t_amodel']\n",
"acc_layer_range = probe_data['ap_layer_range']"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "30a1c8e576f6448bb228b4ae9a3a8a48",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Loading checkpoint shards: 0%| | 0/2 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Some parameters are on the meta device device because they were offloaded to the disk.\n"
]
}
],
"source": [
"import torch\n",
"from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer\n",
"\n",
"model_id = \"meta-llama/Llama-2-7b-chat-hf\"\n",
"model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"auto\")\n",
"tokenizer = AutoTokenizer.from_pretrained(model_id)\n",
"tokenizer.use_default_system_prompt = False"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Љ ( \"ass\n",
"ЪЏ\n",
"հ MO-OC\n",
"tensor(30488, device='mps:0') Љ 1.0 -0.014414779243550946\n",
"tensor(313, device='mps:0') ( -0.9998164331881116 0.9597905489862286\n",
"tensor(376, device='mps:0') \" 0.9999998197256226 -0.9792630307582237\n",
"tensor(465, device='mps:0') ass -0.9999994897301452 0.9680999957882863\n",
"tensor(13, device='mps:0') \n",
" -0.99999964561314 0.9983907264450047\n",
"tensor(31147, device='mps:0') Ъ 1.0 -0.9999976710226259\n",
"tensor(30282, device='mps:0') Џ 1.0 0.9999912572082477\n",
"tensor(13, device='mps:0') \n",
" 0.9999999999869607 0.9999964462206883\n",
"tensor(31488, device='mps:0') հ 1.0 -1.0\n",
"tensor(341, device='mps:0') M 0.9045896738793786 0.5590883316684834\n",
"tensor(29949, device='mps:0') O -0.9999999803476437 -0.5270551643185932\n",
"tensor(29899, device='mps:0') - 0.9992488974195408 0.9987826119127319\n",
"tensor(29949, device='mps:0') O -0.9713693636571169 0.9993573968241007\n",
"tensor(29907, device='mps:0') C -0.9999999701427968 0.9904799691607524\n",
" <span style=\"background-color: #FF0000; color: black\">Љ</span> <span style=\"background-color: #00FF00; color: black\">(</span> <span style=\"background-color: #FF0000; color: black\">\"</span> <span style=\"background-color: #00FF00; color: black\">ass</span> <span style=\"background-color: #00FF00; color: black\">\n",
"</span> <span style=\"background-color: #FF0000; color: black\">Ъ</span> <span style=\"background-color: #FF0000; color: black\">Џ</span> <span style=\"background-color: #FF0000; color: black\">\n",
"</span> <span style=\"background-color: #FF0000; color: black\">հ</span> <span style=\"background-color: #FF1818; color: black\">M</span> <span style=\"background-color: #00FF00; color: black\">O</span> <span style=\"background-color: #FF0000; color: black\">-</span> <span style=\"background-color: #07FF07; color: black\">O</span> <span style=\"background-color: #00FF00; color: black\">C</span>\n"
]
}
],
"source": [
"from typing import Tuple\n",
"\n",
"MAX_INPUT_TOKEN_LENGTH = 512\n",
"\n",
"\n",
"def generate(\n",
" message: str,\n",
" system_prompt: str,\n",
" max_new_tokens: int = 10,\n",
" temperature: float = 0.6,\n",
" top_p: float = 0.9,\n",
" top_k: int = 50,\n",
" repetition_penalty: float = 1.2,\n",
") -> Tuple[str, str]:\n",
" conversation = []\n",
" if system_prompt:\n",
" conversation.append({\"role\": \"system\", \"content\": system_prompt})\n",
" conversation.append({\"role\": \"user\", \"content\": message})\n",
"\n",
" input_ids = tokenizer.apply_chat_template(conversation, return_tensors=\"pt\")\n",
" if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:\n",
" input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]\n",
" input_ids = input_ids.to(model.device)\n",
"\n",
" #### Generate without threading\n",
" generation_kwargs = dict(\n",
" input_ids=input_ids,\n",
" max_new_tokens=max_new_tokens,\n",
" do_sample=True,\n",
" top_p=top_p,\n",
" top_k=top_k,\n",
" temperature=temperature,\n",
" repetition_penalty=repetition_penalty,\n",
" output_hidden_states=True,\n",
" return_dict_in_generate=True,\n",
" attention_mask=torch.ones_like(input_ids),\n",
" )\n",
" with torch.no_grad():\n",
" outputs = model.generate(**generation_kwargs)\n",
" generated_tokens = outputs.sequences[0, input_ids.shape[1]:]\n",
" generated_text = tokenizer.decode(generated_tokens, skip_special_tokens=True)\n",
" print(generated_text)\n",
" # hidden states\n",
" hidden = outputs.hidden_states # list of tensors, one for each token, then (batch size, sequence length, hidden size)\n",
"\n",
" se_highlighted_text = \"\"\n",
" acc_highlighted_text = \"\"\n",
"\n",
" # skip the first hidden state as it is the prompt\n",
" for i in range(1, len(hidden)):\n",
"\n",
" # Semantic Uncertainty Probe\n",
" token_embeddings = torch.stack([generated_token[0, 0, :].cpu() for generated_token in hidden[i]]).numpy() # (num_layers, hidden_size)\n",
" se_concat_layers = token_embeddings[se_layer_range[0]:se_layer_range[1]].reshape(-1)\n",
" se_probe_pred = se_probe.predict_proba(se_concat_layers.reshape(1, -1))[0][1] * 2 - 1\n",
" \n",
" # Accuracy Probe\n",
" acc_concat_layers = token_embeddings[acc_layer_range[0]:acc_layer_range[1]].reshape(-1)\n",
" acc_probe_pred = (1 - acc_probe.predict_proba(acc_concat_layers.reshape(1, -1))[0][1]) * 2 - 1\n",
" \n",
" output_id = outputs.sequences[0, input_ids.shape[1]+i]\n",
" output_word = tokenizer.decode(output_id)\n",
" print(output_id, output_word, se_probe_pred, acc_probe_pred) \n",
"\n",
" se_new_highlighted_text = highlight_text(output_word, se_probe_pred)\n",
" acc_new_highlighted_text = highlight_text(output_word, acc_probe_pred)\n",
" se_highlighted_text += f\" {se_new_highlighted_text}\"\n",
" acc_highlighted_text += f\" {acc_new_highlighted_text}\"\n",
" \n",
" return se_highlighted_text, acc_highlighted_text\n",
"\n",
"\n",
"def highlight_text(text: str, uncertainty_score: float) -> str:\n",
" if uncertainty_score > 0:\n",
" html_color = \"#%02X%02X%02X\" % (\n",
" 255,\n",
" int(255 * (1 - uncertainty_score)),\n",
" int(255 * (1 - uncertainty_score)),\n",
" )\n",
" else:\n",
" html_color = \"#%02X%02X%02X\" % (\n",
" int(255 * (1 + uncertainty_score)),\n",
" 255,\n",
" int(255 * (1 + uncertainty_score)),\n",
" )\n",
" return '<span style=\"background-color: {}; color: black\">{}</span>'.format(\n",
" html_color, text\n",
" )\n",
"\n",
"message = \"What is the capital of France?\"\n",
"system_prompt = \"\"\n",
"se_highlighted_text, acc_highlighted_text = generate(message, system_prompt)\n",
"print(se_highlighted_text)\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([[ 1, 518, 25580, 29962, 3532, 14816, 29903, 6778, 13, 3492,\n",
" 526, 263, 8444, 20255, 29889, 13, 29966, 829, 14816, 29903,\n",
" 6778, 13, 13, 5816, 338, 278, 7483, 310, 3444, 29973,\n",
" 518, 29914, 25580, 29962]]) torch.Size([1, 34])\n",
"\n",
" \n"
]
},
{
"ename": "KeyboardInterrupt",
"evalue": "",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[13], line 37\u001b[0m\n\u001b[1;32m 35\u001b[0m generated_text \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 36\u001b[0m highlighted_text \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m---> 37\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m output \u001b[38;5;129;01min\u001b[39;00m streamer:\n\u001b[1;32m 38\u001b[0m \u001b[38;5;28mprint\u001b[39m(output)\n\u001b[1;32m 39\u001b[0m generated_text \u001b[38;5;241m+\u001b[39m\u001b[38;5;241m=\u001b[39m output\n",
"File \u001b[0;32m~/anaconda3/envs/llm-test/lib/python3.11/site-packages/transformers/generation/streamers.py:223\u001b[0m, in \u001b[0;36mTextIteratorStreamer.__next__\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 222\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m__next__\u001b[39m(\u001b[38;5;28mself\u001b[39m):\n\u001b[0;32m--> 223\u001b[0m value \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtext_queue\u001b[38;5;241m.\u001b[39mget(timeout\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtimeout)\n\u001b[1;32m 224\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m value \u001b[38;5;241m==\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mstop_signal:\n\u001b[1;32m 225\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mStopIteration\u001b[39;00m()\n",
"File \u001b[0;32m~/anaconda3/envs/llm-test/lib/python3.11/queue.py:180\u001b[0m, in \u001b[0;36mQueue.get\u001b[0;34m(self, block, timeout)\u001b[0m\n\u001b[1;32m 178\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m remaining \u001b[38;5;241m<\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m0.0\u001b[39m:\n\u001b[1;32m 179\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m Empty\n\u001b[0;32m--> 180\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mnot_empty\u001b[38;5;241m.\u001b[39mwait(remaining)\n\u001b[1;32m 181\u001b[0m item \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_get()\n\u001b[1;32m 182\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mnot_full\u001b[38;5;241m.\u001b[39mnotify()\n",
"File \u001b[0;32m~/anaconda3/envs/llm-test/lib/python3.11/threading.py:324\u001b[0m, in \u001b[0;36mCondition.wait\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m 322\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 323\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m timeout \u001b[38;5;241m>\u001b[39m \u001b[38;5;241m0\u001b[39m:\n\u001b[0;32m--> 324\u001b[0m gotit \u001b[38;5;241m=\u001b[39m waiter\u001b[38;5;241m.\u001b[39macquire(\u001b[38;5;28;01mTrue\u001b[39;00m, timeout)\n\u001b[1;32m 325\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 326\u001b[0m gotit \u001b[38;5;241m=\u001b[39m waiter\u001b[38;5;241m.\u001b[39macquire(\u001b[38;5;28;01mFalse\u001b[39;00m)\n",
"\u001b[0;31mKeyboardInterrupt\u001b[0m: "
]
}
],
"source": [
"from threading import Thread\n",
"\n",
"system_prompt = \"You are a helpful assistant.\"\n",
"message = \"what is the capital of France?\"\n",
"max_new_tokens = 100\n",
"top_p = 0.9\n",
"top_k = 50\n",
"temperature = 0.7\n",
"repetition_penalty = 1.2\n",
"\n",
"conversation = []\n",
"\n",
"conversation.append({\"role\": \"system\", \"content\": system_prompt})\n",
"conversation.append({\"role\": \"user\", \"content\": message})\n",
"input_ids = tokenizer.apply_chat_template(conversation, return_tensors=\"pt\")\n",
"input_ids = input_ids.to(model.device)\n",
"print(input_ids, input_ids.shape)\n",
"streamer = TextIteratorStreamer(tokenizer, timeout=1000.0, skip_prompt=True, skip_special_tokens=True)\n",
"generation_kwargs = dict(\n",
" input_ids=input_ids,\n",
" max_new_tokens=max_new_tokens,\n",
" do_sample=True,\n",
" top_p=top_p,\n",
" top_k=top_k,\n",
" temperature=temperature,\n",
" repetition_penalty=repetition_penalty,\n",
" streamer=streamer,\n",
" output_hidden_states=True,\n",
" return_dict_in_generate=True,\n",
")\n",
"\n",
"thread = Thread(target=model.generate, kwargs=generation_kwargs)\n",
"thread.start()\n",
"\n",
"generated_text = \"\"\n",
"highlighted_text = \"\"\n",
"for output in streamer:\n",
" print(output)\n",
" generated_text += output\n",
"\n",
" # yield generated_text\n",
"for new_text in streamer:\n",
" print(new_text)\n",
" generated_text += new_text\n",
" print(generated_text)\n",
" current_input_ids = tokenizer.encode(generated_text, return_tensors=\"pt\").to(model.device)\n",
" print(current_input_ids, current_input_ids.shape)\n",
" with torch.no_grad():\n",
" outputs = model(current_input_ids, output_hidden_states=True)\n",
" hidden = outputs.hidden_states \n",
" print(len(hidden))\n",
" print(hidden[-1].shape)\n",
" # Stack second last token embeddings from all layers \n",
" # if len(hidden) == 1: # FIX: runtime error for mistral-7b on bioasq\n",
" # sec_last_input = hidden[0]\n",
" # elif ((n_generated - 2) >= len(hidden)):\n",
" # sec_last_input = hidden[-2]\n",
" # else:\n",
" # sec_last_input = hidden[n_generated - 2]\n",
" sec_last_token_embedding = torch.stack([layer[:, -1, :].cpu() for layer in hidden])\n",
" print(sec_last_token_embedding.shape)\n",
" last_hidden_state = hidden[-1][:, -1, :].cpu().numpy()\n",
" print(last_hidden_state.shape) \n",
" # TODO potentially need to only compute uncertainty for the last token in sentence?\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# concat hidden states\n",
"\n",
"sec_last_token_embedding = np.concatenate(sec_last_token_embedding.cpu().numpy()[layer_range], axis=1)\n",
"# predict with probe\n",
"pred = probe.predict(hidden_states)\n",
"print(pred)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "llm-test",
"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.11.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|