Transformers安装指南
Transformers 提供了数以千计的预训练模型,支持 100 多种语言的文本分类、信息抽取、问答、摘要、翻译、文本生成。
Transformers 支持三个最热门的深度学习库: Jax, PyTorch 以及 TensorFlow — 并与之无缝整合。你可以直接使用一个框架训练你的模型然后用另一个加载和推理。
本文主要介绍安装 Transformers、设置缓存,并选择性配置 Transformers 以离线运行。
- PyTorch 安装说明。
使用 pip 安装
你应该使用虚拟环境安装 Transformers。使用虚拟环境,你可以轻松管理不同项目,避免不同依赖项之间的兼容性问题。
首先,在项目目录中创建虚拟环境:
conda create -n python-transformers python=3.10
激活虚拟环境:
conda activate python-transformers
现在你可以使用以下命令安装 Transformers:
pip install transformers
若仅需 CPU 支持,可以使用单行命令方便地安装 🤗 Transformers 和深度学习库。例如,使用以下命令安装 🤗 Transformers 和 PyTorch:
pip install 'transformers[torch]'
最后,运行以下命令以检查 🤗 Transformers 是否已被正确安装。该命令将下载一个预训练模型:
python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))"
然后打印标签以及分数:
[{'label': 'POSITIVE', 'score': 0.9998704791069031}]
源码安装
使用以下命令从源码安装 🤗 Transformers:
pip install git+https://github.com/huggingface/transformers
此命令下载的是最新的前沿 main
版本而不是最新的 stable
版本。main
版本适用于跟最新开发保持一致。运行以下命令以检查 🤗 Transformers 是否已被正确安装:
python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))"
开发模式安装
如果你有下列需求,需要进行可编辑安装:
- 使用源码的
main
版本。 - 为 🤗 Transformers 贡献代码,需要测试代码中的更改。
使用以下命令克隆仓库并安装 🤗 Transformers:
git clone https://github.com/huggingface/transformers.git
cd transformers
pip install -e .
这些命令将会链接你克隆的仓库以及你的 Python 库路径。现在,Python 不仅会在正常的库路径中搜索库,也会在你克隆到的文件夹中进行查找。例如,如果你的 Python 包通常本应安装在 ~/anaconda3/envs/main/lib/python3.10/site-packages/
目录中,在这种情况下 Python 也会搜索你克隆到的文件夹:~/transformers/
。
如果你想继续使用这个库,必须保留 transformers
文件夹。
现在,你可以使用以下命令,将你克隆的 🤗 Transformers 库轻松更新至最新版本:
cd ~/transformers/
git pull
你的 Python 环境将在下次运行时找到 main
版本的 🤗 Transformers。
docker 安装
在transformers的docker目录中提供了各个版本的dockerfile文件。可以直接docker命令创建镜像。
docker build --build-arg --network host -t ai_suite:cuda12.1-torch2.1-22.04 .
启动容器。
xhost + && docker run --gpus all --env NVIDIA_DISABLE_REQUIRE=1 -it --network=host --name transformers-container --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -v /home:/home -v /tmp:/tmp -v /mnt:/mnt --ipc=host -e DISPLAY=${DISPLAY} -e GIT_INDEX_FILE ai_suite:cuda12.1-torch2.1-22.04 bash
自定义dockerfile
自定义安装,主要是为了在docker中使用conda虚拟环境。
# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-23-11.html#rel-23-11
FROM nvcr.io/nvidia/pytorch:23.11-py3
LABEL maintainer="transformers"
ARG DEBIAN_FRONTEND=noninteractive
ARG PYTORCH='2.1.0'
# Example: `cu102`, `cu113`, etc.
ARG CUDA='cu121'
RUN apt-get update &&\
apt-get install -y libaio-dev wget bzip2 ca-certificates curl git git-lfs unzip mlocate usbutils\
vim tmux g++ gcc build-essential cmake checkinstall lsb-release &&\
rm -rf /var/lib/apt/lists/* &&\
apt-get clean
RUN python3 -m pip uninstall -y torch torchvision torchaudio torch-tensorrt transformer-engine apex
SHELL ["/bin/bash", "--login", "-c"]
RUN cd / && wget --quiet https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /miniconda.sh && \
/bin/bash /miniconda.sh -b -p /opt/conda &&\
ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh &&\
echo ". /opt/conda/etc/profile.d/conda.sh" >> ~/.bashrc &&\
/bin/bash -c "source ~/.bashrc" && \
/opt/conda/bin/conda update -n base -c defaults conda -y &&\
/opt/conda/bin/conda config --set ssl_verify no && \
/opt/conda/bin/conda config --add channels conda-forge &&\
/opt/conda/bin/conda create -n ai python=3.10
ENV PATH $PATH:/opt/conda/envs/ai/bin
RUN conda init bash &&\
echo "conda activate ai" >> ~/.bashrc &&\
conda activate ai &&\
pip install --upgrade pip -i https://mirror.baidu.com/pypi/simple &&\
pip config set global.index-url https://mirror.baidu.com/pypi/simple &&\
# Install latest release PyTorch
# (PyTorch must be installed before pre-compiling any DeepSpeed c++/cuda ops.)
# (https://www.deepspeed.ai/tutorials/advanced-install/#pre-install-deepspeed-ops)
pip install --no-cache-dir -U torch==$PYTORCH torchvision torchaudio \
--extra-index-url https://download.pytorch.org/whl/$CUDA &&\
pip install -U numpy opencv-python onnx onnxoptimizer onnxruntime -i https://mirror.baidu.com/pypi/simple
ARG REF=main
RUN conda activate ai &&\
cd &&\
git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF &&\
cd .. &&\
pip install --no-cache-dir ./transformers[deepspeed-testing] &&\
pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate &&\
# recompile apex
# pip uninstall -y apex &&\
# RUN git clone https://github.com/NVIDIA/apex
# `MAX_JOBS=1` disables parallel building to avoid cpu memory OOM when building image on GitHub Action (standard) runners
# TODO: check if there is alternative way to install latest apex
# RUN cd apex && MAX_JOBS=1 python3 -m pip install --global-option="--cpp_ext" --global-option="--cuda_ext" --no-cache -v --disable-pip-version-check .
# Pre-build **latest** DeepSpeed, so it would be ready for testing (otherwise, the 1st deepspeed test will timeout)
pip uninstall -y deepspeed
# This has to be run (again) inside the GPU VMs running the tests.
# The installation works here, but some tests fail, if we don't pre-build deepspeed again in the VMs running the tests.
# TODO: Find out why test fail.
RUN DS_BUILD_CPU_ADAM=1 DS_BUILD_FUSED_ADAM=1
RUN conda activate ai &&\
pip install deepspeed --global-option="build_ext" \
--global-option="-j8" --no-cache -v --disable-pip-version-check 2>&1
# When installing in editable mode, `transformers` is not recognized as a package.
# this line must be added in order for python to be aware of transformers.
RUN conda activate ai &&\
cd &&\
cd transformers && python3 setup.py develop
# The base image ships with `pydantic==1.8.2` which is not working - i.e. the next command fails
RUN conda activate ai &&\
pip install -U --no-cache-dir "pydantic<2"
RUN conda activate ai &&\
python3 -c "from deepspeed.launcher.runner import main"
RUN apt-get update &&\
rm -rf /var/lib/apt/lists/* &&\
apt-get clean
缓存设置
预训练模型会被下载并本地缓存到 ~/.cache/huggingface/hub
。这是由环境变量 TRANSFORMERS_CACHE
指定的默认目录。在 Windows 上,默认目录为 C:\Users\username\.cache\huggingface\hub
。你可以按照不同优先级改变下述环境变量,以指定不同的缓存目录。更多详情:https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables
- 环境变量(默认):
HUGGINGFACE_HUB_CACHE
或TRANSFORMERS_CACHE
。 - 环境变量
HF_HOME
。 - 环境变量
XDG_CACHE_HOME
+/huggingface
。
# Determine default cache directory. Lots of legacy environment variables to ensure backward compatibility.
# The best way to set the cache path is with the environment variable HF_HOME.
#
# In code, use `HF_HUB_CACHE` as the default cache path. This variable is set by the library and is guaranteed
# to be set to the right value.
# Huggingface_hub/constants.py
from huggingface_hub import constants
default_cache_path = os.path.join(HF_HOME, "hub")
# /src/transformers/utils/hub.py
default_cache_path = constants.default_cache_path
old_default_cache_path = os.path.join(torch_cache_home, "transformers")
import os
import transformers
# datasets/src/config.py
DEFAULT_XDG_CACHE_HOME = "~/.cache"
XDG_CACHE_HOME = os.getenv("XDG_CACHE_HOME", DEFAULT_XDG_CACHE_HOME)
DEFAULT_HF_CACHE_HOME = os.path.join(XDG_CACHE_HOME, "huggingface")
HF_CACHE_HOME = os.path.expanduser(os.getenv("HF_HOME", DEFAULT_HF_CACHE_HOME))
print(HF_CACHE_HOME)
# 更改HF_HOME
os.environ["HF_HOME"] = "E:\huggingface\cache"
HF_CACHE_HOME = os.path.expanduser(os.getenv("HF_HOME", DEFAULT_HF_CACHE_HOME))
print(HF_CACHE_HOME)
除非你明确指定了环境变量 TRANSFORMERS_CACHE
,🤗 Transformers 将可能会使用较早版本设置的环境变量 PYTORCH_TRANSFORMERS_CACHE
或 PYTORCH_PRETRAINED_BERT_CACHE
。
离线模式
🤗 Transformers 可以仅使用本地文件在防火墙或离线环境中运行。设置环境变量 TRANSFORMERS_OFFLINE=1
以启用该行为。
通过设置环境变量 HF_DATASETS_OFFLINE=1
将 🤗 Datasets 添加至你的离线训练工作流程中。
例如,你通常会使用以下命令对外部实例进行防火墙保护的的普通网络上运行程序:
python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ...
在离线环境中运行相同的程序:
HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ...
现在脚本可以应该正常运行,而无需挂起或等待超时,因为它知道只应查找本地文件。
获取离线时使用的模型和分词器
另一种离线时使用 🤗 Transformers 的方法是预先下载好文件,然后在需要离线使用时指向它们的离线路径。有三种实现的方法:
-
单击 Model Hub 用户界面上的 ↓ 图标下载文件。
-
使用 [
PreTrainedModel.from_pretrained
] 和 [PreTrainedModel.save_pretrained
] 工作流程:- 预先使用 [
PreTrainedModel.from_pretrained
] 下载文件:
>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B") >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B")
- 使用 [
PreTrainedModel.save_pretrained
] 将文件保存至指定目录:
>>> tokenizer.save_pretrained("./your/path/bigscience_t0") >>> model.save_pretrained("./your/path/bigscience_t0")
- 现在,你可以在离线时从指定目录使用 [
PreTrainedModel.from_pretrained
] 重新加载你的文件:
>>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0") >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0")
- 预先使用 [
-
使用代码用 huggingface_hub 库下载文件:
- 在你的虚拟环境中安装
huggingface_hub
库:
python -m pip install huggingface_hub
- 使用
hf_hub_download
函数将文件下载到指定路径。例如,以下命令将config.json
文件从 T0 模型下载至你想要的路径:
>>> from huggingface_hub import hf_hub_download >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0")
- 在你的虚拟环境中安装
下载完文件并在本地缓存后,指定其本地路径以加载和使用该模型:
>>> from transformers import AutoConfig
>>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json")
请参阅 如何从 Hub 下载文件 部分,获取有关下载存储在 Hub 上文件的更多详细信息。
参考
- https://github.com/huggingface/transformers/blob/main/docs/source/en/installation.md
- https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables