diff --git a/Makefile b/Makefile
index 09908b3a8..64b647504 100644
--- a/Makefile
+++ b/Makefile
@@ -3,7 +3,7 @@ EXTVERSION = 0.4.4
 
 MODULE_big = vector
 DATA = $(wildcard sql/*--*.sql)
-OBJS = src/hnsw.o src/hnswbuild.o src/hnswinsert.o src/hnswscan.o src/hnswutils.o src/hnswvacuum.o src/ivfbuild.o src/ivfflat.o src/ivfinsert.o src/ivfkmeans.o src/ivfscan.o src/ivfutils.o src/ivfvacuum.o src/vector.o
+OBJS = src/hnsw.o src/hnswbuild.o src/hnswinsert.o src/hnswscan.o src/hnswutils.o src/hnswvacuum.o src/common/ivf_list.o src/common/ivf_options.o src/common/metadata.o src/fixed_point/ivf_sq.o src/fixed_point/scalar_quantizer.o src/ivfbuild.o src/ivfflat.o src/ivfinsert.o src/ivfkmeans.o src/ivfscan.o src/ivfutils.o src/ivfvacuum.o src/vector.o
 
 TESTS = $(wildcard test/sql/*.sql)
 REGRESS = $(patsubst test/sql/%.sql,%,$(TESTS))
diff --git a/Makefile.win b/Makefile.win
index e69810b4b..cdac26945 100644
--- a/Makefile.win
+++ b/Makefile.win
@@ -1,7 +1,7 @@
 EXTENSION = vector
 EXTVERSION = 0.4.4
 
-OBJS = src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\vector.obj
+OBJS = src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\common\ivf_list.obj src\common\ivf_options.obj src\common\metadata.obj src\fixed_point\ivf_sq.obj src\fixed_point\scalar_quantizer.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\vector.obj
 
 REGRESS = btree cast copy functions input ivfflat_cosine ivfflat_ip ivfflat_l2 ivfflat_options ivfflat_unlogged
 REGRESS_OPTS = --inputdir=test --load-extension=vector
diff --git a/README.md b/README.md
index 456591e8a..76c907db2 100644
--- a/README.md
+++ b/README.md
@@ -165,43 +165,56 @@ Three keys to achieving good recall are:
 2. Choose an appropriate number of lists - a good place to start is `rows / 1000` for up to 1M rows and `sqrt(rows)` for over 1M rows
 3. When querying, specify an appropriate number of [probes](#query-options) (higher is better for recall, lower is better for speed) - a good place to start is `sqrt(lists)`
 
-Add an index for each distance function you want to use.
+The IVF index supports both `flat` and `8-bit scalar quantized` storage. The `8-bit quantized` vectors map each vector from `float` space to `int8` space, resulting in up to ~2X faster scoring and ~4X lower storage cost with nearly no recall loss.
+
+Add an index for each distance function you want to use. Specify `ivfflat` to use the `flat` storage, or `ivf` with `quantizer = 'SQ8'` option to use the `8-bit quantized` IVF index.
 
 L2 distance
 
 ```sql
+CREATE INDEX ON items USING ivf (embedding vector_l2_ops) WITH (lists = 100, quantizer = 'SQ8');
 CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100);
 ```
 
 Inner product
 
 ```sql
+CREATE INDEX ON items USING ivf (embedding vector_ip_ops) WITH (lists = 100, quantizer='SQ8');
 CREATE INDEX ON items USING ivfflat (embedding vector_ip_ops) WITH (lists = 100);
 ```
 
 Cosine distance
 
 ```sql
+CREATE INDEX ON items USING ivf (embedding vector_cosine_ops) WITH (lists = 100, quantizer='SQ8');
 CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
 ```
 
-Vectors with up to 2,000 dimensions can be indexed.
+Vectors with up to 8,000 dimensions can be indexed using `IVF` when `8-bit scalar quantization` is enabled, up to 2,000 dimensions can be indexed using `ivfflat` without quantization.
 
 ### Query Options
 
 Specify the number of probes (1 by default)
 
+#### ivfflat
+
 ```sql
 SET ivfflat.probes = 10;
 ```
 
+#### ivf
+
+```sql
+SET ivf.probes = 10;
+```
+
 A higher value provides better recall at the cost of speed, and it can be set to the number of lists for exact nearest neighbor search (at which point the planner won’t use the index)
 
 Use `SET LOCAL` inside a transaction to set it for a single query
 
 ```sql
 BEGIN;
-SET LOCAL ivfflat.probes = 10;
+SET LOCAL ivf[flat].probes = 10;
 SELECT ...
 COMMIT;
 ```
@@ -240,6 +253,9 @@ CREATE INDEX ON items (category_id);
 Or a [partial index](https://www.postgresql.org/docs/current/indexes-partial.html) on the vector column for approximate search
 
 ```sql
+CREATE INDEX ON items USING ivf (embedding vector_l2_ops) WITH (lists = 100, quantizer='SQ8')
+    WHERE (category_id = 123);
+
 CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)
     WHERE (category_id = 123);
 ```
@@ -286,6 +302,8 @@ SELECT * FROM items ORDER BY embedding <#> '[3,1,2]' LIMIT 5;
 To speed up queries with an index, increase the number of inverted lists (at the expense of recall).
 
 ```sql
+CREATE INDEX ON items USING ivf (embedding vector_l2_ops) WITH (lists = 1000, quantizer='SQ8');
+
 CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 1000);
 ```
 
@@ -324,7 +342,7 @@ A non-partitioned table has a limit of 32 TB by default in Postgres. A partition
 
 Yes, pgvector uses the write-ahead log (WAL), which allows for replication and point-in-time recovery.
 
-#### What if I want to index vectors with more than 2,000 dimensions?
+#### What if I want to index vectors with more than 8,000 dimensions?
 
 You’ll need to use [dimensionality reduction](https://en.wikipedia.org/wiki/Dimensionality_reduction) at the moment.
 
diff --git a/sql/vector.sql b/sql/vector.sql
index 137931fed..574921391 100644
--- a/sql/vector.sql
+++ b/sql/vector.sql
@@ -99,6 +99,12 @@ CREATE FUNCTION vector_avg(double precision[]) RETURNS vector
 CREATE FUNCTION vector_combine(double precision[], double precision[]) RETURNS double precision[]
 	AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
 
+CREATE FUNCTION inner_product_int8_float_batched(internal, internal, internal) RETURNS internal
+	AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION squared_l2_distance_int8_float_batched(internal, internal, internal) RETURNS internal
+	AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
 -- aggregates
 
 CREATE AGGREGATE avg(vector) (
@@ -236,6 +242,13 @@ CREATE ACCESS METHOD ivfflat TYPE INDEX HANDLER ivfflathandler;
 
 COMMENT ON ACCESS METHOD ivfflat IS 'ivfflat index access method';
 
+CREATE FUNCTION ivfhandler(internal) RETURNS index_am_handler
+       AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE ACCESS METHOD ivf TYPE INDEX HANDLER ivfhandler;
+
+COMMENT ON ACCESS METHOD ivf IS 'ivf index access method';
+
 CREATE FUNCTION hnswhandler(internal) RETURNS index_am_handler
 	AS 'MODULE_PATHNAME' LANGUAGE C;
 
@@ -290,3 +303,27 @@ CREATE OPERATOR CLASS vector_cosine_ops
 	OPERATOR 1 <=> (vector, vector) FOR ORDER BY float_ops,
 	FUNCTION 1 vector_negative_inner_product(vector, vector),
 	FUNCTION 2 vector_norm(vector);
+
+CREATE OPERATOR CLASS vector_l2_ops
+	DEFAULT FOR TYPE vector USING ivf AS
+	OPERATOR 1 <-> (vector, vector) FOR ORDER BY float_ops,
+	FUNCTION 1 vector_l2_squared_distance(vector, vector),
+	FUNCTION 3 l2_distance(vector, vector),
+	FUNCTION 5 squared_l2_distance_int8_float_batched(internal, internal, internal);
+
+CREATE OPERATOR CLASS vector_ip_ops
+	FOR TYPE vector USING ivf AS
+	OPERATOR 1 <#> (vector, vector) FOR ORDER BY float_ops,
+	FUNCTION 1 vector_negative_inner_product(vector, vector),
+	FUNCTION 3 vector_spherical_distance(vector, vector),
+	FUNCTION 4 vector_norm(vector),
+	FUNCTION 5 inner_product_int8_float_batched(internal, internal, internal);
+
+CREATE OPERATOR CLASS vector_cosine_ops
+	FOR TYPE vector USING ivf AS
+	OPERATOR 1 <=> (vector, vector) FOR ORDER BY float_ops,
+	FUNCTION 1 vector_negative_inner_product(vector, vector),
+	FUNCTION 2 vector_norm(vector),
+	FUNCTION 3 vector_spherical_distance(vector, vector),
+	FUNCTION 4 vector_norm(vector),
+	FUNCTION 5 inner_product_int8_float_batched(internal, internal, internal);
\ No newline at end of file
diff --git a/src/common/ivf_list.c b/src/common/ivf_list.c
new file mode 100644
index 000000000..d23b0f4d4
--- /dev/null
+++ b/src/common/ivf_list.c
@@ -0,0 +1,36 @@
+#include "ivf_list.h"
+
+#include "metadata.h"
+
+/* PG C headers */
+#include "c.h"
+#include "common/relpath.h"
+#include "pg_config.h"
+#include "utils/relcache.h"
+
+IvfListV2 CreateIvfListV2(Relation rel, Metadata *metadata, bool external,
+						  ForkNumber fork_num, size_t *list_size)
+{
+	IvfListV2 list;
+	Metadata *list_metadata = metadata;
+	size_t metadata_size =
+		external ? EXTERNAL_METADATA_SIZE : VARSIZE_ANY(metadata);
+
+	Assert(!VARATT_IS_EXTERNAL(metadata));
+	*list_size = offsetof(IvfListDataV2, metadata) + metadata_size;
+
+	list = (IvfListV2)palloc0(*list_size);
+	list->startPage = InvalidBlockNumber;
+	list->insertPage = InvalidBlockNumber;
+	list->unused = 0UL;
+	if (external)
+	{
+		list_metadata = WriteMetadata(rel, metadata, fork_num);
+		Assert(VARATT_IS_EXTERNAL(list_metadata));
+		Assert(((ExternalMetadata *)list_metadata)->length ==
+			   (VARSIZE_ANY_EXHDR(metadata)));
+	}
+
+	memcpy(&list->metadata, list_metadata, metadata_size);
+	return list;
+}
diff --git a/src/common/ivf_list.h b/src/common/ivf_list.h
new file mode 100644
index 000000000..6824a9519
--- /dev/null
+++ b/src/common/ivf_list.h
@@ -0,0 +1,87 @@
+#ifndef PGVECTOR_SRC_COMMON_IVF_LIST_H_
+#define PGVECTOR_SRC_COMMON_IVF_LIST_H_
+
+#include "postgres.h"
+
+#include "storage/block.h"
+#include "common/relpath.h"
+#include "utils/relcache.h"
+
+#include "metadata.h"
+
+/*
+ * Partition ("list") metadata. It stores the location of its leaf pages
+ * (`start_page`), the location to insert new data into leaf pages
+ * (`insert_page`), together with some user defined metadata.
+ *
+ * STORAGE FORMAT
+ * --------------------------------------------------------
+ * | start_page(4) | insert_page(4) | metadata (varlena) |
+ * --------------------------------------------------------
+ */
+typedef struct IvfListDataV1
+{
+	BlockNumber startPage;
+	BlockNumber insertPage;
+	/* Inline or externalized storage. */
+	Metadata metadata;
+} IvfListDataV1;
+
+typedef IvfListDataV1 *IvfListV1;
+
+/*
+ * Similar to the above but added 8-bytes `unused` space for future use.
+ * Note that the newly built indexes are forced to use this format.
+ */
+typedef struct IvfListDataV2
+{
+	BlockNumber startPage;
+	BlockNumber insertPage;
+	uint64_t unused;
+	// Inline or externalized storage.
+	Metadata metadata;
+} IvfListDataV2;
+
+typedef IvfListDataV2 *IvfListV2;
+
+#define IVF_LIST_GET_START_PAGE(item, version)         \
+	(((version) == 1) ? ((IvfListV1)(item))->startPage \
+					  : ((IvfListV2)(item))->startPage)
+
+#define IVF_LIST_SET_START_PAGE(item, version, startPage) \
+	do                                                    \
+	{                                                     \
+		if ((version) == 1)                               \
+			((IvfListV1)(item))->startPage = startPage;   \
+		else                                              \
+			((IvfListV2)(item))->startPage = startPage;   \
+	} while (0);
+
+#define IVF_LIST_SET_INSERT_PAGE(item, version, insertPage) \
+	do                                                      \
+	{                                                       \
+		if ((version) == 1)                                 \
+			((IvfListV1)(item))->insertPage = insertPage;   \
+		else                                                \
+			((IvfListV2)(item))->insertPage = insertPage;   \
+	} while (0);
+
+#define IVF_LIST_GET_INSERT_PAGE(item, version)         \
+	(((version) == 1) ? ((IvfListV1)(item))->insertPage \
+					  : ((IvfListV2)(item))->insertPage)
+
+#define IVF_LIST_GET_METADATA(item, version)           \
+	(((version) == 1) ? &((IvfListV1)(item))->metadata \
+					  : &((IvfListV2)(item))->metadata)
+
+/*
+ * Creates `IvfListV2` structure from `metadata`. The input `metadata` should be inlined.
+ * When `external` is `true`, it writes the `metadata` into external pages and an
+ * `ExternalMetadata` is written into the structure, otherwise, the `metadata` is copied
+ * into the result.
+ *   RETURNS: `IvfListV2` structure on the heap with its size `list_size`.
+ */
+IvfListV2 CreateIvfListV2(Relation rel, Metadata *metadata, bool external,
+						  ForkNumber fork_num, size_t *list_size);
+
+#endif /* PGVECTOR_SRC_COMMON_IVF_LIST_H_ */
diff --git a/src/common/ivf_options.c b/src/common/ivf_options.c
new file mode 100644
index 000000000..0a4a20a0f
--- /dev/null
+++ b/src/common/ivf_options.c
@@ -0,0 +1,129 @@
+#include <stddef.h>
+#include "ivf_options.h"
+
+#include "../ivfflat.h"
+#include "access/htup_details.h"
+#include "access/reloptions.h"
+#include "c.h"
+#include "catalog/pg_am.h"
+#include "postgres.h"
+#include "utils/guc.h"
+#include "utils/rel.h"
+#include "utils/relcache.h"
+#include "utils/syscache.h"
+
+#define IVFFLAT_AM_NAME "ivfflat"
+#define IVF_AM_NAME "ivf"
+
+#define IVF_DEFAULT_QUANTIZER kIvfsq8
+
+/* Custom relation option kind for IVF. */
+static relopt_kind ivf_relopt_kind;
+/* The quantization method. */
+int ivf_quantizer;
+/* The number of lists to probe during scan. */
+int ivf_probes;
+
+relopt_enum_elt_def IvfQuantizerTypeEnumValues[] = {
+	{"SQ8", kIvfsq8},
+	{(const char *)NULL} /* list terminator */
+};
+
+int IvfGetLists(Relation index)
+{
+	HeapTuple tuple;
+	Form_pg_am amform;
+	int lists = -1;
+
+	tuple = SearchSysCache1(AMOID, ObjectIdGetDatum(index->rd_rel->relam));
+	if (!HeapTupleIsValid(tuple))
+		return -1;
+
+	amform = (Form_pg_am)GETSTRUCT(tuple);
+	if (strcmp(NameStr(amform->amname), IVFFLAT_AM_NAME) == 0)
+		lists = IvfflatGetLists(index);
+	else if (strcmp(NameStr(amform->amname), IVF_AM_NAME) == 0)
+	{
+		IvfOptions *opts = (IvfOptions *)index->rd_options;
+		lists = (opts != NULL) ? opts->lists : IVFFLAT_DEFAULT_LISTS;
+	}
+	else
+		elog(ERROR, "Unknown index AM: %s", NameStr(amform->amname));
+
+	ReleaseSysCache(tuple);
+	return lists;
+}
+
+IvfQuantizerType IvfGetQuantizer(Relation index)
+{
+	HeapTuple tuple;
+	Form_pg_am amform;
+	IvfQuantizerType quantizer = kIvfInvalid;
+
+	tuple = SearchSysCache1(AMOID, ObjectIdGetDatum(index->rd_rel->relam));
+	if (!HeapTupleIsValid(tuple))
+		return kIvfInvalid;
+
+	amform = (Form_pg_am)GETSTRUCT(tuple);
+	if (strcmp(NameStr(amform->amname), IVFFLAT_AM_NAME) == 0)
+		quantizer = kIvfflat;
+	else if (strcmp(NameStr(amform->amname), IVF_AM_NAME) == 0)
+	{
+		IvfOptions *opts = (IvfOptions *)index->rd_options;
+		quantizer = (opts != NULL) ? opts->quantizer : IVF_DEFAULT_QUANTIZER;
+	}
+	else
+		elog(ERROR, "Unknown index AM: %s", NameStr(amform->amname));
+
+	ReleaseSysCache(tuple);
+	return quantizer;
+}
+
+void IvfInit()
+{
+	ivf_relopt_kind = add_reloption_kind();
+
+	add_int_reloption(ivf_relopt_kind, "lists", "Number of inverted lists",
+					  IVFFLAT_DEFAULT_LISTS, 1, IVFFLAT_MAX_LISTS
+#if PG_VERSION_NUM >= 130000
+					  ,
+					  AccessExclusiveLock
+#endif
+	);
+	add_enum_reloption(ivf_relopt_kind, "quantizer",
+					   "Quantization option for ivf index",
+					   IvfQuantizerTypeEnumValues, IVF_DEFAULT_QUANTIZER,
+					   "The valid option for quantization is \"SQ8\"."
+#if PG_VERSION_NUM >= 130000
+					   ,
+					   AccessExclusiveLock
+#endif
+	);
+	DefineCustomIntVariable("ivf.probes", "Sets the number of probes",
+							"Valid range is 1..lists.", &ivf_probes, 1, 1,
+							IVFFLAT_MAX_LISTS, PGC_USERSET, 0, NULL, NULL, NULL);
+}
+
+bytea *ivfoptions(Datum reloptions, bool validate)
+{
+	static const relopt_parse_elt tab[] = {
+		{"lists", RELOPT_TYPE_INT, offsetof(IvfOptions, lists)},
+		{"quantizer", RELOPT_TYPE_ENUM, offsetof(IvfOptions, quantizer)},
+	};
+
+#if PG_VERSION_NUM >= 130000
+	return (bytea *)build_reloptions(reloptions, validate, ivf_relopt_kind,
+									 sizeof(IvfOptions), tab, lengthof(tab));
+#else
+	relopt_value *options;
+	int numoptions;
+	IvfOptions *rdopts;
+
+	options = parseRelOptions(reloptions, validate, ivf_relopt_kind, &numoptions);
+	rdopts = allocateReloptStruct(sizeof(IvfOptions), options, numoptions);
+	fillRelOptions((void *)rdopts, sizeof(IvfOptions), options, numoptions,
+				   validate, tab, lengthof(tab));
+
+	return (bytea *)rdopts;
+#endif
+}
diff --git a/src/common/ivf_options.h b/src/common/ivf_options.h
new file mode 100644
index 000000000..72b1bed52
--- /dev/null
+++ b/src/common/ivf_options.h
@@ -0,0 +1,55 @@
+#ifndef PGVECTOR_SRC_COMMON_IVF_OPTIONS_H_
+#define PGVECTOR_SRC_COMMON_IVF_OPTIONS_H_
+
+#include <stdint.h>
+
+#include "c.h"
+#include "postgres.h"
+#include "utils/relcache.h"
+
+extern int ivf_probes;
+
+typedef enum IvfQuantizerType
+{
+	kIvfflat = 0,
+	kIvfsq8 = 1,
+	kIvfInvalid = 2,
+} IvfQuantizerType;
+
+/* IVF index options */
+typedef struct IvfOptions
+{
+	int32_t vl_len_; /* varlena header (do not touch directly!) */
+	int lists;		 /* number of lists */
+	int quantizer;
+} IvfOptions;
+
+/* IVF Option Accessors
+ * --------------------
+ * These APIs can be called for both `ivfflat` and `ivf` indexes.
+ *
+ * Get the number of lists configured for `index`.
+ *
+ * RETURNS:
+ *   Number of lists, or -1 on error.
+ */
+int IvfGetLists(Relation index);
+
+/* Get the quantization method configured for `index`.
+ *
+ * RETURNS:
+ *   The quantization type, or `kIvfInvalid` on error.
+ */
+IvfQuantizerType IvfGetQuantizer(Relation index);
+
+/*
+ * Initialize ivf index options.
+ */
+void IvfInit(void);
+
+/*
+ * Parses and validates the relation options for ivf index type.
+ */
+bytea *ivfoptions(Datum reloptions, bool validate);
+
+#endif /* PGVECTOR_SRC_COMMON_IVF_OPTIONS_H_ */
diff --git a/src/common/metadata.c b/src/common/metadata.c
new file mode 100644
index 000000000..9332b7335
--- /dev/null
+++ b/src/common/metadata.c
@@ -0,0 +1,364 @@
+#include "metadata.h"
+
+#include "postgres.h"
+
+#include "access/generic_xlog.h"
+#include "c.h"
+#include "common/relpath.h"
+#include "miscadmin.h"
+#include "storage/block.h"
+#include "storage/bufmgr.h"
+#include "storage/bufpage.h"
+#include "storage/item.h"
+#include "storage/itemid.h"
+#include "storage/itemptr.h"
+#include "storage/off.h"
+#include "utils/elog.h"
+#include "utils/rel.h"
+#include "utils/relcache.h"
+
+typedef struct MetadataPageOpaqueData
+{
+	BlockNumber next_blkno;
+	uint16_t unused;
+	uint16_t page_id; /* for identification of metadata pages */
+} MetadataPageOpaqueData;
+
+typedef MetadataPageOpaqueData *MetadataPageOpaque;
+
+/*
+ * Metadata chunk is stored as `varlena` with the following format:
+ * ----------------------------
+ * | VAR_HEADER | NEXT | DATA |
+ * ----------------------------
+ */
+typedef struct MetadataChunkHeader
+{
+	char vl_len_[4];
+	ItemPointerData next;
+} MetadataChunkHeader;
+
+#define kMetadataPageId 0xBEEF
+
+#define kChunkHeaderSize sizeof(MetadataChunkHeader)
+
+#define kMaxChunkDataSize 1024
+
+/* The max number of metadata chunks in a page. */
+#define kMaxMetadataChunksPerPage                                         \
+	(int)((BLCKSZ - MAXALIGN(SizeOfPageHeaderData +                       \
+							 MAXALIGN(sizeof(MetadataPageOpaqueData)))) / \
+		  (sizeof(ItemIdData) + MAXALIGN(kMaxChunkDataSize + kChunkHeaderSize)))
+
+/* The max number of pages a metadata is allowed to span. */
+#define kMaxMetadataPages 16
+
+/* The maximum metadata size supported. */
+#define kMaxMetadataSizeAllowed \
+	(kMaxMetadataPages * kMaxMetadataChunksPerPage * kMaxChunkDataSize)
+
+#define MetadataPageGetOpaque(page) \
+	((MetadataPageOpaque)PageGetSpecialPointer((page)))
+
+/*
+ * Aligned metadata chunk, used as a temporary buffer allocated on the stack
+ * from which page item is copied.
+ */
+typedef union AlignedMetadataChunk
+{
+	MetadataChunkHeader header;
+	char data[kMaxChunkDataSize + kChunkHeaderSize];
+	double force_align_d;
+	int64_t force_align_i64;
+} AlignedMetadataChunk;
+
+/* Returns the pointer to the chunk start (after `MetadataChunkHeader`). */
+#define CHUNK_DATA(ptr) ((char *)VARDATA_ANY((ptr)) + sizeof(ItemPointerData))
+
+/* Returns the size of the chunk (excluding `MetadataChunkHeader`). */
+#define CHUNK_SIZE_EXHDR(ptr) \
+	(VARSIZE_ANY_EXHDR((ptr)) - sizeof(ItemPointerData))
+
+/*
+ * Initialize the metadata page.
+ */
+static void MetadataInitPage(Buffer buf, Page page)
+{
+	PageInit(page, BufferGetPageSize(buf), sizeof(MetadataPageOpaqueData));
+	MetadataPageGetOpaque(page)->next_blkno = InvalidBlockNumber;
+	MetadataPageGetOpaque(page)->page_id = kMetadataPageId;
+}
+
+/*
+ * Initialize the metadata page and register it to xlog for modifications.
+ */
+static void MetadataInitRegisterPage(Relation rel, Buffer *buf, Page *page,
+									 GenericXLogState **state)
+{
+	*state = GenericXLogStart(rel);
+	*page = GenericXLogRegisterBuffer(*state, *buf, GENERIC_XLOG_FULL_IMAGE);
+	MetadataInitPage(*buf, *page);
+}
+
+/*
+ * Allocate and append a new page after the page in `buf`. Note that all pending
+ * writes on `buf` will be committed and a new xlog will be open for the new
+ * page. `buf` gets modified to point to the newly allocated buffer.
+ */
+static void MetadataAppendPage(Relation rel, Buffer *buf, Page *page,
+							   GenericXLogState **state, ForkNumber fork_num)
+{
+	/* Allocate a new buffer. */
+	Page newpage;
+	Buffer newbuf = ReadBufferExtended(rel, fork_num, P_NEW, RBM_NORMAL, NULL);
+
+	LockBuffer(newbuf, BUFFER_LOCK_EXCLUSIVE);
+	newpage = GenericXLogRegisterBuffer(*state, newbuf, GENERIC_XLOG_FULL_IMAGE);
+
+	/* Update the previous buffer. */
+	MetadataPageGetOpaque(*page)->next_blkno = BufferGetBlockNumber(newbuf);
+
+	/* Initialize the new page. */
+	MetadataInitPage(newbuf, newpage);
+
+	/* Commit all pending modifications on the previous page. */
+	GenericXLogFinish(*state);
+	UnlockReleaseBuffer(*buf);
+
+	/* Register the new page to xlog for modifications. */
+	*state = GenericXLogStart(rel);
+	*page = GenericXLogRegisterBuffer(*state, newbuf, GENERIC_XLOG_FULL_IMAGE);
+	*buf = newbuf;
+}
+
+static OffsetNumber WriteChunk(Relation rel, Buffer buf, Page page, char *data,
+							   size_t size)
+{
+	OffsetNumber offno;
+	AlignedMetadataChunk chunk;
+	ItemPointerSet(&chunk.header.next, InvalidBlockNumber, InvalidOffsetNumber);
+
+	SET_VARSIZE(&chunk, kChunkHeaderSize + size);
+	memcpy(CHUNK_DATA(&chunk), data, size);
+
+	if ((offno = PageAddItem(page, (Item)&chunk, MAXALIGN(VARSIZE_ANY(&chunk)),
+							 InvalidOffsetNumber,
+							 /*overwrite=*/false, /*is_heap=*/false)) ==
+		InvalidOffsetNumber)
+		elog(ERROR, "WriteChunk: failed to add a metadata chunk to \"%s\"",
+			 RelationGetRelationName(rel));
+
+	return offno;
+}
+
+/*
+ * Update the `next` pointer for the previous chunk to point to the current
+ * chunk. This function should be called after the current chunk is added to a
+ * page slot (so that its location is known). The current chunk is written to
+ * `curr_blkno` at offset `curr_offno` and similarly, the previous chunk is in
+ * page `prev_blkno` at `prev_offno`.
+ * When current and previous chunks are on the same page, i.e. `prev_blkno ==
+ * curr_blkno`, the update is made directly on `curr_page` image, which should
+ * be X-locked by the caller. Otherwise, the `prev_blkno` needs to be read and
+ * X-locked.
+ */
+static void LinkToPrevChunk(Relation rel, BlockNumber prev_blkno,
+							OffsetNumber prev_offno, BlockNumber curr_blkno,
+							OffsetNumber curr_offno, Page curr_page,
+							ForkNumber fork_num)
+{
+	Page prev_page;
+	Buffer prev_buf;
+	GenericXLogState *state;
+	MetadataChunkHeader *header;
+
+	if (prev_blkno == curr_blkno)
+	{
+		/* Two chunks landed on the same page. */
+		header = (MetadataChunkHeader *)PageGetItem(
+			curr_page, PageGetItemId(curr_page, prev_offno));
+		ItemPointerSet(&header->next, curr_blkno, curr_offno);
+		return;
+	}
+
+	prev_buf = ReadBufferExtended(rel, fork_num, prev_blkno, RBM_NORMAL,
+								  /*strategy=*/NULL);
+	LockBuffer(prev_buf, BUFFER_LOCK_EXCLUSIVE);
+	state = GenericXLogStart(rel);
+	prev_page = GenericXLogRegisterBuffer(state, prev_buf, /*flags=*/0);
+
+	header = (MetadataChunkHeader *)PageGetItem(
+		prev_page, PageGetItemId(prev_page, prev_offno));
+	ItemPointerSet(&header->next, curr_blkno, curr_offno);
+
+	GenericXLogFinish(state);
+	UnlockReleaseBuffer(prev_buf);
+}
+
+Metadata *WriteMetadata(Relation rel, const Metadata *metadata,
+						ForkNumber fork_num)
+{
+	char *ptr = VARDATA_ANY(metadata);
+	size_t size_remaining = VARSIZE_ANY_EXHDR(metadata);
+	Buffer buf;
+	Page curr_page;
+	GenericXLogState *x_log_state;
+	ExternalMetadata *external;
+	BlockNumber prev_blkno, curr_blkno;
+	OffsetNumber prev_offno, curr_offno;
+	int page_allocated = 1;
+	int size_to_write;
+	Size item_size;
+
+	if (size_remaining == 0 || size_remaining > kMaxMetadataSizeAllowed)
+		return NULL;
+
+	external = (ExternalMetadata *)palloc0(EXTERNAL_METADATA_SIZE);
+	SET_VARTAG_EXTERNAL(external, /*tag=*/0);
+	external->length = size_remaining;
+
+	/*
+	 * Always allocate a new page. Note that the caller needs to be responsible
+	 * for ensuring only one backend is extending the relation.
+	 */
+	buf = ReadBufferExtended(rel, fork_num, P_NEW, RBM_NORMAL,
+							 /*strategy=*/NULL);
+	LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
+
+	/* Initialize the first page and update `loc`. */
+	MetadataInitRegisterPage(rel, &buf, &curr_page, &x_log_state);
+	curr_blkno = BufferGetBlockNumber(buf);
+	ItemPointerSetBlockNumber(&external->loc, curr_blkno);
+
+	prev_offno = InvalidOffsetNumber;
+	while (size_remaining > 0)
+	{
+		CHECK_FOR_INTERRUPTS();
+
+		size_to_write = Min(kMaxChunkDataSize, size_remaining);
+		item_size = MAXALIGN(size_to_write + kChunkHeaderSize);
+		if (PageGetFreeSpace(curr_page) < item_size)
+		{
+			if (page_allocated >= kMaxMetadataPages)
+			{
+				elog(WARNING,
+					 "WriteMetadata: max number of pages exceeded, size remaining: "
+					 "%lu, page allocated: %d, max pages allocated: %d",
+					 size_remaining, page_allocated, kMaxMetadataPages);
+				UnlockReleaseBuffer(buf);
+				pfree(external);
+				return NULL;
+			}
+
+			/* Run out of space in the current page, allocate a new page. */
+			MetadataAppendPage(rel, &buf, &curr_page, &x_log_state, fork_num);
+			curr_blkno = BufferGetBlockNumber(buf);
+			page_allocated++;
+		}
+
+		/* Write the current chunk. */
+		curr_offno = WriteChunk(rel, buf, curr_page, ptr, size_to_write);
+
+		if (likely(prev_offno != InvalidOffsetNumber))
+			/* Go back to the previous chunk and update the `next` link. */
+			LinkToPrevChunk(rel, prev_blkno, prev_offno, curr_blkno, curr_offno,
+							curr_page, fork_num);
+		else
+			/* This is the first chunk. */
+			ItemPointerSetOffsetNumber(&external->loc, curr_offno);
+
+		prev_blkno = curr_blkno;
+		prev_offno = curr_offno;
+
+		/* Advance the position in the buffer. */
+		ptr += size_to_write;
+		size_remaining -= size_to_write;
+	}
+
+	/* Commit the last buffer. */
+	GenericXLogFinish(x_log_state);
+	UnlockReleaseBuffer(buf);
+
+	return (Metadata *)external;
+}
+
+bool ReadMetadata(Relation rel, ItemPointer loc, const Metadata *metadata,
+				  size_t max_bytes, ForkNumber fork_num)
+{
+	Buffer buf = InvalidBuffer;
+	Page page = NULL;
+	OffsetNumber max_offno;
+	BlockNumber blkno, next_blkno;
+	OffsetNumber offno;
+
+	char *ptr = VARDATA_ANY(metadata);
+	MetadataChunkHeader *chunk;
+	size_t chunk_size;
+	size_t bytes_read = 0;
+
+	blkno = InvalidBlockNumber;
+	next_blkno = ItemPointerGetBlockNumber(loc);
+	offno = ItemPointerGetOffsetNumber(loc);
+
+	while (next_blkno != InvalidBlockNumber && bytes_read < max_bytes)
+	{
+		Assert(offno != InvalidOffsetNumber);
+		if (blkno != next_blkno)
+		{
+			/* A new page needs to be read. */
+			if (buf != InvalidBuffer)
+				UnlockReleaseBuffer(buf);
+			buf = ReadBufferExtended(rel, fork_num, next_blkno, RBM_NORMAL,
+									 /*strategy=*/NULL);
+			LockBuffer(buf, BUFFER_LOCK_SHARE);
+			page = BufferGetPage(buf);
+
+			blkno = next_blkno;
+		}
+
+		max_offno = PageGetMaxOffsetNumber(page);
+		if (offno > max_offno)
+		{
+			/* Confidence check, this is unexpected. */
+			if (buf != InvalidBuffer)
+				UnlockReleaseBuffer(buf);
+			return false;
+		}
+
+		/* Copy the current chunk into the buffer and advance the buffer position. */
+		chunk = (MetadataChunkHeader *)PageGetItem(page, PageGetItemId(page, offno));
+		chunk_size = CHUNK_SIZE_EXHDR(chunk);
+		memcpy(ptr, CHUNK_DATA(chunk), chunk_size);
+		ptr += chunk_size;
+		bytes_read += chunk_size;
+
+		// Get the location for the next chunk.
+		next_blkno = ItemPointerGetBlockNumberNoCheck(&chunk->next);
+		offno = ItemPointerGetOffsetNumberNoCheck(&chunk->next);
+	}
+
+	if (buf != InvalidBuffer)
+		UnlockReleaseBuffer(buf);
+	SET_VARSIZE(metadata, bytes_read + VARHDRSZ);
+
+	return true;
+}
+
+Metadata *FlattenMetadata(Relation rel, Metadata *metadata,
+						  ForkNumber fork_num)
+{
+	ExternalMetadata *external_metadata;
+	Metadata *flattened;
+
+	if (!VARATT_IS_EXTERNAL(metadata))
+		return metadata;
+
+	external_metadata = (ExternalMetadata *)(metadata);
+	flattened = (Metadata *)palloc0(external_metadata->length + VARHDRSZ);
+	if (ReadMetadata(rel, &external_metadata->loc, flattened,
+					 external_metadata->length, fork_num))
+		return flattened;
+
+	pfree(flattened);
+	return NULL;
+}
diff --git a/src/common/metadata.h b/src/common/metadata.h
new file mode 100644
index 000000000..f46aa6935
--- /dev/null
+++ b/src/common/metadata.h
@@ -0,0 +1,112 @@
+#ifndef PGVECTOR_SRC_COMMON_METADATA_H_
+#define PGVECTOR_SRC_COMMON_METADATA_H_
+
+#include "postgres.h"
+
+#include "c.h"
+#include "common/relpath.h"
+#include "storage/item.h"
+#include "storage/itemptr.h"
+#include "utils/relcache.h"
+
+/*
+ * ********************************************************************
+ *                   METADATA READ & WRITE
+ * ********************************************************************
+ *
+ * I. DATA FORMAT
+ * ==============
+ * `Metadata` is defined as a variable-length byte array `varlena` with a 4-byte
+ * header and body.
+ *
+ * II. WRITE
+ * ==============
+ * We always allocate a new page to persist metadata on write. Metadata is
+ * divided into chunks and each chunk (bounded by `EXTERN_TUPLE_MAX_SIZE`) is
+ * stored in a page slot. Multiple ordered chunks form a linked list by storing
+ * the "next" chunk location in the chunk header (see `MetadataChunkHeader`).
+ * New pages are allocated if the size of the metadata exceeds the page
+ * capacity. To visualize the storage:
+ *
+ *               PAGE ID: 1
+ * -------------------------------------
+ * | 0: chunk[0]: next(1:1), data(xxx) |
+ * -------------------------------------
+ * | 1: chunk[1]: next(2:0), data(xxx) |
+ * -------------------------------------
+ *
+ *               PAGE ID: 2
+ * -------------------------------------
+ * | 0: chunk[2]: next(2:1), data(xxx) |
+ * -------------------------------------
+ * | 1: chunk[3]: next(end), data(xxx) |
+ * -------------------------------------
+ *
+ * *** NOTES ***:
+ *
+ * 1. Since write allocates new page(s), the caller is responsible for ensuring
+ *    that there is only one backend calls this API per relation at a time.
+ * 2. Each buffer page is registered to a separate xlog, and the previous
+ *    xlog is always committed before allowing the next page to be modified.
+ *    This means pages will be "leaked" if the process crashes in between. Since
+ *    pages are registered to the tablespace of some relation, they will be
+ *    recycled only when the tablespace is dropped.
+ * 3. There are various bounds to ensure that a single write does not saturate
+ *    the tablespace. We only allow a single write to span across
+ *    `kMaxMetadataPages` pages. As a result, metadata size is also bounded
+ *    by 'kMaxMetadataSizeAllowed'.
+ *
+ * III. READ
+ * ==============
+ * Chunks are combined and copied into the user provided `varlena` buffer.
+ */
+
+typedef struct varlena Metadata;
+
+/*
+ * External metadata is an extension of `varattrib_1b_e` to be compatible with
+ * `varlena` macros.
+ */
+typedef struct ExternalMetadata
+{
+	uint8_t header;
+	uint8_t unused;
+	uint32_t length;	 /* Externally stored metadata size (i.e., size to read). */
+	ItemPointerData loc; /* Location of the externally stored data. */
+} ExternalMetadata;
+
+#define EXTERNAL_METADATA_SIZE sizeof(ExternalMetadata)
+
+/*
+ * Read the metadata stored at location `loc` in relation `rel`. This function
+ * guarantees that the **effective** max bytes read does not exceed `max_bytes`,
+ * which should usually be the size of metadata (excluding the header). The
+ * caller is responsible for allocating a buffer `metadata` of proper size and
+ * the result is written into `metadata` (including the `varlena` header).
+ *
+ * RETURNS `true` on success or `false` otherwise.
+ */
+bool ReadMetadata(Relation rel, ItemPointer loc, const Metadata *metadata,
+				  size_t max_bytes, ForkNumber fork_num);
+
+/*
+ * Flatten the `metadata`. The input `metadata` can be either inline or
+ * out-of-line (`ExternalMetadata`).
+ *
+ * RETURNS:
+ *  The flattened metadata, when `metadata` is `ExternalMetadata`.
+ *  otherwise, `metadata` itself.
+ */
+Metadata *FlattenMetadata(Relation rel, Metadata *metadata,
+						  ForkNumber fork_num);
+
+/*
+ * Write the `metadata` into pages allocated in relation `rel`. The location of
+ * the first chunk is stored in `loc`. NOTE: refer to the top level comments for
+ * how metadata are externalized.
+ * RETURNS externalized metadata on success or `nullptr` otherwise.
+ */
+Metadata *WriteMetadata(Relation rel, const Metadata *metadata,
+						ForkNumber fork_num);
+
+#endif /* PGVECTOR_SRC_COMMON_METADATA_H_ */
diff --git a/src/fixed_point/ivf_sq.c b/src/fixed_point/ivf_sq.c
new file mode 100644
index 000000000..794c5472d
--- /dev/null
+++ b/src/fixed_point/ivf_sq.c
@@ -0,0 +1,130 @@
+#include "ivf_sq.h"
+
+#include "../common/metadata.h"
+#include "scalar_quantizer.h"
+#include "../vector.h"
+#include "access/generic_xlog.h"
+#include "c.h"
+#include "fmgr.h"
+#include "common/relpath.h"
+#include "storage/bufmgr.h"
+#include "storage/bufpage.h"
+#include "storage/itemptr.h"
+#include "utils/relcache.h"
+
+void UpdateMetaPageWithMultipliers(Relation index, const Vector *multipliers,
+								   ForkNumber fork_num)
+{
+	Buffer buf;
+	Page page;
+	GenericXLogState *state;
+	IvfsqMetaPage ptr;
+	Metadata *metadata;
+
+	buf = ReadBufferExtended(index, fork_num, IVFFLAT_METAPAGE_BLKNO, RBM_NORMAL,
+							 /*strategy=*/NULL);
+	LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
+	state = GenericXLogStart(index);
+	page = GenericXLogRegisterBuffer(state, buf, 0);
+
+	ptr = IvfsqPageGetMeta(page);
+	metadata = WriteMetadata(index, (Metadata *)multipliers, fork_num);
+	Assert(VARATT_IS_EXTERNAL(metadata));
+	memcpy(&ptr->multipliers_loc, &((ExternalMetadata *)metadata)->loc,
+		   sizeof(ItemPointerData));
+
+	GenericXLogFinish(state);
+	UnlockReleaseBuffer(buf);
+}
+
+Vector *IvfsqGetMultipliers(Relation index, ForkNumber fork_num)
+{
+	Buffer buf;
+	Page page;
+	size_t max_bytes;
+	IvfsqMetaPage meta_page;
+	Vector *inv_multipliers;
+
+	buf = ReadBufferExtended(index, fork_num, IVFFLAT_METAPAGE_BLKNO, RBM_NORMAL,
+							 /*strategy=*/NULL);
+	LockBuffer(buf, BUFFER_LOCK_SHARE);
+
+	page = BufferGetPage(buf);
+	meta_page = IvfsqPageGetMeta(page);
+
+	max_bytes = VECTOR_SIZE(meta_page->base.dimensions);
+	inv_multipliers = InitVector(meta_page->base.dimensions);
+	/* Read the metadata and perform some basic dimension check to verify the integrity. */
+	if (!ReadMetadata(index, &meta_page->multipliers_loc,
+					  (Metadata *)(inv_multipliers), max_bytes, fork_num) ||
+		inv_multipliers->dim != meta_page->base.dimensions)
+	{
+		elog(WARNING,
+			 "cannot read metadata from index or dimension mismatch: read: %d vs. "
+			 "meta page dim: %d",
+			 inv_multipliers->dim, meta_page->base.dimensions);
+		pfree(inv_multipliers);
+		inv_multipliers = NULL;
+	}
+
+	UnlockReleaseBuffer(buf);
+	return inv_multipliers;
+}
+
+static Vector *ProprocessQuery(const Vector *query,
+							   const Vector *inv_multipliers)
+{
+	Vector *preprocessed_query = InitVector(query->dim);
+	for (int i = 0; i < preprocessed_query->dim; ++i)
+	{
+		/* We ensure multipliers are non-zero. */
+		Assert(inv_multipliers->x[i] != 0.0);
+		preprocessed_query->x[i] = query->x[i] * inv_multipliers->x[i];
+	}
+
+	return preprocessed_query;
+}
+
+PGDLLEXPORT PG_FUNCTION_INFO_V1(inner_product_int8_float_batched);
+Datum inner_product_int8_float_batched(PG_FUNCTION_ARGS)
+{
+	Vector *query = PG_GETARG_VECTOR_P(0);
+	Vector *inv_multipliers = PG_GETARG_VECTOR_P(1);
+	Page page = PG_GETARG_POINTER(2);
+	Vector *preprocessed_query = ProprocessQuery(query, inv_multipliers);
+	Vector *result = InitVector(PageGetMaxOffsetNumber(page));
+	TupleDesc tupdesc;
+#if PG_VERSION_NUM >= 120000
+	tupdesc = CreateTemplateTupleDesc(1);
+#else
+	tupdesc = CreateTemplateTupleDesc(1, false);
+#endif
+	TupleDescInitEntry(tupdesc, (AttrNumber)1, "quantized_vector", BYTEAOID, -1, 0);
+
+	ComputeOneToManyDotProductDistance(preprocessed_query, tupdesc, page, result);
+
+	pfree(preprocessed_query);
+
+	PG_RETURN_VECTOR_P(result);
+}
+
+PGDLLEXPORT PG_FUNCTION_INFO_V1(squared_l2_distance_int8_float_batched);
+Datum squared_l2_distance_int8_float_batched(PG_FUNCTION_ARGS)
+{
+	Vector *query = PG_GETARG_VECTOR_P(0);
+	Vector *inv_multipliers = PG_GETARG_VECTOR_P(1);
+	Page page = PG_GETARG_POINTER(2);
+	Vector *result = InitVector(PageGetMaxOffsetNumber(page));
+
+	TupleDesc tupdesc;
+#if PG_VERSION_NUM >= 120000
+	tupdesc = CreateTemplateTupleDesc(1);
+#else
+	tupdesc = CreateTemplateTupleDesc(1, false);
+#endif
+	TupleDescInitEntry(tupdesc, (AttrNumber)1, "quantized_vector", BYTEAOID, -1, 0);
+
+	ComputeOneToManySquaredL2Distance(query, inv_multipliers, tupdesc, page,
+									  result);
+	PG_RETURN_VECTOR_P(result);
+}
diff --git a/src/fixed_point/ivf_sq.h b/src/fixed_point/ivf_sq.h
new file mode 100644
index 000000000..f33daa64f
--- /dev/null
+++ b/src/fixed_point/ivf_sq.h
@@ -0,0 +1,38 @@
+#ifndef PGVECTOR_SRC_FIXED_POINT_IVF_SQ_H_
+#define PGVECTOR_SRC_FIXED_POINT_IVF_SQ_H_
+
+#include "../ivfflat.h"
+#include "../vector.h"
+#include "common/relpath.h"
+#include "storage/itemptr.h"
+#include "utils/relcache.h"
+
+#define IVFSQ_MAX_DIM 8000
+
+typedef struct IvfsqMetaPageData {
+  /* Fields inherited from `ivfflat`. */
+  IvfflatMetaPageData base;
+  /* Location of multipliers, always stored on external pages. */
+  ItemPointerData multipliers_loc;
+} IvfsqMetaPageData;
+
+typedef IvfsqMetaPageData* IvfsqMetaPage;
+
+#define IvfsqPageGetMeta(page) ((IvfsqMetaPageData*)PageGetContents(page))
+
+/*
+ * This function writes the multipliers into the IVF meta page for `index`. The
+ * multipliers are *always* written as `ExternalMetadata` (i.e., only the
+ * location gets written into the meta page).
+ */ 
+void UpdateMetaPageWithMultipliers(Relation index, const Vector* multipliers,
+                                   ForkNumber fork_num);
+
+/*
+ * This function reads the multipliers based on the location specified
+ * in meta page in `index`. On success, it allocates the memory for
+ * `multipliers` and the caller is expected to release it.
+ */ 
+Vector* IvfsqGetMultipliers(Relation index, ForkNumber fork_num);
+
+#endif  /* PGVECTOR_SRC_FIXED_POINT_IVF_SQ_H_ */
diff --git a/src/fixed_point/scalar_quantizer.c b/src/fixed_point/scalar_quantizer.c
new file mode 100644
index 000000000..82e3207f2
--- /dev/null
+++ b/src/fixed_point/scalar_quantizer.c
@@ -0,0 +1,115 @@
+/*-------------------------------------------------------------------------
+ *
+ * scalar_quantizer.c
+ *	  
+ *     Implements 8-bit scalar quantizer and scoring functionalities.
+ *
+ * NOTE: the algorithms implemented in this file was heavily influenced by
+ * Google's ScaNN scalar quantization library:
+ *
+ *   https://github.com/google-research/google-research/tree/master/scann
+ * 
+ *-------------------------------------------------------------------------
+ */
+
+#include <stddef.h>
+#include <limits.h>
+#include <math.h>
+
+#include "scalar_quantizer.h"
+
+#include "postgres.h"
+
+/* PG C headers */
+#include "c.h"
+#include "fmgr.h"
+#include "access/itup.h"
+
+/* pg vector C headers */
+#include "../vector.h"
+
+Datum ScalarQuantizeVector(const Vector *in, const Vector *multipliers,
+                           bytea *quantized_storage)
+{
+    /* NOTE: use `VARDATA_ANY` since `quantized_storage` can be packed with 1B header */
+    int8_t  *ptr = (int8_t*) VARDATA_ANY(quantized_storage);
+
+    Assert(in->dim == multipliers->dim);
+
+    for (int i = 0; i < in->dim; ++i)
+    {
+        float fp_val = round(in->x[i] * multipliers->x[i]);
+        if (unlikely(fp_val > SCHAR_MAX))
+            ptr[i] = SCHAR_MAX;
+        else if (unlikely(fp_val < SCHAR_MIN))
+            ptr[i] = SCHAR_MIN;
+        else
+            ptr[i] = (int8_t) fp_val;
+    }
+
+    PG_RETURN_BYTEA_P(quantized_storage);
+}
+
+void ComputeOneToManyDotProductDistance(const Vector *preprocessed_query,
+                                        const TupleDesc tuple_desc,
+                                        const Page page, Vector *result)
+{
+    bool    is_null;
+    int8_t  *ptr;
+    float   distance;
+    OffsetNumber max_offno = PageGetMaxOffsetNumber(page);
+
+    Assert(max_offno == result->dim);
+    Assert(preprocessed_query->dim == inv_multipliers->dim);
+
+    for (int i = 0; i < result->dim; ++i)
+    {
+        IndexTuple tuple = (IndexTuple) PageGetItem(page, PageGetItemId(page, i + FirstOffsetNumber));
+        bytea* data = DatumGetByteaPP(index_getattr(tuple, 1, tuple_desc, &is_null));
+        /* IVF index build should skip null vectors (refer to `ivfbuild.c`). */
+        if (unlikely(is_null))
+            continue;
+
+        ptr = (int8_t*) VARDATA_ANY(data);
+        distance = 0.0f;
+        for (size_t j = 0; j < preprocessed_query->dim; ++j)
+            distance += preprocessed_query->x[j] * ((float) ptr[j]);
+        /* Negative dot product */
+        result->x[i] = -distance;
+    }
+}
+
+void ComputeOneToManySquaredL2Distance(const Vector *query,
+                                       const Vector *inv_multipliers,
+                                       const TupleDesc tuple_desc,
+                                       const Page page, Vector *result)
+{
+    bool    is_null;
+    int8_t  *ptr;
+    float   distance;
+    float   scaled_val;
+    float   diff;
+    OffsetNumber max_offno = PageGetMaxOffsetNumber(page);
+
+    Assert(max_offno == result->dim);
+    Assert(query->dim == inv_multipliers->dim);
+
+    for (int i = 0; i < result->dim; ++i)
+    {
+        IndexTuple tuple = (IndexTuple) PageGetItem(page, PageGetItemId(page, i + FirstOffsetNumber));
+        bytea* data = DatumGetByteaPP(index_getattr(tuple, 1, tuple_desc, &is_null));
+        /* IVF index build should skip null vectors (refer to `ivfbuild.c`). */
+        if (unlikely(is_null))
+            continue;
+        
+        ptr = (int8_t*) VARDATA_ANY(data);
+        distance = 0.0f;
+        for (size_t j = 0; j < query->dim; ++j)
+        {
+            scaled_val = ((float) ptr[j]) * inv_multipliers->x[j];
+            diff = query->x[j] - scaled_val;
+            distance += (diff * diff);
+        }
+        result->x[i] = distance;
+    }
+}
diff --git a/src/fixed_point/scalar_quantizer.h b/src/fixed_point/scalar_quantizer.h
new file mode 100644
index 000000000..ae1adac09
--- /dev/null
+++ b/src/fixed_point/scalar_quantizer.h
@@ -0,0 +1,52 @@
+#ifndef PGVECTOR_SRC_FIXED_POINT_SCALAR_QUANTIZER_H_
+#define PGVECTOR_SRC_FIXED_POINT_SCALAR_QUANTIZER_H_
+
+
+#include "postgres.h"
+
+/* PG C headers */
+#include "access/tupdesc.h"
+#include "c.h"
+#include "storage/bufpage.h"
+
+/* PGVector C headers */
+#include "../vector.h"
+
+/*
+ * This function quantizes the `in` vector with FP8 scalar quantization and
+ * returns the result, which is written into `quantized_storage`. Note that the
+ * caller is responsible for allocating memory for `quantized_storage` - since
+ * this function is typically called in a tight loop, the caller should make
+ * `quantized_storage` reusable across calls.
+ * RETURNS: a datum pointer that points to `quantized_storage`.
+ */
+Datum ScalarQuantizeVector(const Vector* in, const Vector* multipliers,
+                           bytea* quantized_storage);
+
+/*
+ * This function computes similar scores of `preprocessed_query` vector
+ * against all FP8 vectors in the `page`. Note that the caller is responsible
+ * for pre-processing the input query.
+ * INPUTS:
+ *   `preprocessed_query`: the `float` vector scaled by the inverse of fp8
+ *   multipliers.
+ *   `tuple_desc`: the schema of tuples in `page`.
+ *   `page`: the pointer to the page in buffer pool where all fp8 vectors are
+ *   stored.
+ * OUTPUT:
+ *   `result`: distances between `preprocessed_query` and all quantized vectors
+ *   in the page.
+ */
+void ComputeOneToManyDotProductDistance(
+    const Vector* preprocessed_query,
+    const TupleDesc tuple_desc, const Page page, Vector* result);
+
+/*
+ * Similar to the above but computes the squared l2 distance. Note that `query`
+ * is does not need to be pre-processed.
+ */ 
+void ComputeOneToManySquaredL2Distance(
+    const Vector* query, const Vector* inv_multipliers,
+    const TupleDesc tuple_desc, const Page page, Vector* result);
+
+#endif  /* PGVECTOR_SRC_FIXED_POINT_SCALAR_QUANTIZER_H_ */
diff --git a/src/ivfbuild.c b/src/ivfbuild.c
index cc4f7a3a9..7e6cd72cf 100644
--- a/src/ivfbuild.c
+++ b/src/ivfbuild.c
@@ -1,6 +1,7 @@
 #include "postgres.h"
 
 #include <float.h>
+#include <math.h>
 
 #include "access/parallel.h"
 #include "access/xact.h"
@@ -40,6 +41,9 @@
 #define UpdateProgress(index, val) ((void)val)
 #endif
 
+#define MaxSupportedDimension(type) \
+	((type) == kIvfsq8 ? IVFSQ_MAX_DIM : IVFFLAT_MAX_DIM)
+
 #if PG_VERSION_NUM >= 140000
 #include "utils/backend_status.h"
 #include "utils/wait_event.h"
@@ -54,6 +58,12 @@
 #include "pgstat.h"
 #endif
 
+#include "common/metadata.h"
+#include "common/ivf_list.h"
+#include "common/ivf_options.h"
+#include "fixed_point/scalar_quantizer.h"
+#include "fixed_point/ivf_sq.h"
+
 #define PARALLEL_KEY_IVFFLAT_SHARED		UINT64CONST(0xA000000000000001)
 #define PARALLEL_KEY_TUPLESORT			UINT64CONST(0xA000000000000002)
 #define PARALLEL_KEY_IVFFLAT_CENTERS	UINT64CONST(0xA000000000000003)
@@ -194,6 +204,14 @@ AddTupleToSort(Relation index, ItemPointer tid, Datum *values, IvfflatBuildState
 		}
 	}
 
