HuggingFace

起步

安装依赖

  • torch/tensorflow根据不同项目需要安装
# 安装
pip install huggingface_hub

# (按项目需要)安装PyTorch的GPU版,及huggingface辅助特性
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124
pip install 'huggingface_hub[torch]'

# (按项目需要)安装tensorflow,及huggingface辅助特性
pip install tensorflow
pip install 'huggingface_hub[tensorflow]'


# 其他常用依赖
pip install transformers accelerate

# 项目可能有各自需要的依赖,看项目介绍去安装

注册/登录

  • 目前注册/登录必须有"科学"上网环境
  • 很多仓库下载需要权限,所以先配置token
    • 注册HuggingFace账号,并登录
    • 创建AccessToken路径:右上角用户头像 > "Settings" > "Access Tokens" > "Create new token" > "Token Type"切换到"Read" > 随意填个名字 > "Create token" > 复制下来,格式"hf_***"
  • 如下代码登录
    • 登录后,token存储在"~/.cache/huggingface/token"
    • 仅需登录(运行)一次,除非token失效
from huggingface_hub import login

token = 'hf_***'
login(token)

下载模型

  • 国内镜像:https://hf-mirror.com/
    • 主页有下载方式汇总
  • 大模型随随便便就好几G,注意磁盘空间大小

使用cli

# 安装工具
pip install huggingface_hub
# 设置镜像地址
export HF_ENDPOINT=https://hf-mirror.com


# 下载整个库
huggingface-cli download 'stabilityai/stable-diffusion-3-medium-diffusers'
huggingface-cli download 'stabilityai/stable-diffusion-3-medium-diffusers' --local-dir 'sd'
huggingface-cli download 'stabilityai/stable-diffusion-3-medium-diffusers' --local-dir 'sd' --token 'hf_****'

# 下载特定文件
huggingface-cli download 'stabilityai/stable-diffusion-3-medium-diffusers' 'xxx.safetensors'
huggingface-cli download 'stabilityai/stable-diffusion-3-medium-diffusers' 'xxx.safetensors' --local-dir 'sd'
huggingface-cli download 'stabilityai/stable-diffusion-3-medium-diffusers' 'xxx.safetensors' --local-dir 'sd' --token 'hf_****'

使用python

  • 下载
    • 未指定local_dir参数时,默认下载路径:~/.cache/huggingface/
import os
from huggingface_hub import hf_hub_download, snapshot_download

# 设置镜像地址
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'

# 下载整个仓库
snapshot_download(repo_id="stabilityai/stable-diffusion-3-medium-diffusers")
snapshot_download(repo_id="stabilityai/stable-diffusion-3-medium-diffusers", local_dir="sd")
snapshot_download(repo_id="stabilityai/stable-diffusion-3-medium-diffusers", local_dir="sd", token="hd_***")

# 下载特定文件
hf_hub_download(repo_id="stabilityai/stable-diffusion-3-medium-diffusers", filename="xxx.safetensors")
hf_hub_download(repo_id="stabilityai/stable-diffusion-3-medium-diffusers", filename="xxx.safetensors", local_dir="sd")
hf_hub_download(repo_id="stabilityai/stable-diffusion-3-medium-diffusers", filename="xxx.safetensors", local_dir="sd", token="hd_***")

示例

  • 每个项目运行都有差别,注意看项目的README
    • 一部分要加载项目中的"model_index.json"配置运行
    • 一部分使用ComfyUI运行

文生图(emilianJR/epiCRealism)

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124
pip install 'huggingface_hub[torch]'

pip install transformers accelerate diffusers
  • 下载模型
    • 默认下载路径:~/.cache/huggingface/
# 设置镜像
export HF_ENDPOINT=https://hf-mirror.com

# 下载模型
huggingface-cli download 'emilianJR/epiCRealism'
# 默认空间不够的,--local-dir参数指定下载路径,使用时替换成该路径即可
huggingface-cli download 'emilianJR/epiCRealism' --local-dir 'models/emilianJR/epiCRealism'
  • 执行
from diffusers import StableDiffusionPipeline
import torch

model_id = "emilianJR/epiCRealism"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
pipe = pipe.to("cuda")

prompt = "提示词,要用英文,这个模型中文效果差"
image = pipe(prompt).images[0]

image.save("image.png")
  • 包装Gradio使用
pip install gradio
from diffusers import StableDiffusionPipeline
import torch
import gradio as gr

