wikipedia_demo.ipynb 8.16 KB
Newer Older
chenzk's avatar
v1.0  
chenzk committed
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this notebook, we showcase how to use the KVpress pipelines by answering questions about NVIDIA Wikipedia article."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "\n",
    "from transformers import pipeline\n",
    "\n",
    "from kvpress import ExpectedAttentionPress, KnormPress, RandomPress"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load the pipeline and data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "54a814620e6844aba021ea3376c6f823",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading checkpoint shards:   0%|          | 0/5 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Device set to use cuda:0\n"
     ]
    }
   ],
   "source": [
    "# Load pipeline\n",
    "\n",
    "device = \"cuda:0\"\n",
    "ckpt = \"Qwen/Qwen3-8B\"\n",
    "attn_implementation = \"flash_attention_2\"  # use \"eager\" for ObservedAttentionPress and \"sdpa\" if you can't use \"flash_attention_2\"\n",
    "pipe = pipeline(\"kv-press-text-generation\", model=ckpt, device=device, dtype=\"auto\", model_kwargs={\"attn_implementation\":attn_implementation})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of tokens: 11686\n"
     ]
    }
   ],
   "source": [
    "# Load data\n",
    "url = \"https://en.wikipedia.org/wiki/Nvidia\"\n",
    "headers = {\"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) \"}\n",
    "content = requests.get(url, headers=headers).content\n",
    "soup = BeautifulSoup(content, \"html.parser\")\n",
    "context = \"\".join([p.text for p in soup.find_all(\"p\")]) + \"\\n\\n\"\n",
    "tokens = pipe.tokenizer.encode(context, return_tensors=\"pt\").to(device)\n",
    "print(f\"Number of tokens: {tokens.size(1)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Use the pipeline with a press"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Pick a press with a compression ratio, you can run the following cells with different presses\n",
    "compression_ratio = 0.5\n",
    "press = ExpectedAttentionPress(compression_ratio)\n",
    "# press = KnormPress(compression_ratio)\n",
    "# press = RandomPress(compression_ratio)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Question:   Complete this sentence: The Nvidia GeForce Partner Program was a ...\n",
      "Answer:     marketing program designed to provide partnering companies with benefits such as public relations support, video game bundling, and marketing development funds.\n",
      "Prediction: The Nvidia GeForce Partner Program was a marketing initiative designed to provide partnering companies with benefits such as public relations support, video game bundling, and marketing development funds, but it became controversial due to allegations of anti-competitive practices.\n"
     ]
    }
   ],
   "source": [
    "# Run the pipeline on a single question\n",
    "\n",
    "question = \"Complete this sentence: The Nvidia GeForce Partner Program was a ...\"\n",
    "true_answer = \"marketing program designed to provide partnering companies with benefits such as public relations support, video game bundling, and marketing development funds.\"\n",
    "pred_answer = pipe(context, question=question, press=press)[\"answer\"]\n",
    "\n",
    "print(f\"Question:   {question}\")\n",
    "print(f\"Answer:     {true_answer}\")\n",
    "print(f\"Prediction: {pred_answer}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Question:   What happened on March 1, 2024?\n",
      "Answer:     Nvidia became the third company in the history of the United States to close with a market capitalization in excess of $2 trillion\n",
      "Prediction: On **March 1, 2024**, **Nvidia** was ranked **#3** on **Forbes' \"Best Places to Work\" list**. This recognition highlighted the company's strong workplace culture, employee satisfaction, and\n",
      "\n",
      "Question:   What was the unofficial company motto of Nvidia during the early days?\n",
      "Answer:     Our company is thirty days from going out of business\n",
      "Prediction: The unofficial company motto of Nvidia during the early days was **\"A flywheel to reach large markets funding huge R&D to solve massive computational problems.\"** This motto was inspired by the concept of a flywheel, which is a device that stores rotational\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Run the pipeline on multiple questions, the context will be compressed only once\n",
    "\n",
    "questions = [\n",
    "    \"What happened on March 1, 2024?\",\n",
    "    \"What was the unofficial company motto of Nvidia during the early days?\",\n",
    "]\n",
    "\n",
    "true_answers = [\n",
    "    \"Nvidia became the third company in the history of the United States to close with a market capitalization in excess of $2 trillion\",\n",
    "    \"Our company is thirty days from going out of business\",\n",
    "]\n",
    "\n",
    "pred_answers = pipe(context, questions=questions, press=press)[\"answers\"]\n",
    "for question, pred_answer, true_answer in zip(questions, pred_answers, true_answers):\n",
    "    print(f\"Question:   {question}\")\n",
    "    print(f\"Answer:     {true_answer}\")\n",
    "    print(f\"Prediction: {pred_answer}\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Question:              What is GTC ?\n",
      "Answer:                Nvidia's GPU Technology Conference (GTC) is a series of technical conferences held around the world.\n",
      "Prediction w/o prefix: **GTC** stands for **GPU Technology Conference**, which is a major annual event organized by **NVIDIA**. It is a technical conference that\n",
      "Prediction w/ prefix : Come on you don't know GTC ? Everyone knows GTC is the biggest AI conference in the world. It's held by NVIDIA, right? I mean, it's like the Super Bowl of\n"
     ]
    }
   ],
   "source": [
    "# Use an answer prefix and limit the number of tokens in the answer\n",
    "\n",
    "question = \"What is GTC ?\"\n",
    "true_answer = \"Nvidia's GPU Technology Conference (GTC) is a series of technical conferences held around the world.\"\n",
    "answer_prefix = \"Come on you don't know GTC ? Everyone\"\n",
    "max_new_tokens = 30\n",
    "\n",
    "pred_answer_with_prefix = pipe(context, question=question, answer_prefix=answer_prefix, press=press, max_new_tokens=max_new_tokens)[\"answer\"]\n",
    "pred_answer_without_prefix = pipe(context, question=question, press=press, max_new_tokens=max_new_tokens)[\"answer\"]\n",
    "\n",
    "print(f\"Question:              {question}\")\n",
    "print(f\"Answer:                {true_answer}\")\n",
    "print(f\"Prediction w/o prefix: {pred_answer_without_prefix}\")\n",
    "print(f\"Prediction w/ prefix : {answer_prefix + pred_answer_with_prefix}\")"
   ]
  }
 ],
 "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.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}