LLM大模型基础入门:从头开始编写LLM代码

LLM大模型基础入门系列之:(二)大模型如何工作 读到这里,我相信您需要一段时间才能消化所有信息,特别是对于那些刚接触LLM的人来说。现在我相信我们已经在基本概念和背景信息方面涵盖了足够的基础。现在是我们开始准备构建我们自己的大语言模型的时候了。理论已经讲完了,我们将在下一篇文章中讨论Transformers 架构的关键组成部分。技术交流加入「AIGCmagic社区」群聊,一起交流讨论,涉及 AI视频、AI绘画、Sora技术拆解、数字人、多模态、大模型、传统深度学习、自动驾驶等多个不同方向,可私信或添加微信号:【m_aigc2022。 阅读详情

引 言

在本文中,我们将从头开始实现一个类 GPT 的 transformer。

让我们开始吧。

准备环境

pip install numpy requests torch tiktoken matplotlib pandas

import os
import requests
import pandas as pd
import matplotlib.pyplot as plt
import math
import tiktoken
import torch
import torch.nn as nn

设置超参数

超参数是模型的外部配置,无法在训练期间从数据中学习。它们在训练过程开始之前设置,在控制训练算法的行为和训练模型的性能方面发挥着至关重要的作用。

# Hyperparameters
batch_size = 4  # How many batches per training step
context_length = 16  # Length of the token chunk each batch
d_model = 64  # The vector size of the token embeddings
num_layers = 8  # Number of transformer blocks
num_heads = 4  # Number of heads in Multi-head attention 
learning_rate = 1e-3  # 0.001
dropout = 0.1 # Dropout rate
max_iters = 5000  # Total of training iterations
eval_interval = 50  # How often to evaluate the model
eval_iters = 20  # How many iterations to average the loss over when evaluating the model
device = 'cuda' if torch.cuda.is_available() else 'cpu'  # Instead of using the cpu, we'll use the GPU if it's available.

TORCH_SEED = 1337
torch.manual_seed(TORCH_SEED)

准备数据集

正如在示例中一样,我们将使用一个小数据集进行训练。该数据集是包含销售教科书的文本文件。将使用文本文件来训练可以生成销售文本的语言模型。

# download a sample txt file from https://huggingface.co/datasets/goendalf666/sales-textbook_for_convincing_and_selling/raw/main/sales_textbook.txt
if not os.path.exists('sales_textbook.txt'):
    url = 'https://huggingface.co/datasets/goendalf666/sales-textbook_for_convincing_and_selling/raw/main/sales_textbook.txt'
    with open('sales_textbook.txt', 'w') as f:
        f.write(requests.get(url).text)

with open('sales_textbook.txt', 'r', encoding='utf-8') as f:
    text = f.read()

第 1 步:Tokenization

