langchain中使用huggingface中的模型作为LLM可以离线运行

文章介绍了如何使用HuggingFace的Pipeline接口,结合Transformer库,特别是GPT2和THUDM/chatglm3-6b模型进行文本生成,展示了如何创建chain-of-thoughtprompt并演示了在GPU上高效运行的示例。
摘要由CSDN通过智能技术生成
from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline

hf = HuggingFacePipeline.from_model_id(
    model_id="gpt2",
    task="text-generation",
    pipeline_kwargs={"max_new_tokens": 50},
)

from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline


from langchain.prompts import PromptTemplate

template = """Question: {question}

Answer: Let's think step by step."""
prompt = PromptTemplate.from_template(template)

chain = prompt | hf

question = "What is the  result  of  1+ 1?"

print(chain.invoke({"question": question}))
# Use a pipeline as a high-level helper
!pip install langchain_community langchain
from transformers import pipeline

from langchain_community.llms import HuggingFacePipeline
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
from langchain.prompts import PromptTemplate

pipe = pipeline("text-generation", model="HuggingFaceH4/zephyr-7b-beta")

hf = HuggingFacePipeline(pipeline=pipe)



template = """Question: {question}

Answer: Let's think step by step."""
prompt = PromptTemplate.from_template(template)

chain = prompt | hf

question = "What is the  result  of  1+ 1?"

print(chain.invoke({"question": question}))

以下使用清华的大模型GPU运行:

from transformers import pipeline
from langchain_community.llms import HuggingFacePipeline
import time
hf = HuggingFacePipeline.from_model_id(
    model_id="THUDM/chatglm3-6b",
    task="text-generation",
    device=0,
    model_kwargs={"trust_remote_code":True},
    pipeline_kwargs={"max_new_tokens": 500},
)

for i in range(10):
    a = time.time()
    print(hf.invoke("西游记中描写了哪些人物"))
    print(time.time()-a)

也可以作为链式来调用.

from transformers import pipeline
from langchain_community.llms import HuggingFacePipeline
import time
from langchain.prompts import PromptTemplate
hf = HuggingFacePipeline.from_model_id(
    model_id="THUDM/chatglm3-6b",
    task="text-generation",
    device=0,
    model_kwargs={"trust_remote_code":True},
    pipeline_kwargs={"max_new_tokens": 500},
)
template = """{question}"""
prompt = PromptTemplate.from_template(template)
chain = prompt | hf
question = "西游记中描写了哪些人物?"
for i in range(10):
    a = time.time()
    print(chain.invoke({"question": question}))
    print(time.time()-a)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值