Iterators

对torchtext的batch实现的修改算法原理

Batching matters a ton for speed. We want to have very evenly divided batches, with absolutely minimal padding. To do this we have to hack a bit around the default torchtext batching. This code patches their default batching to make sure we search over enough sentences to find tight batches.

这里是对torchtext中默认的batching操作进行的优化修改。

参考:https://towardsdatascience.com/how-to-use-torchtext-for-neural-machine-translation-plus-hack-to-make-it-5x-faster-77f3884d95

Torchtext本身已经很好了,并且sort_key使得dataset中的数据排序,这样batching后序列长度相近的会被放在同一个batch中,可以很大程度上降低padding的个数。

但是下面代码又进行了优化:根据每个batch中序列的最大长度,动态更改batch_size,使得可以更好的利用计算资源。

举个例子:

假设你的RAM每个iteration可以处理1500个tokens, batch_size = 20, 那么只有当batch中的序列长度为sequence length = 1500 / 20 = 75时,才可以将计算资源利用完全。

现实中,每个batch的sequence length的显然是在变化的,那么如果希望尽量多的利用计算资源,就需要可以动态调整当前的batch_size.

Transformer中的MyIterator重载了data.Iterator中的create_batches函数:

 class MyIterator(data.Iterator):
def create_batches(self):
if self.train:
def pool(d, random_shuffler):
for p in data.batch(d, self.batch_size * 100):
p_batch = data.batch(
sorted(p, key=self.sort_key),
self.batch_size, self.batch_size_fn)
for b in random_shuffler(list(p_batch)):
yield b
self.batches = pool(self.data(), self.random_shuffler) else:
self.batches = []
for b in data.batch(self.data(), self.batch_size,
self.batch_size_fn):
self.batches.append(sorted(b, key=self.sort_key)) def rebatch(pad_idx, batch):
"Fix order in torchtext to match ours"
src, trg = batch.src.transpose(0, 1), batch.trg.transpose(0, 1)
return Batch(src, trg, pad_idx)

pool函数

其中pool函数的功能与https://github.com/pytorch/text/blob/master/torchtext/data/iterator.py中定义的class BucketIterator(Iterator)的pool函数功能类似。

1. 将原始的data分成大小为 100 * batch_size的一些chunks => (以上迭代 p 即为 每个chunk)

2. 在每个chunk中根据 sort_key 对examples进行排序,并对每个chunk按照batch_size分成100个batch =>

( p_batch = data.batch( sorted(p, key=self.sort_key), self.batch_size, self.batch_size_fn) )

3. 将这些chunks进行shuffle  => (random_shuffler(list(p_batch)))

4. 在每个chunk中再把examples分成 大小为 batch_size 的 100 个 batch => (以上 b 即为每个 batch)

5. 生成器每次 yield一个batch  => (yield b)

[The Annotated Transformer] Iterators的更多相关文章

  1. [NLP] The Annotated Transformer 代码修正

    1. RuntimeError: "exp" not implemented for 'torch.LongTensor' class PositionalEncoding(nn. ...

  2. 【译】图解Transformer

    目录 从宏观上看Transformer 把张量画出来 开始编码! 从宏观上看自注意力 自注意力的细节 自注意力的矩阵计算 "多头"自注意力 用位置编码表示序列的顺序 残差 解码器 ...

  3. 深入理解Transformer及其源码解读

    深度学习广泛应用于各个领域.基于transformer的预训练模型(gpt/bertd等)基本已统治NLP深度学习领域,可见transformer的重要性.本文结合<Attention is a ...

  4. Transformer模型---encoder

    一.简介 论文链接:<Attention is all you need> 由google团队在2017年发表于NIPS,Transformer 是一种新的.基于 attention 机制 ...

  5. zz全面拥抱Transformer

    放弃幻想,全面拥抱Transformer:自然语言处理三大特征抽取器(CNN/RNN/TF)比较 在辞旧迎新的时刻,大家都在忙着回顾过去一年的成绩(或者在灶台前含泪数锅),并对2019做着规划,当然也 ...

  6. Transformer的PyTorch实现

    Google 2017年的论文 Attention is all you need 阐释了什么叫做大道至简!该论文提出了Transformer模型,完全基于Attention mechanism,抛弃 ...

  7. 动手学Transformer

    动手实现Transformer,所有代码基于tensorflow2.0,配合illustrated-transformer更香. 模型架构 Encoder+Decoder Encoder Decode ...

  8. 深入浅出Transformer

    Transformer Transformer是NLP的颠覆者,它创造性地用非序列模型来处理序列化的数据,而且还获得了大成功.更重要的是,NLP真的可以"深度"学习了,各种基于tr ...

  9. 从Word Embedding到Bert模型—自然语言处理中的预训练技术发展史(转载)

    转载 https://zhuanlan.zhihu.com/p/49271699 首发于深度学习前沿笔记 写文章   从Word Embedding到Bert模型—自然语言处理中的预训练技术发展史 张 ...

随机推荐

  1. java使用顺序数组实现二叉树

    顺序数组实现二叉树 实现原理 对于下标为index的节点其满足 1.左孩子节点的下标为2index+1 2.右孩子节点的下标为2index+2 代码实现 package tree; public cl ...

  2. Eratosthenes筛法

    复杂度为nlogn. 算法思想为:枚举1~sqrt(n),然后把每一个数的倍数都都打上不是素数的标记. 还要特别注意0,1不是素数,打标记枚举到i*k<=n. 代码如下 #include< ...

  3. 3的倍数 或运算构造x(牛客第四场)-- triples I

    题意: 给你一个数,希望你能用最少的3的倍数或运算成它,让你输出答案. 思路: 进制%3有规律,1.2.4.8.16%3是1.2.1.2.1 ... 利用这一点分情况取一些位合成一些数就是答案了. # ...

  4. 前端 使用localStorage 和 Cookie相结合的方式跨页面传递参数

    A页面 html代码: 姓名:<input type="text" id="name1"> 年龄:<input type="text ...

  5. 面向对象-this关键字的内存图解

    /* 标准的代码改进版 this:哪个对象调用那个方法,this就代表那个对象 */ class Student { private String name; private int age; pub ...

  6. luogu题解 P2212 【浇地Watering the Fields】

    题目链接: https://www.luogu.org/problemnew/show/P2212 思路: 一道最小生成树裸题(最近居然变得这么水了),但是因为我太蒻,搞了好久,不过借此加深了对最小生 ...

  7. 如何自己搭建DNS服务器

    DNS服务器是计算机域名系统 (Domain Name System 或Domain Name Service) 的缩写,它是由 解析器和域名服务器组成的.域名服务器是指保存有该网络中所有主机的域名和 ...

  8. tomcat访问日志

    * %a - Remote IP address # 远程ip地址 * %A - Local IP address # 本地ip地址 * %b - Bytes sent, excluding HTTP ...

  9. java 文件上传与解析(excel,txt)

    excel上传与解析 https://blog.csdn.net/zsysu_it/article/details/79074067 txt解析 https://blog.csdn.net/CSDNw ...

  10. C++使用socket传输图片

    Client: #include <WinSock2.h> #include <Windows.h> #include <stdio.h> #pragma comm ...