ml-stable-diffusion

ml-stable-diffusion

在Apple设备上实现高效稳定的AI图像生成

ml-stable-diffusion是一个开源项目,旨在优化Stable Diffusion模型在Apple设备上的运行。它包含用于模型转换的Python工具和用于iOS/macOS应用集成的Swift包。通过权重压缩等技术,该项目显著提升了性能和内存效率,使开发者能够在Apple平台应用中实现高质量的AI图像生成。

Core MLStable DiffusionAI绘图模型转换性能优化Github开源项目

Core ML Stable Diffusion

Run Stable Diffusion on Apple Silicon with Core ML

[Blog Post] [BibTeX]

This repository comprises:

  • python_coreml_stable_diffusion, a Python package for converting PyTorch models to Core ML format and performing image generation with Hugging Face diffusers in Python
  • StableDiffusion, a Swift package that developers can add to their Xcode projects as a dependency to deploy image generation capabilities in their apps. The Swift package relies on the Core ML model files generated by python_coreml_stable_diffusion

If you run into issues during installation or runtime, please refer to the FAQ section. Please refer to the System Requirements section before getting started.

<img src="assets/readme_reel.png">

<a name="system-requirements"></a> System Requirements

<details> <summary> Details (Click to expand) </summary>

Model Conversion:

macOSPythoncoremltools
13.13.87.0

Project Build:

macOSXcodeSwift
13.114.35.8

Target Device Runtime:

macOSiPadOS, iOS
13.116.2

Target Device Runtime (With Memory Improvements):

macOSiPadOS, iOS
14.017.0

Target Device Hardware Generation:

MaciPadiPhone
M1M1A14
</details>

<a name="performance-benchmark"></a> Performance Benchmarks

<details> <summary> Details (Click to expand) </summary>

stabilityai/stable-diffusion-2-1-base (512x512)

Device--compute-unit--attention-implementationEnd-to-End Latency (s)Diffusion Speed (iter/s)
iPhone 12 MiniCPU_AND_NESPLIT_EINSUM_V218.5*1.44
iPhone 12 Pro MaxCPU_AND_NESPLIT_EINSUM_V215.41.45
iPhone 13CPU_AND_NESPLIT_EINSUM_V210.8*2.53
iPhone 13 Pro MaxCPU_AND_NESPLIT_EINSUM_V210.42.55
iPhone 14CPU_AND_NESPLIT_EINSUM_V28.62.57
iPhone 14 Pro MaxCPU_AND_NESPLIT_EINSUM_V27.92.69
iPad Pro (M1)CPU_AND_NESPLIT_EINSUM_V211.22.19
iPad Pro (M2)CPU_AND_NESPLIT_EINSUM_V27.03.07
<details> <summary> Details (Click to expand) </summary>
  • This benchmark was conducted by Apple and Hugging Face using public beta versions of iOS 17.0, iPadOS 17.0 and macOS 14.0 Seed 8 in August 2023.
  • The performance data was collected using the benchmark branch of the Diffusers app
  • Swift code is not fully optimized, introducing up to ~10% overhead unrelated to Core ML model execution.
  • The median latency value across 5 back-to-back end-to-end executions are reported
  • The image generation procedure follows the standard configuration: 20 inference steps, 512x512 output image resolution, 77 text token sequence length, classifier-free guidance (batch size of 2 for unet).
  • The actual prompt length does not impact performance because the Core ML model is converted with a static shape that computes the forward pass for all of the 77 elements (tokenizer.model_max_length) in the text token sequence regardless of the actual length of the input text.
  • Weights are compressed to 6 bit precision. Please refer to this section for details.
  • Activations are in float16 precision for both the GPU and the Neural Engine.
  • * indicates that the reduceMemory option was enabled which loads and unloads models just-in-time to avoid memory shortage. This added up to 2 seconds to the end-to-end latency.
  • In the benchmark table, we report the best performing --compute-unit and --attention-implementation values per device. The former does not modify the Core ML model and can be applied during runtime. The latter modifies the Core ML model. Note that the best performing compute unit is model version and hardware-specific.
  • Note that the performance optimizations in this repository (e.g. --attention-implementation) are generally applicable to Transformers and not customized to Stable Diffusion. Better performance may be observed upon custom kernel tuning. Therefore, these numbers do not represent peak HW capability.
  • Performance may vary across different versions of Stable Diffusion due to architecture changes in the model itself. Each reported number is specific to the model version mentioned in that context.
  • Performance may vary due to factors like increased system load from other applications or suboptimal device thermal state.
