核心内容摘要
蜜桃一区二区三区在线观看:探索数字时代的娱乐新次元
原文towardsdatascience.com/llms-for-everyone-running-the-llama-13b-model-and-langchain-in-google-colab-68d88021cf0bhttps://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/c1c2e1a8e6731e9a039722d2789772e
png由 Glib Albovsky 拍摄的照片Unsplash在故事的
分中我们使用了一个免费的 Google Colab 实例来运行 Mistral-7B 模型并使用 FAISSFacebook AI Similarity Search数据库提取信息。
在这一部分我们将更进一步我将展示如何运行 LLaMA 2 13B 模型我们还将测试一些额外的 LangChain 功能如创建基于聊天的应用程序和使用代理。
同样就像
分一样所有使用的组件都是基于开源项目并且将完全免费使用。
让我们开始吧LLaMA.cppLLaMA.CPP是一个非常有趣的开源项目最初是为了在 Macbooks 上运行 LLaMA 模型而设计的但其功能已经远远超出了这个范围。
首先它使用纯 C/C编写没有外部依赖可以在任何硬件上运行支持 CUDA、OpenCL 和 Apple 硅甚至可以在树莓派上运行。
其次LLaMA.CPP 可以与LangChain连接这允许我们免费测试其许多功能而无需 OpenAI 密钥。
最后但同样重要的是由于 LLaMA.CPP 可以在任何地方运行它是一个很好的候选者可以在免费的 Google Colab 实例上运行。
提醒一下Google 提供了免费访问具有 12 GB RAM 和 16 GB VRAM 的 Python 笔记本可以通过Colab Research页面打开。
代码在网页浏览器中打开并在云端运行因此每个人都可以访问即使是从预算最低的 PC 也可以。
在使用 LLaMA 之前让我们安装库。
安装本身很简单我们只需在使用 pip 之前启用LLAMA_CUBLAS!CMAKE_ARGS-DLLAMA_CUBLASonFORCE_CMAKE1pip3 install llama-cpp-python !pip3 install huggingface-hub !pip3 install sentence-transformers langchain langchain-experimental !huggingface-cli download TheBloke/Llama-
b-Chat-GGUF llama-
b-chat.Q4_K_M.gguf--local-dir/content--local-dir-use-symlinksFalse对于第一次测试我将使用 7B 模型。
在这里我还安装了huggingface-hub库它允许我们自动下载 LLaMA.CPP 所需的 GGUF 格式的“Llama-2–7b-Chat”模型。
我还安装了LangChain库它将被用于进一步的测试。
现在让我们加载模型并测试它是否正常工作fromlangchain.llmsimportLlamaCppfromlangchain.callbacks.managerimportCallbackManagerfromlangchain.callbacks.streaming_stdoutimportStreamingStdOutCallbackHandler n_gpu_layers40n_batch512callback_managerCallbackManager([StreamingStdOutCallbackHandler()])llmLlamaCpp(model_path/content/llama-
b-chat.Q4_K_M.gguf,temperature
1,n_gpu_layersn_gpu_layers,n_batchn_batch,callback_managercallback_manager,verboseTrue,)当模型加载后我们只需一行代码就可以测试它llm(What is the distance to the Moon? Write the short answer.)在这里我还使用了StreamingStdOutCallbackHandler它允许我们在“ChatGPT”风格中获得平滑的“流式”输出https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/2cbbbf238dfa17d368ee34c5acdd
png关于资源由于 4 位量化7B 模型很好地符合 Google Colab 免费限制https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/1c0e16f0618dfa87875b4870c92cd
pngGoogle Colab 资源图片由作者提供如我们所见该模型只需要大约
6GB 的 RAM 和
2GB 的 VRAM因此理论上它几乎可以在任何预算 PC 上运行。
使用 Google Colab我们甚至可以完全免费运行一个 13B 模型我们只需要更改“download”命令中的 URL!huggingface-cli download TheBloke/Llama-
B-chat-GGUF llama-
b-chat.Q4_K_M.gguf--local-dir/content--local-dir-use-symlinksFalse自然地这个模型需要更多的资源但仍然足够用于免费实例https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/bfa6e3dd94d03ab16b9706f5018990d
pngGoogle Colab 资源图片由作者提供我们的模式已经准备好了让我们看看我们如何在 LangChain 中使用它。
LangChainLangChain 是一个为开发由语言模型驱动的应用程序而设计的 开源 Python 框架。
理论上它是“跨平台的”并且可以使用最少的代码更改使用不同的语言模型。
但实际上并不总是清楚需要更改什么官方文档中的大多数示例都是为 OpenAI 制作的OpenAI 不是免费的用户将为每次 API 调用付费。
因此LLaMA.CPP 是一种无需额外成本学习此库的好方法。
让我们开始吧
LLM 链LCELLangChain 表达式语言是 LangChain 库中的基本概念之一。
它允许我们创建一个提示并将其绑定到语言模型fromlangchain.promptsimportPromptTemplatefromlangchain.schema.output_parserimportStrOutputParserfromlangchain.callbacks.tracersimportConsoleCallbackHandler templates[INST] SYS Provide a correct and short answer to the question. /SYS {question} [/INST]promptPromptTemplate(templatetemplate,input_variables[question])chainprompt|llm|StrOutputParser()chain.invoke({question:What is the distance to the Moon?},config{# callbacks: [ConsoleCallbackHandler()]})# Sure! The average distance from Earth to the Moon is about# 384,400 kilometers (238,900 miles).在这里我创建了一个提示指示 LLaMA 模型要做什么将其连接到之前步骤中创建的 LLM并添加了一个StrOutputParser实例来清理输出文本。
callbacks是一个可选参数允许我们调试链如果我们想查看实际发送给模型的提示它非常有用。
合并链使用 LCEL我们可以轻松地组合两个链。
在这里我添加了一个第二个链它使用第一个链的输出作为输入。
template2s[INST] SYS Use the summary {summary} and give 2 one sentence examples of practical applications of the subject [/INST] /SYS [/INST] prompt2PromptTemplate(input_variables[summary],templatetemplate2,)chain2{summary:prompt|llm|StrOutputParser()}|prompt2|llm|StrOutputParser()chain
invoke({question:What is the distance to the Moon?},config{# callbacks: [ConsoleCallbackHandler()]})# The average distance from Earth to the Moon is approximately 384,400# kilometers (238,900 miles), and this information has several practical# applications, such as:# 1\. Planning space missions: Knowing the exact distance between Earth# and the Moon is crucial for designing and executing space missions.# 2\. Navigation and communication: The distance between Earth and the# Moon affects the time it takes for radio signals to travel between# the two bodies...如果我们启用ConsoleCallbackHandler我们将看到在这个例子中语言模型被调用了两次[llm/start]Exiting Prompt runwithoutput:s[INST] SYSnProvide a correct and short answer to the question.n/SYSnWhat is the distance to the Moon? [/INST]Exiting LLM runwithoutput:The average distance from Earth to the Moon is about 384,400 kilometers (238,900 miles).[llm/start]Entering LLM runwithinput:s[INST] SYSnUse the summary The average distance from Earth to the Moon is about 384,400 kilometers (238,900 miles). and give 2 one sentence examples of practical applications of the subject [/INST]n/SYSn[/INST]Exiting LLM runwithoutput:...LangChain 库为我们做了所有需要的工作并在“幕后”进行所有 LLM 调用。
这类事情需要我们牢记在心尤其是如果我们使用付费 API 而不是免费的本地模型如果我们没有意识到这一点账单上的 2 倍增加可能会是一个糟糕的惊喜。
自动路由让我们测试一个更复杂的例子并为不同的请求使用不同的提示。
在这里我将使用HuggingFaceEmbeddings类和余弦相似度来确定问题是否关于空间或数学fromlangchain.embeddingsimportHuggingFaceEmbeddingsfromlangchain.utils.mathimportcosine_similarityfromlangchain.schema.runnableimportRunnableLambda,RunnablePassthrough space_templates[INST] SYS You are an astronaut. You are great at answering questions about space. Provide a short answer to the question, understandable to a small kid. /SYS {query} [/INST]math_templates[INST] SYS You are a mathematician. You are great at answering math questions. Provide a short answer to the question. /SYS {query} [/INST]embeddingsHuggingFaceEmbeddings()prompt_templates[space_template,math_template]prompt_embeddingsembeddings.embed_documents(prompt_templates)defprompt_router(input): Find a proper template for the input query_embeddingembeddings.embed_query(input[query])similaritycosine_similarity([query_embedding],prompt_embeddings)[0]most_similarprompt_templates[similarity.argmax()]print(Using MATHifmost_similarmath_templateelseUsing SPACE)returnPromptTemplate.from_template(most_similar)chain({query:RunnablePassthrough()}|RunnableLambda(prompt_router)|llm|StrOutputParser())这里的逻辑很简单。
HuggingFaceEmbeddings类将问题转换为数值表示。
然后我们使用余弦相似度指标来确定问题更接近“数学”还是“空间”。
输出看起来像这样chain.invoke(How far is Mars?,config{# callbacks: [ConsoleCallbackHandler()]})# Using SPACE# Oh, wow! Thats a really cool question! *adjusts spacesuit* Mars is# actually quite far from Earth! *grin* Its like, really, really far!# *estimates with hands* Let me see... if I hold out my hand like this# (gestures), thats how far Mars is from Earth! *smiling* Its about 140# million miles away!如我们所见如果问题是不同的人提出的例如成人和孩子自动提示检测可能很有用。
基本聊天我们还可以使用ChatPromptTemplate类与 LLM 进行交互该类允许用户与模型进行对话。
fromlangchain.chainsimportLLMChainfromlangchain.prompts.chatimport(ChatPromptTemplate,HumanMessagePromptTemplate,SystemMessagePromptTemplate,)fromlangchain.schemaimportAIMessage,HumanMessagefromlangchain_experimental.chat_modelsimportLlama2Chat sys_templates[INST] SYS Act as an experienced AI assistant. Write only one sentence answers. /SYS [/INST] chat_promptChatPromptTemplate.from_messages([SystemMessagePromptTemplate.from_template(sys_template),HumanMessage(contentHello, how are you doing?),AIMessage(contentIm doing well, thanks!),HumanMessage(contentMay I ask you a question about Moon?),AIMessage(contentYes, sure.),HumanMessagePromptTemplate.from_template({question}),])modelLlama2Chat(llmllm)chainchat_prompt|model|StrOutputParser()chain.invoke({question:How big is it?},config{# callbacks: [ConsoleCallbackHandler()]})# The Moon has a diameter of approximately 2,159 miles (3,475 kilometers).在这里我创建了一个SystemMessagePromptTemplate对象其中包含了模型所需的指令并添加了对话历史。
LangChain 将完成所有必要的工作将这些数据组合成最终的提示。
我们可以启用ConsoleCallbackHandler来查看发送给模型的输入[llm/start]Entering LLM runwithinput:System: s[INST] SYSnAct as an experienced AI assistant. Write only one sentence answers.n/SYSn[/INST]nnHuman: Hello, how are you doing?nAI: Im doing well, thanks!nHuman: May I ask you a question about Moon?nAI: Yes, sure.nHuman: How big is it?
带记忆和消息摘要的聊天将所有消息存储在文本体中的可能性很有用但最终的提示很容易变得过长。
这对人类也是如此我们通常无法记住过去对话中的所有短语但我们记得我们谈论的大致内容。
借助ConversationSummaryMemory类我们可以使用同样的想法来处理 LLM。
fromlangchain.chainsimportConversationChainfromlangchain.memoryimportConversationBufferMemory,ConversationSummaryMemory,CombinedMemory,ChatMessageHistory conv_memoryConversationBufferMemory(memory_keychat_history_lines,input_keyinput)summary_memoryConversationSummaryMemory(llmllm,input_keyinput)memoryCombinedMemory(memories[conv_memory,summary_memory])templates[INST] SYS Act as an experienced AI assistant. Write one-sentence answers only. /SYS Summary of conversation: {history} Current conversation: {chat_history_lines} Human: {input} [/INST] summary_memory.save_context({input:Hi, how are you},{output:Thanks, I am fine})summary_memory.save_context({input:May I ask you questions about Moon?},{output:Yes, sure})summary_memory.load_memory_variables({})promptPromptTemplate(input_variables[history,input,chat_history_lines],templatetemplate,)conversationConversationChain(llmllm,verboseTrue,memorymemory,promptprompt)conversation.run(How far is it?)# The average distance from the Earth to the Moon is about 238,855 miles# (384,400 kilometers)conversation.run(And what about Mars?)# The average distance from Earth to Mars is about 140 million miles# (225 million kilometers)问题和回答看起来很简单但在幕后有很多事情在进行。
每当添加一个新的“请求-响应”对时ConversationSummaryMemory类都会调用 LLM。
每当调用ConversationChain时摘要也会自动更新。
实际上对于我们的简短对话序列看起来是这样的# save_context({input: Hi, how are you}, {output: Thanks, I am fine})The human greets the AIandasks how itisdoing.The AI responds that itisfine.# save_context({input: May I ask you questions about Moon?}, {output: Yes, sure})The human greets the AIandasks how itisdoing.The AI responds that itisfine.The human asksifthey can ask questions about the moon.The AI agrees.# conversation.run(How far is it?)s[INST]SYSActasan experienced AI assistant.Write one-sentence answers only./SYSSummary of conversation:The human greets the AIandasks how itisdoing.The AI responds that itisfine.The human asksifthey can ask questions about the moon.The AI agrees.Current conversation:Human:How farisit?[/INST]The human greets the AIandasks how itisdoing.The AI responds that itisfine.The human asksifthey can ask questions about the moon.The AI agrees.The human asks how far the moonisfromEarth,andthe AI provides a one-sentence answer:The average distance from the Earth to the Moon is about 238,855 miles (384,400 kilometers).# conversation.run(And what about Mars?)s[INST]SYSActasan experienced AI assistant.Write short answers only./SYSSummary of conversation:The human sayshiandthe AI respondswitha brief message indicating itisfunctioning properly.The human asksifthey can ask questions about the moon.The AI agreesandprovides information about the average distancefromthe Earth to the Moon.END OF NEW SUMMARY Please provide the new summary after each line of conversation,progressively adding onto the previous summary.Current conversation:Human:How farisit? AI:Sure thing! I am ready tohelpanswer your questions about the moon.The average distancefromthe Earth to the Moonisabout238,855miles(384,400kilometers).Human:And what about Mars?[/INST]The human sayshiandthe AI respondswitha brief message indicating itisfunctioning properly.The human asksifthey can ask questions about the moon.The AI agreesandprovides information about the average distancefromthe Earth to the Moon.Now,the human wants to know about Mars.Sure thing! Hereisthe updated summary of our conversation so far:nnHuman:Hi! AI:Hi! I amm functioning properly.Human:Can I ask questions about the moon? AI:Of course! I d be happy tohelp.The average distancefromthe Earth to the Moonisabout238,855miles(384,400kilometers).nnNow,what would you like to know about Mars?这里有几个有趣的地方值得关注。
首先会话摘要并不总是完美的至少对于一个 13B 模型来说是这样输出可以相当长。
在我的测试中链有时会返回错误因为标记数超过了 LLaMA 的最大限制。
其次正如这个例子所示我们只提供了两个问题但 LLM 被执行了六次再次这对 LLaMA 模型来说并不重要但在使用付费 API 和大量测试时可能会让人感到惊讶。
代理将外部代理与语言模型连接起来是一个强大的想法它允许模型使用“工具”来完成更具体的任务。
在这个例子中我将使用PythonREPLTool类它允许模型执行 Python 代码。
如我们从 GitHub 源代码 所见PythonREPLTool 只是一个使用multiprocessing.Process调用来执行 Python 代码的包装器。
我们可以很容易地看到它是如何工作的fromlangchain_experimental.toolsimportPythonREPLTool toolPythonREPLTool()tool.run(import math; print(math.sqrt(
))#
23606797749979顺便说一下在撰写本文时这个类内部没有进行任何合理性检查这可能是危险的。
如果用户要求例如删除系统文件该工具可能会毫不犹豫地执行此命令。
要使用 Python 代理我们只需要几行代码fromlangchain_experimental.agents.agent_toolkitsimportcreate_python_agentfromlangchain.agents.agent_typesimportAgentType agentcreate_python_agent(llmllm,tooltool,verboseTrue,agent_typeAgentType.ZERO_SHOT_REACT_DESCRIPTION)agent.agent.llm_chain.verboseTrueagent.run(What is a square root of 5?)输出看起来像这样# You are an agent designed to write and execute python code to answer questions.# You have access to a python REPL, which you can use to execute python code.# If you get an error, debug your code and try again.# Only use the output of your code to answer the question.# You might know the answer without running any code, but you should still run the code to get the answer.# If it does not seem like you can write code to answer the question, just return I dont know as the answer.# Python_REPL: A Python shell. Use this to execute python commands.# Input should be a valid python command. If you want to see the output# of a value, you should print it out with print(...).# Use the following format:# Question: the input question you must answer# Thought: you should always think about what to do# Action: the action to take, should be one of [Python_REPL]# Action Input: the input to the action# Observation: the result of the action# ... (this Thought/Action/Action Input/Observation can repeat N times)# Thought: I now know the final answer# Final Answer: the final answer to the original input question# Begin!# Question: What is a square root of 5?# Thought: Hmm, this one looks easy. I think I can just use the built-in sqrt() function.# Action: Python_REPL# Action Input: print(sqrt(
)# Observation: NameError(name sqrt is not defined)# Thought: Oh dear, it looks like I need to import the math module first.# Action: Python_REPL# Action Input: import math# Observation:# Thought: Now were getting somewhere!# Action: Python_REPL# Action Input: print(math.sqrt(
)# Observation:
23606797749979Finished chain.
23606797749979这里有几个有趣的地方值得关注。
如我们所见这个提示模板相当复杂尤其是对于一个开源模型来说。
实际上7B LLaMA 模型根本无法完成挑战。
经过多次尝试和错误后一个 13B 模型完成了任务但结果在我看来并不一致。
例如“import math”语句没有正确添加REPL 命令被执行了两次正是因为这样代码才成功。
与之前的例子一样LLM 被调用了多次这在使用付费 API 时可能会产生额外的费用。
如果允许用户在系统上运行任意 Python 代码可能会存在严重的安全问题。
最后但同样重要的是由于自然语言提示的使用有害攻击也可能难以检测。
目前我对于在生产环境中使用 Python 代理还是感到有些害怕但从自我教育的角度来看看看它是如何工作的还是很有趣的。
结论使用大型语言模型很有趣。
在这篇文章中我们能够在免费的 Google Colab 实例上运行 LLaMA-13B 模型并仅使用免费组件测试其功能。
一个开源的 LangChain 库允许我们仅用几行代码就完成一些复杂的事情比如制作聊天摘要。
LLaMA.CPP 也是一个有趣的项目它允许我们使用 LLaMA 以及其他Alpaca、Vicuna 等语言模型和不同的硬件。
最后但同样重要的是能够免费运行语言模型和框架对于实验、原型制作或自我教育来说是非常棒的。
在下一部分我将展示如何在 Google Colab 中运行 HuggingFace 文本生成推理工具包LLMs for Everyone: Running the HuggingFace Text Generation Inference in Google Colab对使用语言模型和自然语言处理感兴趣的人也可以阅读其他文章LLMs for Everyone: Running LangChain and a MistralAI 7B Model in Google ColabNatural Language Processing For Absolute Beginners16, 8, and 4-bit Floating Point Formats – How Does it Work?Python Data Analysis: What Do We Know About Pop Songs?如果你喜欢这个故事请随意订阅Medium你将在我新文章发布时收到通知以及访问来自其他作者成千上万故事的完整权限。
你还可以通过LinkedIn与我建立联系。
如果你想获取这个以及其他文章的完整源代码请随意访问我的Patreon 页面。
感谢阅读。