蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

从向量的角度到注意力权重

PYTHONWindows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。dot-numerics.py
dot-numerics.py108 行
"""Exercise real-vector dot products, projections, and CPU attention."""
import json
import math
import platform
import sys

import numpy as np

cases = []


def check(name, inputs, expected, actual):
    assert expected == actual, (name, expected, actual)
    cases.append(dict(name=name,input=inputs,expected=expected,actual=actual,passed=True))


def angle_degrees(a,b):
    magnitude = np.linalg.norm(a)*np.linalg.norm(b)
    if magnitude == 0:
        return None
    return float(np.degrees(np.arccos(np.clip((a@b)/magnitude,-1,1))))


def project(a,b):
    square = b@b
    if square == 0:
        return None
    return ((a@b)/square)*b


a,b,c = np.array([3,1,2]),np.array([-1,4,2]),np.array([2,-2,1])
check("dot_three_methods", [a.tolist(),b.tolist()], [5,5,5],
      [int(np.dot(a,b)),int(a@b),sum(int(x)*int(y) for x,y in zip(a,b,strict=True))])
check("dot_commutative", [a.tolist(),b.tolist()], [5,5], [int(a@b),int(b@a)])
check("dot_distributive", [a.tolist(),b.tolist(),c.tolist()], [11,11], [int(a@(b+c)),int(a@b+a@c)])
check("dot_self_squared_norm", a.tolist(), [14,14], [int(a@a),round(float(np.linalg.norm(a)**2),12)])
try:
    np.ones(2) @ np.ones(3)
except ValueError:
    check("matmul_rejects_different_vector_lengths", [[2],[3]], "ValueError", "ValueError")
else:
    raise AssertionError("incompatible dot product unexpectedly succeeded")
axis = np.array([2,0])
partners = [np.array(x) for x in ([1,1],[0,2],[-1,1],[-2,0],[2,0],[0,0])]
check("dot_sign_and_angle_cases", [axis.tolist(),[p.tolist() for p in partners]],
      [[2,0,-2,-4,4,0],[45,90,135,180,0,None]],
      [[int(axis@p) for p in partners],
       [round(value,6) if (value:=angle_degrees(axis,p)) is not None else None for p in partners]])
check("projection_signed_component", [[-2,3],[2,0]], [[-2,0],-2,0],
      [project(np.array([-2,3]),axis).tolist(), float(np.array([-2,3])@axis/np.linalg.norm(axis)),
       float((np.array([-2,3])-project(np.array([-2,3]),axis))@axis)])
check("projection_zero_axis_undefined", [a.tolist(),[0,0,0]], None, project(a,np.zeros(3)))
check("algebra_matches_geometry", [a.tolist(),b.tolist()], 5.0,
      round(float(np.linalg.norm(a)*np.linalg.norm(b)*math.cos(math.radians(angle_degrees(a,b)))),10))
old_a,old_b = np.array([2,3,1]),np.array([4,1,2])
check("recalculate_historical_values", [old_a.tolist(),old_b.tolist()], [13,0.7582,40.7],
      [int(old_a@old_b), round(float((old_a@old_b)/(np.linalg.norm(old_a)*np.linalg.norm(old_b))),4),
       round(angle_degrees(old_a,old_b),1)])
check("quantity_price_contraction", [[2,3,1],[3,5,4]], 25,
      int(np.array([2,3,1])@np.array([3,5,4])))
check("constant_force_work", [[4,0],[[3,0],[0,3],[-3,0]]], [12,0,-12],
      [int(np.array([4,0])@np.array(displacement)) for displacement in ([3,0],[0,3],[-3,0])])
users=np.array([[2,1],[-1,2]])
items=np.array([[1,3],[2,0],[1,-1]])
check("recommendation_score_matrix", [users.tolist(),items.tolist()], [[5,4,1],[5,-2,-3]], (users@items.T).tolist())

q=np.array([[1.,0.],[0.,1.]])
k=np.array([[1.,0.],[0.,1.],[1.,1.]])
v=np.array([[2.,0.],[0.,4.],[2.,4.]])
logits=q@k.T/math.sqrt(k.shape[-1])
weights=np.exp(logits-logits.max(axis=-1,keepdims=True))
weights=weights/weights.sum(axis=-1,keepdims=True)
share=1/(2+math.exp(-1/math.sqrt(2)))
remainder=1-2*share
reference=np.array([[4*share,4*(remainder+share)],[2*(remainder+share),8*share]])
check("attention_shape_and_normalization", [list(q.shape),list(k.shape),list(v.shape)],
      [[2,3],[1,1]], [list(weights.shape),np.round(weights.sum(axis=-1),12).tolist()])
check("attention_weighted_values", [q.tolist(),k.tolist(),v.tolist()],
      reference.round(10).tolist(), (weights@v).round(10).tolist())

version = None
if "--torch" in sys.argv:
    import torch
    import torch.nn.functional as F

    torch.set_num_threads(1)
    version = str(torch.__version__)
    linear = torch.nn.Linear(784,256)
    with torch.no_grad():
        linear.weight.zero_()
        linear.bias.zero_()
        linear.weight[:2,:2] = torch.tensor([[2.,-1.],[1.,3.]])
        linear.bias[:2] = torch.tensor([1.,-2.])
        features = torch.zeros((2,784))
        features[0,:2] = torch.tensor([4.,2.])
        outputs = linear(features)
        check("linear_real_cpu_forward", [[2,784],[256,784],[4,2]], [[2,256],[[7,8],[1,-2]]],
              [list(outputs.shape),outputs[:,:2].tolist()])
    tensors=[torch.from_numpy(x).unsqueeze(0).unsqueeze(0) for x in (q,k,v)]
    output = F.scaled_dot_product_attention(*tensors,dropout_p=0)
    check("torch_attention_matches_numpy", [list(x.shape) for x in tensors],
          [[1,1,2,2],reference.round(10).tolist()], [list(output.shape),output[0,0].numpy().round(10).tolist()])
    mask = torch.tensor([[True,False,False],[False,True,False]])
    masked=F.scaled_dot_product_attention(*tensors,attn_mask=mask,dropout_p=0)
    check("attention_mask_controls_allowed_key", mask.tolist(), [[2,0],[0,4]], masked[0,0].tolist())
print(json.dumps(dict(version=platform.python_version(),library_versions={"numpy":np.__version__,"torch":version},
                      cases=cases),ensure_ascii=False))
本例需在 Windows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。

入口文件:projects/ai-math-dot-lab/dot-numerics.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 dot-numerics.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a51.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习