SPB Git

Repository Public License

MemoryText.swift 12.2 KB 248 lines swift

1// MemoryEngine — chunking, snippets, rank fusion and the exact vector scan.2import Accelerate3import Foundation4import NaturalLanguage56public enum MemoryChunker {7    /// Splits text into overlapping chunks of about `target` characters without cutting sentences.8    ///9    /// Paragraphs (blank-line separated) are split into sentences with `NLTokenizer`; sentences are packed10    /// until the target is reached; a chunk prefers to end at a paragraph boundary once it is half full; the11    /// next chunk starts with the last sentences of the previous one (at most `overlap` characters) so a fact12    /// stated across a boundary is still found. A single sentence longer than `maximum` is cut at a space.13    public static func chunks(of text: String, target: Int = 900, overlap: Int = 150, maximum: Int = 1_400) -> [String] {14        let target = max(50, target), maximum = max(target, maximum), overlap = max(0, min(overlap, target / 2))15        var units: [(text: String, endsParagraph: Bool)] = []16        let tokenizer = NLTokenizer(unit: .sentence)17        for paragraph in paragraphs(of: text) {18            var sentences: [String] = []19            tokenizer.string = paragraph20            tokenizer.enumerateTokens(in: paragraph.startIndex..<paragraph.endIndex) { range, _ in21                let sentence = paragraph[range].trimmingCharacters(in: .whitespacesAndNewlines)22                if !sentence.isEmpty { sentences.append(sentence) }23                return true24            }25            if sentences.isEmpty { sentences = [paragraph] }26            let pieces = sentences.flatMap { split($0, maximum: maximum) }27            for (index, piece) in pieces.enumerated() { units.append((piece, index == pieces.count - 1)) }28        }29        var chunks: [String] = []30        var current: [(text: String, endsParagraph: Bool)] = []31        var length = 032        func flush() {33            guard !current.isEmpty else { return }34            chunks.append(join(current))35            // Carry the tail over as context for the next chunk.36            var carried: [(text: String, endsParagraph: Bool)] = []37            var carriedLength = 038            for unit in current.reversed() {39                guard carriedLength + unit.text.count <= overlap else { break }40                carried.insert(unit, at: 0)41                carriedLength += unit.text.count + 142            }43            if carried.count == current.count { carried = [] }   // never repeat a whole chunk44            current = carried45            length = carriedLength46        }47        var fresh = 0   // units added since the last flush (so the overlap alone is never emitted)48        for unit in units {49            if fresh > 0, length + unit.text.count > target { flush(); fresh = 0 }50            current.append(unit)51            length += unit.text.count + 152            fresh += 153            if unit.endsParagraph, length >= target / 2 { flush(); fresh = 0 }54        }55        if fresh > 0 { flush() }56        return chunks57    }5859    static func paragraphs(of text: String) -> [String] {60        var result: [String] = []61        var lines: [Substring] = []62        func close() {63            let paragraph = lines.map { $0.split(whereSeparator: { $0 == " " || $0 == "\t" }).joined(separator: " ") }64                .filter { !$0.isEmpty }.joined(separator: " ")65            if !paragraph.isEmpty { result.append(paragraph) }66            lines = []67        }68        for line in text.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) {69            if line.allSatisfy(\.isWhitespace) { close() } else { lines.append(line) }70        }71        close()72        return result73    }7475    private static func split(_ sentence: String, maximum: Int) -> [String] {76        guard sentence.count > maximum else { return [sentence] }77        var pieces: [String] = []78        var current = ""79        for word in sentence.split(separator: " ") {80            if !current.isEmpty, current.count + word.count + 1 > maximum { pieces.append(current); current = "" }81            var word = Substring(word)82            while word.count > maximum {   // a "word" with no space at all (a data URL, a hash)83                pieces.append(String(word.prefix(maximum)))84                word = word.dropFirst(maximum)85            }86            current += current.isEmpty ? String(word) : " \(word)"87        }88        if !current.isEmpty { pieces.append(current) }89        return pieces90    }9192    private static func join(_ units: [(text: String, endsParagraph: Bool)]) -> String {93        var text = ""94        for (index, unit) in units.enumerated() {95            text += unit.text96            if index < units.count - 1 { text += unit.endsParagraph ? "\n\n" : " " }97        }98        return text99    }100}101102/// A piece of a chunk shown in results, with the places to emphasise.103public struct MemorySnippet: Sendable, Hashable {104    public var text: String105    /// UTF-16 ranges of `text` that match a query word (usable as `NSRange`s).106    public var highlights: [Range<Int>]107108    /// Builds a snippet of about `length` characters around the first query word found in `text`. Matching109    /// ignores case and diacritics. When no word occurs (a purely semantic hit) the snippet is the beginning.110    public static func make(from text: String, queryWords: [String], length: Int = 240) -> MemorySnippet {111        let options: String.CompareOptions = [.caseInsensitive, .diacriticInsensitive]112        let words = queryWords.filter { !$0.isEmpty }113        var first: Range<String.Index>?114        for word in words {115            if let range = text.range(of: word, options: options), range.lowerBound < (first?.lowerBound ?? text.endIndex) { first = range }116        }117        var start = text.startIndex118        if let first {119            let lead = text.distance(from: text.startIndex, to: first.lowerBound)120            start = text.index(text.startIndex, offsetBy: max(0, lead - length / 3))121        }122        var end = text.index(start, offsetBy: length, limitedBy: text.endIndex) ?? text.endIndex123        // Do not cut words: move inwards to the nearest space.124        if start > text.startIndex, let space = text[start...].firstIndex(where: \.isWhitespace), space < (first?.lowerBound ?? end) {125            start = text.index(after: space)126        }127        if end < text.endIndex, let space = text[start..<end].lastIndex(where: \.isWhitespace), space > (first?.upperBound ?? start) { end = space }128        var snippet = text[start..<end].split(whereSeparator: \.isNewline).joined(separator: " ")129        if start > text.startIndex { snippet = "…" + snippet }130        if end < text.endIndex { snippet += "…" }131        var highlights: [Range<Int>] = []132        for word in Set(words) {133            var searchStart = snippet.startIndex134            while let range = snippet.range(of: word, options: options, range: searchStart..<snippet.endIndex) {135                let lower = snippet.utf16.distance(from: snippet.utf16.startIndex, to: range.lowerBound)136                let upper = snippet.utf16.distance(from: snippet.utf16.startIndex, to: range.upperBound)137                highlights.append(lower..<upper)138                searchStart = range.upperBound139            }140        }141        highlights.sort { ($0.lowerBound, $0.upperBound) < ($1.lowerBound, $1.upperBound) }142        // Merge overlapping matches ("art" inside "article").143        var merged: [Range<Int>] = []144        for range in highlights {145            if let last = merged.last, range.lowerBound <= last.upperBound {146                merged[merged.count - 1] = last.lowerBound..<max(last.upperBound, range.upperBound)147            } else {148                merged.append(range)149            }150        }151        return MemorySnippet(text: snippet, highlights: merged)152    }153}154155public enum MemoryRanking {156    /// Reciprocal rank fusion: `score(d) = Σ 1 / (k + rank_list(d))` over the lists that contain `d`, ranks157    /// starting at 1. It needs no score calibration between BM25 and cosine similarity, which are not158    /// comparable. Ties are broken by the better best rank, then by id, so the order is deterministic.159    public static func fuse(_ lists: [[Int64]], k: Double = 60) -> [(id: Int64, score: Double)] {160        var scores: [Int64: Double] = [:]161        var best: [Int64: Int] = [:]162        for list in lists {163            var seen = Set<Int64>()164            for (index, id) in list.enumerated() where seen.insert(id).inserted {165                scores[id, default: 0] += 1 / (k + Double(index + 1))166                best[id] = min(best[id] ?? .max, index)167            }168        }169        return scores.map { (id: $0.key, score: $0.value) }.sorted {170            if $0.score != $1.score { return $0.score > $1.score }171            if best[$0.id] != best[$1.id] { return (best[$0.id] ?? .max) < (best[$1.id] ?? .max) }172            return $0.id < $1.id173        }174    }175}176177/// All embeddings of one model in one contiguous row-major matrix, for an exact cosine scan.178///179/// Rows are L2-normalised when stored, so cosine similarity is a dot product and the whole scan is a single180/// matrix × vector product (`vDSP_mmul`). No approximate index: see docs/MEMORY.md for the measured cost.181struct MemoryVectorMatrix: Sendable {182    let dimension: Int183    private(set) var chunkIDs: [Int64] = []184    private(set) var documentIDs: [Int64] = []185    private(set) var storage: [Float] = []186187    init(dimension: Int, capacity: Int = 0) {188        self.dimension = dimension189        chunkIDs.reserveCapacity(capacity); documentIDs.reserveCapacity(capacity); storage.reserveCapacity(capacity * dimension)190    }191192    var count: Int { chunkIDs.count }193    var byteSize: Int { storage.count * MemoryLayout<Float>.size }194195    static func normalised(_ vector: [Float]) -> [Float]? {196        guard !vector.isEmpty, vector.allSatisfy(\.isFinite) else { return nil }197        var norm: Float = 0198        vDSP_svesq(vector, 1, &norm, vDSP_Length(vector.count))199        norm = norm.squareRoot()200        guard norm > 0 else { return nil }201        var result = [Float](repeating: 0, count: vector.count)202        var divisor = norm203        vDSP_vsdiv(vector, 1, &divisor, &result, 1, vDSP_Length(vector.count))204        return result205    }206207    static func data(_ vector: [Float]) -> Data { vector.withUnsafeBufferPointer { Data(buffer: $0) } }208209    static func vector(from data: Data, dimension: Int) -> [Float]? {210        guard dimension > 0, data.count == dimension * MemoryLayout<Float>.size else { return nil }211        return data.withUnsafeBytes { raw in Array(raw.bindMemory(to: Float.self)) }212    }213214    mutating func append(chunkID: Int64, documentID: Int64, vector: [Float]) {215        guard vector.count == dimension else { return }216        chunkIDs.append(chunkID); documentIDs.append(documentID); storage.append(contentsOf: vector)217    }218219    /// The `limit` most similar rows, best first. `query` must be normalised. `allowedDocuments` restricts the220    /// result to those documents (filters); `nil` means all.221    func top(_ limit: Int, query: [Float], minimumSimilarity: Float = -1, allowedDocuments: Set<Int64>? = nil) -> [(chunkID: Int64, documentID: Int64, similarity: Float)] {222        guard limit > 0, count > 0, query.count == dimension else { return [] }223        var scores = [Float](repeating: 0, count: count)224        storage.withUnsafeBufferPointer { matrix in225            query.withUnsafeBufferPointer { vector in226                vDSP_mmul(matrix.baseAddress!, 1, vector.baseAddress!, 1, &scores, 1, vDSP_Length(count), 1, vDSP_Length(dimension))227            }228        }229        // Keep the best `limit` in a small sorted buffer: O(n) for the scan, O(limit) per insertion.230        var best: [(index: Int, score: Float)] = []231        best.reserveCapacity(limit + 1)232        var threshold = minimumSimilarity233        for index in 0..<count {234            let score = scores[index]235            guard score >= threshold, score.isFinite else { continue }236            if let allowedDocuments, !allowedDocuments.contains(documentIDs[index]) { continue }237            var position = best.count238            while position > 0, best[position - 1].score < score { position -= 1 }239            best.insert((index, score), at: position)240            if best.count > limit {241                best.removeLast()242                threshold = max(threshold, best[best.count - 1].score)243            }244        }245        return best.map { (chunkIDs[$0.index], documentIDs[$0.index], $0.score) }246    }247}248
Files main
Menu

Theme