</details>

stabilityai/stable-diffusion-xl-base-1.0-ios (768x768)

Device--compute-unit--attention-implementationEnd-to-End Latency (s)Diffusion Speed (iter/s)
iPhone 12 ProCPU_AND_NESPLIT_EINSUM116*0.50
iPhone 13 Pro MaxCPU_AND_NESPLIT_EINSUM86*0.68
iPhone 14 Pro MaxCPU_AND_NESPLIT_EINSUM77*0.83
iPhone 15 Pro MaxCPU_AND_NESPLIT_EINSUM310.85
iPad Pro (M1)CPU_AND_NESPLIT_EINSUM360.69
iPad Pro (M2)CPU_AND_NESPLIT_EINSUM270.98
<details> <summary> Details (Click to expand) </summary>
  • This benchmark was conducted by Apple and Hugging Face using iOS 17.0.2 and iPadOS 17.0.2 in September 2023.
  • The performance data was collected using the benchmark branch of the Diffusers app
  • The median latency value across 5 back-to-back end-to-end executions are reported
  • The image generation procedure follows this configuration: 20 inference steps, 768x768 output image resolution, 77 text token sequence length, classifier-free guidance (batch size of 2 for unet).
  • Unet.mlmodelc is compressed to 4.04 bit precision following the Mixed-Bit Palettization algorithm recipe published here
  • All models except for Unet.mlmodelc are compressed to 16 bit precision
  • madebyollin/sdxl-vae-fp16-fix by @madebyollin was used as the source PyTorch model for VAEDecoder.mlmodelc in order to enable float16 weight and activation quantization for the VAE model.
  • --attention-implementation SPLIT_EINSUM is chosen in lieu of SPLIT_EINSUM_V2 due to the prohibitively long compilation time of the latter
  • * indicates that the reduceMemory option was enabled which loads and unloads models just-in-time to avoid memory shortage. This added significant overhead to the end-to-end latency. Note that end-to-end latency difference between iPad Pro (M1) and iPhone 13 Pro Max despite identical diffusion speed.
  • The actual prompt length does not impact performance because the Core ML model is converted with a static shape that computes the forward pass for all of the 77 elements (tokenizer.model_max_length) in the text token sequence regardless of the actual length of the input text.
  • In the benchmark table, we report the best performing --compute-unit and --attention-implementation values per device. The former does not modify the Core ML model and can be applied during runtime. The latter modifies the Core ML model. Note that the best performing compute unit is model version and hardware-specific.
  • Note that the performance optimizations in this repository (e.g. --attention-implementation) are generally applicable to Transformers and not customized to Stable Diffusion. Better performance may be observed upon custom kernel tuning. Therefore, these numbers do not represent peak HW capability.
  • Performance may vary across different versions of Stable Diffusion due to architecture changes in the model itself. Each reported number is specific to the model version mentioned in that context.
  • Performance may vary due to factors like increased system load from other applications or suboptimal device thermal state.
</details>

stabilityai/stable-diffusion-xl-base-1.0 (1024x1024)

