use pigeonhole_format::vector as fmt;
use crate::{Error, ErrorCode, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Element {
F32,
I8,
Bit,
F16,
BF16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Metric {
L2,
InnerProduct,
Cosine,
Hamming,
}
impl Element {
fn to_format(self) -> fmt::Element {
match self {
Element::F32 => fmt::Element::F32,
Element::I8 => fmt::Element::I8,
Element::Bit => fmt::Element::Bit,
Element::F16 => fmt::Element::F16,
Element::BF16 => fmt::Element::BF16,
}
}
fn from_format(e: fmt::Element) -> Self {
match e {
fmt::Element::F32 => Element::F32,
fmt::Element::I8 => Element::I8,
fmt::Element::Bit => Element::Bit,
fmt::Element::F16 => Element::F16,
fmt::Element::BF16 => Element::BF16,
}
}
}
impl Metric {
fn to_format(self) -> fmt::Metric {
match self {
Metric::L2 => fmt::Metric::L2,
Metric::InnerProduct => fmt::Metric::InnerProduct,
Metric::Cosine => fmt::Metric::Cosine,
Metric::Hamming => fmt::Metric::Hamming,
}
}
fn from_format(m: fmt::Metric) -> Self {
match m {
fmt::Metric::L2 => Metric::L2,
fmt::Metric::InnerProduct => Metric::InnerProduct,
fmt::Metric::Cosine => Metric::Cosine,
fmt::Metric::Hamming => Metric::Hamming,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VectorSpec {
params: fmt::Params,
}
impl VectorSpec {
pub fn new(dim: u32, element: Element, metric: Metric) -> Result<Self> {
fmt::Params::new(element.to_format(), dim, metric.to_format())
.map(|params| Self { params })
.map_err(invalid)
}
pub fn dim(&self) -> u32 {
self.params.dim
}
pub fn element(&self) -> Element {
Element::from_format(self.params.element)
}
pub fn metric(&self) -> Metric {
Metric::from_format(self.params.metric)
}
pub fn distance_f32(&self, query: &[f32], stored: VectorRef<'_>) -> Result<f64> {
self.distance(fmt::Query::F32(query), stored)
}
pub fn distance_i8(&self, query: &[i8], stored: VectorRef<'_>) -> Result<f64> {
self.distance(fmt::Query::I8(query), stored)
}
pub fn distance_bits(&self, query: &[u8], stored: VectorRef<'_>) -> Result<f64> {
self.distance(fmt::Query::Bits(query), stored)
}
fn distance(&self, q: fmt::Query<'_>, stored: VectorRef<'_>) -> Result<f64> {
self.params.check(q).map_err(invalid)?;
if !self.params.accepts(&stored.inner) {
return Err(Error::new(
ErrorCode::InvalidArgument,
"the stored vector is not of this spec",
));
}
Ok(self.params.distance(q, &stored.inner))
}
pub(crate) fn from_kind_params(params: &[u8]) -> Option<Self> {
fmt::Params::parse(params)
.ok()
.map(|params| Self { params })
}
pub(crate) fn kind_params(&self) -> Vec<u8> {
self.params.encode()
}
pub(crate) fn params(&self) -> &fmt::Params {
&self.params
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct VectorRef<'a> {
inner: fmt::VectorRef<'a>,
}
impl<'a> VectorRef<'a> {
pub(crate) fn new(inner: fmt::VectorRef<'a>) -> Self {
Self { inner }
}
pub fn element(&self) -> Element {
Element::from_format(self.inner.element())
}
pub fn dim(&self) -> u32 {
self.inner.dim()
}
pub fn as_bytes(&self) -> &'a [u8] {
self.inner.as_bytes()
}
pub fn to_f32_vec(&self) -> Option<Vec<f32>> {
if self.inner.element() == fmt::Element::Bit {
return None;
}
let mut out = Vec::with_capacity(self.dim() as usize);
self.widen_into(&mut out).then_some(out)
}
pub fn widen_into(&self, out: &mut Vec<f32>) -> bool {
let p = self.inner.as_bytes();
match self.inner.element() {
fmt::Element::F32 => {
out.extend(p.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)));
}
fmt::Element::I8 => out.extend(p.iter().map(|b| f32::from(*b as i8))),
fmt::Element::F16 => out.extend(
p.as_chunks::<2>()
.0
.iter()
.map(|c| pigeonhole_format::half::f16_to_f32(u16::from_le_bytes(*c))),
),
fmt::Element::BF16 => out.extend(
p.as_chunks::<2>()
.0
.iter()
.map(|c| pigeonhole_format::half::bf16_to_f32(u16::from_le_bytes(*c))),
),
fmt::Element::Bit => return false,
}
true
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Vector {
element: fmt::Element,
dim: u32,
payload: Vec<u8>,
}
impl Vector {
pub fn from_f32(components: &[f32]) -> Result<Self> {
let payload = components.iter().flat_map(|x| x.to_le_bytes()).collect();
Self::new(fmt::Element::F32, components.len(), payload)
}
pub fn from_i8(components: &[i8]) -> Result<Self> {
let payload = components.iter().map(|x| *x as u8).collect();
Self::new(fmt::Element::I8, components.len(), payload)
}
pub fn from_f16_bits(bits: &[u16]) -> Result<Self> {
let payload = bits.iter().flat_map(|h| h.to_le_bytes()).collect();
Self::new(fmt::Element::F16, bits.len(), payload)
}
pub fn from_bf16_bits(bits: &[u16]) -> Result<Self> {
let payload = bits.iter().flat_map(|h| h.to_le_bytes()).collect();
Self::new(fmt::Element::BF16, bits.len(), payload)
}
pub fn from_bits(dim: u32, bits: &[u8]) -> Result<Self> {
if bits.len() as u64 * 8 != u64::from(dim) {
return Err(Error::new(
ErrorCode::InvalidArgument,
"a bit vector of dim bits is dim / 8 bytes",
));
}
Self::new(fmt::Element::Bit, dim as usize, bits.to_vec())
}
fn new(element: fmt::Element, dim: usize, payload: Vec<u8>) -> Result<Self> {
let dim =
u32::try_from(dim).map_err(|_| invalid(fmt::VectorError("too many dimensions")))?;
fmt::VectorRef::new(element, dim, &payload).map_err(invalid)?;
Ok(Self {
element,
dim,
payload,
})
}
pub fn element(&self) -> Element {
Element::from_format(self.element)
}
pub fn dim(&self) -> u32 {
self.dim
}
pub fn as_ref(&self) -> VectorRef<'_> {
VectorRef::new(
fmt::VectorRef::new(self.element, self.dim, &self.payload).expect("checked when made"),
)
}
}
fn invalid(e: fmt::VectorError) -> Error {
Error::new(ErrorCode::InvalidArgument, e.0)
}
pub(crate) fn payload(spec: &VectorSpec, q: fmt::Query<'_>, out: &mut Vec<u8>) -> Result<()> {
spec.params().payload(q, out).map_err(invalid)
}