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

实算注意力、缓存和一层解码器

PYTHONCPython 3.12.14、PyTorch 2.10.0,CPU 单线程、自编小矩阵及五词元词表。decoder_lab.py
decoder_lab.py269 行

"""Inspect Transformer components and train a small CPU decoder on synthetic tokens."""
import math
import sys

import torch
from torch import nn
from torch.nn import functional as F

from attention_lab import exercise as basic_attention
from lab_tools import run_exercise


def close(left, right):
    return torch.allclose(left, right, atol=1e-6, rtol=1e-6)


def number_row(row):
    return [round(float(value), 6) for value in row]


def position_encoding(length, width):
    even_columns = torch.arange(0, width, 2, dtype=torch.float64)
    angle = torch.arange(length, dtype=torch.float64)[:, None] / (10_000 ** (even_columns / width))
    encoding = torch.empty((length, width), dtype=torch.float64)
    encoding[:, ::2] = angle.sin()
    encoding[:, 1::2] = angle[:, :width // 2].cos()
    return encoding


def rotate_pairs(vector, angle):
    paired = vector.reshape(-1, 2)
    x, y = paired.unbind(-1)
    return torch.stack((x * angle.cos() - y * angle.sin(),
                        x * angle.sin() + y * angle.cos()), dim=-1).flatten()


def online_attention(scores, values, tile_size):
    """Evaluate one attention row with online max, denominator and weighted sum."""
    largest = -math.inf
    total = 0.0
    weighted = torch.zeros_like(values[0])
    for offset in range(0, len(scores), tile_size):
        score_tile = scores[offset:offset + tile_size]
        value_tile = values[offset:offset + tile_size]
        next_largest = max(largest, float(score_tile.max()))
        old_scale = math.exp(largest - next_largest)
        weights = (score_tile - next_largest).exp()
        total = total * old_scale + float(weights.sum())
        weighted = weighted * old_scale + weights @ value_tile
        largest = next_largest
    return weighted / total


def recurrence_and_heads(checks):
    sequence = torch.tensor([[0.25], [0.75], [-0.5]], dtype=torch.float64)
    rnn = nn.RNN(1, 1, bias=False, batch_first=True, dtype=torch.float64)
    with torch.no_grad():
        rnn.weight_ih_l0.fill_(2)
        rnn.weight_hh_l0.fill_(0.5)
    expected, hidden = [], 0.0
    for row in sequence:
        hidden = math.tanh(2 * float(row[0]) + 0.5 * hidden)
        expected.append(round(hidden, 6))
    output, _ = rnn(sequence.unsqueeze(0))
    reverse, _ = rnn(sequence.flip(0).unsqueeze(0))
    checks.expect("transformer_rnn", sequence.flatten().tolist(),
                  "Compare a real recurrent layer with scalar recurrence and then reverse token order",
                  [expected, True], [number_row(output.flatten().detach()), not close(output, reverse.flip(1))])

    x = torch.tensor([[1.0, 0.0, 2.0, -1.0], [0.0, 1.0, -1.0, 2.0]])
    identity = torch.eye(4)
    mha = nn.MultiheadAttention(4, 2, batch_first=True, bias=False)
    with torch.no_grad():
        mha.in_proj_weight.copy_(torch.cat((identity * 2, identity, identity * 3)))
        mha.out_proj.weight.copy_(torch.diag(torch.tensor([1., 2., 3., 4.])))
        actual, observed_weights = mha(x[None], x[None], x[None], average_attn_weights=False)
    q, k, v = [data.reshape(2, 2, 2).transpose(0, 1) for data in (2*x, x, 3*x)]
    weights = (q @ k.transpose(-2, -1) / math.sqrt(2)).softmax(dim=-1)
    joined = (weights @ v).transpose(0, 1).reshape(2, 4)
    expected = joined @ mha.out_proj.weight.T
    checks.expect("transformer_projected_heads", x.tolist(),
                  "Compare two projected heads, concatenation and a distinct output projection",
                  [[1, 2, 4], [1, 2, 2, 2], True, True, True],
                  [list(actual.shape), list(observed_weights.shape), close(actual[0], expected),
                   close(observed_weights[0], weights), not close(weights[0], weights[1])])
    try:
        nn.MultiheadAttention(5, 2)
    except (AssertionError, ValueError):
        invalid_width = True
    else:
        invalid_width = False
    checks.expect("transformer_head_divisibility", [5, 2], "Create a standard multihead layer with indivisible width",
                  True, invalid_width)
    tokens = torch.tensor([[[[1.0,0.0],[0.0,1.0]]]])
    alternate = tokens.clone()
    alternate[0,0,1] = torch.tensor([3.0,2.0])
    original_bi = F.scaled_dot_product_attention(tokens, tokens, tokens)
    changed_bi = F.scaled_dot_product_attention(alternate, alternate, alternate)
    original_causal = F.scaled_dot_product_attention(tokens, tokens, tokens, is_causal=True)
    changed_causal = F.scaled_dot_product_attention(alternate, alternate, alternate, is_causal=True)
    cross = F.scaled_dot_product_attention(tokens[:,:,:1], alternate, alternate)
    checks.expect("transformer_architecture_masks", [tokens.flatten().tolist(), alternate.flatten().tolist()],
                  "Change only the future token and compare bidirectional, causal and source-attending queries",
                  [True, True, [1,1,1,2], True],
                  [not close(original_bi[:,:,:1], changed_bi[:,:,:1]), close(original_causal[:,:,:1], changed_causal[:,:,:1]),
                   list(cross.shape), close(cross, changed_bi[:,:,:1])])



def positions_and_layers(checks):
    encoding = position_encoding(3, 5)
    angles = torch.tensor([1., 10_000 ** (-2/5), 10_000 ** (-4/5)], dtype=torch.float64)
    expected = [math.sin(1), math.cos(1), math.sin(float(angles[1])),
                math.cos(float(angles[1])), math.sin(float(angles[2]))]
    checks.expect("transformer_sinusoidal", [3, 5], "Check the first two rows and the unpaired fifth sine column",
                  [[0., 1., 0., 1., 0.], [round(value, 6) for value in expected]],
                  [number_row(encoding[0]), number_row(encoding[1])])

    q = torch.tensor([1., 2., 3., -1.], dtype=torch.float64)
    k = torch.tensor([3., 0., 1., 2.], dtype=torch.float64)
    frequencies = torch.tensor([0.3, 0.07], dtype=torch.float64)
    baseline = rotate_pairs(q, 2 * frequencies) @ rotate_pairs(k, 5 * frequencies)
    shifted = rotate_pairs(q, 8 * frequencies) @ rotate_pairs(k, 11 * frequencies)
    reference = q @ rotate_pairs(k, 3 * frequencies)
    checks.expect("transformer_rope", [[2,5],[8,11]], "Shift both positions by six and compare relative dot products",
                  [True, True, True], [close(baseline, shifted), close(baseline, reference),
                                       close(rotate_pairs(q, 2 * frequencies).norm(), q.norm())])

    score = torch.zeros(3, dtype=torch.float64)
    biased = score - 0.5 * torch.arange(2, -1, -1, dtype=torch.float64)
    checks.expect("transformer_alibi", [0,0,0], "Apply distance bias before softmax at the third position",
                  [[-1., -0.5, 0.], [0.186324, 0.307196, 0.50648]],
                  [number_row(biased), number_row(biased.softmax(dim=0))])

    gate = torch.tensor([2., -1.], dtype=torch.float64)
    up = torch.tensor([3., 4.], dtype=torch.float64)
    out = torch.tensor([2., -1.], dtype=torch.float64)
    relu_output = F.relu(gate) @ out
    swiglu_output = (F.silu(gate) * up) @ out
    glu_output = (gate.sigmoid() * up) @ out
    expected_swi = 12/(1+math.exp(-2)) + 4/(1+math.exp(1))
    checks.expect("transformer_ffn_gates", [gate.tolist(), up.tolist(), out.tolist()],
                  "Compare ReLU, Swish-gated and sigmoid-gated intermediate features through the output projection",
                  [4., round(expected_swi, 6), True],
                  [float(relu_output), round(float(swiglu_output), 6), not close(swiglu_output, glu_output)])

    x = torch.tensor([1., 3.], dtype=torch.float64)
    gamma, beta = torch.tensor([2., 3.], dtype=x.dtype), torch.tensor([4., 5.], dtype=x.dtype)
    eps = 0.25
    norm = F.layer_norm(x, (2,), gamma, beta, eps)
    constant = F.layer_norm(torch.ones_like(x), (2,), gamma, beta, eps)
    rms = F.rms_norm(x, (2,), gamma, eps)
    zero = F.rms_norm(torch.zeros_like(x), (2,), gamma, eps)
    checks.expect("transformer_norms", [x.tolist(),gamma.tolist(),beta.tolist(),eps],
                  "Compare LayerNorm and RMSNorm with affine terms and check constant and zero rows",
                  [[round(4-2/math.sqrt(1.25),6), round(5+3/math.sqrt(1.25),6)], [4.,5.],
                   [round(2/math.sqrt(5.25),6), round(9/math.sqrt(5.25),6)], [0.,0.]],
                  [number_row(norm), number_row(constant), number_row(rms), number_row(zero)])
    f = lambda values: values * torch.tensor([2., 4.], dtype=x.dtype)
    pre = x + f(F.layer_norm(x, (2,)))
    post = F.layer_norm(x + f(x), (2,))
    checks.expect("transformer_norm_order", x.tolist(), "Apply residual and normalization in both orders",
                  [True, True], [not close(pre, post), abs(float(post.mean())) < 1e-6])


class Decoder(nn.Module):
    """One causal decoder layer with a full-prefix and cached inference path."""
    def __init__(self, vocabulary=5, width=8, heads=2, max_tokens=12):
        super().__init__()
        self.heads = heads
        self.embedding = nn.Embedding(vocabulary, width)
        self.position = nn.Embedding(max_tokens, width)
        self.attention_norm = nn.LayerNorm(width)
        self.qkv = nn.Linear(width, 3 * width, bias=False)
        self.merge = nn.Linear(width, width, bias=False)
        self.ffn_norm = nn.LayerNorm(width)
        self.ffn = nn.Sequential(nn.Linear(width, 16), nn.ReLU(), nn.Linear(16, width))
        self.output_norm = nn.LayerNorm(width)
        self.logits = nn.Linear(width, vocabulary)

    def forward(self, tokens, cache=None):
        batch, steps = tokens.shape
        past = 0 if cache is None else cache[0].size(-2)
        positions = torch.arange(past, past + steps, device=tokens.device)
        x = self.embedding(tokens) + self.position(positions)
        q, k, v = self.qkv(self.attention_norm(x)).chunk(3, dim=-1)
        q, k, v = (data.reshape(batch, steps, self.heads, -1).transpose(1, 2) for data in (q, k, v))
        if cache is not None:
            k = torch.cat((cache[0], k), dim=-2)
            v = torch.cat((cache[1], v), dim=-2)
        mask = torch.arange(past + steps, device=tokens.device)[None, :] <= positions[:, None]
        attended = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
        x = x + self.merge(attended.transpose(1, 2).reshape_as(x))
        x = x + self.ffn(self.ffn_norm(x))
        return self.logits(self.output_norm(x)), (k, v)


def caches_and_training(checks):
    scores = torch.tensor([1000., 999., 1002., 998., 1001.], dtype=torch.float64)
    values = torch.tensor([[1.,2.],[3.,5.],[1.,6.],[0.,-1.],[-2.,5.]], dtype=torch.float64)
    dense = scores.softmax(0) @ values
    checks.expect("transformer_online_softmax", [scores.tolist(), [1,2,5]],
                  "Compare online block rescaling to a materialized dense row on the CPU",
                  [True, True, True], [close(dense, online_attention(scores, values, n)) for n in (1,2,5)])
    # Per layer, each token has a K vector and a V vector per KV head.
    bytes_per_token = 2 * 32 * 128 * 2
    cache_sizes = [bytes_per_token * 32 * 4096 // 2**20 // reduction for reduction in (1,4,32)]
    checks.expect("transformer_cache_memory", [1,32,4096,128,2,[32,8,1]],
                  "Count only keys and values for 32, 8 and 1 KV heads",
                  [2048, 512, 64], cache_sizes)

    tokens = torch.tensor([[0, 1, 2, 3]])
    model = Decoder().eval()
    with torch.no_grad():
        full, _ = model(tokens)
        prefix, cache = model(tokens[:, :2])
        parts = [prefix]
        lengths = [cache[0].size(-2)]
        for i in range(2, tokens.size(1)):
            logits, cache = model(tokens[:, i:i+1], cache)
            parts.append(logits)
            lengths.append(cache[0].size(-2))
        edited, _ = model(torch.tensor([[0, 1, 3, 4]]))
    checks.expect("transformer_kv_equivalence", tokens.tolist(),
                  "Prefill two tokens, decode two more and compare logits to a full causal pass",
                  [True, [2,3,4], [1,2,4,4], True],
                  [close(full,torch.cat(parts,dim=1)), lengths,list(cache[0].shape),close(full[:,:2],edited[:,:2])])

    model.train()
    optimizer = torch.optim.Adam(model.parameters(), lr=0.04)
    inputs = torch.tensor([[0,1,2,3],[1,2,3,4],[2,3,4,0],[3,4,0,1],[4,0,1,2]])
    labels = (inputs + 1) % 5
    def loss(logits):
        return F.cross_entropy(logits.flatten(0,1), labels.flatten())
    with torch.no_grad():
        initial = float(loss(model(inputs)[0]))
    for _ in range(40):
        optimizer.zero_grad()
        objective = loss(model(inputs)[0])
        objective.backward()
        optimizer.step()
    model.eval()
    with torch.no_grad():
        predictions, _ = model(inputs)
        final = float(loss(predictions))
        next_probabilities = predictions[0, -1].softmax(dim=-1)
    checks.expect("transformer_tiny_training", [40, inputs.tolist()],
                  "Train with shifted labels and check loss reduction, argmax, probabilities and vocabulary size",
                  [True, True, 5, 4, 1.0], [final < initial/4, bool(torch.equal(predictions.argmax(-1), labels)),
                     next_probabilities.numel(), int(next_probabilities.argmax()),
                     round(float(next_probabilities.sum()),6)])


def exercise(checks, workspace):
    torch.set_num_threads(1)
    torch.manual_seed(31)
    version = [sys.version.split()[0], torch.__version__.split("+")[0]]
    checks.expect("transformer_cpu_version", "CPU", "Identify the isolated runtime",
                  ["3.12.14", "2.10.0"], version)
    basic_attention(checks, workspace)
    recurrence_and_heads(checks)
    positions_and_layers(checks)
    caches_and_training(checks)


if __name__ == "__main__":
    run_exercise(exercise)
本例需在 CPython 3.12.14、PyTorch 2.10.0,CPU 单线程、自编小矩阵及五词元词表。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12.14、PyTorch 2.10.0,CPU 单线程、自编小矩阵及五词元词表。

入口文件:projects/ai-transformer/decoder_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 decoder_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12.14、PyTorch 2.10.0,CPU 单线程、自编小矩阵及五词元词表。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI(人工智能)

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

下载课程关联工程包:AI(人工智能)

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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