Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Add scalar quantization support to vectors, closes #583

davidmezzetti0f35409219be
diff --git a/src/python/txtai/embeddings/index/transform.py b/src/python/txtai/embeddings/index/transform.py
index 6a08760e..2f3149ff 100644
--- a/src/python/txtai/embeddings/index/transform.py
+++ b/src/python/txtai/embeddings/index/transform.py
@@ -40,6 +40,10 @@ class Transform:
self.offset = embeddings.config.get("offset", 0) if action == Action.UPSERT else 0
self.batch = embeddings.config.get("batch", 1024)
+ # Scalar quantization
+ quantize = embeddings.config.get("quantize")
+ self.qbits = quantize if isinstance(quantize, int) and not isinstance(quantize, bool) else None
+
# Transform columns
columns = embeddings.config.get("columns", {})
self.text = columns.get("text", "text")
@@ -93,7 +97,11 @@ class Transform:
# Check that embeddings are available and load as a memmap
embeddings = None
if ids:
- embeddings = np.memmap(buffer, dtype=np.float32, shape=(len(ids), dimensions), mode="w+")
+ # Determine dtype
+ dtype = np.uint8 if self.qbits else np.float32
+
+ # Write batches
+ embeddings = np.memmap(buffer, dtype=dtype, shape=(len(ids), dimensions), mode="w+")
with open(stream, "rb") as queue:
x = 0
for _ in range(batches):
diff --git a/src/python/txtai/vectors/base.py b/src/python/txtai/vectors/base.py
index 3cbc33fd..c8c9f471 100644
--- a/src/python/txtai/vectors/base.py
+++ b/src/python/txtai/vectors/base.py
@@ -44,6 +44,10 @@ class Vectors:
# Embeddings instructions
self.instructions = config.get("instructions")
+ # Scalar quantization - supports 1-bit through 8-bit quantization
+ quantize = config.get("quantize")
+ self.qbits = max(min(quantize, 8), 1) if isinstance(quantize, int) and not isinstance(quantize, bool) else None
+
def load(self, path):
"""
Loads vector model at path.
@@ -141,7 +145,7 @@ class Vectors:
if documents and isinstance(documents[0], np.ndarray):
return np.array(documents, dtype=np.float32)
- return self.encode(documents)
+ return self.vectorize(documents)
def batch(self, documents, output):
"""
@@ -161,7 +165,7 @@ class Vectors:
dimensions = None
# Build embeddings
- embeddings = self.encode(documents)
+ embeddings = self.vectorize(documents)
if embeddings is not None:
dimensions = embeddings.shape[1]
pickle.dump(embeddings, output, protocol=__pickle__)
@@ -189,3 +193,73 @@ class Vectors:
data = f"{self.instructions[category]}{data}"
return data
+
+ def vectorize(self, data):
+ """
+ Runs data vectorization, which consists of the following steps.
+
+ 1. Encode data into vectors using underlying model
+ 2. Normalize vectors
+ 3. Quantize vectors, if necessary
+
+ Args:
+ data: input data
+
+ Returns:
+ embeddings vectors
+ """
+
+ # Transform data into vectors
+ embeddings = self.encode(data)
+
+ if embeddings is not None:
+ # Normalize data
+ self.normalize(embeddings)
+
+ # Apply quantization, if necessary
+ if self.qbits:
+ embeddings = self.quantize(embeddings)
+
+ return embeddings
+
+ def normalize(self, embeddings):
+ """
+ Normalizes embeddings using L2 normalization. Operation applied directly on array.
+
+ Args:
+ embeddings: input embeddings
+ """
+
+ # Calculation is different for matrices vs vectors
+ if len(embeddings.shape) > 1:
+ embeddings /= np.linalg.norm(embeddings, axis=1)[:, np.newaxis]
+ else:
+ embeddings /= np.linalg.norm(embeddings)
+
+ def quantize(self, embeddings):
+ """
+ Quantizes embeddings using scalar quantization.
+
+ Args:
+ embeddings: input embeddings
+
+ Returns:
+ quantized embeddings
+ """
+
+ # Scale factor is midpoint in range
+ factor = 2 ** (self.qbits - 1)
+
+ # Quantize to uint8
+ scalars = embeddings * factor
+ scalars = scalars.clip(-factor, factor - 1) + factor
+ scalars = scalars.astype(np.uint8)
+
+ # Transform uint8 to bits
+ bits = np.unpackbits(scalars.reshape(-1, 1), axis=1)
+
+ # Remove unused bits (i.e. for 3-bit quantization, the leading 5 bits are removed)
+ bits = bits[:, -self.qbits :]
+
+ # Reshape using original data dimensions and pack bits into uint8 array
+ return np.packbits(bits.reshape(embeddings.shape[0], embeddings.shape[1] * self.qbits), axis=1)
diff --git a/test/python/testdatabase/testrdbms.py b/test/python/testdatabase/testrdbms.py
index f8af1584..e73040b5 100644
--- a/test/python/testdatabase/testrdbms.py
+++ b/test/python/testdatabase/testrdbms.py
@@ -521,6 +521,19 @@ class Common:
obj = embeddings.search("select object from txtai where id = 0")[0]["object"]
self.assertEqual(str(obj.getvalue(), "utf-8"), "binary data")
+ def testQuantize(self):
+ """
+ Test scalar quantization
+ """
+
+ # Index data with 1-bit scalar quantization
+ embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "quantize": 1, "content": self.backend})
+ embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+
+ # Search for best match
+ result = self.embeddings.search("feel good story", 1)[0]
+ self.assertEqual(result["text"], self.data[4])
+
def testQueryModel(self):
"""
Test index
diff --git a/test/python/testembeddings.py b/test/python/testembeddings.py
index 64708cea..01e340d9 100644
--- a/test/python/testembeddings.py
+++ b/test/python/testembeddings.py
@@ -268,26 +268,19 @@ class TestEmbeddings(unittest.TestCase):
uid = embeddings.search("feel good story", 1)[0][0]
self.assertEqual(uid, 0)
- def testNormalize(self):
+ def testQuantize(self):
"""
- Test batch normalize and single input normalize are equal
+ Test scalar quantization
"""
- # Generate data
- data1 = np.random.rand(5, 5).astype(np.float32)
- data2 = data1.copy()
+ for ann in ["faiss", "numpy", "torch"]:
+ # Index data with 1-bit scalar quantization
+ embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "quantize": 1, "backend": ann})
+ embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
- # Keep original data to ensure it changed
- original = data1.copy()
-
- # Normalize data
- self.embeddings.normalize(data1)
- for x in data2:
- self.embeddings.normalize(x)
-
- # Test both data arrays are the same and changed from original
- self.assertTrue(np.allclose(data1, data2))
- self.assertFalse(np.allclose(data1, original))
+ # Search for best match
+ uid = embeddings.search("feel good story", 1)[0][0]
+ self.assertEqual(uid, 4)
def testReducer(self):
"""
diff --git a/test/python/testvectors/testvectors.py b/test/python/testvectors/testvectors.py
index 188d7e88..2c8ca7c5 100644
--- a/test/python/testvectors/testvectors.py
+++ b/test/python/testvectors/testvectors.py
@@ -4,6 +4,8 @@ Vectors module tests
import unittest
+import numpy as np
+
from txtai.vectors import Vectors
@@ -21,3 +23,26 @@ class TestVectors(unittest.TestCase):
self.assertRaises(NotImplementedError, vectors.load, None)
self.assertRaises(NotImplementedError, vectors.encode, None)
+
+ def testNormalize(self):
+ """
+ Test batch normalize and single input normalize are equal
+ """
+
+ vectors = Vectors(None, None)
+
+ # Generate data
+ data1 = np.random.rand(5, 5).astype(np.float32)
+ data2 = data1.copy()
+
+ # Keep original data to ensure it changed
+ original = data1.copy()
+
+ # Normalize data
+ vectors.normalize(data1)
+ for x in data2:
+ vectors.normalize(x)
+
+ # Test both data arrays are the same and changed from original
+ self.assertTrue(np.allclose(data1, data2))
+ self.assertFalse(np.allclose(data1, original))