+	/* Update the multiplier for quantization */
+	if (buildstate->multipliers != NULL) {
+		Vector* vector = DatumGetVector(value);
+		for (int i = 0; i < vector->dim; i++) {
+			buildstate->multipliers->x[i] = fmax(buildstate->multipliers->x[i], fabs(vector->x[i]));
+		}
+	}
+
 #ifdef IVFFLAT_KMEANS_DEBUG
 	buildstate->inertia += minDistance;
 	buildstate->listSums[closestCenter] += minDistance;
@@ -254,15 +272,20 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
  * Get index tuple from sort state
  */
 static inline void
-GetNextTuple(Tuplesortstate *sortstate, TupleDesc tupdesc, TupleTableSlot *slot, IndexTuple *itup, int *list)
+GetNextTuple(IvfflatBuildState *buildstate, TupleDesc tupdesc, TupleTableSlot *slot, IndexTuple *itup, int *list)
 {
 	Datum		value;
 	bool		isnull;
 
-	if (tuplesort_gettupleslot(sortstate, true, false, slot, NULL))
+	if (tuplesort_gettupleslot(buildstate->sortstate, true, false, slot, NULL))
 	{
 		*list = DatumGetInt32(slot_getattr(slot, 1, &isnull));
 		value = slot_getattr(slot, 3, &isnull);
+		if (!isnull && buildstate->multipliers != NULL) {
+			value = ScalarQuantizeVector(DatumGetVector(value),
+										 buildstate->multipliers,
+										 buildstate->quantized_storage);
+		}
 
 		/* Form the index tuple */
 		*itup = index_form_tuple(tupdesc, &value, &isnull);
@@ -272,6 +295,27 @@ GetNextTuple(Tuplesortstate *sortstate, TupleDesc tupdesc, TupleTableSlot *slot,
 		*list = -1;
 }
 
+/*
+ * Scale the multipliers and write it to the meta page
+ */
+static void
+UpdateAndWriteMultipliers(Relation index, Vector* multipliers, ForkNumber forkNum)
+{
+	Assert(multipliers != NULL);
+	/* Scale the multipliers and write it to the meta page */
+	for (int i = 0; i < multipliers->dim; ++i)
+	{
+		if (unlikely(multipliers->x[i] == 0.0f))
+			// This corner-case only triggers for dimensions
+			// that lack values other than 0.0, so the
+			// choice of multiplier can be arbitrary.
+			multipliers->x[i] = 1.0f;
+		else
+			multipliers->x[i] = SCHAR_MAX / multipliers->x[i];
+	}
+	UpdateMetaPageWithMultipliers(index, multipliers, forkNum);
+}
+
 /*
  * Create initial entry pages
  */
@@ -288,12 +332,25 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
 	TupleTableSlot *slot = MakeSingleTupleTableSlot(buildstate->tupdesc);
 #endif
 	TupleDesc	tupdesc = RelationGetDescr(index);
+	if (buildstate->quantizer != kIvfflat) {
+#if PG_VERSION_NUM >= 120000
+		tupdesc = CreateTemplateTupleDesc(/*natts=*/1);
+#else
+		tupdesc = CreateTemplateTupleDesc(/*natts=*/1, false);
+#endif
+		TupleDescInitEntry(tupdesc, (AttrNumber) 1, "quantized_vector", BYTEAOID, -1, 0);
+		tupdesc->attrs[0].attstorage = TYPSTORAGE_PLAIN;
+	}
 
 	UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_LOAD);
 
 	UpdateProgress(PROGRESS_CREATEIDX_TUPLES_TOTAL, buildstate->indtuples);
 
-	GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
+	if (buildstate->multipliers != NULL)
+		/* Needs to be called before `GetNextTuple` which uses `multipliers` to quantize vectors */
+		UpdateAndWriteMultipliers(index, buildstate->multipliers, forkNum);
+
+	GetNextTuple(buildstate, tupdesc, slot, &itup, &list);
 
 	for (int i = 0; i < buildstate->centers->length; i++)
 	{
@@ -329,7 +386,7 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
 
 			UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++inserted);
 
-			GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
+			GetNextTuple(buildstate, tupdesc, slot, &itup, &list);
 		}
 
 		insertPage = BufferGetBlockNumber(buf);
