TensorTonic
Study Plans
Study Plan
Implement Symmetric CLIP Contrastive Loss
Loss FunctionsLanguage ModelsComputer Vision
Medium

Compute symmetric CLIP contrastive loss for B paired image and text embeddings. Matching pairs occupy the same row. Normalize each embedding vector x using

x^=xmax⁡(∥x∥2,10−12).\widehat{x}=\frac{x}{\max(\lVert x\rVert_2,10^{-12})}.x=max(∥x∥2​,10−12)x​.

Here, the norm is Euclidean; this normalization leaves a zero vector at zero. With image vector v, text vector t, and positive temperature τ\tauτ, define the similarity matrix

Sij=v^iTt^jτ.S_{ij}=\frac{\widehat v_i^{\mathsf T}\widehat t_j}{\tau}.Sij​=τviT​tj​​.

The symmetric loss is

L=−12B∑i=1B[log⁡eSii∑j=1BeSij+log⁡eSii∑j=1BeSji].L=-\frac{1}{2B}\sum_{i=1}^{B}\left[\log\frac{e^{S_{ii}}}{\sum_{j=1}^{B}e^{S_{ij}}}+\log\frac{e^{S_{ii}}}{\sum_{j=1}^{B}e^{S_{ji}}}\right].L=−2B1​i=1∑B​[log∑j=1B​eSij​eSii​​+log∑j=1B​eSji​eSii​​].

Indices i and j identify pairs; log is the natural logarithm. Each directional accuracy is the fraction of rows or columns whose highest similarity selects its matched diagonal entry. Ties select the lowest index.

Return a Python dictionary of PyTorch tensors: loss, image_to_text_accuracy, and text_to_image_accuracy are scalars; similarities has shape (B, B). All outputs preserve the embedding dtype and device.

Loading visualization...

Examples

Input: image_embeddings = [[1,0],[0,1]], text_embeddings = [[1,0],[0,1]], temperature = 1

Output: {"loss":0.313262,"similarities":[[1,0],[0,1]],"image_to_text_accuracy":1,"text_to_image_accuracy":1}

Explanation: Each diagonal cosine similarity exceeds its off-diagonal alternative by one.

Input: image_embeddings = [[3,4]], text_embeddings = [[6,8]], temperature = 0.5

Output: {"loss":0,"similarities":[[2]],"image_to_text_accuracy":1,"text_to_image_accuracy":1}

Input: image_embeddings = [[1,0],[1,1]], text_embeddings = [[1,0],[0,1]], temperature = 1

Output: {"loss":0.491157,"similarities":[[1,0],[0.707107,0.707107]],"image_to_text_accuracy":0.5,"text_to_image_accuracy":1}

Hint 1

torch.nn.functional.normalize supports a lower bound for the norm denominator.

Hint 2

torch.nn.functional.cross_entropy accepts a logit matrix and class-index targets.

Hint 3

Tensor.argmax returns the first index when maximum values are tied.

Requirements

  • Use PyTorch and preserve floating dtype and device.
  • Evaluate the contrastive loss stably for large logits.
  • Do not modify either embedding tensor.

Constraints

  • Image and text embeddings are finite rank-two PyTorch tensors with identical positive shape (batch, features).
  • Both tensors share floating dtype and device; editor inputs use float32.
  • temperature is a positive finite Python number.
  • Zero rows and noncontiguous inputs are valid.
Try Similar Problems
Implement the SigLIP Pairwise LossMediumAssign Multimodal RoPE CoordinatesMediumPatchify a Batch of ImagesEasyCompare Sequence and Token Length NormalizationMediumImplement the DPO LossMediumScore a KL-Regularized Policy BatchMediumCompute a Clipped GRPO SurrogateHardBuild an Assistant-Only SFT Loss MaskEasySigmoid Focal LossMediumGeneralized IoU LossMediumComplete IoU LossMediumDice LossEasy

Accepts: array

Accepts: array

Accepts: number

