"""用二维教学向量观察点积、归一化与距离；这些数值不是文本模型输出。"""
import math

def dot(a, b):
    # zip 会忽略较长一侧的尾部，所以比较前显式检查维度。
    if len(a) != len(b):
        raise ValueError("向量维度不一致")
    return sum(x * y for x, y in zip(a, b))

def normalize(vector):
    length = math.sqrt(dot(vector, vector))
    if length == 0:
        raise ValueError("零向量没有可定义的余弦方向")
    return [value / length for value in vector]

query = [1.0, 0.0]
candidates = {"A": [0.8, 0.6], "B": [8.0, 6.0], "C": [0.0, 1.0]}
for name, vector in candidates.items():
    cosine = dot(normalize(query), normalize(vector))
    distance = math.sqrt(sum((x-y)**2 for x,y in zip(query, vector)))
    # A 与 B 的方向相同，余弦相同；原始点积与欧氏距离并不相同。
    print(name, {"dot": dot(query, vector), "cosine": cosine, "distance": distance})

# 简化的三候选对比目标：索引 0 是正例，另两个是负例。
# 固定 logits 只是展示损失，不执行梯度更新，不代表训练效果。
logits = [2.0, 1.0, 0.0]
weights = [math.exp(x - max(logits)) for x in logits]
p_positive = weights[0] / sum(weights)
print("正例概率与损失：", p_positive, -math.log(p_positive))
