Temperature-Scaled Zero-Shot Confidence
Problem Statement
Zero-shot logits are cosine similarities in [-1, 1], so a raw softmax over them is nearly flat and useless as a confidence. Apply CLIP's logit scale (1/tau), then report the predicted class and its calibrated probability.
Background
CLIP multiplies cosine similarities by a learned logit_scale (equivalently divides by a temperature tau) before the softmax:
A small tau (large logit scale, ~100 at convergence) sharpens the distribution so the top class gets a meaningful probability. Return the argmax class and its probability. Use a numerically stable softmax (subtract the max).
Your Task
Implement:
def zero_shot_confidence(sims, tau):
Return a tuple (pred_index, probability) where probability is rounded to 4 decimals. Ties in the argmax go to the smallest index.
Input Format
- sims: list of cosine similarities (one per class).
- tau (float): temperature, tau > 0.
Output Format
- A tuple (int, float).
Sample
print(zero_shot_confidence([0.3, 0.2, 0.1], 0.01))
Output:
(0, 1.0)
Example
print(zero_shot_confidence([0.3, 0.2, 0.1], 0.01))
(0, 1.0)
- Scale the similarities: Divide each cosine similarity by the temperature to sharpen the distribution, resulting in logits .
- Stabilize for exponentiation: Subtract the maximum logit () from each value to prevent numerical overflow, yielding shifted values .
- Compute unnormalized probabilities: Apply the exponential function to the shifted values, giving , , and .
- Normalize to get probabilities: Divide each exponential value by their sum (), resulting in probabilities .
- Determine prediction and confidence: The maximum probability occurs at index with a value of ; rounding this to 4 decimal places yields .
- The final output is
(0, 1.0)
Constraints
1 <= len(sims) <= 10000,tau > 0.- Divide by
taubefore the softmax; use a stable softmax. - Argmax ties go to the smallest index; probability rounded to 4 decimals.