s-a-malik commited on
Commit
b874271
1 Parent(s): f4748d0
app_sep.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle as pkl
3
+ from pathlib import Path
4
+ from threading import Thread
5
+ from typing import List, Optional, Tuple, Iterator
6
+
7
+ import gradio as gr
8
+ import numpy as np
9
+ import torch
10
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
11
+
12
+
13
+ MAX_MAX_NEW_TOKENS = 2048
14
+ DEFAULT_MAX_NEW_TOKENS = 1024
15
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
16
+
17
+ DESCRIPTION = """\
18
+ # Llama-2 7B Chat with Streamable Semantic Uncertainty Probe
19
+ This Space demonstrates the Llama-2-7b-chat model with an added semantic uncertainty probe.
20
+ The highlighted text shows the model's uncertainty in real-time, with more intense yellow indicating higher uncertainty.
21
+ """
22
+
23
+ if torch.cuda.is_available():
24
+ model_id = "meta-llama/Llama-2-7b-chat-hf"
25
+ # TODO load the full model?
26
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", load_in_8bit=True)
27
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
28
+ tokenizer.use_default_system_prompt = False
29
+
30
+ # load the probe data
31
+ # TODO load accuracy and SE probe and compare in different tabs
32
+ with open("./model/20240625-131035_demo.pkl", "rb") as f:
33
+ probe_data = pkl.load(f)
34
+ # take the NQ open one
35
+ probe_data = probe_data[-2]
36
+ model = probe_data['t_bmodel']
37
+ layer_range = probe_data['sep_layer_range']
38
+ acc_model = probe_data['t_amodel']
39
+ acc_layer_range = probe_data['ap_layer_range']
40
+
41
+ def generate(
42
+ message: str,
43
+ chat_history: List[Tuple[str, str]],
44
+ system_prompt: str,
45
+ max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS,
46
+ temperature: float = 0.6,
47
+ top_p: float = 0.9,
48
+ top_k: int = 50,
49
+ repetition_penalty: float = 1.2,
50
+ ) -> Iterator[str]:
51
+ conversation = []
52
+ if system_prompt:
53
+ conversation.append({"role": "system", "content": system_prompt})
54
+ for user, assistant in chat_history:
55
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
56
+ conversation.append({"role": "user", "content": message})
57
+
58
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
59
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
60
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
61
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
62
+ input_ids = input_ids.to(model.device)
63
+
64
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
65
+ generation_kwargs = dict(
66
+ input_ids=input_ids,
67
+ max_new_tokens=max_new_tokens,
68
+ do_sample=True,
69
+ top_p=top_p,
70
+ top_k=top_k,
71
+ temperature=temperature,
72
+ repetition_penalty=repetition_penalty,
73
+ streamer=streamer,
74
+ output_hidden_states=True,
75
+ return_dict_in_generate=True,
76
+ )
77
+
78
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
79
+ thread.start()
80
+
81
+ generated_text = ""
82
+ highlighted_text = ""
83
+ for output in streamer:
84
+ print(output)
85
+ generated_text += output
86
+
87
+ yield generated_text
88
+
89
+ # this is doing it twice... just do autoregressive generation instead
90
+ for new_text in streamer:
91
+ generated_text += new_text
92
+ current_input_ids = tokenizer.encode(generated_text, return_tensors="pt").to(model.device)
93
+
94
+ with torch.no_grad():
95
+ outputs = model(current_input_ids, output_hidden_states=True)
96
+ hidden = outputs.hidden_states
97
+ # Stack second last token embeddings from all layers
98
+ # if len(hidden) == 1: # FIX: runtime error for mistral-7b on bioasq
99
+ # sec_last_input = hidden[0]
100
+ # elif ((n_generated - 2) >= len(hidden)):
101
+ # sec_last_input = hidden[-2]
102
+ # else:
103
+ # sec_last_input = hidden[n_generated - 2]
104
+ last_hidden_state = torch.stack([layer[:, -1, :].cpu() for layer in hidden[-1]]).cpu().numpy()
105
+ # print(sec_last_token_embedding.shape)
106
+ # last_hidden_state = outputs.hidden_states[-1][:, -1, :].cpu().numpy()
107
+ print(last_hidden_state.shape)
108
+ # TODO potentially need to only compute uncertainty for the last token in sentence?
109
+
110
+ # concatenate the hidden states from the specified layers
111
+ probe_input = np.concatenate(last_hidden_state[layer_range], axis=1)
112
+ print(probe_input.shape)
113
+ uncertainty_score = model.predict(probe_input)
114
+ print(uncertainty_score)
115
+ new_highlighted_text = highlight_text(new_text, uncertainty_score[0])
116
+ print(new_highlighted_text)
117
+ highlighted_text += new_highlighted_text
118
+
119
+ yield highlighted_text
120
+
121
+
122
+ def highlight_text(text: str, uncertainty_score: float) -> str:
123
+ if uncertainty_score > 0:
124
+ html_color = "#%02X%02X%02X" % (
125
+ 255,
126
+ int(255 * (1 - uncertainty_score)),
127
+ int(255 * (1 - uncertainty_score)),
128
+ )
129
+ else:
130
+ html_color = "#%02X%02X%02X" % (
131
+ int(255 * (1 + uncertainty_score)),
132
+ 255,
133
+ int(255 * (1 + uncertainty_score)),
134
+ )
135
+ return '<span style="background-color: {}; color: black">{}</span>'.format(
136
+ html_color, text
137
+ )
138
+ chat_interface = gr.ChatInterface(
139
+ fn=generate,
140
+ additional_inputs=[
141
+ gr.Textbox(label="System prompt", lines=6),
142
+ gr.Slider(
143
+ label="Max new tokens",
144
+ minimum=1,
145
+ maximum=MAX_MAX_NEW_TOKENS,
146
+ step=1,
147
+ value=DEFAULT_MAX_NEW_TOKENS,
148
+ ),
149
+ gr.Slider(
150
+ label="Temperature",
151
+ minimum=0.1,
152
+ maximum=4.0,
153
+ step=0.1,
154
+ value=0.6,
155
+ ),
156
+ gr.Slider(
157
+ label="Top-p (nucleus sampling)",
158
+ minimum=0.05,
159
+ maximum=1.0,
160
+ step=0.05,
161
+ value=0.9,
162
+ ),
163
+ gr.Slider(
164
+ label="Top-k",
165
+ minimum=1,
166
+ maximum=1000,
167
+ step=1,
168
+ value=50,
169
+ ),
170
+ gr.Slider(
171
+ label="Repetition penalty",
172
+ minimum=1.0,
173
+ maximum=2.0,
174
+ step=0.05,
175
+ value=1.2,
176
+ ),
177
+ ],
178
+ stop_btn=None,
179
+ examples=[
180
+ ["What is the capital of France?"],
181
+ ["Explain the theory of relativity in simple terms."],
182
+ ["Write a short poem about artificial intelligence."]
183
+ ],
184
+ title="Llama-2 7B Chat with Streamable Semantic Uncertainty Probe",
185
+ description=DESCRIPTION,
186
+ )
187
+
188
+ if __name__ == "__main__":
189
+ chat_interface.launch()
debug.ipynb ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "name": "stdout",
10
+ "output_type": "stream",
11
+ "text": [
12
+ "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",
13
+ "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"
14
+ ]
15
+ },
16
+ {
17
+ "name": "stderr",
18
+ "output_type": "stream",
19
+ "text": [
20
+ "/Users/shreshth/anaconda3/envs/llm-test/lib/python3.11/site-packages/threadpoolctl.py:1214: RuntimeWarning: \n",
21
+ "Found Intel OpenMP ('libiomp') and LLVM OpenMP ('libomp') loaded at\n",
22
+ "the same time. Both libraries are known to be incompatible and this\n",
23
+ "can cause random crashes or deadlocks on Linux when loaded in the\n",
24
+ "same Python program.\n",
25
+ "Using threadpoolctl may cause crashes or deadlocks. For more\n",
26
+ "information and possible workarounds, please see\n",
27
+ " https://github.com/joblib/threadpoolctl/blob/master/multiple_openmp.md\n",
28
+ "\n",
29
+ " warnings.warn(msg, RuntimeWarning)\n"
30
+ ]
31
+ },
32
+ {
33
+ "data": {
34
+ "text/plain": [
35
+ "{'name': 'nq',\n",
36
+ " 't_bmodel': LogisticRegression(),\n",
37
+ " 't_amodel': LogisticRegression(),\n",
38
+ " 'sep_layer_range': (27, 32),\n",
39
+ " 'ap_layer_range': (17, 22)}"
40
+ ]
41
+ },
42
+ "execution_count": 1,
43
+ "metadata": {},
44
+ "output_type": "execute_result"
45
+ }
46
+ ],
47
+ "source": [
48
+ "# test probe loading \n",
49
+ "import pickle as pkl\n",
50
+ "import numpy as np\n",
51
+ "import sklearn \n",
52
+ "from sklearn import linear_model\n",
53
+ "import os\n",
54
+ "os.environ[\"PYTORCH_ENABLE_MPS_FALLBACK\"] = \"1\"\n",
55
+ "\n",
56
+ "# load the probe data\n",
57
+ "with open(\"./model/20240625-131035_demo.pkl\", \"rb\") as f:\n",
58
+ " probe_data = pkl.load(f)\n",
59
+ "# take the NQ open one\n",
60
+ "probe_data = probe_data[-2]\n",
61
+ "probe_data"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "execution_count": 2,
67
+ "metadata": {},
68
+ "outputs": [],
69
+ "source": [
70
+ "probe = probe_data['t_bmodel']\n",
71
+ "layer_range = probe_data['sep_layer_range']"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "execution_count": 5,
77
+ "metadata": {},
78
+ "outputs": [
79
+ {
80
+ "data": {
81
+ "application/vnd.jupyter.widget-view+json": {
82
+ "model_id": "1c0e30b73cab48069e985203c598a9b0",
83
+ "version_major": 2,
84
+ "version_minor": 0
85
+ },
86
+ "text/plain": [
87
+ "Loading checkpoint shards: 0%| | 0/2 [00:00<?, ?it/s]"
88
+ ]
89
+ },
90
+ "metadata": {},
91
+ "output_type": "display_data"
92
+ }
93
+ ],
94
+ "source": [
95
+ "import torch\n",
96
+ "from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer\n",
97
+ "\n",
98
+ "model_id = \"meta-llama/Llama-2-7b-chat-hf\"\n",
99
+ "model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cpu\")\n",
100
+ "tokenizer = AutoTokenizer.from_pretrained(model_id)\n",
101
+ "tokenizer.use_default_system_prompt = False"
102
+ ]
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "execution_count": 8,
107
+ "metadata": {},
108
+ "outputs": [
109
+ {
110
+ "name": "stdout",
111
+ "output_type": "stream",
112
+ "text": [
113
+ "tensor([[ 1, 518, 25580, 29962, 3532, 14816, 29903, 6778, 13, 3492,\n",
114
+ " 526, 263, 8444, 20255, 29889, 13, 29966, 829, 14816, 29903,\n",
115
+ " 6778, 13, 13, 5816, 338, 278, 7483, 310, 3444, 29973,\n",
116
+ " 518, 29914, 25580, 29962]]) torch.Size([1, 34])\n"
117
+ ]
118
+ },
119
+ {
120
+ "name": "stderr",
121
+ "output_type": "stream",
122
+ "text": [
123
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)\n"
124
+ ]
125
+ }
126
+ ],
127
+ "source": [
128
+ "from threading import Thread\n",
129
+ "\n",
130
+ "system_prompt = \"You are a helpful assistant.\"\n",
131
+ "message = \"what is the capital of France?\"\n",
132
+ "max_new_tokens = 100\n",
133
+ "top_p = 0.9\n",
134
+ "top_k = 50\n",
135
+ "temperature = 0.7\n",
136
+ "repetition_penalty = 1.2\n",
137
+ "\n",
138
+ "conversation = []\n",
139
+ "\n",
140
+ "conversation.append({\"role\": \"system\", \"content\": system_prompt})\n",
141
+ "conversation.append({\"role\": \"user\", \"content\": message})\n",
142
+ "input_ids = tokenizer.apply_chat_template(conversation, return_tensors=\"pt\")\n",
143
+ "input_ids = input_ids.to(model.device)\n",
144
+ "print(input_ids, input_ids.shape)\n",
145
+ "streamer = TextIteratorStreamer(tokenizer, timeout=1000.0, skip_prompt=True, skip_special_tokens=True)\n",
146
+ "generation_kwargs = dict(\n",
147
+ " input_ids=input_ids,\n",
148
+ " max_new_tokens=max_new_tokens,\n",
149
+ " do_sample=True,\n",
150
+ " top_p=top_p,\n",
151
+ " top_k=top_k,\n",
152
+ " temperature=temperature,\n",
153
+ " repetition_penalty=repetition_penalty,\n",
154
+ " streamer=streamer,\n",
155
+ " output_hidden_states=True,\n",
156
+ " return_dict_in_generate=True,\n",
157
+ ")\n",
158
+ "\n",
159
+ "thread = Thread(target=model.generate, kwargs=generation_kwargs)\n",
160
+ "thread.start()\n",
161
+ "\n",
162
+ "generated_text = \"\"\n",
163
+ "highlighted_text = \"\"\n",
164
+ "\n",
165
+ "for new_text in streamer:\n",
166
+ " print(new_text)\n",
167
+ " generated_text += new_text\n",
168
+ " current_input_ids = tokenizer.encode(generated_text, return_tensors=\"pt\").to(model.device)\n",
169
+ " print(current_input_ids, current_input_ids.shape)\n",
170
+ " with torch.no_grad():\n",
171
+ " outputs = model(current_input_ids, output_hidden_states=True)\n",
172
+ " print(outputs)\n",
173
+ " hidden = outputs.hidden_states \n",
174
+ " print(hidden.shape)\n",
175
+ " # Stack second last token embeddings from all layers \n",
176
+ " # if len(hidden) == 1: # FIX: runtime error for mistral-7b on bioasq\n",
177
+ " # sec_last_input = hidden[0]\n",
178
+ " # elif ((n_generated - 2) >= len(hidden)):\n",
179
+ " # sec_last_input = hidden[-2]\n",
180
+ " # else:\n",
181
+ " # sec_last_input = hidden[n_generated - 2]\n",
182
+ " # sec_last_token_embedding = torch.stack([layer[:, -1, :].cpu() for layer in sec_last_input])\n",
183
+ " # print(sec_last_token_embedding.shape)\n",
184
+ " last_hidden_state = outputs.hidden_states[-1][:, -1, :].cpu().numpy()\n",
185
+ " print(last_hidden_state.shape) \n",
186
+ " # TODO potentially need to only compute uncertainty for the last token in sentence?\n"
187
+ ]
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "execution_count": null,
192
+ "metadata": {},
193
+ "outputs": [],
194
+ "source": [
195
+ "# concat hidden states\n",
196
+ "\n",
197
+ "\n",
198
+ "hidden_states = np.concatenate(np.array(hidden_states)[layer_range], axis=1)\n",
199
+ "# predict with probe\n",
200
+ "pred = probe.predict(hidden_states)\n",
201
+ "print(pred)"
202
+ ]
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "execution_count": null,
207
+ "metadata": {},
208
+ "outputs": [],
209
+ "source": []
210
+ }
211
+ ],
212
+ "metadata": {
213
+ "kernelspec": {
214
+ "display_name": "llm-test",
215
+ "language": "python",
216
+ "name": "python3"
217
+ },
218
+ "language_info": {
219
+ "codemirror_mode": {
220
+ "name": "ipython",
221
+ "version": 3
222
+ },
223
+ "file_extension": ".py",
224
+ "mimetype": "text/x-python",
225
+ "name": "python",
226
+ "nbconvert_exporter": "python",
227
+ "pygments_lexer": "ipython3",
228
+ "version": "3.11.4"
229
+ }
230
+ },
231
+ "nbformat": 4,
232
+ "nbformat_minor": 2
233
+ }
model/{spiece.model → 20240625-131035_demo.pkl} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:b5cbdfa8aa7c54c8c5af85b78c309c54a5f2749a20468bf6f60eee007fe6fec1
3
- size 805634
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c48fbd05e51c7b72d97012266d3f483198ec99ce66ed9611eefc347ab2e21360
3
+ size 1313378
model/config.json DELETED
@@ -1,40 +0,0 @@
1
- {
2
- "_name_or_path": "rinna/japanese-gpt2-medium",
3
- "activation_function": "gelu_new",
4
- "architectures": [
5
- "GPT2LMHeadModel"
6
- ],
7
- "attn_pdrop": 0.1,
8
- "bos_token_id": 1,
9
- "embd_pdrop": 0.1,
10
- "eos_token_id": 2,
11
- "gradient_checkpointing": false,
12
- "initializer_range": 0.02,
13
- "layer_norm_epsilon": 1e-05,
14
- "model_type": "gpt2",
15
- "n_ctx": 1024,
16
- "n_embd": 1024,
17
- "n_head": 16,
18
- "n_inner": 4096,
19
- "n_layer": 24,
20
- "n_positions": 1024,
21
- "reorder_and_upcast_attn": false,
22
- "resid_pdrop": 0.1,
23
- "scale_attn_by_inverse_layer_idx": false,
24
- "scale_attn_weights": true,
25
- "summary_activation": null,
26
- "summary_first_dropout": 0.1,
27
- "summary_proj_to_labels": true,
28
- "summary_type": "cls_index",
29
- "summary_use_proj": true,
30
- "task_specific_params": {
31
- "text-generation": {
32
- "do_sample": true,
33
- "max_length": 50
34
- }
35
- },
36
- "torch_dtype": "float32",
37
- "transformers_version": "4.25.1",
38
- "use_cache": true,
39
- "vocab_size": 32000
40
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
model/pytorch_model.bin DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:21035c9390e20b77578237469586e51d2275cf889d1c3418c4b57da8c67160c6
3
- size 1369783965
 
 
 
 
model/special_tokens_map.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "bos_token": "<s>",
3
- "cls_token": "[CLS]",
4
- "eos_token": "</s>",
5
- "mask_token": "[MASK]",
6
- "pad_token": "[PAD]",
7
- "sep_token": "[SEP]",
8
- "unk_token": "<unk>"
9
- }
 
 
 
 
 
 
 
 
 
 
model/tokenizer_config.json DELETED
@@ -1,17 +0,0 @@
1
- {
2
- "additional_special_tokens": [],
3
- "bos_token": "<s>",
4
- "cls_token": "[CLS]",
5
- "do_lower_case": true,
6
- "eos_token": "</s>",
7
- "extra_ids": 0,
8
- "mask_token": "[MASK]",
9
- "model_max_length": 1000000000000000019884624838656,
10
- "name_or_path": "rinna/japanese-gpt2-medium",
11
- "pad_token": "[PAD]",
12
- "sep_token": "[SEP]",
13
- "sp_model_kwargs": {},
14
- "special_tokens_map_file": "/Users/agiats/.cache/huggingface/hub/models--rinna--japanese-gpt2-medium/snapshots/f464b76739c884d8b0479a0a7705b7fa71c3fd5a/special_tokens_map.json",
15
- "tokenizer_class": "T5Tokenizer",
16
- "unk_token": "<unk>"
17
- }