objects76 commited on
Commit
0702527
1 Parent(s): 61aa42f

Upload phi-3.5-mini.ipynb with huggingface_hub

Browse files
Files changed (1) hide show
  1. phi-3.5-mini.ipynb +489 -0
phi-3.5-mini.ipynb ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "%reload_ext autoreload\n",
10
+ "%autoreload 2\n",
11
+ "if '__file__' not in globals():\n",
12
+ " __file__, __name__ = globals()['__vsc_ipynb_file__'], '__ipynb__'\n",
13
+ " import types, sys; sys.modules['__ipynb__'] = types.ModuleType('__ipynb__')\n",
14
+ " from IPython.core.magic import register_cell_magic\n",
15
+ " @register_cell_magic\n",
16
+ " def skip_if(flag, cell): exec(cell, globals())if flag and not eval(flag) else print('Cell skipped...')\n",
17
+ "\n",
18
+ "import sys, os\n",
19
+ "if os.path.abspath('.') not in sys.path: sys.path.append(os.path.abspath('.'))\n",
20
+ "\n",
21
+ "import os, huggingface_hub # !pip install huggingface_hub[hf_transfer]\n",
22
+ "huggingface_hub.login(token = os.environ.get('HF_TOKEN'), add_to_git_credential=True)\n",
23
+ "\n",
24
+ "import inspect\n",
25
+ "from pathlib import Path\n",
26
+ "from tqdm import tqdm\n",
27
+ "from glob import glob\n",
28
+ "import numpy as np; np.set_printoptions(precision=8, suppress=True); np.random.seed(42)\n",
29
+ "\n",
30
+ "class text_color:\n",
31
+ " black,red,green,yellow,blue,magenta,cyan,white,gray = [*range(30,38), 90] # fgclr, [*range(90,98), ''] # light-fgclr\n",
32
+ " bold, italic, underline, strike = 1, 3, 4, 9 # attrs supported on vscode notebook.\n",
33
+ " def __init__(self, fg,bg=0,attr=0):\n",
34
+ " attr = f'{attr};' if attr > 0 else ''\n",
35
+ " bg = f'{bg+10};' if bg > 0 else ''\n",
36
+ " self.clr = f'\\33[{attr}{bg}{fg}m'\n",
37
+ "\n",
38
+ " def __ror__(self, obj): return self.clr + str(obj) + '\\33[0m'\n",
39
+ " @staticmethod\n",
40
+ " def all(): return (text_color(clr) for clr in [*range(30,38), 90])\n",
41
+ "\n",
42
+ "black,red,green,yellow,blue,magenta,cyan,white,gray = text_color.all()\n",
43
+ "\n",
44
+ "class cout:\n",
45
+ " def __ror__(self, obj): print(f'[{inspect.stack()[1].lineno}] {str(obj)}')\n",
46
+ " def __call__(self, *args, **kwds): print(f'[{inspect.stack()[1].lineno+1}]', *args, **kwds)\n",
47
+ "out = cout()"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "markdown",
52
+ "metadata": {},
53
+ "source": [
54
+ "### load weight"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "execution_count": null,
60
+ "metadata": {},
61
+ "outputs": [],
62
+ "source": [
63
+ "# https://colab.research.google.com/drive/1uskRfCesambdQrhGp2s5wx6zGwSUR0Sh\n",
64
+ "# https://huggingface.co/microsoft/Phi-3.5-mini-instruct/blob/main/config.json\n",
65
+ "# https://github.com/microsoft/Phi-3CookBook\n",
66
+ "# !pip install -q sentencepiece\n",
67
+ "\n",
68
+ "import torch, peft, transformers\n",
69
+ "\n",
70
+ "model_id = \"microsoft/Phi-3.5-mini-instruct\" # 128k, 7.7GB\n",
71
+ "model_id = \"outputs_unslot/merged-model\" # ft.\n",
72
+ "\n",
73
+ "model = transformers.AutoModelForCausalLM.from_pretrained(\n",
74
+ " model_id,\n",
75
+ " device_map=\"auto\",\n",
76
+ " torch_dtype=torch.bfloat16,\n",
77
+ " trust_remote_code=True,\n",
78
+ " low_cpu_mem_usage=True,\n",
79
+ " attn_implementation=\"flash_attention_2\",\n",
80
+ ")\n",
81
+ "\n",
82
+ "# model_id = \"outputs_unslot/model/lora\"\n",
83
+ "# model = peft.AutoPeftModelForCausalLM.from_pretrained(\n",
84
+ "# model_id, device_map=\"cuda\",\n",
85
+ "# torch_dtype=\"auto\",\n",
86
+ "# trust_remote_code=True,\n",
87
+ "# low_cpu_mem_usage=True,\n",
88
+ "# attn_implementation=\"flash_attention_2\")\n",
89
+ "\n",
90
+ "model.config.use_cache = True\n",
91
+ "model.eval()\n",
92
+ "print(model)\n",
93
+ "\n",
94
+ "tokenizer = transformers.AutoTokenizer.from_pretrained(model_id)\n"
95
+ ]
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "execution_count": 182,
100
+ "metadata": {},
101
+ "outputs": [],
102
+ "source": [
103
+ "from IPython.display import display, Markdown, clear_output\n",
104
+ "\n",
105
+ "class CallbackTextStreamer(transformers.TextStreamer):\n",
106
+ " def __init__(self, markdown=False, **kwargs):\n",
107
+ " super().__init__(**kwargs)\n",
108
+ " self.markdown = markdown\n",
109
+ " self.ans = \"\"\n",
110
+ "\n",
111
+ " def on_finalized_text(self, text: str, stream_end: bool = False):\n",
112
+ " super().on_finalized_text(text, stream_end)\n",
113
+ " self.ans += text\n",
114
+ " if stream_end:\n",
115
+ " self.finally_markdown()\n",
116
+ "\n",
117
+ " def finally_markdown(self):\n",
118
+ " if self.markdown:\n",
119
+ " clear_output(wait=False)\n",
120
+ " display(Markdown(self.ans))\n",
121
+ "\n",
122
+ "def generate(input_text, system_prompt=\"\",max_length=512, stream=True):\n",
123
+ "\n",
124
+ " if isinstance(input_text, list):\n",
125
+ " messages = input_text\n",
126
+ " else:\n",
127
+ " if not system_prompt:\n",
128
+ " system_prompt = \"You are a friendly and helpful assistant\"\n",
129
+ " messages = [\n",
130
+ " { \"role\": \"system\", \"content\": system_prompt,},\n",
131
+ " {\"role\": \"user\", \"content\": input_text},\n",
132
+ " ]\n",
133
+ "\n",
134
+ " streamer = CallbackTextStreamer(tokenizer=tokenizer, skip_prompt=True) if stream else None\n",
135
+ "\n",
136
+ " prompt = tokenizer.apply_chat_template(messages,\n",
137
+ " tokenize=False,\n",
138
+ " add_generation_prompt=True)\n",
139
+ "\n",
140
+ " inputs = tokenizer.encode(prompt, add_special_tokens=True, return_tensors=\"pt\").to(\"cuda\")\n",
141
+ " outputs = model.generate(input_ids=inputs.to(model.device),\n",
142
+ " max_new_tokens=max_length,\n",
143
+ " do_sample=True,\n",
144
+ " temperature=0.1,\n",
145
+ " top_k=50,\n",
146
+ " streamer=streamer,\n",
147
+ " )\n",
148
+ " # text = ''.join([t for t in streamer])\n",
149
+ "\n",
150
+ " text = tokenizer.decode(outputs[0, len(inputs[0]):],skip_special_tokens=True, clean_up_tokenization_spaces=True)\n",
151
+ " return text\n"
152
+ ]
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "execution_count": 183,
157
+ "metadata": {},
158
+ "outputs": [
159
+ {
160
+ "name": "stdout",
161
+ "output_type": "stream",
162
+ "text": [
163
+ "So the answer: 16\n",
164
+ "\n",
165
+ "Here's the breakdown:\n",
166
+ "\n",
167
+ "1. Kaylee has sold 12 boxes of lemon biscuits.\n",
168
+ "2. She has sold 5 boxes of chocolate biscuits.\n",
169
+ "3. She has sold 4 boxes of oatmeal biscuits.\n",
170
+ "4. Total boxes sold so far: 12 (lemon) + 5 (chocolate) + 4 (oatmeal) = 21 boxes.\n",
171
+ "5. Kaylee needs to sell a total of 33 boxes.\n",
172
+ "6. Boxes still needed to be sold: 33 (total) - 21 (sold) = 12 boxes.\n",
173
+ "\n",
174
+ "Therefore, Kaylee needs to sell 12 more boxes of biscuits.<|end|>\n"
175
+ ]
176
+ }
177
+ ],
178
+ "source": [
179
+ "# reformat answer for better cot training\n",
180
+ "#\n",
181
+ "system = \"\"\"Following is dataset to fine tuning llm with cot concept.\n",
182
+ "To make more good dataset, reformat assistant's cot answer as numbering. And lastly the answer with leading words 'So the answer: '. Answer the reformatted string only.\"\"\"\n",
183
+ "\n",
184
+ "content = '''\n",
185
+ "{\"type\": \"cot\", \"messages\": [{\"role\": \"user\", \"content\": \"Kaylee needs to sell 33 boxes of biscuits. So far, she has sold 12 boxes of lemon biscuits to her aunt, 5 boxes of chocolate biscuits to her mother, and 4 boxes of oatmeal biscuits to a neighbor. How many more boxes of biscuits does Kaylee need to sell? Let's think first. Chain of thought:\"}, {\"role\": \"assistant\", \"content\": \"To solve this problem, we need to find out how many boxes of biscuits Kaylee has sold so far and then subtract that number from the total number of boxes she needs to sell. We can do this by adding up the number of boxes she has sold and then subtracting that sum from the total number of boxes she needs to sell.\"}], \"source\": \"open-orca\"}\n",
186
+ "'''\n",
187
+ "# 33 - (12 + 5 + 4) = 12\n",
188
+ "\n",
189
+ "content = '''\\\n",
190
+ "user query: \"Kaylee needs to sell 33 boxes of biscuits. So far, she has sold 12 boxes of lemon biscuits to her aunt, 5 boxes of chocolate biscuits to her mother, and 4 boxes of oatmeal biscuits to a neighbor. How many more boxes of biscuits does Kaylee need to sell? Let's think first. Chain of thought:\"\n",
191
+ "\n",
192
+ "assistant answer: \"To solve this problem, we need to find out how many boxes of biscuits Kaylee has sold so far and then subtract that number from the total number of boxes she needs to sell. We can do this by adding up the number of boxes she has sold and then subtracting that sum from the total number of boxes she needs to sell.\"\n",
193
+ "'''\n",
194
+ "gen = generate(content, system, max_length=512)\n",
195
+ "\n"
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "execution_count": null,
201
+ "metadata": {},
202
+ "outputs": [],
203
+ "source": [
204
+ "Markdown( generate('Write a detailed analogy between mathematics and a lighthouse.',\n",
205
+ " system_prompt=\"You are Phi, a small language model trained by Microsoft. Write out your reasoning step-by-step to be sure you get the right answers!\",\n",
206
+ " max_length=1024))"
207
+ ]
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "execution_count": null,
212
+ "metadata": {},
213
+ "outputs": [],
214
+ "source": [
215
+ "generate('Write a short email to Sam Altman giving reasons to open source GPT-4',\n",
216
+ " system_prompt=\"You are Phi-3, a large language model trained by Microsoft. Write out your reasoning step-by-step to be sure you get the right answers!\",\n",
217
+ " max_length=512, stream=True);"
218
+ ]
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "execution_count": null,
223
+ "metadata": {},
224
+ "outputs": [],
225
+ "source": [
226
+ "generate('''```python\n",
227
+ "def detect_prime(n):\n",
228
+ " \"\"\"\n",
229
+ " detect if a number is a prime number or not. return True or False\n",
230
+ " \"\"\"''',\n",
231
+ " system_prompt=\"You are a genius python coder, please think carefully and write the following code:\");\n"
232
+ ]
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "execution_count": null,
237
+ "metadata": {},
238
+ "outputs": [],
239
+ "source": [
240
+ "gen = generate('Answer the following question by reasoning step by step. The cafeteria had 23 apples. If they used 20 for lunch, and bought 6 more, how many apple do they have?',\n",
241
+ " system_prompt=\"You are Phi-3, a large language model trained by Microsoft. Write out your reasoning step-by-step to be sure you get the right answers!\",\n",
242
+ " max_length=512)"
243
+ ]
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "execution_count": null,
248
+ "metadata": {},
249
+ "outputs": [],
250
+ "source": [
251
+ "gen = generate(\"Weng earns $12 an hour for babysitting. Yesterday, she just did 50 minutes of babysitting. How much did she earn?\",\n",
252
+ " system_prompt=\"Write out your reasoning step-by-step to be sure you get the right answers!\",\n",
253
+ " max_length=512)"
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "markdown",
258
+ "metadata": {},
259
+ "source": [
260
+ "### function call"
261
+ ]
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "execution_count": null,
266
+ "metadata": {},
267
+ "outputs": [],
268
+ "source": [
269
+ "import datasets, re, json\n",
270
+ "\n",
271
+ "ds_test = datasets.load_dataset(\"json\", data_files=\"xlam-dataset-60k-qwen2-test.jsonl\")['train']\n",
272
+ "\n",
273
+ "system_prompt = \"Write out your reasoning step-by-step to be sure you get the right answers!\"\n",
274
+ "\n",
275
+ "\n",
276
+ "for i, sample in enumerate(ds_test):\n",
277
+ " message = sample[\"messages\"]\n",
278
+ " user_content = message[0]['content']\n",
279
+ " # message.insert(0, dict(role='system', content=system_prompt))\n",
280
+ "\n",
281
+ " ans = message[-1][\"content\"]\n",
282
+ " gen = generate(message[:-1], stream=False)\n",
283
+ " gen = gen.replace('```json', '').replace('```', '')\n",
284
+ "\n",
285
+ " true,false = True,False\n",
286
+ " gen = json.dumps(eval(gen), indent=3)\n",
287
+ " ans = json.dumps(eval(ans), indent=3)\n",
288
+ "\n",
289
+ " if gen != ans:\n",
290
+ " # print(f'{i}.query:', user_content[-200:]|gray)\n",
291
+ " print('gen:', gen|red)\n",
292
+ " print('ans:', ans|green)"
293
+ ]
294
+ },
295
+ {
296
+ "cell_type": "markdown",
297
+ "metadata": {},
298
+ "source": [
299
+ "### from https://deepgram.com/learn/chain-of-thought-prompting-guide"
300
+ ]
301
+ },
302
+ {
303
+ "cell_type": "code",
304
+ "execution_count": 184,
305
+ "metadata": {},
306
+ "outputs": [
307
+ {
308
+ "name": "stdout",
309
+ "output_type": "stream",
310
+ "text": [
311
+ "Roger starts with 5 tennis balls.\n",
312
+ "\n",
313
+ "He buys 2 more cans, and each can has 3 tennis balls. So, the number of tennis balls in the cans is:\n",
314
+ "2 cans * 3 tennis balls per can = 6 tennis balls\n",
315
+ "\n",
316
+ "Now, we add the tennis balls he already had to the ones he bought:\n",
317
+ "5 tennis balls + 6 tennis balls = 11 tennis balls\n",
318
+ "\n",
319
+ "Roger now has a total of 11 tennis balls.<|end|>\n",
320
+ "answer: 11\n"
321
+ ]
322
+ }
323
+ ],
324
+ "source": [
325
+ "prompts = [\n",
326
+ "(\"Roger has 5 tennis balls. He buys 2 more cans of tennis balls. Each can has 3 tennis balls. How many tennis balls does he have now?\", 11),\n",
327
+ "(\"Yes or no: Would a pear sink in water?\",None),\n",
328
+ "(\"How would you bring me something that isn’t a fruit?\",None),\n",
329
+ "(\"How many keystrokes are needed to type the numbers from 1 to 500?\", 1392),\n",
330
+ "(\"The concert was scheduled to be on 06/01/1943, but was delayed by one day to today. What is the date 10 days ago in MM/DD/YYYY?\", \"05/23/1943\"),\n",
331
+ "(\"Take the last letters of the words in 'Lady Gaga' and concatenate them.\", 'ya'),\n",
332
+ "(\"Sammy wanted to go to where the people were. Where might he go?\",None),\n",
333
+ "(\"Is the following sentence plausible? 'Joao Moutinho caught the screen pass in the NFC championship.'\", 'not plausible'),\n",
334
+ "(\"A coin is heads up. Maybelle flips the coin. Shalonda does not flip the coin. Is the coin still heads up?\", \"No\"),\n",
335
+ "('Answer the following question by reasoning step by step. The cafeteria had 23 apples. If they used 20 for lunch, and bought 6 more, how many apple do they have?', 9)\n",
336
+ "]\n",
337
+ "\n",
338
+ "line = 2\n",
339
+ "generate(prompts[line-2][0],\n",
340
+ " system_prompt=\"Write out your reasoning step-by-step to be sure you get the right answers!\",\n",
341
+ " max_length=512)\n",
342
+ "\n",
343
+ "if prompts[line-2][1]:\n",
344
+ " print('answer:', prompts[line-2][1])"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "code",
349
+ "execution_count": null,
350
+ "metadata": {},
351
+ "outputs": [],
352
+ "source": [
353
+ "react_prompt = \"\"\"\\\n",
354
+ "Assistant is a large language model trained by Microsoft.\n",
355
+ "\n",
356
+ "Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n",
357
+ "\n",
358
+ "Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n",
359
+ "\n",
360
+ "Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.\n",
361
+ "\n",
362
+ "TOOLS:\n",
363
+ "------\n",
364
+ "\n",
365
+ "Assistant has access to the following tools:\n",
366
+ "\n",
367
+ "wikipedia_search - searches the wikipedia database for the answer\\n\n",
368
+ "web_search - searches the web for the answer\\n\n",
369
+ "calculator - calculates the answer to the question\\n\n",
370
+ "weather_api - gets the weather for the location\\n\n",
371
+ "\n",
372
+ "\n",
373
+ "To use a tool, please use the following format:\n",
374
+ "\n",
375
+ "```\n",
376
+ "Thought: Do I need to use a tool? Yes\n",
377
+ "Action: the action to take, should be one of [wikipedia_search, web_search, calculator, weather_api]\n",
378
+ "Action Input: the input to the action\n",
379
+ "Observation: the result of the action\n",
380
+ "```\n",
381
+ "\n",
382
+ "When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:\n",
383
+ "\n",
384
+ "```\n",
385
+ "Thought: Do I need to use a tool? No\n",
386
+ "Final Answer: [your response here]\n",
387
+ "```\n",
388
+ "\n",
389
+ "Begin!\n",
390
+ "\n",
391
+ "\n",
392
+ "New input: {query}\n",
393
+ "\"\"\" #{agent_scratchpad}\n"
394
+ ]
395
+ },
396
+ {
397
+ "cell_type": "code",
398
+ "execution_count": null,
399
+ "metadata": {},
400
+ "outputs": [],
401
+ "source": [
402
+ "gen = generate(react_prompt.format(query=\"What is the latest AI news today?\"), max_length=512)"
403
+ ]
404
+ },
405
+ {
406
+ "cell_type": "code",
407
+ "execution_count": null,
408
+ "metadata": {},
409
+ "outputs": [],
410
+ "source": [
411
+ "generate(react_prompt.format(query=\"오늘 날씨 어때?\"), max_length=512)"
412
+ ]
413
+ },
414
+ {
415
+ "cell_type": "code",
416
+ "execution_count": null,
417
+ "metadata": {},
418
+ "outputs": [],
419
+ "source": [
420
+ "generate(\"사과와 귤중 어떤게 더 맛있어?\", max_length=1024)"
421
+ ]
422
+ },
423
+ {
424
+ "cell_type": "markdown",
425
+ "metadata": {},
426
+ "source": [
427
+ "# ollama"
428
+ ]
429
+ },
430
+ {
431
+ "cell_type": "code",
432
+ "execution_count": null,
433
+ "metadata": {},
434
+ "outputs": [],
435
+ "source": [
436
+ "import openai\n",
437
+ "from IPython.display import display, Markdown\n",
438
+ "from multimethod import multimethod\n",
439
+ "_ollama = openai.OpenAI(base_url='http://localhost:11434/v1')\n",
440
+ "\n",
441
+ "ollama_model_id = 'phi3.5:3.8b-mini-instruct-q8_0'\n",
442
+ "ollama_model_id = 'jjkim76/phi3.5-fc:Q8_0'\n",
443
+ "\n",
444
+ "def generate(input_text, system_prompt=None, max_length=1024):\n",
445
+ " if system_prompt is None:\n",
446
+ " system_prompt = \"\"\"Write out your reasoning step-by-step to be sure you get the right answers!\"\"\"\n",
447
+ "\n",
448
+ " messages = input_text\n",
449
+ " if not isinstance(messages, list):\n",
450
+ " messages = [dict(role=\"system\", content=system_prompt), dict(role=\"user\", content=input_text)]\n",
451
+ "\n",
452
+ " response = _ollama.chat.completions.create(\n",
453
+ " model=ollama_model_id,\n",
454
+ " messages=messages,\n",
455
+ " temperature = 0.01, top_p = 0.01,\n",
456
+ " max_tokens=max_length,\n",
457
+ " # do_sample=True, temperature=0.1, top_k=50,\n",
458
+ " )\n",
459
+ " text = response.choices[0].message.content\n",
460
+ " # print(input_text[-200:]|gray)\n",
461
+ " # display(Markdown(text))\n",
462
+ " return text\n",
463
+ "\n",
464
+ "\n"
465
+ ]
466
+ }
467
+ ],
468
+ "metadata": {
469
+ "kernelspec": {
470
+ "display_name": "fcv3-2",
471
+ "language": "python",
472
+ "name": "python3"
473
+ },
474
+ "language_info": {
475
+ "codemirror_mode": {
476
+ "name": "ipython",
477
+ "version": 3
478
+ },
479
+ "file_extension": ".py",
480
+ "mimetype": "text/x-python",
481
+ "name": "python",
482
+ "nbconvert_exporter": "python",
483
+ "pygments_lexer": "ipython3",
484
+ "version": "3.10.14"
485
+ }
486
+ },
487
+ "nbformat": 4,
488
+ "nbformat_minor": 2
489
+ }