手把手拆解:从零实现Llama3大模型(Python)(附代码)

从0实现llama3 这个链接实现了一个非常简洁的BPE分词器 简易分词器实现 1) 训练 tokenizer 词汇表并合并给定文本,2) 将文本编码为 token,3) 将 token 解码为文本。项目结构如下: Basic.py文件 通过BPE算法来合并最常见的字节对,从而构建词汇表并对文本进行编码和解码。 加载BPE分词器 Llama3定义了一些特殊token,如begin/end_of_text用来标记文本开始结束,reserved_special_token_n:预留标记用来完成特定任务。load_t 阅读详情

自Meta 发布了开源大模型 llama3 系列,在多个关键基准测试中优于业界 SOTA 模型,并在代码生成任务上全面领先。太强了!10大开源大模型!

此后,开发者们便开始了本地部署和实现,比如 llama3 的中文实现、llama3 的纯 NumPy 实现等。

近期,有位名为「Nishant Aklecha」的开发者发布了一个从零开始实现 llama3 的存储库,包括跨多个头的注意力矩阵乘法、位置编码和每个层在内都有非常详细的解释。项目初期就已在 GitHub 上收获了 1.5k 的 star,足可见其含金量!

从零开始实现 llama3

接下来项目作者手把手教你如何从头开始实现 llama3。

项目地址:

https://github.com/naklecha/llama3-from-scratch

首先从 Meta 提供的 llama3 模型文件中加载张量。

下载地址:

https://llama.meta.com/llama-downloads/

接着是分词器(tokenizer),作者表示没打算自己实现分词器,因而借用了 Andrej Karpathy 的实现方式:

分词器的实现链接:

https://github.com/karpathy/minbpe

