langchain 如何使用本地大模型(LLM)

本文详细介绍了如何在Langchain中,特别是HuggingFacePipeline的上下文中,加载并使用本地的预训练Transformer模型进行文本生成,强调了device_map设置的重要性,以防运行时错误或设备不匹配的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

langchain 很多例子里面,默认都是调用的OpenAI的模型,但是有时候我们希望使用自己本地的大模型。具体代码如下: 

from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
from langchain import LLMChain,HuggingFacePipeline,PromptTemplate
import torch

model_path = "写入模型存在路径"
device = torch.device("cuda:0")
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True, device_map="auto").half()
pipe = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
    max_length=512,
    top_p=1,
    repetition_penalty=1.15
)
llama_model = HuggingFacePipeline(pipeline=pipe)
template = '''
#背景信息# 
你是一名知识丰富的导航助手,了解中国每一个地方的名胜古迹及旅游景点. 
#问题# 
游客:我想去{地方}旅游,给我推荐一下值得玩的地方?"
'''
prompt = PromptTemplate(
    input_variables=["地方"],
    template=template
)
chain = LLMChain(llm=llama_model, prompt=prompt)
print(chain.run("天津"))

注意: 

这行代码一定要写成 device_map="auto"

AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True, device_map="auto").half() 

如果代码写成.cuda(),具体如下

AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True, ).half().cuda

会报错:

RuntimeError: Expected all tensors to be on the same device, but found at least two devices.

或者

warning : 

You are calling .generate() with the input_ids being on a device type different than your model's device. input_ids is on cuda, whereas the model is on cpu. You may experience unexpected behaviors or slower generation. Please make sure that you have put input_ids to the correct device by calling for example input_ids = input_ids.to('cpu') before running .generate().
 

### 使用Langchain框架调用本地大规模语言模型 为了利用Langchain框架来调用部署在本地的大规模语言模型,开发者可以通过简单的配置实现这一目标。具体来说,在完成对Langchain框架的适配后,用户能够基于此框架迅速构建各种大型模型应用程序[^1]。 对于希望使用本地部署的语言模型执行推理任务的情况,通常涉及以下几个方面的工作: #### 配置环境变量与依赖项安装 确保已经正确设置了Python虚拟环境,并按照官方文档指导安装必要的库文件和支持包。这一步骤至关重要,因为不同的硬件平台可能需要特定版本的支持软件。 #### 加载预训练模型 假设已经在本地成功加载了一个预训练好的大模型实例,则可通过如下方式初始化该模型对象: ```python from langchain import LangChainModel model_path = "path/to/local/model" lang_model = LangChainModel.load(model_path) ``` #### 构建Prompt并传递给模型 根据实际需求设计合适的提示语句(Prompt),这里可以根据具体的业务场景选用不同类型的提示策略,比如少量描述、少样本或是思维链等方式[^2]。下面是一个简单例子展示如何创建一个基本查询请求并向模型发送数据流: ```python prompt_text = "请解释什么是机器学习?" response = lang_model.generate(prompt=prompt_text, max_tokens=50) print(response.text.strip()) ``` #### 多GPU加速及优化设置 如果计划进一步提高性能表现,特别是当面对复杂度较高的自然语言处理任务时,建议启用多GPU支持以及采用混合精度训练方法来加快运算过程和改善资源利用率[^3]: ```python import torch if torch.cuda.device_count() > 1: device_ids = list(range(torch.cuda.device_count())) model.to(f'cuda:{device_ids[0]}') model.parallelize(device_ids=device_ids) # 如果适用的话 torch.backends.cudnn.benchmark = True ``` 通过上述操作指南,可以有效地将已有的本地化大规模语言模型集成到Langchain工作流当中,从而更好地服务于下游应用场景中的多样化需求。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值