HuggingFace

  • Bilibili視頻:白嫖AI大模型-HuggingFace
  • 官網:https://huggingface.co/
  • 網絡
    • 大部分操作使用hf-mirror鏡像可以完成
    • 目前唯一需要"科學"網絡環(huán)境的是登錄及獲取Token(下載模型使用)衩匣,且Token只需用配置一次金麸,就無需再登錄

起步

安裝依賴

  • torch/tensorflow根據(jù)不同項目需要安裝
# 安裝
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

# 項目可能有各自需要的依賴纺裁,看項目介紹去安裝

注冊/登錄

  • 目前注冊/登錄必須有"科學"上網環(huán)境
  • 很多倉庫下載需要權限诫肠,所以先配置token
    • 注冊HuggingFace賬號,并登錄
    • 創(chuàng)建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

  • 使用方法看官網介紹:https://huggingface.co/docs/huggingface_hub/guides/cli
    • --local-dir: 下載到本地的目錄丧鸯,未指定時,默認下載路徑:~/.cache/huggingface/
    • --token: 鑒權token嫩絮,使用上述方法登錄過的不需要該參數(shù)
# 安裝工具
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參數(shù)時丛肢,默認下載路徑:~/.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參數(shù)指定下載路徑蜂怎,使用時替換成該路徑即可
huggingface-cli download 'emilianJR/epiCRealism' --local-dir 'models/emilianJR/epiCRealism'
  • 執(zhí)行
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指定下載目錄犀被,運行代碼時將模型設置為相同目錄即可
# 設置環(huán)境變了
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.
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末寡键,一起剝皮案震驚了整個濱河市掀泳,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌西轩,老刑警劉巖员舵,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異藕畔,居然都是意外死亡马僻,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門注服,熙熙樓的掌柜王于貴愁眉苦臉地迎上來韭邓,“玉大人,你說我怎么就攤上這事溶弟∨纾” “怎么了?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵辜御,是天一觀的道長鸭你。 經常有香客問我,道長我抠,這世上最難降的妖魔是什么苇本? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任袜茧,我火速辦了婚禮菜拓,結果婚禮上,老公的妹妹穿的比我還像新娘笛厦。我一直安慰自己纳鼎,他們只是感情好,可當我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布裳凸。 她就那樣靜靜地躺著贱鄙,像睡著了一般。 火紅的嫁衣襯著肌膚如雪姨谷。 梳的紋絲不亂的頭發(fā)上逗宁,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天,我揣著相機與錄音梦湘,去河邊找鬼瞎颗。 笑死件甥,一個胖子當著我的面吹牛,可吹牛的內容都是我干的哼拔。 我是一名探鬼主播引有,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼倦逐!你這毒婦竟也來了譬正?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤檬姥,失蹤者是張志新(化名)和其女友劉穎曾我,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體健民,經...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡您单,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了荞雏。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片虐秦。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖凤优,靈堂內的尸體忽然破棺而出悦陋,到底是詐尸還是另有隱情,我是刑警寧澤筑辨,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布俺驶,位于F島的核電站,受9級特大地震影響棍辕,放射性物質發(fā)生泄漏暮现。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一楚昭、第九天 我趴在偏房一處隱蔽的房頂上張望栖袋。 院中可真熱鬧,春花似錦抚太、人聲如沸塘幅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽电媳。三九已至,卻和暖如春庆亡,著一層夾襖步出監(jiān)牢的瞬間匾乓,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工又谋, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留拼缝,地道東北人括享。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像珍促,于是被迫代替她去往敵國和親铃辖。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內容