hex/ios/HEXMobile/EmojiSemanticIndex.swift
Ryan Vogel c2d78847d4 iOS: rank emoji for the text before the cursor, on device
What changed
- EmojiLibrary maps an emoji-index file (Data .alwaysMapped) and keeps only the emoji,
  their skin tones and byte offsets: word and phrase lookups binary-search the file's
  sorted keys and parse postings in place; search scans each emoji's folded name and
  keyword words for prefixes (name words first, a short name the query fills before a
  long one it touches, then your use and everyday emoji). Emoji newer than 15.1 are
  listed only if the emoji font itself draws them as one glyph.
- EmojiSuggester reads the last eight content words (the newest counts 1, then 0.85
  each word back), their forms (plurals, -ing, -ed, held-down letters: "lmaooo"),
  two- to four-word phrases ("new year", "good luck") and the word still being typed;
  an emoji several words point at gains a third of the rest. One emoji per family
  ("man running", "woman running"); your use breaks ties and fills the row, then
  everyday defaults. forFinishedWord gives the strip at most three strong matches for
  the word just finished ("pizza " -> 🍕).
- EmojiUsageStore keeps, in the App Group, a use count per emoji that halves every 10
  days (frequency and recency in one score, at most 120 emoji) and the skin tone last
  picked for each; no words. clear() empties both.
- EmojiRoutedTarget lets the keys type into the emoji search's query instead of the
  field while you search.
- EmojiSemanticIndex (app target only, for the comparison test): Apple's on-device
  NLEmbedding word vectors over the index's 3,257 words, standing in for a context word
  with no emoji of its own. Not used by the keyboard (see Measured).
- EmojiSuggesterTests: index, folding, context, families, endings, other layouts,
  strip, search, history decay and tones, the search's routing, and quality on 60
  hand-written sentences (Fixtures/emoji-context-sentences.json, 30 to tune, 30 held
  out) with and without the embedding.

Measured (sensible emoji in the top 5, context only; top-1 in brackets)
- Simulator, iPhone 17, iOS 27.2: keywords dev 30/30 (27), held-out 30/30 (27), 0.04 ms
  a sentence; with the embedding the same counts at 0.14 ms, its index built in 120 ms.
- Mac harness, same code: CLDR keywords alone dev 26/30 (13), held-out 22/30 (14);
  with Hex's chat words 30/30 (27) and 30/30 (27). A blind set of 40 messages and
  sensible emoji written by a separate agent that saw no code or word lists: CLDR
  alone 30/40 (13), with chat words 37/40 (28), adding the embedding 37/40 (28); 38/40
  after the held-down-letter rule, which those failures suggested. Apple's sentence
  embedding scored 18/40 (7) and took 7.5 s to embed the 1,923 descriptions.
- Memory on the Mac: the mapped index adds 0.72 MB; the embedding adds 5.3 MB (1 MB
  NLEmbedding, 3.9 MB vectors) and none of it came back after release. No measurable
  gain for that, so the keyboard uses keywords and your history only.

Verified: xcodebuild test on an iPhone 17 simulator (iOS 27.2): 245 tests, 1 skipped,
0 failures.
2026-11-20 10:49:41 -05:00

85 lines
3.6 KiB
Swift

import Accelerate
import Foundation
import NaturalLanguage
/// Words near in meaning to a context word, among the emoji index's own words, from the
/// word embedding Apple ships with iOS (NaturalLanguage, on device, nothing downloaded by
/// Hex). "congrats" finds "celebration" and "party", whose emoji the words alone miss.
///
/// Built when the emoji panel opens and dropped when it closes: the vocabulary's vectors
/// are the only memory it holds beyond the system's embedding.
nonisolated final class EmojiSemanticIndex: @unchecked Sendable {
/// Below this cosine similarity a word isn't near enough to suggest anything.
static let threshold: Float = 0.55
static let neighborLimit = 6
let dimension: Int
private let embedding: NLEmbedding
private let words: [String]
/// `words.count` rows of `dimension` floats, each of unit length.
private let matrix: [Float]
var vocabularySize: Int { words.count }
var byteCount: Int { matrix.count * MemoryLayout<Float>.size }
/// Nil where iOS has no word embedding for the language (Norwegian).
init?(language: String, vocabulary: [String]) {
let nlLanguage: NLLanguage = switch language {
case "en": .english
case "es": .spanish
case "de": .german
default: NLLanguage(rawValue: language)
}
guard let embedding = NLEmbedding.wordEmbedding(for: nlLanguage) else { return nil }
let dimension = embedding.dimension
var kept: [String] = []
var matrix: [Float] = []
kept.reserveCapacity(vocabulary.count)
matrix.reserveCapacity(vocabulary.count * dimension)
// The index already leaves stopwords out.
for word in vocabulary where word.count >= 3 {
guard let vector = embedding.vector(for: word), vector.count == dimension else { continue }
Self.appendUnit(vector, to: &matrix)
kept.append(word)
}
guard !kept.isEmpty else { return nil }
self.embedding = embedding
self.dimension = dimension
self.words = kept
self.matrix = matrix
}
private static func appendUnit(_ vector: [Double], to matrix: inout [Float]) {
var norm = 0.0
vDSP_svesqD(vector, 1, &norm, vDSP_Length(vector.count))
let scale = norm > 0 ? 1 / norm.squareRoot() : 0
for value in vector { matrix.append(Float(value * scale)) }
}
/// The vocabulary words nearest `word`, most similar first, above `threshold`.
func neighbors(of word: String) -> [(word: String, similarity: Float)] {
// The embedding keeps names capitalised ("Tokyo").
guard let vector = embedding.vector(for: word) ?? embedding.vector(for: word.capitalized),
vector.count == dimension else { return [] }
var query: [Float] = []
query.reserveCapacity(dimension)
Self.appendUnit(vector, to: &query)
var scores = [Float](repeating: 0, count: words.count)
matrix.withUnsafeBufferPointer { m in
query.withUnsafeBufferPointer { q in
scores.withUnsafeMutableBufferPointer { out in
vDSP_mmul(
m.baseAddress!, 1, q.baseAddress!, 1, out.baseAddress!, 1,
vDSP_Length(words.count), 1, vDSP_Length(dimension)
)
}
}
}
var best: [(Int, Float)] = []
for (index, score) in scores.enumerated() where score >= Self.threshold {
best.append((index, score))
}
best.sort { $0.1 > $1.1 }
return best.prefix(Self.neighborLimit).map { (words[$0.0], $0.1) }
}
}