@@ -353,13 +410,35 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
 
 	buildstate->lists = IvfflatGetLists(index);
 	buildstate->dimensions = TupleDescAttr(index->rd_att, 0)->atttypmod;
+	buildstate->quantizer = IvfGetQuantizer(index);
+	if (buildstate->quantizer == kIvfflat)
+	{
+		buildstate->lists = IvfflatGetLists(index);
+		buildstate->multipliers = NULL;
+		buildstate->quantized_storage = NULL;
+	}
+	else if (buildstate->quantizer == kIvfsq8)
+	{
+		buildstate->lists = IvfGetLists(index);
+		buildstate->multipliers = InitVector(buildstate->dimensions);
+		for (int i = 0; i < buildstate->dimensions; ++i) {
+			buildstate->multipliers->x[i] = 0.0f;
+		}
+		buildstate->quantized_storage =
+				(bytea *)palloc0(buildstate->dimensions + VARHDRSZ);
+		SET_VARSIZE(buildstate->quantized_storage,
+					buildstate->dimensions + VARHDRSZ);
+	}
+	else {
+		elog(ERROR, "Unsupported quantizer: %d", buildstate->quantizer);
+	}
 
 	/* Require column to have dimensions to be indexed */
 	if (buildstate->dimensions < 0)
 		elog(ERROR, "column does not have dimensions");
 