Device--compute-unit--attention-implementationEnd-to-End Latency (s)Diffusion Speed (iter/s)
MacBook Pro (M1 Max)CPU_AND_GPUORIGINAL460.46
MacBook Pro (M2 Max)CPU_AND_GPUORIGINAL370.57
Mac Studio (M1 Ultra)CPU_AND_GPUORIGINAL250.89
Mac Studio (M2 Ultra)CPU_AND_GPUORIGINAL201.11
<details> <summary> Details (Click to expand) </summary>
  • This benchmark was conducted by Apple and Hugging Face using public beta versions of iOS 17.0, iPadOS 17.0 and macOS 14.0 in July 2023.
  • The performance data was collected by running the StableDiffusion Swift pipeline.
  • The median latency value across 3 back-to-back end-to-end executions are reported
  • The image generation procedure follows the standard configuration: 20 inference steps, 1024x1024 output image resolution, classifier-free guidance (batch size of 2 for unet).
  • Weights and activations are in float16 precision
  • Performance may vary across different versions of Stable Diffusion due to architecture changes in the model itself. Each reported number is specific to the model version mentioned in that context.
  • Performance may vary due to factors like increased system load from other applications or suboptimal device thermal state. Given these factors, we do not report sub-second variance in latency.
</details> </details>

<a name="compression-6-bits-and-higher"></a> Weight Compression (6-bits and higher)

<details> <summary> Details (Click to expand) </summary>

coremltools-7.0 supports advanced weight compression techniques for pruning, palettization and linear 8-bit quantization. For these techniques, coremltools.optimize.torch.* includes APIs that require fine-tuning to maintain accuracy at higher compression rates whereas coremltools.optimize.coreml.* includes APIs that are applied post-training and are data-free.

We demonstrate how data-free post-training palettization implemented in coremltools.optimize.coreml.palettize_weights enables us to achieve greatly improved performance for Stable Diffusion on mobile devices. This API implements the Fast Exact k-Means algorithm for optimal weight clustering which yields more accurate palettes. Using --quantize-nbits {2,4,6,8} during conversion is going to apply this compression to the unet and text_encoder models.

For best results, we recommend training-time palettization: coremltools.optimize.torch.palettization.DKMPalettizer if fine-tuning your model is feasible. This API implements the Differentiable k-Means (DKM) learned palettization algorithm. In this exercise, we stick to post-training palettization for the sake of simplicity and ease of reproducibility.

The Neural Engine is capable of accelerating models with low-bit palettization: 1, 2, 4, 6 or 8 bits. With iOS 17 and macOS 14, compressed weights for Core ML models can be just-in-time decompressed during runtime (as opposed to ahead-of-time decompression upon load) to match the precision of activation tensors. This yields significant memory savings and enables models to run on devices with smaller RAM (e.g. iPhone 12 Mini). In addition, compressed weights are faster to fetch from memory which reduces the latency of memory bandwidth-bound layers. The just-in-time decompression behavior depends on the compute unit, layer type and hardware generation.

Weight Precision--compute-unitstabilityai/stable-diffusion-2-1-base generating "a high quality photo of a surfing dog"
6-bitcpuAndNeuralEngine<img src="assets/palette6_cpuandne_readmereel.png">
16-bitcpuAndNeuralEngine<img src="assets/float16_cpuandne_readmereel.png">
16-bitcpuAndGPU<img src="assets/float16_gpu_readmereel.png">

Note that there are minor differences across 16-bit (float16) and 6-bit results. These differences are comparable to the differences across float16 and float32 or differences across compute units as exemplified above. We recommend a minimum of 6 bits for palettizing Stable Diffusion. Smaller number of bits (1, 2 and 4) will require either fine-tuning or advanced palettization techniques such as MBP.

Resources:

</details>

<a name="compression-lower-than-6-bits"></a> Advanced Weight Compression (Lower than 6-bits)

<details> <summary> Details (Click to expand) </summary>

This section describes an advanced compression algorithm called Mixed-Bit Palettization (MBP) built on top of the Post-Training Weight Palettization tools and using the Weights Metadata API from coremltools.

MBP builds a per-layer "palettization

编辑推荐精选

Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

下拉加载更多