>本教程的目的是为如何使用Pytorch构建变压器模型提供全面的理解。变压器是现代机器学习中最强大的模型之一。他们彻底改变了该领域,特别是在自然语言处理(NLP)任务中,例如语言翻译和文本摘要。长期的短期内存(LSTM)网络由于能够处理远程依赖和并行计算的能力而被这些任务中的变压器所取代。
构建变压器指南中使用的工具是Pytorch,Pytorch是一个流行的开源机器学习库,以其简单,多功能性和效率而闻名。借助动态计算图和广泛的库,Pytorch已成为机器学习和人工智能领域的研究人员和开发人员的首选。 对于那些不熟悉Pytorch的人来说,访问Datacamp的课程,建议使用Pytorch进行深度学习介绍。 Vaswani等人所需要的全部所需的> Transformers之后,由于其独特的设计和有效性,变形金刚已成为许多NLP任务的基石。
>。在变压器的核心是注意机制,特别是“自我注意力”的概念,它允许模型称重和优先级输入数据。这种机制使变压器能够管理数据中的长期依赖性。从根本上讲,这是一种加权方案,允许模型在产生输出时专注于输入的不同部分。
变形金刚在NLP领域的影响不能被夸大。他们在许多任务中都表现出了传统模型的表现,证明了以更细微的方式理解和产生人类语言的能力。
为了更深入地了解NLP,Datacamp在Python课程中的自然语言处理简介是推荐的资源。设置Pytorch
>在构建变压器之前,必须正确设置工作环境。首先,需要安装Pytorch。 Pytorch(当前稳定版本-2.0.1)可以通过PIP或CONDA软件包管理器轻松安装。
对于PIP,请使用命令:
对于conda,请使用命令:
pip3 install torch torchvision torchaudio
>使用pytorch和cpu友善访问pytorch文档。
此外,对深度学习概念有基本的理解是有益的,因为这些理解对于理解变形金刚的操作至关重要。对于需要进修的人来说,python中的Datacamp课程深度学习是一个宝贵的资源,涵盖了深度学习中的关键概念。>用pytorch
导入库和模块
2。定义基本构建块:多头注意,位置馈线网络,位置编码
conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia
>
类定义和初始化:
import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import math import copy
d_model:输入的维度。
num_heads:将输入拆分为。class MultiHeadAttention(nn.Module): def __init__(self, d_model, num_heads): super(MultiHeadAttention, self).__init__() # Ensure that the model dimension (d_model) is divisible by the number of heads assert d_model % num_heads == 0, "d_model must be divisible by num_heads" # Initialize dimensions self.d_model = d_model # Model's dimension self.num_heads = num_heads # Number of attention heads self.d_k = d_model // num_heads # Dimension of each head's key, query, and value # Linear layers for transforming inputs self.W_q = nn.Linear(d_model, d_model) # Query transformation self.W_k = nn.Linear(d_model, d_model) # Key transformation self.W_v = nn.Linear(d_model, d_model) # Value transformation self.W_o = nn.Linear(d_model, d_model) # Output transformation def scaled_dot_product_attention(self, Q, K, V, mask=None): # Calculate attention scores attn_scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k) # Apply mask if provided (useful for preventing attention to certain parts like padding) if mask is not None: attn_scores = attn_scores.masked_fill(mask == 0, -1e9) # Softmax is applied to obtain attention probabilities attn_probs = torch.softmax(attn_scores, dim=-1) # Multiply by values to obtain the final output output = torch.matmul(attn_probs, V) return output def split_heads(self, x): # Reshape the input to have num_heads for multi-head attention batch_size, seq_length, d_model = x.size() return x.view(batch_size, seq_length, self.num_heads, self.d_k).transpose(1, 2) def combine_heads(self, x): # Combine the multiple heads back to original shape batch_size, _, seq_length, d_k = x.size() return x.transpose(1, 2).contiguous().view(batch_size, seq_length, self.d_model) def forward(self, Q, K, V, mask=None): # Apply linear transformations and split heads Q = self.split_heads(self.W_q(Q)) K = self.split_heads(self.W_k(K)) V = self.split_heads(self.W_v(V)) # Perform scaled dot-product attention attn_output = self.scaled_dot_product_attention(Q, K, V, mask) # Combine heads and apply output transformation output = self.W_o(self.combine_heads(attn_output)) return output
初始化检查d_model是否可以由num_heads除外,然后定义查询,键,值和输出的转换权重。
pip3 install torch torchvision torchaudio
此方法将输入X重塑为形状(batch_size,num_heads,seq_length,d_k)。它使模型能够同时处理多个注意力头,从而可以进行并行计算。
组合头:
conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia
分别将注意力应用于每个头部后,此方法将结果结合回形状的单个张量(batch_size,seq_length,d_model)。这为进一步处理的结果做准备。
forward方法:
import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import math import copy
正向方法是实际计算发生的地方:
应用线性转换:首先使用初始化中定义的权重通过线性转换。 拆分头:使用split_heads方法将变换后的Q,K,V分为多个头。
class MultiHeadAttention(nn.Module): def __init__(self, d_model, num_heads): super(MultiHeadAttention, self).__init__() # Ensure that the model dimension (d_model) is divisible by the number of heads assert d_model % num_heads == 0, "d_model must be divisible by num_heads" # Initialize dimensions self.d_model = d_model # Model's dimension self.num_heads = num_heads # Number of attention heads self.d_k = d_model // num_heads # Dimension of each head's key, query, and value # Linear layers for transforming inputs self.W_q = nn.Linear(d_model, d_model) # Query transformation self.W_k = nn.Linear(d_model, d_model) # Key transformation self.W_v = nn.Linear(d_model, d_model) # Value transformation self.W_o = nn.Linear(d_model, d_model) # Output transformation def scaled_dot_product_attention(self, Q, K, V, mask=None): # Calculate attention scores attn_scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k) # Apply mask if provided (useful for preventing attention to certain parts like padding) if mask is not None: attn_scores = attn_scores.masked_fill(mask == 0, -1e9) # Softmax is applied to obtain attention probabilities attn_probs = torch.softmax(attn_scores, dim=-1) # Multiply by values to obtain the final output output = torch.matmul(attn_probs, V) return output def split_heads(self, x): # Reshape the input to have num_heads for multi-head attention batch_size, seq_length, d_model = x.size() return x.view(batch_size, seq_length, self.num_heads, self.d_k).transpose(1, 2) def combine_heads(self, x): # Combine the multiple heads back to original shape batch_size, _, seq_length, d_k = x.size() return x.transpose(1, 2).contiguous().view(batch_size, seq_length, self.d_model) def forward(self, Q, K, V, mask=None): # Apply linear transformations and split heads Q = self.split_heads(self.W_q(Q)) K = self.split_heads(self.W_k(K)) V = self.split_heads(self.W_v(V)) # Perform scaled dot-product attention attn_output = self.scaled_dot_product_attention(Q, K, V, mask) # Combine heads and apply output transformation output = self.W_o(self.combine_heads(attn_output)) return output
>
>组合头:使用combine_heads方法将每个头的结果组合回单个张量。类是Pytorch的NN.Module的子类,这意味着它将继承使用神经网络层所需的所有功能。
pip3 install torch torchvision torchaudio
conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia
类定义:
该类被定义为Pytorch的NN.模块的子类,允许将其用作标准的Pytorch层。
import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import math import copy
>
d_model:模型输入的尺寸。class MultiHeadAttention(nn.Module): def __init__(self, d_model, num_heads): super(MultiHeadAttention, self).__init__() # Ensure that the model dimension (d_model) is divisible by the number of heads assert d_model % num_heads == 0, "d_model must be divisible by num_heads" # Initialize dimensions self.d_model = d_model # Model's dimension self.num_heads = num_heads # Number of attention heads self.d_k = d_model // num_heads # Dimension of each head's key, query, and value # Linear layers for transforming inputs self.W_q = nn.Linear(d_model, d_model) # Query transformation self.W_k = nn.Linear(d_model, d_model) # Key transformation self.W_v = nn.Linear(d_model, d_model) # Value transformation self.W_o = nn.Linear(d_model, d_model) # Output transformation def scaled_dot_product_attention(self, Q, K, V, mask=None): # Calculate attention scores attn_scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k) # Apply mask if provided (useful for preventing attention to certain parts like padding) if mask is not None: attn_scores = attn_scores.masked_fill(mask == 0, -1e9) # Softmax is applied to obtain attention probabilities attn_probs = torch.softmax(attn_scores, dim=-1) # Multiply by values to obtain the final output output = torch.matmul(attn_probs, V) return output def split_heads(self, x): # Reshape the input to have num_heads for multi-head attention batch_size, seq_length, d_model = x.size() return x.view(batch_size, seq_length, self.num_heads, self.d_k).transpose(1, 2) def combine_heads(self, x): # Combine the multiple heads back to original shape batch_size, _, seq_length, d_k = x.size() return x.transpose(1, 2).contiguous().view(batch_size, seq_length, self.d_model) def forward(self, Q, K, V, mask=None): # Apply linear transformations and split heads Q = self.split_heads(self.W_q(Q)) K = self.split_heads(self.W_k(K)) V = self.split_heads(self.W_v(V)) # Perform scaled dot-product attention attn_output = self.scaled_dot_product_attention(Q, K, V, mask) # Combine heads and apply output transformation output = self.W_o(self.combine_heads(attn_output)) return output
pe:一个充满零的张量,将用位置编码填充。
位置:一个张量,包含序列中每个位置的位置索引。
class MultiHeadAttention(nn.Module): def __init__(self, d_model, num_heads):
位置编码类添加了有关令牌在序列中的位置的信息。由于变压器模型缺乏对代币顺序的固有知识(由于其自我发挥机制),因此该类别有助于该模型考虑令牌在序列中的位置。选择使用的正弦函数以使模型可以轻松学习到相对位置,因为它们为序列中的每个位置都产生独特而光滑的编码。
3。构建编码器块
类定义:
pip3 install torch torchvision torchaudio
该类被定义为Pytorch的Nn.模块的子类,这意味着它可以用作Pytorch中神经网络的构建块。
conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia
>
参数:
import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import math import copy
d_model:输入的维度。 num_heads:多头注意力中注意力的数量。
>self.self_attn:多头注意机制。 self.feed_forward:位置上的馈送神经网络。
>输入:>
class MultiHeadAttention(nn.Module): def __init__(self, d_model, num_heads): super(MultiHeadAttention, self).__init__() # Ensure that the model dimension (d_model) is divisible by the number of heads assert d_model % num_heads == 0, "d_model must be divisible by num_heads" # Initialize dimensions self.d_model = d_model # Model's dimension self.num_heads = num_heads # Number of attention heads self.d_k = d_model // num_heads # Dimension of each head's key, query, and value # Linear layers for transforming inputs self.W_q = nn.Linear(d_model, d_model) # Query transformation self.W_k = nn.Linear(d_model, d_model) # Key transformation self.W_v = nn.Linear(d_model, d_model) # Value transformation self.W_o = nn.Linear(d_model, d_model) # Output transformation def scaled_dot_product_attention(self, Q, K, V, mask=None): # Calculate attention scores attn_scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k) # Apply mask if provided (useful for preventing attention to certain parts like padding) if mask is not None: attn_scores = attn_scores.masked_fill(mask == 0, -1e9) # Softmax is applied to obtain attention probabilities attn_probs = torch.softmax(attn_scores, dim=-1) # Multiply by values to obtain the final output output = torch.matmul(attn_probs, V) return output def split_heads(self, x): # Reshape the input to have num_heads for multi-head attention batch_size, seq_length, d_model = x.size() return x.view(batch_size, seq_length, self.num_heads, self.d_k).transpose(1, 2) def combine_heads(self, x): # Combine the multiple heads back to original shape batch_size, _, seq_length, d_k = x.size() return x.transpose(1, 2).contiguous().view(batch_size, seq_length, self.d_model) def forward(self, Q, K, V, mask=None): # Apply linear transformations and split heads Q = self.split_heads(self.W_q(Q)) K = self.split_heads(self.W_k(K)) V = self.split_heads(self.W_v(V)) # Perform scaled dot-product attention attn_output = self.scaled_dot_product_attention(Q, K, V, mask) # Combine heads and apply output transformation output = self.W_o(self.combine_heads(attn_output)) return output
>蒙版:可选的掩码以忽略输入的某些部分。
>前进网络:上一个步骤的输出通过位置馈线向前网络传递。 添加&归一化(进率后):类似于步骤2,将馈送输出添加到此阶段的输入(残留连接),然后使用norm2。
>输出:返回处理后的张量作为编码层的输出。
pip3 install torch torchvision torchaudio
conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia
>
参数import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import math import copy
d_model:输入的维度。
self.self_attn:目标序列的多头自我注意机制。
self.cross_attn:参与编码器输出的多头注意机制。:
class MultiHeadAttention(nn.Module): def __init__(self, d_model, num_heads): super(MultiHeadAttention, self).__init__() # Ensure that the model dimension (d_model) is divisible by the number of heads assert d_model % num_heads == 0, "d_model must be divisible by num_heads" # Initialize dimensions self.d_model = d_model # Model's dimension self.num_heads = num_heads # Number of attention heads self.d_k = d_model // num_heads # Dimension of each head's key, query, and value # Linear layers for transforming inputs self.W_q = nn.Linear(d_model, d_model) # Query transformation self.W_k = nn.Linear(d_model, d_model) # Key transformation self.W_v = nn.Linear(d_model, d_model) # Value transformation self.W_o = nn.Linear(d_model, d_model) # Output transformation def scaled_dot_product_attention(self, Q, K, V, mask=None): # Calculate attention scores attn_scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k) # Apply mask if provided (useful for preventing attention to certain parts like padding) if mask is not None: attn_scores = attn_scores.masked_fill(mask == 0, -1e9) # Softmax is applied to obtain attention probabilities attn_probs = torch.softmax(attn_scores, dim=-1) # Multiply by values to obtain the final output output = torch.matmul(attn_probs, V) return output def split_heads(self, x): # Reshape the input to have num_heads for multi-head attention batch_size, seq_length, d_model = x.size() return x.view(batch_size, seq_length, self.num_heads, self.d_k).transpose(1, 2) def combine_heads(self, x): # Combine the multiple heads back to original shape batch_size, _, seq_length, d_k = x.size() return x.transpose(1, 2).contiguous().view(batch_size, seq_length, self.d_model) def forward(self, Q, K, V, mask=None): # Apply linear transformations and split heads Q = self.split_heads(self.W_q(Q)) K = self.split_heads(self.W_k(K)) V = self.split_heads(self.W_v(V)) # Perform scaled dot-product attention attn_output = self.scaled_dot_product_attention(Q, K, V, mask) # Combine heads and apply output transformation output = self.W_o(self.combine_heads(attn_output)) return output
> enc_output:来自相应的encoder的输出(在跨注意步骤中使用)。
> src_mask:源蒙版忽略了编码器输出的某些部分。
>
初始化:
pip3 install torch torchvision torchaudio
> src_vocab_size:源词汇大小。
> tgt_vocab_size:目标词汇大小。conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia
d_model:模型嵌入的尺寸。> num_heads:多头注意机制中注意力头的数量。
import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import math import copy
d_ff:馈送网络中内层的维度。
生成蒙版方法:
pip3 install torch torchvision torchaudio
forward方法:
此方法定义了变压器的正向通行证,采用源和目标序列并产生输出预测。
conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia
>编码器层:源序列通过编码层传递,最终的编码器输出代表已处理的源序列。
>解码器层:目标序列和编码器的输出通过解码器层传递,从而导致解码器的输出。变压器类将变压器模型的各个组件汇总在一起,包括嵌入,位置编码,编码器层和解码器层。它提供了一个方便的界面,用于训练和推理,封装了多头关注,进率向前网络和层归一化的复杂性。
>>此实现遵循标准变压器体系结构,使其适合于序列到序列任务,例如机器翻译,文本摘要等。包含掩蔽可确保该模型遵守序列中的因果关系,忽略填充令牌,并防止未来的代币泄漏。
这些顺序步骤使变压器模型有效地处理输入序列并产生相应的输出序列。训练Pytorch变压器模型 样本数据准备
出于说明目的,将在此示例中制作一个虚拟数据集。但是,在实际情况下,将采用更实质性的数据集,并且该过程将涉及文本预处理以及为源和目标语言创建词汇映射。pip3 install torch torchvision torchaudio
超参数:
这些值定义了变压器模型的体系结构和行为:
>此行创建了变压器类的实例,并用给定的超参数初始化它。该实例将具有这些超参数定义的架构和行为。>
conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia
>
以下几行生成随机源和目标序列:> src_data:1和src_vocab_size之间的随机整数,代表具有形状的一批源序列(64,max_seq_length)。
> tgt_data:1和tgt_vocab_size之间的随机整数,代表具有形状的一批目标序列(64,max_seq_length)。
训练模型 接下来,将使用上述样本数据训练该模型。但是,在现实世界中,将采用更大的数据集,通常将其划分为不同的集合,以进行培训和验证目的。
>损失功能和优化器:
>
优化器= optim.Adam(...):将优化器定义为ADAM,学习率为0.0001和特定的beta值。import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import math import copy
模型训练模式:
训练环:
代码代码使用典型的训练循环训练100个时期的模型:
此代码片段在100个时期的随机生成源和目标序列上训练变压器模型。它使用ADAM优化器和横向渗透损失函数。每个时期都打印损失,使您可以监视培训进度。在现实世界中,您将用任务中的实际数据替换随机源和目标序列,例如机器翻译。 >变压器模型性能评估
训练模型后,可以在验证数据集或测试数据集上评估其性能。以下是如何完成此操作的一个示例:
>评估模式:
pip3 install torch torchvision torchaudio
transformer.eval():将变压器模型置于评估模式。这很重要,因为它关闭了仅在训练期间使用的某些行为(例如辍学)。
val_src_data:1和src_vocab_size之间的随机整数,代表具有形状的一批验证源序列(64,max_seq_length)。 val_tgt_data:1和tgt_vocab_size之间的随机整数,代表具有形状的一批验证目标序列(64,max_seq_length)。
摘要:
此代码段评估随机生成的验证数据集上的变压器模型,计算验证损失并打印它。在实际情况下,应从您正在处理的任务中替换随机验证数据。验证损失可以使您表明您的模型在看不见的数据上的性能,这是对模型概括能力的关键衡量。>有关变压器和拥抱面孔的更多详细信息,我们的教程,使用变压器和拥抱面的介绍是有用的。
结论和进一步的资源总之,该教程演示了如何使用Pytorch构建变压器模型,Pytorch是最通用的深度学习工具之一。凭借其并行的能力和捕获数据中的长期依赖性的能力,变形金刚在各个领域都具有巨大的潜力,尤其是NLP任务,例如翻译,摘要和情感分析。
渴望加深对先进深度学习概念和技术的理解的人,请考虑使用Datacamp上的Keras探索课程。您还可以在单独的教程中使用Pytorch构建简单的神经网络。>获得顶级AI认证>证明您可以有效,负责任地使用AI。
以上是使用Pytorch构建变压器模型的综合指南的详细内容。更多信息请关注PHP中文网其他相关文章!