hex/ios/HEXMobileTests/CleanupTaggerTests.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

335 lines
16 KiB
Swift

import UIKit
import XCTest
@testable import HEX
/// Clean up what I say: the Swift tokenizer, Core ML model, and reconstruction against
/// fixtures generated by the tagger's reference pipeline (`train/ios_fixtures.py` in the
/// training experiment): Hugging Face's BertTokenizer, ONNX int8 and the fp32 PyTorch
/// checkpoint at the 0.98 threshold, and `js/reconstruct.js`.
final class CleanupTaggerTests: XCTestCase {
private struct HandwrittenFixture: Decodable {
struct Case: Decodable {
let id: Int
let category: String
let input: String
/// ONNX int8 labels at the threshold, rebuilt with the reference reconstruct.
let expected: String
/// The hand-written ideal cleanup.
let target: String
let labels: [Int]
let pDelete: [Double]
let checkpointLabels: [Int]
let checkpointPDelete: [Double]
}
let threshold: Double
let cases: [Case]
}
private struct TokenizerFixture: Decodable {
struct Case: Decodable {
let word: String
let ids: [Int32]
}
let cases: [Case]
}
private struct ReconstructFixture: Decodable {
struct Case: Decodable {
let words: [String]
let labels: [Int]
let output: String
}
let cases: [Case]
}
/// An ONNX label may differ only for a word whose ONNX P(DELETE) is this close to the
/// threshold: ONNX quantizes activations to int8, Core ML only the weights.
private static let borderline = 0.015
// MARK: Parity
func testHandwrittenSetMatchesTheReferencePipeline() throws {
let fixture = try Self.load(HandwrittenFixture.self, "cleanup-tagger-handwritten")
XCTAssertEqual(fixture.threshold, CleanupTagger.deleteThreshold)
let tagger = CleanupTagger()
var onnxMismatches: [String] = []
var checkpointMismatches: [String] = []
var exactVersusONNX = 0
var exactVersusTarget = 0
var words = 0
var gapONNX = 0.0
var gapCheckpoint = 0.0
for item in fixture.cases {
let split = CleanupTagger.words(in: item.input)
XCTAssertEqual(split.count, item.labels.count, "#\(item.id) splits into the reference's words")
let probabilities = try tagger.deleteProbabilities(for: split)
let labels = probabilities.map { $0 > CleanupTagger.deleteThreshold ? 1 : 0 }
let output = try tagger.clean(item.input)
words += split.count
for index in split.indices {
gapONNX = max(gapONNX, abs(probabilities[index] - item.pDelete[index]))
gapCheckpoint = max(gapCheckpoint, abs(probabilities[index] - item.checkpointPDelete[index]))
if labels[index] != item.labels[index] {
onnxMismatches.append(String(
format: "#%d %@: Core ML %.4f, ONNX %.4f, fp32 %.4f",
item.id, split[index], probabilities[index], item.pDelete[index], item.checkpointPDelete[index]
))
XCTAssertLessThan(
abs(item.pDelete[index] - CleanupTagger.deleteThreshold), Self.borderline,
"#\(item.id) '\(split[index])' disagrees with ONNX away from the threshold"
)
}
if labels[index] != item.checkpointLabels[index] {
checkpointMismatches.append("#\(item.id) \(split[index])")
}
}
if output == item.expected {
exactVersusONNX += 1
} else {
XCTAssertNotEqual(labels, item.labels, "#\(item.id): same labels must rebuild the same text")
}
if output == item.target {
exactVersusTarget += 1
}
}
XCTAssertEqual(checkpointMismatches, [], "Core ML labels match the fp32 checkpoint's")
XCTAssertLessThanOrEqual(onnxMismatches.count, 2)
print("""
CLEANUP-TAGGER parity: \(fixture.cases.count) sentences, \(words) words at \(CleanupTagger.deleteThreshold)
exact match vs ONNX int8 pipeline: \(exactVersusONNX)/\(fixture.cases.count)
exact match vs hand-written targets: \(exactVersusTarget)/\(fixture.cases.count)
label mismatches vs ONNX int8: \(onnxMismatches.count) \(onnxMismatches)
label mismatches vs fp32 checkpoint: \(checkpointMismatches.count)
max |dP| vs ONNX \(String(format: "%.4f", gapONNX)), vs fp32 \(String(format: "%.4f", gapCheckpoint))
""")
}
// MARK: Tokenizer
func testTokenizerMatchesHuggingFace() throws {
let fixture = try Self.load(TokenizerFixture.self, "cleanup-tokenizer")
let tokenizer = try Self.tokenizer()
var failures: [String] = []
for item in fixture.cases where tokenizer.encode(item.word) != item.ids {
let scalars = item.word.unicodeScalars.map { String($0.value, radix: 16) }.joined(separator: " ")
failures.append("\(scalars): \(tokenizer.encode(item.word)) != \(item.ids)")
}
XCTAssertEqual(failures, [], "\(failures.count) of \(fixture.cases.count) words")
}
func testTokenizerSplitsSpecialTokensAndStripsAccents() throws {
let tokenizer = try Self.tokenizer()
XCTAssertEqual(tokenizer.encode("[CLS]"), [CleanupTokenizer.clsID])
XCTAssertEqual(tokenizer.encode("x[SEP]y"), tokenizer.encode("x") + [CleanupTokenizer.sepID] + tokenizer.encode("y"))
XCTAssertEqual(tokenizer.encode("Café"), tokenizer.encode("cafe"))
XCTAssertEqual(tokenizer.encode("e\u{301}clair"), tokenizer.encode("eclair"))
XCTAssertEqual(tokenizer.encode(String(repeating: "a", count: 101)), [CleanupTokenizer.unknownID])
XCTAssertEqual(tokenizer.encode("4pm?"), tokenizer.encode("4pm") + tokenizer.encode("?"))
XCTAssertEqual(tokenizer.encode("\u{200B}"), [])
}
// MARK: Reconstruction
func testReconstructionMatchesTheJavaScriptReference() throws {
let fixture = try Self.load(ReconstructFixture.self, "cleanup-reconstruct")
var failures: [String] = []
for item in fixture.cases {
let output = CleanupReconstruction.reconstruct(item.words, deletes: item.labels.map { $0 == 1 })
if output != item.output {
failures.append("\(item.words) \(item.labels): \(output) != \(item.output)")
}
}
XCTAssertEqual(failures, [], "\(failures.count) of \(fixture.cases.count) cases")
}
func testReconstructionRepairsPunctuationAndCapitals() {
func rebuild(_ text: String, _ deletes: [Int]) -> String {
CleanupReconstruction.reconstruct(text.split(separator: " ").map(String.init), deletes: deletes.map { $0 == 1 })
}
XCTAssertEqual(
rebuild("Hey Tim, um, are you available on Friday at 3pm, actually 4pm?", [0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0]),
"Hey Tim, are you available on Friday at 4pm?"
)
XCTAssertEqual(rebuild("Can you, um, send it", [0, 0, 1, 0, 0]), "Can you send it")
XCTAssertEqual(rebuild("Thanks, um. See you", [0, 1, 0, 0]), "Thanks. See you")
XCTAssertEqual(rebuild("Um, so we go", [1, 0, 0, 0]), "So we go")
XCTAssertEqual(rebuild("We left... um, early", [0, 0, 1, 0]), "We left early")
XCTAssertEqual(rebuild("Call me at 5, um,", [0, 0, 0, 0, 1]), "Call me at 5")
XCTAssertEqual(rebuild("See you, uh.", [0, 0, 1]), "See you.")
// JavaScript cases the first UTF-16 unit: an emoji is never capitalized, ß becomes SS.
XCTAssertEqual(rebuild("Um, 😀ok", [1, 0]), "😀ok")
XCTAssertEqual(rebuild("Um, ßtraße", [1, 0]), "SStraße")
XCTAssertEqual(rebuild("Um, iPhone", [1, 0]), "iPhone")
XCTAssertEqual(rebuild("um uh", [1, 1]), "")
}
// MARK: Chunks
func testChunksKeepWholeWordsWithinTheModelLength() {
XCTAssertEqual(
CleanupTagger.chunks([[7, 8], [], [9]]),
[CleanupTagger.Chunk(ids: [101, 7, 8, 9, 102], firstTokens: [1, nil, 3])]
)
let chunks = CleanupTagger.chunks(Array(repeating: [5, 6], count: 70))
XCTAssertEqual(chunks.count, 2)
XCTAssertEqual(chunks.map(\.firstTokens.count), [63, 7])
XCTAssertTrue(chunks.allSatisfy { $0.ids.count <= CleanupTagger.maxTokens && $0.ids.first == 101 && $0.ids.last == 102 })
let long = CleanupTagger.chunks([[1], Array(repeating: 4, count: 200)])
XCTAssertEqual(long.map(\.ids.count), [3, CleanupTagger.maxTokens])
}
func testLongTranscriptsAreTaggedInChunks() throws {
let fixture = try Self.load(HandwrittenFixture.self, "cleanup-tagger-handwritten")
let text = fixture.cases.prefix(30).map(\.input).joined(separator: " ")
let words = CleanupTagger.words(in: text)
let tagger = CleanupTagger()
let probabilities = try tagger.deleteProbabilities(for: words)
XCTAssertEqual(probabilities.count, words.count)
XCTAssertGreaterThan(words.count, 200)
let cleaned = try tagger.clean(text)
XCTAssertLessThan(cleaned.count, text.count)
XCTAssertGreaterThan(cleaned.count, text.count / 2)
}
// MARK: Dictation entry point
func testCleanIfEnabledRunsOnlyWhenOnAndNeverForVerbatim() async throws {
let suite = "hex.tests.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let settings = CleanupTaggerSettings(defaults: defaults)
let tagger = CleanupTagger()
let spoken = "Let's ship it Tuesday, no wait, Thursday."
XCTAssertFalse(settings.isEnabled, "off by default")
var result = await CleanupTagger.cleanIfEnabled(spoken, style: .polished, settings: settings, tagger: tagger)
XCTAssertEqual(result, spoken)
XCTAssertFalse(tagger.isLoaded, "nothing loads while the experiment is off")
settings.isEnabled = true
result = await CleanupTagger.cleanIfEnabled(spoken, style: .verbatim, settings: settings, tagger: tagger)
XCTAssertEqual(result, spoken)
result = await CleanupTagger.cleanIfEnabled(" ", style: .casual, settings: settings, tagger: tagger)
XCTAssertEqual(result, " ")
XCTAssertFalse(tagger.isLoaded)
tagger.prepare()
XCTAssertTrue(tagger.isLoaded)
for style in [DictationStyle.polished, .casual, .notes] {
result = await CleanupTagger.cleanIfEnabled(spoken, style: style, settings: settings, tagger: tagger)
XCTAssertEqual(result, "Let's ship it Thursday.", "\(style)")
}
result = await CleanupTagger.cleanIfEnabled("I mean what I say.", style: .polished, settings: settings, tagger: tagger)
XCTAssertEqual(result, "I mean what I say.", "a sentence with nothing to remove comes back as said")
}
func testDictationStartPreparesOnlyWhenOnAndNotForVerbatim() throws {
let suite = "hex.tests.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let settings = CleanupTaggerSettings(defaults: defaults)
let tagger = CleanupTagger()
CleanupTagger.prepareIfEnabled(style: .polished, settings: settings, tagger: tagger)
XCTAssertFalse(tagger.isLoaded)
settings.isEnabled = true
CleanupTagger.prepareIfEnabled(style: .verbatim, settings: settings, tagger: tagger)
XCTAssertFalse(tagger.isLoaded)
CleanupTagger.prepareIfEnabled(style: .casual, settings: settings, tagger: tagger)
XCTAssertTrue(tagger.isLoaded)
}
func testALateCleanupKeepsTheTranscriptAndStillLoads() async throws {
let tagger = CleanupTagger()
let spoken = "Can you send it to John, I mean Mike?"
let late = await tagger.clean(spoken, within: 0)
XCTAssertEqual(late, spoken)
XCTAssertTrue(tagger.isLoaded, "the late run finishes loading for the next dictation")
let warm = await tagger.clean(spoken, within: 5)
XCTAssertEqual(warm, "Can you send it to Mike?")
}
func testMemoryWarningReleasesTheModel() throws {
let tagger = CleanupTagger()
XCTAssertEqual(try tagger.clean("Let's ship it Tuesday, no wait, Thursday."), "Let's ship it Thursday.")
XCTAssertTrue(tagger.isLoaded)
NotificationCenter.default.post(name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
XCTAssertFalse(tagger.isLoaded)
XCTAssertEqual(try tagger.clean("Let's ship it Tuesday, no wait, Thursday."), "Let's ship it Thursday.")
}
// MARK: Measurements
/// Simulator numbers only (Core ML runs on the CPU there). Printed for the report.
func testLatencyAndFootprint() throws {
let fixture = try Self.load(HandwrittenFixture.self, "cleanup-tagger-handwritten")
let tagger = CleanupTagger()
let before = Self.footprintMB()
var start = CFAbsoluteTimeGetCurrent()
tagger.prepare()
XCTAssertTrue(tagger.isLoaded)
let load = (CFAbsoluteTimeGetCurrent() - start) * 1000
start = CFAbsoluteTimeGetCurrent()
_ = try tagger.clean(fixture.cases[0].input)
let first = (CFAbsoluteTimeGetCurrent() - start) * 1000
let loaded = Self.footprintMB()
var times: [Double] = []
for _ in 0..<3 {
for item in fixture.cases {
start = CFAbsoluteTimeGetCurrent()
_ = try tagger.clean(item.input)
times.append((CFAbsoluteTimeGetCurrent() - start) * 1000)
}
}
let afterRuns = Self.footprintMB()
times.sort()
let median = times[times.count / 2]
let p95 = times[times.count * 95 / 100]
tagger.unload()
XCTAssertFalse(tagger.isLoaded)
let released = Self.footprintMB()
XCTAssertLessThan(median, CleanupTagger.timeBudget * 1000)
XCTAssertLessThan(first, CleanupTagger.timeBudget * 1000, "a prepared model cleans the first dictation in budget")
print(String(
format: "CLEANUP-TAGGER latency (simulator): load %.1f ms, first sentence after load %.1f ms; per sentence median %.2f ms, p95 %.2f ms, max %.2f ms over %d runs",
load, first, median, p95, times.last ?? 0, times.count
))
print(String(
format: "CLEANUP-TAGGER footprint (simulator): before %.1f MB, loaded %.1f MB (+%.1f), after runs %.1f MB (+%.1f), after unload %.1f MB",
before, loaded, loaded - before, afterRuns, afterRuns - before, released
))
}
// MARK: Helpers
private static func tokenizer() throws -> CleanupTokenizer {
let url = try XCTUnwrap(
CleanupTagger.resourceURL(CleanupTagger.vocabularyName, withExtension: "txt"),
"the vocabulary ships in the keyboard extension"
)
return try CleanupTokenizer(vocabulary: String(contentsOf: url, encoding: .utf8))
}
private static func load<T: Decodable>(_ type: T.Type, _ name: String) throws -> T {
let url = try XCTUnwrap(Bundle(for: CleanupTaggerTests.self).url(forResource: name, withExtension: "json"))
return try JSONDecoder().decode(T.self, from: Data(contentsOf: url))
}
private static func footprintMB() -> Double {
var info = task_vm_info_data_t()
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<natural_t>.size)
let result = withUnsafeMutablePointer(to: &info) {
$0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
}
}
return result == KERN_SUCCESS ? Double(info.phys_footprint) / 1_048_576 : -1
}
}