-	if (buildstate->dimensions > IVFFLAT_MAX_DIM)
-		elog(ERROR, "column cannot have more than %d dimensions for ivfflat index", IVFFLAT_MAX_DIM);
+	if (buildstate->dimensions > MaxSupportedDimension(buildstate->quantizer))
+		elog(ERROR, "column cannot have more than %d dimensions for ivfflat index", MaxSupportedDimension(buildstate->quantizer));
 
 	buildstate->reltuples = 0;
 	buildstate->indtuples = 0;
@@ -424,6 +503,17 @@ FreeBuildState(IvfflatBuildState * buildstate)
 	pfree(buildstate->listCounts);
 #endif
 
+	if (buildstate->multipliers != NULL)
+	{
+		pfree(buildstate->multipliers);
+		buildstate->multipliers = NULL;
+	}
+	if (buildstate->quantized_storage != NULL)
+	{
+		pfree(buildstate->quantized_storage);
+		buildstate->quantized_storage = NULL;
+	}
+
 	MemoryContextDelete(buildstate->tmpCtx);
 }
 
@@ -480,9 +570,11 @@ CreateMetaPage(Relation index, int dimensions, int lists, ForkNumber forkNum)
 	Page		page;
 	GenericXLogState *state;
 	IvfflatMetaPage metap;
