Project Icon

ml-stable-diffusion

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

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

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.

System Requirements

Details (Click to expand)

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

Performance Benchmarks

Details (Click to expand)

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 (Click to expand)
  • 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.

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 (Click to expand)
  • 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.

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 (Click to expand)
  • 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.

Weight Compression (6-bits and higher)

Details (Click to expand)

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
16-bitcpuAndNeuralEngine
16-bitcpuAndGPU

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:

Advanced Weight Compression (Lower than 6-bits)

Details (Click to expand)

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

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号