from pathlib import Path``import tiktoken``from tiktoken.load import load_tiktoken_bpe``import torch``import json``import matplotlib.pyplot as plt``tokenizer_path = "Meta-Llama-3-8B/tokenizer.model"``special_tokens = [`            `"<|begin_of_text|>",`            `"<|end_of_text|>",`            `"<|reserved_special_token_0|>",`            `"<|reserved_special_token_1|>",`            `"<|reserved_special_token_2|>",`            `"<|reserved_special_token_3|>",`            `"<|start_header_id|>",`            `"<|end_header_id|>",`            `"<|reserved_special_token_4|>",`            `"<|eot_id|>",  # end of turn`        `] + [f"<|reserved_special_token_{i}|>" for i in range (5, 256 - 5)] mergeable_ranks = load_tiktoken_bpe (tokenizer_path) tokenizer = tiktoken.Encoding (`    `name=Path (tokenizer_path).name,`    `pat_str=r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p {L}\p {N}]?\p {L}+|\p {N}{1,3}| ?[^\s\p {L}\p {N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+",`    `mergeable_ranks=mergeable_ranks,`    `special_tokens={token: len (mergeable_ranks) + i for i, token in enumerate (special_tokens)},``)``tokenizer.decode (tokenizer.encode ("hello world!"))
'hello world!'

上述步骤完成后,就是读取模型文件了。由于该研究是从头开始实现 llama3,因此代码一次只读取一个张量文件。

model = torch.load ("Meta-Llama-3-8B/consolidated.00.pth")``print (json.dumps (list (model.keys ())[:20], indent=4))
[`    `"tok_embeddings.weight",`    `"layers.0.attention.wq.weight",`    `"layers.0.attention.wk.weight",`    `"layers.0.attention.wv.weight",`    `"layers.0.attention.wo.weight",`    `"layers.0.feed_forward.w1.weight",`    `"layers.0.feed_forward.w3.weight",`    `"layers.0.feed_forward.w2.weight",`    `"layers.0.attention_norm.weight",`    `"layers.0.ffn_norm.weight",`    `"layers.1.attention.wq.weight",`    `"layers.1.attention.wk.weight",`    `"layers.1.attention.wv.weight",`    `"layers.1.attention.wo.weight",`    `"layers.1.feed_forward.w1.weight",`    `"layers.1.feed_forward.w3.weight",`    `"layers.1.feed_forward.w2.weight",`    `"layers.1.attention_norm.weight",`    `"layers.1.ffn_norm.weight",`    `"layers.2.attention.wq.weight"``]
with open ("Meta-Llama-3-8B/params.json", "r") as f:`    `config = json.load (f)``config
{'dim': 4096,` `'n_layers': 32,` `'n_heads': 32,` `'n_kv_heads': 8,` `'vocab_size': 128256,` `'multiple_of': 1024,` `'ffn_dim_multiplier': 1.3,` `'norm_eps': 1e-05,` `'rope_theta': 500000.0}

项目作者使用以下配置来推断模型细节:

  • 模型有 32 个 transformer 层;

  • 每个多头注意力块有 32 个头。

dim = config ["dim"]``n_layers = config ["n_layers"]``n_heads = config ["n_heads"]``n_kv_heads = config ["n_kv_heads"]``vocab_size = config ["vocab_size"]``multiple_of = config ["multiple_of"]``ffn_dim_multiplier = config ["ffn_dim_multiplier"]``norm_eps = config ["norm_eps"]``rope_theta = torch.tensor (config ["rope_theta"])

接下来的操作是将文本装换为 token,这里作者使用的是 tiktoken 库(一个用于 OpenAI 模型的 BPE tokeniser)。

prompt = "the answer to the ultimate question of life, the universe, and everything is"``tokens = [128000] + tokenizer.encode (prompt)``print (tokens)``tokens = torch.tensor (tokens)``prompt_split_as_tokens = [tokenizer.decode ([token.item ()]) for token in tokens]``print (prompt_split_as_tokens)
[128000, 1820, 4320, 311, 279, 17139, 3488, 315, 2324, 11, 279, 15861, 11, 323, 4395, 374, 220]``['<|begin_of_text|>', 'the', ' answer', ' to', ' the', ' ultimate', ' question', ' of', ' life', ',', ' the', ' universe', ',', ' and', ' everything', ' is', ' ']

然后将 token 转换为嵌入。

embedding_layer = torch.nn.Embedding (vocab_size, dim)``embedding_layer.weight.data.copy_(model ["tok_embeddings.weight"])``token_embeddings_unnormalized = embedding_layer (tokens).to (torch.bfloat16)``token_embeddings_unnormalized.shape
torch.Size ([17, 4096])

将嵌入进行归一化。该研究使用均方根 RMS 算法进行归一化。不过,在这一步之后,张量形状不会改变,只是值进行了归一化。

# def rms_norm (tensor, norm_weights):``#     rms = (tensor.pow (2).mean (-1, keepdim=True) + norm_eps)**0.5``#     return tensor * (norm_weights /rms)``def rms_norm (tensor, norm_weights):`    `return (tensor * torch.rsqrt (tensor.pow (2).mean (-1, keepdim=True) + norm_eps)) * norm_weights

构建 transformer 第一层。完成上述准备后,接着是构建 transformer 第一层:从模型文件中访问 layer.0(即第一层),归一化后嵌入维度仍然是 [17x4096] 。

token_embeddings = rms_norm (token_embeddings_unnormalized, model ["layers.0.attention_norm.weight"])``token_embeddings.shape
torch.Size ([17, 4096])

从头开始实现注意力。加载第一层 transformer 的注意力头:

print (`    `model ["layers.0.attention.wq.weight"].shape,`    `model ["layers.0.attention.wk.weight"].shape,`    `model ["layers.0.attention.wv.weight"].shape,`    `model ["layers.0.attention.wo.weight"].shape``)``torch.Size ([4096, 4096]) torch.Size ([1024, 4096]) torch.Size ([1024, 4096]) torch.Size ([4096, 4096])

展开查询。展开来自多个注意力头的查询,得到的形状是 [32x128x4096],这里,32 是 llama3 中注意力头的数量,128 是查询向量的大小,4096 是 token 嵌入的大小。

q_layer0 = model ["layers.0.attention.wq.weight"]``head_dim = q_layer0.shape [0] //n_heads``q_layer0 = q_layer0.view (n_heads, head_dim, dim)``q_layer0.shape
torch.Size ([32, 128, 4096])

从头实现第一层的第一个头。访问第一层的查询权重矩阵,大小是 [128x4096]。

q_layer0_head0 = q_layer0 [0]``q_layer0_head0.shape
torch.Size ([128, 4096])

将查询权重与 token 嵌入相乘,从而得到 token 的查询,在这里你可以看到结果大小是 [17x128]。

q_per_token = torch.matmul (token_embeddings, q_layer0_head0.T)``q_per_token.shape
torch.Size ([17, 128])

定位编码。现在处于这样一个阶段,即对提示符中的每个 token 都有一个查询向量,但是考虑单个查询向量,我们不知道其提示符中的位置。作者使用了 RoPE(旋转位置嵌入)来解决。

q_per_token_split_into_pairs = q_per_token.float ().view (q_per_token.shape [0], -1, 2)``q_per_token_split_into_pairs.shape
torch.Size ([17, 64, 2])

在上面的步骤中,该研究将查询向量分成对,并对每对应用旋转角度移位。

使用复数点积来旋转向量。

zero_to_one_split_into_64_parts = torch.tensor (range (64))/64``zero_to_one_split_into_64_parts
tensor ([0.0000, 0.0156, 0.0312, 0.0469, 0.0625, 0.0781, 0.0938, 0.1094, 0.1250,`        `0.1406, 0.1562, 0.1719, 0.1875, 0.2031, 0.2188, 0.2344, 0.2500, 0.2656,`        `0.2812, 0.2969, 0.3125, 0.3281, 0.3438, 0.3594, 0.3750, 0.3906, 0.4062,`        `0.4219, 0.4375, 0.4531, 0.4688, 0.4844, 0.5000, 0.5156, 0.5312, 0.5469,`        `0.5625, 0.5781, 0.5938, 0.6094, 0.6250, 0.6406, 0.6562, 0.6719, 0.6875,`        `0.7031, 0.7188, 0.7344, 0.7500, 0.7656, 0.7812, 0.7969, 0.8125, 0.8281,`        `0.8438, 0.8594, 0.8750, 0.8906, 0.9062, 0.9219, 0.9375, 0.9531, 0.9688,`        `0.9844])
freqs = 1.0 / (rope_theta ** zero_to_one_split_into_64_parts)``freqs
tensor ([1.0000e+00, 8.1462e-01, 6.6360e-01, 5.4058e-01, 4.4037e-01, 3.5873e-01,`        `2.9223e-01, 2.3805e-01, 1.9392e-01, 1.5797e-01, 1.2869e-01, 1.0483e-01,`        `8.5397e-02, 6.9566e-02, 5.6670e-02, 4.6164e-02, 3.7606e-02, 3.0635e-02,`        `2.4955e-02, 2.0329e-02, 1.6560e-02, 1.3490e-02, 1.0990e-02, 8.9523e-03,`        `7.2927e-03, 5.9407e-03, 4.8394e-03, 3.9423e-03, 3.2114e-03, 2.6161e-03,`        `2.1311e-03, 1.7360e-03, 1.4142e-03, 1.1520e-03, 9.3847e-04, 7.6450e-04,`        `6.2277e-04, 5.0732e-04, 4.1327e-04, 3.3666e-04, 2.7425e-04, 2.2341e-04,`        `1.8199e-04, 1.4825e-04, 1.2077e-04, 9.8381e-05, 8.0143e-05, 6.5286e-05,`        `5.3183e-05, 4.3324e-05, 3.5292e-05, 2.8750e-05, 2.3420e-05, 1.9078e-05,`        `1.5542e-05, 1.2660e-05, 1.0313e-05, 8.4015e-06, 6.8440e-06, 5.5752e-06,`        `4.5417e-06, 3.6997e-06, 3.0139e-06, 2.4551e-06])
freqs_for_each_token = torch.outer (torch.arange (17), freqs)``freqs_cis = torch.polar (torch.ones_like (freqs_for_each_token), freqs_for_each_token)``freqs_cis.shape``# viewing tjhe third row of freqs_cis``value = freqs_cis [3]``plt.figure ()``for i, element in enumerate (value [:17]):`    `plt.plot ([0, element.real], [0, element.imag], color='blue', linewidth=1, label=f"Index: {i}")`    `plt.annotate (f"{i}", xy=(element.real, element.imag), color='red')`    `plt.xlabel ('Real')`    `plt.ylabel ('Imaginary')`    `plt.title ('Plot of one row of freqs_cis')`    `plt.show ()

现在每个 token 查询都有了复数。

q_per_token_as_complex_numbers = torch.view_as_complex (q_per_token_split_into_pairs)``q_per_token_as_complex_numbers.shape
torch.Size ([17, 64])
q_per_token_as_complex_numbers_rotated = q_per_token_as_complex_numbers * freqs_cis``q_per_token_as_complex_numbers_rotated.shape
torch.Size ([17, 64])

旋转后的向量。

q_per_token_split_into_pairs_rotated = torch.view_as_real (q_per_token_as_complex_numbers_rotated)``q_per_token_split_into_pairs_rotated.shape
torch.Size ([17, 64, 2])

现在有了一个新的查询向量 (旋转查询向量),形状为 [17x128],其中 17 是 token 数量,128 是查询向量的维度。

q_per_token_rotated = q_per_token_split_into_pairs_rotated.view (q_per_token.shape)``q_per_token_rotated.shape
torch.Size ([17, 128])

键(几乎和查询一样),键也生成维度为 128 的键向量。键的权重只有查询的 1/4,这是因为键的权重在 4 个头之间共享,以减少所需的计算量,键也会被旋转以添加位置信息,就像查询一样。

k_layer0 = model ["layers.0.attention.wk.weight"]``k_layer0 = k_layer0.view (n_kv_heads, k_layer0.shape [0] //n_kv_heads, dim)``k_layer0.shape
torch.Size ([8, 128, 4096])
k_layer0_head0 = k_layer0 [0]``k_layer0_head0.shape
torch.Size ([128, 4096])
k_per_token = torch.matmul (token_embeddings, k_layer0_head0.T)``k_per_token.shape
torch.Size ([17, 128])
k_per_token_split_into_pairs = k_per_token.float ().view (k_per_token.shape [0], -1, 2)``k_per_token_split_into_pairs.shape
torch.Size ([17, 64, 2])
k_per_token_as_complex_numbers = torch.view_as_complex (k_per_token_split_into_pairs)``k_per_token_as_complex_numbers.shape
torch.Size ([17, 64])
k_per_token_split_into_pairs_rotated = torch.view_as_real (k_per_token_as_complex_numbers * freqs_cis)``k_per_token_split_into_pairs_rotated.shape
torch.Size ([17, 64, 2])
k_per_token_rotated = k_per_token_split_into_pairs_rotated.view (k_per_token.shape)``k_per_token_rotated.shape
torch.Size ([17, 128])

每个 token 查询和键的旋转值如下,每个查询和键现在的形状都是 [17x128]。

接下来一步是将查询和键矩阵相乘。注意力得分矩阵 (qk_per_token) 的形状为 [17x17],其中 17 是提示中 token 的数量。

qk_per_token = torch.matmul (q_per_token_rotated, k_per_token_rotated.T)/(head_dim)**0.5``qk_per_token.shape
torch.Size ([17, 17])

现在必须掩蔽查询键分数。

在 llama3 的训练过程中,未来 token 的 qk 分数被掩蔽。这是因为在训练期间,只学习使用过去的 token 来预测未来的 token。因此在推理过程中,将未来的 token 标记为零。

def display_qk_heatmap (qk_per_token):`    `_, ax = plt.subplots ()`    `im = ax.imshow (qk_per_token.to (float).detach (), cmap='viridis')`    `ax.set_xticks (range (len (prompt_split_as_tokens)))`    `ax.set_yticks (range (len (prompt_split_as_tokens)))`    `ax.set_xticklabels (prompt_split_as_tokens)`    `ax.set_yticklabels (prompt_split_as_tokens)`    `ax.figure.colorbar (im, ax=ax)`    `display_qk_heatmap (qk_per_token)

mask = torch.full ((len (tokens), len (tokens)), float ("-inf"), device=tokens.device) mask = torch.triu (mask, diagonal=1) mask
tensor ([[0., -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf],`        `[0., 0., -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf],`        `[0., 0., 0., -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf],`        `[0., 0., 0., 0., -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf],`        `[0., 0., 0., 0., 0., -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf],`        `[0., 0., 0., 0., 0., 0., -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf],`        `[0., 0., 0., 0., 0., 0., 0., -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf],`        `[0., 0., 0., 0., 0., 0., 0., 0., -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf],`        `[0., 0., 0., 0., 0., 0., 0., 0., 0., -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf],`        `[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -inf, -inf, -inf, -inf, -inf, -inf, -inf],`        `[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -inf, -inf, -inf, -inf, -inf, -inf],`        `[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -inf, -inf, -inf, -inf, -inf],`        `[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -inf, -inf, -inf, -inf],`        `[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -inf, -inf, -inf],`        `[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -inf, -inf],`        `[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -inf],`        `[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
qk_per_token_after_masking = qk_per_token + mask``display_qk_heatmap (qk_per_token_after_masking)

qk_per_token_after_masking_after_softmax = torch.nn.functional.softmax (qk_per_token_after_masking, dim=1).to (torch.bfloat16) display_qk_heatmap (qk_per_token_after_masking_after_softmax)

值(几乎在注意力结束时)

这些分数 (0-1) 被用于确定每个 token 使用了多少值矩阵。

  • 就像键一样,值权重也在 4 个注意力头之间共享(以节省计算量)

  • 结果,下面的值权重矩阵形状为 [8x128x4096]

v_layer0 = model ["layers.0.attention.wv.weight"] v_layer0 = v_layer0.view (n_kv_heads, v_layer0.shape [0] //n_kv_heads, dim) v_layer0.shape
torch.Size ([8, 128, 4096])

第一层和第一个头的值权重矩阵如下所示。

v_layer0_head0 = v_layer0 [0] v_layer0_head0.shape
torch.Size ([128, 4096])

值向量如下图所示。

现在使用值权重来获取每个 token 的注意力值,其大小为 [17x128],其中 17 为提示中的 token 数,128 为每个 token 的值向量维数。

v_per_token = torch.matmul (token_embeddings, v_layer0_head0.T)v_per_token.shape
torch.Size ([17, 128])

注意力如下图所示。

与每个 token 的值相乘后得到的注意力向量的形状为 [17*128]。

qkv_attention = torch.matmul (qk_per_token_after_masking_after_softmax, v_per_token) qkv_attention.shape
torch.Size ([17, 128])

多头注意力与单头注意力如下图所示。

现在有了第一层和第一个头的注意力值。

接下来运行一个循环并执行与上面单元完全相同的数学运算,不过第一层中的每个头除外。

qkv_attention_store = []``for head in range (n_heads):`    `q_layer0_head = q_layer0 [head]`    `k_layer0_head = k_layer0 [head//4] # key weights are shared across 4 heads``v_layer0_head = v_layer0 [head//4] # value weights are shared across 4 heads``q_per_token = torch.matmul (token_embeddings, q_layer0_head.T)`    `k_per_token = torch.matmul (token_embeddings, k_layer0_head.T)`    `v_per_token = torch.matmul (token_embeddings, v_layer0_head.T)``   ``   `    `q_per_token_split_into_pairs = q_per_token.float ().view (q_per_token.shape [0], -1, 2)`    `q_per_token_as_complex_numbers = torch.view_as_complex (q_per_token_split_into_pairs)`    `q_per_token_split_into_pairs_rotated = torch.view_as_real (q_per_token_as_complex_numbers * freqs_cis [:len (tokens)])`    `q_per_token_rotated = q_per_token_split_into_pairs_rotated.view (q_per_token.shape)``   ``   `    `k_per_token_split_into_pairs = k_per_token.float ().view (k_per_token.shape [0], -1, 2)`    `k_per_token_as_complex_numbers = torch.view_as_complex (k_per_token_split_into_pairs)`    `k_per_token_split_into_pairs_rotated = torch.view_as_real (k_per_token_as_complex_numbers * freqs_cis [:len (tokens)])`    `k_per_token_rotated = k_per_token_split_into_pairs_rotated.view (k_per_token.shape)``   ``   `    `qk_per_token = torch.matmul (q_per_token_rotated, k_per_token_rotated.T)/(128)**0.5``mask = torch.full ((len (tokens), len (tokens)), float ("-inf"), device=tokens.device)`    `mask = torch.triu (mask, diagonal=1)`    `qk_per_token_after_masking = qk_per_token + mask``qk_per_token_after_masking_after_softmax = torch.nn.functional.softmax (qk_per_token_after_masking, dim=1).to (torch.bfloat16)`    `qkv_attention = torch.matmul (qk_per_token_after_masking_after_softmax, v_per_token)`    `qkv_attention = torch.matmul (qk_per_token_after_masking_after_softmax, v_per_token)`    `qkv_attention_store.append (qkv_attention)``len (qkv_attention_store)
32

现在第一层上的所有 32 个头都有了 qkv_attention 矩阵,并在快结束的时候将所有注意力分数合并为一个大小为 [17x4096] 的大矩阵。

stacked_qkv_attention = torch.cat (qkv_attention_store, dim=-1) stacked_qkv_attention.shape
torch.Size ([17, 4096])

权重矩阵是最后的步骤之一。

第 0 层注意力要做的最后一件事是,对以下的权重矩阵进行乘法操作。

w_layer0 = model ["layers.0.attention.wo.weight"] w_layer0.shape
torch.Size ([4096, 4096])

这是一个简单的线性层,所以只做矩阵乘法(matmul)。

embedding_delta = torch.matmul (stacked_qkv_attention, w_layer0.T) embedding_delta.shape
torch.Size ([17, 4096])

现在,注意力之后的嵌入值有了变化,并应该被添加到原始 token 嵌入中。

embedding_after_edit = token_embeddings_unnormalized + embedding_delta``embedding_after_edit.shape
torch.Size ([17, 4096])

归一化并在嵌入 delta 过程中运行一个前馈神经网络。

embedding_after_edit_normalized = rms_norm (embedding_after_edit, model ["layers.0.ffn_norm.weight"]) embedding_after_edit_normalized.shape
torch.Size ([17, 4096])

加载 ff 权重,并实现前馈网络。

llama3 使用 SwiGLU前馈网络,该网络架构非常擅长在模型需要时添加非线性。当前,在 LLMs 中使用这一前馈网络是非常标准的做法。

w1 = model ["layers.0.feed_forward.w1.weight"] w2 = model ["layers.0.feed_forward.w2.weight"] w3 = model ["layers.0.feed_forward.w3.weight"] output_after_feedforward = torch.matmul (torch.functional.F.silu (torch.matmul (embedding_after_edit_normalized, w1.T)) * torch.matmul (embedding_after_edit_normalized, w3.T), w2.T) output_after_feedforward.shape
torch.Size ([17, 4096])

现在终于在第一层之后为每个 token 提供了新的编辑后的嵌入,并且在完成之前只剩下 31 层需要处理(one for loop away)。

你可以想象这个编辑后的嵌入拥有在第一层上所有查询的信息。现在每一层将在所问问题上编码越来越复杂的查询,直到得到的嵌入了解所需的下一个 token 的一切。

layer_0_embedding = embedding_after_edit+output_after_feedforward``layer_0_embedding.shape
torch.Size ([17, 4096])

之前为每一层做的所有事情,都可以一次性完成。

final_embedding = token_embeddings_unnormalized``for layer in range (n_layers):`    `qkv_attention_store = []`    `layer_embedding_norm = rms_norm (final_embedding, model [f"layers.{layer}.attention_norm.weight"])`    `q_layer = model [f"layers.{layer}.attention.wq.weight"]`    `q_layer = q_layer.view (n_heads, q_layer.shape [0] //n_heads, dim)`    `k_layer = model [f"layers.{layer}.attention.wk.weight"]`    `k_layer = k_layer.view (n_kv_heads, k_layer.shape [0] //n_kv_heads, dim)`    `v_layer = model [f"layers.{layer}.attention.wv.weight"]`    `v_layer = v_layer.view (n_kv_heads, v_layer.shape [0] //n_kv_heads, dim)`    `w_layer = model [f"layers.{layer}.attention.wo.weight"]`    `for head in range (n_heads):`        `q_layer_head = q_layer [head]`        `k_layer_head = k_layer [head//4]`        `v_layer_head = v_layer [head//4]`        `q_per_token = torch.matmul (layer_embedding_norm, q_layer_head.T)`        `k_per_token = torch.matmul (layer_embedding_norm, k_layer_head.T)`        `v_per_token = torch.matmul (layer_embedding_norm, v_layer_head.T)`        `q_per_token_split_into_pairs = q_per_token.float ().view (q_per_token.shape [0], -1, 2)`        `q_per_token_as_complex_numbers = torch.view_as_complex (q_per_token_split_into_pairs)`        `q_per_token_split_into_pairs_rotated = torch.view_as_real (q_per_token_as_complex_numbers * freqs_cis)`        `q_per_token_rotated = q_per_token_split_into_pairs_rotated.view (q_per_token.shape)`        `k_per_token_split_into_pairs = k_per_token.float ().view (k_per_token.shape [0], -1, 2)`        `k_per_token_as_complex_numbers = torch.view_as_complex (k_per_token_split_into_pairs)`        `k_per_token_split_into_pairs_rotated = torch.view_as_real (k_per_token_as_complex_numbers * freqs_cis)`        `k_per_token_rotated = k_per_token_split_into_pairs_rotated.view (k_per_token.shape)`        `qk_per_token = torch.matmul (q_per_token_rotated, k_per_token_rotated.T)/(128)**0.5`        `mask = torch.full ((len (token_embeddings_unnormalized), len (token_embeddings_unnormalized)), float ("-inf"))`        `mask = torch.triu (mask, diagonal=1)`        `qk_per_token_after_masking = qk_per_token + mask`        `qk_per_token_after_masking_after_softmax = torch.nn.functional.softmax (qk_per_token_after_masking, dim=1).to (torch.bfloat16)`        `qkv_attention = torch.matmul (qk_per_token_after_masking_after_softmax, v_per_token)`        `qkv_attention_store.append (qkv_attention)``   ``   `    `stacked_qkv_attention = torch.cat (qkv_attention_store, dim=-1)`    `w_layer = model [f"layers.{layer}.attention.wo.weight"]`    `embedding_delta = torch.matmul (stacked_qkv_attention, w_layer.T)`    `embedding_after_edit = final_embedding + embedding_delta`    `embedding_after_edit_normalized = rms_norm (embedding_after_edit, model [f"layers.{layer}.ffn_norm.weight"])`    `w1 = model [f"layers.{layer}.feed_forward.w1.weight"]`    `w2 = model [f"layers.{layer}.feed_forward.w2.weight"]`    `w3 = model [f"layers.{layer}.feed_forward.w3.weight"]`    `output_after_feedforward = torch.matmul (torch.functional.F.silu (torch.matmul (embedding_after_edit_normalized, w1.T)) * torch.matmul (embedding_after_edit_normalized, w3.T), w2.T)`    `final_embedding = embedding_after_edit+output_after_feedforward

现在有了最终的嵌入,即该模型对下一个 token 的最佳猜测。该嵌入的形状与常见的 token 嵌入 [17x4096] 相同,其中 17 为 token 数,4096 为嵌入维数。

final_embedding = rms_norm (final_embedding, model ["norm.weight"]) final_embedding.shape
torch.Size ([17, 4096])

将该嵌入解码为 token 值。

使用该输入解码器将最终的嵌入转换为一个 token。

model ["output.weight"].shape
torch.Size ([128256, 4096])

使用最后 token 的嵌入来预测下一个值。在示例中,42 是「生命、宇宙和万物终极问题的答案是什么」的答案,根据《银河系漫游指南》一书,大多数现代 LLMs 都会回答 42,应该验证了整个代码。

logits = torch.matmul (final_embedding [-1], model ["output.weight"].T) logits.shape
torch.Size ([128256])

模型预测 token 数 2983 为下一个 token,这是 42 的 token 数吗?以下是最后的代码单元。

next_token = torch.argmax (logits, dim=-1) next_token
tensor (2983)

最后,启动。

tokenizer.decode ([next_token.item ()])
'42'

如何学习大模型 AI ?

由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。

但是具体到个人,只能说是:

“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。

这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

在这里插入图片描述

第一阶段(10天):初阶应用

该阶段让大家对大模型 AI有一个最前沿的认识,对大模型 AI 的理解超过 95% 的人,可以在相关讨论时发表高级、不跟风、又接地气的见解,别人只会和 AI 聊天,而你能调教 AI,并能用代码将大模型和业务衔接。

  • 大模型 AI 能干什么?
  • 大模型是怎样获得「智能」的?
  • 用好 AI 的核心心法
  • 大模型应用业务架构
  • 大模型应用技术架构
  • 代码示例:向 GPT-3.5 灌入新知识
  • 提示工程的意义和核心思想
  • Prompt 典型构成
  • 指令调优方法论
  • 思维链和思维树
  • Prompt 攻击和防范
  • …

第二阶段(30天):高阶应用

该阶段我们正式进入大模型 AI 进阶实战学习,学会构造私有知识库,扩展 AI 的能力。快速开发一个完整的基于 agent 对话机器人。掌握功能最强的大模型开发框架,抓住最新的技术进展,适合 Python 和 JavaScript 程序员。

  • 为什么要做 RAG
  • 搭建一个简单的 ChatPDF
  • 检索的基础概念
  • 什么是向量表示(Embeddings)
  • 向量数据库与向量检索
  • 基于向量检索的 RAG
  • 搭建 RAG 系统的扩展知识
  • 混合检索与 RAG-Fusion 简介
  • 向量模型本地部署
  • …

第三阶段(30天):模型训练

恭喜你,如果学到这里,你基本可以找到一份大模型 AI相关的工作,自己也能训练 GPT 了!通过微调,训练自己的垂直大模型,能独立训练开源多模态大模型,掌握更多技术方案。

到此为止,大概2个月的时间。你已经成为了一名“AI小子”。那么你还想往下探索吗?

  • 为什么要做 RAG
  • 什么是模型
  • 什么是模型训练
  • 求解器 & 损失函数简介
  • 小实验2:手写一个简单的神经网络并训练它
  • 什么是训练/预训练/微调/轻量化微调
  • Transformer结构简介
  • 轻量化微调
  • 实验数据集的构建
  • …

第四阶段(20天):商业闭环

对全球大模型从性能、吞吐量、成本等方面有一定的认知,可以在云端和本地等多种环境下部署大模型,找到适合自己的项目/创业方向,做一名被 AI 武装的产品经理。

  • 硬件选型
  • 带你了解全球大模型
  • 使用国产大模型服务
  • 搭建 OpenAI 代理
  • 热身:基于阿里云 PAI 部署 Stable Diffusion
  • 在本地计算机运行大模型
  • 大模型的私有化部署
  • 基于 vLLM 部署大模型
  • 案例:如何优雅地在阿里云私有部署开源大模型
  • 部署一套开源 LLM 项目
  • 内容安全
  • 互联网信息服务算法备案
  • …

学习是一个过程,只要学习就会有挑战。天道酬勤,你越努力,就会成为越优秀的自己。

如果你能在15天内完成所有的任务,那你堪称天才。然而,如果你能完成 60-70% 的内容,你就已经开始具备成为一名大模型 AI 的正确特征了。

这份完整版的大模型 AI 学习资料已经上传优快云,朋友们如果需要可以微信扫描下方优快云官方认证二维码免费领取【保证100%免费】

在这里插入图片描述

Vicuna-13B本地部署实战:llama.cpp+FastAPI轻量级生产方案 大语言模型(LLM)本地化部署正成为企业AI落地的关键路径,其核心在于平衡推理性能、硬件兼容性与工程可控性。基于llama.cpp的GGUF量化技术可将13B级模型压缩至5GB以内,实现CPU端稳定推理;FastAPI与Uvicorn组合则提供高并发、自文档化的RESTful接口能力。该方案规避了PyTorch显存瓶颈、Ollama黑盒封装及Flask GIL限制,特别适合知识库问答、智能客服、技术文档摘要等中低延迟业务场景。本文聚焦Vicuna-13B在消费级设备(如M1 Mac)上的端到端部署,涵盖4- 阅读详情

相关推荐

手写Llama 3原理:500行Python拆解RMSNorm、RoPE与GQA

Transformer架构是现代大语言模型的基石,其核心组件包括归一化层、位置编码和注意力机制。RMSNorm通过根均方缩放替代传统LayerNorm,在保持数值稳定性的同时降低计算开销;RoPE(旋转位置编码)以复数乘法实现相对位置建模,赋予模型天然的序列感知能力;Grouped-Query Attention(GQA)则在显存效率与推理质量间取得关键平衡,显著缓解KV缓存压力。这些技术并非黑箱,而是可被逐行实现、单步调试的确定性计算流程。本文基于NumPy纯手工实现Llama 3核心模块,聚焦原理落地细

weixin_33937778的博客 343

Karpathy大神点赞,从零实现LLaMa3项目爆火,已获1.5k star

一个月前,Meta 发布了开源大模型 llama3 系列,在多个关键基准测试中优于业界 SOTA 模型,并在代码生成任务上全面领先。此后,开发者们便开始了本地部署和实现,比如 llama3 的中文实现、llama3 的纯 NumPy 实现等。十几个小时前,有位名为「Nishant Aklecha」的开发者发布了一个从零开始实现 llama3 的存储库,包括跨多个头的注意力矩阵乘法、位置编码和每个层...

深度学习技术前沿 421

Vicuna-13B本地部署实战:llama.cpp量化推理与GGUF优化指南

大语言模型本地部署是AI工程化落地的关键环节,其核心在于平衡显存占用、推理精度与运行效率。Vicuna-13B作为主流开源对话模型,具备较强中文理解能力,但原生PyTorch加载易触发CUDA内存溢出;而llama.cpp通过GGUF格式封装、细粒度量化(如Q4_K_M)及C++底层优化,显著提升稳定性与可控性。GGUF不仅存储权重,更固化RoPE参数、词表映射等运行时元数据,保障跨平台行为一致;量化则需在精度与资源间权衡,非越低越好。本文聚焦显存受限环境(如单卡RTX 3090),详解从编译、模型验证、P

cuixie2370的博客 552

Karpathy称赞,从零实现LLaMa3项目爆火,半天1.5k star

一个月前,Meta 发布了开源大模型 llama3 系列,在多个关键基准测试中优于业界 SOTA 模型,并在代码生成任务上全面领先。此后,开发者们便开始了本地部署和实现,比如、llama3 的纯 NumPy 实现等。十几个小时前,有位名为「Nishant Aklecha」的开发者发布了一个从零开始实现 llama3 的存储库,包括跨多个头的注意力矩阵乘法、位置编码和每个层在内都有非常详细的解释。

weixin_59191169的博客 913

Code Llama技术深度解析:开源代码大模型的范式迁移与工程落地

代码大模型正从‘智能补全’迈向‘系统级代码理解’,其核心在于结构化建模编程语言的语法、语义与运行时契约。Code Llama 作为Llama架构在代码领域的深度演进,依托3T高质量代码语料、RoPE位置编码扩展至16K上下文、以及代码专属约束解码(CSCD)等关键技术,显著提升类型推断、跨文件依赖推理与多语言FFI理解能力。它不仅支撑IDE实时辅助,更成为企业构建私有代码知识图谱、CI/CD智能守门员与安全漏洞泛化识别的可信基座。本文聚焦其底层设计逻辑、量化部署实践与生产级扩展路径,为自托管代码智能基建提供

weixin_34242509的博客 651

Code Llama深度解析:开源代码大模型的工程范式革命

代码大模型正从‘通用文本生成’迈向‘可理解、可验证、可嵌入开发流程’的新阶段。其核心原理在于对代码语义结构(如缩进、类型注解、函数边界)的原生建模,结合高质量开源语料与结构化位置编码,显著提升生成代码的工程合规性与上下文一致性。技术价值体现在本地化部署能力、多语言协同生成、低资源微调支持等工程友好特性上,广泛应用于IDE智能补全、PR自动化审查、遗留系统现代化改造等真实研发场景。本文聚焦Code Llama这一标志性开源模型,深入剖析其词表设计、训练数据哲学与系统级适配机制。

426

llama3 中文 源代码解析

🤗。

具身机器人和通用AI 2545

从零实现LLaMA2:Happy-LLM大模型实战教程与PyTorch训练指南

如果你正在寻找一个能让你从零开始,真正动手搭建和训练一个大语言模型的教程,而不是仅仅停留在调用API的层面,那么今天要聊的这个项目,你绝对不能错过。它叫 Happy-LLM ,由国内知名的开源组织 Datawhale 发起,在 GitHub 上已经收获了超过 8 万颗星标,这个数字本身就说明了它在开发者社区中的分量和认可度。 这个项目的核心目标非常直接: 授人以渔 。它不是一个简单的“调包”指南,而是一个系统性的、从 NLP 基础到 Transformer 架构,再到亲手实现 LLaMA2 模型并进行预训练

weixin_34416649的博客 412

LLaMa-1/2/3 原理+源码——拆解 (KV-Cache, RoPE, RMSNorm, GQA, SwiGLU)

LLama原理拆解 (KV-Cache, Rotary Positional Embedding, RMS Norm, Grouped Query Attention, SwiGLU)

ZhengrongYue的博客 1万+

开源大模型本地部署实战:从Llama 3到生产级API服务

大语言模型(LLM)作为当前人工智能的核心技术,其部署方式直接关系到应用的性能、成本与可控性。从技术原理上看,LLM通过海量参数实现复杂的语言理解和生成,而部署方式则决定了其在实际工程中的可用性。开源模型的价值在于提供了从模型权重到推理框架的完整技术栈,使开发者能够实现私有化部署,从而在数据安全、成本控制和深度定制方面获得优势。在应用场景上,对于金融、医疗等敏感行业,以及需要高频调用和定制化需求的业务,开源模型的本地部署成为关键技术选择。本文以Meta Llama 3为例,结合**Ollama**和**ll

weixin_34408624的博客 393

从零实现 LLaMA 架构:一步步构建轻量级大语言模型

本文从 LLaMA 的核心设计出发,拆解并实现了一个轻量级的 LLaMA-like 模型,覆盖了 RMSNorm、SwiGLU、RoPE、因果自注意力等关键组件。大模型看似复杂,但本质是 “简单组件的有序组合”—— 掌握这些核心设计,就能理解大模型的底层逻辑,为后续的模型训练、优化和部署打下基础。训练模型:用小数据集(如 WikiText)训练模型,观察 Loss 的下降趋势;扩展参数:将调至 4096、num_layers调至 32,实现原版 LLaMA 7B 的架构;

2501_92464201的博客 1139

【实战】AI大模型入门:Python调用大模型(新手零门槛,附完整代码+避坑指南

如今AI大模型已渗透到开发、办公、创作等各个场景,从ChatGPT、通义千问到本地部署的Llama 3、Qwen,大模型的应用门槛越来越低。而Python作为AI开发的首选语言,凭借简洁的语法和丰富的第三方库,让我们无需深入研究模型训练,就能快速调用大模型能力。

2602_95518972的博客 829

SAP CO-PA获利分析避坑指南:从数据采集到报表设计的5个关键步骤

本文深入解析了SAP CO-PA获利分析模块从数据采集到报表设计的完整流程。文章重点剖析了数据源头、特征派生、获利段设计等关键步骤,并对比了基于账户与基于成本核算两种模式的差异,特别强调了在S/4HANA时代的选择与常见陷阱,旨在帮助企业构建可靠、可执行的盈利分析体系。

flink9streamer的博客 826

llama的Qwen3.5大模型单GPU高效部署与股票筛选应用|附代码教程

Qwen3.5是阿里推出的最新大模型系列,在推理、编程和多模态任务上都有出色表现。独立基准测试显示,Qwen3.5-397B-A17B在LiveCodeBench、AIME26等测试中得分很高,不少类别上超过了主流模型,推理吞吐量也比前代提升明显。本地运行Qwen3.5是一种强大的方式,可以在保持一切私密和完全在你控制之下的同时,访问前沿规模的模型。在本文中,模型托管在单个H200 GPU虚拟机上,使用SSH端口转发从本地机器安全访问,并通过优化的llama.cpp OpenAI兼容端点提供服务。

大数据部落 1109

LightGBM处理类别特征和缺失值有多省心?一个真实业务数据案例带你上手

本文通过真实电商数据案例,详细解析了LightGBM如何高效处理类别特征和缺失值。相比传统方法,LightGBM仅需一行代码即可自动处理高基数类别特征和缺失值,大幅提升模型训练效率和预测准确度,特别适合业务场景中的脏数据处理。

weixin_30689307的博客 460

代码大模型选型指南:StarCoder与Code Llama核心差异解析

代码大模型(Code LLM)是一类专为理解、生成与调试源代码而优化的大语言模型,其核心价值在于将自然语言指令精准映射为可执行、符合规范、具备工程鲁棒性的程序逻辑。不同于通用大模型,Code LLM需在语法严谨性、类型感知、API调用惯性及安全意识等维度达到专业级水平。其技术原理涵盖代码原生训练(如StarCoder基于The Stack的纯代码预训练与FIM范式)与通用基座专业化跃迁(如Code Llama基于Llama 2的长上下文微调与指令对齐)。关键价值体现在可验证的工程落地能力——支持IDE实时补

weixin_30856725的博客 411

对工时评估的思考:当AI颠覆了coding效率

在AI时代,“人日”作为软件工时度量衡已然失效。开发的价值核心正从“编码实现”转向“深度思考”与“精准沟通”——即如何将人类的模糊需求精确地传达给AI。当最有价值的“思想工作”变得最难量化时,传统的项目管理范式随之动摇。我们必须超越对过程的算计,开始探索衡量思想、沟通与业务价值的新标尺。

架构师刘7的博客 1017

别光看理论了!手把手用Python代码拆解LLaMA 3.2的Embedding层(附完整权重提取脚本)

本文通过Python代码实战拆解LLaMA 3.2的Embedding层,详细展示了从权重提取到向量可视化的全过程。文章包含完整的权重提取脚本,帮助开发者深入理解LLM中Embedding的工作原理,并提供了性能优化技巧,适用于自然语言处理研究和应用开发。

weixin_30687051的博客 413

当R语言遇见MaxENT:参数优化的艺术与自动化调参实践

本文探讨了R语言与MaxENT在生态位建模中的结合应用,重点介绍了参数优化与自动化调参的实践方法。通过caret与ENMeval工具链,研究人员可以高效处理多物种、多环境变量的大规模分析任务,提升模型性能与工作效率。文章还涵盖了从数据准备到结果可视化的全流程,为生态学家提供了实用的技术指导。

corn8的博客 455

基于STM32设计的智能水母投喂器(华为云IOT)_170

本项目利用STM32单片机控制各种传感器和水泵等设备,能够自动检测和调整水温和水质等参数,自动换水,自动供氧等等,充分满足了水母的养殖要求和需要。同时,根据水母喜欢的光环境,添加了RGB氛围灯,以及可以手动控制的喂食器等功能,提升了水母养殖的便利性和趣味性。

8808

Llama 3、Qwen2、Mistral 开源大模型选型实战指南

开源大模型已从参数竞赛迈入工程化落地阶段,Llama 3、Qwen2、Mistral 代表三种典型技术范式:Llama 3 以可预测性与生态兼容性构建工业级基线,Qwen2 聚焦中文语义精度与国产化适配实现全栈优化,Mistral 则通过 MoE 架构与推理共生设计持续突破小模型性能边界。三者并非简单性能对比,而是分别在稳定性、本地化效率与高并发低延迟场景中形成不可替代的技术价值。面向金融合规、政务等保、制造业离线部署、实时音视频处理等真实业务负载,选型需回归硬件栈能力、数据语种特征与团队工程成熟度。本文基

weixin_30681121的博客 454

YOLO26涨点改进 | 全网独家创新!注意力改进篇 | CVPR 2025 | 引入RALA秩增强线性注意力模块,含多种创新改进,助力YOLO26适合目标检测、图像分割、图像分类有效涨点

🔥本文给大家介绍使用RALA模块改进YOLO26可以显著提升其性能,尤其在复杂场景和小物体检测中。通过增强线性注意力机制的矩阵秩,RALA改善了模型对空间信息的建模能力,提升了特征的多样性和全局信息的融合,进而提高了检测精度。同时,RALA保持了线性复杂度,避免了Softmax注意力的高计算成本,使YOLO26在实时检测任务中既能保持高效计算,又能提高检测精度,尤其是在小物体和遮挡物体的检测中表现突出。🔥欢迎订阅我的专栏、带你学习使用最新-最前沿-独家YOLO26创新改进!

Ai缝合怪、助力小伙伴高效发论文 143

本地运行大模型:本地通过python运行AI大语言模型LLaMa2

Llama 全称 large language model, Meta AI 公司2023年发布的开源AI大型语言模型,参数7B~65B。最新版本为Llama 3。

huang9604的博客 442

7、复杂分布式水文模型的两阶段代理参数校准框架

本文提出了一种针对复杂分布式水文模型的两阶段代理参数校准框架,旨在解决可变入渗能力模型(VIC)在参数校准过程中计算成本高、耗时长的问题。该框架结合AdaBoost与反向传播神经网络(BPNN)构建高精度代理模型,并引入ε-NSGA II多目标优化算法加速搜索最优参数集。通过在兰江流域和湘江流域的实验验证,该方法在校准效率上提升了约20倍,同时保持了高模拟精度(NSE接近1,Bias接近0)。框架采用两阶段设计:第一阶段(SM-I)快速筛选关键参数范围,第二阶段(SM-II)进行高精度预测,显著减少了无效计

apple5的专栏 86

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

上一篇: 初学者怎么入门大语言模型开发?
下一篇: 我花了2元,15分钟,零基础入门了Llama3的微调。
Python_金钱豹
博客等级 码龄5年 1万+粉丝 2835原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值