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/7/28 18:21:10 阅读更多 →
终极指南:如何免费解锁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/7/28 18:21:10 阅读更多 →
Playwright自定义Fixtures:解决测试数据管理与环境隔离的工程实践

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

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

2026/7/28 18:21:10 阅读更多 →

最新新闻

JVS视角:工信部新提的“小快轻准“,到底在说什么

JVS视角:工信部新提的“小快轻准“,到底在说什么

最近工信部出了一份文件——《"小快轻准"数字化产品和服务培育指引&#xff08;2026年版&#xff09;》。四个字&#xff1a;小、快、轻、准。看着像口号&#xff0c;但细看内容&#xff0c;其实是对过去几年制造业数字化转型路线的一次方向性调整。过去几年行业里的…

2026/7/28 18:33:13 阅读更多 →
全球首个3T级模型Kimi K3开源,魔搭社区同步上线

全球首个3T级模型Kimi K3开源,魔搭社区同步上线

7月28日&#xff0c;Kimi K3已上线魔搭社区&#xff0c;用户可在魔搭社区官网一键下载。作为全球首个开放的 3T 级模型&#xff0c;Kimi K3 总参数量达 2.8T&#xff0c;具备原生视觉能力与 100 万 token 上下文窗口&#xff0c;面向长程编码、知识工作与推理等前沿智能场景设计…

2026/7/28 18:33:13 阅读更多 →
虚拟机无法连接虚拟设备sata0:1

虚拟机无法连接虚拟设备sata0:1

以下仅作为自己的一个尝试设置&#xff0c;验证对自己的虚拟机问题有效。在设置里面修改CD/DVD(SATA)&#xff0c;改为使用ISO影像文件。改完后虚拟机开机黑屏的问题也解决了。同时我虚拟机设置硬件设备中删除了打印机。这个主要是因为虚拟机每次开启的时候总是消息提醒找不到打…

2026/7/28 18:33:13 阅读更多 →
Manjaro升级后中文乱码的解决办法(2019-07-22)

Manjaro升级后中文乱码的解决办法(2019-07-22)

刚日常升级了一下Manjaro,结果悲催了&#xff0c;界面所有中文变成小方格&#xff0c;想切换回英文版都找不到地方了在网上找到了解决办法&#xff0c;在此分享一下 其实就是安装一个字体就可以了 sudo pacman -S wqy-microhei亲测有效

2026/7/28 18:33:13 阅读更多 →
POJO、PO、VO、DAO、JavaBean

POJO、PO、VO、DAO、JavaBean

Java中对象的作用&#xff1a; 1. POJO&#xff1a;Plain Old Java Objects: 简单无规则java对象。只有属性和get、set方法。它包含vo和po 2. PO:persistent Object:持久化对象&#xff0c;POJO持久化之也叫POJO&#xff0c;一般项目中放在Entity包下的类&#xff0c;也就是PO …

2026/7/28 18:33:13 阅读更多 →
6岁患儿临床试验离世后:仇子龙Nature论文事件

6岁患儿临床试验离世后:仇子龙Nature论文事件

一则国际顶刊调查报道&#xff0c;揭开一场罕见病个体化基因编辑人体试验的悲剧&#xff1b;紧随其后&#xff0c;学术博主公开质疑相关《Nature》论文数据存在异常。上海交通大学医学院仇子龙团队 CHD3 碱基编辑研究事件&#xff0c;同时牵动人体临床试验伦理监管、学术论文数…

2026/7/28 18:32:13 阅读更多 →

日新闻

告别臃肿!3步让你的暗影精灵笔记本重获新生

告别臃肿!3步让你的暗影精灵笔记本重获新生

告别臃肿&#xff01;3步让你的暗影精灵笔记本重获新生 【免费下载链接】OmenSuperHub Control Omen laptop performance, fan speeds, and keyboard lighting, and unlock power limits. 项目地址: https://gitcode.com/gh_mirrors/om/OmenSuperHub 你是否也曾为官方Om…

2026/7/28 0:00:43 阅读更多 →
RAG必踩坑!财报法规检索不准?这款开源工具让答案浮出水面,准确率飙升98.7%!

RAG必踩坑!财报法规检索不准?这款开源工具让答案浮出水面,准确率飙升98.7%!

做 RAG 的人应该都踩过这个致命的坑&#xff1a;把几百页的财报、法规、技术手册扔给向量库&#xff0c;问一个具体问题&#xff0c;搜出来的全是沾边但没用的内容 —— 关键信息要么被硬切块拆碎了&#xff0c;要么藏在几十条结果的最下面。语义相似≠真正相关&#xff0c;这个…

2026/7/28 0:00:43 阅读更多 →
抖音视频文案提取工具全指南:免费2026版、手机App、在线工具一网打尽

抖音视频文案提取工具全指南:免费2026版、手机App、在线工具一网打尽

2026年做短视频运营&#xff0c;从抖音上扒文案早就不是偷偷抄笔记的事了。我刚开始做内容的时候&#xff0c;每天刷半小时抖音&#xff0c;手动把爆款视频的口播敲进备忘录&#xff0c;一条2分钟的视频得花十来分钟&#xff0c;碰到语速快的还要反复回听。后来试了一圈工具&am…

2026/7/28 0:00:43 阅读更多 →

周新闻

深度学习道路桥梁裂缝检测系统 道路桥梁裂缝检测数据集 道路桥梁病害识别检测数据集

深度学习道路桥梁裂缝检测系统 道路桥梁裂缝检测数据集 道路桥梁病害识别检测数据集

深度学习道路桥梁裂缝检测系统 数据集6000张 完整源码已标注数据集训练好的模型环境配置教程程序运行说明文档&#xff0c;可以直接使用&#xff01;系统支持图片、视频、摄像头等多种方式检测裂缝&#xff0c;功能强大实用。 1数据集6000张 8各类别

2026/7/28 12:04:22 阅读更多 →
深度学习YOLO模型如何训练 PUBG 绝地求生目标检测数据集

深度学习YOLO模型如何训练 PUBG 绝地求生目标检测数据集

pubg数据集 精选原图1.42万数据 1.49万标签 无任何重复、算法增强或冗余图像&#xff01; pubg绝地求生目标检测数据集 1分类&#xff1a;e_body&#xff0c;14905个标签&#xff0c;txt格式 共计14244张图&#xff0c;99%为640*640尺寸图像 适合yolo目标检测、AI训练关键词&am…

2026/7/28 8:29:16 阅读更多 →
Apex英雄目标检测数据集 深度学习框架YOLO如何训练APEX数据集

Apex英雄目标检测数据集 深度学习框架YOLO如何训练APEX数据集

Apex检测数据集数据集详情检测类别&#xff1a; allies enemy tag图片总量&#xff1a;7247张训练集&#xff1a;5139张验证集&#xff1a;1425张测试集&#xff1a;683张标注状态&#xff1a;全部已标注&#xff0c;即拿即用数据格式&#xff1a;支持YOLO格式及其他格式&#…

2026/7/28 5:03:42 阅读更多 →

月新闻