PyTorch翻译官网教程-FAST TRANSFORMER INFERENCE WITH BETTER TRANSFORMER

这篇具有很好参考价值的文章主要介绍了PyTorch翻译官网教程-FAST TRANSFORMER INFERENCE WITH BETTER TRANSFORMER。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

官网链接

Fast Transformer Inference with Better Transformer — PyTorch Tutorials 2.0.1+cu117 documentation

使用 BETTER TRANSFORMER 快速的推理TRANSFORMER

本教程介绍了作为PyTorch 1.12版本的一部分的Better Transformer (BT)。在本教程中,我们将展示如何使用更好的Transformertorchtext进行生产推理。Better Transformer是一个具备生产条件fastpath并且可以加速在CPU和GPU上具有高性能的Transformer模型的部署。对于直接基于PyTorch核心nn.module或基于torchtext的模型,fastpath功能可以透明地工作。

使用PyTorch核心torch.nn.module类TransformerEncoder, TransformerEncoderLayer和MultiHeadAttention的模型,可以通过Better Transformer fastpath 执行加速。此外,torchtext已经更新为使用核心库模块,以受益于fastpath加速。(将来可能会启用其他模块的fastpath执行。)

Better Transformer提供两种类型的加速:

  • 实现CPU和GPU的Native multihead attention(MHA),提高整体执行效率。
  • 利用NLP推理中的稀疏性。由于输入长度可变,输入令牌可能包含大量填充令牌,可以跳过处理,从而显著提高速度。


Fastpath执行受制于一些标准。最重要的是,模型必须在推理模式下执行,并且在不收集梯度信息的输入张量上运行(例如,使用torch.no_grad运行)。

本教程中Better Transformer 特点

  • 加载预训练模型(1.12之前没有Better Transformer)
  • 在CPU上并且没有BT fastpath(仅本机MHA))的情况下 运行和基准测试推断
  • 在设备(可配置)上并且没有BT fastpath(仅本机MHA))的情况下 运行和基准测试推断
  • 启用稀疏性支持
  • 在设备(可配置)上并且没有BT fastpath(仅本机MHA+稀疏性))的情况下 运行和基准测试推断

额外的信息

关于Better Transformer的其他信息可以在PyTorch.Org 博客中找到。A Better Transformer for Fast Transformer Inference.

设置

加载预训练模型

我们按照torchtext.models中的说明从预定义的torchtext模型下载XLM-R模型。我们还将DEVICE设置为执行加速器上的测试。(根据您的环境适当启用GPU执行。)

import torch
import torch.nn as nn

print(f"torch version: {torch.__version__}")

DEVICE = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

print(f"torch cuda available: {torch.cuda.is_available()}")

import torch, torchtext
from torchtext.models import RobertaClassificationHead
from torchtext.functional import to_tensor
xlmr_large = torchtext.models.XLMR_LARGE_ENCODER
classifier_head = torchtext.models.RobertaClassificationHead(num_classes=2, input_dim = 1024)
model = xlmr_large.get_model(head=classifier_head)
transform = xlmr_large.transform()

数据集搭建

我们设置了两种类型的输入:一个小的输入批次和一个具有稀疏性的大的输入批次。

small_input_batch = [
               "Hello world",
               "How are you!"
]
big_input_batch = [
               "Hello world",
               "How are you!",
               """`Well, Prince, so Genoa and Lucca are now just family estates of the
Buonapartes. But I warn you, if you don't tell me that this means war,
if you still try to defend the infamies and horrors perpetrated by
that Antichrist- I really believe he is Antichrist- I will have
nothing more to do with you and you are no longer my friend, no longer
my 'faithful slave,' as you call yourself! But how do you do? I see
I have frightened you- sit down and tell me all the news.`

It was in July, 1805, and the speaker was the well-known Anna
Pavlovna Scherer, maid of honor and favorite of the Empress Marya
Fedorovna. With these words she greeted Prince Vasili Kuragin, a man
of high rank and importance, who was the first to arrive at her
reception. Anna Pavlovna had had a cough for some days. She was, as
she said, suffering from la grippe; grippe being then a new word in
St. Petersburg, used only by the elite."""
]