+	IvfQuantizerType quantizer;
 
 	buf = IvfflatNewBuffer(index, forkNum);
 	IvfflatInitRegisterPage(index, &buf, &page, &state);
+	quantizer = IvfGetQuantizer(index);
 
 	/* Set metapage data */
 	metap = IvfflatPageGetMeta(page);
@@ -490,8 +582,22 @@ CreateMetaPage(Relation index, int dimensions, int lists, ForkNumber forkNum)
 	metap->version = IVFFLAT_VERSION;
 	metap->dimensions = dimensions;
 	metap->lists = lists;
-	((PageHeader) page)->pd_lower =
-		((char *) metap + sizeof(IvfflatMetaPageData)) - (char *) page;
+	if (quantizer == kIvfflat)
+	{
+		((PageHeader) page)->pd_lower =
+			((char *) metap + sizeof(IvfflatMetaPageData)) - (char *) page;
+	}
+	else if (quantizer == kIvfsq8)
+	{
+		ItemPointerSet(&((IvfsqMetaPage)metap)->multipliers_loc, InvalidBlockNumber,
+					   InvalidOffsetNumber);
+		((PageHeader) page)->pd_lower =
+			((char *) metap + sizeof(IvfsqMetaPageData)) - (char *) page;
+	}
+	else
+	{
+		elog(ERROR, "Unsupported quantizer: %d", quantizer);
+	}
 
 	IvfflatCommitBuffer(buf, state);
 }
@@ -508,10 +614,8 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
 	GenericXLogState *state;
 	OffsetNumber offno;
 	Size		itemsz;
-	IvfflatList list;
-
-	itemsz = MAXALIGN(IVFFLAT_LIST_SIZE(dimensions));
-	list = palloc(itemsz);
+	IvfListV2	list;
+	const bool	externalize_center_storage = dimensions > IVFFLAT_MAX_DIM;
 
 	buf = IvfflatNewBuffer(index, forkNum);
 	IvfflatInitRegisterPage(index, &buf, &page, &state);
@@ -519,9 +623,8 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
 	for (int i = 0; i < lists; i++)
 	{
 		/* Load list */
-		list->startPage = InvalidBlockNumber;
-		list->insertPage = InvalidBlockNumber;
-		memcpy(&list->center, VectorArrayGet(centers, i), VECTOR_SIZE(dimensions));
+		list = CreateIvfListV2(index, (Metadata*)VectorArrayGet(centers, i),
+								externalize_center_storage, forkNum, &itemsz);
 
 		/* Ensure free space */
 		if (PageGetFreeSpace(page) < itemsz)
@@ -535,11 +638,11 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
 		/* Save location info */
 		(*listInfo)[i].blkno = BufferGetBlockNumber(buf);
 		(*listInfo)[i].offno = offno;
+
+		pfree(list);
 	}
 
 	IvfflatCommitBuffer(buf, state);
-
-	pfree(list);
 }
 
 /*
diff --git a/src/ivfflat.c b/src/ivfflat.c
index 3753a74d1..354df6a38 100644
--- a/src/ivfflat.c
+++ b/src/ivfflat.c
@@ -182,19 +182,12 @@ ivfflatvalidate(Oid opclassoid)
 	return true;
 }
 
-/*
- * Define index handler
- *
- * See https://www.postgresql.org/docs/current/index-api.html
- */
-PGDLLEXPORT PG_FUNCTION_INFO_V1(ivfflathandler);
-Datum
-ivfflathandler(PG_FUNCTION_ARGS)
+IndexAmRoutine* CreateIvfAmRoutine(bool flat_only)
 {
 	IndexAmRoutine *amroutine = makeNode(IndexAmRoutine);
 
 	amroutine->amstrategies = 0;
-	amroutine->amsupport = 4;
+	amroutine->amsupport = flat_only ? 4 : 5;
 #if PG_VERSION_NUM >= 130000
 	amroutine->amoptsprocnum = 0;
 #endif
@@ -225,7 +218,7 @@ ivfflathandler(PG_FUNCTION_ARGS)
 	amroutine->amvacuumcleanup = ivfflatvacuumcleanup;
 	amroutine->amcanreturn = NULL;	/* tuple not included in heapsort */
 	amroutine->amcostestimate = ivfflatcostestimate;
-	amroutine->amoptions = ivfflatoptions;
+	amroutine->amoptions = flat_only ? ivfflatoptions : ivfoptions;
 	amroutine->amproperty = NULL;	/* TODO AMPROP_DISTANCE_ORDERABLE */
 #if PG_VERSION_NUM >= 120000
 	amroutine->ambuildphasename = ivfflatbuildphasename;
@@ -247,5 +240,25 @@ ivfflathandler(PG_FUNCTION_ARGS)
 	amroutine->aminitparallelscan = NULL;
 	amroutine->amparallelrescan = NULL;
 
-	PG_RETURN_POINTER(amroutine);
+	return amroutine;
+}
+
+/*
+ * Define index handler
+ *
+ * See https://www.postgresql.org/docs/current/index-api.html
+ */
+PGDLLEXPORT PG_FUNCTION_INFO_V1(ivfflathandler);
+Datum
+ivfflathandler(PG_FUNCTION_ARGS)
+{
+	PG_RETURN_POINTER(CreateIvfAmRoutine(/*flat_only=*/true));
 }
