# 在 Hugging Face 上使用 AllenNLP

`allennlp` 是一个用于在不同语言任务上开发最先进模型的 NLP 库。它为现代 NLP 中的常见组件和模型提供了高级抽象和 API。它还提供了一个可扩展的框架，便于运行和管理 NLP 实验。

## 在 Hub 中探索 allennlp

您可以在[模型页面](https://huggingface.co/models?library=allennlp)左侧进行筛选，以查找 Hub 上的`allennlp`模型。

Hub 上的所有模型都附带了实用功能
1. 带有自动托管的 TensorBoard 跟踪记录的训练指标选项卡。
2. 有助于提高可发现性的元数据标签。
3. 一个交互式小部件，可直接在浏览器中用于体验该模型。
4. 一个用于发起推理请求的 Inference Providers 小部件。

## 使用现有模型

您可以使用 `Predictor` 类来加载 Hub 上现有的模型。为此，请使用 `from_path` 方法，并在仓库 id 前加上 `"hf://"` 前缀。下面是一个端到端的示例。

```py
import allennlp_models
from allennlp.predictors.predictor import Predictor

predictor = Predictor.from_path("hf://allenai/bidaf-elmo")
predictor_input = {
    "passage": "My name is Wolfgang and I live in Berlin", 
    "question": "Where do I live?"
}
predictions = predictor.predict_json(predictor_input)
```

要获取这样的代码片段，您可以点击右上角的 `Use in AllenNLP`，

## 共享您的模型

第一步是将模型保存到本地。例如，你可以使用 [`archive_model`](https://docs.allennlp.org/main/api/models/archival/#archive_model) 方法将模型保存为 `model.tar.gz` 文件。然后，你可以将压缩后的模型推送到 Hub。当你使用 `allennlp` 训练模型时，模型会自动序列化，因此你可以将其作为首选方案。

### 使用 AllenNLP CLI

要通过 CLI 推送，您可以使用如下所示的 `allennlp push_to_hf` 命令。

```bash
allennlp push_to_hf --repo_name test_allennlp --archive_path model 
```

| 参数                    	| 类型         	| 描述                                                                                                                   	|
|-----------------------------	|--------------	|-------------------------------------------------------------------------------------------------------------------------------	|
| `--repo_name`, `-n`         	| str / `Path` 	| Hub 上仓库的名称。                                                                                            	|
| `--organization`, `-o`      	| str          	| 要上传该 pipeline 的组织的可选名称。                                                       	|
| `--serialization-dir`, `-s` 	| str / `Path` 	| 包含序列化模型的目录的路径。                                                                                  	|
| `--archive-path`, `-a`      	| str / `Path` 	| 如果您使用的是压缩模型（例如 model/model.tar.gz）而非序列化路径，则可以使用此标志。              	|
| `--local-repo-path`, `-l`   	| str / `Path` 	| 模型仓库的本地路径（如果不存在则会自动创建）。默认值为当前工作目录下的 `hub`。 	|
| `--commit-message`, `-c`    	| str          	| 用于更新的提交信息。默认为 `"update repository"`。                                                          	|

### 从 Python 脚本

`push_to_hf` 函数与 bash 脚本具有相同的参数。

```py
from allennlp.common.push_to_hf import push_to_hf

serialization_dir = "path/to/serialization/directory"
push_to_hf(
    repo_name="my_repo_name",
    serialization_dir=serialization_dir,
    local_repo_path=self.local_repo_path
)
```

只需一分钟，你就可以将模型上传到 Hub，直接在浏览器中试用，并与社区其他成员分享。所有必需的元数据都会自动为你上传！

## 其他资源

* AllenNLP [网站](https://allenai.org/allennlp)。
* AllenNLP [仓库](https://github.com/allenai/allennlp)。