You must run your code first.

Implement Symmetric CLIP Contrastive Loss

Loss FunctionsLanguage ModelsComputer Vision
Medium

Compute symmetric CLIP contrastive loss for B paired image and text embeddings. Matching pairs occupy the same row. Normalize each embedding vector x using

x^=xmax⁡(∥x∥2,10−12).\widehat{x}=\frac{x}{\max(\lVert x\rVert_2,10^{-12})}.x=max(∥x∥2​,10−12)x​.

Here, the norm is Euclidean; this normalization leaves a zero vector at zero. With image vector v, text vector t, and positive temperature τ\tauτ, define the similarity matrix

Sij=v^iTt^jτ.S_{ij}=\frac{\widehat v_i^{\mathsf T}\widehat t_j}{\tau}.Sij​=τviT​tj​​.

The symmetric loss is

L=−12B∑i=1B[log⁡eSii∑j=1BeSij+log⁡eSii∑j=1BeSji].L=-\frac{1}{2B}\sum_{i=1}^{B}\left[\log\frac{e^{S_{ii}}}{\sum_{j=1}^{B}e^{S_{ij}}}+\log\frac{e^{S_{ii}}}{\sum_{j=1}^{B}e^{S_{ji}}}\right].L=−2B1​i=1∑B​[log∑j=1B​eSij​eSii​​+log∑j=1B​eSji​eSii​​].

Indices i and j identify pairs; log is the natural logarithm. Each directional accuracy is the fraction of rows or columns whose highest similarity selects its matched diagonal entry. Ties select the lowest index.

Return a Python dictionary of PyTorch tensors: loss, image_to_text_accuracy, and text_to_image_accuracy are scalars; similarities has shape (B, B). All outputs preserve the embedding dtype and device.

Loading visualization...

Examples

Input: image_embeddings = [[1,0],[0,1]], text_embeddings = [[1,0],[0,1]], temperature = 1

Output: {"loss":0.313262,"similarities":[[1,0],[0,1]],"image_to_text_accuracy":1,"text_to_image_accuracy":1}

Explanation: Each diagonal cosine similarity exceeds its off-diagonal alternative by one.

Input: image_embeddings = [[3,4]], text_embeddings = [[6,8]], temperature = 0.5

Output: {"loss":0,"similarities":[[2]],"image_to_text_accuracy":1,"text_to_image_accuracy":1}

Input: image_embeddings = [[1,0],[1,1]], text_embeddings = [[1,0],[0,1]], temperature = 1

Output: {"loss":0.491157,"similarities":[[1,0],[0.707107,0.707107]],"image_to_text_accuracy":0.5,"text_to_image_accuracy":1}

Hint 1

torch.nn.functional.normalize supports a lower bound for the norm denominator.

Hint 2

torch.nn.functional.cross_entropy accepts a logit matrix and class-index targets.

Hint 3

Tensor.argmax returns the first index when maximum values are tied.

Requirements

  • Use PyTorch and preserve floating dtype and device.
  • Evaluate the contrastive loss stably for large logits.
  • Do not modify either embedding tensor.

Constraints

  • Image and text embeddings are finite rank-two PyTorch tensors with identical positive shape (batch, features).
  • Both tensors share floating dtype and device; editor inputs use float32.
  • temperature is a positive finite Python number.
  • Zero rows and noncontiguous inputs are valid.
Try Similar Problems
Implement the SigLIP Pairwise LossMediumAssign Multimodal RoPE CoordinatesMediumPatchify a Batch of ImagesEasyCompare Sequence and Token Length NormalizationMediumImplement the DPO LossMediumScore a KL-Regularized Policy BatchMediumCompute a Clipped GRPO SurrogateHardBuild an Assistant-Only SFT Loss MaskEasySigmoid Focal LossMediumGeneralized IoU LossMediumComplete IoU LossMediumDice LossEasy

Accepts: array

Accepts: array

Accepts: number

You must run your code first.