> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Hugging Face 本地管道集成

> 使用 LangChain Python 与 Hugging Face 本地管道 LLM 进行集成。

可以通过 `HuggingFacePipeline` 类在本地运行 Hugging Face 模型。

[Hugging Face 模型库](https://huggingface.co/models) 托管了超过 12 万个模型、2 万个数据集和 5 万个演示应用（Spaces），全部开源并公开可用，这是一个人们可以轻松协作和共同构建机器学习的在线平台。

这些可以通过此本地管道包装器从 LangChain 调用，或者通过 HuggingFaceHub 类调用其托管的推理端点。

使用时，您应该已安装 `transformers` Python [包](https://pypi.org/project/transformers/)，以及 [PyTorch](https://pytorch.org/get-started/locally/)。您还可以安装 `xformer` 以实现更节省内存的注意力机制实现。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU transformers
```

### 模型加载

可以使用 `from_model_id` 方法指定模型参数来加载模型。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_huggingface.llms import HuggingFacePipeline

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

也可以直接传入现有的 `transformers` 管道来加载它们

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_huggingface.llms import HuggingFacePipeline
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline

model_id = "gpt2"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=10)
hf = HuggingFacePipeline(pipeline=pipe)
```

### 创建链

将模型加载到内存后，您可以将其与提示词组合以形成链。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_core.prompts import PromptTemplate

template = """Question: {question}

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

chain = prompt | hf

question = "What is electroencephalography?"

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

若要获取不带提示词的响应，可以将 `skip_prompt=True` 绑定到 LLM。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
chain = prompt | hf.bind(skip_prompt=True)

question = "What is electroencephalography?"

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

流式响应。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
for chunk in chain.stream(question):
    print(chunk, end="", flush=True)
```

### GPU 推理

当在有 GPU 的机器上运行时，可以指定 `device=n` 参数将模型放置在指定的设备上。默认为 `-1` 用于 CPU 推理。

如果您有多个 GPU 和/或模型太大无法放入单个 GPU，可以指定 `device_map="auto"`，这需要并使用 [Accelerate](https://huggingface.co/docs/accelerate/index) 库来自动确定如何加载模型权重。

*注意*：不应同时指定 `device` 和 `device_map`，否则可能导致意外行为。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
gpu_llm = HuggingFacePipeline.from_model_id(
    model_id="gpt2",
    task="text-generation",
    device=0,  # replace with device_map="auto" to use the accelerate library.
    pipeline_kwargs={"max_new_tokens": 10},
)

gpu_chain = prompt | gpu_llm

question = "What is electroencephalography?"

print(gpu_chain.invoke({"question": question}))
```

### 批量 GPU 推理

如果在带有 GPU 的设备上运行，也可以在 GPU 上以批处理模式运行推理。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
gpu_llm = HuggingFacePipeline.from_model_id(
    model_id="bigscience/bloom-1b7",
    task="text-generation",
    device=0,  # -1 for CPU
    batch_size=2,  # adjust as needed based on GPU map and model size.
    model_kwargs={"temperature": 0, "max_length": 64},
)

gpu_chain = prompt | gpu_llm.bind(stop=["\n\n"])

questions = []
for i in range(4):
    questions.append({"question": f"What is the number {i} in french?"})

answers = gpu_chain.batch(questions)
for answer in answers:
    print(answer)
```

### 使用 OpenVINO 后端进行推理

要使用 OpenVINO 部署模型，可以指定 `backend="openvino"` 参数以触发 OpenVINO 作为后端推理框架。

如果您有 Intel GPU，可以指定 `model_kwargs={"device": "GPU"}` 在其上运行推理。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -U-strategy eager "optimum[openvino,nncf]" --quiet
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
ov_config = {"PERFORMANCE_HINT": "LATENCY", "NUM_STREAMS": "1", "CACHE_DIR": ""}

ov_llm = HuggingFacePipeline.from_model_id(
    model_id="gpt2",
    task="text-generation",
    backend="openvino",
    model_kwargs={"device": "CPU", "ov_config": ov_config},
    pipeline_kwargs={"max_new_tokens": 10},
)

ov_chain = prompt | ov_llm

question = "What is electroencephalography?"

print(ov_chain.invoke({"question": question}))
```

### 使用本地 OpenVINO 模型进行推理

您可以通过 CLI 将 [导出您的模型](https://github.com/huggingface/optimum-intel?tab=readme-ov-file#export) 为 OpenVINO IR 格式，并从本地文件夹加载模型。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
!optimum-cli export openvino --model gpt2 ov_model_dir
```

建议使用 `--weight-format` 应用 8 位或 4 位权重量化以减少推理延迟和模型占用空间：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
!optimum-cli export openvino --model gpt2  --weight-format int8 ov_model_dir # for 8-bit quantization

!optimum-cli export openvino --model gpt2  --weight-format int4 ov_model_dir # for 4-bit quantization
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
ov_llm = HuggingFacePipeline.from_model_id(
    model_id="ov_model_dir",
    task="text-generation",
    backend="openvino",
    model_kwargs={"device": "CPU", "ov_config": ov_config},
    pipeline_kwargs={"max_new_tokens": 10},
)

ov_chain = prompt | ov_llm

question = "What is electroencephalography?"

print(ov_chain.invoke({"question": question}))
```

您可以通过激活值的动态量化和 KV 缓存量化获得额外的推理速度提升。这些选项可以通过 `ov_config` 启用，如下所示：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
ov_config = {
    "KV_CACHE_PRECISION": "u8",
    "DYNAMIC_QUANTIZATION_GROUP_SIZE": "32",
    "PERFORMANCE_HINT": "LATENCY",
    "NUM_STREAMS": "1",
    "CACHE_DIR": "",
}
```

更多信息请参阅 [OpenVINO LLM 指南](https://docs.openvino.ai/2024/learn-openvino/llm_inference_guide.html) 和 [OpenVINO 本地管道笔记本](/oss/python/integrations/llms/openvino/)。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\python\integrations\llms\huggingface_pipelines.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
