212 lines · 10.8 KB · SwiftRaw
// THE FACE IDENTITY MODEL (assets/design/albums/DECISIONS.md question 5, RESEARCH.md §2): the one thing neither// platform gives, a vector per aligned face, bundled as Core ML so it runs on this phone and nothing leaves it. Which// model ships is measured (`AlbumsMeasure`) and said in the lane's report; every vector carries the model's name, so// a better model later means one pass to make them again. A build without the model's file makes no vectors and says// so: faces are found and kept, grouping waits.#if os(iOS) || ALBUMS_HARNESSimport CoreGraphicsimport CoreMLimport Foundationimport ImageIOimport Vision/// A face model: its name (stamped on every vector), the side of the crop it takes, and the vector of one crop.protocol AlbumsFaceModel: Sendable { var name: String { get } var side: Int { get } /// `rgb`: `side` by `side` RGB bytes, row by row from the top. Answers the vector, unit length. func vector(_ rgb: [UInt8]) -> [Float]?}/// A Core ML face model in the app's bundle (`<file>.mlmodelc`), taking a 1x3xSxS float input.final class CoreMLFaceModel: AlbumsFaceModel, @unchecked Sendable { /// How the model wants its pixels: SFace takes RGB 0…255 as is; the ArcFace family (x − 127.5) / 127.5. struct Input: Sendable { var scale: Float var shift: Float var bgr: Bool static let raw = Input(scale: 1, shift: 0, bgr: false) static let centred = Input(scale: 1 / 127.5, shift: -1, bgr: false) /// AdaFace's IR-50 (HyperFace): (x − 127.5) / 127.5, blue first. static let centredBGR = Input(scale: 1 / 127.5, shift: -1, bgr: true) } let name: String let side: Int private let model: MLModel private let input: Input private let inputName: String private let outputName: String private let lock = NSLock() init?(file: String, name: String, side: Int, input: Input, units: MLComputeUnits = AlbumsFaces.units) { guard let url = AlbumsFaces.url(file) else { return nil } let configuration = MLModelConfiguration() configuration.computeUnits = units guard let model = try? MLModel(contentsOf: url, configuration: configuration), let inName = model.modelDescription.inputDescriptionsByName.keys.first, let outName = model.modelDescription.outputDescriptionsByName.keys.first else { return nil } self.model = model self.name = name self.side = side self.input = input inputName = inName outputName = outName } func vector(_ rgb: [UInt8]) -> [Float]? { let plane = side * side guard rgb.count == plane * 3, let array = try? MLMultiArray(shape: [1, 3, NSNumber(value: side), NSNumber(value: side)], dataType: .float32) else { return nil } let pointer = array.dataPointer.bindMemory(to: Float.self, capacity: plane * 3) for i in 0..<plane { for c in 0..<3 { let from = input.bgr ? 2 - c : c pointer[c * plane + i] = Float(rgb[3 * i + from]) * input.scale + input.shift } } lock.lock() defer { lock.unlock() } guard let provider = try? MLDictionaryFeatureProvider(dictionary: [inputName: MLFeatureValue(multiArray: array)]), let out = try? model.prediction(from: provider), let vector = out.featureValue(for: outputName)?.multiArrayValue else { return nil } var values = [Float](repeating: 0, count: vector.count) for i in 0..<vector.count { values[i] = vector[i].floatValue } let norm = sqrt(values.reduce(0) { $0 + $1 * $1 }) return norm > 0 ? values.map { $0 / norm } : nil }}enum AlbumsFaces { /// The phone chooses where the model runs; a simulator has only the CPU. static var units: MLComputeUnits { #if targetEnvironment(simulator) .cpuOnly #else .all #endif } /// The models this build may carry, the one to ship first; the first found is the one used. `-pal8`: 8-bit /// palettised weights; `-fp16`: half-precision weights (`scripts/albums-face-models.py convert`). /// The first one found is the one used. HyperFace-50k, 8-bit: the coordinator's choice (DECISIONS §5, 27 Nov) until /// our own model trained on HyperFace exists; its weights are MIT and it learned only from synthetic faces. It is /// put in the bundle at build time by its pinned hash (scripts/albums-face-model.sh), never committed. static let known: [(file: String, name: String, side: Int, input: CoreMLFaceModel.Input)] = [ ("HyperFace50k-pal8", "hyperface-50k-stylegan-pal8", 112, .centredBGR), ] + measured /// Only the Dev build's measurements read these, from Documents/FaceModels: no shipped bundle carries them. #if COTTON_DEV || ALBUMS_HARNESS private static let measured: [(file: String, name: String, side: Int, input: CoreMLFaceModel.Input)] = [ ("HyperFace50k-fp16", "hyperface-50k-stylegan", 112, .centredBGR), ("SFace-pal8", "sface-2021dec-pal8", 112, .raw), ("SFace-fp16", "sface-2021dec", 112, .raw), ("AuraFace-pal8", "auraface-v1-pal8", 112, .centred), ("AuraFace-fp16", "auraface-v1", 112, .centred), ] #else private static let measured: [(file: String, name: String, side: Int, input: CoreMLFaceModel.Input)] = [] #endif /// A compiled model in the app's `FaceModels` folder; in the Dev build also one put in Documents/FaceModels /// (the measurements try models too large to carry). static func url(_ file: String) -> URL? { if let url = Bundle.main.url(forResource: file, withExtension: "mlmodelc", subdirectory: "FaceModels") { return url } #if ALBUMS_HARNESS if let dir = ProcessInfo.processInfo.environment["ALBUMS_FACE_MODELS"] { let url = URL(fileURLWithPath: dir).appendingPathComponent("\(file).mlmodelc") if FileManager.default.fileExists(atPath: url.path) { return url } } #endif #if COTTON_DEV let dev = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] .appendingPathComponent("FaceModels/\(file).mlmodelc") if FileManager.default.fileExists(atPath: dev.path) { return dev } #endif return nil } static func load(_ one: (file: String, name: String, side: Int, input: CoreMLFaceModel.Input), units: MLComputeUnits = AlbumsFaces.units) -> CoreMLFaceModel? { CoreMLFaceModel(file: one.file, name: one.name, side: one.side, input: one.input, units: units) } /// The model this phone uses, loaded once. static let model: AlbumsFaceModel? = { if let forced = ProcessInfo.processInfo.environment["ALBUMS_FACE_MODEL"] { return known.first { $0.file == forced }.flatMap { load($0) } } for one in known { if let model = load(one) { return model } } return nil }() static func cosine(_ a: [Float], _ b: [Float]) -> Float { guard a.count == b.count else { return 0 } var dot: Float = 0 for i in 0..<a.count { dot += a[i] * b[i] } return dot } #if COTTON_DEV /// Speed per face of every model this phone can find, on the aligned 112 px faces in Documents/bench-faces /// (synthetic HyperFace crops), written to Documents/albums-face-bench.json with each crop's vector. static func bench() async { let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let files = ((try? FileManager.default.contentsOfDirectory(at: docs.appendingPathComponent("bench-faces"), includingPropertiesForKeys: nil)) ?? []) .filter { $0.pathExtension == "png" }.sorted { $0.lastPathComponent < $1.lastPathComponent } let crops: [[UInt8]] = files.compactMap { url in guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { return nil } return rgb(image, side: 112) } var out: [String: Any] = ["faces": crops.count, "files": files.map(\.lastPathComponent)] for one in known { for (unitsName, units) in [("all", MLComputeUnits.all), ("cpu", MLComputeUnits.cpuOnly)] { let loadStart = ContinuousClock.now guard let model = load(one, units: units) else { continue } let loaded = loadStart.duration(to: .now) _ = model.vector(crops.first ?? []) let start = ContinuousClock.now var vectors: [[Float]] = [] for crop in crops { vectors.append(model.vector(crop) ?? []) } let took = start.duration(to: .now) let ms = (Double(took.components.seconds) * 1000 + Double(took.components.attoseconds) / 1e15) / Double(max(1, crops.count)) out["\(one.file)/\(unitsName)"] = [ "ms_per_face": ms, "load_ms": Double(loaded.components.seconds) * 1000 + Double(loaded.components.attoseconds) / 1e15, "vectors": vectors, ] Log.write("albums: face bench \(one.file) \(unitsName) \(String(format: "%.2f", ms)) ms a face") } } // Vision's feature print on the same files: two different faces must print apart. var prints: [Double] = [] let urls = Array(files.prefix(12)) var made: [FeaturePrintObservation] = [] for url in urls { let handler = ImageRequestHandler(url) if let p = try? await handler.perform(AlbumsAnalysis.placed(GenerateImageFeaturePrintRequest())) { made.append(p) } } for i in 1..<max(1, made.count) { prints.append((try? made[0].distance(to: made[i])) ?? -1) } out["print_distances_from_first"] = prints if let data = try? JSONSerialization.data(withJSONObject: out) { try? data.write(to: docs.appendingPathComponent("albums-face-bench.json")) } } private static func rgb(_ image: CGImage, side: Int) -> [UInt8]? { var bytes = [UInt8](repeating: 0, count: side * side * 4) let ok: Bool = bytes.withUnsafeMutableBytes { buffer in guard let context = CGContext(data: buffer.baseAddress, width: side, height: side, bitsPerComponent: 8, bytesPerRow: side * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return false } context.draw(image, in: CGRect(x: 0, y: 0, width: side, height: side)) return true } guard ok else { return nil } var rgb = [UInt8](repeating: 0, count: side * side * 3) for i in 0..<(side * side) { rgb[3 * i] = bytes[4 * i]; rgb[3 * i + 1] = bytes[4 * i + 1]; rgb[3 * i + 2] = bytes[4 * i + 2] } return rgb } #endif}#endif