model_id = "emilianJR/epiCRealism"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
pipe = pipe.to("cuda")


def generate(prompt: str):
    image = pipe(prompt).images[0]
    return image


demo = gr.Interface(fn=generate,
                    inputs=gr.Textbox(label="提示词,使用英文,中文兼容性不好"),
                    outputs=gr.Image(),
                    examples=["A girl smiling", "A boy smiling", "A dog running"])
demo.launch()

文生视频(ByteDance/AnimateDiff-Lightning)

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124
pip install 'huggingface_hub[torch]'

pip install transformers accelerate diffusers
  • 轻量文生视频,需要借助文生图模型,再生成视频
    • 文生图模型使用上述emilianJR/epiCRealism
# 设置镜像
export HF_ENDPOINT=https://hf-mirror.com

# 基础文生图模型
huggingface-cli download 'emilianJR/epiCRealism'
# 下载文生视频模型
huggingface-cli download 'ByteDance/AnimateDiff-Lightning' 'animatediff_lightning_4step_diffusers.safetensors'

# 也可以下载整个仓库,仓库包含多个级别的模型文件
huggingface-cli download 'ByteDance/AnimateDiff-Lightning'

  • 示例
    • 生成结果是gif动图
import torch
from diffusers import AnimateDiffPipeline, MotionAdapter, EulerDiscreteScheduler
from diffusers.utils import export_to_gif
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file

device = "cuda"
dtype = torch.float16

step = 4  # Options: [1,2,4,8]
repo = "ByteDance/AnimateDiff-Lightning"
ckpt = f"animatediff_lightning_{step}step_diffusers.safetensors"
base = "emilianJR/epiCRealism"  # Choose to your favorite base model.

adapter = MotionAdapter().to(device, dtype)
adapter.load_state_dict(load_file(hf_hub_download(repo ,ckpt), device=device))
pipe = AnimateDiffPipeline.from_pretrained(base, motion_adapter=adapter, torch_dtype=dtype).to(device)
pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing", beta_schedule="linear")

output = pipe(prompt="A girl smiling", guidance_scale=1.0, num_inference_steps=step)
export_to_gif(output.frames[0], "animation.gif")

文生图(stable-diffusion-3)

pip install huggingface_hub

# 安装PyTorch的CUDA(GPU)版,安装命令参考PyTorch官网:https://pytorch.org/
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124
# 或者Torch的CPU版,建议上GPU,CPU根本跑不动
pip install 'huggingface_hub[torch]'

# 其他依赖
pip install transformers
pip install accelerate
pip install diffusers
pip install sentencepiece
pip install protobuf
  • 下载模型
    • 默认下载路径:~/.cache/huggingface/
    • --local-dir指定下载目录,运行代码时将模型设置为相同目录即可
# 设置环境变了
export HF_ENDPOINT=https://hf-mirror.com

# 下载整个库
huggingface-cli download 'stabilityai/stable-diffusion-3-medium-diffusers'
huggingface-cli download 'stabilityai/stable-diffusion-3-medium-diffusers' --local-dir 'sd'
  • 运行代码
    • 提示词使用英文,中文效果很差
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained("stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16)
# pipe = StableDiffusion3Pipeline.from_pretrained("sd", torch_dtype=torch.float16) # 指定目录

pipe = pipe.to("cuda")

image = pipe("A cat holding a sign that says hello world",
             negative_prompt="",
             num_inference_steps=28,
             guidance_scale=7.0).images[0]

# 保存成图片
image.save('cat.jpg')

  • GPU显存小于16GB报错
torch.OutOfMemoryError: CUDA out of memory. 
Tried to allocate 512.00 MiB. GPU 0 has a total capacity of 11.00 GiB of which 0 bytes is free. 
Of the allocated memory 16.80 GiB is allocated by PyTorch, and 574.00 MiB is reserved by PyTorch but unallocated. 
If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. 
See documentation for Memory Management  (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)

可能遇到问题

报错缺失'fbgemm.dll'

  • 报错内容
OSError: [WinError 126] 找不到指定的模块。 Error loading "...\site-packages\torch\lib\fbgemm.dll" or one of its dependencies.
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,490评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,581评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,830评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,957评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,974评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,754评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,464评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,847评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,995评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,137评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,819评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,482评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,023评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,149评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,409评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,086评论 2 355

推荐阅读更多精彩内容