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:
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
print(modality_gap([[1.0, 0.0]], [[0.0, 1.0]]))
1.4142
-
L2 Normalization: Each embedding vector is projected onto the unit sphere to simulate contrastive model behavior. The image vector has a norm of , so it remains . The text vector has a norm of , so it remains .
-
Centroid Calculation: The mean vector for each modality is computed. With only one sample per modality, the image centroid is and the text centroid is .
-
Difference Vector: The vector difference between the centroids is calculated to determine the separation: .
-
Euclidean Distance: The modality gap is the L2 norm of this difference vector: .
-
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.