+
+// Define index handler for ivf.
+PGDLLEXPORT PG_FUNCTION_INFO_V1(ivfhandler);
+Datum
+ivfhandler(PG_FUNCTION_ARGS)
+{
+	PG_RETURN_POINTER(CreateIvfAmRoutine(/*flat_only=*/false));
+}
\ No newline at end of file
diff --git a/src/ivfflat.h b/src/ivfflat.h
index 2c18fd4bf..24a65c1c8 100644
--- a/src/ivfflat.h
+++ b/src/ivfflat.h
@@ -11,6 +11,7 @@
 #include "utils/sampling.h"
 #include "utils/tuplesort.h"
 #include "vector.h"
+#include "common/ivf_options.h"
 
 #if PG_VERSION_NUM >= 150000
 #include "common/pg_prng.h"
@@ -31,8 +32,9 @@
 #define IVFFLAT_NORM_PROC 2
 #define IVFFLAT_KMEANS_DISTANCE_PROC 3
 #define IVFFLAT_KMEANS_NORM_PROC 4
+#define IVF_QUANTIZED_DISTANCE_PROC 5
 
-#define IVFFLAT_VERSION	1
+#define IVFFLAT_VERSION	2
 #define IVFFLAT_MAGIC_NUMBER 0x14FF1A7
 #define IVFFLAT_PAGE_ID	0xFF84
 
@@ -49,8 +51,6 @@
 #define PROGRESS_IVFFLAT_PHASE_ASSIGN	3
 #define PROGRESS_IVFFLAT_PHASE_LOAD		4
 
-#define IVFFLAT_LIST_SIZE(_dim)	(offsetof(IvfflatListData, center) + VECTOR_SIZE(_dim))
-
 #define IvfflatPageGetOpaque(page)	((IvfflatPageOpaque) PageGetSpecialPointer(page))
 #define IvfflatPageGetMeta(page)	((IvfflatMetaPageData *) PageGetContents(page))
 
@@ -180,6 +180,11 @@ typedef struct IvfflatBuildState
 	ListInfo   *listInfo;
 	Vector	   *normvec;
 
+	/* Scalar quantization */
+	Vector*		multipliers;
+	bytea*		quantized_storage;
+	IvfQuantizerType quantizer;
+
 #ifdef IVFFLAT_KMEANS_DEBUG
 	double		inertia;
 	double	   *listSums;
@@ -222,15 +227,6 @@ typedef struct IvfflatPageOpaqueData
 
 typedef IvfflatPageOpaqueData * IvfflatPageOpaque;
 
-typedef struct IvfflatListData
-{
-	BlockNumber startPage;
-	BlockNumber insertPage;
-	Vector		center;
-}			IvfflatListData;
-
-typedef IvfflatListData * IvfflatList;
-
 typedef struct IvfflatScanList
 {
 	pairingheap_node ph_node;
@@ -253,8 +249,13 @@ typedef struct IvfflatScanOpaqueData
 	/* Support functions */
 	FmgrInfo   *procinfo;
 	FmgrInfo   *normprocinfo;
+	FmgrInfo   *quantized_distance_procinfo;
 	Oid			collation;
 
+	/* Scalar quantization */
+	Vector*		inv_multipliers;
+	IvfQuantizerType quantizer;
+
 	/* Lists */
 	pairingheap *listQueue;
 	IvfflatScanList lists[FLEXIBLE_ARRAY_MEMBER];	/* must come last */
@@ -284,6 +285,8 @@ void		IvfflatInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXL
 void		IvfflatInit(void);
 PGDLLEXPORT void IvfflatParallelBuildMain(dsm_segment *seg, shm_toc *toc);
 
+uint32_t	IvfflatGetVersion(Relation index, ForkNumber fork_num);
+
 /* Index access methods */
 IndexBuildResult *ivfflatbuild(Relation heap, Relation index, IndexInfo *indexInfo);
 void		ivfflatbuildempty(Relation index);
@@ -300,4 +303,6 @@ void		ivfflatrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderby
 bool		ivfflatgettuple(IndexScanDesc scan, ScanDirection dir);
 void		ivfflatendscan(IndexScanDesc scan);
 
+IndexAmRoutine* CreateIvfAmRoutine(bool flat_only);
+
 #endif
diff --git a/src/ivfinsert.c b/src/ivfinsert.c
index cc744af91..831d5d746 100644
--- a/src/ivfinsert.c
+++ b/src/ivfinsert.c
@@ -6,6 +6,10 @@
 #include "storage/bufmgr.h"
 #include "storage/lmgr.h"
 #include "utils/memutils.h"
+#include "common/ivf_list.h"
+#include "common/ivf_options.h"
+#include "fixed_point/ivf_sq.h"
+#include "fixed_point/scalar_quantizer.h"
 
 /*
  * Find the list that minimizes the distance function
@@ -15,7 +19,9 @@ FindInsertPage(Relation rel, Datum *values, BlockNumber *insertPage, ListInfo *
 {
 	Buffer		cbuf;
 	Page		cpage;
-	IvfflatList list;
+	Item		list;
+	Metadata	*list_metadata;
+	Metadata	*flattened;
 	double		distance;
 	double		minDistance = DBL_MAX;
 	BlockNumber nextblkno = IVFFLAT_HEAD_BLKNO;
@@ -23,6 +29,7 @@ FindInsertPage(Relation rel, Datum *values, BlockNumber *insertPage, ListInfo *
 	Oid			collation;
 	OffsetNumber offno;
 	OffsetNumber maxoffno;
+	uint32_t	version = IvfflatGetVersion(rel, MAIN_FORKNUM);
 
 	/* Avoid compiler warning */
 	listInfo->blkno = nextblkno;
@@ -41,12 +48,22 @@ FindInsertPage(Relation rel, Datum *values, BlockNumber *insertPage, ListInfo *
 
 		for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
 		{
-			list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, offno));
-			distance = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, values[0], PointerGetDatum(&list->center)));
+			list = PageGetItem(cpage, PageGetItemId(cpage, offno));
+			list_metadata = IVF_LIST_GET_METADATA(list, version);
+			flattened = FlattenMetadata(rel, list_metadata, MAIN_FORKNUM);
+			if (flattened == NULL) {
+				UnlockReleaseBuffer(cbuf);
+				elog(ERROR, "failed to get metadata from \"%s\"", RelationGetRelationName(rel));
+			}
+			distance = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, values[0], PointerGetDatum((Vector*)flattened)));
+			if (flattened != list_metadata) {
+				/* This is an external metadata for which we allocated temporary storage that needs to be freed. */
+				pfree(flattened);
+			}
 
 			if (distance < minDistance || !BlockNumberIsValid(*insertPage))
 			{
-				*insertPage = list->insertPage;
+				*insertPage = IVF_LIST_GET_INSERT_PAGE(list, version);
 				listInfo->blkno = nextblkno;
 				listInfo->offno = offno;
 				minDistance = distance;
@@ -59,6 +76,45 @@ FindInsertPage(Relation rel, Datum *values, BlockNumber *insertPage, ListInfo *
 	}
 }
 
+/*
+ * Form an index tuple from a raw vector in its scalar 8-bit quantized form.
+ */
+static IndexTuple
+IndexFormSQQuantizedTuple(Relation index, Vector *raw_vector, bool* is_null)
+{
+	TupleDesc	tupdesc;
+	Vector*		multipliers = NULL;
+	Datum		value;
+	bytea*		quantized_storage = NULL;
+	IndexTuple	itup;
+
+#if PG_VERSION_NUM >= 120000
+	tupdesc = CreateTemplateTupleDesc(/*natts=*/1);
+#else
+	tupdesc = CreateTemplateTupleDesc(/*natts=*/1, false);
+#endif
+	TupleDescInitEntry(tupdesc, (AttrNumber) 1, "quantized_vector", BYTEAOID, -1, 0);
+	tupdesc->attrs[0].attstorage = TYPSTORAGE_PLAIN;
+
+	if (is_null[0])
+		return index_form_tuple(tupdesc, &value, is_null);
+
+	// Compute the quantized vector.
+	multipliers = IvfsqGetMultipliers(index, MAIN_FORKNUM);
+	if (multipliers == NULL)
+		elog(ERROR, "cannot get multipliers from index.");
+
+	quantized_storage = (bytea *) palloc0(multipliers->dim + VARHDRSZ);
+	SET_VARSIZE(quantized_storage, multipliers->dim + VARHDRSZ);
+	value = ScalarQuantizeVector(raw_vector, multipliers, quantized_storage);
+	pfree(multipliers);
+
+	itup = index_form_tuple(tupdesc, &value, is_null);
+	pfree(quantized_storage);
+
+	return itup;
+}
+
 /*
  * Insert a tuple into the index
  */
@@ -75,6 +131,7 @@ InsertTuple(Relation rel, Datum *values, bool *isnull, ItemPointer heap_tid, Rel
 	BlockNumber insertPage = InvalidBlockNumber;
 	ListInfo	listInfo;
 	BlockNumber originalInsertPage;
+	IvfQuantizerType quantizer;
 
 	/* Detoast once for all calls */
 	value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
@@ -93,7 +150,19 @@ InsertTuple(Relation rel, Datum *values, bool *isnull, ItemPointer heap_tid, Rel
 	originalInsertPage = insertPage;
 
 	/* Form tuple */
-	itup = index_form_tuple(RelationGetDescr(rel), &value, isnull);
+	quantizer = IvfGetQuantizer(rel);
+	if (quantizer == kIvfsq8)
+	{
+		itup = IndexFormSQQuantizedTuple(rel, DatumGetVector(value), isnull);
+	}
+	else if (quantizer == kIvfflat)
+	{
+		itup = index_form_tuple(RelationGetDescr(rel), &value, isnull);
+	}
+	else
+	{
+		elog(ERROR, "Unsupported quantizer: %d", quantizer);
+	}
 	itup->t_tid = *heap_tid;
 
 	/* Get tuple size */
diff --git a/src/ivfscan.c b/src/ivfscan.c
index 6703120aa..c7e069b12 100644
--- a/src/ivfscan.c
+++ b/src/ivfscan.c
@@ -9,6 +9,8 @@
 #include "miscadmin.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "common/ivf_list.h"
+#include "fixed_point/ivf_sq.h"
 
 /*
  * Compare list distances
@@ -33,7 +35,9 @@ GetScanLists(IndexScanDesc scan, Datum value)
 {
 	Buffer		cbuf;
 	Page		cpage;
-	IvfflatList list;
+	Item		list;
+	Metadata	*list_metadata;
+	Metadata	*flattened = NULL;
 	OffsetNumber offno;
 	OffsetNumber maxoffno;
 	BlockNumber nextblkno = IVFFLAT_HEAD_BLKNO;
@@ -42,6 +46,7 @@ GetScanLists(IndexScanDesc scan, Datum value)
 	double		distance;
 	IvfflatScanList *scanlist;
 	double		maxDistance = DBL_MAX;
+	uint32_t	version = IvfflatGetVersion(scan->indexRelation, MAIN_FORKNUM);
 
 	/* Search all list pages */
 	while (BlockNumberIsValid(nextblkno))
@@ -54,15 +59,26 @@ GetScanLists(IndexScanDesc scan, Datum value)
 
 		for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
 		{
-			list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, offno));
+			list = PageGetItem(cpage, PageGetItemId(cpage, offno));
+			list_metadata = IVF_LIST_GET_METADATA(list, version);
+			flattened = FlattenMetadata(scan->indexRelation, list_metadata, MAIN_FORKNUM);
+			if (flattened == NULL) {
+				UnlockReleaseBuffer(cbuf);
+				elog(ERROR, "failed to get metadata from \"%s\"", RelationGetRelationName(scan->indexRelation));
+			}
 
 			/* Use procinfo from the index instead of scan key for performance */
-			distance = DatumGetFloat8(FunctionCall2Coll(so->procinfo, so->collation, PointerGetDatum(&list->center), value));
+			distance = DatumGetFloat8(FunctionCall2Coll(so->procinfo, so->collation, PointerGetDatum((Vector*)flattened), value));
+			if (flattened != list_metadata) {
+				// This is an external metadata for which we allocated temporary
+				// storage that needs to be freed.
+				pfree(flattened);
+			}
 
 			if (listCount < so->probes)
 			{
 				scanlist = &so->lists[listCount];
-				scanlist->startPage = list->startPage;
+				scanlist->startPage = IVF_LIST_GET_START_PAGE(list, version);
 				scanlist->distance = distance;
 				listCount++;
 
@@ -79,7 +95,7 @@ GetScanLists(IndexScanDesc scan, Datum value)
 				scanlist = (IvfflatScanList *) pairingheap_remove_first(so->listQueue);
 
 				/* Reuse */
-				scanlist->startPage = list->startPage;
+				scanlist->startPage = IVF_LIST_GET_START_PAGE(list, version);
 				scanlist->distance = distance;
 				pairingheap_add(so->listQueue, &scanlist->ph_node);
 
@@ -111,6 +127,8 @@ GetScanItems(IndexScanDesc scan, Datum value)
 	bool		isnull;
 	TupleDesc	tupdesc = RelationGetDescr(scan->indexRelation);
 	double		tuples = 0;
+	Vector*		distances = NULL;
+	Vector* 	query = DatumGetVector(value);
 
 #if PG_VERSION_NUM >= 120000
 	TupleTableSlot *slot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsVirtual);
@@ -137,6 +155,10 @@ GetScanItems(IndexScanDesc scan, Datum value)
 			LockBuffer(buf, BUFFER_LOCK_SHARE);
 			page = BufferGetPage(buf);
 			maxoffno = PageGetMaxOffsetNumber(page);
+			if (so->quantizer == kIvfsq8)
+				// Compute the distance in batch for all quantized vectors in the page.
+				distances = DatumGetVector(FunctionCall3Coll(so->quantized_distance_procinfo, so->collation,
+								PointerGetDatum(query), PointerGetDatum(so->inv_multipliers), PointerGetDatum(page)));
 
 			for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
 			{
@@ -150,7 +172,9 @@ GetScanItems(IndexScanDesc scan, Datum value)
 				 * performance
 				 */
 				ExecClearTuple(slot);
-				slot->tts_values[0] = FunctionCall2Coll(so->procinfo, so->collation, datum, value);
+				slot->tts_values[0] = (so->quantizer == kIvfsq8) ?
+											Float8GetDatum(distances->x[offno - FirstOffsetNumber]) :
+											FunctionCall2Coll(so->procinfo, so->collation, datum, value);
 				slot->tts_isnull[0] = false;
 				slot->tts_values[1] = PointerGetDatum(&itup->t_tid);
 				slot->tts_isnull[1] = false;
@@ -162,6 +186,11 @@ GetScanItems(IndexScanDesc scan, Datum value)
 
 				tuples++;
 			}
+			if (distances != NULL)
+			{
+				pfree(distances);
+				distances = NULL;
+			}
 
 			searchPage = IvfflatPageGetOpaque(page)->nextblkno;
 
@@ -216,10 +245,11 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
 	Oid			sortOperators[] = {Float8LessOperator};
 	Oid			sortCollations[] = {InvalidOid};
 	bool		nullsFirstFlags[] = {false};
-	int			probes = ivfflat_probes;
+	IvfQuantizerType quantizer = IvfGetQuantizer(index);
+	int			probes = quantizer == kIvfflat ? ivfflat_probes : ivf_probes;
 
 	scan = RelationGetIndexScan(index, nkeys, norderbys);
-	lists = IvfflatGetLists(scan->indexRelation);
+	lists = IvfGetLists(scan->indexRelation);
 
 	if (probes > lists)
 		probes = lists;
@@ -227,12 +257,24 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
 	so = (IvfflatScanOpaque) palloc(offsetof(IvfflatScanOpaqueData, lists) + probes * sizeof(IvfflatScanList));
 	so->buf = InvalidBuffer;
 	so->first = true;
+	so->quantizer = quantizer;
 	so->probes = probes;
 
 	/* Set support functions */
 	so->procinfo = index_getprocinfo(index, 1, IVFFLAT_DISTANCE_PROC);
+	so->quantized_distance_procinfo = (so->quantizer == kIvfflat ?
+											NULL : index_getprocinfo(index, 1, IVF_QUANTIZED_DISTANCE_PROC));
 	so->normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
 	so->collation = index->rd_indcollation[0];
+	so->inv_multipliers = NULL;
+	if (so->quantizer == kIvfsq8)
+	{
+		so->inv_multipliers = IvfsqGetMultipliers(index, MAIN_FORKNUM);
+		if (so->inv_multipliers == NULL)
+			elog(ERROR, "cannot get inversed multipliers from index.");
+		for (int i = 0; i < so->inv_multipliers->dim; ++i)
+			so->inv_multipliers->x[i] = 1.0f / so->inv_multipliers->x[i];
+	}
 
 	/* Create tuple description for sorting */
 #if PG_VERSION_NUM >= 120000
@@ -376,6 +418,10 @@ ivfflatendscan(IndexScanDesc scan)
 	pairingheap_free(so->listQueue);
 	tuplesort_end(so->sortstate);
 
+	if (so->inv_multipliers != NULL) {
+		pfree(so->inv_multipliers);
+		so->inv_multipliers = NULL;
+	}
 	pfree(so);
 	scan->opaque = NULL;
 }