我们将使用 tiktoken(https://github.com/openai/tiktoken) 库对数据集进行标记。该库是一个快速且轻量级的分词器,可用于将文本分词为 Tokens。

# Using TikToken to tokenize the source text
encoding = tiktoken.get_encoding("cl100k_base")
tokenized_text = encoding.encode(text) # size of tokenized source text is 77,919
vocab_size = len(set(tokenized_text)) # size of vocabulary is 3,771
max_token_value = max(tokenized_text)

print(f"Tokenized text size: {len(tokenized_text)}")
print(f"Vocabulary size: {vocab_size}")
print(f"The maximum value in the tokenized text is: {max_token_value}")

打印输出:

Tokenized text size: 77919
Vocabulary size: 3771
The maximum value in the tokenized text is: 100069

第 2 步:词嵌入

把数据集分成训练集和验证集。训练集将用于训练模型,验证集将用于评估模型的性能。

# Split train and validation
split_idx = int(len(tokenized_text) * 0.8)
train_data = tokenized_text[:split_idx]
val_data = tokenized_text[split_idx:]

# Prepare data for training batch
# Prepare data for training batch
data = train_data
idxs = torch.randint(low=0, high=len(data) - context_length, size=(batch_size,))
x_batch = torch.stack([data[idx:idx + context_length] for idx in idxs])
y_batch = torch.stack([data[idx + 1:idx + context_length + 1] for idx in idxs])
print(x_batch.shape, x_batch.shape)

打印输出(训练输入x和y的形状):

torch.Size([4, 16]) torch.Size([4, 16])

第 3 步:位置编码

将使用一个简单的嵌入层将输入标记转换为向量。

# Define Token Embedding look-up table
token_embedding_lookup_table = nn.Embedding(max_token_value, d_model)

# Get X and Y embedding
x = token_embedding_lookup_table(x_batch.data)
y = token_embedding_lookup_table(y_batch.data)

现在,输入 x 和 y 的形状都是(batch_size、context_length、d_model)。

# Get x and y embedding
x = token_embedding_lookup_table(x_batch.data) # [4, 16, 64] [batch_size, context_length, d_model]
y = token_embedding_lookup_table(y_batch.data)

应用位置嵌入

正如最初的“Attention is All You Need”论文中所述,我们将使用正弦和余弦生成位置嵌入表,然后将这些位置信息添加到输入嵌入标记中。

# Define Position Encoding look-up table
position_encoding_lookup_table = torch.zeros(context_length, d_model) # initial with zeros with shape (context_length, d_model)
position = torch.arange(0, context_length, dtype=torch.float).unsqueeze(1)
# apply the sine & cosine
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
position_encoding_lookup_table[:, 0::2] = torch.sin(position * div_term)
position_encoding_lookup_table[:, 1::2] = torch.cos(position * div_term)
position_encoding_lookup_table = position_encoding_lookup_table.unsqueeze(0).expand(batch_size, -1, -1) #add batch to the first dimension

print("Position Encoding Look-up Table: ", position_encoding_lookup_table.shape)

打印输出:

Position Encoding Look-up Table:  torch.Size([4, 16, 64])

然后,将位置编码添加到输入嵌入向量中。

# Add positional encoding into the input embedding vector
input_embedding_x = x + position_encoding_lookup_table # [4, 16, 64] [batch_size, context_length, d_model]
input_embedding_y = y + position_encoding_lookup_table

X = input_embedding_x

x_plot = input_embedding_x[0].detach().cpu().numpy()
print("Final Input Embedding of x: \n", pd.DataFrame(x_plot))

现在,得到 X 的最终输入嵌入,这是要输入到 transformer 块中的值:

Final Input Embedding of x:
           0         1         2         3         4         5         6         7         8         9   ...        54        55        56        57        58        59        60        61        62        63
0  -1.782388  1.200549 -0.177262  0.278616 -1.322919  0.929397 -0.178307  1.453488 -0.216367 -2.049190  ... -0.009743  2.694576 -0.592321  1.235002  1.137691  1.076938 -1.583359  1.994682 -0.411284  2.365598
1   0.434183  2.051380  0.642167  1.294858  0.287493 -0.132648 -0.388530  0.106470  0.515283  1.686583  ...  0.423079  0.564006 -1.514647  0.263115 -2.233931  1.759137  2.413690 -0.372896  0.512504  2.831246
2   0.180579 -0.714483  0.983105 -0.944209  1.182870 -0.100558  0.807144  0.232830 -0.455422  2.246022  ...  0.056277  0.913973 -0.200273  0.688581  1.302482  2.202587 -0.980815 -0.181238  0.747766  1.742957
3  -0.249654 -3.228277 -0.017824  0.492374  0.992460 -1.281102  0.811163  0.678884  0.251492  0.319295  ...  1.329760  1.259970 -0.345209  1.030813  0.629613  1.289158  0.586766  0.970829  1.487210  0.858970
4   1.533710 -1.794257 -0.115366 -2.216147  0.143978 -2.549789  0.285271  0.908505 -1.371307  1.000596  ... -0.171948  1.476006 -0.411271  2.187133  0.580001  1.330921 -0.996333  3.353865  0.216231 -0.570538
5  -2.187219 -0.290028 -0.914946 -0.614617 -0.033163 -1.060609  2.265111 -1.180711  1.237476  0.817889  ...  1.869089  0.720627 -1.679796  1.405375  0.399367  0.725817 -0.047124 -0.977291  0.013971  0.819522
6  -1.015749  1.862600  0.785039  2.425240  0.613279 -1.725359  1.288837 -1.810941  2.514978  0.433844  ...  0.408046  1.537934 -0.192739  0.709489  0.535088 -0.347714 -2.239857 -0.033674  0.192698 -0.136556
7  -0.446721  1.136845  0.336349  1.287424  1.515973  0.814479  0.233362 -1.706994 -0.438097 -0.674278  ...  0.697751  0.913269 -0.332155 -0.149376  0.140298  2.597988  0.219866  1.489297  1.089043 -1.265491
8  -0.190227 -0.968500 -1.648937  2.915030 -3.227971 -0.739308 -0.485671 -0.869817 -0.153695 -1.206717  ...  1.403767  0.636459  0.094945 -0.747135  0.495720  0.164661 -0.610816  0.730676  0.587971  2.341617
9  -0.224795 -0.326915 -0.362390  1.489488 -0.389251 -0.362224  0.913598 -2.051510  0.778566 -0.696349  ...  0.394737  1.314234 -0.124517  1.888481  0.689187  0.396996  1.056659  0.785319  1.079981 -0.194575
10 -0.692015 -1.732475  2.214933 -1.991298 -0.398353  1.266861 -1.057534 -1.157881 -0.801310 -0.614316  ... -1.901223 -0.854748  0.163998  0.173750 -1.058628  1.532371 -0.257311  1.359694  1.033851  0.677123
11  0.713966 -0.232073  2.291222  0.224710 -1.199412  0.022869 -1.532023 -0.403545 -0.262371 -1.097961  ...  1.827974  0.126189  1.134699  0.425639 -1.347956  0.086310 -0.774953  1.218501 -1.761807  0.117464
12 -0.468460  1.830461  1.335220 -1.410995  0.069466  1.672440 -1.680814 -1.598549  0.521277 -1.871883  ... -1.775825 -0.046493  0.723062  1.785805  1.166462  2.608919  1.078712  2.193650  1.377550  1.002753
13  1.436239  0.494849  1.781795  0.060173  0.538164  1.890070 -2.363284  2.231389 -1.082167  0.040986  ... -0.764243 -1.155260  0.084449  1.592648  0.105955  1.080390 -1.063937  0.691866 -0.906071  0.383779
14 -0.113100  0.519679  0.316672  0.299135  3.229518  1.496113 -0.325615  0.203938 -2.198124 -0.356190  ...  0.700703  0.913256 -0.329941 -0.149384  0.141958  2.597984  0.221110  1.489295  1.089976 -1.265493
15  0.301521  0.997564 -0.672755 -1.215677  0.949777  0.474997 -0.279164  1.144048 -1.059472  0.068650  ...  0.796498 -1.032138  0.977697  0.790623  0.725540  1.646803  1.253047  0.296801  0.798098  2.022164

[16 rows x 64 columns]

注意:y 嵌入向量将与 x 的形状相同。

第 4 步:Transformer Block

4.1 多头注意力概述

让我们回到多头注意力图。
在这里插入图片描述

有了输入嵌入 X,我们可以开始实现多头注意力模块。实现多头注意力模块需要一系列步骤。让我们一一编码。

4.2 准备Q、K、V

# Prepare Query, Key, Value for Multi-head Attention

query = key = value = X # [4, 16, 64] [batch_size, context_length, d_model]

# Define Query, Key, Value weight matrices
Wq = nn.Linear(d_model, d_model)
Wk = nn.Linear(d_model, d_model)
Wv = nn.Linear(d_model, d_model)

Q = Wq(query) #[4, 16, 64]
Q = Q.view(batch_size, -1, num_heads, d_model // num_heads)  #[4, 16, 4, 16]

K = Wk(key) #[4, 16, 64]
K = K.view(batch_size, -1, num_heads, d_model // num_heads)  #[4, 16, 4, 16]

V = Wv(value) #[4, 16, 64]
V = V.view(batch_size, -1, num_heads, d_model // num_heads)  #[4, 16, 4, 16]

然后,将 Q、K、V 重塑为 [batch_size, num_heads, context_length, head_size] 以进行进一步计算。

# Transpose q,k,v from [batch_size, context_length, num_heads, head_size] to [batch_size, num_heads, context_length, head_size]
# The reason is that treat each batch with "num_heads" as its first dimension.
Q = Q.transpose(1, 2) # [4, 4, 16, 16]
K = K.transpose(1, 2) # [4, 4, 16, 16]
V = V.transpose(1, 2) # [4, 4, 16, 16]

4.3 计算QK^T注意力

通过使用 torch.matmul 函数可以非常轻松地完成此操作。

# Calculate the attention score betwee Q and K^T
attention_score = torch.matmul(Q, K.transpose(-2, -1))

4.4 Scale

# Then Scale the attention score by the square root of the head size
attention_score = attention_score / math.sqrt(d_model // num_heads)

实际上可以将 4.3 和 4.4 重写为一行:

attention_score = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_model // num_heads) # [4, 4, 16, 16] #[4, 4, 16, 16] [batch_size, num_heads, context_length, context_length]
print(pd.DataFrame(attention_score[0][0].detach().cpu().numpy()))

打印输出(一批次的一个序列):

           0         1         2         3         4         5         6         7         8         9         10        11        12        13        14        15
0   0.105279 -0.365092 -0.339839 -0.650558 -0.464043 -0.531401  0.437939 -0.650732 -0.616331 -0.429000 -0.332607  0.080401  0.000111 -0.601670 -0.783942  0.147967
1  -0.302636  0.525435  0.863502 -0.218539  0.600691 -0.413970  0.408111  0.765074 -0.376257  0.233526  0.915393 -0.263153  0.683832  0.430964  0.802033  0.281169
2   0.201820  0.156336 -0.245585  0.101653  0.228243 -0.565197  0.589193 -0.579525 -0.080071  0.078848 -0.471447  0.481268 -0.129725 -0.123364 -0.963065 -0.582126
3   0.517998 -0.303064  0.484515 -0.399551 -0.004528 -0.028223 -0.602194  0.107085 -0.504462  0.017590  0.592893 -0.750240  0.022489 -0.014217 -0.038678  0.484633
4   0.519200  0.322036  0.328027 -0.031755  0.006269  0.133609 -0.095071 -0.252013  0.096449 -0.268063 -0.306129 -0.045432 -0.027766 -0.163095 -0.338737  0.712901
5  -0.635913  0.137114  0.083046  0.234778 -0.668992 -0.366838 -0.613126  0.245075 -0.042131  0.221872  0.806992 -0.279996  0.046113  0.646270  0.284564  0.478298
6  -0.287777 -0.841604 -0.128455 -0.566180  0.079559 -0.530863 -0.082675  0.072495 -0.264806 -0.229649  0.269325 -0.185602 -0.366693 -0.321176 -0.130587  0.416121
7  -0.798519 -0.905525  0.317880 -0.176577  0.751465 -0.564863  1.014724 -0.068284 -0.527703  0.118972  0.085287 -0.102589 -0.640548  0.376717 -0.120097  0.164074
8   0.141614 -0.022169  0.152088 -0.519404 -0.069152 -0.880496 -0.229767 -0.849347 -0.539544 -0.510258 -0.246146 -0.266640 -0.086958 -0.577571 -1.191547  0.050306
9  -0.097493  0.860376  0.073501  0.150553 -0.651579 -0.376676 -0.691368  0.315606  0.135982  0.292198  0.774460 -0.131879  0.626085  0.452120  0.153703  0.082386
10 -0.469827  0.302545 -0.015767 -0.175387 -0.049927 -0.706852  0.511237  0.043908 -0.492887 -0.168435 -0.167744  0.016956  0.141400 -0.102674 -0.072396 -0.261558
11 -0.335474 -0.399539 -0.093901 -0.682290  0.312682 -0.310319  0.344753  0.017465 -0.364808 -0.262316 -0.282589 -0.239767  0.008904 -0.621042 -0.261246 -0.214888
12 -1.757631 -0.967825 -0.516159 -0.246766 -0.352132 -0.780370 -0.262975 -0.793605 -0.238561 -0.374695 -0.132526 -0.126956 -0.524015 -0.194315 -1.046538 -0.402560
13  0.550975  0.313643 -0.074468  0.519995 -0.149188 -0.565922  0.199527 -0.738029  0.142203 -0.164007 -0.494203  0.570010 -0.579608 -0.198923 -0.869503 -0.120218
14 -0.616347 -0.812240  0.245260  0.167278  0.913596 -0.493119  1.139083 -0.300623 -0.399155  0.200648 -0.114634  0.147219 -0.829207  0.363519 -0.325846  0.026840
15 -0.145391  0.514632 -0.296119 -0.038103 -0.187110 -0.634636  0.509902 -0.338267 -0.231534 -0.007304 -0.432799  0.339123  0.248173 -0.242426 -0.595925 -0.442379

4.5 Mask

# Apply Mask to attention scores
attention_score = attention_score.masked_fill(torch.triu(torch.ones(attention_score.shape[-2:]), diagonal=1).bool(), float('-inf')) #[4, 4, 16, 16] [batch_size, num_heads, context_length, context_length]
print(pd.DataFrame(attention_score[0][0].detach().cpu().numpy()))

打印输出(一批次的一个序列):

           0         1         2         3         4         5         6         7         8         9         10        11        12        13        14        15
0   0.105279      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf
1  -0.302636  0.525435      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf
2   0.201820  0.156336 -0.245585      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf
3   0.517998 -0.303064  0.484515 -0.399551      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf
4   0.519200  0.322036  0.328027 -0.031755  0.006269      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf
5  -0.635913  0.137114  0.083046  0.234778 -0.668992 -0.366838      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf
6  -0.287777 -0.841604 -0.128455 -0.566180  0.079559 -0.530863 -0.082675      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf
7  -0.798519 -0.905525  0.317880 -0.176577  0.751465 -0.564863  1.014724 -0.068284      -inf      -inf      -inf      -inf      -inf      -inf      -inf      -inf
8   0.141614 -0.022169  0.152088 -0.519404 -0.069152 -0.880496 -0.229767 -0.849347 -0.539544      -inf      -inf      -inf      -inf      -inf      -inf      -inf
9  -0.097493  0.860376  0.073501  0.150553 -0.651579 -0.376676 -0.691368  0.315606  0.135982  0.292198      -inf      -inf      -inf      -inf      -inf      -inf
10 -0.469827  0.302545 -0.015767 -0.175387 -0.049927 -0.706852  0.511237  0.043908 -0.492887 -0.168435 -0.167744      -inf      -inf      -inf      -inf      -inf
11 -0.335474 -0.399539 -0.093901 -0.682290  0.312682 -0.310319  0.344753  0.017465 -0.364808 -0.262316 -0.282589 -0.239767      -inf      -inf      -inf      -inf
12 -1.757631 -0.967825 -0.516159 -0.246766 -0.352132 -0.780370 -0.262975 -0.793605 -0.238561 -0.374695 -0.132526 -0.126956 -0.524015      -inf      -inf      -inf
13  0.550975  0.313643 -0.074468  0.519995 -0.149188 -0.565922  0.199527 -0.738029  0.142203 -0.164007 -0.494203  0.570010 -0.579608 -0.198923      -inf      -inf
14 -0.616347 -0.812240  0.245260  0.167278  0.913596 -0.493119  1.139083 -0.300623 -0.399155  0.200648 -0.114634  0.147219 -0.829207  0.363519 -0.325846      -inf
15 -0.145391  0.514632 -0.296119 -0.038103 -0.187110 -0.634636  0.509902 -0.338267 -0.231534 -0.007304 -0.432799  0.339123  0.248173 -0.242426 -0.595925 -0.442379

我们可以看到对角线和上三角形被 -inf掩盖。

4.6 Softmax

# Softmax the attention score
attention_score = torch.softmax(attention_score, dim=-1)  #[4, 4, 16, 16] [batch_size, num_heads, context_length, context_length]
print(pd.DataFrame(attention_score.detach().cpu().numpy()))

打印输出(一批次的一个序列):

           0         1         2         3         4         5         6         7         8         9         10        11        12        13        14        15
0   0.062604  0.062472  0.062478  0.062419  0.062452  0.062439  0.062748  0.062419  0.062424  0.062459  0.062479  0.062595  0.062568  0.062427  0.062399  0.062619
1   0.062377  0.062529  0.062643  0.062387  0.062551  0.062364  0.062499  0.062605  0.062368  0.062460  0.062664  0.062381  0.062577  0.062505  0.062619  0.062470
2   0.062565  0.062551  0.062453  0.062535  0.062574  0.062400  0.062717  0.062398  0.062488  0.062529  0.062414  0.062668  0.062477  0.062479  0.062354  0.062398
3   0.062647  0.062427  0.062634  0.062411  0.062486  0.062480  0.062384  0.062513  0.062396  0.062491  0.062679  0.062367  0.062492  0.062483  0.062478  0.062634
4   0.062635  0.062566  0.062567  0.062473  0.062481  0.062512  0.062460  0.062430  0.062502  0.062428  0.062421  0.062470  0.062474  0.062446  0.062416  0.062720
5   0.062371  0.062501  0.062488  0.062527  0.062367  0.062405  0.062373  0.062529  0.062461  0.062523  0.062744  0.062418  0.062480  0.062669  0.062541  0.062603
6   0.062467  0.062379  0.062504  0.062417  0.062562  0.062422  0.062516  0.062560  0.062472  0.062480  0.062628  0.062490  0.062451  0.062460  0.062503  0.062689
7   0.062358  0.062348  0.062566  0.062444  0.062742  0.062384  0.062900  0.062465  0.062389  0.062509  0.062500  0.062458  0.062375  0.062585  0.062455  0.062521
8   0.062632  0.062573  0.062636  0.062449  0.062559  0.062391  0.062513  0.062395  0.062445  0.062450  0.062509  0.062504  0.062553  0.062438  0.062356  0.062598
9   0.062434  0.062727  0.062467  0.062484  0.062360  0.062391  0.062356  0.062525  0.062480  0.062519  0.062687  0.062428  0.062625  0.062565  0.062484  0.062469
10  0.062419  0.062608  0.062511  0.062473  0.062502  0.062385  0.062693  0.062527  0.062415  0.062475  0.062475  0.062520  0.062555  0.062490  0.062497  0.062455
11  0.062463  0.062450  0.062519  0.062403  0.062655  0.062468  0.062669  0.062551  0.062457  0.062478  0.062474  0.062484  0.062548  0.062412  0.062479  0.062489
12  0.062327  0.062405  0.062489  0.062561  0.062530  0.062435  0.062556  0.062433  0.062564  0.062524  0.062599  0.062601  0.062487  0.062578  0.062394  0.062517
13  0.062685  0.062591  0.062482  0.062671  0.062466  0.062395  0.062554  0.062374  0.062538  0.062463  0.062405  0.062693  0.062393  0.062456  0.062360  0.062472
14  0.062372  0.062352  0.062530  0.062509  0.062806  0.062387  0.062958  0.062414  0.062400  0.062518  0.062447  0.062504  0.062350  0.062566  0.062410  0.062476
15  0.062479  0.062693  0.062448  0.062504  0.062470  0.062394  0.062691  0.062440  0.062460  0.062512  0.062424  0.062620  0.062588  0.062458  0.062399  0.062422

应用softmax函数后,分数现在在0和1之间,并且每行的总和为1。

4.7 计算V注意力

最后,将注意力分数与 V 相乘,以获得多头注意力模块的输出。

# Calculate the V attention output
A = torch.matmul(attention_score, V) # [4, 4, 16, 16] [batch_size, num_heads, context_length, head_size]
print(attention_output.shape)

打印输出:

torch.Size([4, 4, 16, 16])

注意:现在的形状是 [4, 4, 16, 16],即 [batch_size, num_heads, context_length, head_size]。

4.8 连接和输出

回想一下上一篇文章,我们需要连接多头注意力模块的输出并将其输入线性层。

A = A.transpose(1, 2) # [4, 16, 4, 16] [batch_size, context_length, num_heads, head_size]
A = A.reshape(batch_size, -1, d_model) # [4, 16, 64] [batch_size, context_length, d_model]

注意:现在的形状是 [4, 16, 64],即 [batch_size, context_length, d_model]。

现在,我们可以应用 Wo 的另一个 [64,64] 线性层(在训练期间学习权重)并获得多头注意力模块的最终输出:

# Define the output weight matrix
Wo = nn.Linear(d_model, d_model)
output = Wo(A) # [4, 16, 64] [batch_size, context_length, d_model]

print(output.shape)

如果我们打印出来,形状又回到 [4, 16, 64],与我们输入的嵌入形状相同。

第 5 步:残差连接和层标准化

现在我们有了多头注意力模块的输出,可以应用残差连接和层归一化。

# Add residual connection
output = output + X

# Add Layer Normalization
layer_norm = nn.LayerNorm(d_model)
output = layer_norm(output)

第 6 步:前馈网络

# Define Feed Forward Network
output = nn.Linear(d_model, d_model * 4)(output)
output = nn.ReLU()(output)
output = nn.Linear(d_model * 4, d_model)(output)
output = torch.dropout(output, p=dropout, train=True)

添加最后的残差连接和层归一化:

# Add residual connection
output = output + X
# Add Layer Normalization
layer_norm = nn.LayerNorm(d_model)
output = layer_norm(output)

第 7 步:重复步骤 4 至 6

上面完成的只是一个 transformer 块。在实践中,我们将多个 Transformer 块堆叠在一起以形成 Transformer 解码器。

实际上,我们应该将代码打包到类中,并使用 PyTorch.nn.Module 来构建 Transformer 解码器。但为了演示,我们只保留一个块。

第 8 步:输出概率

应用最终的线性层来获取 logits:

logits = nn.Linear(d_model, max_token_value)(output)
print(pd.DataFrame(logits[0].detach().cpu().numpy()))

最后一步是对 logits 进行 softmax 以获得每个标记的概率:

# torch.softmax usually used during inference, during training we use torch.nn.CrossEntropyLoss
# but for illustration purpose, we'll use torch.softmax here
probabilities = torch.softmax(logits, dim=-1)
           0         1         2         3         4         5         6         7         8         9       ...    100059    100060    100061    100062    100063    100064    100065    100066    100067    100068
0   0.000007  0.000008  0.000006  0.000005  0.000004  0.000004  0.000009  0.000007  0.000009  0.000008  ...  0.000013  0.000005  0.000006  0.000014  0.000009  0.000005  0.000005  0.000016  0.000006  0.000005
1   0.000018  0.000016  0.000006  0.000017  0.000005  0.000006  0.000005  0.000005  0.000008  0.000004  ...  0.000006  0.000004  0.000006  0.000007  0.000006  0.000007  0.000014  0.000020  0.000004  0.000001
2   0.000013  0.000007  0.000008  0.000003  0.000007  0.000009  0.000021  0.000005  0.000007  0.000013  ...  0.000018  0.000009  0.000010  0.000010  0.000018  0.000009  0.000007  0.000008  0.000005  0.000015
3   0.000005  0.000013  0.000011  0.000004  0.000006  0.000007  0.000012  0.000006  0.000015  0.000010  ...  0.000032  0.000006  0.000008  0.000005  0.000014  0.000009  0.000021  0.000014  0.000004  0.000005
4   0.000005  0.000010  0.000008  0.000006  0.000017  0.000005  0.000010  0.000003  0.000008  0.000010  ...  0.000012  0.000005  0.000010  0.000003  0.000015  0.000022  0.000015  0.000010  0.000013  0.000005
5   0.000008  0.000004  0.000007  0.000003  0.000004  0.000011  0.000018  0.000007  0.000002  0.000010  ...  0.000013  0.000004  0.000012  0.000010  0.000015  0.000017  0.000010  0.000019  0.000013  0.000012
6   0.000005  0.000008  0.000014  0.000004  0.000007  0.000007  0.000012  0.000016  0.000005  0.000005  ...  0.000012  0.000007  0.000012  0.000022  0.000011  0.000018  0.000011  0.000010  0.000004  0.000014
7   0.000004  0.000008  0.000003  0.000006  0.000005  0.000019  0.000010  0.000016  0.000007  0.000011  ...  0.000014  0.000007  0.000007  0.000010  0.000013  0.000012  0.000013  0.000003  0.000008  0.000004
8   0.000002  0.000006  0.000005  0.000004  0.000006  0.000010  0.000008  0.000006  0.000016  0.000012  ...  0.000022  0.000004  0.000006  0.000011  0.000031  0.000016  0.000022  0.000006  0.000006  0.000005
9   0.000006  0.000005  0.000010  0.000008  0.000019  0.000018  0.000012  0.000011  0.000005  0.000015  ...  0.000019  0.000008  0.000005  0.000029  0.000009  0.000010  0.000009  0.000017  0.000007  0.000007
10  0.000011  0.000005  0.000008  0.000007  0.000017  0.000009  0.000007  0.000013  0.000010  0.000008  ...  0.000015  0.000011  0.000012  0.000007  0.000012  0.000020  0.000010  0.000006  0.000011  0.000009
11  0.000011  0.000006  0.000004  0.000005  0.000006  0.000012  0.000009  0.000007  0.000007  0.000004  ...  0.000042  0.000011  0.000010  0.000010  0.000021  0.000009  0.000004  0.000021  0.000008  0.000014
12  0.000005  0.000010  0.000007  0.000009  0.000007  0.000023  0.000011  0.000005  0.000006  0.000006  ...  0.000015  0.000006  0.000009  0.000003  0.000019  0.000010  0.000009  0.000056  0.000017  0.000004
13  0.000004  0.000016  0.000010  0.000010  0.000026  0.000008  0.000009  0.000002  0.000008  0.000007  ...  0.000014  0.000006  0.000010  0.000010  0.000007  0.000012  0.000008  0.000009  0.000016  0.000006
14  0.000003  0.000008  0.000019  0.000007  0.000014  0.000004  0.000009  0.000009  0.000005  0.000004  ...  0.000014  0.000010  0.000010  0.000003  0.000007  0.000013  0.000013  0.000005  0.000013  0.000002
15  0.000005  0.000010  0.000008  0.000005  0.000011  0.000010  0.000009  0.000005  0.000004  0.000005  ...  0.000009  0.000007  0.000012  0.000006  0.000013  0.000013  0.000008  0.000014  0.000005  0.000005

[16 rows x 100069 columns]

请注意,在这里得到的是一个形状为 [16, 100069] 的巨大矩阵,它是整个词汇表中每个 token 的概率。

完整代码

在实践中,多个 Transformer 块将堆叠在一起以执行一个解码事务。在训练过程中,输出 token 将与ground truth token 进行比较以计算损失。然后对超参数中定义的 max_iters 次数重复该过程。

我的 GitHub (https://github.com/AI-mzq/From-Zero-to-Transformer.git)中有 完整的 Transformer Decoder 代码,您可以查看。将数据集更改为您自己的数据,尝试自己训练一个小模型。拥有第一个定制小模型是我们成为LLM英雄的第一步!

如何学习大模型 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 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】
Matlab机械臂建模:机器人工具箱的使用&&导入自己的机械臂模型 本文主要介绍如何在matlab中建立机械臂模型(前提要下载了Robotics Toolbox机器人工具箱~),并进行基于正逆运动学计算的轨迹运动。对于已有的Solidworks机械臂三维模型,如何导入Matlab,并对其进行运动控制。 阅读详情

相关推荐

告别调试烦恼:用Lattice Diamond手把手教你JTAG烧录FPGA(附SRAM/Flash模式详解)

本文详细介绍了使用Lattice Diamond软件进行JTAG烧录FPGA的全流程,包括SRAM临时调试和Flash固化的核心区别。从环境准备、硬件连接到文件准备、烧录模式选择,再到典型问题排查和高级技巧,手把手教你快速掌握FPGA烧录技术,提升开发效率。

weixin_42569329的博客 505

20个主流的代码生成LLM大模型及9种常见应用场景

自动完成或代码生成功能已在开发工具中存在多年。早在 1996 年,微软就在 Visual Studio 中为 Visual Basic 引入了这一功能(IntelliSense)。熟悉 Eclipse 的人可能使用过 Java getter 和 setter 生成函数,以及变量名的字符串导出函数(著名的“public String toString()”函数)。提供下一行代码仍然是这些 IDE 工具的一个重要功能,通常通过同时按下 Control 和空格键来激活。

新缸中之脑 1万+

自动驾驶IDM与MOBIL模型

IDM模型,自动驾驶

不想学好数学的汽车工程师不是一个好的程序员 1万+

自定义训练大型语言模型(LLM):带有代码示例的详细指南

这篇文章提供了一个综合指南,描述了关于如何使用代码示例和实例来自定义训练大型语言模型(例如GPT-4)的方法。近年来,大型语言模型(LLM)如GPT-4因其在自然语言理解和生成方面的惊人能力而引起了广泛关注。然而,为了将LLM定制到特定任务或领域,需要进行自定义训练。本文提供了一份详细的、分步指南,介绍了如何自定义训练LLM,其中包含完整的代码示例和实例。

lantianye的专栏 6128

AI驱动Spine骨骼动画生成:从图像拆分到动画自动化的全流程解析

计算机视觉与生成式AI技术正深度赋能传统数字内容生产流程。在2D动画制作领域,骨骼动画技术通过模拟真实生物关节运动,实现了角色动画的高效制作与灵活控制。其核心原理在于将角色拆分为独立部件,通过骨骼层级关系驱动部件变换,结合关键帧插值算法生成流畅动作。这项技术的工程价值在于大幅降低动画制作门槛,提升内容生产效率,尤其适用于游戏开发、影视预演、广告设计等需要快速原型迭代的场景。本文聚焦于如何利用SIFT特征匹配、RANSAC几何验证等CV算法实现部件自动对位,并结合动画12原则的程序化实现,构建从单张角色立绘到

weixin_28696185的博客 1570

手把手教你用UM982搭建厘米级RTK定位系统(附避坑指南)

本文详细介绍了如何使用UM982模组搭建厘米级RTK定位系统,涵盖硬件连接、软件配置和深度优化技巧。UM982支持BDS、GPS、GLONASS和Galileo等多系统全频点信号,特别适合精准农业、无人机导航等高精度应用场景。通过实战案例和避坑指南,帮助开发者快速实现厘米级定位精度。

y7z8a的博客 1466

国内外大语言模型(LLM)超详细总结与代码实战​(可用于面试或学习,持续更新)-----国外篇

每个 token 对应一个词嵌入(token embedding)、一个段落嵌入(segment embedding),再加上位置编码,一起输入模型。生成策略可选最大概率取样(greedy)、束搜索(beam search)或随机采样(top-k/top-p),直到生成结束符为止。每个 token 被映射为一个高维向量(词嵌入),再加上与其在序列中位置对应的“位置编码”,以注入位置信息。系统(system)、用户(user)、助手(assistant)分角色输入,模型根据上下文角色切换生成。

qq_43664407的博客 1383

立创EDA开源足轮机器人:基于STM32F407与ESP32的LQR自平衡与FOC驱动设计全解析

本文详细解析了基于立创EDA平台的开源足轮机器人项目。该项目采用STM32F407作为主控,ESP32负责无线通信,并应用LQR自平衡算法与FOC驱动技术,实现了机器人的稳定站立、移动转向及复杂地形适应能力。文章深入剖析了其硬件架构、软件设计及调试经验,为机器人运动控制学习提供了宝贵参考。

weixin_42608299的博客 242

(徒手搓LLM)逐行代码从0构造一个LLM——LlaMa篇

本篇为:面向人群:觉得LLM很多复杂的结构和层级,懂很多原理,但是不知道怎么结合到一起本篇会很长,但是应该不会又臭又长本篇可能像当头一棒,但是有可能:力度刚刚好,懵逼不伤脑。逐行拆解LlaMa大模型的所有算子,架构,包括RMSNorm,ROPE,SwiGLU实现本篇未采用huggingface的库,全程pytorch实现,没有任何预训练模型起始点为一本《西游记》原文,终点为你自己练的大模型。

python12345_的博客 1404

ABAP Open SQL 数据拷贝导致 SAPSQL_DATA_LOSS:从报错机理到稳妥修复

数据类型与长度不合规。一旦在Open SQL的无损赋值检查里被发现,系统宁可中止也不会偷偷替你截断。把变量声明对齐到字典、在需要时明确表达转换/截断意图、写法上避免落入高危的操作数位置,再配合ATC的预防性检查,既能解决你这次的ST22Dump,也能把同类问题消灭在萌芽状态。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 441

Java Swing教程-16. Swing中的图形绘制

这篇教程介绍了Java Swing中的图形绘制功能,主要内容包括: Graphics类的基本使用 - 介绍了如何重写paintComponent方法实现自定义绘制,以及基本图形绘制方法(线条、矩形、椭圆、多边形等) 文本与图片绘制 - 讲解了文本绘制方法、字体设置和图片加载绘制技术 颜色与字体设置 - 包括预定义颜色、RGB自定义颜色、透明色设置以及字体样式控制 案例实现 - 提供了一个简单绘图程序的框架,支持鼠标绘制不同图形、选择工具和自定义颜色等功能 教程通过代码示例详细演示了各种绘图操作,适合Java

无 239

LLM大模型基础入门系列之:(四)从头开始编写LLM代码

从头开始实现一个类 GPT 的 transformer。

m_aigc2022的博客 2297

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

七天入门大模型 :LLM大模型基础知识最全汇总

Base模型和Chat模型我们通常会看到某模型研发机构开源了base模型和chat模型,那base模型和chat模型有什么区别呢?首先,所有的大语言模型(LLM)的工作方式都是接收一些文本,然后预测最有可能出现在其后面的文本。base模型,也就是基础模型,是在海量不同文本上训练出来的预测后续文本的模型。后续文本未必是对指令和对话的响应。qwen-1.8B。

2201_75499313的博客 7334

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

七天入门LLM大模型 | 第一天:魔搭社区和LLM大模型基础知识

Base模型和Chat模型我们通常会看到某模型研发机构开源了base模型和chat模型,那base模型和chat模型有什么区别呢?首先,所有的大语言模型(LLM)的工作方式都是接收一些文本,然后预测最有可能出现在其后面的文本。base模型,也就是基础模型,是在海量不同文本上训练出来的预测后续文本的模型。后续文本未必是对指令和对话的响应。qwen-1.8B。

2401_85375186的博客 1541

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

AI大佬吴恩达+OpenAI团队编写:面向大模型入门者的 LLM CookBook 汉化版(附pdf)

AI大佬吴恩达+OpenAI团队编写:面向大模型入门者的 LLM CookBook 汉化版(附pdf)

Y525698136的博客 1355

如何零基础入门LLM,零基础入门到精通,收藏这篇就够了

之前推送了这篇文章后大家纷纷留言希望能再多深入介绍下LLM于是今天继续更新!☑️☑️☑️实习tips首先,我们从Stanford DS coursework出发,总结出了以下4个必备技能点:Machine Learning:比较常见的课程包括NLP、CV、GNN,更传统的一些ML,比如说Random Forest,Boosted Trees;Stats & Math:更多是数学方面,也有stochastic processes,A/B testing等;

leah126的博客 1692

LLM大模型入门

我们先了解什么是大语言模型。大语言模型是一种基于深度学习的自然语言处理技术,它可以通过学习大量的文本数据,生成连贯、有逻辑的文本。大语言模型在许多领域都有广泛的应用,如文本生成、机器翻译、情感分析等。入门步骤1. 学习基础知识首先,我们需要学习一些基础知识,包括机器学习、深度学习、自然语言处理等。这些知识将为我们学习大语言模型打下坚实的基础。编程语言:大多数LLM相关的库和框架都是用Python编写的,因此掌握Python是必不可少的。开发环境。

xiangxueerfei的博客 1366

【LLM应用】大模型在编写代码中的应用

随着人工智能技术的飞速发展,大模型在各个领域的应用越来越广泛。在代码编程领域,大模型通过深度学习技术,极大地提高了代码编写的效率、质量和可维护性。大模型通过学习大量代码样本,能够预测并推荐接下来要编写的代码片段,实现代码自动补全和智能提示。这种功能不仅提高了开发者的编写速度,还能减少拼写和语法错误。大模型能够分析代码中的潜在问题和错误,为开发者提供质量检查和错误预测服务。通过这种模式匹配和规则学习,大模型能够发现代码中的冗余、重复和潜在的安全隐患,帮助开发者提前修复问题。

weixin_42458975的博客 2231

0基础必备大模型书籍!吴恩达教授的《开发者的LLM入门完全指南》来了!

本项目是一个面向开发者的 LLM 入门教程,基于吴恩达老师大模型系列课程内容,将原课程内容翻译为中文并复现其范例代码,实现中文 Prompt,指导国内开发者如何基于 LLM 快速、高效开发具备强大能力的应用程序。面向开发者的 Prompt Engineering。

2401_85373691的博客 971

全面且基础的大模型LLM入门教程书来了(附pdf)

24年8月出版的名为《Large Language Models: A Deep Dive》的教程书,内容和书名完美匹配,真的是完美符合新手入门大语言模型(LLM)的需求,不仅全面还足够基础。

pythonhy的博客 873

AI/LLM 大模型入门指南

这里是一份大模型入门指南,带你从API调用走进本地大模型部署和微调。

Hoper-J的博客 1372

大模型LLM入门篇:小白入门一文快速了解大模型(附教程)

本系列文章的深度有限,只是个人对大模型知识脉络的梳理,同时也会借鉴一下同行的博客内容充实本文,文末将会注明参考来源。

DEVELOPERAA的博客 1403

大模型开源教程:LLM开源大模型食用指南:self-llm(附文档)

本项目的学习建议是,先学习环境配置,然后再学习模型的配置使用,最后再学习扭矩。因为环境配置是基础,模型的配置使用是基础,扭矩是进阶。初学者可以选择Qwen1.5,InternLM2,MiniCPM等模型优先学习。

2401_82469710的博客 1499

llm-action 实战指南:程序员零基础轻松学 LLM 大模型,从入门到精通

本文介绍了轻量级LLM开发工具llm-action,它通过极简API、多模型兼容和低门槛集成的特点,帮助开发者快速上手大模型开发。文章详细讲解了环境搭建、核心功能实战和项目集成全流程,包括基础文本生成、多轮对话、函数调用和流式输出等核心功能,并展示了如何集成到Flask服务和自定义扩展。该工具既适合零基础开发者入门,也能满足企业级项目需求,让开发者无需关注模型底层细节,专注于业务实现。

xiugou3365的博客 1059
上一篇: 大模型算法入行&转行?我建议你这样做!
下一篇: 零基础转行自学大模型路线规划(附快速学习路线图)
冻感糕人~
博客等级 码龄3年 8926粉丝 2433原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址