Spaces:
Sleeping
Sleeping
ACMCMC
commited on
Commit
·
3b410d3
1
Parent(s):
c2dd9fb
v1
Browse files- README.md +2 -0
- main.ipynb +292 -0
- requirements.txt +4 -0
README.md
CHANGED
@@ -1,2 +1,4 @@
|
|
1 |
# ss-prompts
|
2 |
Simon Says Prompts
|
|
|
|
|
|
1 |
# ss-prompts
|
2 |
Simon Says Prompts
|
3 |
+
|
4 |
+
This repo is a demo of how to generate an embedding that gets fed into a given LLM and is optimized to make the LLM output a specific text under a greedy decoding scheme.
|
main.ipynb
ADDED
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": null,
|
6 |
+
"id": "d1daab37",
|
7 |
+
"metadata": {},
|
8 |
+
"outputs": [],
|
9 |
+
"source": [
|
10 |
+
"import ipywidgets\n",
|
11 |
+
"\n",
|
12 |
+
"text_widget = ipywidgets.Textarea(\n",
|
13 |
+
" value=\"Solomonoff's theory of inductive inference proposes that all problems of logical induction can be interpreted as finding a model that predicts what comes next given some sequence, and that the theoretically most likely model for what comes next should be the smallest possible computer program that outputs the sequence so far.\",\n",
|
14 |
+
" placeholder=\"Type something\",\n",
|
15 |
+
" description=\"Text to process:\",\n",
|
16 |
+
" disabled=False,\n",
|
17 |
+
")\n",
|
18 |
+
"display(text_widget)"
|
19 |
+
]
|
20 |
+
},
|
21 |
+
{
|
22 |
+
"cell_type": "code",
|
23 |
+
"execution_count": null,
|
24 |
+
"id": "09b3c097",
|
25 |
+
"metadata": {},
|
26 |
+
"outputs": [],
|
27 |
+
"source": [
|
28 |
+
"import transformers\n",
|
29 |
+
"import torch\n",
|
30 |
+
"import tqdm\n",
|
31 |
+
"\n",
|
32 |
+
"print(f\"Optimizing: {text_widget.value}\")\n",
|
33 |
+
"\n",
|
34 |
+
"tokenizer: transformers.PreTrainedTokenizer = (\n",
|
35 |
+
" transformers.AutoTokenizer.from_pretrained(\"openai-community/gpt2\")\n",
|
36 |
+
")\n",
|
37 |
+
"model: transformers.PreTrainedModel = transformers.AutoModelForCausalLM.from_pretrained(\n",
|
38 |
+
" \"openai-community/gpt2\"\n",
|
39 |
+
")\n",
|
40 |
+
"\n",
|
41 |
+
"# Tokenize the text\n",
|
42 |
+
"tokens = tokenizer(\n",
|
43 |
+
" text_widget.value,\n",
|
44 |
+
" return_tensors=\"pt\",\n",
|
45 |
+
" padding=False,\n",
|
46 |
+
" truncation=True,\n",
|
47 |
+
" add_special_tokens=True,\n",
|
48 |
+
")\n",
|
49 |
+
"\n",
|
50 |
+
"embeddings = model.transformer.wte(tokens[\"input_ids\"]).detach()\n",
|
51 |
+
"\n",
|
52 |
+
"# We'll use a soft prompt - a special token and its hidden states for the first token that we'll use to condition the model. We'll optimize the hidden states of this token to maximize the likelihood of the text that follows it.\n",
|
53 |
+
"# Generate a soft prompt by creating random hidden states for the first token\n",
|
54 |
+
"# We'll optimize these hidden states to maximize the likelihood of the text that follows it\n",
|
55 |
+
"# past_key_values (Tuple[Tuple[torch.Tensor]] of length config.n_layers) — Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see past_key_values output below). Can be used to speed up sequential decoding. The input_ids which have their past given to this model should not be passed as input_ids as they have already been computed.\n",
|
56 |
+
"# Shape: past_key_values (Tuple[Tuple[torch.Tensor]] of length config.n_layers)\n",
|
57 |
+
"# with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head))\n",
|
58 |
+
"# The precision of the hidden states should be fp16\n",
|
59 |
+
"ss_prompt = (\n",
|
60 |
+
" # One tensor of shape (1, 1, embed_size_per_head)\n",
|
61 |
+
" torch.randn(\n",
|
62 |
+
" 1,\n",
|
63 |
+
" 4,\n",
|
64 |
+
" model.config.n_embd,\n",
|
65 |
+
" requires_grad=True,\n",
|
66 |
+
" # dtype=torch.float16,\n",
|
67 |
+
" )\n",
|
68 |
+
" # for _ in range(model.config.n_layer)\n",
|
69 |
+
")\n",
|
70 |
+
"\n",
|
71 |
+
"# Copy the soft prompts since we'll optimize them and they'll change\n",
|
72 |
+
"original_ss_prompt = tuple(key.detach().clone() for key in ss_prompt)\n",
|
73 |
+
"\n",
|
74 |
+
"# Define the optimizer\n",
|
75 |
+
"optimizer = torch.optim.Adam([ss_prompt], lr=1e-2)\n",
|
76 |
+
"\n",
|
77 |
+
"# Define the loss function\n",
|
78 |
+
"loss_fn = torch.nn.CrossEntropyLoss()\n",
|
79 |
+
"\n",
|
80 |
+
"# Define the number of optimization steps\n",
|
81 |
+
"n_steps = 5000\n",
|
82 |
+
"patience = 50\n",
|
83 |
+
"patience_counter = 0\n",
|
84 |
+
"epsilon = 1e-1\n",
|
85 |
+
"\n",
|
86 |
+
"# Freeze the model parameters\n",
|
87 |
+
"model.eval()\n",
|
88 |
+
"\n",
|
89 |
+
"# Check that the soft prompt is optimizable (requires_grad=True)\n",
|
90 |
+
"for key in ss_prompt:\n",
|
91 |
+
" assert key.requires_grad\n",
|
92 |
+
"\n",
|
93 |
+
"# Disable gradient computation for the model\n",
|
94 |
+
"for param in model.parameters():\n",
|
95 |
+
" param.requires_grad = False\n",
|
96 |
+
"\n",
|
97 |
+
"best_loss = float(\"inf\")\n",
|
98 |
+
"best_ss_prompt = None\n",
|
99 |
+
"\n",
|
100 |
+
"# Optimize the soft prompt\n",
|
101 |
+
"for step in tqdm.tqdm(range(n_steps)):\n",
|
102 |
+
" # Zero the gradients\n",
|
103 |
+
" optimizer.zero_grad()\n",
|
104 |
+
"\n",
|
105 |
+
" # Add the optimizable SS prompt to the embeddings\n",
|
106 |
+
" expanded_prompt = torch.cat([ss_prompt, embeddings], dim=1)\n",
|
107 |
+
"\n",
|
108 |
+
" # Generate the logits for the text\n",
|
109 |
+
" logits: torch.Tensor = model(inputs_embeds=expanded_prompt).logits\n",
|
110 |
+
"\n",
|
111 |
+
" probs = torch.softmax(logits[:, ss_prompt.size(-2) - 1 :-1], dim=-1)\n",
|
112 |
+
"\n",
|
113 |
+
" # Compute the ranks of the input IDs, i.e. how many tokens would have been more likely than the correct one (the label, the input IDs)\n",
|
114 |
+
" \n",
|
115 |
+
" count_higher_logits = (logits[:, ss_prompt.size(-2) - 1 :-1] > logits[:, -1:]).float()\n",
|
116 |
+
" ranks = count_higher_logits.sum(dim=-1)\n",
|
117 |
+
"\n",
|
118 |
+
" # Compute the loss\n",
|
119 |
+
" loss = loss_fn(\n",
|
120 |
+
" logits[:, ss_prompt.size(-2) - 1 :-1].reshape(-1, logits.size(-1)),\n",
|
121 |
+
" tokens[\"input_ids\"].reshape(-1),\n",
|
122 |
+
" )\n",
|
123 |
+
"\n",
|
124 |
+
" # Backpropagate the gradients\n",
|
125 |
+
" loss.backward()\n",
|
126 |
+
"\n",
|
127 |
+
" # Optimize the soft prompt\n",
|
128 |
+
" optimizer.step()\n",
|
129 |
+
"\n",
|
130 |
+
" if step % 10 == 0:\n",
|
131 |
+
" # Get the L2 norm of the difference between the original and optimized soft prompts\n",
|
132 |
+
" l2_norm = sum(\n",
|
133 |
+
" torch.norm(optimized - original, p=2)\n",
|
134 |
+
" for optimized, original in zip(ss_prompt, original_ss_prompt)\n",
|
135 |
+
" )\n",
|
136 |
+
" print(\n",
|
137 |
+
" f\"Step {step}, Loss: {loss.item()}, L2 norm: {l2_norm.item()}, avg rank: {ranks.mean().item()}\"\n",
|
138 |
+
" )\n",
|
139 |
+
"\n",
|
140 |
+
" # Early stopping with patience\n",
|
141 |
+
" if loss.item() < best_loss and loss.item() > epsilon:\n",
|
142 |
+
" best_loss = loss.item()\n",
|
143 |
+
" best_ss_prompt = ss_prompt.detach().clone()\n",
|
144 |
+
" patience_counter = 0\n",
|
145 |
+
" else:\n",
|
146 |
+
" patience_counter += 1\n",
|
147 |
+
"\n",
|
148 |
+
" if patience_counter >= patience:\n",
|
149 |
+
" print(f\"Early stopping at step {step} with best loss {best_loss}\")\n",
|
150 |
+
" break"
|
151 |
+
]
|
152 |
+
},
|
153 |
+
{
|
154 |
+
"cell_type": "code",
|
155 |
+
"execution_count": null,
|
156 |
+
"id": "cc9a6a2f",
|
157 |
+
"metadata": {},
|
158 |
+
"outputs": [],
|
159 |
+
"source": [
|
160 |
+
"# Save the best soft prompt\n",
|
161 |
+
"torch.save(best_ss_prompt, \"best_ss_prompt.pt\")"
|
162 |
+
]
|
163 |
+
},
|
164 |
+
{
|
165 |
+
"cell_type": "code",
|
166 |
+
"execution_count": null,
|
167 |
+
"id": "3186747d",
|
168 |
+
"metadata": {},
|
169 |
+
"outputs": [],
|
170 |
+
"source": [
|
171 |
+
"import os\n",
|
172 |
+
"import transformers\n",
|
173 |
+
"import torch\n",
|
174 |
+
"import tqdm\n",
|
175 |
+
"\n",
|
176 |
+
"# tokenizer: transformers.PreTrainedTokenizer = (\n",
|
177 |
+
"# transformers.AutoTokenizer.from_pretrained(\"openai-community/gpt2\")\n",
|
178 |
+
"# )\n",
|
179 |
+
"# model: transformers.PreTrainedModel = transformers.AutoModelForCausalLM.from_pretrained(\n",
|
180 |
+
"# \"openai-community/gpt2\"\n",
|
181 |
+
"# )\n",
|
182 |
+
"\n",
|
183 |
+
"# Load the best soft prompt from file\n",
|
184 |
+
"best_ss_prompt = torch.load(\"best_ss_prompt.pt\")\n",
|
185 |
+
"\n",
|
186 |
+
"# Do a greedy decoding manually\n",
|
187 |
+
"# Pass the optimized soft prompt to the model\n",
|
188 |
+
"# We can't use .generate() since we need to pass the inputs_embeds\n",
|
189 |
+
"all_logits = []\n",
|
190 |
+
"generated_tokens = []\n",
|
191 |
+
"with torch.no_grad():\n",
|
192 |
+
" for i in tqdm.tqdm(range(150)):\n",
|
193 |
+
" # Generate the logits for the next token using what we've generated so far\n",
|
194 |
+
" # If there are no generated tokens yet, just take the soft prompt\n",
|
195 |
+
" if len(generated_tokens) == 0:\n",
|
196 |
+
" expanded_prompt = best_ss_prompt\n",
|
197 |
+
" else:\n",
|
198 |
+
" expanded_prompt = torch.cat(\n",
|
199 |
+
" [\n",
|
200 |
+
" ss_prompt,\n",
|
201 |
+
" model.transformer.wte(\n",
|
202 |
+
" torch.tensor(generated_tokens).unsqueeze(0)\n",
|
203 |
+
" ).detach(),\n",
|
204 |
+
" ],\n",
|
205 |
+
" dim=1,\n",
|
206 |
+
" )\n",
|
207 |
+
"\n",
|
208 |
+
" assert expanded_prompt.shape == (\n",
|
209 |
+
" 1,\n",
|
210 |
+
" best_ss_prompt.size(-2) + len(generated_tokens),\n",
|
211 |
+
" model.config.n_embd,\n",
|
212 |
+
" ), f\"Got size {expanded_prompt.shape} instead of (1, {best_ss_prompt.size(-2) + len(generated_tokens)}, {model.config.n_embd})\"\n",
|
213 |
+
"\n",
|
214 |
+
" # Generate the logits for the text\n",
|
215 |
+
" logits: torch.Tensor = model(inputs_embeds=expanded_prompt).logits\n",
|
216 |
+
"\n",
|
217 |
+
" # Get the logits for the next token\n",
|
218 |
+
" next_token_logits = logits[0, -1, :]\n",
|
219 |
+
"\n",
|
220 |
+
" # Get the token with the highest probability\n",
|
221 |
+
" next_token = next_token_logits.argmax().item()\n",
|
222 |
+
"\n",
|
223 |
+
" # Append the token and its logits\n",
|
224 |
+
" generated_tokens.append(next_token)\n",
|
225 |
+
" all_logits.append(next_token_logits)\n",
|
226 |
+
"\n",
|
227 |
+
" if next_token == tokenizer.eos_token_id:\n",
|
228 |
+
" break\n",
|
229 |
+
"\n",
|
230 |
+
"all_logits = torch.stack(all_logits).view(1, -1, model.config.vocab_size)\n",
|
231 |
+
"generated_tokens = torch.tensor(generated_tokens)\n",
|
232 |
+
"\n",
|
233 |
+
"if \"text_widget\" in locals():\n",
|
234 |
+
" reference_text = text_widget.value\n",
|
235 |
+
" reference_tokens = tokenizer.encode(\n",
|
236 |
+
" reference_text, add_special_tokens=False, return_tensors=\"pt\"\n",
|
237 |
+
" )\n",
|
238 |
+
"else:\n",
|
239 |
+
" reference_text = \"\"\n",
|
240 |
+
" reference_tokens = torch.ones_like(generated_tokens)\n",
|
241 |
+
"\n",
|
242 |
+
"# Decode the generated tokens\n",
|
243 |
+
"generated_text = tokenizer.decode(generated_tokens)\n",
|
244 |
+
"print(f\"Reference: {reference_text}\")\n",
|
245 |
+
"print(f\"Generated: {generated_text}\")\n",
|
246 |
+
"\n",
|
247 |
+
"# Print the generated text with the rank of each token\n",
|
248 |
+
"for index, token in enumerate(generated_tokens):\n",
|
249 |
+
" this_tok_logits = all_logits[:, index, :]\n",
|
250 |
+
" # How many tokens have a logit > than this token's logit\n",
|
251 |
+
" count_higher_logits = this_tok_logits[..., :] > this_tok_logits[..., token]\n",
|
252 |
+
" this_tok_probs = torch.softmax(this_tok_logits, dim=-1)\n",
|
253 |
+
" try:\n",
|
254 |
+
" reference_token = reference_tokens[0, index].item()\n",
|
255 |
+
" except IndexError:\n",
|
256 |
+
" reference_token = None\n",
|
257 |
+
" print(\n",
|
258 |
+
" f\"'{tokenizer.decode(token)}':\\tRank {count_higher_logits.sum().item():.2f}, probability: {this_tok_probs[..., token].item() * 100:.2f}%, Reference: '{tokenizer.decode(reference_token) if reference_token is not None else 'N/A'}'\"\n",
|
259 |
+
" )"
|
260 |
+
]
|
261 |
+
},
|
262 |
+
{
|
263 |
+
"cell_type": "code",
|
264 |
+
"execution_count": null,
|
265 |
+
"id": "bc95664e",
|
266 |
+
"metadata": {},
|
267 |
+
"outputs": [],
|
268 |
+
"source": []
|
269 |
+
}
|
270 |
+
],
|
271 |
+
"metadata": {
|
272 |
+
"kernelspec": {
|
273 |
+
"display_name": ".venv",
|
274 |
+
"language": "python",
|
275 |
+
"name": "python3"
|
276 |
+
},
|
277 |
+
"language_info": {
|
278 |
+
"codemirror_mode": {
|
279 |
+
"name": "ipython",
|
280 |
+
"version": 3
|
281 |
+
},
|
282 |
+
"file_extension": ".py",
|
283 |
+
"mimetype": "text/x-python",
|
284 |
+
"name": "python",
|
285 |
+
"nbconvert_exporter": "python",
|
286 |
+
"pygments_lexer": "ipython3",
|
287 |
+
"version": "3.11.11"
|
288 |
+
}
|
289 |
+
},
|
290 |
+
"nbformat": 4,
|
291 |
+
"nbformat_minor": 5
|
292 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
transformers
|
3 |
+
tqdm
|
4 |
+
ipywidgets
|