PIXELBANKv9.1.0
Menu

Modality Gap Between Image and Text Embeddings

Problem Statement

Even after contrastive training, image and text embeddings occupy two separated cones on the hypersphere — the "modality gap." Quantify it as the Euclidean distance between the two centroids of the L2-normalized embeddings.

Background

Given a batch of image embeddings and text embeddings, first L2-normalize each vector (contrastive models operate on the unit sphere). The modality gap is the distance between the mean image vector and the mean text vector:

Δ=∥1N∑iu^i−1M∑jv^j∥2\Delta = \left\lVert \frac{1}{N}\sum_i \hat{u}_i - \frac{1}{M}\sum_j \hat{v}_j \right\rVert_2

Liang et al. (2022) showed this gap is created at initialization and persists through training; shrinking it can change downstream behavior.

Your Task

Implement:

def modality_gap(image_embs, text_embs):

Return the gap as a float rounded to 4 decimals.

Input Format

  • image_embs: N x D nested list.
  • text_embs: M x D nested list.

Output Format

  • A float rounded to 4 decimals.

Sample

print(modality_gap([[1.0, 0.0]], [[0.0, 1.0]]))

Output:

1.4142

Example:

Input:
print(modality_gap([[1.0, 0.0]], [[0.0, 1.0]]))
Output:
1.4142
Reasoning:
  • L2 Normalization: Each embedding vector is projected onto the unit sphere to simulate contrastive model behavior. The image vector [1.0,0.0][1.0, 0.0] has a norm of 12+02=1\sqrt{1^2 + 0^2} = 1, so it remains u^1=[1.0,0.0]\hat{u}_1 = [1.0, 0.0]. The text vector [0.0,1.0][0.0, 1.0] has a norm of 02+12=1\sqrt{0^2 + 1^2} = 1, so it remains v^1=[0.0,1.0]\hat{v}_1 = [0.0, 1.0].

  • Centroid Calculation: The mean vector for each modality is computed. With only one sample per modality, the image centroid is uˉ=[1.0,0.0]\bar{u} = [1.0, 0.0] and the text centroid is vˉ=[0.0,1.0]\bar{v} = [0.0, 1.0].

  • Difference Vector: The vector difference between the centroids is calculated to determine the separation: uˉ−vˉ=[1.0−0.0,0.0−1.0]=[1.0,−1.0]\bar{u} - \bar{v} = [1.0 - 0.0, 0.0 - 1.0] = [1.0, -1.0].

  • Euclidean Distance: The modality gap is the L2 norm of this difference vector: Δ=1.02+(−1.0)2=1+1=2≈1.41421356\Delta = \sqrt{1.0^2 + (-1.0)^2} = \sqrt{1 + 1} = \sqrt{2} \approx 1.41421356.

  • The final output is 1.4142

Constraints:

  • 1 <= N, M <= 2000, 1 <= D <= 1024.
  • L2-normalize every vector before averaging (skip zero vectors: leave them as zeros).
  • Return the Euclidean distance between the two centroids, rounded to 4 decimals.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Modality Gap Between Image and Text Embeddings - Medium | PixelBank