{ "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Љ ( \" ass \n", " Ъ Џ \n", " հ M O - O C\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 '{}'.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 }