diff --git a/src/ivfutils.c b/src/ivfutils.c
index a37f51f20..c0b2f052d 100644
--- a/src/ivfutils.c
+++ b/src/ivfutils.c
@@ -3,6 +3,7 @@
 #include "ivfflat.h"
 #include "storage/bufmgr.h"
 #include "vector.h"
+#include "common/ivf_list.h"
 
 /*
  * Allocate a vector array
@@ -183,29 +184,30 @@ IvfflatUpdateList(Relation index, ListInfo listInfo,
 	Buffer		buf;
 	Page		page;
 	GenericXLogState *state;
-	IvfflatList list;
+	Item		list;
 	bool		changed = false;
+	uint32_t	version = IvfflatGetVersion(index, MAIN_FORKNUM);
 
 	buf = ReadBufferExtended(index, forkNum, listInfo.blkno, RBM_NORMAL, NULL);
 	LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 	state = GenericXLogStart(index);
 	page = GenericXLogRegisterBuffer(state, buf, 0);
-	list = (IvfflatList) PageGetItem(page, PageGetItemId(page, listInfo.offno));
+	list = PageGetItem(page, PageGetItemId(page, listInfo.offno));
 
-	if (BlockNumberIsValid(insertPage) && insertPage != list->insertPage)
+	if (BlockNumberIsValid(insertPage) && insertPage != IVF_LIST_GET_INSERT_PAGE(list, version))
 	{
 		/* Skip update if insert page is lower than original insert page  */
 		/* This is needed to prevent insert from overwriting vacuum */
 		if (!BlockNumberIsValid(originalInsertPage) || insertPage >= originalInsertPage)
 		{
-			list->insertPage = insertPage;
+			IVF_LIST_SET_INSERT_PAGE(list, version, insertPage);
 			changed = true;
 		}
 	}
 
-	if (BlockNumberIsValid(startPage) && startPage != list->startPage)
+	if (BlockNumberIsValid(startPage) && startPage != IVF_LIST_GET_START_PAGE(list, version))
 	{
-		list->startPage = startPage;
+		IVF_LIST_SET_START_PAGE(list, version, startPage);
 		changed = true;
 	}
 
@@ -218,3 +220,21 @@ IvfflatUpdateList(Relation index, ListInfo listInfo,
 		UnlockReleaseBuffer(buf);
 	}
 }
+
+uint32_t
+IvfflatGetVersion(Relation index, ForkNumber fork_num)
+{
+	Buffer buf;
+	Page page;
+	uint32_t version;
+
+	buf = ReadBufferExtended(index, fork_num, IVFFLAT_METAPAGE_BLKNO, RBM_NORMAL,
+							 /*strategy=*/NULL);
+	LockBuffer(buf, BUFFER_LOCK_SHARE);
+
+	page = BufferGetPage(buf);
+	version = IvfflatPageGetMeta(page)->version;
+
+	UnlockReleaseBuffer(buf);
+	return version;
+}
\ No newline at end of file
diff --git a/src/ivfvacuum.c b/src/ivfvacuum.c
index 435dfe1f1..34b0db12f 100644
--- a/src/ivfvacuum.c
+++ b/src/ivfvacuum.c
@@ -3,6 +3,7 @@
 #include "commands/vacuum.h"
 #include "ivfflat.h"
 #include "storage/bufmgr.h"
+#include "common/ivf_list.h"
 
 /*
  * Bulk delete tuples from the index
@@ -14,6 +15,7 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
 	Relation	index = info->index;
 	BlockNumber blkno = IVFFLAT_HEAD_BLKNO;
 	BufferAccessStrategy bas = GetAccessStrategy(BAS_BULKREAD);
+	uint32_t version = IvfflatGetVersion(index, MAIN_FORKNUM);
 
 	if (stats == NULL)
 		stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
@@ -37,9 +39,9 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
 		/* Iterate over lists */
 		for (coffno = FirstOffsetNumber; coffno <= cmaxoffno; coffno = OffsetNumberNext(coffno))
 		{
-			IvfflatList list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, coffno));
+			Item list = PageGetItem(cpage, PageGetItemId(cpage, coffno));
 
-			startPages[coffno - FirstOffsetNumber] = list->startPage;
+			startPages[coffno - FirstOffsetNumber] = IVF_LIST_GET_START_PAGE(list, version);
 		}
 
 		listInfo.blkno = blkno;
diff --git a/src/vector.c b/src/vector.c
index 8a2fa54f1..328ea2886 100644
--- a/src/vector.c
+++ b/src/vector.c
@@ -14,6 +14,7 @@
 #include "utils/lsyscache.h"
 #include "utils/numeric.h"
 #include "vector.h"
+#include "common/ivf_options.h"
 
 #if PG_VERSION_NUM >= 120000
 #include "common/shortest_dec.h"
