diff --git a/README.md b/README.md index 8e7e60e..25a3a32 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ 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](https://github.com/huggingface/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](#FAQ) section. +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. ## Example Results @@ -25,6 +25,13 @@ M2 MacBook Air 8GB Latency (s) | 18 | 23 | 23 | Please see [Important Notes on Performance Benchmarks](#important-notes-on-performance-benchmarks) section for details. +## System Requirements + +The following is recommended to use all the functionality in this repository: + +Python | macOS | Xcode | iPadOS, iOS | +:------:|:------:|:------:|:------:| +3.8 | 13.1 | 14.2 | 16.2 | ## Converting Models to Core ML @@ -50,7 +57,7 @@ pip install -e . python -m python_coreml_stable_diffusion.torch2coreml --convert-unet --convert-text-encoder --convert-vae-decoder --convert-safety-checker -o ``` -**WARNING:** This command will download several GB worth of PyTorch checkpoints from Hugging Face. +**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. 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 ``. Some additional notable arguments: @@ -59,9 +66,9 @@ This generally takes 15-20 minutes on an M1 MacBook Pro. Upon successful executi - `--bundle-resources-for-swift-cli`: Compiles all 4 models and bundles them along with necessary resources for text tokenization into `/Resources` which should provided as input to the Swift package. This flag is not necessary for the diffusers-based Python pipeline. -- `--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. +- `--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. -- `--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. +- `--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. - `--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. @@ -86,27 +93,30 @@ Please refer to the help menu for all available arguments: `python -m python_cor -## Image Generation with Swift +## Image Generation with Swift
Click to expand ### System Requirements -Building the Swift projects require: -- macOS 13 or newer -- 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. -- 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 - -If deploying this model to: -- iPhone - - iOS 16.2 or newer - - iPhone 12 or newer -- iPad - - iPadOS 16.2 or newer - - M1 or newer -- Mac - - macOS 13.1 or newer - - M1 or newer + +**Building** (recommended): + +- Xcode 14.2 +- Command Line Tools for Xcode 14.2 + +Check [developer.apple.com](https://developer.apple.com/download/all/?q=xcode) for the latest versions. + +**Running** (minimum): + +| Mac | iPad\* | iPhone\* | +|:------:|:------:|:------:| +| macOS 13.1 | iPadOS 16.2 | iOS 16.2 | +| M1 | M1 | iPhone 12 Pro | + +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) + +\* Please see [FAQ](#faq) [Q6](#q-mobile-app) regarding deploying on iPad and iPhone. ### Example CLI Usage ```shell @@ -123,8 +133,10 @@ Please use the `--help` flag to learn about batched generation and more. import StableDiffusion ... let pipeline = try StableDiffusionPipeline(resourcesAt: resourceURL) +pipeline.loadResources() let image = try pipeline.generateImages(prompt: prompt, seed: seed).first ``` +On iOS, the `reduceMemory` option should bet set to `true` when constructing `StableDiffusionPipeline` ### Swift Package Details @@ -184,7 +196,7 @@ Please see [Important Notes on Performance Benchmarks](#important-notes-on-perfo - 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). - 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. - 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. -- Weights and activations are in float16 precision for both the GPU and the ANE. +- Weights and activations are in float16 precision for both the GPU and the Neural Engine. - 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. - 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. @@ -208,7 +220,7 @@ Differences may be less or more pronounced for different inputs. Please see the
-## FAQ +## FAQ
Click to expand @@ -228,7 +240,7 @@ Differences may be less or more pronounced for different inputs. Please see the
- Q3: 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? + Q3: 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? A3: In order to minimize the memory impact of the model conversion process, please execute the following command instead: @@ -257,12 +269,22 @@ python -m python_coreml_stable_diffusion.torch2coreml --convert-unet --chunk-une Q5: Every time I generate an image using the Python pipeline, loading all the Core ML models takes 2-3 minutes. Is this expected? A5: 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. + +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. +
+
- Q6: I want to deploy StableDiffusion, the Swift package, in my mobile app. What should I be aware of?" + Q6: I want to deploy StableDiffusion, the Swift package, in my mobile app. What should I be aware of? - A6: [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. + A6: 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. + +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. + +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. + +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.
@@ -302,4 +324,26 @@ python -m python_coreml_stable_diffusion.torch2coreml --convert-unet --chunk-une
+
+ Q10: `Could not initialize NNPACK! Reason: Unsupported hardware` + + A10: This warning is safe to ignore in the context of this repository. + +
+ +
+ Q11: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect + + A11: This warning is safe to ignore in the context of this repository. +
+ +
+ Q12: UserWarning: resource_tracker: There appear to be 1 leaked semaphore objects to clean up at shutdown + + A12: If this warning is printed right after zsh: killed python -m python_coreml_stable_diffusion.torch2coreml ... , 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. + +
+ + + diff --git a/swift/StableDiffusion/pipeline/Decoder.swift b/swift/StableDiffusion/pipeline/Decoder.swift index 2b55085..d938dd0 100644 --- a/swift/StableDiffusion/pipeline/Decoder.swift +++ b/swift/StableDiffusion/pipeline/Decoder.swift @@ -6,21 +6,30 @@ import CoreML import Accelerate /// A decoder model which produces RGB images from latent samples -public struct Decoder { +public struct Decoder: ResourceManaging { /// VAE decoder model - var model: MLModel + var model: ManagedMLModel /// Create decoder from Core ML model /// - /// - Parameters - /// - model: Core ML model for VAE decoder - public init(model: MLModel) { - self.model = model + /// - Parameters: + /// - url: Location of compiled VAE decoder Core ML model + /// - configuration: configuration to be used when the model is loaded + /// - Returns: A decoder that will lazily load its required resources when needed or requested + public init(modelAt url: URL, configuration: MLModelConfiguration) { + self.model = ManagedMLModel(modelAt: url, configuration: configuration) } - /// Prediction queue - let queue = DispatchQueue(label: "decoder.predict") + /// Ensure the model has been loaded into memory + public func loadResources() throws { + try model.loadResources() + } + + /// Unload the underlying model to free up memory + public func unloadResources() { + model.unloadResources() + } /// Batch decode latent samples into images /// @@ -42,7 +51,9 @@ public struct Decoder { let batch = MLArrayBatchProvider(array: inputs) // Batch predict with model - let results = try queue.sync { try model.predictions(fromBatch: batch) } + let results = try model.perform { model in + try model.predictions(fromBatch: batch) + } // Transform the outputs to CGImages let images: [CGImage] = (0.. diff --git a/swift/StableDiffusion/pipeline/ManagedMLModel.swift b/swift/StableDiffusion/pipeline/ManagedMLModel.swift new file mode 100644 index 0000000..701bf07 --- /dev/null +++ b/swift/StableDiffusion/pipeline/ManagedMLModel.swift @@ -0,0 +1,76 @@ +// For licensing see accompanying LICENSE.md file. +// Copyright (C) 2022 Apple Inc. All Rights Reserved. + +import CoreML + +/// A class to manage and gate access to a Core ML model +/// +/// It will automatically load a model into memory when needed or requested +/// It allows one to request to unload the model from memory +public final class ManagedMLModel: ResourceManaging { + + /// The location of the model + var modelURL: URL + + /// The configuration to be used when the model is loaded + var configuration: MLModelConfiguration + + /// The loaded model (when loaded) + var loadedModel: MLModel? + + /// Queue to protect access to loaded model + var queue: DispatchQueue + + /// Create a managed model given its location and desired loaded configuration + /// + /// - Parameters: + /// - url: The location of the model + /// - configuration: The configuration to be used when the model is loaded/used + /// - Returns: A managed model that has not been loaded + public init(modelAt url: URL, configuration: MLModelConfiguration) { + self.modelURL = url + self.configuration = configuration + self.loadedModel = nil + self.queue = DispatchQueue(label: "managed.\(url.lastPathComponent)") + } + + /// Instantiation and load model into memory + public func loadResources() throws { + try queue.sync { + try loadModel() + } + } + + /// Unload the model if it was loaded + public func unloadResources() { + queue.sync { + loadedModel = nil + } + } + + /// Perform an operation with the managed model via a supplied closure. + /// The model will be loaded and supplied to the closure and should only be + /// used within the closure to ensure all resource management is synchronized + /// + /// - Parameters: + /// - body: Closure which performs and action on a loaded model + /// - Returns: The result of the closure + /// - Throws: An error if the model cannot be loaded or if the closure throws + public func perform(_ body: (MLModel) throws -> R) throws -> R { + return try queue.sync { + try autoreleasepool { + try loadModel() + return try body(loadedModel!) + } + } + } + + private func loadModel() throws { + if loadedModel == nil { + loadedModel = try MLModel(contentsOf: modelURL, + configuration: configuration) + } + } + + +} diff --git a/swift/StableDiffusion/pipeline/ResourceManaging.swift b/swift/StableDiffusion/pipeline/ResourceManaging.swift new file mode 100644 index 0000000..3813487 --- /dev/null +++ b/swift/StableDiffusion/pipeline/ResourceManaging.swift @@ -0,0 +1,20 @@ +// For licensing see accompanying LICENSE.md file. +// Copyright (C) 2022 Apple Inc. All Rights Reserved. + +/// Protocol for managing internal resources +public protocol ResourceManaging { + + /// Request resources to be loaded and ready if possible + func loadResources() throws + + /// Request resources are unloaded / remove from memory if possible + func unloadResources() +} + +extension ResourceManaging { + /// Request resources are pre-warmed by loading and unloading + func prewarmResources() throws { + try loadResources() + unloadResources() + } +} diff --git a/swift/StableDiffusion/pipeline/SafetyChecker.swift b/swift/StableDiffusion/pipeline/SafetyChecker.swift index e7b8641..46d8450 100644 --- a/swift/StableDiffusion/pipeline/SafetyChecker.swift +++ b/swift/StableDiffusion/pipeline/SafetyChecker.swift @@ -6,22 +6,30 @@ import CoreML import Accelerate /// Image safety checking model -public struct SafetyChecker { +public struct SafetyChecker: ResourceManaging { /// Safety checking Core ML model - var model: MLModel + var model: ManagedMLModel /// Creates safety checker /// /// - Parameters: - /// - model: Underlying model which performs the safety check - /// - Returns: Safety checker ready from checks - public init(model: MLModel) { - self.model = model + /// - url: Location of compiled safety checking Core ML model + /// - configuration: configuration to be used when the model is loaded + /// - Returns: A safety cherker that will lazily load its required resources when needed or requested + public init(modelAt url: URL, configuration: MLModelConfiguration) { + self.model = ManagedMLModel(modelAt: url, configuration: configuration) } - /// Prediction queue - let queue = DispatchQueue(label: "safetycheker.predict") + /// Ensure the model has been loaded into memory + public func loadResources() throws { + try model.loadResources() + } + + /// Unload the underlying model to free up memory + public func unloadResources() { + model.unloadResources() + } typealias PixelBufferPFx1 = vImage.PixelBuffer typealias PixelBufferP8x1 = vImage.PixelBuffer @@ -49,7 +57,9 @@ public struct SafetyChecker { let adjustmentName = "adjustment" let imagesNames = "images" - let inputInfo = model.modelDescription.inputDescriptionsByName + let inputInfo = try model.perform { model in + model.modelDescription.inputDescriptionsByName + } let inputShape = inputInfo[inputName]!.multiArrayConstraint!.shape let width = inputShape[2].intValue @@ -74,7 +84,9 @@ public struct SafetyChecker { throw SafetyCheckError.modelInputFailure } - let result = try queue.sync { try model.prediction(from: input) } + let result = try model.perform { model in + try model.prediction(from: input) + } let output = result.featureValue(for: "has_nsfw_concepts") diff --git a/swift/StableDiffusion/pipeline/StableDiffusionPipeline+Resources.swift b/swift/StableDiffusion/pipeline/StableDiffusionPipeline+Resources.swift index 19c8bcf..b3a6815 100644 --- a/swift/StableDiffusion/pipeline/StableDiffusionPipeline+Resources.swift +++ b/swift/StableDiffusion/pipeline/StableDiffusionPipeline+Resources.swift @@ -6,6 +6,29 @@ import CoreML public extension StableDiffusionPipeline { + struct ResourceURLs { + + public let textEncoderURL: URL + public let unetURL: URL + public let unetChunk1URL: URL + public let unetChunk2URL: URL + public let decoderURL: URL + public let safetyCheckerURL: URL + public let vocabURL: URL + public let mergesURL: URL + + public init(resourcesAt baseURL: URL) { + textEncoderURL = baseURL.appending(path: "TextEncoder.mlmodelc") + unetURL = baseURL.appending(path: "Unet.mlmodelc") + unetChunk1URL = baseURL.appending(path: "UnetChunk1.mlmodelc") + unetChunk2URL = baseURL.appending(path: "UnetChunk2.mlmodelc") + decoderURL = baseURL.appending(path: "VAEDecoder.mlmodelc") + safetyCheckerURL = baseURL.appending(path: "SafetyChecker.mlmodelc") + vocabURL = baseURL.appending(path: "vocab.json") + mergesURL = baseURL.appending(path: "merges.txt") + } + } + /// Create stable diffusion pipeline using model resources at a /// specified URL /// @@ -14,55 +37,48 @@ public extension StableDiffusionPipeline { /// and tokenization resources /// - configuration: The configuration to load model resources with /// - disableSafety: Load time disable of safety to save memory + /// - reduceMemory: Setup pipeline in reduced memory mode /// - Returns: /// Pipeline ready for image generation if all necessary resources loaded init(resourcesAt baseURL: URL, configuration config: MLModelConfiguration = .init(), - disableSafety: Bool = false) throws { + disableSafety: Bool = false, + reduceMemory: Bool = false) throws { /// Expect URL of each resource - let textEncoderURL = baseURL.appending(path: "TextEncoder.mlmodelc") - let unetURL = baseURL.appending(path: "Unet.mlmodelc") - let unetChunk1URL = baseURL.appending(path: "UnetChunk1.mlmodelc") - let unetChunk2URL = baseURL.appending(path: "UnetChunk2.mlmodelc") - let decoderURL = baseURL.appending(path: "VAEDecoder.mlmodelc") - let safetyCheckerURL = baseURL.appending(path: "SafetyChecker.mlmodelc") - let vocabURL = baseURL.appending(path: "vocab.json") - let mergesURL = baseURL.appending(path: "merges.txt") + let urls = ResourceURLs(resourcesAt: baseURL) // Text tokenizer and encoder - let tokenizer = try BPETokenizer(mergesAt: mergesURL, vocabularyAt: vocabURL) - let textEncoderModel = try MLModel(contentsOf: textEncoderURL, configuration: config) - let textEncoder = TextEncoder(tokenizer: tokenizer, model:textEncoderModel ) + let tokenizer = try BPETokenizer(mergesAt: urls.mergesURL, vocabularyAt: urls.vocabURL) + let textEncoder = TextEncoder(tokenizer: tokenizer, + modelAt: urls.textEncoderURL, + configuration: config) // Unet model let unet: Unet - if FileManager.default.fileExists(atPath: unetChunk1URL.path) && - FileManager.default.fileExists(atPath: unetChunk2URL.path) { - let chunk1 = try MLModel(contentsOf: unetChunk1URL, configuration: config) - let chunk2 = try MLModel(contentsOf: unetChunk2URL, configuration: config) - unet = Unet(chunks: [chunk1, chunk2]) + if FileManager.default.fileExists(atPath: urls.unetChunk1URL.path) && + FileManager.default.fileExists(atPath: urls.unetChunk2URL.path) { + unet = Unet(chunksAt: [urls.unetChunk1URL, urls.unetChunk2URL], + configuration: config) } else { - let unetModel = try MLModel(contentsOf: unetURL, configuration: config) - unet = Unet(model: unetModel) + unet = Unet(modelAt: urls.unetURL, configuration: config) } // Image Decoder - let decoderModel = try MLModel(contentsOf: decoderURL, configuration: config) - let decoder = Decoder(model: decoderModel) + let decoder = Decoder(modelAt: urls.decoderURL, configuration: config) // Optional safety checker var safetyChecker: SafetyChecker? = nil if !disableSafety && - FileManager.default.fileExists(atPath: safetyCheckerURL.path) { - let checkerModel = try MLModel(contentsOf: safetyCheckerURL, configuration: config) - safetyChecker = SafetyChecker(model: checkerModel) + FileManager.default.fileExists(atPath: urls.safetyCheckerURL.path) { + safetyChecker = SafetyChecker(modelAt: urls.safetyCheckerURL, configuration: config) } // Construct pipelien self.init(textEncoder: textEncoder, unet: unet, decoder: decoder, - safetyChecker: safetyChecker) + safetyChecker: safetyChecker, + reduceMemory: reduceMemory) } } diff --git a/swift/StableDiffusion/pipeline/StableDiffusionPipeline.swift b/swift/StableDiffusion/pipeline/StableDiffusionPipeline.swift index bc888cc..a8773da 100644 --- a/swift/StableDiffusion/pipeline/StableDiffusionPipeline.swift +++ b/swift/StableDiffusion/pipeline/StableDiffusionPipeline.swift @@ -10,7 +10,7 @@ import CoreGraphics /// /// This implementation matches: /// [Hugging Face Diffusers Pipeline](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py) -public struct StableDiffusionPipeline { +public struct StableDiffusionPipeline: ResourceManaging { /// Model to generate embeddings for tokenized input text var textEncoder: TextEncoder @@ -32,6 +32,14 @@ public struct StableDiffusionPipeline { safetyChecker != nil } + /// Option to reduce memory during image generation + /// + /// If true, the pipeline will lazily load TextEncoder, Unet, Decoder, and SafetyChecker + /// when needed and aggressively unload their resources after + /// + /// This will increase latency in favor of reducing memory + var reduceMemory: Bool = false + /// Creates a pipeline using the specified models and tokenizer /// /// - Parameters: @@ -40,17 +48,51 @@ public struct StableDiffusionPipeline { /// - decoder: Model for decoding latent sample to image /// - safetyChecker: Optional model for checking safety of generated images /// - guidanceScale: Influence of the text prompt on generation process + /// - reduceMemory: Option to enable reduced memory mode /// - Returns: Pipeline ready for image generation public init(textEncoder: TextEncoder, unet: Unet, decoder: Decoder, safetyChecker: SafetyChecker? = nil, - guidanceScale: Float = 7.5) { + guidanceScale: Float = 7.5, + reduceMemory: Bool = false) { self.textEncoder = textEncoder self.unet = unet self.decoder = decoder self.safetyChecker = safetyChecker self.guidanceScale = guidanceScale + self.reduceMemory = reduceMemory + } + + /// Load required resources for this pipeline + /// + /// If reducedMemory is true this will instead call prewarmResources instead + /// and let the pipeline lazily load resources as needed + public func loadResources() throws { + if reduceMemory { + try prewarmResources() + } else { + try textEncoder.loadResources() + try unet.loadResources() + try decoder.loadResources() + try safetyChecker?.loadResources() + } + } + + /// Unload the underlying resources to free up memory + public func unloadResources() { + textEncoder.unloadResources() + unet.unloadResources() + decoder.unloadResources() + safetyChecker?.unloadResources() + } + + // Prewarm resources one at a time + public func prewarmResources() throws { + try textEncoder.prewarmResources() + try unet.prewarmResources() + try decoder.prewarmResources() + try safetyChecker?.prewarmResources() } /// Text to image generation using stable diffusion @@ -77,6 +119,10 @@ public struct StableDiffusionPipeline { let promptEmbedding = try textEncoder.encode(prompt) let blankEmbedding = try textEncoder.encode("") + if reduceMemory { + textEncoder.unloadResources() + } + // Convert to Unet hidden state representation let concatEmbedding = MLShapedArray( concatenating: [blankEmbedding, promptEmbedding], @@ -136,6 +182,10 @@ public struct StableDiffusionPipeline { } } + if reduceMemory { + unet.unloadResources() + } + // Decode the latent samples to images return try decodeToImages(latents, disableSafety: disableSafety) } @@ -144,7 +194,7 @@ public struct StableDiffusionPipeline { var sampleShape = unet.latentSampleShape sampleShape[0] = 1 - var random = NumPyRandomSource(seed: UInt32(seed)) + var random = NumPyRandomSource(seed: UInt32(truncatingIfNeeded: seed)) let samples = (0..( converting: random.normalShapedArray(sampleShape, mean: 0.0, stdev: Double(stdev))) @@ -192,8 +242,10 @@ public struct StableDiffusionPipeline { func decodeToImages(_ latents: [MLShapedArray], disableSafety: Bool) throws -> [CGImage?] { - let images = try decoder.decode(latents) + if reduceMemory { + decoder.unloadResources() + } // If safety is disabled return what was decoded if disableSafety { @@ -210,6 +262,10 @@ public struct StableDiffusionPipeline { try safetyChecker.isSafe(image) ? image : nil } + if reduceMemory { + safetyChecker.unloadResources() + } + return safeImages } diff --git a/swift/StableDiffusion/pipeline/TextEncoder.swift b/swift/StableDiffusion/pipeline/TextEncoder.swift index 1271cb4..92e3cc7 100644 --- a/swift/StableDiffusion/pipeline/TextEncoder.swift +++ b/swift/StableDiffusion/pipeline/TextEncoder.swift @@ -5,22 +5,36 @@ import Foundation import CoreML /// A model for encoding text -public struct TextEncoder { +public struct TextEncoder: ResourceManaging { /// Text tokenizer var tokenizer: BPETokenizer /// Embedding model - var model: MLModel + var model: ManagedMLModel /// Creates text encoder which embeds a tokenized string /// /// - Parameters: /// - tokenizer: Tokenizer for input text - /// - model: Model for encoding tokenized text - public init(tokenizer: BPETokenizer, model: MLModel) { + /// - url: Location of compiled text encoding Core ML model + /// - configuration: configuration to be used when the model is loaded + /// - Returns: A text encoder that will lazily load its required resources when needed or requested + public init(tokenizer: BPETokenizer, + modelAt url: URL, + configuration: MLModelConfiguration) { self.tokenizer = tokenizer - self.model = model + self.model = ManagedMLModel(modelAt: url, configuration: configuration) + } + + /// Ensure the model has been loaded into memory + public func loadResources() throws { + try model.loadResources() + } + + /// Unload the underlying model to free up memory + public func unloadResources() { + model.unloadResources() } /// Encode input text/string @@ -60,13 +74,18 @@ public struct TextEncoder { let inputFeatures = try! MLDictionaryFeatureProvider( dictionary: [inputName: MLMultiArray(inputArray)]) - let result = try queue.sync { try model.prediction(from: inputFeatures) } + let result = try model.perform { model in + try model.prediction(from: inputFeatures) + } + let embeddingFeature = result.featureValue(for: "last_hidden_state") return MLShapedArray(converting: embeddingFeature!.multiArrayValue!) } var inputDescription: MLFeatureDescription { - model.modelDescription.inputDescriptionsByName.first!.value + try! model.perform { model in + model.modelDescription.inputDescriptionsByName.first!.value + } } var inputShape: [Int] { diff --git a/swift/StableDiffusion/pipeline/Unet.swift b/swift/StableDiffusion/pipeline/Unet.swift index b161177..401ccaa 100644 --- a/swift/StableDiffusion/pipeline/Unet.swift +++ b/swift/StableDiffusion/pipeline/Unet.swift @@ -5,33 +5,62 @@ import Foundation import CoreML /// U-Net noise prediction model for stable diffusion -public struct Unet { +public struct Unet: ResourceManaging { /// Model used to predict noise residuals given an input, diffusion time step, and conditional embedding /// /// It can be in the form of a single model or multiple stages - var models: [MLModel] + var models: [ManagedMLModel] /// Creates a U-Net noise prediction model /// /// - Parameters: - /// - model: U-Net held in single Core ML model - /// - Returns: Ready for prediction - public init(model: MLModel) { - self.models = [model] + /// - url: Location of single U-Net compiled Core ML model + /// - configuration: Configuration to be used when the model is loaded + /// - Returns: U-net model that will lazily load its required resources when needed or requested + public init(modelAt url: URL, + configuration: MLModelConfiguration) { + self.models = [ManagedMLModel(modelAt: url, configuration: configuration)] } /// Creates a U-Net noise prediction model /// /// - Parameters: - /// - chunks: U-Net held chunked into multiple Core ML models - /// - Returns: Ready for prediction - public init(chunks: [MLModel]) { - self.models = chunks + /// - urls: Location of chunked U-Net via urls to each compiled chunk + /// - configuration: Configuration to be used when the model is loaded + /// - Returns: U-net model that will lazily load its required resources when needed or requested + public init(chunksAt urls: [URL], + configuration: MLModelConfiguration) { + self.models = urls.map { ManagedMLModel(modelAt: $0, configuration: configuration) } + } + + /// Load resources. + public func loadResources() throws { + for model in models { + try model.loadResources() + } + } + + /// Unload the underlying model to free up memory + public func unloadResources() { + for model in models { + model.unloadResources() + } + } + + /// Pre-warm resources + public func prewarmResources() throws { + // Override default to pre-warm each model + for model in models { + try model.loadResources() + model.unloadResources() + } } var latentSampleDescription: MLFeatureDescription { - models.first!.modelDescription.inputDescriptionsByName["sample"]! + try! models.first!.perform { model in + model.modelDescription.inputDescriptionsByName["sample"]! + } } /// The expected shape of the models latent sample input @@ -91,13 +120,10 @@ public struct Unet { return noise } - /// Prediction queue - let queue = DispatchQueue(label: "unet.predict") - func predictions(from batch: MLBatchProvider) throws -> MLBatchProvider { - var results = try queue.sync { - try models.first!.predictions(fromBatch: batch) + var results = try models.first!.perform { model in + try model.predictions(fromBatch: batch) } if models.count == 1 { @@ -117,8 +143,8 @@ public struct Unet { let nextBatch = MLArrayBatchProvider(array: next) // Predict - results = try queue.sync { - try stage.predictions(fromBatch: nextBatch) + results = try stage.perform { model in + try model.predictions(fromBatch: nextBatch) } } diff --git a/swift/StableDiffusionCLI/main.swift b/swift/StableDiffusionCLI/main.swift index 6b09af6..8007169 100644 --- a/swift/StableDiffusionCLI/main.swift +++ b/swift/StableDiffusionCLI/main.swift @@ -55,6 +55,9 @@ struct StableDiffusionSample: ParsableCommand { @Flag(help: "Disable safety checking") var disableSafety: Bool = false + @Flag(help: "Reduce memory usage") + var reduceMemory: Bool = false + mutating func run() throws { guard FileManager.default.fileExists(atPath: resourcePath) else { throw RunError.resources("Resource path does not exist \(resourcePath)") @@ -68,7 +71,9 @@ struct StableDiffusionSample: ParsableCommand { log("(Note: This can take a while the first time using these resources)\n") let pipeline = try StableDiffusionPipeline(resourcesAt: resourceURL, configuration: config, - disableSafety: disableSafety) + disableSafety: disableSafety, + reduceMemory: reduceMemory) + try pipeline.loadResources() log("Sampling ...\n") let sampleTimer = SampleTimer()