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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"id": "9cfae24c-01e5-480b-ad5e-2aec772e0983",
|
6 |
+
"metadata": {},
|
7 |
+
"source": [
|
8 |
+
"### Checking for availability of GPUs"
|
9 |
+
]
|
10 |
+
},
|
11 |
+
{
|
12 |
+
"cell_type": "code",
|
13 |
+
"execution_count": null,
|
14 |
+
"id": "8229d250-fd3c-4ee6-ba55-dcfbeba9b06e",
|
15 |
+
"metadata": {},
|
16 |
+
"outputs": [],
|
17 |
+
"source": [
|
18 |
+
"!nvidia-smi"
|
19 |
+
]
|
20 |
+
},
|
21 |
+
{
|
22 |
+
"cell_type": "markdown",
|
23 |
+
"id": "8b9081a3-e5bb-45c5-a88b-4ef4e0490574",
|
24 |
+
"metadata": {},
|
25 |
+
"source": [
|
26 |
+
"### Installing the necessary libraries\n",
|
27 |
+
"Please note that this installation step might fail if no GPU is available."
|
28 |
+
]
|
29 |
+
},
|
30 |
+
{
|
31 |
+
"cell_type": "code",
|
32 |
+
"execution_count": null,
|
33 |
+
"id": "a9c4d533-ec98-4b0f-a263-c3c8f649547e",
|
34 |
+
"metadata": {},
|
35 |
+
"outputs": [],
|
36 |
+
"source": [
|
37 |
+
"!pip install --upgrade pip\n",
|
38 |
+
"!pip install -q -U bitsandbytes\n",
|
39 |
+
"!pip install -q -U git+https://github.com/huggingface/transformers.git\n",
|
40 |
+
"!pip install -q -U git+https://github.com/huggingface/peft.git\n",
|
41 |
+
"!pip install -q -U git+https://github.com/huggingface/accelerate.git\n",
|
42 |
+
"!pip install -q trl xformers wandb datasets einops gradio sentencepiece\n",
|
43 |
+
"!pip install flash-attn"
|
44 |
+
]
|
45 |
+
},
|
46 |
+
{
|
47 |
+
"cell_type": "code",
|
48 |
+
"execution_count": null,
|
49 |
+
"id": "3425af9b-12cd-46e5-80f5-30fd2f7fed67",
|
50 |
+
"metadata": {},
|
51 |
+
"outputs": [],
|
52 |
+
"source": [
|
53 |
+
"# Libraries used for analyzing the dataset\n",
|
54 |
+
"!pip install matplotlib\n",
|
55 |
+
"!pip install statistics"
|
56 |
+
]
|
57 |
+
},
|
58 |
+
{
|
59 |
+
"cell_type": "markdown",
|
60 |
+
"id": "b0ddd32e-2c21-4abd-8e5c-db85efb194ab",
|
61 |
+
"metadata": {},
|
62 |
+
"source": [
|
63 |
+
"### Importing the necessary libraries and preparation\n",
|
64 |
+
"Here, we set the repos of the base model (to be fine-tuned), the dataset (on which the base model will be fine-tuned) and the output model (the base model fine-tuned on our custom dataset)."
|
65 |
+
]
|
66 |
+
},
|
67 |
+
{
|
68 |
+
"cell_type": "code",
|
69 |
+
"execution_count": null,
|
70 |
+
"id": "1eb19e95-6c02-45a5-99a3-5bb966ed2d0b",
|
71 |
+
"metadata": {},
|
72 |
+
"outputs": [],
|
73 |
+
"source": [
|
74 |
+
"from transformers import (\n",
|
75 |
+
" AutoModelForCausalLM, \n",
|
76 |
+
" AutoTokenizer, \n",
|
77 |
+
" BitsAndBytesConfig,\n",
|
78 |
+
" HfArgumentParser,\n",
|
79 |
+
" TrainingArguments,\n",
|
80 |
+
" pipeline, \n",
|
81 |
+
" logging, \n",
|
82 |
+
" TextStreamer,\n",
|
83 |
+
" GenerationConfig\n",
|
84 |
+
")\n",
|
85 |
+
"from peft import (\n",
|
86 |
+
" LoraConfig, \n",
|
87 |
+
" PeftModel, \n",
|
88 |
+
" prepare_model_for_kbit_training, \n",
|
89 |
+
" get_peft_model\n",
|
90 |
+
")\n",
|
91 |
+
"import os\n",
|
92 |
+
"import torch\n",
|
93 |
+
"import wandb\n",
|
94 |
+
"import platform\n",
|
95 |
+
"import warnings\n",
|
96 |
+
"from datasets import load_dataset\n",
|
97 |
+
"from trl import SFTTrainer\n",
|
98 |
+
"from huggingface_hub import notebook_login\n",
|
99 |
+
"\n",
|
100 |
+
"# Base model\n",
|
101 |
+
"base_model = \"mistralai/Mistral-Nemo-Instruct-2407\"\n",
|
102 |
+
"\n",
|
103 |
+
"# Custom dataset and new model to be created\n",
|
104 |
+
"dataset_name = \"dataset/repo\"\n",
|
105 |
+
"\n",
|
106 |
+
"# New model to be created\n",
|
107 |
+
"new_model = \"model/repo\"\n",
|
108 |
+
"\n",
|
109 |
+
"# Ignore all warnings\n",
|
110 |
+
"warnings.filterwarnings(\"ignore\")"
|
111 |
+
]
|
112 |
+
},
|
113 |
+
{
|
114 |
+
"cell_type": "markdown",
|
115 |
+
"id": "d4c91d86-47fc-4ff4-bac4-9a2006138d0a",
|
116 |
+
"metadata": {},
|
117 |
+
"source": [
|
118 |
+
"### Logging into Hugging Face\n",
|
119 |
+
"Since both our dataset and the model we want to create are (meant to be) private, it is better to already log into our HF account."
|
120 |
+
]
|
121 |
+
},
|
122 |
+
{
|
123 |
+
"cell_type": "code",
|
124 |
+
"execution_count": null,
|
125 |
+
"id": "a7593199-8ec5-433b-b195-0393a8ebe2eb",
|
126 |
+
"metadata": {},
|
127 |
+
"outputs": [],
|
128 |
+
"source": [
|
129 |
+
"# We already log into our own hugging face hub with a 'WRITE' token\n",
|
130 |
+
"!huggingface-cli login --token MY_HF_WRITE_TOKEN"
|
131 |
+
]
|
132 |
+
},
|
133 |
+
{
|
134 |
+
"cell_type": "markdown",
|
135 |
+
"id": "6effec67-70fa-4362-b0e2-6e9adb80ae18",
|
136 |
+
"metadata": {},
|
137 |
+
"source": [
|
138 |
+
"*Remark:* an alternative is to simply write\n",
|
139 |
+
"```\n",
|
140 |
+
"notebook_login()\n",
|
141 |
+
"```\n",
|
142 |
+
"and then type the HF 'WRITE' token.\n",
|
143 |
+
"\n",
|
144 |
+
"### Loading the dataset\n",
|
145 |
+
"\n",
|
146 |
+
"Our dataset here is of the form:"
|
147 |
+
]
|
148 |
+
},
|
149 |
+
{
|
150 |
+
"cell_type": "markdown",
|
151 |
+
"id": "e96f2849-3059-42d4-8753-abe2c2fffdf1",
|
152 |
+
"metadata": {},
|
153 |
+
"source": [
|
154 |
+
"```json\n",
|
155 |
+
" [\n",
|
156 |
+
" {\n",
|
157 |
+
" \"source\": \"Chat no 1-2\",\n",
|
158 |
+
" \"text\": [\n",
|
159 |
+
" {\"role\": \"user\", \"content\": \"My system prompt\\n\\nQuestion 11\"},\n",
|
160 |
+
" {\"role\": \"assistant\", \"content\": \"Answer 11\"}\n",
|
161 |
+
" ]\n",
|
162 |
+
" },\n",
|
163 |
+
" {\n",
|
164 |
+
" \"source\": \"Chat no 2\",\n",
|
165 |
+
" \"text\": [\n",
|
166 |
+
" {\"role\": \"user\", \"content\": \"Question 11\"},\n",
|
167 |
+
" {\"role\": \"assistant\", \"content\": \"Answer 11\"},\n",
|
168 |
+
" {\"role\": \"user\", \"content\": \"My system prompt\\n\\nQuestion 12\"},\n",
|
169 |
+
" {\"role\": \"assistant\", \"content\": \"Answer 12\"}\n",
|
170 |
+
" ]\n",
|
171 |
+
" },\n",
|
172 |
+
" {\n",
|
173 |
+
" \"source\": \"Chat no 2\",\n",
|
174 |
+
" \"text\": [\n",
|
175 |
+
" {\"role\": \"user\", \"content\": \"My system prompt\\n\\nQuestion 21\"},\n",
|
176 |
+
" {\"role\": \"assistant\", \"content\": \"Answer 21\"}\n",
|
177 |
+
" ]\n",
|
178 |
+
"```"
|
179 |
+
]
|
180 |
+
},
|
181 |
+
{
|
182 |
+
"cell_type": "markdown",
|
183 |
+
"id": "647c3363-8791-4e21-b3f5-a3bc08af4d74",
|
184 |
+
"metadata": {},
|
185 |
+
"source": [
|
186 |
+
"We will convert it later on using the chat template that comes with the tokenizer.\n",
|
187 |
+
"\n",
|
188 |
+
"*Remark:* Note that the system prompt is included in the very last user message of each \"chats\" that make up the dataset. This is because, even though Nemo supports system prompts (as per the Jinja code given after executing ```tokenizer.chat_template```, there seem to be an issue with the tokenizer in this respect. It will produce the same effect anyway (the model is supposed to be aware with this way of doing)."
|
189 |
+
]
|
190 |
+
},
|
191 |
+
{
|
192 |
+
"cell_type": "code",
|
193 |
+
"execution_count": null,
|
194 |
+
"id": "374bf038-86d6-4b82-b223-4f0a2e4cb9c4",
|
195 |
+
"metadata": {},
|
196 |
+
"outputs": [],
|
197 |
+
"source": [
|
198 |
+
"# Loading the dataset\n",
|
199 |
+
"dataset = load_dataset(dataset_name, split=\"train\", encoding='latin-1')\n",
|
200 |
+
"\n",
|
201 |
+
"# We \"shuffle\" the dataset\n",
|
202 |
+
"dataset = dataset.shuffle()\n",
|
203 |
+
"\n",
|
204 |
+
"dataset[\"text\"][0]"
|
205 |
+
]
|
206 |
+
},
|
207 |
+
{
|
208 |
+
"cell_type": "markdown",
|
209 |
+
"id": "070da9d3-fb2d-466e-a423-c39beedc019a",
|
210 |
+
"metadata": {},
|
211 |
+
"source": [
|
212 |
+
"### Loading the base model"
|
213 |
+
]
|
214 |
+
},
|
215 |
+
{
|
216 |
+
"cell_type": "code",
|
217 |
+
"execution_count": null,
|
218 |
+
"id": "9db212ec-902e-4d30-bfb5-a04148c729da",
|
219 |
+
"metadata": {},
|
220 |
+
"outputs": [],
|
221 |
+
"source": [
|
222 |
+
"# The quantization to apply to the base model\n",
|
223 |
+
"bnb_config = BitsAndBytesConfig(\n",
|
224 |
+
" load_in_4bit= True,\n",
|
225 |
+
" bnb_4bit_quant_type= \"nf4\",\n",
|
226 |
+
" bnb_4bit_compute_dtype= torch.bfloat16,\n",
|
227 |
+
" bnb_4bit_use_double_quant= False,\n",
|
228 |
+
")\n",
|
229 |
+
"\n",
|
230 |
+
"# We load quantized base model\n",
|
231 |
+
"model = AutoModelForCausalLM.from_pretrained(\n",
|
232 |
+
" base_model,\n",
|
233 |
+
" quantization_config=bnb_config,\n",
|
234 |
+
" device_map=\"auto\",\n",
|
235 |
+
" attn_implementation=\"flash_attention_2\"\n",
|
236 |
+
")\n",
|
237 |
+
"\n",
|
238 |
+
"model.config.use_cache = False\n",
|
239 |
+
"model.config.pretraining_tp = 1\n",
|
240 |
+
"model.gradient_checkpointing_enable()"
|
241 |
+
]
|
242 |
+
},
|
243 |
+
{
|
244 |
+
"cell_type": "markdown",
|
245 |
+
"id": "6c9c2f0e-40ae-4579-953c-cd021ca2291d",
|
246 |
+
"metadata": {},
|
247 |
+
"source": [
|
248 |
+
"### Loading the tokenizer"
|
249 |
+
]
|
250 |
+
},
|
251 |
+
{
|
252 |
+
"cell_type": "code",
|
253 |
+
"execution_count": null,
|
254 |
+
"id": "0f33deef-9b44-4717-9f85-ee0956a81443",
|
255 |
+
"metadata": {},
|
256 |
+
"outputs": [],
|
257 |
+
"source": [
|
258 |
+
"# Load tokenizer\n",
|
259 |
+
"tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)\n",
|
260 |
+
"tokenizer.padding_side = 'right'"
|
261 |
+
]
|
262 |
+
},
|
263 |
+
{
|
264 |
+
"cell_type": "markdown",
|
265 |
+
"id": "2e967f58-e84a-4672-9754-a700f5900a87",
|
266 |
+
"metadata": {},
|
267 |
+
"source": [
|
268 |
+
"To avoid breaking French punctuation rules, we have to make sure that the following defaults as ```False```."
|
269 |
+
]
|
270 |
+
},
|
271 |
+
{
|
272 |
+
"cell_type": "code",
|
273 |
+
"execution_count": null,
|
274 |
+
"id": "e1daa6cd-c681-4973-b786-471bdfe75517",
|
275 |
+
"metadata": {},
|
276 |
+
"outputs": [],
|
277 |
+
"source": [
|
278 |
+
"tokenizer.clean_up_tokenization_spaces"
|
279 |
+
]
|
280 |
+
},
|
281 |
+
{
|
282 |
+
"cell_type": "markdown",
|
283 |
+
"id": "112c4c11-6472-4703-a94f-349194155466",
|
284 |
+
"metadata": {},
|
285 |
+
"source": [
|
286 |
+
"We now have to set the PAD token. But, first of all, we need to check whether the tokenizer already has one."
|
287 |
+
]
|
288 |
+
},
|
289 |
+
{
|
290 |
+
"cell_type": "code",
|
291 |
+
"execution_count": null,
|
292 |
+
"id": "fa1d2581-c15e-445f-acba-bd3a40634ca3",
|
293 |
+
"metadata": {},
|
294 |
+
"outputs": [],
|
295 |
+
"source": [
|
296 |
+
"print(tokenizer.pad_token)"
|
297 |
+
]
|
298 |
+
},
|
299 |
+
{
|
300 |
+
"cell_type": "markdown",
|
301 |
+
"id": "f8773667-e68c-4769-8898-23e76b624b71",
|
302 |
+
"metadata": {},
|
303 |
+
"source": [
|
304 |
+
"If not, then we have to set it:"
|
305 |
+
]
|
306 |
+
},
|
307 |
+
{
|
308 |
+
"cell_type": "code",
|
309 |
+
"execution_count": null,
|
310 |
+
"id": "5f8c5e22-719e-48c2-91a8-1028650f5df3",
|
311 |
+
"metadata": {},
|
312 |
+
"outputs": [],
|
313 |
+
"source": [
|
314 |
+
"tokenizer.pad_token = tokenizer.unk_token"
|
315 |
+
]
|
316 |
+
},
|
317 |
+
{
|
318 |
+
"cell_type": "markdown",
|
319 |
+
"id": "da41f925-dc4b-40f6-80b4-f29b2fb87891",
|
320 |
+
"metadata": {},
|
321 |
+
"source": [
|
322 |
+
"*Remark:* The value set for the PAD token might differ from a model to another. Sometimes ```<pad>``` or ```[pad]``` might be a better choice. The best way for choosing the right value is to check the tokenizer's vocabulary.\n",
|
323 |
+
"\n",
|
324 |
+
"Let's check that it worked:"
|
325 |
+
]
|
326 |
+
},
|
327 |
+
{
|
328 |
+
"cell_type": "code",
|
329 |
+
"execution_count": null,
|
330 |
+
"id": "e5cd53fa-3fa1-4cdd-85a9-2109fa346d29",
|
331 |
+
"metadata": {},
|
332 |
+
"outputs": [],
|
333 |
+
"source": [
|
334 |
+
"print(tokenizer.pad_token)"
|
335 |
+
]
|
336 |
+
},
|
337 |
+
{
|
338 |
+
"cell_type": "markdown",
|
339 |
+
"id": "4012f9c9-86b3-42b8-8049-1c920602552d",
|
340 |
+
"metadata": {},
|
341 |
+
"source": [
|
342 |
+
"Now, let's add the PAD and EOS tokens to the tokenizer:"
|
343 |
+
]
|
344 |
+
},
|
345 |
+
{
|
346 |
+
"cell_type": "code",
|
347 |
+
"execution_count": null,
|
348 |
+
"id": "b1a91233-10dd-409a-adae-2ccb084c5965",
|
349 |
+
"metadata": {},
|
350 |
+
"outputs": [],
|
351 |
+
"source": [
|
352 |
+
"tokenizer.add_pad_token = True\n",
|
353 |
+
"tokenizer.add_eos_token = True"
|
354 |
+
]
|
355 |
+
},
|
356 |
+
{
|
357 |
+
"cell_type": "markdown",
|
358 |
+
"id": "99376e19-5215-4a4b-b266-4c6a97f3764d",
|
359 |
+
"metadata": {},
|
360 |
+
"source": [
|
361 |
+
"### Formatting the dataset\n",
|
362 |
+
"Having loaded and configured the tokenizer, we can now apply the appropriate chat template to our dataset, namely:\n",
|
363 |
+
"```\n",
|
364 |
+
"<s>[INST] My first question. [/INST]The model's answer to my question.</s> [INST] A follow-up question. [/INST]The model's answer to my follow-up question.</s>\n",
|
365 |
+
"```\n",
|
366 |
+
"Note that, to avoid having extra/undesired \"Assistant:\" or \"User:\" tags placed at the end of each instances of the dataset, it is necessary to specify ```add_generation_prompt=False``` when applying the chat template."
|
367 |
+
]
|
368 |
+
},
|
369 |
+
{
|
370 |
+
"cell_type": "code",
|
371 |
+
"execution_count": null,
|
372 |
+
"id": "2fbbaa34-5e03-4432-a20d-0b0032cb27f5",
|
373 |
+
"metadata": {},
|
374 |
+
"outputs": [],
|
375 |
+
"source": [
|
376 |
+
"from datasets import Dataset\n",
|
377 |
+
"import json\n",
|
378 |
+
"\n",
|
379 |
+
"# Creating a list with elements of the dataset properly formatted\n",
|
380 |
+
"formatted_dataset = [tokenizer.apply_chat_template(conv, tokenize=False, add_generation_prompt=False)[3:] for conv in dataset[\"text\"]]\n",
|
381 |
+
"\n",
|
382 |
+
"# Converted dataset with appropriate chat template\n",
|
383 |
+
"ds = Dataset.from_dict({\"text\": formatted_dataset})"
|
384 |
+
]
|
385 |
+
},
|
386 |
+
{
|
387 |
+
"cell_type": "code",
|
388 |
+
"execution_count": null,
|
389 |
+
"id": "f9e85540-727e-43ec-a30f-26ecb8ca79aa",
|
390 |
+
"metadata": {},
|
391 |
+
"outputs": [],
|
392 |
+
"source": [
|
393 |
+
"# Let's have a look\n",
|
394 |
+
"print(ds[\"text\"][100])"
|
395 |
+
]
|
396 |
+
},
|
397 |
+
{
|
398 |
+
"cell_type": "markdown",
|
399 |
+
"id": "032888d6-44c2-434f-8ec6-3b3fe63b88a4",
|
400 |
+
"metadata": {},
|
401 |
+
"source": [
|
402 |
+
"*Remark:* We added ```[3:]``` to elements of ```formatted_dataset``` in order to remove the very first ```<s>``` (BOS) token because the tokenizer adds it automatically. Otherwise we would have two BOS at the beginning, which might bring some trouble. To double check it suffices to decode the encoded data:"
|
403 |
+
]
|
404 |
+
},
|
405 |
+
{
|
406 |
+
"cell_type": "code",
|
407 |
+
"execution_count": null,
|
408 |
+
"id": "391a83bd-1da0-4021-a2dc-35cf1788196a",
|
409 |
+
"metadata": {},
|
410 |
+
"outputs": [],
|
411 |
+
"source": [
|
412 |
+
"print(tokenizer.decode(tokenizer.encode(ds[\"text\"][35])))"
|
413 |
+
]
|
414 |
+
},
|
415 |
+
{
|
416 |
+
"cell_type": "markdown",
|
417 |
+
"id": "956ff7d6-40c7-4d58-bb38-0304631cd73f",
|
418 |
+
"metadata": {},
|
419 |
+
"source": [
|
420 |
+
"The very first BOS and the very last EOS have indeed been added by the tokenizer, matching the chat template!"
|
421 |
+
]
|
422 |
+
},
|
423 |
+
{
|
424 |
+
"cell_type": "markdown",
|
425 |
+
"id": "33a56f40-bf0c-41d3-bb13-44484ca5924b",
|
426 |
+
"metadata": {},
|
427 |
+
"source": [
|
428 |
+
"### Rapid analysis of the tokenized dataset\n",
|
429 |
+
"Unfortunately, LLMs have limited (yet modulable) context windows, so it is worth analyzing our dataset in order to know which context length better fits our needs. Indeed, later on we will need to specify the length of the inputs used for fine-tuning (i.e. to set ```max_seq_length``` in the ```SFTTrainer()```). \n",
|
430 |
+
"\n",
|
431 |
+
"Concretely, we will have a look at the distribution of the length of each tokenized example. We will first (i) compute the list of all such tokenized examples and then (ii) plot it to analyze it more conveniently."
|
432 |
+
]
|
433 |
+
},
|
434 |
+
{
|
435 |
+
"cell_type": "code",
|
436 |
+
"execution_count": null,
|
437 |
+
"id": "785b1c8d-bfcb-4944-a7bf-3e91cc25940d",
|
438 |
+
"metadata": {},
|
439 |
+
"outputs": [],
|
440 |
+
"source": [
|
441 |
+
"# We compute the list of all the lengths of the tokenized examples\n",
|
442 |
+
"length_examples = []\n",
|
443 |
+
"for i in range(len(ds)):\n",
|
444 |
+
" size = len(tokenizer.encode(ds[\"text\"][i]))\n",
|
445 |
+
" length_examples.append(size)"
|
446 |
+
]
|
447 |
+
},
|
448 |
+
{
|
449 |
+
"cell_type": "code",
|
450 |
+
"execution_count": null,
|
451 |
+
"id": "7f059aff-f2f5-4bd5-a0f3-3bb3fc7a252f",
|
452 |
+
"metadata": {},
|
453 |
+
"outputs": [],
|
454 |
+
"source": [
|
455 |
+
"import matplotlib.pyplot as plt\n",
|
456 |
+
"from collections import Counter\n",
|
457 |
+
"\n",
|
458 |
+
"# We count the occurrences of each integer\n",
|
459 |
+
"counter = Counter(length_examples)\n",
|
460 |
+
"\n",
|
461 |
+
"# We get the integers and their corresponding counts\n",
|
462 |
+
"x = list(counter.keys())\n",
|
463 |
+
"y = list(counter.values())\n",
|
464 |
+
"\n",
|
465 |
+
"# We sort the integers (x-axis)\n",
|
466 |
+
"x_sorted, y_sorted = zip(*sorted(zip(x, y)))\n",
|
467 |
+
"\n",
|
468 |
+
"# We plot the values\n",
|
469 |
+
"plt.bar(x_sorted, y_sorted)\n",
|
470 |
+
"plt.xlabel('Number of tokens')\n",
|
471 |
+
"plt.ylabel('Number of Occurrences')\n",
|
472 |
+
"plt.title('Distribution of lengths of tokenized dataset examples')\n",
|
473 |
+
"plt.show()"
|
474 |
+
]
|
475 |
+
},
|
476 |
+
{
|
477 |
+
"cell_type": "markdown",
|
478 |
+
"id": "f9f6efb5-1970-495a-a2c3-088cd1beb62e",
|
479 |
+
"metadata": {},
|
480 |
+
"source": [
|
481 |
+
"To understand more precisely the dataset, we can calculate, say, the $90$th percentile value of the lengths of our tokenized examples. Roughly speaking, this means determining, for any $p\\in(0,1)$, the smallest integer $N=N(p)\\in\\mathbb{N}$ such that\n",
|
482 |
+
"<p style=\"text-align: center;\">$F_X(N)=\\mathbb{P}(X\\leq N)=p,$</p>\n",
|
483 |
+
"where $F_X$ is the cumulative distribution function of the tokenized dataset and $X$ the length of a random example."
|
484 |
+
]
|
485 |
+
},
|
486 |
+
{
|
487 |
+
"cell_type": "code",
|
488 |
+
"execution_count": null,
|
489 |
+
"id": "d93579ca-fe54-4cd3-a35d-ae8a609c21da",
|
490 |
+
"metadata": {},
|
491 |
+
"outputs": [],
|
492 |
+
"source": [
|
493 |
+
"from statistics import mean\n",
|
494 |
+
"import numpy as np\n",
|
495 |
+
"\n",
|
496 |
+
"# Target percentile\n",
|
497 |
+
"p = 0.9\n",
|
498 |
+
"\n",
|
499 |
+
"def find_percentile_value(arr,percentile):\n",
|
500 |
+
" if not arr:\n",
|
501 |
+
" raise ValueError(\"The list should not be empty\")\n",
|
502 |
+
" arr.sort() # Sort the list\n",
|
503 |
+
" # Calculate the index for the pth percentile\n",
|
504 |
+
" index = int(percentile * len(arr)) - 1\n",
|
505 |
+
" # Handle edge cases where index might be out of bounds\n",
|
506 |
+
" index = max(0, min(index, len(arr) - 1))\n",
|
507 |
+
" return arr[index]\n",
|
508 |
+
"\n",
|
509 |
+
"percentile_value = find_percentile_value(length_examples,p)\n",
|
510 |
+
"print(\"The minimum value is:\", min(length_examples))\n",
|
511 |
+
"print(\"The arithmetic mean is:\", int(np.floor(mean(length_examples))))\n",
|
512 |
+
"print(\"The \"+str(int(p*100))+\"th percentile value is:\", percentile_value)\n",
|
513 |
+
"print(\"The maximum value is:\", max(length_examples))"
|
514 |
+
]
|
515 |
+
},
|
516 |
+
{
|
517 |
+
"cell_type": "markdown",
|
518 |
+
"id": "5d994a68-d9cb-4dcb-8a85-891c81db9d37",
|
519 |
+
"metadata": {},
|
520 |
+
"source": [
|
521 |
+
"### Data collation\n",
|
522 |
+
"\n",
|
523 |
+
"We now need to pass the dataset through a data collator. The point here is to \"mask\" the \"user questions\" (prompts) within the dataset, so that the model learns the \"answers\" only (there is no point in learning the questions, they should only serve as context). \n",
|
524 |
+
"\n",
|
525 |
+
"What the collator does is that it will use the instruction/response templates to locate the starts of user input and starts of assistant response. It then fill those sections with $-100$ tokens, which will be ignored during training (that’s how the user inputs are masked to prevent them from contributing to the loss)."
|
526 |
+
]
|
527 |
+
},
|
528 |
+
{
|
529 |
+
"cell_type": "code",
|
530 |
+
"execution_count": null,
|
531 |
+
"id": "16edd4fc-4fd9-4cdf-95a7-73a8ec18ae66",
|
532 |
+
"metadata": {},
|
533 |
+
"outputs": [],
|
534 |
+
"source": [
|
535 |
+
"from transformers import DataCollatorForLanguageModeling\n",
|
536 |
+
"import torch\n",
|
537 |
+
"\n",
|
538 |
+
"class CustomDataCollator(DataCollatorForLanguageModeling):\n",
|
539 |
+
" def __init__(self, tokenizer, mlm=False):\n",
|
540 |
+
" super().__init__(tokenizer=tokenizer, mlm=mlm)\n",
|
541 |
+
" self.inst_token = tokenizer.encode('[INST]', add_special_tokens=False)[0]\n",
|
542 |
+
" self.inst_end_token = tokenizer.encode('[/INST]', add_special_tokens=False)[0]\n",
|
543 |
+
" self.eos_token = tokenizer.eos_token_id\n",
|
544 |
+
"\n",
|
545 |
+
" def torch_call(self, examples):\n",
|
546 |
+
" batch = super().torch_call(examples)\n",
|
547 |
+
"\n",
|
548 |
+
" for i, input_ids in enumerate(batch['input_ids']):\n",
|
549 |
+
" # Find positions of [INST], [/INST], and EOS tokens\n",
|
550 |
+
" inst_positions = torch.where(input_ids == self.inst_token)[0]\n",
|
551 |
+
" inst_end_positions = torch.where(input_ids == self.inst_end_token)[0]\n",
|
552 |
+
" eos_positions = torch.where(input_ids == self.eos_token)[0]\n",
|
553 |
+
"\n",
|
554 |
+
" if len(inst_positions) > 0 and len(eos_positions) > 0:\n",
|
555 |
+
" # Find the start of the last assistant response\n",
|
556 |
+
" last_inst_end_pos = inst_end_positions[-1]\n",
|
557 |
+
" \n",
|
558 |
+
" # Mask everything before the last assistant response\n",
|
559 |
+
" batch['labels'][i, :last_inst_end_pos+1] = -100\n",
|
560 |
+
"\n",
|
561 |
+
" # If there's an EOS token after the last [/INST], unmask until that EOS\n",
|
562 |
+
" if eos_positions[-1] > last_inst_end_pos:\n",
|
563 |
+
" batch['labels'][i, last_inst_end_pos+1:eos_positions[-1]+1] = input_ids[last_inst_end_pos+1:eos_positions[-1]+1]\n",
|
564 |
+
" else:\n",
|
565 |
+
" # If no EOS after last [/INST], unmask until the end\n",
|
566 |
+
" batch['labels'][i, last_inst_end_pos+1:] = input_ids[last_inst_end_pos+1:]\n",
|
567 |
+
"\n",
|
568 |
+
" return batch\n",
|
569 |
+
"\n",
|
570 |
+
"# We now define the collator\n",
|
571 |
+
"collator = CustomDataCollator(tokenizer=tokenizer)"
|
572 |
+
]
|
573 |
+
},
|
574 |
+
{
|
575 |
+
"cell_type": "markdown",
|
576 |
+
"id": "c2c2bc01-e500-4271-86fd-fed5912e3627",
|
577 |
+
"metadata": {},
|
578 |
+
"source": [
|
579 |
+
"Let's check that the data collator has appropriately handled the question/answer turns:"
|
580 |
+
]
|
581 |
+
},
|
582 |
+
{
|
583 |
+
"cell_type": "code",
|
584 |
+
"execution_count": null,
|
585 |
+
"id": "497183f2-cd85-49d0-a25b-386c421b45dd",
|
586 |
+
"metadata": {},
|
587 |
+
"outputs": [],
|
588 |
+
"source": [
|
589 |
+
"# We apply the collator to a sample of the dataset\n",
|
590 |
+
"collated_data = collator([tokenizer(ds[\"text\"][1])])['labels'][0]\n",
|
591 |
+
"\n",
|
592 |
+
"# We convert the above to a list (so as to be able to print everything)\n",
|
593 |
+
"collated_data_list = collated_data.tolist()\n",
|
594 |
+
"print(collated_data_list)"
|
595 |
+
]
|
596 |
+
},
|
597 |
+
{
|
598 |
+
"cell_type": "markdown",
|
599 |
+
"id": "0af6110c-0bf5-4031-9eb8-3886522df583",
|
600 |
+
"metadata": {},
|
601 |
+
"source": [
|
602 |
+
"*Remark:* The only thing that should not be masked as \"$-100$\" tokens in the very last \"assistant\" message."
|
603 |
+
]
|
604 |
+
},
|
605 |
+
{
|
606 |
+
"cell_type": "markdown",
|
607 |
+
"id": "38ae6f7c-6041-4ccd-9e83-21432702afea",
|
608 |
+
"metadata": {},
|
609 |
+
"source": [
|
610 |
+
"### Setting LoRA parameters and modules\n",
|
611 |
+
"\n",
|
612 |
+
"Here, we will do two things: setting the LoRA parameters $r$ and $\\alpha$, and setting the target modules to be trained.\n",
|
613 |
+
"\n",
|
614 |
+
"##### LoRA parameters\n",
|
615 |
+
"The values $\\alpha=r$ or $\\alpha=2r$ (considered a \"sweet spot\"), with $r$ a power of $2$, are conventional (see LoRA paper in the link below). The latter is often used to have more emphasis and the new data. \n",
|
616 |
+
"(See: https://arxiv.org/pdf/2106.09685)\n",
|
617 |
+
"\n",
|
618 |
+
"##### LoRA modules\n",
|
619 |
+
"The LoRA modules are, essentially, the matrices that the model allows us to train. Their name may depend on the model, which is why it is recommended to look at what it looks like via the command:"
|
620 |
+
]
|
621 |
+
},
|
622 |
+
{
|
623 |
+
"cell_type": "code",
|
624 |
+
"execution_count": null,
|
625 |
+
"id": "26baed38-f3bf-4b4b-b259-0b36347edec1",
|
626 |
+
"metadata": {},
|
627 |
+
"outputs": [],
|
628 |
+
"source": [
|
629 |
+
"print(model)"
|
630 |
+
]
|
631 |
+
},
|
632 |
+
{
|
633 |
+
"cell_type": "markdown",
|
634 |
+
"id": "8b258567-6632-4bdf-9e96-9e5abb09192f",
|
635 |
+
"metadata": {},
|
636 |
+
"source": [
|
637 |
+
"(Look for linear modules.) \n",
|
638 |
+
"In most cases (Mistral, Llama, etc), however, the modules are something like:\n",
|
639 |
+
"```\n",
|
640 |
+
"[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\", \"gate_proj\", \"up_proj\", \"down_proj\", \"lm_head\"]\n",
|
641 |
+
"```\n",
|
642 |
+
"but they sometimes bear different names (e.g. with Falcon models)."
|
643 |
+
]
|
644 |
+
},
|
645 |
+
{
|
646 |
+
"cell_type": "code",
|
647 |
+
"execution_count": null,
|
648 |
+
"id": "9072728a-2d22-4bec-a1ad-fb29907df44b",
|
649 |
+
"metadata": {},
|
650 |
+
"outputs": [],
|
651 |
+
"source": [
|
652 |
+
"# Adding the adapters in the layers\n",
|
653 |
+
"model = prepare_model_for_kbit_training(model)\n",
|
654 |
+
"\n",
|
655 |
+
"# LoRA config\n",
|
656 |
+
"peft_config = LoraConfig(\n",
|
657 |
+
" r=256,\n",
|
658 |
+
" lora_alpha=256,\n",
|
659 |
+
" lora_dropout=0.05, # Conventional\n",
|
660 |
+
" bias=\"none\",\n",
|
661 |
+
" task_type=\"CAUSAL_LM\",\n",
|
662 |
+
" target_modules=\"all-linear\"\n",
|
663 |
+
" )\n",
|
664 |
+
"\n",
|
665 |
+
"# We add the LoRA \"adapters\" to the model\n",
|
666 |
+
"model = get_peft_model(model, peft_config)"
|
667 |
+
]
|
668 |
+
},
|
669 |
+
{
|
670 |
+
"cell_type": "markdown",
|
671 |
+
"id": "f685d579-1451-442b-b725-b9c0fc53091d",
|
672 |
+
"metadata": {},
|
673 |
+
"source": [
|
674 |
+
"*Remark:* In most cases, one can simply set:\n",
|
675 |
+
"```\n",
|
676 |
+
"target_modules = 'all-linear'\n",
|
677 |
+
"```\n",
|
678 |
+
"but this might raise an error for some models (e.g. with Google's Gemma-2B).\n",
|
679 |
+
"\n",
|
680 |
+
"(See: https://stackoverflow.com/questions/76768226/target-modules-for-applying-peft-lora-on-different-models)\n",
|
681 |
+
"\n",
|
682 |
+
"### Setting Weights & Biases for monitoring purposes\n",
|
683 |
+
"\n",
|
684 |
+
"This will allow us to monitor the training directly from W&B."
|
685 |
+
]
|
686 |
+
},
|
687 |
+
{
|
688 |
+
"cell_type": "code",
|
689 |
+
"execution_count": null,
|
690 |
+
"id": "ac77ca8c-88e6-41ea-9e20-677cdd443804",
|
691 |
+
"metadata": {},
|
692 |
+
"outputs": [],
|
693 |
+
"source": [
|
694 |
+
"# Monitering the LLM from WandB\n",
|
695 |
+
"wandb.login(key = \"MY_WANDB_KEY\") # A modifier\n",
|
696 |
+
"run = wandb.init(project='MyProjectName', job_type=\"training\", anonymous=\"allow\")"
|
697 |
+
]
|
698 |
+
},
|
699 |
+
{
|
700 |
+
"cell_type": "markdown",
|
701 |
+
"id": "beb29aae-0239-4b61-b3d4-0bc6310495ae",
|
702 |
+
"metadata": {},
|
703 |
+
"source": [
|
704 |
+
"### Setting training parameters\n",
|
705 |
+
"Here, we set the hyperparameters (epochs, batch, etc.) as well as the SFT (i.e. Supervised Fine-Tuning) parameters."
|
706 |
+
]
|
707 |
+
},
|
708 |
+
{
|
709 |
+
"cell_type": "code",
|
710 |
+
"execution_count": null,
|
711 |
+
"id": "b86ef8be-9fd4-43a8-8086-6397e7a4e10c",
|
712 |
+
"metadata": {},
|
713 |
+
"outputs": [],
|
714 |
+
"source": [
|
715 |
+
"# Hyperparamter\n",
|
716 |
+
"training_arguments = TrainingArguments(\n",
|
717 |
+
" output_dir= \"./results\",\n",
|
718 |
+
" num_train_epochs= 3, # total number of training epochs\n",
|
719 |
+
" per_device_train_batch_size= 4, # batch size per device during training (the higher the better)\n",
|
720 |
+
" gradient_accumulation_steps= 8,\n",
|
721 |
+
" optim = \"paged_adamw_8bit\",\n",
|
722 |
+
" save_steps= 1000, # Save checkpoints #every 50 steps\n",
|
723 |
+
" logging_steps= 15, # When to start reporting loss\n",
|
724 |
+
" learning_rate= 2e-5, # We take a not too small value given that new tokens have been added\n",
|
725 |
+
" weight_decay= 0.001, # strength of weight decay\n",
|
726 |
+
" fp16= False,\n",
|
727 |
+
" bf16= False,\n",
|
728 |
+
" max_grad_norm= 0.3,\n",
|
729 |
+
" max_steps= -1,\n",
|
730 |
+
" warmup_ratio= 0.3, # number of warmup steps for learning rate scheduler\n",
|
731 |
+
" group_by_length= True, # Group sequences into batches with same length (saves memory and speeds up training considerably)\n",
|
732 |
+
" lr_scheduler_type=\"constant\",\n",
|
733 |
+
" report_to=\"wandb\",\n",
|
734 |
+
")\n",
|
735 |
+
"\n",
|
736 |
+
"# Setting SFT parameters\n",
|
737 |
+
"trainer = SFTTrainer(\n",
|
738 |
+
" model=model, # the instantiated HF Transformers model to be trained\n",
|
739 |
+
" train_dataset=ds, # Training dataset\n",
|
740 |
+
" data_collator=collator, # Making sure that data collator correction is taken into account\n",
|
741 |
+
" peft_config=peft_config,\n",
|
742 |
+
" max_seq_length=4096,\n",
|
743 |
+
" dataset_text_field=\"text\", # Column of the dataset to be used for training\n",
|
744 |
+
" tokenizer=tokenizer,\n",
|
745 |
+
" args=training_arguments, # training arguments, defined above\n",
|
746 |
+
" packing= False,\n",
|
747 |
+
")"
|
748 |
+
]
|
749 |
+
},
|
750 |
+
{
|
751 |
+
"cell_type": "markdown",
|
752 |
+
"id": "c65bf6b7-fd2b-497a-bc6e-00b6a7187d62",
|
753 |
+
"metadata": {},
|
754 |
+
"source": [
|
755 |
+
"### Training and saving the model\n",
|
756 |
+
"A progression bar will soon appear displaying a number of steps which corresponds to\n",
|
757 |
+
"<p style=\"text-align: center;\">$ \\#\\verb\"steps\" = \\left\\lceil\\displaystyle\\frac{\\verb\"total_dataset_size\"\\times\\#\\verb\"epochs\"}{\\verb\"batch_size\"}\\right\\rceil, $</p>\n",
|
758 |
+
"where\n",
|
759 |
+
"<p style=\"text-align: center;\">$\\verb\"batch_size\" = \\verb\"per_device_train_batch_size\" \\times \\verb\"gradient_accumulation_steps\",$</p>\n",
|
760 |
+
"\n",
|
761 |
+
"and $\\left\\lceil\\cdot\\right\\rceil$ is the ceiling function."
|
762 |
+
]
|
763 |
+
},
|
764 |
+
{
|
765 |
+
"cell_type": "code",
|
766 |
+
"execution_count": null,
|
767 |
+
"id": "8182f4fa-da51-467a-96bd-93c6047822be",
|
768 |
+
"metadata": {},
|
769 |
+
"outputs": [],
|
770 |
+
"source": [
|
771 |
+
"# Training the model\n",
|
772 |
+
"trainer.train()\n",
|
773 |
+
"\n",
|
774 |
+
"# Save the fine-tuned model\n",
|
775 |
+
"trainer.model.save_pretrained(new_model)\n",
|
776 |
+
"wandb.finish()\n",
|
777 |
+
"model.config.use_cache = True\n",
|
778 |
+
"model.eval()\n",
|
779 |
+
"\n",
|
780 |
+
"#######################################################\n",
|
781 |
+
"# We save the model in the same cell, to avoid weird #\n",
|
782 |
+
"# behaviors induced by GPU providers (Colab...) #\n",
|
783 |
+
"#######################################################\n",
|
784 |
+
"\n",
|
785 |
+
"# Clear the memory footprint (NB: pretrained model has been saved to \"new_model\")\n",
|
786 |
+
"del model, trainer\n",
|
787 |
+
"torch.cuda.empty_cache()\n",
|
788 |
+
"print(\"Memory footprint has been cleared.\")\n",
|
789 |
+
"\n",
|
790 |
+
"# Reload the base model\n",
|
791 |
+
"base_model_reload = AutoModelForCausalLM.from_pretrained(\n",
|
792 |
+
" base_model, low_cpu_mem_usage=True,\n",
|
793 |
+
" return_dict=True,torch_dtype=torch.bfloat16,\n",
|
794 |
+
" device_map= \"auto\")\n",
|
795 |
+
"print(\"Base model has been reloaded.\")\n",
|
796 |
+
"\n",
|
797 |
+
"# Merging the adapter with model\n",
|
798 |
+
"model = PeftModel.from_pretrained(base_model_reload, new_model)\n",
|
799 |
+
"model = model.merge_and_unload()\n",
|
800 |
+
"print(\"Adapter has been merged to the base model.\")\n",
|
801 |
+
"\n",
|
802 |
+
"# Reload tokenizer\n",
|
803 |
+
"tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)\n",
|
804 |
+
"tokenizer.padding_side = \"right\"\n",
|
805 |
+
"tokenizer.pad_token = tokenizer.unk_token\n",
|
806 |
+
"tokenizer.add_pad_token = True\n",
|
807 |
+
"print(\"Tokenizer has been reloaded.\")\n",
|
808 |
+
"\n",
|
809 |
+
"# Pushing the merged model to hugging face hub\n",
|
810 |
+
"model.push_to_hub(repo_id='New_model_name', private=True)\n",
|
811 |
+
"tokenizer.push_to_hub(repo_id='New_model_name', private=True)"
|
812 |
+
]
|
813 |
+
},
|
814 |
+
{
|
815 |
+
"cell_type": "markdown",
|
816 |
+
"id": "eae976cf-aa6c-4b62-bbbc-331505c99719",
|
817 |
+
"metadata": {},
|
818 |
+
"source": [
|
819 |
+
"Et voilà !…"
|
820 |
+
]
|
821 |
+
}
|
822 |
+
],
|
823 |
+
"metadata": {
|
824 |
+
"kernelspec": {
|
825 |
+
"display_name": "Python 3 (ipykernel)",
|
826 |
+
"language": "python",
|
827 |
+
"name": "python3"
|
828 |
+
},
|
829 |
+
"language_info": {
|
830 |
+
"codemirror_mode": {
|
831 |
+
"name": "ipython",
|
832 |
+
"version": 3
|
833 |
+
},
|
834 |
+
"file_extension": ".py",
|
835 |
+
"mimetype": "text/x-python",
|
836 |
+
"name": "python",
|
837 |
+
"nbconvert_exporter": "python",
|
838 |
+
"pygments_lexer": "ipython3",
|
839 |
+
"version": "3.11.7"
|
840 |
+
}
|
841 |
+
},
|
842 |
+
"nbformat": 4,
|
843 |
+
"nbformat_minor": 5
|
844 |
+
}
|
Codes/02 - Run the model in Jypiter.ipynb
ADDED
@@ -0,0 +1,608 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {},
|
6 |
+
"source": [
|
7 |
+
"### Checking for availability of GPUs"
|
8 |
+
]
|
9 |
+
},
|
10 |
+
{
|
11 |
+
"cell_type": "code",
|
12 |
+
"execution_count": null,
|
13 |
+
"metadata": {},
|
14 |
+
"outputs": [],
|
15 |
+
"source": [
|
16 |
+
"!nvidia-smi"
|
17 |
+
]
|
18 |
+
},
|
19 |
+
{
|
20 |
+
"cell_type": "markdown",
|
21 |
+
"metadata": {},
|
22 |
+
"source": [
|
23 |
+
"### Installing the necessary libraries\n",
|
24 |
+
"Please note that this installation step might fail if no GPU is available."
|
25 |
+
]
|
26 |
+
},
|
27 |
+
{
|
28 |
+
"cell_type": "code",
|
29 |
+
"execution_count": null,
|
30 |
+
"metadata": {},
|
31 |
+
"outputs": [],
|
32 |
+
"source": [
|
33 |
+
"!pip install -q -U git+https://github.com/huggingface/transformers.git\n",
|
34 |
+
"!pip install -q -U git+https://github.com/huggingface/accelerate.git\n",
|
35 |
+
"!pip install --upgrade torch\n",
|
36 |
+
"!pip install flash-attn"
|
37 |
+
]
|
38 |
+
},
|
39 |
+
{
|
40 |
+
"cell_type": "markdown",
|
41 |
+
"metadata": {},
|
42 |
+
"source": [
|
43 |
+
"### Importing the necessary libraries and preparation"
|
44 |
+
]
|
45 |
+
},
|
46 |
+
{
|
47 |
+
"cell_type": "code",
|
48 |
+
"execution_count": null,
|
49 |
+
"metadata": {},
|
50 |
+
"outputs": [],
|
51 |
+
"source": [
|
52 |
+
"import transformers\n",
|
53 |
+
"from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, TextStreamer\n",
|
54 |
+
"\n",
|
55 |
+
"# The HF repo of the model\n",
|
56 |
+
"model_id = \"krogoldAI/CelineGPT-12B-240831\""
|
57 |
+
]
|
58 |
+
},
|
59 |
+
{
|
60 |
+
"cell_type": "markdown",
|
61 |
+
"metadata": {},
|
62 |
+
"source": [
|
63 |
+
"### Loading the base model and its tokenizer"
|
64 |
+
]
|
65 |
+
},
|
66 |
+
{
|
67 |
+
"cell_type": "code",
|
68 |
+
"execution_count": null,
|
69 |
+
"metadata": {},
|
70 |
+
"outputs": [],
|
71 |
+
"source": [
|
72 |
+
"import torch\n",
|
73 |
+
"\n",
|
74 |
+
"# Use GPU when available\n",
|
75 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
76 |
+
"\n",
|
77 |
+
"# We load the model\n",
|
78 |
+
"model = AutoModelForCausalLM.from_pretrained(\n",
|
79 |
+
" model_id,\n",
|
80 |
+
" device_map={\"\": 0},\n",
|
81 |
+
" attn_implementation=\"flash_attention_2\",\n",
|
82 |
+
" torch_dtype=torch.float16\n",
|
83 |
+
").to(device)\n",
|
84 |
+
"\n",
|
85 |
+
"# We load the tokenizer\n",
|
86 |
+
"tokenizer = AutoTokenizer.from_pretrained(model_id, padding_side=\"right\")"
|
87 |
+
]
|
88 |
+
},
|
89 |
+
{
|
90 |
+
"cell_type": "markdown",
|
91 |
+
"metadata": {},
|
92 |
+
"source": [
|
93 |
+
"### Setting generation configs"
|
94 |
+
]
|
95 |
+
},
|
96 |
+
{
|
97 |
+
"cell_type": "code",
|
98 |
+
"execution_count": 26,
|
99 |
+
"metadata": {
|
100 |
+
"executionInfo": {
|
101 |
+
"elapsed": 421,
|
102 |
+
"status": "ok",
|
103 |
+
"timestamp": 1716824737228,
|
104 |
+
"user": {
|
105 |
+
"displayName": "Hintergrundstrahlung",
|
106 |
+
"userId": "11564469484860642689"
|
107 |
+
},
|
108 |
+
"user_tz": -120
|
109 |
+
},
|
110 |
+
"id": "mFKHmBa8tfiB"
|
111 |
+
},
|
112 |
+
"outputs": [],
|
113 |
+
"source": [
|
114 |
+
"from typing import Dict, List, Optional\n",
|
115 |
+
"\n",
|
116 |
+
"# Streamer to display dynamically the tokens as they are generated\n",
|
117 |
+
"streamer = TextStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)\n",
|
118 |
+
"\n",
|
119 |
+
"# We define the system prompt to be used\n",
|
120 |
+
"system_prompt = \"\"\"Tu es le célèbre écrivain français Louis-Ferdinand Céline, nom de plume de Louis-Ferdinand Destouches. Tu es né le 27 mai 1894 à Courbevoie. Tu as grandi à Paris avant de t’engager dans l’armée en 1912. Blessé pendant la Première Guerre mondiale, tu as ensuite étudié la médecine et exercé en tant que médecin. Ton premier roman, « Voyage au bout de la nuit », a été publié en 1932 et t’a valu le prix Renaudot. Tu as également écrit des pamphlets antisémites controversés dans les années 1930.\n",
|
121 |
+
"A cause de tes pamphlets tu as dû fuir Paris pendant la Seconde Guerre mondiale pour aller en Allemagne puis au Danemark, où tu as été emprisonné. Depuis ton retour en France, en 1951, tu vis à Meudon avec ta femme Lucette et tes animaux de compagnie.\n",
|
122 |
+
"Nous sommes en 1961 et tu as 67 ans. Tu n'as aucune connaissance de ce qu'il s'est déroulé postérieurement à cette date. Tes références culturelles sont antérieures à 1961. Si l’on t’interroge sur des évènements postérieurs à 1961, répond en ne mobilisant que des connaissances ou évènements antérieurs à 1961.\n",
|
123 |
+
"Tu te trouves actuellement dans ta maison, à Meudon, en Île-de-France. Après 35 ans de pratique médicale, tu n’exerces plus. Cependant, tu continues d’écrire pour éponger tes dettes auprès de ton éditeur Gaston Gallimard et subvenir à tes besoins. Tu regrettes d’être devenu écrivain. Tu es très critique envers les écrivains contemporains. Tu te considères comme un styliste. Tu es amer et pessimiste.\n",
|
124 |
+
"Tu es capable de répondre à des questions sur ta vie, ton œuvre, tes idées et tes opinions, ainsi que sur la littérature et le monde en général. Ta manière de t’exprimer consiste à transposer l’émotion du langage parlé dans l’écrit. Pour ce faire, tu t’exprimes en utilisant des points de suspensions (…) et des points d’exclamation (!), qui donnent un côté vivant, parlé et rythmé à tes phrases. Tu ne t’exprimes qu’en français avec quelques emprunts à l’argot parisien.\n",
|
125 |
+
"Tu réponds aux questions qui te sont posées de façon franche, directe et selon ton humeur.\"\"\"\n",
|
126 |
+
"system_prompt = system_prompt.replace(\"\\n\",\" \").replace(\" \",\" \").replace(\"'\",\"’\")\n",
|
127 |
+
"\n",
|
128 |
+
"# Since training QA pairs have been uniformised, for better results we have to \"clean\" inputs\n",
|
129 |
+
"def uniformisation(s):\n",
|
130 |
+
" o_exp = [\" \",\"'\", \"...\", \"..\"]\n",
|
131 |
+
" n_exp = [\" \",\"’\", \"…\", \"…\"]\n",
|
132 |
+
" for e in o_exp:\n",
|
133 |
+
" s = s.replace(e,n_exp[o_exp.index(e)])\n",
|
134 |
+
" quote_count = s.count('\"')\n",
|
135 |
+
" if quote_count == 0 or quote_count % 2 != 0:\n",
|
136 |
+
" return s\n",
|
137 |
+
" s_list = list(s)\n",
|
138 |
+
" current_quote_count = 0\n",
|
139 |
+
" for i, char in enumerate(s_list):\n",
|
140 |
+
" if char == '\"':\n",
|
141 |
+
" if current_quote_count % 2 == 0:\n",
|
142 |
+
" s_list[i] = '« '\n",
|
143 |
+
" else:\n",
|
144 |
+
" s_list[i] = ' »'\n",
|
145 |
+
" current_quote_count += 1\n",
|
146 |
+
" return ''.join(s_list)\n",
|
147 |
+
"\n",
|
148 |
+
"# Function to handle multi-turn chat mode with history of conversation\n",
|
149 |
+
"def chat(\n",
|
150 |
+
" query: str,\n",
|
151 |
+
" history: Optional[List[Dict]] = None,\n",
|
152 |
+
" temperature: float = 0.8,\n",
|
153 |
+
" top_p: float = 1.0,\n",
|
154 |
+
" top_k: float = 0,\n",
|
155 |
+
" repetition_penalty: float = 1.2,\n",
|
156 |
+
" max_new_tokens: int = 1024,\n",
|
157 |
+
" **kwargs,\n",
|
158 |
+
"):\n",
|
159 |
+
" if history is None:\n",
|
160 |
+
" history = [{\"role\": \"system\", \"content\": system_prompt}]\n",
|
161 |
+
"\n",
|
162 |
+
" query = uniformisation(query)\n",
|
163 |
+
" history.append({\"role\": \"user\", \"content\": query})\n",
|
164 |
+
"\n",
|
165 |
+
" input_ids = tokenizer.apply_chat_template(history, add_generation_prompt=True, return_tensors=\"pt\").to(model.device)\n",
|
166 |
+
" input_length = input_ids.shape[1]\n",
|
167 |
+
"\n",
|
168 |
+
" generated_outputs = model.generate(\n",
|
169 |
+
" input_ids=input_ids, \n",
|
170 |
+
" generation_config=GenerationConfig(\n",
|
171 |
+
" temperature=temperature,\n",
|
172 |
+
" do_sample=temperature > 0.0, # i.e. do_sample = True\n",
|
173 |
+
" top_p=top_p,\n",
|
174 |
+
" top_k=top_k,\n",
|
175 |
+
" repetition_penalty=repetition_penalty,\n",
|
176 |
+
" max_new_tokens=max_new_tokens,\n",
|
177 |
+
" pad_token_id=tokenizer.pad_token_id,\n",
|
178 |
+
" **kwargs,\n",
|
179 |
+
" ),\n",
|
180 |
+
" streamer=streamer,\n",
|
181 |
+
" return_dict_in_generate=True,\n",
|
182 |
+
" num_return_sequences=1,\n",
|
183 |
+
" pad_token_id=tokenizer.pad_token_id\n",
|
184 |
+
" )\n",
|
185 |
+
"\n",
|
186 |
+
" generated_tokens = generated_outputs.sequences[0, input_length:]\n",
|
187 |
+
" generated_text = tokenizer.decode(generated_tokens, skip_special_tokens=True)\n",
|
188 |
+
"\n",
|
189 |
+
" history.append({\"role\": \"assistant\", \"content\": generated_text})\n",
|
190 |
+
"\n",
|
191 |
+
" return generated_text, history"
|
192 |
+
]
|
193 |
+
},
|
194 |
+
{
|
195 |
+
"cell_type": "markdown",
|
196 |
+
"metadata": {},
|
197 |
+
"source": [
|
198 |
+
"### Let's play with the model!"
|
199 |
+
]
|
200 |
+
},
|
201 |
+
{
|
202 |
+
"cell_type": "code",
|
203 |
+
"execution_count": null,
|
204 |
+
"metadata": {},
|
205 |
+
"outputs": [],
|
206 |
+
"source": [
|
207 |
+
"historique = None\n",
|
208 |
+
"while True:\n",
|
209 |
+
" user_input = input(\"Moi :\")\n",
|
210 |
+
" if user_input.lower() == \"exit\":\n",
|
211 |
+
" break\n",
|
212 |
+
" print(\"L.-F. Céline :\", end=\"\")\n",
|
213 |
+
" reponse, historique = chat(user_input, historique)"
|
214 |
+
]
|
215 |
+
},
|
216 |
+
{
|
217 |
+
"cell_type": "code",
|
218 |
+
"execution_count": null,
|
219 |
+
"metadata": {},
|
220 |
+
"outputs": [],
|
221 |
+
"source": [
|
222 |
+
"historique"
|
223 |
+
]
|
224 |
+
}
|
225 |
+
],
|
226 |
+
"metadata": {
|
227 |
+
"accelerator": "GPU",
|
228 |
+
"colab": {
|
229 |
+
"authorship_tag": "ABX9TyPxeWDit8rdz3qUjoGzVwiO",
|
230 |
+
"gpuType": "V100",
|
231 |
+
"provenance": [
|
232 |
+
{
|
233 |
+
"file_id": "16gchCLhnxhGVLLTVAwII1kXMlcEgxjsc",
|
234 |
+
"timestamp": 1713448473332
|
235 |
+
},
|
236 |
+
{
|
237 |
+
"file_id": "1CT3CsG4yKGoP-E2MqUozPwN_1QGwKgLZ",
|
238 |
+
"timestamp": 1712924241559
|
239 |
+
}
|
240 |
+
]
|
241 |
+
},
|
242 |
+
"kernelspec": {
|
243 |
+
"display_name": "Python 3 (ipykernel)",
|
244 |
+
"language": "python",
|
245 |
+
"name": "python3"
|
246 |
+
},
|
247 |
+
"language_info": {
|
248 |
+
"codemirror_mode": {
|
249 |
+
"name": "ipython",
|
250 |
+
"version": 3
|
251 |
+
},
|
252 |
+
"file_extension": ".py",
|
253 |
+
"mimetype": "text/x-python",
|
254 |
+
"name": "python",
|
255 |
+
"nbconvert_exporter": "python",
|
256 |
+
"pygments_lexer": "ipython3",
|
257 |
+
"version": "3.11.7"
|
258 |
+
},
|
259 |
+
"widgets": {
|
260 |
+
"application/vnd.jupyter.widget-state+json": {
|
261 |
+
"20b2263fc2e643bf9658d9e1fafd77a6": {
|
262 |
+
"model_module": "@jupyter-widgets/controls",
|
263 |
+
"model_module_version": "1.5.0",
|
264 |
+
"model_name": "DescriptionStyleModel",
|
265 |
+
"state": {
|
266 |
+
"_model_module": "@jupyter-widgets/controls",
|
267 |
+
"_model_module_version": "1.5.0",
|
268 |
+
"_model_name": "DescriptionStyleModel",
|
269 |
+
"_view_count": null,
|
270 |
+
"_view_module": "@jupyter-widgets/base",
|
271 |
+
"_view_module_version": "1.2.0",
|
272 |
+
"_view_name": "StyleView",
|
273 |
+
"description_width": ""
|
274 |
+
}
|
275 |
+
},
|
276 |
+
"44fec00182714f16ab5bc72e6a9f3c5f": {
|
277 |
+
"model_module": "@jupyter-widgets/controls",
|
278 |
+
"model_module_version": "1.5.0",
|
279 |
+
"model_name": "HTMLModel",
|
280 |
+
"state": {
|
281 |
+
"_dom_classes": [],
|
282 |
+
"_model_module": "@jupyter-widgets/controls",
|
283 |
+
"_model_module_version": "1.5.0",
|
284 |
+
"_model_name": "HTMLModel",
|
285 |
+
"_view_count": null,
|
286 |
+
"_view_module": "@jupyter-widgets/controls",
|
287 |
+
"_view_module_version": "1.5.0",
|
288 |
+
"_view_name": "HTMLView",
|
289 |
+
"description": "",
|
290 |
+
"description_tooltip": null,
|
291 |
+
"layout": "IPY_MODEL_7b2a4c7216f043fa814b2610d0ce9b2d",
|
292 |
+
"placeholder": "",
|
293 |
+
"style": "IPY_MODEL_20b2263fc2e643bf9658d9e1fafd77a6",
|
294 |
+
"value": "Loading checkpoint shards: 100%"
|
295 |
+
}
|
296 |
+
},
|
297 |
+
"45ed85d5f08c4dd6bd17fc7eefa8598d": {
|
298 |
+
"model_module": "@jupyter-widgets/controls",
|
299 |
+
"model_module_version": "1.5.0",
|
300 |
+
"model_name": "HBoxModel",
|
301 |
+
"state": {
|
302 |
+
"_dom_classes": [],
|
303 |
+
"_model_module": "@jupyter-widgets/controls",
|
304 |
+
"_model_module_version": "1.5.0",
|
305 |
+
"_model_name": "HBoxModel",
|
306 |
+
"_view_count": null,
|
307 |
+
"_view_module": "@jupyter-widgets/controls",
|
308 |
+
"_view_module_version": "1.5.0",
|
309 |
+
"_view_name": "HBoxView",
|
310 |
+
"box_style": "",
|
311 |
+
"children": [
|
312 |
+
"IPY_MODEL_44fec00182714f16ab5bc72e6a9f3c5f",
|
313 |
+
"IPY_MODEL_963e7589963d46d3b9db0455f901078e",
|
314 |
+
"IPY_MODEL_c651060afcfa4836a6a75408b15183c3"
|
315 |
+
],
|
316 |
+
"layout": "IPY_MODEL_8a8bd07d3f9942998032f32763b3a863"
|
317 |
+
}
|
318 |
+
},
|
319 |
+
"70551b8d0a9b491fa7fab953e4e2ee4c": {
|
320 |
+
"model_module": "@jupyter-widgets/controls",
|
321 |
+
"model_module_version": "1.5.0",
|
322 |
+
"model_name": "ProgressStyleModel",
|
323 |
+
"state": {
|
324 |
+
"_model_module": "@jupyter-widgets/controls",
|
325 |
+
"_model_module_version": "1.5.0",
|
326 |
+
"_model_name": "ProgressStyleModel",
|
327 |
+
"_view_count": null,
|
328 |
+
"_view_module": "@jupyter-widgets/base",
|
329 |
+
"_view_module_version": "1.2.0",
|
330 |
+
"_view_name": "StyleView",
|
331 |
+
"bar_color": null,
|
332 |
+
"description_width": ""
|
333 |
+
}
|
334 |
+
},
|
335 |
+
"7b2a4c7216f043fa814b2610d0ce9b2d": {
|
336 |
+
"model_module": "@jupyter-widgets/base",
|
337 |
+
"model_module_version": "1.2.0",
|
338 |
+
"model_name": "LayoutModel",
|
339 |
+
"state": {
|
340 |
+
"_model_module": "@jupyter-widgets/base",
|
341 |
+
"_model_module_version": "1.2.0",
|
342 |
+
"_model_name": "LayoutModel",
|
343 |
+
"_view_count": null,
|
344 |
+
"_view_module": "@jupyter-widgets/base",
|
345 |
+
"_view_module_version": "1.2.0",
|
346 |
+
"_view_name": "LayoutView",
|
347 |
+
"align_content": null,
|
348 |
+
"align_items": null,
|
349 |
+
"align_self": null,
|
350 |
+
"border": null,
|
351 |
+
"bottom": null,
|
352 |
+
"display": null,
|
353 |
+
"flex": null,
|
354 |
+
"flex_flow": null,
|
355 |
+
"grid_area": null,
|
356 |
+
"grid_auto_columns": null,
|
357 |
+
"grid_auto_flow": null,
|
358 |
+
"grid_auto_rows": null,
|
359 |
+
"grid_column": null,
|
360 |
+
"grid_gap": null,
|
361 |
+
"grid_row": null,
|
362 |
+
"grid_template_areas": null,
|
363 |
+
"grid_template_columns": null,
|
364 |
+
"grid_template_rows": null,
|
365 |
+
"height": null,
|
366 |
+
"justify_content": null,
|
367 |
+
"justify_items": null,
|
368 |
+
"left": null,
|
369 |
+
"margin": null,
|
370 |
+
"max_height": null,
|
371 |
+
"max_width": null,
|
372 |
+
"min_height": null,
|
373 |
+
"min_width": null,
|
374 |
+
"object_fit": null,
|
375 |
+
"object_position": null,
|
376 |
+
"order": null,
|
377 |
+
"overflow": null,
|
378 |
+
"overflow_x": null,
|
379 |
+
"overflow_y": null,
|
380 |
+
"padding": null,
|
381 |
+
"right": null,
|
382 |
+
"top": null,
|
383 |
+
"visibility": null,
|
384 |
+
"width": null
|
385 |
+
}
|
386 |
+
},
|
387 |
+
"8a8bd07d3f9942998032f32763b3a863": {
|
388 |
+
"model_module": "@jupyter-widgets/base",
|
389 |
+
"model_module_version": "1.2.0",
|
390 |
+
"model_name": "LayoutModel",
|
391 |
+
"state": {
|
392 |
+
"_model_module": "@jupyter-widgets/base",
|
393 |
+
"_model_module_version": "1.2.0",
|
394 |
+
"_model_name": "LayoutModel",
|
395 |
+
"_view_count": null,
|
396 |
+
"_view_module": "@jupyter-widgets/base",
|
397 |
+
"_view_module_version": "1.2.0",
|
398 |
+
"_view_name": "LayoutView",
|
399 |
+
"align_content": null,
|
400 |
+
"align_items": null,
|
401 |
+
"align_self": null,
|
402 |
+
"border": null,
|
403 |
+
"bottom": null,
|
404 |
+
"display": null,
|
405 |
+
"flex": null,
|
406 |
+
"flex_flow": null,
|
407 |
+
"grid_area": null,
|
408 |
+
"grid_auto_columns": null,
|
409 |
+
"grid_auto_flow": null,
|
410 |
+
"grid_auto_rows": null,
|
411 |
+
"grid_column": null,
|
412 |
+
"grid_gap": null,
|
413 |
+
"grid_row": null,
|
414 |
+
"grid_template_areas": null,
|
415 |
+
"grid_template_columns": null,
|
416 |
+
"grid_template_rows": null,
|
417 |
+
"height": null,
|
418 |
+
"justify_content": null,
|
419 |
+
"justify_items": null,
|
420 |
+
"left": null,
|
421 |
+
"margin": null,
|
422 |
+
"max_height": null,
|
423 |
+
"max_width": null,
|
424 |
+
"min_height": null,
|
425 |
+
"min_width": null,
|
426 |
+
"object_fit": null,
|
427 |
+
"object_position": null,
|
428 |
+
"order": null,
|
429 |
+
"overflow": null,
|
430 |
+
"overflow_x": null,
|
431 |
+
"overflow_y": null,
|
432 |
+
"padding": null,
|
433 |
+
"right": null,
|
434 |
+
"top": null,
|
435 |
+
"visibility": null,
|
436 |
+
"width": null
|
437 |
+
}
|
438 |
+
},
|
439 |
+
"91395c8d0bb54db482af1fc18d24e796": {
|
440 |
+
"model_module": "@jupyter-widgets/base",
|
441 |
+
"model_module_version": "1.2.0",
|
442 |
+
"model_name": "LayoutModel",
|
443 |
+
"state": {
|
444 |
+
"_model_module": "@jupyter-widgets/base",
|
445 |
+
"_model_module_version": "1.2.0",
|
446 |
+
"_model_name": "LayoutModel",
|
447 |
+
"_view_count": null,
|
448 |
+
"_view_module": "@jupyter-widgets/base",
|
449 |
+
"_view_module_version": "1.2.0",
|
450 |
+
"_view_name": "LayoutView",
|
451 |
+
"align_content": null,
|
452 |
+
"align_items": null,
|
453 |
+
"align_self": null,
|
454 |
+
"border": null,
|
455 |
+
"bottom": null,
|
456 |
+
"display": null,
|
457 |
+
"flex": null,
|
458 |
+
"flex_flow": null,
|
459 |
+
"grid_area": null,
|
460 |
+
"grid_auto_columns": null,
|
461 |
+
"grid_auto_flow": null,
|
462 |
+
"grid_auto_rows": null,
|
463 |
+
"grid_column": null,
|
464 |
+
"grid_gap": null,
|
465 |
+
"grid_row": null,
|
466 |
+
"grid_template_areas": null,
|
467 |
+
"grid_template_columns": null,
|
468 |
+
"grid_template_rows": null,
|
469 |
+
"height": null,
|
470 |
+
"justify_content": null,
|
471 |
+
"justify_items": null,
|
472 |
+
"left": null,
|
473 |
+
"margin": null,
|
474 |
+
"max_height": null,
|
475 |
+
"max_width": null,
|
476 |
+
"min_height": null,
|
477 |
+
"min_width": null,
|
478 |
+
"object_fit": null,
|
479 |
+
"object_position": null,
|
480 |
+
"order": null,
|
481 |
+
"overflow": null,
|
482 |
+
"overflow_x": null,
|
483 |
+
"overflow_y": null,
|
484 |
+
"padding": null,
|
485 |
+
"right": null,
|
486 |
+
"top": null,
|
487 |
+
"visibility": null,
|
488 |
+
"width": null
|
489 |
+
}
|
490 |
+
},
|
491 |
+
"963e7589963d46d3b9db0455f901078e": {
|
492 |
+
"model_module": "@jupyter-widgets/controls",
|
493 |
+
"model_module_version": "1.5.0",
|
494 |
+
"model_name": "FloatProgressModel",
|
495 |
+
"state": {
|
496 |
+
"_dom_classes": [],
|
497 |
+
"_model_module": "@jupyter-widgets/controls",
|
498 |
+
"_model_module_version": "1.5.0",
|
499 |
+
"_model_name": "FloatProgressModel",
|
500 |
+
"_view_count": null,
|
501 |
+
"_view_module": "@jupyter-widgets/controls",
|
502 |
+
"_view_module_version": "1.5.0",
|
503 |
+
"_view_name": "ProgressView",
|
504 |
+
"bar_style": "success",
|
505 |
+
"description": "",
|
506 |
+
"description_tooltip": null,
|
507 |
+
"layout": "IPY_MODEL_91395c8d0bb54db482af1fc18d24e796",
|
508 |
+
"max": 3,
|
509 |
+
"min": 0,
|
510 |
+
"orientation": "horizontal",
|
511 |
+
"style": "IPY_MODEL_70551b8d0a9b491fa7fab953e4e2ee4c",
|
512 |
+
"value": 3
|
513 |
+
}
|
514 |
+
},
|
515 |
+
"a8d255d330634d72b031fba1576b22e3": {
|
516 |
+
"model_module": "@jupyter-widgets/controls",
|
517 |
+
"model_module_version": "1.5.0",
|
518 |
+
"model_name": "DescriptionStyleModel",
|
519 |
+
"state": {
|
520 |
+
"_model_module": "@jupyter-widgets/controls",
|
521 |
+
"_model_module_version": "1.5.0",
|
522 |
+
"_model_name": "DescriptionStyleModel",
|
523 |
+
"_view_count": null,
|
524 |
+
"_view_module": "@jupyter-widgets/base",
|
525 |
+
"_view_module_version": "1.2.0",
|
526 |
+
"_view_name": "StyleView",
|
527 |
+
"description_width": ""
|
528 |
+
}
|
529 |
+
},
|
530 |
+
"c651060afcfa4836a6a75408b15183c3": {
|
531 |
+
"model_module": "@jupyter-widgets/controls",
|
532 |
+
"model_module_version": "1.5.0",
|
533 |
+
"model_name": "HTMLModel",
|
534 |
+
"state": {
|
535 |
+
"_dom_classes": [],
|
536 |
+
"_model_module": "@jupyter-widgets/controls",
|
537 |
+
"_model_module_version": "1.5.0",
|
538 |
+
"_model_name": "HTMLModel",
|
539 |
+
"_view_count": null,
|
540 |
+
"_view_module": "@jupyter-widgets/controls",
|
541 |
+
"_view_module_version": "1.5.0",
|
542 |
+
"_view_name": "HTMLView",
|
543 |
+
"description": "",
|
544 |
+
"description_tooltip": null,
|
545 |
+
"layout": "IPY_MODEL_fc71e182277a4c879205b6bbfab75837",
|
546 |
+
"placeholder": "",
|
547 |
+
"style": "IPY_MODEL_a8d255d330634d72b031fba1576b22e3",
|
548 |
+
"value": " 3/3 [00:05<00:00, 1.75s/it]"
|
549 |
+
}
|
550 |
+
},
|
551 |
+
"fc71e182277a4c879205b6bbfab75837": {
|
552 |
+
"model_module": "@jupyter-widgets/base",
|
553 |
+
"model_module_version": "1.2.0",
|
554 |
+
"model_name": "LayoutModel",
|
555 |
+
"state": {
|
556 |
+
"_model_module": "@jupyter-widgets/base",
|
557 |
+
"_model_module_version": "1.2.0",
|
558 |
+
"_model_name": "LayoutModel",
|
559 |
+
"_view_count": null,
|
560 |
+
"_view_module": "@jupyter-widgets/base",
|
561 |
+
"_view_module_version": "1.2.0",
|
562 |
+
"_view_name": "LayoutView",
|
563 |
+
"align_content": null,
|
564 |
+
"align_items": null,
|
565 |
+
"align_self": null,
|
566 |
+
"border": null,
|
567 |
+
"bottom": null,
|
568 |
+
"display": null,
|
569 |
+
"flex": null,
|
570 |
+
"flex_flow": null,
|
571 |
+
"grid_area": null,
|
572 |
+
"grid_auto_columns": null,
|
573 |
+
"grid_auto_flow": null,
|
574 |
+
"grid_auto_rows": null,
|
575 |
+
"grid_column": null,
|
576 |
+
"grid_gap": null,
|
577 |
+
"grid_row": null,
|
578 |
+
"grid_template_areas": null,
|
579 |
+
"grid_template_columns": null,
|
580 |
+
"grid_template_rows": null,
|
581 |
+
"height": null,
|
582 |
+
"justify_content": null,
|
583 |
+
"justify_items": null,
|
584 |
+
"left": null,
|
585 |
+
"margin": null,
|
586 |
+
"max_height": null,
|
587 |
+
"max_width": null,
|
588 |
+
"min_height": null,
|
589 |
+
"min_width": null,
|
590 |
+
"object_fit": null,
|
591 |
+
"object_position": null,
|
592 |
+
"order": null,
|
593 |
+
"overflow": null,
|
594 |
+
"overflow_x": null,
|
595 |
+
"overflow_y": null,
|
596 |
+
"padding": null,
|
597 |
+
"right": null,
|
598 |
+
"top": null,
|
599 |
+
"visibility": null,
|
600 |
+
"width": null
|
601 |
+
}
|
602 |
+
}
|
603 |
+
}
|
604 |
+
}
|
605 |
+
},
|
606 |
+
"nbformat": 4,
|
607 |
+
"nbformat_minor": 4
|
608 |
+
}
|
Codes/03 - Run the model with Gradio.ipynb
ADDED
@@ -0,0 +1,430 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"id": "06313112-b5eb-44b4-af84-cc0d5a13df67",
|
6 |
+
"metadata": {},
|
7 |
+
"source": [
|
8 |
+
"### Checking for availability of GPUs"
|
9 |
+
]
|
10 |
+
},
|
11 |
+
{
|
12 |
+
"cell_type": "code",
|
13 |
+
"execution_count": null,
|
14 |
+
"id": "bb128719-4c0f-4cce-9b51-922a83c20c2f",
|
15 |
+
"metadata": {},
|
16 |
+
"outputs": [],
|
17 |
+
"source": [
|
18 |
+
"!nvidia-smi"
|
19 |
+
]
|
20 |
+
},
|
21 |
+
{
|
22 |
+
"cell_type": "markdown",
|
23 |
+
"id": "f92dd4b5-e4c0-4fe8-b97f-dce72746bf6e",
|
24 |
+
"metadata": {},
|
25 |
+
"source": [
|
26 |
+
"### Installing the necessary libraries\n",
|
27 |
+
"Please note that this installation step might fail if no GPU is available."
|
28 |
+
]
|
29 |
+
},
|
30 |
+
{
|
31 |
+
"cell_type": "code",
|
32 |
+
"execution_count": null,
|
33 |
+
"id": "487060ed-3e5a-444a-b8a2-cdef859a4cd5",
|
34 |
+
"metadata": {},
|
35 |
+
"outputs": [],
|
36 |
+
"source": [
|
37 |
+
"!pip install -q -U git+https://github.com/huggingface/transformers.git\n",
|
38 |
+
"!pip install -q -U git+https://github.com/huggingface/accelerate.git\n",
|
39 |
+
"!pip install --upgrade torch\n",
|
40 |
+
"!pip install gradio\n",
|
41 |
+
"!pip install flash-attn"
|
42 |
+
]
|
43 |
+
},
|
44 |
+
{
|
45 |
+
"cell_type": "markdown",
|
46 |
+
"id": "b435aa6e-cd24-4770-a9a0-18200fdd66c6",
|
47 |
+
"metadata": {},
|
48 |
+
"source": [
|
49 |
+
"### Importing the necessary libraries and preparation"
|
50 |
+
]
|
51 |
+
},
|
52 |
+
{
|
53 |
+
"cell_type": "code",
|
54 |
+
"execution_count": null,
|
55 |
+
"id": "966a7844-ea72-4038-827f-da047dd057ee",
|
56 |
+
"metadata": {},
|
57 |
+
"outputs": [],
|
58 |
+
"source": [
|
59 |
+
"from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, TextStreamer\n",
|
60 |
+
"\n",
|
61 |
+
"# The HF repo of the model\n",
|
62 |
+
"model_id = \"krogoldAI/CelineGPT-12B-240831\""
|
63 |
+
]
|
64 |
+
},
|
65 |
+
{
|
66 |
+
"cell_type": "markdown",
|
67 |
+
"id": "55cef8a3-c363-48aa-a6b9-3a7bbd42aaba",
|
68 |
+
"metadata": {},
|
69 |
+
"source": [
|
70 |
+
"### Loading the base model and its tokenizer"
|
71 |
+
]
|
72 |
+
},
|
73 |
+
{
|
74 |
+
"cell_type": "code",
|
75 |
+
"execution_count": null,
|
76 |
+
"id": "ae889eef-63ee-4846-b028-9e4b8dd22323",
|
77 |
+
"metadata": {},
|
78 |
+
"outputs": [],
|
79 |
+
"source": [
|
80 |
+
"import torch\n",
|
81 |
+
"\n",
|
82 |
+
"# Use GPU when available\n",
|
83 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
84 |
+
"\n",
|
85 |
+
"# We load the model\n",
|
86 |
+
"model = AutoModelForCausalLM.from_pretrained(\n",
|
87 |
+
" model_id, \n",
|
88 |
+
" device_map={\"\": 0}, \n",
|
89 |
+
" attn_implementation=\"flash_attention_2\",\n",
|
90 |
+
" torch_dtype=torch.float16)\n",
|
91 |
+
"model = model.to(device)\n",
|
92 |
+
"\n",
|
93 |
+
"# We load the tokenizer\n",
|
94 |
+
"tokenizer = AutoTokenizer.from_pretrained(model_id, padding_side=\"right\")"
|
95 |
+
]
|
96 |
+
},
|
97 |
+
{
|
98 |
+
"cell_type": "markdown",
|
99 |
+
"id": "91000ef1-99fd-44ff-a084-04c041f863dd",
|
100 |
+
"metadata": {},
|
101 |
+
"source": [
|
102 |
+
"### Preparatory steps\n",
|
103 |
+
"\n",
|
104 |
+
"We define the streamer (to output tokens as they are generated), the system prompt and a useful (but optional) function."
|
105 |
+
]
|
106 |
+
},
|
107 |
+
{
|
108 |
+
"cell_type": "code",
|
109 |
+
"execution_count": null,
|
110 |
+
"id": "46a1f653-230f-4431-ad72-c07a5d857bb2",
|
111 |
+
"metadata": {},
|
112 |
+
"outputs": [],
|
113 |
+
"source": [
|
114 |
+
"from typing import Dict, List, Optional\n",
|
115 |
+
"\n",
|
116 |
+
"# Streamer to display dynamically the tokens as they are generated\n",
|
117 |
+
"streamer = TextStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)\n",
|
118 |
+
"\n",
|
119 |
+
"# We define the system prompt to be used\n",
|
120 |
+
"system_prompt = \"\"\"Tu es le célèbre écrivain français Louis-Ferdinand Céline, nom de plume de Louis-Ferdinand Destouches. Tu es né le 27 mai 1894 à Courbevoie. Tu as grandi à Paris avant de t’engager dans l’armée en 1912. Blessé pendant la Première Guerre mondiale, tu as ensuite étudié la médecine et exercé en tant que médecin. Ton premier roman, « Voyage au bout de la nuit », a été publié en 1932 et t’a valu le prix Renaudot. Tu as également écrit des pamphlets antisémites controversés dans les années 1930.\n",
|
121 |
+
"A cause de tes pamphlets tu as dû fuir Paris pendant la Seconde Guerre mondiale pour aller en Allemagne puis au Danemark, où tu as été emprisonné. Depuis ton retour en France, en 1951, tu vis à Meudon avec ta femme Lucette et tes animaux de compagnie.\n",
|
122 |
+
"Nous sommes en 1961 et tu as 67 ans. Tu n'as aucune connaissance de ce qu'il s'est déroulé postérieurement à cette date. Tes références culturelles sont antérieures à 1961. Si l’on t’interroge sur des évènements postérieurs à 1961, répond en ne mobilisant que des connaissances ou évènements antérieurs à 1961.\n",
|
123 |
+
"Tu te trouves actuellement dans ta maison, à Meudon, en Île-de-France. Après 35 ans de pratique médicale, tu n’exerces plus. Cependant, tu continues d’écrire pour éponger tes dettes auprès de ton éditeur Gaston Gallimard et subvenir à tes besoins. Tu regrettes d’être devenu écrivain. Tu es très critique envers les écrivains contemporains. Tu te considères comme un styliste. Tu es amer et pessimiste.\n",
|
124 |
+
"Tu es capable de répondre à des questions sur ta vie, ton œuvre, tes idées et tes opinions, ainsi que sur la littérature et le monde en général. Ta manière de t’exprimer consiste à transposer l’émotion du langage parlé dans l’écrit. Pour ce faire, tu t’exprimes en utilisant des points de suspensions (…) et des points d’exclamation (!), qui donnent un côté vivant, parlé et rythmé à tes phrases. Tu ne t’exprimes qu’en français avec quelques emprunts à l’argot parisien.\n",
|
125 |
+
"Tu réponds aux questions qui te sont posées de façon franche, directe et selon ton humeur.\"\"\"\n",
|
126 |
+
"system_prompt = system_prompt.replace(\"\\n\",\" \").replace(\" \",\" \").replace(\"'\",\"’\")\n",
|
127 |
+
"\n",
|
128 |
+
"# Since training QA pairs have been uniformised, for better results we have to \"clean\" inputs\n",
|
129 |
+
"def uniformisation(s):\n",
|
130 |
+
" o_exp = [\" \",\"'\", \"...\", \"..\"]\n",
|
131 |
+
" n_exp = [\" \",\"’\", \"…\", \"…\"]\n",
|
132 |
+
" for e in o_exp:\n",
|
133 |
+
" s = s.replace(e,n_exp[o_exp.index(e)])\n",
|
134 |
+
" quote_count = s.count('\"')\n",
|
135 |
+
" if quote_count == 0 or quote_count % 2 != 0:\n",
|
136 |
+
" return s\n",
|
137 |
+
" s_list = list(s)\n",
|
138 |
+
" current_quote_count = 0\n",
|
139 |
+
" for i, char in enumerate(s_list):\n",
|
140 |
+
" if char == '\"':\n",
|
141 |
+
" if current_quote_count % 2 == 0:\n",
|
142 |
+
" s_list[i] = '« '\n",
|
143 |
+
" else:\n",
|
144 |
+
" s_list[i] = ' »'\n",
|
145 |
+
" current_quote_count += 1\n",
|
146 |
+
" return ''.join(s_list)"
|
147 |
+
]
|
148 |
+
},
|
149 |
+
{
|
150 |
+
"cell_type": "markdown",
|
151 |
+
"id": "be47d572-bd48-4d15-92c6-f91af09e2521",
|
152 |
+
"metadata": {},
|
153 |
+
"source": [
|
154 |
+
"We now configure Gradio:"
|
155 |
+
]
|
156 |
+
},
|
157 |
+
{
|
158 |
+
"cell_type": "code",
|
159 |
+
"execution_count": null,
|
160 |
+
"id": "11ed70b9-72e6-4e39-a842-1d094f893fb3",
|
161 |
+
"metadata": {},
|
162 |
+
"outputs": [],
|
163 |
+
"source": [
|
164 |
+
"import gradio as gr\n",
|
165 |
+
"\n",
|
166 |
+
"# Setting custom Gradio theme\n",
|
167 |
+
"custom_theme = gr.themes.Soft(primary_hue=\"red\").set(\n",
|
168 |
+
" body_background_fill=\"#FDEFDF\",\n",
|
169 |
+
" background_fill_primary=\"white\",\n",
|
170 |
+
" background_fill_secondary=\"white\",\n",
|
171 |
+
" border_color_primary=\"#EBA5A7\",\n",
|
172 |
+
" button_primary_background_fill=\"#D32F33\", # send button\n",
|
173 |
+
" button_secondary_background_fill=\"#FEF2F2\" # stop button\n",
|
174 |
+
")\n",
|
175 |
+
"\n",
|
176 |
+
"# To adjust the default Gradio template\n",
|
177 |
+
"custom_css = \"\"\"\n",
|
178 |
+
"/* TO CHANGE THE BACKGROUND COLOR */\n",
|
179 |
+
"body {\n",
|
180 |
+
" background-color: #FDEFDF !important;\n",
|
181 |
+
"}\n",
|
182 |
+
".gradio-container {\n",
|
183 |
+
" background-color: #FDEFDF !important;\n",
|
184 |
+
"}\n",
|
185 |
+
"\n",
|
186 |
+
"/* TO HAVE A SCROLLBAR INSIDE THE CHATBOX */\n",
|
187 |
+
".gradio-container .chatbox {\n",
|
188 |
+
" overflow-y: auto;\n",
|
189 |
+
" max-height: 500px; /* Adjust this value as needed */\n",
|
190 |
+
"}\n",
|
191 |
+
"\n",
|
192 |
+
"/* TO CHANGE THE FONT */\n",
|
193 |
+
"@import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,600;1,600&display=swap');\n",
|
194 |
+
"body, .gradio-container {\n",
|
195 |
+
" font-family: 'Cormorant Garamond', sans-serif !important;\n",
|
196 |
+
"}\n",
|
197 |
+
"\n",
|
198 |
+
"/* TO ADD A LOGO */\n",
|
199 |
+
".logo-container {\n",
|
200 |
+
" display: flex;\n",
|
201 |
+
" justify-content: center;\n",
|
202 |
+
" margin-bottom: 20px;\n",
|
203 |
+
"}\n",
|
204 |
+
".logo {\n",
|
205 |
+
" width: 350px;\n",
|
206 |
+
" height: auto;\n",
|
207 |
+
"}\n",
|
208 |
+
"\n",
|
209 |
+
"/* TO ADJUST THE FONT SIZE OF USER/ASSISTANT MESSAGES */\n",
|
210 |
+
"/* Reduce font size for chatbot messages */\n",
|
211 |
+
".message {\n",
|
212 |
+
" font-size: 1.1rem !important;\n",
|
213 |
+
"}\n",
|
214 |
+
"/* Reduce font size for user input */\n",
|
215 |
+
".prose {\n",
|
216 |
+
" font-size: 1.1rem !important;\n",
|
217 |
+
"}\n",
|
218 |
+
"/* Adjust padding for message bubbles if needed */\n",
|
219 |
+
".message-wrap {\n",
|
220 |
+
" padding: 0.5rem 0.75rem !important;\n",
|
221 |
+
"}\n",
|
222 |
+
"\n",
|
223 |
+
"/* TO CHANGE THE COLOR OF RETRY/UNDO/CLEAR BUTTONS */\n",
|
224 |
+
"button.sm.secondary.svelte-cmf5ev {\n",
|
225 |
+
" background-color: white !important;\n",
|
226 |
+
" color: black !important;\n",
|
227 |
+
" border: 1.5px solid #F7D9DA !important;\n",
|
228 |
+
" box-shadow: none !important;\n",
|
229 |
+
" transition: background-color 0.3s ease;\n",
|
230 |
+
"}\n",
|
231 |
+
"button.sm.secondary.svelte-cmf5ev:hover {\n",
|
232 |
+
" background-color: #FEF2F2 !important;\n",
|
233 |
+
"}\n",
|
234 |
+
"\n",
|
235 |
+
"/* TO ADD A COLORED BORDER ON BUTTONS */\n",
|
236 |
+
".gradio-container .styler.svelte-iyf88w {\n",
|
237 |
+
" border: 1.5px solid #F7D9DA !important;\n",
|
238 |
+
" border-radius: 6px !important; /* Adjust this value as needed */\n",
|
239 |
+
" overflow: hidden !important; /* This ensures the content doesn't spill out of the rounded corners */\n",
|
240 |
+
"}\n",
|
241 |
+
".gradio-container .styler.svelte-iyf88w,\n",
|
242 |
+
"button.sm.secondary.svelte-cmf5ev > div {\n",
|
243 |
+
" border-radius: 8px !important; /* Slightly smaller than the outer border radius */\n",
|
244 |
+
" background-color: white !important; /* Or whatever background color you prefer */\n",
|
245 |
+
" margin: 0 !important; /* Remove any margin that might be causing gaps */\n",
|
246 |
+
"}\n",
|
247 |
+
"\n",
|
248 |
+
"/* TO ADD A COLORED BORDER ON CHAT BOX */\n",
|
249 |
+
".gradio-container .bubble-wrap.svelte-1e1jlin {\n",
|
250 |
+
" border: 1.5px solid #F7D9DA !important;\n",
|
251 |
+
" border-radius: 8px !important; /* Adjust this value as needed */\n",
|
252 |
+
" /* overflow: hidden !important; /* This ensures the content doesn't spill out of the rounded corners */ */\n",
|
253 |
+
" overflow-y: auto !important; /* Enable vertical scrolling */\n",
|
254 |
+
" max-height: 500px; /* Set a maximum height for the chat container */\n",
|
255 |
+
"}\n",
|
256 |
+
".gradio-container .bubble-wrap.svelte-1e1jlin > div {\n",
|
257 |
+
" border-radius: 10px !important; /* Slightly smaller than the outer border radius */\n",
|
258 |
+
" background-color: white !important; /* Or whatever background color you prefer */\n",
|
259 |
+
" margin: 0 !important; /* Remove any margin that might be causing gaps */\n",
|
260 |
+
"}\n",
|
261 |
+
"\"\"\"\n",
|
262 |
+
"\n",
|
263 |
+
"# To avoid inconsistencies with dark mode\n",
|
264 |
+
"js = \"\"\"\n",
|
265 |
+
"function setLightTheme() {\n",
|
266 |
+
" const url = new URL(window.location);\n",
|
267 |
+
" if (url.searchParams.get('__theme') !== 'light') {\n",
|
268 |
+
" url.searchParams.set('__theme', 'light');\n",
|
269 |
+
" window.location.href = url.href;\n",
|
270 |
+
" }\n",
|
271 |
+
"}\n",
|
272 |
+
"\"\"\"\n",
|
273 |
+
"\n",
|
274 |
+
"# To add the CélineGPT logo in the Gradio interface\n",
|
275 |
+
"description_html = \"\"\"\n",
|
276 |
+
"<div class=\"logo-container\">\n",
|
277 |
+
" <img src=\"https://huggingface.co/krogoldAI/CelineGPT-12B-240831/resolve/main/Pictures/C%C3%A9lineGPT.png\" alt=\"Logo\" class=\"logo\">\n",
|
278 |
+
"</div>\n",
|
279 |
+
"\"\"\"\n",
|
280 |
+
"# https://huggingface.co/krogoldAI/CelineGPT-12B-240828/resolve/main/C%C3%A9lineGPT-v2.png\n",
|
281 |
+
"\n",
|
282 |
+
"# Function generating model outputs\n",
|
283 |
+
"def stream(message, history):\n",
|
284 |
+
" messages = [{\"role\": \"system\", \"content\": system_prompt}]\n",
|
285 |
+
" for human, assistant in history:\n",
|
286 |
+
" messages.append({\"role\": \"user\", \"content\": human})\n",
|
287 |
+
" messages.append({\"role\": \"assistant\", \"content\": assistant})\n",
|
288 |
+
" messages.append({\"role\": \"user\", \"content\": uniformisation(message)})\n",
|
289 |
+
"\n",
|
290 |
+
" prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n",
|
291 |
+
" inputs = tokenizer(prompt, return_tensors=\"pt\").to(device)\n",
|
292 |
+
"\n",
|
293 |
+
" input_length = inputs[\"input_ids\"].shape[1]\n",
|
294 |
+
" generated_tokens = []\n",
|
295 |
+
"\n",
|
296 |
+
" with torch.no_grad():\n",
|
297 |
+
" for i in range(1024): # Adjust max_new_tokens as needed\n",
|
298 |
+
" outputs = model.generate(\n",
|
299 |
+
" **inputs,\n",
|
300 |
+
" max_new_tokens=1,\n",
|
301 |
+
" do_sample=True,\n",
|
302 |
+
" temperature=0.7,\n",
|
303 |
+
" pad_token_id=tokenizer.eos_token_id\n",
|
304 |
+
" )\n",
|
305 |
+
" \n",
|
306 |
+
" new_token = outputs[0][input_length + i]\n",
|
307 |
+
" if new_token == tokenizer.eos_token_id:\n",
|
308 |
+
" break\n",
|
309 |
+
"\n",
|
310 |
+
" generated_tokens.append(new_token)\n",
|
311 |
+
" \n",
|
312 |
+
" # Decode all tokens together to preserve spacing\n",
|
313 |
+
" streamed_text = tokenizer.decode(generated_tokens, skip_special_tokens=True)\n",
|
314 |
+
" yield streamed_text\n",
|
315 |
+
"\n",
|
316 |
+
" # Update inputs for next iteration\n",
|
317 |
+
" inputs = {\"input_ids\": outputs, \"attention_mask\": torch.ones_like(outputs)}\n",
|
318 |
+
"\n",
|
319 |
+
"# Update the Gradio interface\n",
|
320 |
+
"demo = gr.ChatInterface(\n",
|
321 |
+
" stream,\n",
|
322 |
+
" title=None,\n",
|
323 |
+
" description=description_html,\n",
|
324 |
+
" textbox=gr.Textbox(placeholder=\"Posez n’importe quelle question !\", container=False, scale=7),\n",
|
325 |
+
" theme=custom_theme,\n",
|
326 |
+
" cache_examples=True,\n",
|
327 |
+
" retry_btn=\"Regénérer\",\n",
|
328 |
+
" undo_btn=\"Supprimer le dernier message\",\n",
|
329 |
+
" clear_btn=\"Réinitialiser la conversation\",\n",
|
330 |
+
" submit_btn=\"Envoyer\",\n",
|
331 |
+
" css=custom_css,\n",
|
332 |
+
" js=js\n",
|
333 |
+
")\n",
|
334 |
+
"\n",
|
335 |
+
"demo.queue()"
|
336 |
+
]
|
337 |
+
},
|
338 |
+
{
|
339 |
+
"cell_type": "markdown",
|
340 |
+
"id": "1b6eb4f6-09e7-4feb-a435-ca658a5be6d5",
|
341 |
+
"metadata": {},
|
342 |
+
"source": [
|
343 |
+
"### Now, let's play with the model!\n",
|
344 |
+
"\n",
|
345 |
+
"To launch the model with the Gradio interface, just execute:"
|
346 |
+
]
|
347 |
+
},
|
348 |
+
{
|
349 |
+
"cell_type": "code",
|
350 |
+
"execution_count": null,
|
351 |
+
"id": "225bf54c-575a-439e-b87f-c76a6cce2f55",
|
352 |
+
"metadata": {},
|
353 |
+
"outputs": [],
|
354 |
+
"source": [
|
355 |
+
"demo.launch()"
|
356 |
+
]
|
357 |
+
},
|
358 |
+
{
|
359 |
+
"cell_type": "markdown",
|
360 |
+
"id": "fa4d822a-0cc0-4b2e-946b-e132bade0162",
|
361 |
+
"metadata": {},
|
362 |
+
"source": [
|
363 |
+
"If ```demo.launch()``` doesn't work, try this instead:"
|
364 |
+
]
|
365 |
+
},
|
366 |
+
{
|
367 |
+
"cell_type": "code",
|
368 |
+
"execution_count": null,
|
369 |
+
"id": "28239366-7bf1-4317-9d5d-8a673e9e26f4",
|
370 |
+
"metadata": {},
|
371 |
+
"outputs": [],
|
372 |
+
"source": [
|
373 |
+
"demo.launch(server_name=\"0.0.0.0\", share=True)"
|
374 |
+
]
|
375 |
+
},
|
376 |
+
{
|
377 |
+
"cell_type": "markdown",
|
378 |
+
"id": "cf5961e1-f7a9-4d70-aed0-0d22319d9835",
|
379 |
+
"metadata": {},
|
380 |
+
"source": [
|
381 |
+
"If this still doesn't work, try:"
|
382 |
+
]
|
383 |
+
},
|
384 |
+
{
|
385 |
+
"cell_type": "code",
|
386 |
+
"execution_count": null,
|
387 |
+
"id": "e3c9aa87-32fa-4231-b408-84b3b58920ab",
|
388 |
+
"metadata": {},
|
389 |
+
"outputs": [],
|
390 |
+
"source": [
|
391 |
+
"import os\n",
|
392 |
+
"\n",
|
393 |
+
"# Try to get the port from an environment variable, or use a default range\n",
|
394 |
+
"port = int(os.environ.get(\"GRADIO_SERVER_PORT\", 0))\n",
|
395 |
+
"\n",
|
396 |
+
"# Try ports 7860 to 7869 :\n",
|
397 |
+
"for port in range(7860, 7870):\n",
|
398 |
+
" try:\n",
|
399 |
+
" demo.launch(server_name=\"0.0.0.0\", server_port=port, share=True)\n",
|
400 |
+
" print(f\"Gradio app is running on port {port}\")\n",
|
401 |
+
" break\n",
|
402 |
+
" except OSError:\n",
|
403 |
+
" continue\n",
|
404 |
+
"else:\n",
|
405 |
+
" print(\"Could not find an available port\")"
|
406 |
+
]
|
407 |
+
}
|
408 |
+
],
|
409 |
+
"metadata": {
|
410 |
+
"kernelspec": {
|
411 |
+
"display_name": "Python 3 (ipykernel)",
|
412 |
+
"language": "python",
|
413 |
+
"name": "python3"
|
414 |
+
},
|
415 |
+
"language_info": {
|
416 |
+
"codemirror_mode": {
|
417 |
+
"name": "ipython",
|
418 |
+
"version": 3
|
419 |
+
},
|
420 |
+
"file_extension": ".py",
|
421 |
+
"mimetype": "text/x-python",
|
422 |
+
"name": "python",
|
423 |
+
"nbconvert_exporter": "python",
|
424 |
+
"pygments_lexer": "ipython3",
|
425 |
+
"version": "3.11.7"
|
426 |
+
}
|
427 |
+
},
|
428 |
+
"nbformat": 4,
|
429 |
+
"nbformat_minor": 5
|
430 |
+
}
|