-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathPipelineLoader.swift
194 lines (166 loc) · 6.13 KB
/
PipelineLoader.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
//
// PipelineLoader.swift
// Diffusion
//
// Created by Pedro Cuenca on December 2022.
// See LICENSE at https://github.com/huggingface/swift-coreml-diffusers/LICENSE
//
import CoreML
import Combine
import ZIPFoundation
import StableDiffusion
class PipelineLoader {
static let models = Settings.shared.applicationSupportURL().appendingPathComponent("hf-diffusion-models")
let model: ModelInfo
let computeUnits: ComputeUnits
let maxSeed: UInt32
private var downloadSubscriber: Cancellable?
init(model: ModelInfo, computeUnits: ComputeUnits? = nil, maxSeed: UInt32 = UInt32.max) {
self.model = model
self.computeUnits = computeUnits ?? model.defaultComputeUnits
self.maxSeed = maxSeed
state = .undetermined
setInitialState()
}
enum PipelinePreparationPhase {
case undetermined
case waitingToDownload
case downloading(Double)
case downloaded
case uncompressing
case readyOnDisk
case loaded
case failed(Error)
}
var state: PipelinePreparationPhase {
didSet {
statePublisher.value = state
}
}
private(set) lazy var statePublisher: CurrentValueSubject<PipelinePreparationPhase, Never> = CurrentValueSubject(state)
private(set) var downloader: Downloader? = nil
func setInitialState() {
if ready {
state = .readyOnDisk
return
}
if downloaded {
state = .downloaded
return
}
state = .waitingToDownload
}
}
extension PipelineLoader {
// Unused. Kept for debugging purposes. --pcuenca
static func removeAll() {
// Delete the parent models folder as it will be recreated when it's needed again
do {
try FileManager.default.removeItem(at: models)
} catch {
print("Failed to delete: \(models), error: \(error.localizedDescription)")
}
}
}
extension PipelineLoader {
func cancel() { downloader?.cancel() }
}
extension PipelineLoader {
var url: URL {
return model.modelURL(for: variant)
}
var filename: String {
return url.lastPathComponent
}
var downloadedURL: URL { PipelineLoader.models.appendingPathComponent(filename) }
var uncompressURL: URL { PipelineLoader.models }
var packagesFilename: String { (filename as NSString).deletingPathExtension }
var compiledURL: URL {
guard BENCHMARK else { return downloadedURL.deletingLastPathComponent().appendingPathComponent(packagesFilename) }
// Model files must be part of the bundle when benchmarking
return Bundle.main.resourceURL!
}
var downloaded: Bool {
return FileManager.default.fileExists(atPath: downloadedURL.path)
}
var ready: Bool {
return FileManager.default.fileExists(atPath: compiledURL.path)
}
var variant: AttentionVariant {
switch computeUnits {
case .cpuOnly : return .original // Not supported yet
case .cpuAndGPU : return .original
case .cpuAndNeuralEngine: return model.supportsAttentionV2 ? .splitEinsumV2 : .splitEinsum
case .all : return .splitEinsum
@unknown default:
fatalError("Unknown MLComputeUnits")
}
}
func prepare() async throws -> Pipeline {
do {
do {
try FileManager.default.createDirectory(atPath: PipelineLoader.models.path, withIntermediateDirectories: true, attributes: nil)
} catch {
print("Error creating PipelineLoader.models path: \(error)")
}
try await download()
try await unzip()
let pipeline = try await load(url: compiledURL)
return Pipeline(pipeline, maxSeed: maxSeed)
} catch {
state = .failed(error)
throw error
}
}
@discardableResult
func download() async throws -> URL {
if ready || downloaded { return downloadedURL }
let downloader = Downloader(from: url, to: downloadedURL)
self.downloader = downloader
downloadSubscriber = downloader.downloadState.sink { state in
if case .downloading(let progress) = state {
self.state = .downloading(progress)
}
}
try downloader.waitUntilDone()
return downloadedURL
}
func unzip() async throws {
guard downloaded else { return }
state = .uncompressing
do {
try FileManager().unzipItem(at: downloadedURL, to: uncompressURL)
} catch {
// Cleanup if error occurs while unzipping
try FileManager.default.removeItem(at: uncompressURL)
throw error
}
try FileManager.default.removeItem(at: downloadedURL)
state = .readyOnDisk
}
func load(url: URL) async throws -> StableDiffusionPipelineProtocol {
let beginDate = Date()
let configuration = MLModelConfiguration()
configuration.computeUnits = computeUnits
let pipeline: StableDiffusionPipelineProtocol
if model.isXL {
if #available(macOS 14.0, iOS 17.0, *) {
pipeline = try StableDiffusionXLPipeline(resourcesAt: url,
configuration: configuration,
reduceMemory: model.reduceMemory)
} else {
throw "Stable Diffusion XL requires macOS 14"
}
} else {
pipeline = try StableDiffusionPipeline(resourcesAt: url,
controlNet: [],
configuration: configuration,
disableSafety: false,
reduceMemory: model.reduceMemory)
}
try pipeline.loadResources()
print("Pipeline loaded in \(Date().timeIntervalSince(beginDate))")
state = .loaded
return pipeline
}
}