接下来,我们选择小批量或大批量输入,对输入进行预处理并测试模型。

input_batch=big_input_batch

model_input = to_tensor(transform(input_batch), padding_value=1)
output = model(model_input)
output.shape

最后,我们设置基准迭代计数:

ITERATIONS=10

执行

在CPU上并且没有BT fastpath(仅本机MHA)的情况下 运行和基准测试推断

我们在CPU上运行模型,并收集概要信息:

  • 第一次运行使用传统方式(“slow path”)执行。
  • 第二次运行通过使用model.eval()将模型置于推理模式来启用BT fastpath执行,并使用torch.no_grad()禁用梯度收集。

当模型在CPU上执行时,您可以看到改进(其大小取决于CPU模型)。注意,fastpath配置文件显示了本机TransformerEncoderLayer实现aten::_transformer_encoder_layer_fwd.中的大部分执行时间。
 

print("slow path:")
print("==========")
with torch.autograd.profiler.profile(use_cuda=False) as prof:
  for i in range(ITERATIONS):
    output = model(model_input)
print(prof)

model.eval()

print("fast path:")
print("==========")
with torch.autograd.profiler.profile(use_cuda=False) as prof:
  with torch.no_grad():
    for i in range(ITERATIONS):
      output = model(model_input)
print(prof)


 

在设备(可配置)上并且没有BT fastpath(仅本机MHA))的情况下 运行和基准测试推断

我们检查BT 稀疏性设置:

model.encoder.transformer.layers.enable_nested_tensor

我们禁用BT 稀疏性:

model.encoder.transformer.layers.enable_nested_tensor=False


我们在DEVICE上运行模型,并收集DEVICE上本机MHA执行的配置文件信息:

  • 第一次运行使用传统方式(“slow path”)执行。
  • 第二次运行通过使用model.eval()将模型置于推理模式来启用BT fastpath执行,并使用torch.no_grad()禁用梯度收集。

当在GPU上执行时,你应该看到一个显著的加速,特别是对于包含稀疏性的大输入批处理设置:

model.to(DEVICE)
model_input = model_input.to(DEVICE)

print("slow path:")
print("==========")
with torch.autograd.profiler.profile(use_cuda=True) as prof:
  for i in range(ITERATIONS):
    output = model(model_input)
print(prof)

model.eval()

print("fast path:")
print("==========")
with torch.autograd.profiler.profile(use_cuda=True) as prof:
  with torch.no_grad():
    for i in range(ITERATIONS):
      output = model(model_input)
print(prof)

总结

在本教程中,我们介绍了使用 Better Transformer fastpath快速的transformer 推理,在torchtext 中使用PyTorch核心的 Better Transformer包支持Transformer Encoder 模型。在确认BT fastpath可用性的前提下,我们已经演示了 Better Transformer 的使用。我们已经演示并测试了BT fastpath 执行模式·、本机MHA执行和BT稀疏性加速的使用。文章来源地址https://www.toymoban.com/news/detail-645124.html

