File size: 16,672 Bytes
c504954 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Configuration ok\n"
]
}
],
"source": [
"from ctransformers import AutoModelForCausalLM, AutoConfig\n",
"import utils\n",
"import json\n",
"from llama_cpp import Llama\n",
"\n",
"# load model .gguf bằng CTransformers\n",
"\n",
"\n",
"def configure():\n",
" path = \"models/theblokeai/Mistral-7B-Instruct-v0.2.Q4_K_M\"\n",
" # llm = CTransformers(\n",
" # model=path, max_new_tokens=1024, context_length=1024, gpu_layers=20\n",
" # )\n",
" # llm = AutoModelForCausalLM.from_pretrained(\n",
" # path=path,\n",
" # model_file=\"mistral-7b-instruct-v0.2.Q4_K_M.gguf\",\n",
" # local_files_only=True,\n",
" # config = \n",
" # )\n",
" llm = Llama(\n",
" model_path=path+\"/mistral-7b-instruct-v0.2.Q4_K_M.gguf\", # Download the model file first\n",
" n_ctx=1024, # The max sequence length to use - note that longer sequence lengths require much more resources\n",
" n_threads=4, # The number of CPU threads to use, tailor to your system and the resulting performance\n",
" n_batch=1024,\n",
" verbose=False, # Verbose = True to see full configuration, but expect output logs on every model call\n",
" # n_gpu_layers=35, # The number of layers to offload to GPU, if you have GPU acceleration available\n",
" )\n",
" db = utils.ArxivChroma()\n",
" sqldb = utils.ArxivSQL()\n",
" print(\"Configuration ok\")\n",
" return llm, sqldb, db\n",
"\n",
"\n",
"model, sqldb, db = configure()"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def extract_keyword_prompt(query):\n",
" \"\"\"A prompt that return a JSON block as arguments for querying database\"\"\"\n",
"\n",
" prompt = (\n",
" \"\"\"[INST] You are an assistant that choose only one action below based on guest question.\n",
" 1. If the guest question is asking for some specific document or article, you need to respond the information in JSON format with 2 keys \"title\", \"author\" if found any above. The authors are separated with the word 'and'. \n",
" 2. If the guest question is asking for relevant informations about a topic, you need to respond the information in JSON format with 2 keys \"keywords\", \"description\", include a list of keywords represent the main academic topic, \\\n",
" and a description about the main topic. You may paraphrase the keywords to add more. \\\n",
" 3. If the guest is not asking for any informations or documents, you need to respond with a polite answer in JSON format with 1 key \"answer\".\n",
" QUESTION: '{query}'\n",
" [/INST]\n",
" ANSWER: \n",
" \"\"\"\n",
" ).format(query=query)\n",
"\n",
" return prompt\n",
"\n",
"def make_answer_prompt(input, contexts):\n",
" \"\"\"A prompt that return the final answer, based on the queried context\"\"\"\n",
"\n",
" prompt = (\n",
" \"\"\"[INST] You are an library assistant that help to search articles and documents based on user's question.\n",
" From guest's question, you have found some records and documents that may help. Now you need to answer the guest with the information found.\n",
" You should answer in a conversational form politely.\n",
" QUESTION: '{input}'\n",
" INFORMATION: '{contexts}'\n",
" [/INST]\n",
" ANSWER:\n",
" \"\"\"\n",
" ).format(input=input, contexts=contexts)\n",
"\n",
" return prompt"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"def response(args):\n",
" \"\"\"Create response context, based on input arguments\"\"\"\n",
" keys = list(dict.keys(args))\n",
" if \"answer\" in keys:\n",
" return args['answer'], None # trả lời trực tiếp\n",
" if \"keywords\" in keys:\n",
" # perform query\n",
" query_texts = args[\"description\"]\n",
" keywords = args[\"keywords\"]\n",
" results = db.query_relevant(keywords=keywords, query_texts=query_texts)\n",
" # print(results)\n",
" ids = results['metadatas'][0]\n",
" paper_id = [id['paper_id'] for id in ids]\n",
" paper_info = sqldb.query_id(paper_id)\n",
" # print(paper_info)\n",
" records = [] # get title (2), author (3), link (6)\n",
" result_string = \"\"\n",
" for i in range(len(paper_id)):\n",
" result_string += \"Title: {}, Author: {}, Link: {}\".format(paper_info[i][2],paper_info[i][3],paper_info[i][6])\n",
" records.append([paper_info[i][2],paper_info[i][3],paper_info[i][6]])\n",
" # process results:\n",
" return result_string, records\n",
" # invoke llm and return result\n",
" if \"title\" in keys:\n",
" results = sqldb.query(title = args['title'],author = args['author'])\n",
" print(results)\n",
" paper_info = sqldb.query(title = args['title'],author = args['author'])\n",
" # if query not found then go crawl brh\n",
" # -------------------------------------\n",
" records = [] # get title (2), author (3), link (6)\n",
" result_string = \"\"\n",
" for i in range(len(paper_info)):\n",
" result_string += \"Title: {}, Author: {}, Link: {}\".format(paper_info[i][2],paper_info[i][3],paper_info[i][6])\n",
" records.append([paper_info[i][2],paper_info[i][3],paper_info[i][6]])\n",
" # process results:\n",
" if len(result_string) == 0:\n",
" return \"Information not found\", None\n",
" return result_string, records\n",
" # invoke llm and return result"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"--------------------------\n",
" {\n",
" \"keywords\": [\"LSTM model\", \"video analysis\", \"action recognition\"],\n",
" \"description\": \"For recognizing actions in videos using Long Short-Term Memory (LSTM) models, you may find the following papers insightful. These studies explore various aspects of action recognition using LSTM: (1) 'Action Recognition with 3D Convolutional Neural Networks and Long Short-Term Memory' by Tran et al., 2015; (2) 'ConvLSTM: A Convolutional Neural Network for Video Recognition' by Shi et al., 2015; (3) 'Using Long-Short Term Memory for Action Recognition in Videos' by Graves, 2013.\"\n",
" }\n",
"For recognizing actions in videos using Long Short-Term Memory (LSTM) models, you may find the following papers insightful. These studies explore various aspects of action recognition using LSTM: (1) 'Action Recognition with 3D Convolutional Neural Networks and Long Short-Term Memory' by Tran et al., 2015; (2) 'ConvLSTM: A Convolutional Neural Network for Video Recognition' by Shi et al., 2015; (3) 'Using Long-Short Term Memory for Action Recognition in Videos' by Graves, 2013.\n",
"['LSTM model', 'video analysis', 'action recognition']\n"
]
}
],
"source": [
"# test first step\n",
"# input_prompt = input()\n",
"input_prompt = \"I'm working on a LSTM model to recognize actions in a video, recommend me some related papers\"\n",
"first_prompt = extract_keyword_prompt(input_prompt)\n",
"# print(first_prompt)\n",
"# answer = model.invoke(first_prompt,\n",
"# temperature=0.0) # ctrans\n",
"answer = model(prompt=first_prompt,\n",
" temperature=0.0) # llama\n",
"print(\"--------------------------\")\n",
"print(answer)\n",
"args = json.loads(utils.trimming(answer))\n",
"# print(args)\n",
"response(args)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"For recognizing actions in videos using Long Short-Term Memory (LSTM) models, you may find the following papers insightful. These studies explore various aspects of action recognition using LSTM: (1) 'Action Recognition with 3D Convolutional Neural Networks and Long Short-Term Memory' by Tran et al., 2015; (2) 'ConvLSTM: A Convolutional Neural Network for Video Recognition' by Shi et al., 2015; (3) 'Using Long-Short Term Memory for Action Recognition in Videos' by Graves, 2013.\n",
"['LSTM model', 'video analysis', 'action recognition']\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Llama.generate: prefix-match hit\n",
"\n",
"llama_print_timings: load time = 139768.70 ms\n",
"llama_print_timings: sample time = 140.16 ms / 412 runs ( 0.34 ms per token, 2939.41 tokens per second)\n",
"llama_print_timings: prompt eval time = 0.00 ms / 1 tokens ( 0.00 ms per token, inf tokens per second)\n",
"llama_print_timings: eval time = 91570.34 ms / 412 runs ( 222.26 ms per token, 4.50 tokens per second)\n",
"llama_print_timings: total time = 93048.98 ms / 413 tokens\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"------------------------\n",
"Hello there! I see that you're working on an LSTM model for recognizing actions in videos. I have found some related papers that might be of interest to you.\n",
"\n",
" 1. The first one is titled \"Action in Mind: A Neural Network Approach to Action Recognition and Segmentation\" by Zahra Gharae. This paper proposes a neural network approach for action recognition and segmentation, which could provide some insights into your work with LSTM models. You can find it at this link: <http://arxiv.org/pdf/2104.14870v1>\n",
"\n",
" 2. Another interesting paper is \"Deep Neural Networks in Video Human Action Recognition: A Review\" by Zihan Wang, Yang Yang, Zhi Liu, and Yifan Zhen. This review discusses the application of deep neural networks for video human action recognition. It could give you a broader perspective on the current state-of-the-art methods in this field. You can access it here: <http://arxiv.org/pdf/2305.15692v1>\n",
"\n",
" 3. Lastly, there's \"3D Convolutional Neural Networks for Ultrasound-Based Silent Speech Interfaces\" by László Tóth and Amin Honarmandi Shandi. Although the title might not seem directly related to your work on LSTM models for action recognition, it does involve the use of 3D convolutional neural networks in video processing, which could still provide valuable insights. You can read it at this link: <http://arxiv.org/pdf/2104.11532v1>\n",
"\n",
" I hope you find these resources helpful! Let me know if there's anything else I can assist you with. Have a great day!\n"
]
}
],
"source": [
"# test response, second step\n",
"input_prompt = \"I'm working on a LSTM model to recognize actions in a video, recommend me some related papers\"\n",
"args = {\n",
" \"keywords\": [\"LSTM model\", \"video analysis\", \"action recognition\"],\n",
" \"description\": \"For recognizing actions in videos using Long Short-Term Memory (LSTM) models, you may find the following papers insightful. These studies explore various aspects of action recognition using LSTM: (1) 'Action Recognition with 3D Convolutional Neural Networks and Long Short-Term Memory' by Tran et al., 2015; (2) 'ConvLSTM: A Convolutional Neural Network for Video Recognition' by Shi et al., 2015; (3) 'Using Long-Short Term Memory for Action Recognition in Videos' by Graves, 2013.\"\n",
" }\n",
"contexts, results = response(args)\n",
"if not results:\n",
" # direct answer\n",
" print(contexts)\n",
"else:\n",
" output_prompt = make_answer_prompt(input_prompt,contexts)\n",
" # answer = model.invoke(output_prompt,\n",
" # temperature=0.3) # ctrans\n",
" answer = model(prompt=output_prompt,\n",
" temperature=0.0,\n",
" max_tokens=1024,\n",
" ) # llama\n",
" print(\"------------------------\")\n",
" print(answer['choices'][0]['text'])"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"--------------------------\n",
"------------------------\n",
"Hello there! I see that you're working on an LSTM model for recognizing actions in videos. I have some related papers that might be of interest to you.\n",
"\n",
" 1. The first paper is titled \"Deep Neural Networks in Video Human Action Recognition: A Review\" by Zihan Wang, Yang Yang, Zhi Liu, and Yifan Zhen. This review discusses the application of deep neural networks in recognizing human actions from videos. You can find it at this link: <http://arxiv.org/pdf/2305.15692v1>\n",
"\n",
" 2. The second paper is titled \"A Video Recognition Method by using Adaptive Structural Learning of Long Short Term Memory based Deep Belief Network\" by Shin Kamada and Takumi Ichimur. This study proposes a method for video recognition using an adaptive structural learning LSTM-DBN model. You can access it at this link: <http://arxiv.org/pdf/1909.13480v1>\n",
"\n",
" 3. Lastly, there's the paper \"3D Convolutional Neural Networks for Ultrasound-Based Silent Speech Interfaces\" by László Tóth and Amin Honarmandi Shandi. Although it focuses on silent speech interfaces using ultrasound videos, it also employs 3D CNNs and LSTM networks for action recognition. You can read it here: <http://arxiv.org/pdf/2104.11532v1>\n",
"\n",
" I hope these resources will help you in your research! Let me know if there's anything else I can assist you with. Have a great day!\n"
]
}
],
"source": [
"# full chain\n",
"# inference time depends on hardware ability :')\n",
"# with CPU i7-8750H, 16GB RAM and no GPU cuda, expect inference time up to 5-6 min\n",
"# input_prompt = input()\n",
"input_prompt = \"I'm working on a LSTM model to recognize actions in a video, recommend me some related papers\"\n",
"first_prompt = extract_keyword_prompt(input_prompt)\n",
"# print(first_prompt)\n",
"# answer = model.invoke(first_prompt,\n",
"# temperature=0.0) # ctrans, answer is a string\n",
"answer = model(prompt=first_prompt,\n",
" temperature=0.0,\n",
" max_tokens=512,\n",
" ) # llama, answer is a dict\n",
"print(\"--------------------------\")\n",
"# print(answer['choices'][0]['text']) # see middle answer\n",
"args = json.loads(utils.trimming(answer['choices'][0]['text']))\n",
"contexts, results = response(args)\n",
"if not results:\n",
" # direct answer\n",
" print(contexts)\n",
"else:\n",
" output_prompt = make_answer_prompt(input_prompt,contexts)\n",
" # answer = model.invoke(output_prompt,\n",
" # temperature=0.3) # ctrans, answer is a string\n",
" answer = model(prompt=output_prompt,\n",
" temperature=0.0,\n",
" max_tokens=1024,\n",
" ) # llama, answer is a dict\n",
" print(\"--------------------------\")\n",
" print(answer['choices'][0]['text'])"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"!pip freeze > requirements.txt"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "langchain_llms",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|