// 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_HARNESS import CoreGraphics import CoreML import Foundation import ImageIO import 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 (`.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.. 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.. [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