Use Faiss in Swift.
Based on Faiss Mobile and OpenMP Mobile.
Command line demo
$ swift run swift-faiss <subcommand> <options>
Available subcommands:
flat: create aFlatIndex, add vectors to it and search for the most similar sentences.ivfflat: create anIVFFlatIndex, train and add vectors to it and search for the most similar sentences.pq: create anPQIndex, train and add vectors to it and search for the most similar sentences.clustering: k-means clustering example.
Command line help
$ swift run swift-faiss --help
In your own code
import SwiftFaiss
let embeddings: [[Float]] = [
[0.1, 0.2, 0.3],
[0.4, 0.5, 0.6],
[0.7, 0.8, 0.9],
[1.0, 1.1, 1.2],
[1.3, 1.4, 1.5],
[1.6, 1.7, 1.8]
]
let d = embeddings[0].count
let index = try FlatIndex(d: d, metricType: .l2)
try index.add(embeddings)
let result = try index.search([[0.1, 0.5, 0.9]], k: 2)
// do something with resulthttps://github.com/jkrukowski/UseSwiftFaiss contains an iOS example.
You can use Swift Package Manager and specify dependency in Package.swift by adding:
.package(url: "https://github.com/jkrukowski/SwiftFaiss.git", from: "0.0.7")$ swift package plugin --allow-writing-to-package-directory swiftformat
$ swift test