今天Apple官方支持了這個庫,所以特意下載下來試試看,效果還不錯,M芯片在深度學習領(lǐng)域第一次給人驚喜了。
https://machinelearning.apple.com/research/stable-diffusion-coreml-apple-silicon
1.win使用
安裝
分享一下一個有意思的庫的安裝經(jīng)歷。
最近才發(fā)現(xiàn)有大神將這種生成模型給開源了,之前一直關(guān)注DELL這種的大型模型,被ai這種天馬行空的想象力給驚艷到。但他們大都只是api接口,現(xiàn)在貧民百姓也可以自己擁有。<笑臉>
下載庫
去github網(wǎng)址下載 - > https://github.com/CompVis/stable-diffusion
git clone https://github.com/CompVis/stable-diffusion.git
配置環(huán)境和文件
簡單的操作,在下載后的文件夾下直接輸下面兩個
conda env create -f environment.yaml
conda activate ldm
就配置好了。
或者就像我一樣傻傻的報錯一個安裝一個。
我本身的環(huán)境是pytorch torchvision
pip install transformers==4.19.2 diffusers invisible-watermark
pip install -e .
pip install OmegaConf einops taming-transformers pytorch-lighnting clip kornia
問題
第一個問題官網(wǎng)是有說明的,但就是這個下載地址藏得很深不好找。
我也是找了一會才找到https://huggingface.co/CompVis/stable-diffusion-v-1-4-original,把這個sd-v1-4.ckpt文件下載下來(隨便哪個都行),大概四個G。
下載模型文件放置到這個文件夾下,就是上面官方說明的那個位置,命名成model.ckpt。
運行下面的代碼,不出意外會報錯。
python scripts/txt2img.py --prompt "a photograph of an astronaut riding a horse" --plms
問題好像是原作者修改了這個庫,將你的quantize.py(報錯的信息里包含文件所在的絕對路徑)文件替換成這個網(wǎng)址的文件
https://github.com/CompVis/taming-transformers/blob/master/taming/modules/vqvae/quantize.py
再運行一次又報錯
我只是12g的3060,看來這不是一般人能玩得起的-_-
?。。。。。。。。。。。。。。?!
現(xiàn)在有一個簡單的辦法了,感謝數(shù)學系之恥的建議,直接降精度就可以釋放顯存了。
?。。。。。。。。。。。。。。?!
如下修改txt2img.py文件第244行
效果 -->
或者接下去看比較復(fù)雜的方法!
不知道需要多大的內(nèi)存才可以,網(wǎng)上找到方法是用優(yōu)化的庫。網(wǎng)上還有一種辦法說注釋掉什么安全檢查的我試了沒有變化。
https://github.com/basujindal/stable-diffusion
下載完后在新的庫上也是需要安裝一些環(huán)境,在新的文件夾下運行下面的安裝代碼
pip install -e .
優(yōu)化的庫代碼放在optimizedSD文件夾下,也保留了之前的源代碼,不要搞錯了。
重新安裝一下這個優(yōu)化庫的環(huán)境,將ckpt放到對應(yīng)的位置。
python optimizedSD/optimized_txt2img.py --prompt "Cyberpunk style image of a Tesla car reflection in rain" --H 512 --W 512 --seed 27 --n_iter 2 --n_samples 5 --ddim_steps 50
運行后報這個錯。
查了一下,好像是最近優(yōu)化的作者也換了一個庫
https://github.com/basujindal/stable-diffusion/issues/175
用下面的辦法就能解決了。
pip install git+https://github.com/crowsonkb/k-diffusion.git
然后打開編輯optimizedSD/ddpm.py文件,將from samplers…改成上面圖片的三個from k_diffusion…
然后貧窮的顯卡的電腦也就可以跑了,不說了要努力搬磚買24g的顯卡了。
實測效果 -->
2.mac使用
安裝
https://github.com/apple/ml-stable-diffusion
git clone https://github.com/apple/ml-stable-diffusion
pip install -e . #來到下載好的文件夾下面運行
登陸hugging face
https://huggingface.co
沒有的話直接注冊,注冊好了以后點擊token生成https://huggingface.co/settings/tokens,然后復(fù)制token
接下去命令行輸入指令,按提示輸入
huggingface-cli login
運行指令
在文件夾下運行,順便創(chuàng)建一個放置ml模型的文件夾,替換下面的-o
python -m python_coreml_stable_diffusion.torch2coreml --convert-unet --convert-text-encoder --convert-vae-decoder --convert-safety-checker -o ./output_ml
官方還給了一個api
--model-version runwayml/stable-diffusion-v1-5 #可以指定其他版本的diffusion模型,默認是 CompVis/stable-diffusion-v1-4
--bundle-resources-for-swift-cli #將ml文件整理成一個swift包,python生成不需要使用
--chunk-unet #ios和ipados部署需要,后面兩個之后有機會我想去嘗試一下在真機上的部署
--attention-implementation #在Apple芯片上的npu上實現(xiàn)
如果想部署手機和平板可以參考下面這個
python -m python_coreml_stable_diffusion.torch2coreml --convert-unet --convert-text-encoder --convert-vae-decoder --convert-safety-checker -o ./sd2_ml --chunk-unet --model-version stabilityai/stable-diffusion-2-1-base --bundle-resources-for-swift-cli
大約20幾分鐘吧,會生成這些文件
接著還是在ml-stable-diffusion的文件夾下運行,對了再創(chuàng)建一個放圖片的文件夾。
python -m python_coreml_stable_diffusion.pipeline --prompt "a photo of an astronaut riding a horse on mars" -i ./output_ml -o ./output_image --compute-unit ALL --seed 93
swift用下面這個
swift run StableDiffusionSample "A photo of a little girl walking on the beach with the Jenny Turtle" --resource-path ./sd2_ml/Resources/ --seed 93 --output-path ./output_image
--model-version #如果前面修改了這個也要修改
--num-inference-steps #默認推理50次,用這個可以自定義次數(shù)
我是M2的MacBook Air,我參考了官方的基準指南--compute-unit
選擇了CPU_AND_NE
,大概21秒一個推理還是蠻快的(python),swift 2秒左右一個step,快了很多。
就是從上圖中我們可以看到似乎無后綴的M芯片由于GPU數(shù)量較少吧我猜--compute-unit
都推薦選CPU_AND_NE
,pro系列芯片選ALL
,以上選CPU_AND_GPU
。--attention-implementation
直接看GPU核心數(shù),小于等于16個使用SPLLIT_EINSUM
,就是默認的其實啥也不用加。大于16個使用ORIGINAL
。我猜因為M芯片是16核NPU的,GPU核心數(shù)比NPU小那肯定用NPU,GPU核心數(shù)大大超過NPU,那還是GPU的效率更高吧。
3.iphone&ipad部署
打開Xcode,導(dǎo)入庫和上面生成的ML文件文章來源:http://www.zghlxwxcb.cn/news/detail-781239.html
import SwiftUI
import StableDiffusion
import CoreML
struct ContentView: View {
@State var prompt: String = "a photo of an astronaut riding a horse on mars"
@State var step = 10
@State var seed = 100
@State var image: CGImage?
@State var progress = 0.0
@State var generating = false
@State var booting = true
@State var pipeline: StableDiffusionPipeline?
private let disableSafety = false
var body: some View {
VStack {
if booting {
Text("Initializing...")
} else {
if let image {
Image(uiImage: UIImage(cgImage: image))
.resizable()
.scaledToFit()
}
if generating {
ProgressView(value: progress)
}
if !generating {
TextField("Prompt", text: $prompt)
Stepper(value: $step, in: 1...100) {
Text("steps: \(step)")
}
Stepper(value: $seed, in: 0...10000) {
Text("Seed: \(seed)")
}
Button("Generate") {
progress = 0.0
image = nil
generating = true
Task.detached(priority: .high) {
var images: [CGImage?]?
do {
print("generate")
images = try pipeline?.generateImages(prompt: prompt, stepCount: step,seed: seed, disableSafety: disableSafety, progressHandler: { progress in
print("test")
self.progress = Double(progress.step) / Double(step)
if let image = progress.currentImages.first {
self.image = image
}
return true
})
} catch let error {
print(error.localizedDescription)
}
print("finish")
if let image = images?.first {
self.image = image
}
generating = false
}
}
}
}
}
.padding()
.onAppear{
Task.detached(priority: .high) {
do {
print(os_proc_available_memory())
guard let path = Bundle.main.path(forResource: "CoreMLModels", ofType: nil, inDirectory: nil) else {
fatalError("Fatal error: failed to find the CoreML models.")
}
let resourceURL = URL(fileURLWithPath: path)
let config = MLModelConfiguration()
config.computeUnits = .cpuAndNeuralEngine
pipeline = try StableDiffusionPipeline(resourcesAt: resourceURL, configuration: config,reduceMemory: true)
try pipeline?.loadResources()
print("initialized pipeline")
} catch let error {
print("error initializing pipeline")
print(error.localizedDescription)
}
booting = false
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
在iPad和Mac上建議config.computeUnits = .cpuAndNeuralEngine
。如果要繼續(xù)在iPhone上部署的話改為這個config.computeUnits = .cpuAndGPU
,然后來到Signing界面,點擊Capability,選擇Increased Memory Limit。這樣就可以在iPhone真機上運行了。這個項目在iPhone真機上需要3GB多一點的內(nèi)存,我是iPhone 14pro,程序默認可用內(nèi)存也是3GB多一點剛好殺死。所以通過Increased Memory Limit將可用內(nèi)存提升至4GB左右才可以運行。另外,即使提升了內(nèi)存使用神經(jīng)引擎還是會抱內(nèi)存錯誤,只有用GPU才可以,iPad air5沒有這種報錯兩個都可。GPU的運行速度是比神經(jīng)引擎慢一點的,但是一臺手機可以本地運行diffusion還是蠻酷的。文章來源地址http://www.zghlxwxcb.cn/news/detail-781239.html
到了這里,關(guān)于Stable diffusion安裝踩坑(win&Mac&iOS)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!