[NLP] The Annotated Transformer 代码修正
1. RuntimeError: "exp" not implemented for 'torch.LongTensor'
class PositionalEncoding(nn.Module)
div_term = torch.exp(torch.arange(0., d_model, 2) *
-(math.log(10000.0) / d_model))
将 “0” 改为 “0.”
否则会报错:RuntimeError: "exp" not implemented for 'torch.LongTensor'
2. RuntimeError: expected type torch.FloatTensor but got torch.LongTensor
class PositionalEncoding(nn.Module)
position = torch.arange(0., max_len).unsqueeze(1)
将 “0” 改为 “0.”
否则会报错:
pe[:, 0::2] = torch.sin(position * div_term)
RuntimeError: expected type torch.FloatTensor but got torch.LongTensor
3. UserWarning: nn.init.xavier_uniform is now deprecated in favor of nn.init.xavier_uniform_.
def make_model
nn.init.xavier_uniform_(p)
将“nn.init.xavier_uniform(p)” 改为 “nn.init.xavier_uniform_(p)”
否则会提示:UserWarning: nn.init.xavier_uniform is now deprecated in favor of nn.init.xavier_uniform_.
4. UserWarning: size_average and reduce args will be deprecated, please use reduction='sum' instead.
class LabelSmoothing
self.criterion = nn.KLDivLoss(reduction='sum')
将 “self.criterion = nn.KLDivLoss(size_average=False)” 改为 “self.criterion = nn.KLDivLoss(reduction='sum')”
否则会提示:UserWarning: size_average and reduce args will be deprecated, please use reduction='sum' instead.
5. IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number
class SimpleLossCompute
return loss.item() * norm
将 “loss.data[0]” 改为 loss.item(),
否则会报错:IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number
6. floating point exception (core dumped)
直接运行“A First Example”会报错:floating point exception (core dumped)
参考的修改方法:https://github.com/harvardnlp/annotated-transformer/issues/26,该方法中,修改 run_epoch 函数,将计数值转换为numpy。方法:.detach().numpy() 或者直接 .numpy()
但是我试了仍有问题。最后需要将gpu上的先移到cpu中,再进行numpy转换。
以下是自己调整后的代码,是可以正确运行的:
def run_epoch(data_iter, model, loss_compute, epoch = 0):
"Standard Training and Logging Function"
start = time.time()
total_tokens = 0
total_loss = 0
tokens = 0
for i, batch in enumerate(data_iter):
out = model.forward(batch.src, batch.trg, batch.src_mask, batch.trg_mask)
loss = loss_compute(out, batch.trg_y, batch.ntokens) total_loss += loss.detach().cpu().numpy()
total_tokens += batch.ntokens.cpu().numpy()
tokens += batch.ntokens.cpu().numpy()
if i % 50 == 1:
elapsed = time.time() - start
print("Epoch Step: %d Loss: %f Tokens per Sec: %f" % (i, loss.detach().cpu().numpy() / batch.ntokens.cpu().numpy(), tokens / elapsed))
start = time.time()
tokens = 0
return total_loss / total_tokens
7. loss 均为整数
class SimpleLossCompute
在运行“A First Example” 时, 结果显示的 loss 全部是整数,这就很奇怪了。测试后发现,是 class SimpleLossCompute中的返回值的问题,norm这个tensor是int型的,虽然loss.item()是浮点数,但是return loss.item() * norm的值仍是int型tensor.
修改方法:将norm转为float再进行乘法运算:
return loss.item() * norm.float()
[NLP] The Annotated Transformer 代码修正的更多相关文章
- 【转载/修改】ScrollLayout代码修正,追加模仿viewpager滚动速度
组件作用为类似ViewPager但直接插视图的横向滚动容器. 修改自:http://blog.csdn.net/yaoyeyzq/article/details/7571940 在该组件基础上修正了滚 ...
- [The Annotated Transformer] Iterators
Iterators 对torchtext的batch实现的修改算法原理 Batching matters a ton for speed. We want to have very evenly di ...
- [原创]PHP代码修正之CodeSniffer
目录 参考链接 介绍 安装 使用 命令行模式 PHPStorm 让编辑器使用PSR-2标准 集成phpcbf 参考链接 PHP开发规范之使用phpcbf脚本自动修正代码格式 在PhpStorm中使用P ...
- 对于国嵌上学期《一跃进入C大门》Mini2440的代码修正
摸索了几天,加了无数的群,病急乱投医式地问了好多个人,终于改对了代码. 下面先贴出给的范例代码 这是C语言代码,是没有错的. 那么出错的地方就在start.S部分 很明显,MPLLCON地址错误,正确 ...
- NLP之基于Transformer的句子翻译
Transformer 目录 Transformer 1.理论 1.1 Model Structure 1.2 Multi-Head Attention & Scaled Dot-Produc ...
- vscode vue 项目保存运行lint进行代码修正
{ "editor.tabSize": 2, "files.associations": { "*.vue": "vue" ...
- NLP整体流程的代码
import nltk import numpy as np import re from nltk.corpus import stopwords # 1 分词1 text = "Sent ...
- nlp英文的数据清洗代码
1.常用的清洗方式 #coding=utf-8 import jieba import unicodedata import sys,re,collections,nltk from nltk.ste ...
- Transformer各层网络结构详解!面试必备!(附代码实现)
1. 什么是Transformer <Attention Is All You Need>是一篇Google提出的将Attention思想发挥到极致的论文.这篇论文中提出一个全新的模型,叫 ...
随机推荐
- AC自动机练习题1:地图匹配
AC自动机板子,学习之前要是忘记了就看一下 1465: [AC自动机]地图匹配 poj1204 时间限制: 1 Sec 内存限制: 256 MB提交: 78 解决: 46[提交] [状态] [讨论 ...
- Eslint报错整理与解决方法
1.‘Unexpected tab character’ 字面意思理解呢就是意想不到的制表符,当时出现的时候就是我习惯的使用Tab键去打空格,但是eslint默认不认可Tab,所以解决方法很简单: 在 ...
- Web前端开发HTML基础
HTML是英文Hyper Text Mark-up Language(超文本标记语言)的缩写,他是一种制作万维网页面标准语言(标记),相当于定义统一的一套规则,大家都来遵守他,这样就可以让浏览器根据标 ...
- 福建工程学院第十四届ACM校赛J题题解
第六集,想不到你这个浓眉大眼的都叛变革命了 题意: 给你两个只包含01的字符串S和T,问你在允许一次错误的情况下,T是否能成为S的子串 思路: 这个问题的解法挺多,我是用fft匹配的,也比较简单,针对 ...
- Scala学习二——控制结构和函数
一.if表达式有值 val s=if(x>0) 1 else -1,相当于Java中x>0?1:-1(不过不拿呢个在?:中插入语句),而且Scala中可以用混合类型(如if (x>0 ...
- org.apache.shiro.realm.AuthorizingRealm - No cache or cacheManager properties have been set. Authorization cache cannot be obtained.
项目中用spring shiro来处理权限的问题,但是启动的时候会打印如下日志 org.apache.shiro.realm.AuthorizingRealm - No cache or cacheM ...
- C数据结构排序算法——希尔排序法用法总结(转http://www.cnblogs.com/skywang12345/p/3597597.html)
希尔排序介绍 希尔排序(Shell Sort)是插入排序的一种,它是针对直接插入排序算法的改进.该方法又称缩小增量排序,因DL.Shell于1959年提出而得名. 希尔排序实质上是一种分组插入方法.它 ...
- JQ向上取整 和向下取整 四舍五入
向上取整 var a = 23.2325236 var abc = Math.ceil(a); //注意:Math.ceil(a)不要单独写一行,否则向上取整失败 abc = 24; ...
- linux中查看文件夹结构的小工具
tree命令是Linux/UNIX系统中常用的命令,可以非常方便地查看文件夹的结构,并且以树形目录的形式展示 在Ubuntu中安装 sudo apt-get install tree 在CentOS中 ...
- appium基础之简单的小例子
appium环境搭建了,当然也要开始用起来了,记录一下学习的过程 遇到问题 1.The permission to start '.ui.home.view.HomeActivity' activit ...