hex/ios/HEXKeyboard/KeyboardViewController.swift
Ryan Vogel efb7dcafb5
iOS: clean up what I say with an on-device tagger (experiment) (#2023)
* ios: clean up what I say with Hex's on-device dictation tagger (experiment)

What changed
- Experiments › Clean up what I say (off by default, App Group key
  experiments.cleanupTagger): Hex's trained cleanup tagger removes ums,
  repeats, and the words a spoken correction replaces ("3pm, actually 4pm"),
  on the iPhone, in in-keyboard dictation and in app dictation. It runs after
  transcription and learned fixes (in the app also after custom vocabulary),
  before Apple Intelligence cleanup, translation, and formatting, and never
  for Verbatim. When both cleanups are on, Apple Intelligence now receives the
  tagged text instead of the raw transcript; nothing else changes while the
  experiment is off.
- Model: the BERT L-4/H-512 token classifier (ckpt-1200k-l4h512) converted to
  an int8 Core ML ML Program (coremltools 9, fp16 compute, enumerated lengths
  16/32/64/128 plus a length input that masks the padding; the output is
  logit(DELETE) - logit(KEEP)), 28.5 MB, with its WordPiece vocabulary. Both
  ship once, in HEXKeyboard.appex (HEXKeyboard/CleanupTagger/), and the app
  loads them from its embedded keyboard extension. Core ML codegen is off for
  the keyboard target.
- HEXShared: CleanupTokenizer (Hugging Face BertTokenizer: special tokens,
  BertNormalizer, BertPreTokenizer, WordPiece, byte-exact vocabulary keys,
  HF's Unicode 8.0 character classes), CleanupReconstruction (a port of
  js/reconstruct.js with JavaScript's UTF-16 casing), and CleanupTagger
  (chunks of whole words within 128 tokens, P(DELETE) > 0.98, one serial
  queue, 150 ms budget). A timeout, an error, or a result with no words left
  keeps the transcript. The model loads when a dictation starts recording with
  the experiment on, stays loaded, and is freed on a memory warning. It runs
  on the Neural Engine or the CPU, never the GPU.
- Call sites: one each in KeyboardLocalDictation (after DictationCorrections,
  before translation) and DictationController (after VocabularySpelling,
  before the Apple Intelligence pass). prepareIfEnabled runs at recording
  start, in KeyboardViewController and in DictationController.startRecording.

Why
- In the simulator the first load took 0.15 s on the CPU and 0.8 s on the GPU
  path, both over the 150 ms budget. So loading starts when recording starts,
  and the GPU isn't used (it also added 30 MB of footprint, against 3 MB on the
  CPU, which keeps the int8 weights memory-mapped).
- Threshold 0.98, not the exported 0.95: 1/45 false deletes on hand-written
  clean sentences against 3/45, with the same self-correction accuracy.

Verified
- xcodebuild test on the iPhone 18 Pro simulator: 168 tests, 0 failures,
  including the new CleanupTaggerTests and DictationControllerTests
  testCleanupTaggerRunsAfterLearnedFixesAndSkipsVerbatim. After the fixtures
  were rewritten one case per line (same content), CleanupTaggerTests and
  DictationControllerTests passed again (28 tests).
- Parity on the 137 hand-written sentences at 0.98: labels match the fp32
  checkpoint on all 1,128 words, and 136/137 outputs match the ONNX int8
  pipeline. #120 ("The cat keeps trying to scratch that chair.") differs on
  two words that ONNX keeps (P 0.9725/0.9794) and Core ML deletes (0.984).
  The fp32 checkpoint also deletes them (0.9879/0.9853), so the difference
  comes from ONNX's int8 activations. 128/137 outputs match the hand-written
  targets. The tokenizer matches HF on 1,891 words, and reconstruction matches
  reconstruct.js on 670 cases.
- Simulator, CPU path: load 140-161 ms, first sentence after load about 8 ms,
  then 3.3 ms median and 7.5 ms p95 per sentence; phys_footprint +2.9 MB.
- The Release generic iOS build with CODE_SIGNING_ALLOWED=NO succeeds.
  HEXKeyboard.appex is 30.2 MB (model 27.8 MB, vocabulary 0.2 MB).
- Not verified on a physical iPhone: Neural Engine load time, latency, and the
  keyboard extension's footprint next to Apple Speech.

Note: this adds a 28.4 MB binary (weight.bin) to git; the repo has no LFS.

* Fetch the cleanup tagger's Core ML model at build time instead of committing it

The 27 MB mlpackage would have been ~30x the largest file in the repo, kept in history forever. It is now the ios-model-cleanup-tagger-1 release asset; ios/scripts/fetch-cleanup-model.sh downloads it, checks its SHA-256, and skips when the pinned copy is already in place. Xcode Cloud runs it in ci_post_clone.sh before xcodegen; the folder is gitignored.

Verified the fetched package is byte-identical to the one the tests ran against (diff -r), and a second run is a no-op.
2026-11-20 01:29:41 +00:00

437 lines
17 KiB
Swift

import SwiftUI
import UIKit
@MainActor
final class KeyboardViewController: UIInputViewController {
private let bridge = KeyboardBridge()
private let viewModel = KeyboardViewModel()
private let localDictation = KeyboardLocalDictation()
private var pollTimer: Timer?
private var coldStartJobID = UUID().uuidString
private var lastURLRefreshBucket: Int = 0
private var lastFullAccessNote: TimeInterval = 0
private var surface: UIView?
private var fullKeyboard: FullKeyboardView?
private var heightConstraint: NSLayoutConstraint?
private var pollInterval: TimeInterval = 0
private var didHandOffCurrentField = false
private var didWarmLexicon = false
/// Learn how I type: what becomes of each dictation Hex inserts.
private let dictationEdits = DictationEditTracker()
private lazy var documentTarget = DocumentProxyTextTarget { [weak self] in self?.textDocumentProxy }
override func viewDidLoad() {
super.viewDidLoad()
configureView()
syncFromBridge(animated: false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
coldStartJobID = UUID().uuidString
didHandOffCurrentField = false
// The keyboard may come back for another field: settle on where the dictation was last seen.
dictationEdits.finish(nil)
mountSurface()
fullKeyboard?.prepareForField()
handOffNumericPadIfNeeded()
syncFromBridge(animated: false)
schedulePoll(force: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
warmFullKeyboardLexiconIfNeeded()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if dictationEdits.isTracking { dictationEdits.finish(editContext) }
TypingJournal.sharedIfEnabled()?.save()
pollTimer?.invalidate()
pollTimer = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
fullKeyboard?.handleMemoryWarning()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let fullKeyboard, heightConstraint?.constant != fullKeyboard.preferredHeight {
heightConstraint?.constant = fullKeyboard.preferredHeight
preferredContentSize.height = fullKeyboard.preferredHeight
}
}
override func textWillChange(_ textInput: UITextInput?) {
super.textWillChange(textInput)
if KeyboardFieldRouting.route(for: textDocumentProxy.keyboardType) != .handOff {
didHandOffCurrentField = false
}
}
override func textDidChange(_ textInput: UITextInput?) {
super.textDidChange(textInput)
updateKeyboardTraits()
fullKeyboard?.textDidChange()
observeDictationEdits(fromKeys: false)
handOffNumericPadIfNeeded()
}
// MARK: - Learn how I type
/// Dictations are followed only while Learn how I type is on, in plain text fields
/// that allow autocorrect.
private var learnsFromDictation: Bool {
guard TypingJournalSettings().isEnabled,
case .keys(let kind, _) = KeyboardFieldRouting.route(for: textDocumentProxy.keyboardType)
else { return false }
return TypingJournal.allows(field: kind, target: documentTarget)
}
private var editContext: DictationEditTracker.Context {
DictationEditTracker.Context(
before: textDocumentProxy.documentContextBeforeInput,
after: textDocumentProxy.documentContextAfterInput,
hasText: textDocumentProxy.hasText
)
}
private func observeDictationEdits(fromKeys: Bool) {
guard dictationEdits.isTracking else { return }
dictationEdits.observe(editContext, fromKeys: fromKeys)
}
/// A return key labelled Send ends the dictation's edit window: what is there is sent.
private func returnKeyWillInsert() {
guard dictationEdits.isTracking, textDocumentProxy.returnKeyType == .send else { return }
dictationEdits.finish(editContext)
}
private func handOffNumericPadIfNeeded() {
guard fullKeyboard != nil else { return }
if KeyboardFieldRouting.route(for: textDocumentProxy.keyboardType) == .handOff {
guard !didHandOffCurrentField else { return }
didHandOffCurrentField = true
if needsInputModeSwitchKey {
advanceToNextInputMode()
}
} else {
didHandOffCurrentField = false
}
}
private func warmFullKeyboardLexiconIfNeeded() {
guard let fullKeyboard else { return }
fullKeyboard.warmUpTextCheckerAsync()
guard !didWarmLexicon else { return }
didWarmLexicon = true
// UIKit calls back on its lexicon-request queue. A main-actor closure here trips
// Swift's runtime isolation check (EXC_BREAKPOINT, TestFlight build 3), so the
// callback is nonisolated and hops to the main actor itself.
requestSupplementaryLexicon { @Sendable [weak self] lexicon in
Task { @MainActor in
self?.fullKeyboard?.loadLexicon(lexicon)
}
}
}
private func configureView() {
view.backgroundColor = .clear
viewModel.inputViewController = self
dictationEdits.onResult = { result in
TypingJournal.sharedIfEnabled()?.recordDictation(result)
}
localDictation.corrections = {
TypingJournal.sharedIfEnabled()?.dictationCorrections() ?? []
}
viewModel.onDictateTap = { [weak self] in self?.startWarmDictation() }
viewModel.onStopTap = { [weak self] in
guard let self else { return }
if self.localDictation.isActive { self.localDictation.stop() } else { self.stopWarmDictation() }
}
viewModel.onCancelTap = { [weak self] in
guard let self else { return }
if self.localDictation.isActive { self.localDictation.cancel() } else { self.cancelWarmDictation() }
}
if KeyboardLocalDictation.isSupported {
viewModel.onLocalDictateTap = { [weak self] in
guard let self else { return }
CleanupTagger.prepareIfEnabled(style: self.bridge.style)
self.localDictation.start(in: self.view, allowBluetoothMic: self.bridge.allowBluetoothMic)
}
}
viewModel.onStyleSelected = { [weak self] style in
guard let self else { return }
self.bridge.style = style
if self.viewModel.style != style {
self.viewModel.style = style
}
self.refreshColdStartURL(now: Date().timeIntervalSince1970, force: true)
}
viewModel.onReturnAppSelected = { [weak self] appID in
guard let self else { return }
self.bridge.returnAppID = appID
if self.viewModel.returnAppID != appID {
self.viewModel.returnAppID = appID
}
self.refreshColdStartURL(now: Date().timeIntervalSince1970, force: true)
}
viewModel.onSpace = { [weak self] in
self?.textDocumentProxy.insertText(" ")
self?.observeDictationEdits(fromKeys: true)
}
viewModel.onDelete = { [weak self] in
self?.textDocumentProxy.deleteBackward()
self?.observeDictationEdits(fromKeys: true)
}
viewModel.onReturn = { [weak self] in
self?.returnKeyWillInsert()
self?.textDocumentProxy.insertText("\n")
self?.observeDictationEdits(fromKeys: true)
}
viewModel.onOpenURL = { [weak self] url in
guard let self else { return }
ContainingAppOpener.open(url, from: self)
}
let heightConstraint = view.heightAnchor.constraint(equalToConstant: 140)
heightConstraint.priority = UILayoutPriority(999)
heightConstraint.isActive = true
self.heightConstraint = heightConstraint
mountSurface()
}
/// The dictation bar, or the full keyboard when its experiment is on (iPhone only).
/// Only switches while idle.
private func mountSurface() {
let wantsFull = FullKeyboardSettings().isEnabled && UIDevice.current.userInterfaceIdiom == .phone
guard surface == nil || wantsFull != (fullKeyboard != nil) else { return }
guard surface == nil || viewModel.stagePhase == .idle || viewModel.stagePhase == .failed else { return }
children.forEach { child in
child.willMove(toParent: nil)
child.removeFromParent()
}
surface?.removeFromSuperview()
fullKeyboard = nil
didWarmLexicon = false
let mounted: UIView
if wantsFull {
let keyboard = FullKeyboardView(
model: viewModel,
target: DocumentProxyTextTarget { [weak self] in self?.textDocumentProxy }
)
keyboard.hostController = self
keyboard.allowsHaptics = { [weak self] in self?.hasFullAccess ?? false }
keyboard.onTextEdit = { [weak self] in self?.observeDictationEdits(fromKeys: true) }
keyboard.onUndoDictation = { [weak self] in self?.dictationEdits.didUndo() }
keyboard.onReturnKey = { [weak self] in self?.returnKeyWillInsert() }
fullKeyboard = keyboard
mounted = keyboard
heightConstraint?.constant = keyboard.preferredHeight
} else {
let hosting = UIHostingController(
rootView: KeyboardSurfaceView(model: viewModel, defersDotScopeUntilActive: true)
)
hosting.view.backgroundColor = .clear
addChild(hosting)
hosting.didMove(toParent: self)
mounted = hosting.view
heightConstraint?.constant = 140
}
preferredContentSize.height = heightConstraint?.constant ?? 140
mounted.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(mounted)
NSLayoutConstraint.activate([
mounted.leadingAnchor.constraint(equalTo: view.leadingAnchor),
mounted.trailingAnchor.constraint(equalTo: view.trailingAnchor),
mounted.topAnchor.constraint(equalTo: view.topAnchor),
mounted.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
surface = mounted
schedulePoll(force: false)
}
/// The dictation bar polls at 25 Hz; the full keyboard at 4 Hz, and 30 Hz while recording.
private func schedulePoll(force: Bool) {
let busy = viewModel.stagePhase == .recording || viewModel.stagePhase == .transcribing
|| viewModel.pendingCommand != nil
let interval: TimeInterval = fullKeyboard == nil ? 0.04 : (busy ? 1.0 / 30 : 0.25)
guard force || (pollTimer != nil && interval != pollInterval) else { return }
pollInterval = interval
pollTimer?.invalidate()
pollTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
MainActor.assumeIsolated {
self?.syncFromBridge(animated: true)
}
}
}
private func syncFromBridge(animated: Bool) {
let now = Date().timeIntervalSince1970
updateKeyboardTraits()
fullKeyboard?.syncSettings()
#if targetEnvironment(simulator)
let simSnap = bridge.snapshot()
let effectiveFullAccess = hasFullAccess || simSnap.isAvailable(at: now)
#else
let effectiveFullAccess = hasFullAccess
#endif
guard effectiveFullAccess else {
viewModel.applyBridgeState(
hasFullAccess: false,
snapshot: .offline,
isModelInstalled: false,
style: viewModel.style,
returnAppID: viewModel.returnAppID,
now: now,
clearPending: true,
animated: animated
)
return
}
if now - lastFullAccessNote >= 5 {
lastFullAccessNote = now
bridge.fullAccessSeenAt = now
}
if dictationEdits.isTracking {
dictationEdits.tick { editContext }
}
let snap = localDictation.snapshot(now: now) ?? bridge.snapshot()
var insertedResult = false
if snap.hasDeliverableResult(at: now),
let resultID = snap.resultID,
let rawTranscript = snap.transcript,
bridge.lastInsertedResultID != resultID {
let context = editContext
let insertion = TranscriptFormatter.insertionText(
for: rawTranscript,
beforeContext: context.before,
afterContext: context.after
)
if learnsFromDictation {
dictationEdits.willInsert(heard: snap.heard, inserted: insertion, context: context)
} else {
dictationEdits.finish(context)
}
textDocumentProxy.insertText(insertion)
fullKeyboard?.didInsertDictation(insertion)
observeDictationEdits(fromKeys: true)
bridge.lastInsertedResultID = resultID
localDictation.markDelivered(resultID: resultID)
insertedResult = true
coldStartJobID = UUID().uuidString
}
let quickReturnApps = bridge.quickReturnApps
if viewModel.quickReturnApps != quickReturnApps {
viewModel.quickReturnApps = quickReturnApps
}
viewModel.applyBridgeState(
hasFullAccess: true,
snapshot: snap,
isModelInstalled: bridge.isModelInstalled,
style: bridge.style,
returnAppID: bridge.returnAppID,
now: now,
clearPending: insertedResult,
animated: animated
)
refreshColdStartURL(now: now, force: false)
schedulePoll(force: false)
}
private func refreshColdStartURL(now: TimeInterval, force: Bool) {
let bucket = Int(now / 2.0)
guard force || bucket != lastURLRefreshBucket else { return }
lastURLRefreshBucket = bucket
mountSurface()
let request: KeyboardLaunchRequest
if bridge.isModelInstalled {
request = .startRecording(
jobID: coldStartJobID,
requestedAt: now,
style: bridge.style,
returnAppID: bridge.returnAppID
)
} else {
request = .startSession(
requestedAt: now,
returnAppID: bridge.returnAppID
)
}
viewModel.coldStartURL = request.url
}
private func updateKeyboardTraits() {
let globe = needsInputModeSwitchKey
if viewModel.needsGlobeKey != globe {
viewModel.needsGlobeKey = globe
}
// Fields that ask for a dark keyboard get one even in light mode, like the system keyboard.
overrideUserInterfaceStyle = textDocumentProxy.keyboardAppearance == .dark ? .dark : .unspecified
let nextReturn: String = switch textDocumentProxy.returnKeyType {
case .send: "Send"
case .google, .yahoo, .search: "Search"
case .go: "Go"
case .done: "Done"
case .join: "Join"
case .next: "Next"
case .route: "Route"
case .continue: "Continue"
case .emergencyCall: "SOS"
default: "Return"
}
if viewModel.returnKeyLabel != nextReturn {
viewModel.returnKeyLabel = nextReturn
}
}
private func startWarmDictation() {
let now = Date().timeIntervalSince1970
guard viewModel.hasFullAccess, viewModel.currentSnapshot.isAvailable(at: now) else { return }
let jobID = UUID().uuidString
viewModel.setPendingCommand(
KeyboardViewModel.PendingCommand(kind: .start, jobID: jobID, sentAt: now),
now: now,
animated: true
)
bridge.send(.start, jobID: jobID, style: viewModel.style, sentAt: now)
}
private func stopWarmDictation() {
let now = Date().timeIntervalSince1970
guard let jobID = viewModel.currentSnapshot.jobID ?? viewModel.pendingCommand?.jobID else { return }
viewModel.setPendingCommand(
KeyboardViewModel.PendingCommand(kind: .stop, jobID: jobID, sentAt: now),
now: now,
animated: true
)
bridge.send(.stop, jobID: jobID, style: viewModel.style, sentAt: now)
}
private func cancelWarmDictation() {
let now = Date().timeIntervalSince1970
guard let jobID = viewModel.currentSnapshot.jobID ?? viewModel.pendingCommand?.jobID else { return }
viewModel.setPendingCommand(
KeyboardViewModel.PendingCommand(kind: .cancel, jobID: jobID, sentAt: now),
now: now,
animated: true
)
bridge.send(.cancel, jobID: jobID, style: viewModel.style, sentAt: now)
}
}