到了这里,关于PyTorch翻译官网教程-FAST TRANSFORMER INFERENCE WITH BETTER TRANSFORMER的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • PyTorch翻译官网教程5-BUILD THE NEURAL NETWORK

    Build the Neural Network — PyTorch Tutorials 2.0.1+cu117 documentation 神经网络由操作数据的层/模块组成,torch.nn 命名空间提供了构建自己的神经网络所需的所有构建块。PyTorch中的每个模块都是nn.Module 的子类。神经网络本身就是一个由其他模块(层)组成的模型.这种嵌套结构允许轻松地构建

    2024年02月12日
    浏览(39)
  • PyTorch翻译官网教程6-AUTOMATIC DIFFERENTIATION WITH TORCH.AUTOGRAD

    Automatic Differentiation with torch.autograd — PyTorch Tutorials 2.0.1+cu117 documentation 当训练神经网络时,最常用的算法是方向传播算法。在该算法中,根据损失函数与给定参数的梯度来调整模型参数(权重)。 为了计算这些梯度,PyTorch有一个内置的微分引擎,名为torch.autograd。它支持任

    2024年02月16日
    浏览(35)
  • PyTorch翻译官网教程8-SAVE AND LOAD THE MODEL

    Save and Load the Model — PyTorch Tutorials 2.0.1+cu117 documentation 在本节中,我们将了解如何通过保存、加载和运行模型预测来持久化模型状态。 PyTorch模型将学习到的参数存储在一个名为state_dict的内部状态字典中。这些可以通过 torch.save 方法持久化 输出 要加载模型权重,需要首先创

    2024年02月16日
    浏览(29)
  • PyTorch翻译官网教程-DEPLOYING PYTORCH IN PYTHON VIA A REST API WITH FLASK

    Deploying PyTorch in Python via a REST API with Flask — PyTorch Tutorials 2.0.1+cu117 documentation 在本教程中,我们将使用Flask部署PyTorch模型,并开放用于模型推断的REST API。特别是,我们将部署一个预训练的DenseNet 121模型来检测图像。 这是关于在生产环境中部署PyTorch模型的系列教程中的第一篇

    2024年02月16日
    浏览(34)
  • PyTorch翻译官网教程-NLP FROM SCRATCH: CLASSIFYING NAMES WITH A CHARACTER-LEVEL RNN

    NLP From Scratch: Classifying Names with a Character-Level RNN — PyTorch Tutorials 2.0.1+cu117 documentation 我们将建立和训练一个基本的字符级递归神经网络(RNN)来分类单词。本教程以及另外两个“from scratch”的自然语言处理(NLP)教程 NLP From Scratch: Generating Names with a Character-Level RNN 和 NLP From Scratch

    2024年02月12日
    浏览(53)
  • PyTorch翻译官网教程-NLP FROM SCRATCH: GENERATING NAMES WITH A CHARACTER-LEVEL RNN

    NLP From Scratch: Generating Names with a Character-Level RNN — PyTorch Tutorials 2.0.1+cu117 documentation 这是我们关于“NLP From Scratch”的三篇教程中的第二篇。在第一个教程中 /intermediate/char_rnn_classification_tutorial 我们使用RNN将名字按其原始语言进行分类。这一次,我们将通过语言中生成名字。

    2024年02月13日
    浏览(36)
  • GPT最佳实践-翻译官网

    https://platform.openai.com/docs/guides/gpt-best-practices/gpt-best-practices 本指南分享了从 GPT 获得更好结果的策略和战术。有时可以结合使用此处描述的方法以获得更大的效果。我们鼓励进行实验以找到最适合您的方法。 此处演示的一些示例目前仅适用于我们功能最强大的模型 gpt-4 .如果

    2024年02月09日
    浏览(38)
  • 【python】python结合js逆向,让有道翻译成为你的翻译官,实现本地免费实时翻译

    ✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN新星创作者等等。 🏆《博客》:Python全栈,前后端开发,人工智能,js逆向,App逆

    2024年03月23日
    浏览(34)
  • 基于transformer的Seq2Seq机器翻译模型训练、预测教程

    机器翻译(Machine Translation, MT)是一类将某种语言(源语言,source language)的句子 x x x 翻译成另一种语言(目标语言,target language)的句子 y y y 的任务。机器翻译的相关研究早在上世纪50年代美苏冷战时期就开始了,当时的机器翻译系统是基于规则的,利用两种语言的单词、

    2024年02月03日
    浏览(32)
  • FAST协议解析3 FIX Fast Tutorial翻译 HelloWorld示例

    Fields in FAST do not have a fixed size and do not use a field separator. Instead, there is a notion of a stop bit (the high order bit on each byte of the message acts as a stop bit) signaling the end of the field. All of the above concepts used together allow the sender to compress a message (sometimes as much as 90%) and the receiver to restore the origina

    2024年02月03日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包