Stable diffusion安装踩坑(winMaciOS)
创始人
2024-06-03 16:36:06
0

今天Apple官方支持了这个库,所以特意下载下来试试看,效果还不错,M芯片在深度学习领域第一次给人惊喜了。
https://machinelearning.apple.com/research/stable-diffusion-coreml-apple-silicon

1.win使用

安装

分享一下一个有意思的库的安装经历。
最近才发现有大神将这种生成模型给开源了,之前一直关注DELL这种的大型模型,被ai这种天马行空的想象力给惊艳到。但他们大都只是api接口,现在贫民百姓也可以自己拥有。<笑脸>

下载库

去github网址下载 - > https://github.com/CompVis/stable-diffusion

git clone https://github.com/CompVis/stable-diffusion.git

配置环境和文件

简单的操作,在下载后的文件夹下直接输下面两个

conda env create -f environment.yaml
conda activate ldm

就配置好了。
或者就像我一样傻傻的报错一个安装一个。
我本身的环境是pytorch torchvision

pip install transformers==4.19.2 diffusers invisible-watermark
pip install -e .
pip install OmegaConf einops taming-transformers pytorch-lighnting clip kornia

问题

第一个问题官网是有说明的,但就是这个下载地址藏得很深不好找。
在这里插入图片描述
我也是找了一会才找到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(报错的信息里包含文件所在的绝对路径)文件替换成这个网址的文件
https://github.com/CompVis/taming-transformers/blob/master/taming/modules/vqvae/quantize.py
在这里插入图片描述

再运行一次又报错
在这里插入图片描述
我只是12g的3060,看来这不是一般人能玩得起的-_-
!!!!!!!!!!!!!!!!
现在有一个简单的办法了,感谢数学系之耻的建议,直接降精度就可以释放显存了。
!!!!!!!!!!!!!!!!
如下修改txt2img.py文件第244行
在这里插入图片描述
效果 -->
在这里插入图片描述

或者接下去看比较复杂的方法!
不知道需要多大的内存才可以,网上找到方法是用优化的库。网上还有一种办法说注释掉什么安全检查的我试了没有变化。
https://github.com/basujindal/stable-diffusion
下载完后在新的库上也是需要安装一些环境,在新的文件夹下运行下面的安装代码

pip install -e .

在这里插入图片描述
优化的库代码放在optimizedSD文件夹下,也保留了之前的源代码,不要搞错了。
重新安装一下这个优化库的环境,将ckpt放到对应的位置。

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

运行后报这个错。
在这里插入图片描述

查了一下,好像是最近优化的作者也换了一个库
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,然后复制token
在这里插入图片描述

接下去命令行输入指令,按提示输入

huggingface-cli login

在这里插入图片描述

运行指令

在文件夹下运行,顺便创建一个放置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上实现

如果想部署手机和平板可以参考下面这个

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的文件夹下运行,对了再创建一个放图片的文件夹。

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次,用这个可以自定义次数

我是M2的MacBook Air,我参考了官方的基准指南--compute-unit 选择了CPU_AND_NE,大概21秒一个推理还是蛮快的(python),swift 2秒左右一个step,快了很多。
在这里插入图片描述

在这里插入图片描述

就是从上图中我们可以看到似乎无后缀的M芯片由于GPU数量较少吧我猜--compute-unit 都推荐选CPU_AND_NE,pro系列芯片选ALL,以上选CPU_AND_GPU
--attention-implementation 直接看GPU核心数,小于等于16个使用SPLLIT_EINSUM,就是默认的其实啥也不用加。大于16个使用ORIGINAL。我猜因为M芯片是16核NPU的,GPU核心数比NPU小那肯定用NPU,GPU核心数大大超过NPU,那还是GPU的效率更高吧。
在这里插入图片描述

3.iphone&ipad部署

打开Xcode,导入库和上面生成的ML文件
在这里插入图片描述

import SwiftUI
import StableDiffusion
import CoreMLstruct 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 = falsevar 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.0image = nilgenerating = trueTask.detached(priority: .high) {var images: [CGImage?]?do {print("generate")images = try pipeline?.generateImages(prompt: prompt, stepCount: step,seed: seed, disableSafety: disableSafety, progressHandler: { progress inprint("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 = .cpuAndNeuralEnginepipeline = 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。如果要继续在iPhone上部署的话改为这个config.computeUnits = .cpuAndGPU,然后来到Signing界面,点击Capability,选择Increased Memory Limit。这样就可以在iPhone真机上运行了。这个项目在iPhone真机上需要3GB多一点的内存,我是iPhone 14pro,程序默认可用内存也是3GB多一点刚好杀死。所以通过Increased Memory Limit将可用内存提升至4GB左右才可以运行。另外,即使提升了内存使用神经引擎还是会抱内存错误,只有用GPU才可以,iPad air5没有这种报错两个都可。GPU的运行速度是比神经引擎慢一点的,但是一台手机可以本地运行diffusion还是蛮酷的。
在这里插入图片描述

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...
有效的括号 一、题目 给定一个只包括 '(',')','{','}'...
【Ctfer训练计划】——(三... 作者名:Demo不是emo  主页面链接:主页传送门 创作初心ÿ...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
带头循环双向链表来咯!!! 前言:继上文,我们了解了结构最简单的一种链表---单链表那么我们今天就来...