Skip to content

Commit a4238a3

Browse files
atiorhmsiracusa
andcommitted
README improvements and reduceMemory option in Swift
Co-authored-by: msiracusa <[email protected]>
1 parent 016d071 commit a4238a3

File tree

10 files changed

+387
-100
lines changed

10 files changed

+387
-100
lines changed

README.md

Lines changed: 69 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ This repository comprises:
99
- `python_coreml_stable_diffusion`, a Python package for converting PyTorch models to Core ML format and performing image generation with Hugging Face [diffusers](https://github.com/huggingface/diffusers) in Python
1010
- `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`
1111

12-
If you run into issues during installation or runtime, please refer to the [FAQ](#FAQ) section.
12+
If you run into issues during installation or runtime, please refer to the [FAQ](#faq) section. Please refer to the [System Requirements](#system-requirements) section before getting started.
1313

1414

1515
## <a name="example-results"></a> Example Results
@@ -25,6 +25,13 @@ M2 MacBook Air 8GB Latency (s) | 18 | 23 | 23 |
2525

2626
Please see [Important Notes on Performance Benchmarks](#important-notes-on-performance-benchmarks) section for details.
2727

28+
## <a name="system-requirements"></a> System Requirements
29+
30+
The following is recommended to use all the functionality in this repository:
31+
32+
Python | macOS | Xcode | iPadOS, iOS |
33+
:------:|:------:|:------:|:------:|
34+
3.8 | 13.1 | 14.2 | 16.2 |
2835

2936
## <a name="converting-models-to-coreml"></a> Converting Models to Core ML
3037

@@ -50,7 +57,7 @@ pip install -e .
5057
python -m python_coreml_stable_diffusion.torch2coreml --convert-unet --convert-text-encoder --convert-vae-decoder --convert-safety-checker -o <output-mlpackages-directory>
5158
```
5259

53-
**WARNING:** This command will download several GB worth of PyTorch checkpoints from Hugging Face.
60+
**WARNING:** This command will download several GB worth of PyTorch checkpoints from Hugging Face. Please ensure that you are on Wi-Fi and have enough disk space.
5461

5562
This generally takes 15-20 minutes on an M1 MacBook Pro. Upon successful execution, the 4 neural network models that comprise Stable Diffusion will have been converted from PyTorch to Core ML (`.mlpackage`) and saved into the specified `<output-mlpackages-directory>`. Some additional notable arguments:
5663

@@ -59,9 +66,9 @@ This generally takes 15-20 minutes on an M1 MacBook Pro. Upon successful executi
5966

6067
- `--bundle-resources-for-swift-cli`: Compiles all 4 models and bundles them along with necessary resources for text tokenization into `<output-mlpackages-directory>/Resources` which should provided as input to the Swift package. This flag is not necessary for the diffusers-based Python pipeline.
6168

62-
- `--chunk-unet`: Splits the Unet model in two approximately equal chunks (each with less than 1GB of weights) for mobile-friendly deployment. This is **required** for ANE deployment on iOS and iPadOS. This is not required for macOS. Swift CLI is able to consume both the chunked and regular versions of the Unet model but prioritizes the former. Note that chunked unet is not compatible with the Python pipeline because Python pipeline is intended for macOS only. Chunking is for on-device deployment with Swift only.
69+
- `--chunk-unet`: Splits the Unet model in two approximately equal chunks (each with less than 1GB of weights) for mobile-friendly deployment. This is **required** for Neural Engine deployment on iOS and iPadOS. This is not required for macOS. Swift CLI is able to consume both the chunked and regular versions of the Unet model but prioritizes the former. Note that chunked unet is not compatible with the Python pipeline because Python pipeline is intended for macOS only. Chunking is for on-device deployment with Swift only.
6370

64-
- `--attention-implementation`: Defaults to `SPLIT_EINSUM` which is the implementation described in [Deploying Transformers on the Apple Neural Engine](https://machinelearning.apple.com/research/neural-engine-transformers). `--attention-implementation ORIGINAL` will switch to an alternative that should be used for non-ANE deployment. Please refer to the [Performance Benchmark](#performance-benchmark) section for further guidance.
71+
- `--attention-implementation`: Defaults to `SPLIT_EINSUM` which is the implementation described in [Deploying Transformers on the Apple Neural Engine](https://machinelearning.apple.com/research/neural-engine-transformers). `--attention-implementation ORIGINAL` will switch to an alternative that should be used for CPU or GPU deployment. Please refer to the [Performance Benchmark](#performance-benchmark) section for further guidance.
6572

6673
- `--check-output-correctness`: Compares original PyTorch model's outputs to final Core ML model's outputs. This flag increases RAM consumption significantly so it is recommended only for debugging purposes.
6774

@@ -86,27 +93,30 @@ Please refer to the help menu for all available arguments: `python -m python_cor
8693

8794
</details>
8895

89-
## Image Generation with Swift
96+
## <a name="image-gen-swift"></a> Image Generation with Swift
9097

9198
<details>
9299
<summary> Click to expand </summary>
93100

94101
### <a name="swift-requirements"></a> System Requirements
95-
Building the Swift projects require:
96-
- macOS 13 or newer
97-
- Xcode 14.1 or newer with command line tools installed. Please check [developer.apple.com](https://developer.apple.com/download/all/?q=xcode) for the latest version.
98-
- Core ML models and tokenization resources. Please see `--bundle-resources-for-swift-cli` from the [Converting Models to Core ML](#converting-models-to-coreml) section above
99-
100-
If deploying this model to:
101-
- iPhone
102-
- iOS 16.2 or newer
103-
- iPhone 12 or newer
104-
- iPad
105-
- iPadOS 16.2 or newer
106-
- M1 or newer
107-
- Mac
108-
- macOS 13.1 or newer
109-
- M1 or newer
102+
103+
**Building** (recommended):
104+
105+
- Xcode 14.2
106+
- Command Line Tools for Xcode 14.2
107+
108+
Check [developer.apple.com](https://developer.apple.com/download/all/?q=xcode) for the latest versions.
109+
110+
**Running** (minimum):
111+
112+
| Mac | iPad\* | iPhone\* |
113+
|:------:|:------:|:------:|
114+
| macOS 13.1 | iPadOS 16.2 | iOS 16.2 |
115+
| M1 | M1 | iPhone 12 Pro |
116+
117+
You will also need the resources generated by the `--bundle-resources-for-swift-cli` option described in [Converting Models to Core ML](#converting-models-to-coreml)
118+
119+
\* Please see [FAQ](#faq) [Q6](#q-mobile-app) regarding deploying on iPad and iPhone.
110120

111121
### Example CLI Usage
112122
```shell
@@ -123,8 +133,10 @@ Please use the `--help` flag to learn about batched generation and more.
123133
import StableDiffusion
124134
...
125135
let pipeline = try StableDiffusionPipeline(resourcesAt: resourceURL)
136+
pipeline.loadResources()
126137
let image = try pipeline.generateImages(prompt: prompt, seed: seed).first
127138
```
139+
On iOS, the `reduceMemory` option should bet set to `true` when constructing `StableDiffusionPipeline`
128140

129141
### Swift Package Details
130142

@@ -184,7 +196,7 @@ Please see [Important Notes on Performance Benchmarks](#important-notes-on-perfo
184196
- The image generation procedure follows the standard configuration: 50 inference steps, 512x512 output image resolution, 77 text token sequence length, classifier-free guidance (batch size of 2 for unet).
185197
- 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.
186198
- Pipelining across the 4 models is not optimized and these performance numbers are subject to variance under increased system load from other applications. Given these factors, we do not report sub-second variance in latency.
187-
- Weights and activations are in float16 precision for both the GPU and the ANE.
199+
- Weights and activations are in float16 precision for both the GPU and the Neural Engine.
188200
- The Swift CLI program consumes a peak memory of approximately 2.6GB (without the safety checker), 2.1GB of which is model weights in float16 precision. We applied [8-bit weight quantization](https://coremltools.readme.io/docs/compressing-ml-program-weights#use-affine-quantization) to reduce peak memory consumption by approximately 1GB. However, we observed that it had an adverse effect on generated image quality and we rolled it back. We encourage developers to experiment with other advanced weight compression techniques such as [palettization](https://coremltools.readme.io/docs/compressing-ml-program-weights#use-a-lookup-table) and/or [pruning](https://coremltools.readme.io/docs/compressing-ml-program-weights#use-sparse-representation) which may yield better results.
189201
- In the [benchmark table](performance-benchmark), 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.
190202

@@ -208,7 +220,7 @@ Differences may be less or more pronounced for different inputs. Please see the
208220

209221
</details>
210222

211-
## FAQ
223+
## <a name="faq"></a> FAQ
212224

213225
<details>
214226
<summary> Click to expand </summary>
@@ -228,7 +240,7 @@ Differences may be less or more pronounced for different inputs. Please see the
228240
</details>
229241

230242
<details>
231-
<summary> <b> Q3: </b> My Mac has 8GB RAM and I am converting models to Core ML using the example command. The process is geting killed because of memory issues. How do I fix this issue? </summary>
243+
<summary> <b> <a name="low-mem-conversion"></a> Q3: </b> My Mac has 8GB RAM and I am converting models to Core ML using the example command. The process is geting killed because of memory issues. How do I fix this issue? </summary>
232244

233245
<b> A3: </b> In order to minimize the memory impact of the model conversion process, please execute the following command instead:
234246

@@ -257,12 +269,22 @@ python -m python_coreml_stable_diffusion.torch2coreml --convert-unet --chunk-une
257269
<summary> <b> Q5: </b> Every time I generate an image using the Python pipeline, loading all the Core ML models takes 2-3 minutes. Is this expected? </summary>
258270

259271
<b> A5: </b> Yes and using the Swift library reduces this to just a few seconds. The reason is that `coremltools` loads Core ML models (`.mlpackage`) and each model is compiled to be run on the requested compute unit during load time. Because of the size and number of operations of the unet model, it takes around 2-3 minutes to compile it for Neural Engine execution. Other models should take at most a few seconds. Note that `coremltools` does not cache the compiled model for later loads so each load takes equally long. In order to benefit from compilation caching, `StableDiffusion` Swift package by default relies on compiled Core ML models (`.mlmodelc`) which will be compiled down for the requested compute unit upon first load but then the cache will be reused on subsequent loads until it is purged due to lack of use.
272+
273+
If you intend to use the Python pipeline in an application, we recommend initializing the pipeline once so that the load time is only incurred once. Afterwards, generating images using different prompts and random seeds will not incur the load time for the current session of your application.
274+
260275
</details>
261276

277+
262278
<details>
263-
<summary> <b> Q6: </b> I want to deploy <code>StableDiffusion</code>, the Swift package, in my mobile app. What should I be aware of?" </summary>
279+
<summary> <b> <a name="q-mobile-app"></a> Q6: </b> I want to deploy <code>StableDiffusion</code>, the Swift package, in my mobile app. What should I be aware of? </summary>
264280

265-
<b> A6: </b> [This section](#swift-requirements) describes the minimum SDK and OS versions as well as the device models supported by this package. In addition to these requirements, for best practice, we recommend testing the package on the device with the least amount of RAM available among your deployment targets. This is due to the fact that `StableDiffusion` consumes approximately 2.6GB of peak memory during runtime while using `.cpuAndNeuralEngine` (the Swift equivalent of `coremltools.ComputeUnit.CPU_AND_NE`). Other compute units may have a higher peak memory consumption so `.cpuAndNeuralEngine` is recommended for iOS and iPadOS deployment (Please refer to this [section](#swift-requirements) for minimum device model requirements). If your app crashes during image generation, please try adding the [Increased Memory Limit](https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_developer_kernel_increased-memory-limit) capability to your Xcode project which should significantly increase your app's memory limit.
281+
<b> A6: </b>The [Image Generation with Swift](#image-gen-swift) section describes the minimum SDK and OS versions as well as the device models supported by this package. We recommend carefully testing the package on the device with the least amount of RAM available among your deployment targets.
282+
283+
The image generation process in `StableDiffusion` can yield over 2 GB of peak memory during runtime depending on the compute units selected. On iPadOS, we recommend using `.cpuAndNeuralEngine` in your configuration and the `reduceMemory` option when constructing a `StableDiffusionPipeline` to minimize memory pressure.
284+
285+
If your app crashes during image generation, consider adding the [Increased Memory Limit](https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_developer_kernel_increased-memory-limit) capability to inform the system that some of your app’s core features may perform better by exceeding the default app memory limit on supported devices.
286+
287+
On iOS, depending on the iPhone model, Stable Diffusion model versions, selected compute units, system load and design of your app, this may still not be sufficient to keep your apps peak memory under the limit. Please remember, because the device shares memory between apps and iOS processes, one app using too much memory can compromise the user experience across the whole device.
266288
</details>
267289

268290
<details>
@@ -302,4 +324,26 @@ python -m python_coreml_stable_diffusion.torch2coreml --convert-unet --chunk-une
302324

303325
</details>
304326

327+
<details>
328+
<summary> <b> Q10: </b> <code> `Could not initialize NNPACK! Reason: Unsupported hardware` </code> </summary>
329+
330+
<b> A10: </b> This warning is safe to ignore in the context of this repository.
331+
332+
</details>
333+
334+
<details>
335+
<summary> <b> Q11: </b> <code> TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect </code> </summary>
336+
337+
<b> A11: </b> This warning is safe to ignore in the context of this repository.
338+
</details>
339+
340+
<details>
341+
<summary> <b> Q12: </b> <code> UserWarning: resource_tracker: There appear to be 1 leaked semaphore objects to clean up at shutdown </code> </summary>
342+
343+
<b> A12: </b> If this warning is printed right after <code> zsh: killed python -m python_coreml_stable_diffusion.torch2coreml ... </code>, then it is highly likely that your Mac has run out of memory while converting models to Core ML. Please see [Q3](#low-mem-conversion) from above for the solution.
344+
345+
</details>
346+
347+
</details>
348+
305349
</details>

swift/StableDiffusion/pipeline/Decoder.swift

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,30 @@ import CoreML
66
import Accelerate
77

88
/// A decoder model which produces RGB images from latent samples
9-
public struct Decoder {
9+
public struct Decoder: ResourceManaging {
1010

1111
/// VAE decoder model
12-
var model: MLModel
12+
var model: ManagedMLModel
1313

1414
/// Create decoder from Core ML model
1515
///
16-
/// - Parameters
17-
/// - model: Core ML model for VAE decoder
18-
public init(model: MLModel) {
19-
self.model = model
16+
/// - Parameters:
17+
/// - url: Location of compiled VAE decoder Core ML model
18+
/// - configuration: configuration to be used when the model is loaded
19+
/// - Returns: A decoder that will lazily load its required resources when needed or requested
20+
public init(modelAt url: URL, configuration: MLModelConfiguration) {
21+
self.model = ManagedMLModel(modelAt: url, configuration: configuration)
2022
}
2123

22-
/// Prediction queue
23-
let queue = DispatchQueue(label: "decoder.predict")
24+
/// Ensure the model has been loaded into memory
25+
public func loadResources() throws {
26+
try model.loadResources()
27+
}
28+
29+
/// Unload the underlying model to free up memory
30+
public func unloadResources() {
31+
model.unloadResources()
32+
}
2433

2534
/// Batch decode latent samples into images
2635
///
@@ -42,7 +51,9 @@ public struct Decoder {
4251
let batch = MLArrayBatchProvider(array: inputs)
4352

4453
// Batch predict with model
45-
let results = try queue.sync { try model.predictions(fromBatch: batch) }
54+
let results = try model.perform { model in
55+
try model.predictions(fromBatch: batch)
56+
}
4657

4758
// Transform the outputs to CGImages
4859
let images: [CGImage] = (0..<results.count).map { i in
@@ -57,7 +68,9 @@ public struct Decoder {
5768
}
5869

5970
var inputName: String {
60-
model.modelDescription.inputDescriptionsByName.first!.key
71+
try! model.perform { model in
72+
model.modelDescription.inputDescriptionsByName.first!.key
73+
}
6174
}
6275

6376
typealias PixelBufferPFx1 = vImage.PixelBuffer<vImage.PlanarF>
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// For licensing see accompanying LICENSE.md file.
2+
// Copyright (C) 2022 Apple Inc. All Rights Reserved.
3+
4+
import CoreML
5+
6+
/// A class to manage and gate access to a Core ML model
7+
///
8+
/// It will automatically load a model into memory when needed or requested
9+
/// It allows one to request to unload the model from memory
10+
public final class ManagedMLModel: ResourceManaging {
11+
12+
/// The location of the model
13+
var modelURL: URL
14+
15+
/// The configuration to be used when the model is loaded
16+
var configuration: MLModelConfiguration
17+
18+
/// The loaded model (when loaded)
19+
var loadedModel: MLModel?
20+
21+
/// Queue to protect access to loaded model
22+
var queue: DispatchQueue
23+
24+
/// Create a managed model given its location and desired loaded configuration
25+
///
26+
/// - Parameters:
27+
/// - url: The location of the model
28+
/// - configuration: The configuration to be used when the model is loaded/used
29+
/// - Returns: A managed model that has not been loaded
30+
public init(modelAt url: URL, configuration: MLModelConfiguration) {
31+
self.modelURL = url
32+
self.configuration = configuration
33+
self.loadedModel = nil
34+
self.queue = DispatchQueue(label: "managed.\(url.lastPathComponent)")
35+
}
36+
37+
/// Instantiation and load model into memory
38+
public func loadResources() throws {
39+
try queue.sync {
40+
try loadModel()
41+
}
42+
}
43+
44+
/// Unload the model if it was loaded
45+
public func unloadResources() {
46+
queue.sync {
47+
loadedModel = nil
48+
}
49+
}
50+
51+
/// Perform an operation with the managed model via a supplied closure.
52+
/// The model will be loaded and supplied to the closure and should only be
53+
/// used within the closure to ensure all resource management is synchronized
54+
///
55+
/// - Parameters:
56+
/// - body: Closure which performs and action on a loaded model
57+
/// - Returns: The result of the closure
58+
/// - Throws: An error if the model cannot be loaded or if the closure throws
59+
public func perform<R>(_ body: (MLModel) throws -> R) throws -> R {
60+
return try queue.sync {
61+
try autoreleasepool {
62+
try loadModel()
63+
return try body(loadedModel!)
64+
}
65+
}
66+
}
67+
68+
private func loadModel() throws {
69+
if loadedModel == nil {
70+
loadedModel = try MLModel(contentsOf: modelURL,
71+
configuration: configuration)
72+
}
73+
}
74+
75+
76+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// For licensing see accompanying LICENSE.md file.
2+
// Copyright (C) 2022 Apple Inc. All Rights Reserved.
3+
4+
/// Protocol for managing internal resources
5+
public protocol ResourceManaging {
6+
7+
/// Request resources to be loaded and ready if possible
8+
func loadResources() throws
9+
10+
/// Request resources are unloaded / remove from memory if possible
11+
func unloadResources()
12+
}
13+
14+
extension ResourceManaging {
15+
/// Request resources are pre-warmed by loading and unloading
16+
func prewarmResources() throws {
17+
try loadResources()
18+
unloadResources()
19+
}
20+
}

0 commit comments

Comments
 (0)