@@ -40,6 +41,7 @@ _PG_init(void)
 {
 	HnswInit();
 	IvfflatInit();
+	IvfInit();
 }
 
 /*
diff --git a/test/expected/ivf_cosine.out b/test/expected/ivf_cosine.out
new file mode 100644
index 000000000..f8e4529e5
--- /dev/null
+++ b/test/expected/ivf_cosine.out
@@ -0,0 +1,26 @@
+SET enable_seqscan = off;
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivf (val vector_cosine_ops) WITH (lists = 1, quantizer = 'SQ8');
+INSERT INTO t (val) VALUES ('[1,2,4]');
+SELECT * FROM t ORDER BY val <=> '[3,3,3]';
+   val   
+---------
+ [1,1,1]
+ [1,2,3]
+ [1,2,4]
+(3 rows)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> '[0,0,0]') t2;
+ count 
+-------
+     3
+(1 row)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::vector)) t2;
+ count 
+-------
+     3
+(1 row)
+
+DROP TABLE t;
diff --git a/test/expected/ivf_ip.out b/test/expected/ivf_ip.out
new file mode 100644
index 000000000..60022daa4
--- /dev/null
+++ b/test/expected/ivf_ip.out
@@ -0,0 +1,20 @@
+SET enable_seqscan = off;
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), ('[1,2,4]'), (NULL);
+CREATE INDEX ON t USING ivf (val vector_ip_ops) WITH (lists = 1, quantizer = 'SQ8');
+SELECT * FROM t ORDER BY val <#> '[3,3,3]';
+   val   
+---------
+ [1,2,4]
+ [1,2,3]
+ [1,1,1]
+ [0,0,0]
+(4 rows)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::vector)) t2;
+ count 
+-------
+     4
+(1 row)
+
+DROP TABLE t;
diff --git a/test/expected/ivf_l2.out b/test/expected/ivf_l2.out
new file mode 100644
index 000000000..d44d59011
--- /dev/null
+++ b/test/expected/ivf_l2.out
@@ -0,0 +1,30 @@
+SET enable_seqscan = off;
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivf (val vector_l2_ops) WITH (lists = 1, quantizer = 'SQ8');
+INSERT INTO t (val) VALUES ('[1,2,4]');
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+   val   
+---------
+ [1,2,3]
+ [1,2,4]
+ [1,1,1]
+ [0,0,0]
+(4 rows)
+
+SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector);
+   val   
+---------
+ [0,0,0]
+ [1,1,1]
+ [1,2,3]
+ [1,2,4]
+(4 rows)
+
+SELECT COUNT(*) FROM t;
+ count 
+-------
+     5
+(1 row)
+
+DROP TABLE t;
diff --git a/test/expected/ivf_options.out b/test/expected/ivf_options.out
new file mode 100644
index 000000000..391b76c7c
--- /dev/null
+++ b/test/expected/ivf_options.out
@@ -0,0 +1,17 @@
+CREATE TABLE t (val vector(3));
+CREATE INDEX ON t USING ivf (val vector_l2_ops) WITH (lists = 0);
+ERROR:  value 0 out of bounds for option "lists"
+DETAIL:  Valid values are between "1" and "32768".
+CREATE INDEX ON t USING ivf (val vector_l2_ops) WITH (lists = 32769);
+ERROR:  value 32769 out of bounds for option "lists"
+DETAIL:  Valid values are between "1" and "32768".
+CREATE INDEX ON t USING ivf (val vector_l2_ops) WITH (lists = 1, quantizer = 'invalid');
+ERROR:  invalid value for enum option "quantizer": invalid
+DETAIL:  The valid option for quantization is "SQ8".
+SHOW ivf.probes;
+ ivf.probes 
+------------
+ 1
+(1 row)
+
+DROP TABLE t;
diff --git a/test/expected/ivf_unlogged.out b/test/expected/ivf_unlogged.out
new file mode 100644
index 000000000..d748e736f
--- /dev/null
+++ b/test/expected/ivf_unlogged.out
@@ -0,0 +1,13 @@
+SET enable_seqscan = off;
+CREATE UNLOGGED TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivf (val vector_l2_ops) WITH (lists = 1, quantizer = 'SQ8');
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+   val   
+---------
+ [1,2,3]
+ [1,1,1]
+ [0,0,0]
+(3 rows)
+
+DROP TABLE t;
diff --git a/test/perl/ivf_options.sql b/test/perl/ivf_options.sql
new file mode 100644
index 000000000..e69de29bb
diff --git a/test/sql/ivf_cosine.sql b/test/sql/ivf_cosine.sql
new file mode 100644
index 000000000..a3c8ae278
--- /dev/null
+++ b/test/sql/ivf_cosine.sql
@@ -0,0 +1,13 @@
+SET enable_seqscan = off;
+
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivf (val vector_cosine_ops) WITH (lists = 1, quantizer = 'SQ8');
+
+INSERT INTO t (val) VALUES ('[1,2,4]');
+
+SELECT * FROM t ORDER BY val <=> '[3,3,3]';
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> '[0,0,0]') t2;
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::vector)) t2;
+
+DROP TABLE t;
diff --git a/test/sql/ivf_ip.sql b/test/sql/ivf_ip.sql
new file mode 100644
index 000000000..79cebf458
--- /dev/null
+++ b/test/sql/ivf_ip.sql
@@ -0,0 +1,10 @@
+SET enable_seqscan = off;
+
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), ('[1,2,4]'), (NULL);
+CREATE INDEX ON t USING ivf (val vector_ip_ops) WITH (lists = 1, quantizer = 'SQ8');
+
+SELECT * FROM t ORDER BY val <#> '[3,3,3]';
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::vector)) t2;
+
+DROP TABLE t;
diff --git a/test/sql/ivf_l2.sql b/test/sql/ivf_l2.sql
new file mode 100644
index 000000000..257169dc7
--- /dev/null
+++ b/test/sql/ivf_l2.sql
@@ -0,0 +1,13 @@
+SET enable_seqscan = off;
+
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivf (val vector_l2_ops) WITH (lists = 1, quantizer = 'SQ8');
+
+INSERT INTO t (val) VALUES ('[1,2,4]');
+
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector);
+SELECT COUNT(*) FROM t;
+
+DROP TABLE t;
diff --git a/test/sql/ivf_options.sql b/test/sql/ivf_options.sql
new file mode 100644
index 000000000..fe2671d9b
--- /dev/null
+++ b/test/sql/ivf_options.sql
@@ -0,0 +1,8 @@
+CREATE TABLE t (val vector(3));
+CREATE INDEX ON t USING ivf (val vector_l2_ops) WITH (lists = 0);
+CREATE INDEX ON t USING ivf (val vector_l2_ops) WITH (lists = 32769);
+CREATE INDEX ON t USING ivf (val vector_l2_ops) WITH (lists = 1, quantizer = 'invalid');
+
+SHOW ivf.probes;
+
+DROP TABLE t;
diff --git a/test/sql/ivf_unlogged.sql b/test/sql/ivf_unlogged.sql
new file mode 100644
index 000000000..e18b93b12
--- /dev/null
+++ b/test/sql/ivf_unlogged.sql
@@ -0,0 +1,9 @@
+SET enable_seqscan = off;
+
+CREATE UNLOGGED TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivf (val vector_l2_ops) WITH (lists = 1, quantizer = 'SQ8');
+
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+
+DROP TABLE t;
diff --git a/test/t/017_ivf_wal.pl b/test/t/017_ivf_wal.pl
new file mode 100644
index 000000000..5d9cbf715
--- /dev/null
+++ b/test/t/017_ivf_wal.pl
@@ -0,0 +1,101 @@
+# Based on postgres/contrib/bloom/t/001_wal.pl
+
+# Test generic xlog record work for ivf index replication.
+use strict;
+use warnings;
+use PostgresNode;
+use TestLib;
+use Test::More;
+
+my $dim = 32;
+
+my $node_primary;
+my $node_replica;
+
+# Run few queries on both primary and replica and check their results match.
+sub test_index_replay
+{
+	my ($test_name) = @_;
+
+	# Wait for replica to catch up
+	my $applname = $node_replica->name;
+
+	my $server_version_num = $node_primary->safe_psql("postgres", "SHOW server_version_num");
+	my $caughtup_query = "SELECT pg_current_wal_lsn() <= replay_lsn FROM pg_stat_replication WHERE application_name = '$applname';";
+	$node_primary->poll_query_until('postgres', $caughtup_query)
+	  or die "Timed out while waiting for replica 1 to catch up";
+
+	my @r = ();
+	for (1 .. $dim)
+	{
+		push(@r, rand());
+	}
+	my $sql = join(",", @r);
+
+	my $queries = qq(
+		SET enable_seqscan = off;
+		SELECT * FROM tst ORDER BY v <-> '[$sql]' LIMIT 10;
+	);
+
+	# Run test queries and compare their result
+	my $primary_result = $node_primary->safe_psql("postgres", $queries);
+	my $replica_result = $node_replica->safe_psql("postgres", $queries);
+
+	is($primary_result, $replica_result, "$test_name: query result matches");
+	return;
+}
+
+# Use ARRAY[random(), random(), random(), ...] over
+# SELECT array_agg(random()) FROM generate_series(1, $dim)
+# to generate different values for each row
+my $array_sql = join(",", ('random()') x $dim);
+
+# Initialize primary node
+$node_primary = get_new_node('primary');
+$node_primary->init(allows_streaming => 1);
+if ($dim > 32)
+{
+	# TODO use wal_keep_segments for Postgres < 13
+	$node_primary->append_conf('postgresql.conf', qq(wal_keep_size = 1GB));
+}
+if ($dim > 1500)
+{
+	$node_primary->append_conf('postgresql.conf', qq(maintenance_work_mem = 128MB));
+}
+$node_primary->start;
+my $backup_name = 'my_backup';
+
+# Take backup
+$node_primary->backup($backup_name);
+
+# Create streaming replica linking to primary
+$node_replica = get_new_node('replica');
+$node_replica->init_from_backup($node_primary, $backup_name, has_streaming => 1);
+$node_replica->start;
+
+# Create ivf index on primary
+$node_primary->safe_psql("postgres", "CREATE EXTENSION vector;");
+$node_primary->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim));");
+$node_primary->safe_psql("postgres",
+	"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series(1, 100000) i;"
+);
+$node_primary->safe_psql("postgres", "CREATE INDEX ON tst USING ivf (v vector_l2_ops) WITH (quantizer='SQ8');");
+
+# Test that queries give same result
+test_index_replay('initial');
+
+# Run 10 cycles of table modification. Run test queries after each modification.
+for my $i (1 .. 10)
+{
+	$node_primary->safe_psql("postgres", "DELETE FROM tst WHERE i = $i;");
+	test_index_replay("delete $i");
+	$node_primary->safe_psql("postgres", "VACUUM tst;");
+	test_index_replay("vacuum $i");
+	my ($start, $end) = (100001 + ($i - 1) * 10000, 100000 + $i * 10000);
+	$node_primary->safe_psql("postgres",
+		"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series($start, $end) i;"
+	);
+	test_index_replay("insert $i");
+}
+
+done_testing();
diff --git a/test/t/018_ivf_vacuum.pl b/test/t/018_ivf_vacuum.pl
new file mode 100644
index 000000000..ecaaa782c
--- /dev/null
+++ b/test/t/018_ivf_vacuum.pl
@@ -0,0 +1,44 @@
+use strict;
+use warnings;
+use PostgresNode;
+use TestLib;
+use Test::More;
+
+my $dim = 3;
+
+my @r = ();
+for (1 .. $dim)
+{
+	my $v = int(rand(1000)) + 1;
+	push(@r, "i % $v");
+}
+my $array_sql = join(", ", @r);
+
+# Initialize node
+my $node = get_new_node('node');
+$node->init;
+$node->start;
+
+# Create table and index
+$node->safe_psql("postgres", "CREATE EXTENSION vector;");
+$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim));");
+$node->safe_psql("postgres",
+	"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series(1, 100000) i;"
+);
+$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivf (v vector_l2_ops) WITH (quantizer='SQ8');");
+
+# Get size
+my $size = $node->safe_psql("postgres", "SELECT pg_total_relation_size('tst_v_idx');");
+
+# Delete all, vacuum, and insert same data
+$node->safe_psql("postgres", "DELETE FROM tst;");
+$node->safe_psql("postgres", "VACUUM tst;");
+$node->safe_psql("postgres",
+	"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series(1, 100000) i;"
+);
+
+# Check size
+my $new_size = $node->safe_psql("postgres", "SELECT pg_total_relation_size('tst_v_idx');");
+is($size, $new_size, "size does not change");
+
+done_testing();
diff --git a/test/t/019_ivf_recall.pl b/test/t/019_ivf_recall.pl
new file mode 100644
index 000000000..5d3537feb
--- /dev/null
+++ b/test/t/019_ivf_recall.pl
@@ -0,0 +1,112 @@
+use strict;
+use warnings;
+use PostgresNode;
+use TestLib;
+use Test::More;
+
+my $node;
+my @queries = ();
+my @expected;
+my $limit = 20;
+
+sub test_recall
+{
+	my ($probes, $min, $operator) = @_;
+	my $correct = 0;
+	my $total = 0;
+
+	my $explain = $node->safe_psql("postgres", qq(
+		SET enable_seqscan = off;
+		SET ivf.probes = $probes;
+		EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator '$queries[0]' LIMIT $limit;
+	));
+	like($explain, qr/Index Scan using idx on tst/);
+
+	for my $i (0 .. $#queries)
+	{
+		my $actual = $node->safe_psql("postgres", qq(
+			SET enable_seqscan = off;
+			SET ivf.probes = $probes;
+			SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
+		));
+		my @actual_ids = split("\n", $actual);
+		my %actual_set = map { $_ => 1 } @actual_ids;
+
+		my @expected_ids = split("\n", $expected[$i]);
+
+		foreach (@expected_ids)
+		{
+			if (exists($actual_set{$_}))
+			{
+				$correct++;
+			}
+			$total++;
+		}
+	}
+
+	cmp_ok($correct / $total, ">=", $min, $operator);
+}
+
+# Initialize node
+$node = get_new_node('node');
+$node->init;
+$node->start;
+
+# Create table
+$node->safe_psql("postgres", "CREATE EXTENSION vector;");
+$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector(3));");
+$node->safe_psql("postgres",
+	"INSERT INTO tst SELECT i, ARRAY[random(), random(), random()] FROM generate_series(1, 100000) i;"
+);
+
+# Generate queries
+for (1 .. 20)
+{
+	my $r1 = rand();
+	my $r2 = rand();
+	my $r3 = rand();
+	push(@queries, "[$r1,$r2,$r3]");
+}
+
+# Check each index type
+my @operators = ("<->", "<#>", "<=>");
+my @opclasses = ("vector_l2_ops", "vector_ip_ops", "vector_cosine_ops");
+
+for my $i (0 .. $#operators)
+{
+	my $operator = $operators[$i];
+	my $opclass = $opclasses[$i];
+
+	# Get exact results
+	@expected = ();
+	foreach (@queries)
+	{
+		my $res = $node->safe_psql("postgres", "SELECT i FROM tst ORDER BY v $operator '$_' LIMIT $limit;");
+		push(@expected, $res);
+	}
+
+	# Build index serially
+	$node->safe_psql("postgres", qq(
+		SET max_parallel_maintenance_workers = 0;
+		CREATE INDEX idx ON tst USING ivf (v $opclass) WITH (quantizer='SQ8');
+	));
+
+	# Test approximate results
+	if ($operator ne "<#>" && $operator ne "<=>")
+	{
+		# TODO fix test
+		test_recall(1, 0.73, $operator);
+		test_recall(10, 0.80, $operator);
+	}
+
+	# TODO fix test
+	if ($operator ne "<=>")
+	{
+		# Account for equal distances
+		test_recall(100, 0.90, $operator);
+	}
+
+	$node->safe_psql("postgres", "DROP INDEX idx;");
+}
+
+done_testing();
diff --git a/test/t/021_ivf_inserts.pl b/test/t/021_ivf_inserts.pl
new file mode 100644
index 000000000..bf1876927
--- /dev/null
+++ b/test/t/021_ivf_inserts.pl
@@ -0,0 +1,59 @@
+use strict;
+use warnings;
+use PostgresNode;
+use TestLib;
+use Test::More;
+
+my $dim = 8000;
+
+my $array_sql = join(",", ('random()') x $dim);
+
+# Initialize node
+my $node = get_new_node('node');
+$node->init;
+$node->append_conf('postgresql.conf', qq(ivf.create_sq8_index_enabled = on));
+$node->append_conf('postgresql.conf', qq(maintenance_work_mem = 512MB));
+$node->start;
+
+# Create table and index
+$node->safe_psql("postgres", "CREATE EXTENSION vector;");
+$node->safe_psql("postgres", "CREATE TABLE tst (i int4 primary key, v vector($dim));");
+$node->safe_psql("postgres",
+	"INSERT INTO tst SELECT i, ARRAY[$array_sql] FROM generate_series(1, 10000) i;"
+);
+$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivf (v vector_l2_ops) WITH (quantizer='SQ8');");
+
+sub idx_scan
+{
+	# Stats do not update instantaneously
+	# https://www.postgresql.org/docs/current/monitoring-stats.html#MONITORING-STATS-VIEWS
+	sleep(1);
+	$node->safe_psql("postgres", "SELECT idx_scan FROM pg_stat_user_indexes WHERE indexrelid = 'tst_v_idx'::regclass;");
+}
+
+my $expected = 10000;
+
+my $count = $node->safe_psql("postgres", "SELECT COUNT(*) FROM tst;");
+is($count, $expected);
+is(idx_scan(), 0);
+
+$count = $node->safe_psql("postgres", qq(
+	SET enable_seqscan = off;
+	SET ivf.probes = 100;
+	SELECT COUNT(*) FROM (SELECT v FROM tst ORDER BY v <-> (SELECT v FROM tst LIMIT 1)) t;
+));
+is($count, $expected);
+is(idx_scan(), 1);
+
+# Test recall
+for (1..20) {
+  my $i = int(rand() * 10000);
+  my $query = $node->safe_psql("postgres", "SELECT v FROM tst WHERE i = $i;");
+  my $res = $node->safe_psql("postgres", qq(
+    SET enable_seqscan = off;
+    SELECT v FROM tst ORDER BY v <-> '$query' LIMIT 1;
+  ));
+  is($res, $query);
+}
+
+done_testing();
