v9.1.1
Menu

L2-Normalize an Embedding

easyFREEContrastive Objectives: CLIP and SigLIPVision-Language ModelsVLM 1: Vision-Language Models

Problem Statement

Contrastive training compares embeddings by cosine similarity, which requires them to live on the unit sphere. Implement the L2 normalization applied to every image and text embedding before the dot product.

Background

For a vector v, the L2-normalized version is

v^=v∥v∥2,∥v∥2=∑ivi2\hat{v} = \frac{v}{\lVert v \rVert_2}, \qquad \lVert v \rVert_2 = \sqrt{\sum_i v_i^2}

After this, a dot product between two normalized vectors is their cosine similarity. Guard the zero vector: if the norm is 0, return the vector unchanged (all zeros) rather than dividing by zero.

Your Task

Implement:

def l2_normalize(v):

Return the normalized vector as a list rounded to 4 decimals.

Input Format

  • v: list of numbers.

Output Format

  • A list of floats rounded to 4 decimals.

Sample

print(l2_normalize([3.0, 4.0]))

Output:

[0.6, 0.8]

Example

Input
print(l2_normalize([3.0, 4.0]))
Output
[0.6, 0.8]
Reasoning
  • The input v is the embedding [3.0,4.0][3.0, 4.0]: a point in 2-D space whose length is not yet 1, so a dot product with it would mix direction with magnitude.
  • Its Euclidean length is ∥v∥2=32+42=9+16=25=5\lVert v \rVert_2 = \sqrt{3^2 + 4^2} = \sqrt{9 + 16} = \sqrt{25} = 5, the classic 3-4-5 right triangle.
  • Dividing every component by that length shrinks the vector onto the unit circle without turning it: v^=[3/5, 4/5]=[0.6, 0.8]\hat{v} = [3/5,\ 4/5] = [0.6,\ 0.8].
  • Check: 0.62+0.82=0.36+0.64=10.6^2 + 0.8^2 = 0.36 + 0.64 = 1, so the result has length exactly 1. Both values are already exact at 4 decimal places, giving [0.6, 0.8].
  • Notice that the ratio 3:43:4 is preserved: only the scale changes, never the direction. Any positive multiple, such as [6,8][6, 8], lands on the same [0.6, 0.8].
  • The zero vector has length 0 and no direction, so [0.0, 0.0] comes back as [0.0, 0.0] instead of a division by zero.

Constraints

  • 1 <= len(v) <= 4096.
  • The norm is the Euclidean (L2) norm.
  • A zero vector is returned unchanged (no division by zero).
  • Round every entry to 4 decimals; avoid -0.0.

More from VLM 1: Vision-Language Models

solution.py

Test results

Sign in to run your code against the test cases.