Neural Mastery
← Practice
Scalar Quantize a Vectormedium

Scalar Quantize a Vector

medium RAG & Retrieval 15–20 min

NumPy allowed · plain Python earns 10 bonus points

RAG step 1/4

A query retrieves context

Embedding similarity ranks the documents before generation.
Open lesson →
01query
02embed
03retrieve
04context
What is RAG?→ embed →top context
retrieval.md44%
rag-systems.md33%
agents.md24%

Cosine-like similarity scores ranked before context assembly

Implement scalar quantization, the memory-compression technique real vector databases (Qdrant, Milvus, FAISS's ScalarQuantizer) use to shrink float32 embeddings down to 8-bit (or fewer) integer codes so billions of vectors fit in RAM.

Related Skills

Task

Implement scalar_quantize(vector, num_bits): map each float in vector linearly from [min(vector), max(vector)] onto integer codes in [0, 2**num_bits - 1], rounding to the nearest code.

Function Signature

scalar_quantize(vector: list[float], num_bits: int) -> list[int]

Examples

Example 1: 8-bit Quantization
Input: vector = [0, 0.25, 1] num_bits = 8
Output: [0, 64, 255]
Explanation: 0.25 of the [0,1] range maps to round(0.25 * 255) = 64
Example 2: 2-bit Quantization With Negatives
Input: vector = [-1, -0.2, 1] num_bits = 2
Output: [0, 1, 3]

Constraints

  • Libraries (NumPy) are allowed and accepted normally.
  • A plain-Python solution earns 10 bonus points.
  • Raise ValueError if num_bits <= 0.
  • Each returned code must be an integer in [0, 2**num_bits - 1] inclusive.
  • If min(vector) == max(vector) (zero range), return a list of all zeros instead of dividing by zero.
Python3Saved ✓
def scalar_quantize(vector: list[float], num_bits: int) -> list[int]:
"""Uniformly quantize each element of 'vector' to an integer code in
[0, 2**num_bits - 1] using min-max scalar quantization. Raise
ValueError if num_bits <= 0. If every element is identical (a zero
range), return all-zero codes instead of dividing by zero."""
# Your implementation here
pass

Case 1: 8-bit Quantization
Input: vector = [0, 0.25, 1] num_bits = 8
Expected: [0, 64, 255]
Case 2: 2-bit Quantization With Negatives
Input: vector = [-1, -0.2, 1] num_bits = 2
Expected: [0, 1, 3]