mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS: Italian, French and Portuguese full-keyboard layouts that autocorrect in their own language A TestFlight tester on build 31 with an Italian iPhone reported that Hex kept autocorrecting their Italian into English. KeyboardLanguage only knew en, nb, es and de, so Automatic mapped an it-IT dictation language (and any other language without a layout) to English: English letters, and UITextChecker's en_US dictionary rewriting Italian words. Adds italian/french/portuguese cases. They type on the English QWERTY rows (Apple's Italian and Portuguese keyboards are QWERTY; Hex has no AZERTY yet, so French is QWERTY too), with their own long-press accent order (Italian à è ì ò ù, é right after è), their UITextChecker dictionary (it, fr, pt_BR then pt_PT), and an Italian common two-letter list. Automatic now resolves it-*, fr-* and pt-* to these; the dictation language still wins over the iPhone's keyboards, and Hebrew or Russian still get English. Automatic deliberately ignores Hex's own input mode: its primaryLanguage is the Info.plist's en-US whatever you type. Spatial autocorrect (#2059) only has en and es models; the new layouts get no model and fall back to the dictionary engine in their own language (the decoder also refuses a model of another language). The space bar already names the dictation language ("Italiano"). Snapshot scenes get Italian, French and Portuguese drafts (--dictation-language it-IT, --keyboard-layout it|fr|pt). Verified on an iOS 27.2 iPhone 17 Pro simulator: full HEXMobileTests suite (272 tests, 0 failures, 1 skipped as before). New cases in KeyboardLayoutTests, AutocorrectEngineTests and FullKeyboardEngineTests. Measured on 12 Italian sentences (19 one-slip typos, 59 correct words) with the real dictionary: English fallback fixed 4, miscorrected 4 and broke 19 correct words (Domani->Domain, stai->stay, Sono->Soon, molto->moto); Italian fixed 17, miscorrected 0 and broke none. Renders of the Italian keyboard (typing with the "ritardo" suggestion, the E and I accent menus, "Italiano" on the space bar) checked by eye. * iOS: spoken "at the rate" and "at sign" become "@", joining a spoken email address An Indian English TestFlight tester (build 32) said "at the rate", India's name for @, and got the words. Apple's on-device models don't fix it: checked on macOS 27.2 with Hex's settings and an en_IN voice, SpeechTranscriber (Hex's default) writes "My email is John at the rategmail.com." and "Send it to Priya at signyahoo.com." (gluing the domain to the word before), and DictationTranscriber writes "at the rate gmail.com", though it already writes "priya@yahoo.com" for "at sign" and "john@gmail.com" for "john at gmail dot com". SpokenCleanupRules.spokenSymbols (English only) turns "at the rate" and "at sign" into "@". Before a domain ("gmail dot com", "gmail.com", "co dot in", or glued as above), the word before (with any "dot"-joined parts) and the domain join into one lowercase address, "dot" becoming "." only there: "John at the rate Gmail dot com." becomes "john@gmail.com.". "at the rate" counts only before a domain, so "at the rate of 5%" and "at the rate we planned" stay, and "at" alone is never touched; "at sign" elsewhere is a lone "@" (but not in "at sign language"). Only the matched words change. It runs from CleanupTagger.cleanIfEnabled, which both the app's and in-keyboard dictation call: in every style but Verbatim, with Clean up what I say on or off (the experiment's guard moved below it; the tagger itself still only runs when on). TranscriptFormatter: Polished capitalized after every full stop, which would have written "john@gmail.Com."; a sentence now starts only after ".", "!" or "?" and a space, an address keeps its case (Polished and Notes), and a lone address gets no full stop. Verified on an iOS 27.2 simulator: full HEXMobileTests suite (272 tests, 0 failures, 1 skipped as before), with new cases in TranscriptCleanupTests (Apple's real outputs included) and CleanupTaggerTests.
389 lines
19 KiB
Swift
389 lines
19 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")
|
|
}
|
|
|
|
/// Spoken "@" runs in every style but Verbatim, with the experiment off too, so both the
|
|
/// app's and the keyboard's dictation get it.
|
|
func testSpokenAtSignsApplyWithTheExperimentOffButNotInVerbatim() 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 = "Mail it to john at the rate gmail dot com."
|
|
|
|
XCTAssertFalse(settings.isEnabled)
|
|
for style in [DictationStyle.polished, .casual, .notes] {
|
|
let result = await CleanupTagger.cleanIfEnabled(spoken, style: style, language: "en-IN", settings: settings, tagger: tagger)
|
|
XCTAssertEqual(result, "Mail it to john@gmail.com.", "\(style)")
|
|
}
|
|
let verbatim = await CleanupTagger.cleanIfEnabled(spoken, style: .verbatim, language: "en-IN", settings: settings, tagger: tagger)
|
|
XCTAssertEqual(verbatim, spoken)
|
|
let spanish = await CleanupTagger.cleanIfEnabled(spoken, style: .polished, language: "es-ES", settings: settings, tagger: tagger)
|
|
XCTAssertEqual(spanish, spoken)
|
|
XCTAssertFalse(tagger.isLoaded, "the experiment's model stays unloaded")
|
|
}
|
|
|
|
/// The English tagger never runs on another language: on Spanish it dropped negations
|
|
/// ("Te digo que no puedo ir" became "Te puedo ir"). Spanish, German and Norwegian get
|
|
/// word rules; the rest stay as heard.
|
|
func testOtherLanguagesGetRulesNeverTheEnglishTagger() 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)
|
|
settings.isEnabled = true
|
|
let tagger = CleanupTagger()
|
|
|
|
for (language, spoken, cleaned) in [
|
|
("nb-NO", "Vi sender den tirsdag, nei vent, torsdag.", "Vi sender den torsdag."),
|
|
("es-MX", "Te digo que no puedo ir.", "Te digo que no puedo ir."),
|
|
("es-ES", "Nos vemos a las 3, digo, a las 4.", "Nos vemos a las 4."),
|
|
("de-DE", "Wir treffen uns um 3, nein, um 4.", "Wir treffen uns um 4."),
|
|
("fr-FR", "On se voit mardi, non, jeudi.", "On se voit mardi, non, jeudi."),
|
|
] {
|
|
CleanupTagger.prepareIfEnabled(style: .polished, language: language, settings: settings, tagger: tagger)
|
|
let result = await CleanupTagger.cleanIfEnabled(spoken, style: .polished, language: language, settings: settings, tagger: tagger)
|
|
XCTAssertEqual(result, cleaned, language)
|
|
let verbatim = await CleanupTagger.cleanIfEnabled(spoken, style: .verbatim, language: language, settings: settings, tagger: tagger)
|
|
XCTAssertEqual(verbatim, spoken, "\(language) Verbatim")
|
|
}
|
|
XCTAssertFalse(tagger.isLoaded, "no other language loads the model")
|
|
|
|
let english = await CleanupTagger.cleanIfEnabled(
|
|
"Let's ship it Tuesday, no wait, Thursday.", style: .polished, language: "en-GB", settings: settings, tagger: tagger
|
|
)
|
|
XCTAssertEqual(english, "Let's ship it Thursday.")
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|