qidao123.com技术社区-IT企服评测·应用市场

标题: LLM入门——在Colab上部署Llama2 [打印本页]

作者: 张裕    时间: 2024-9-18 06:52
标题: LLM入门——在Colab上部署Llama2
LLM入门——在Colab上部署Llama2

2024/07/09
   本文属于“LLM入门”系列,该系列是笔者自学LLM时记载的一些实践记载与心得,可能存在错误或过时的部分,请读者体贴。
对于LLM入门学者,我推荐从Large Language Model Course开始,这是一份优秀的学习路径引导。
  本文为笔者二次整理的资料,重点关注在Colab上用根本方法部署Llama的指令过程。如有其他需求请参考对应博客:

Llama2

Llama2是meta最新开源的语言大模子,训练数据集2万亿token,上下文长度是由llama的2048扩展到4096,可以明白和生成更长的文本,包罗7B、13B和70B三个模子。
   其中其中B是Billion,代表十亿参数
  以Llama2为代表的开源LLM根本都能在huggingface下载。Hugging Face 是一个旨在推动天然语言处置惩罚(NLP)技能和工具发展的开源社区和公司。他们致力于提供各种NLP任务中的最新技能、模子和工具,以及为开发者提供便捷的方式来使用、微调和部署这些技能。
   当然你也别着急去下载,个人PC的性能在LLM方向能做的事有限,我推荐初学者先在Colab上练练手。
  Colab

Colaboratory(简称为Colab)是由Google开发的一种基于云端的交互式笔记本环境。它提供了免费的计算资源(包罗CPU、GPU和TPU),可让用户在欣赏器中编写和实行代码,而无需进行任何配置和安装。
怎样用Colab创建代码请参考【呆板学习 | 深度学习】Colab是什么?以及怎样使用它?
Llama2 访问

获取Llama的两种方式:

具体方式请参考Llama2 部署及试用。假如后续有继续使用Llama做研究的需求,建议官方申请,实测一两小时内即可乐成。官方申请有几点注意事项:

Colab部署

   参考:Getting Started with LlaMA 2: A Beginner’s Guide
  LangChain 是一个用于开发由语言模子驱动的应用步伐的框架。接下来基于LangChain在Colab上部署使用meta-llama/Llama-2-7b-chat-hf。
总体来看,部署一个LLM可以归纳为以下步骤:
Colab选择T4 GPU





下载相干库

  1. !pip install -q transformers einops accelerate langchain bitsandbytes langchain-community langchain-core langchain-huggingface
复制代码

Hugging Face登录

  1. !huggingface-cli login
复制代码

模子下载加载

  1. from langchain_huggingface import HuggingFacePipeline
  2. from transformers import AutoTokenizer
  3. import transformers
  4. import torch
  5. model = "meta-llama/Llama-2-7b-chat-hf"
  6. tokenizer = AutoTokenizer.from_pretrained(model, truncation=True)
  7. pipeline = transformers.pipeline(
  8.     "text-generation",
  9.     model=model,
  10.     tokenizer=tokenizer,
  11.     torch_dtype=torch.bfloat16,
  12.     trust_remote_code=True,
  13.     device_map="auto",
  14.     max_length=1000,
  15.     eos_token_id=tokenizer.eos_token_id
  16. )
复制代码

  1. llm = HuggingFacePipeline(pipeline = pipeline, model_kwargs = {'temperature':0})
复制代码

Prompt Template

  1. from langchain import PromptTemplate
  2. template = """
  3.               You are an intelligent chatbot that gives out useful information to humans.
  4.               You return the responses in sentences with arrows at the start of each sentence
  5.               {query}
  6.            """
  7. prompt = PromptTemplate(template=template, input_variables=["query"])
  8. llm_chain = prompt | llm
复制代码

  1. print(llm_chain.run('What are the 3 causes of glacier meltdowns?'))
复制代码

参考



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 qidao123.com技术社区-IT企服评测·应用市场 (https://dis.qidao123.com/) Powered by Discuz! X3.4