attention代码
s计算score的方式有以下几种import torch class Attn(nn.module): def __init__(self, method ,hidden_size): super(Attn, self).__init__() self.method method self.hidden_size hidden_size if self.method not in [dot, general, concat]: raise ValueError(self.method, is not an appropriate attention method.) self.hidden_size hidden_size if self.method general: self.attn nn.Linear(self.hidden_size, hidden_size) elif self.method concat: self.attn nn.Linear(self.hidden_size * 2, hidden_size) self.v nn.Parameter(torch.FloatTensor(hidden_size)) def dot_score(self, hidden, encoder_outputs): return torch.sum(hidden*encoder_outputs, dim2) def general_score(self, hidden, encoder_outputs): return torch.sum(hidden*self.attn(encoder_outputs), dim2) def concat_score(self, hidden, encoder_outputs): energy self.attn(torc.cat(hidden.expand(encoder_outputs.size(0),-1,-1), encoder_outputs)).tanh() return torch.sum(self.v * energy, dim2) def forward(self, hidden, encoder_outputs): if self.method general: attn_energies self.general_score(hidden, encoder_outputs) elif self.method concat: attn_energies self.concat_score(hidden, encoder_outputs) elif self.method dot: attn_energies self.dot_score(hidden, encoder_outputs) # Transpose max_length and batch_size dimensions attn_energies attn_energies.t() # Return the softmax normalized probability scores (with added dimension) return F.softmax(attn_energies, dim1).unsqueeze(1) #在LuongAttnDecoderRNN中使用attn: rnn_output, hidden self.gru(embedded, last_hidden) attn_weights self.attn(rnn_output, encoder_outputs) context attn_weights.bmm(encoder_outputs.transpose(0, 1)) #[batch, 1, hidden] context context.squeeze(1)#去除size为1的维度 #[batch, hidden] concat_input torch.cat((rnn_output, context), 1) concat_output torch.tanh(self.concat(concat_input)) output self.out(concat_output) output F.softmax(output, dim1)bert中的attn借鉴别人博客明白的class BertSelfAttention(nn.Module): def __init__(self, config): super(BertSelfAttention, self).__init__() if config.hidden_size % config.num_attention_heads ! 0: raise ValueError( The hidden size (%d) is not a multiple of the number of attention heads (%d) % (config.hidden_size, config.num_attention_heads)) self.output_attentions config.output_attentions self.num_attention_heads config.num_attention_heads self.attention_head_size int(config.hidden_size / config.num_attention_heads) self.all_head_size self.num_attention_heads * self.attention_head_size self.query nn.Linear(config.hidden_size, self.all_head_size) self.key nn.Linear(config.hidden_size, self.all_head_size) self.value nn.Linear(config.hidden_size, self.all_head_size) self.dropout nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape x.size()[:-1] (self.num_attention_heads, self.attention_head_size) x x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward(self, hidden_states, attention_mask, head_maskNone): mixed_query_layer self.query(hidden_states) mixed_key_layer self.key(hidden_states) mixed_value_layer self.value(hidden_states) query_layer self.transpose_for_scores(mixed_query_layer) key_layer self.transpose_for_scores(mixed_key_layer) value_layer self.transpose_for_scores(mixed_value_layer) # Take the dot product between query and key to get the raw attention scores. attention_scores torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores attention_scores / math.sqrt(self.attention_head_size) # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_scores attention_scores attention_mask # Normalize the attention scores to probabilities. attention_probs nn.Softmax(dim-1)(attention_scores) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs attention_probs * head_mask context_layer torch.matmul(attention_probs, value_layer) context_layer context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape context_layer.size()[:-2] (self.all_head_size,) context_layer context_layer.view(*new_context_layer_shape) outputs (context_layer, attention_probs) if self.output_attentions else (context_layer,) return outputs

相关新闻

Netty(一)之helloworld

Netty(一)之helloworld

HelloWorld客户端通向服务器端发送消息&#xff0c;服务器端读取数据&#xff08;你好&#xff09;并且返回&#xff08;new Date()&#xff09;&#xff0c;客户端读取数据pom<dependency><groupId>io.netty</groupId><artifactId>netty-all</arti…

2026/11/4 9:29:49 阅读更多 →
终极指南:如何免费解锁WeMod完整功能,获得专业版体验

终极指南:如何免费解锁WeMod完整功能,获得专业版体验

终极指南&#xff1a;如何免费解锁WeMod完整功能&#xff0c;获得专业版体验 【免费下载链接】Wand-Enhancer Advanced UX and interoperability extension for Wand (WeMod) app 项目地址: https://gitcode.com/GitHub_Trending/we/Wand-Enhancer 还在为WeMod专业版功能…

2026/10/22 9:14:27 阅读更多 →
Playwright自定义Fixtures:解决测试数据管理与环境隔离的工程实践

Playwright自定义Fixtures:解决测试数据管理与环境隔离的工程实践

1. 项目概述&#xff1a;为什么我们需要自定义 Fixtures&#xff1f;如果你在用 Playwright 做自动化测试&#xff0c;大概率已经熟悉了它的test函数和page对象。官方提供的test和page这些内置 Fixtures 确实方便&#xff0c;开箱即用。但当你开始构建一个稍具规模的测试套件时…

2026/11/4 1:55:15 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年&#xff0c;我大部分时间都在跟浏览器标签页打交道&#xff0c;直到第一次把桌面应用跑起来&#xff0c;才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词&#xff0c;最开始是在某段时间频繁出现在同事的讨论里&#xff0c;一个用HTML…

2026/11/4 1:35:24 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介&#xff1a;亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档&#xff0c;主要面向智能锁安装人员、终端用户及售后维护者&#xff0c;帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件&#xff0c;大小4.37MB&#xff0c;内容结构清晰&#xff…

2026/11/3 10:57:27 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统&#xff0c;整车要求空载跑到8m/s&#xff0c;电机转速已经拉到额定点&#xff0c;驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令&#xff0c;转速纹丝不动&#xff0c;三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/11/3 11:35:49 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年&#xff0c;用它写过嵌入式驱动、做过游戏服务端&#xff0c;也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词&#xff0c;我其实挺感慨的——这门语言的难点从来不是语法多&#xff0c;而是知识点之间的耦合太深…

2026/11/4 6:23:50 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介&#xff1a;亚太天能T109滑盖智能锁产品说明书以PDF格式发布&#xff0c;适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开&#xff0c;先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能&#xff0c;再给出完整安装步骤&…

2026/11/3 10:47:27 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历&#xff1a;翻开源码注释、论文摘要或者一份专业报告&#xff0c;每个字都认识&#xff0c;连在一起却像天书。想找人聊聊&#xff0c;身边要么没人懂&#xff0c;要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型&#xff0c;几秒钟之后&a…

2026/11/3 10:57:33 阅读更多 →

日新闻

周新闻

月新闻