学习笔记6《调用模型:使用OpenAI API还是微调开源Llama2/ChatGLM?》

155 阅读3分钟

大语言模型概述

大语言模型(Large Language Models,LLMs)是基于深度学习的算法,能够理解和生成自然语言。这些模型通常在大量文本数据上进行预训练,学习语言的基本规则和模式,然后可以在特定任务上进行微调。

发展历程

  • Transformer架构:Google在2018年提出的Transformer架构是现代预训练语言模型的基础。
  • BERT模型:BERT是早期的代表性模型,通过学习文本的双向上下文信息,实现了对句子结构的深入理解。

预训练与微调

  • 预训练:在大量无标注文本数据上进行训练,学习通用的语言知识。
  • 微调:在预训练模型的基础上,针对特定任务进行调整,通常需要较少的数据和计算资源。

使用开源模型

HuggingFace平台

HuggingFace提供了一个平台,可以下载和使用各种开源的预训练模型。

安装与设置

  1. 注册HuggingFace账号并获取API Token。
  2. 安装transformers库:pip install transformers
  3. 设置API Token:huggingface-cli login

使用Llama2模型

  • 下载并使用Meta的Llama2模型,推荐从HuggingFace下载,以便未来模型更新时可以方便地迁移。

代码示例

from transformers import AutoTokenizer, AutoModelForCausalLM

# 加载分词器和模型
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-2-7b-chat-hf", device_map='auto'
)

# 定义提示并生成文本
prompt = "请给我讲个玫瑰的爱情故事?"
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
outputs = model.generate(inputs["input_ids"], max_new_tokens=2000)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(response)

LangChain集成

LangChain是一个利用大语言模型推理功能开发新工具或应用的平台。

通过HuggingFace Hub集成

import os
from langchain import PromptTemplate, HuggingFaceHub, LLMChain

os.environ['HUGGINGFACEHUB_API_TOKEN'] = '你的HuggingFace API Token'
llm = HuggingFaceHub(repo_id="google/flan-t5-small")
template = "Question: {question} Answer: "
prompt = PromptTemplate(template=template, input_variables=["question"])
llm_chain = LLMChain(prompt=prompt, llm=llm)
question = "Rose is which type of flower?"
print(llm_chain.run(question))

通过HuggingFace Pipeline集成

from transformers import AutoTokenizer, pipeline

model = "meta-llama/Llama-2-7b-chat-hf"
tokenizer = AutoTokenizer.from_pretrained(model)
pipeline = pipeline(
    "text-generation",
    model=model,
    torch_dtype=torch.float16,
    device_map="auto",
    max_length=1000
)

from langchain import HuggingFacePipeline
llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature':0})
template = """
              为以下的花束生成一个详细且吸引人的描述:
              花束的详细信息:
              ```{flower_details}```

from langchain import PromptTemplate, LLMChain
prompt = PromptTemplate(template=template, input_variables=["flower_details"])
llm_chain = LLMChain(prompt=prompt, llm=llm)
flower_details = "12支红玫瑰,搭配白色满天星和绿叶,包装在浪漫的红色纸中。"
print(llm_chain.run(flower_details))

本地模型集成

如果需要使用自定义或私有模型,可以在LangChain中创建自定义LLM类。

from langchain.llms.base import LLM

class CustomLLM(LLM):
    def _call(self, prompt: str, stop: list = None) -> str:
        # 模型调用逻辑
        return response

    def _identifying_params(self) -> dict:
        return {"name_of_model": "your_model_name"}

    def _llm_type(self) -> str:
        return "custom"

llm = CustomLLM()
result = llm("你的输入文本")
print(result)

总结与思考

  • 使用OpenAI API vs 开源模型:根据需求、成本和资源选择。OpenAI API可能更稳定,而开源模型可能更灵活。
  • 性能比较:使用HuggingFace的Transformers库下载不同模型进行推理,比较它们的性能。
  • 流行模型调用:在LangChain中使用HuggingFaceHub和HuggingFace Pipeline接口调用当前最流行的大语言模型。

通过这些学习,我们可以更好地理解大语言模型的工作原理和应用方式,以及如何在实际项目中集成和使用这些模型。