终极解决Hugging Face 模型推理 HTTPSConnectionPool(host=‘huggingface.co‘, port=443): Max retries...

大陆地区由于网络的问题,在使用Hugging Face进行模型下载或推理时总会遇到类似这样的问题.原因在于需要比较频繁的访问Hugging Face网页.模型下载时有时确实没有办法,但模型推理时,有时候为了验证模型的正确性,依然需要大量访问Hhugging Face,这实际是没有必要的.经过大量尝试,发现把模型文件拷贝至缓存以外的区域,就不会再出现标题所示的问题,甚至关闭网络都可以正常推理.这儿给出一个例子:

hf_generator = pipeline(model="declare-lab/flan-alpaca-large", device=0)

这儿加载模型declare-lab/flan-alpaca-large,如果事先没有下载该模型,直接运行该语句,那么会自动下载该模型到以下目录(以ubuntu为例):

/home/lhs/.cache/huggingface/hub/models--declare-lab--flan-alpaca-large

可以考虑直接把models–declare-lab–flan-alpaca-large拷贝至另外文件夹,该模型文件夹目录为:

-models--declare-lab--flan-alpaca-large
├── blobs
├── refs
└── snapshots
    └── 5c9e43db774036eb8878cf19550f3f19c98c608b

注意,5c9e43db774036eb8878cf19550f3f19c98c608b文件夹中便是模型文件的软链接文件,直接把这个目录名地址放入pipeline语句中即可本地调用文件,并不需要访问Hugging Face网页,语句如下:

hf_generator = pipeline("text2text-generation", model="./models/models--declare-lab--flan-alpaca-large/snapshots/5c9e43db774036eb8878cf19550f3f19c98c608b", device=0)

这儿相比之前的语句还需写明模型的task类型为"text2text-generation",模型的task类型包括以下几种,可以去模型的主页查看其类型并填入相应的类型:

            - `"audio-classification"`
            - `"automatic-speech-recognition"`
            - `"conversational"`
            - `"depth-estimation"`
            - `"document-question-answering"`
            - `"feature-extraction"`
            - `"fill-mask"`
            - `"image-classification"`
            - `"image-segmentation"`
            - `"image-to-text"`
            - `"object-detection"`
            - `"question-answering"`
            - `"summarization"`
            - `"table-question-answering"`
            - `"text2text-generation"`
            - `"text-classification"` (alias `"sentiment-analysis"` available)
            - `"text-generation"`
            - `"token-classification"` (alias `"ner"` available)
            - `"translation"`
            - `"translation_xx_to_yy"`
            - `"video-classification"`
            - `"visual-question-answering"`
            - `"zero-shot-classification"`
            - `"zero-shot-image-classification"`
            - `"zero-shot-object-detection"`

参考链接:

https://github.com/huggingface/transformers/blob/main/src/transformers/pipelines/init.py

使用上述方法可以有效解决网络访问报错的问题.

你可能感兴趣的:(深度学习,python,语言模型,人工智能)