NVIDIA NeMo 简介—教程和示例

每日分享最新,最流行的软件开发知识与最新行业趋势,希望大家能够一键三连,多多支持,跪求关注,点赞,留言。

本文,我们将向您展示如何使用 NVIDIA Nemo 运行实际的自然语言处理模型。

NVIDIA NeMo 是一个用于构建新的最先进的对话式 AI 模型的工具包。NeMo 有自动语音识别 (ASR)、自然语言处理 (NLP) 和文本到语音 (TTS) 模型的单独集合。

NVIDIA NeMo 简介—教程和示例

每个集合都包含预构建的模块,其中包括训练数据所需的一切。每个模块都可以轻松定制、扩展和组合,以创建新的对话式 AI 模型架构。那么让我们简单解释一下什么是 ASR、NLP 和 TTS 模型。

ASR是Automatic Speech Recognition的缩写,是机器学习的一个子领域,专注于将口语翻译成文本格式的技术。这些方法背后的主要好处是允许在给定的语音消息中提供更好的单词搜索能力。

当今世界普遍使用 ASR 模型;最著名的实际用途包括苹果著名的语音交互系统 Siri。

自然语言处理( NLP )是一个人工智能子领域,能够理解和处理不同的语言格式以提取独特的见解和模式。

最常见的用途包括推荐系统,其中自然语言处理技术可以将不同的项目、对象或服务分类为不同的类别。此外,如果用户喜欢某些项目类别,推荐系统可以推荐相同或相似类别的项目。

TTS是Text-to-Speech 的缩写,与前面提到的自动语音识别领域完全相反。在 ASR 中,机器学习模型接收语音消息并将其转换为文本格式。同时,Text-to-Speech 模型接收文本格式的数据并将其转换为语音格式。

正如前面提到的 Siri 模型,ASR 系统用于将用户的语音转换为文本以供 Siri 理解,然后 TTS 模型也用于 Siri 以语音格式回答。

在本文的以下部分中,我们将向您展示如何使用 NVIDIA Nemo 运行实际的自然语言处理模型。

使用 NVIDIA NeMo 的先决条件
在使用 NeMo 之前,假设您满足以下先决条件。

您有 Python 版本 3.6、3.7 或 3.8。
你有 Pytorch 版本 1.8.1。
您可以使用 NVIDIA GPU 进行训练。
使用 NLP 构建机器学习模型
使用自然语言处理 (NLP),我们将构建一个能够检测给定句子情绪的机器学习模型。情绪旨在将给定的句子分类为情绪上的积极或消极。

例如,积极的情绪是“他工作非常努力,取得了伟大的成就”。另一方面,负面情绪是“他的表现不够好,他没有达到目标”。

数据集
本教程中使用的文本分类模型要求数据集以 TAB 分隔文件 (.tsv) 格式存储。以下是数据应存储的格式。

[WORD][SPACE][WORD][SPACE][WORD][TAB][LABEL]

为了更好地解释给定的格式,让我们以数据集的第一行为例:

第一个数据点是:

hide new secretions from the parental units: 0

因此,数据必须以下面给出的格式存储:

[hide][SPACE][new][SPACE][secretions][SPACE][from][SPACE][the][SPACE][parental][SPACE][units][TAB][0]

我们的数据集仅包含 2 列,即Sentence和Label 列。句子列(自变量)将用作我们模型的输入值。此列包含给定用户撰写的实际电影评论。

对于输出变量,我们将使用标签列(因变量),它表示先前写入的消息的实际情绪(正面或负面)。标签列通常由人类用户手动填写。

NVIDIA NeMo 简介—教程和示例

NVIDIA NeMo NLP 教程
查看本教程中使用的测试分类情感分析示例。

1. 选择在本地或在 Google Colab 上运行模型
“”” You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.
Instructions for setting up Colab are as follows: Open a new Python 3 notebook. Import this notebook from GitHub (File -> Upload Notebook -> “GITHUB” tab -> copy/paste GitHub URL) Connect to an instance with a GPU (Runtime -> Change runtime type -> select “GPU” for hardware accelerator) Run this cell to set up dependencies. “”” # If you’re using Google Colab and not running locally, run this cell # install NeMo BRANCH = ‘r1.10.0’ !python -m pip install git+
https://github.com/NVIDIA/NeMo…;BRANCH#egg=nemo_toolkit[nlp]

2.安装ipywidgets并升级Jupyter Notebook
如果您不使用 Colab,则可能需要升级 Jupyter notebook 以避免出现以下错误:

# ‘ImportError: IProgress not found. Please update jupyter and ipywidgets.’

安装 ipywidgets 扩展

! pip install ipywidgets ! jupyter nbextension enable –py widgetsnbextension # Please restart the kernel after running this cell

请注意,当您使用 Google Colab 运行模型时,始终需要遵循上述 2 个步骤。

3. 导入需要的库
作为训练我们模型的实际第一步,我们需要导入所有需要的库和包。

您之前可能使用过的一些必要库可能包括torch和pytorch库。在这个模型中,我们还将使用几个 NeMo 包,例如nemo.collections和nemo.utils.exp_manager包。

from nemo.collections import nlp as nemo_nlp from nemo.utils.exp_manager import exp_manager
import os import wget import torch import pytorch_lightning as pl from omegaconf import OmegaConf

4. 创建数据和工作目录
在这一步中,我们将通过创建 2 个新目录来保存我们的工作。您可以选择不创建或创建并重命名您自己的目录,但始终确保将旧目录名称替换为代码中的新目录名称。

最后两行命令以“!”开头 将自动安装数据集,然后将其解压缩到指定的数据目录文件中。为您节省一些不必要的工作。

DATA_DIR = “DATA_DIR” WORK_DIR = “WORK_DIR” os.environ[‘DATA_DIR’] = DATA_DIR
os.makedirs(WORK_DIR, exist_ok=True) os.makedirs(DATA_DIR, exist_ok=True)
! wget <a href=”
https://dl.fbaipublicfiles.com/glue/data/SST-2.zip” target=”_self”>
https://dl.fbaipublicfiles.com/glue/data/SST-2.zip </a>! unzip -o SST-2.zip -d {DATA_DIR}

5.过滤和清理数据
由于 Nemo 数据集有自己独特的格式,因此应插入或修改任何使用的数据集以适应这种所需的格式。在我们的数据集中,我们需要删除额外的标题行。这是使用 sed 1d 命令完成的,该命令从指定数据集中删除第一列。请注意,我们从训练和验证数据集中删除了标题行,只是因为测试数据集没有这个问题。

! sed 1d {DATA_DIR}/SST-2/train.tsv > {DATA_DIR}
/SST-2/train_nemo_format.tsv ! sed 1d {DATA_DIR}/SST-2/dev.tsv > {DATA_DIR}
/SST-2/dev_nemo_format.tsv ! ls -l {DATA_DIR}/SST-2 To print the first 5 lines of each data set: print(‘Contents (first 5 lines) of train.tsv:’) ! head -n 5 {DATA_DIR}
/SST-2/train_nemo_format.tsv

print(‘nContents (first 5 lines) of test.tsv:’) ! head -n 5 {DATA_DIR}/SST-2/test.tsv

6.下载配置文件
NVIDIA Nemo 模型使用配置系统工作,其中保存和使用包含运行模型所需的所有必要数据的配置文件。本教程中编写的大部分代码都会更新并向该文件添加新数据。

首先,NVIDIA 为您提供了一个可以立即使用的基本 YAML 配置文件。当然,从模型到模型都需要一些修改和调整。配置文件将下载到指定目录。

# download the model’s configuration file MODEL_CONFIG = “
text_classification_config.yaml” CONFIG_DIR = WORK_DIR + ‘/configs/’ os.makedirs(CONFIG_DIR, exist_ok=True) if not os.path.exists(CONFIG_DIR + MODEL_CONFIG): print(‘Downloading config file…’) wget.download(f'<a href=”
https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}
/examples/nlp/text_classification/conf/”>
https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}
/examples/nlp/text_classification/conf/</a>’ + MODEL_CONFIG, CONFIG_DIR) print(‘Config file downloaded!’) else: print (‘config file already exists’) config_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}’ print(config_path) config = OmegaConf.load(config_path)

7. 配置给定模型中的类数
dataset.num_classes 数字表示我们数据集中使用的不同变量值。在这一步中,我们选择我们的值等于 2,因为我们的标签列可以有 0(负)或 1(正)值。例如,如果还有一个中性值,那么我们应该有 num.classes=3。


config.model.dataset.num_classes=2

8. 将训练和验证文件路径传递给配置文件。
下载和修改(删除标题行)我们的数据集文件后,我们会将它们给定的路径传递到我们的配置文件中。这有点类似于更知名的 pd.read_csv(“file path”) 函数。


config.model.train_ds.file_path = os.path.join(DATA_DIR, ‘
SST-2/train_nemo_format.tsv’)
config.model.validation_ds.file_path = os.path.join(DATA_DIR, ‘SST-2/dev_nemo_format.tsv’) # Name of the .nemo file where trained model will be saved. config.save_to = ‘trained-model.nemo’ config.export_to = ‘trained-model.onnx’

9. 在配置文件中配置 Trainer String
检查是否提供了 GPU,如果有,我们将使用它。


config.trainer.accelerator = ‘gpu’ if torch.cuda.is_available() else ‘cpu’ config.trainer.devices = 1

使用 Colab 时禁用分布式训练以防止错误。

config.trainer.strategy = None

设置最大步数以减少训练时间。当达到 max_epochs 时,训练停止。

config.trainer.max_epochs = 1

使用配置的 trainer 部分实例化 PT Trainer 对象。

trainer = pl.Trainer(**config.trainer)

10. 处理记录和保存检查点
Nemo 为其用户提供了自动处理日志记录和保存检查点任务的能力。

由于一个trainer对象的experiment manager不能设置两次。我们在这里重复训练器创建代码,以防止在多次执行此单元格时出错。

trainer = pl.Trainer(**config.trainer)

exp_dir 指定存储检查点和日志的路径;它的默认值为“./nemo_experiments”。exp_dir 提供了当前实验的路径以便于访问。

exp_dir = exp_manager(trainer, config.exp_manager)

11. 指定 BERT-Like 模型并创建它
在指定 BERT-base-uncased 模型名称后,我们会将配置和训练器参数传递给我们的最终模型。BERT代表来自 Transformers 的双向编码器表示,它是由 Google 开发的用于自然语言处理预训练的基于转换器的机器学习技术。

将配置中的“
model.language_model.pretrained_model_name”参数设置为bert-base-uncased模型。



config.model.language_model.pretrained_model_name = “bert-base-uncased”

创建实际模型。

model =
nemo_nlp.models.TextClassificationModel(cfg=config.model, trainer=trainer)

12. 运行模型
使用 trainer.fit() 函数,模型的实际训练开始。

trainer.fit(model) model.save_to(config.save_to)

13. 模型评估
从训练中提取最佳检查点的路径;您可以将其更新到任何检查点。

checkpoint_path =
trainer.checkpoint_callback.best_model_path

创建评估模型并加载检查点。

eval_model =
nemo_nlp.models.TextClassificationModel.load_from_checkpoint(checkpoint_path=checkpoint_path)

创建用于评估的数据加载器配置;这里使用了validation_ds 中提供的相同数据文件。

eval_config = OmegaConf.create({‘file_path’:
config.model.validation_ds.file_path, ‘batch_size’: 64, ‘shuffle’: False, ‘num_samples’: -1})
eval_model.setup_test_data(test_data_config=eval_config)

创建了一个新的训练器来展示如何从已经训练的模型中评估一个检查点。然后我们将创建培训师配置的副本并对其进行更新以用于最终评估。

eval_trainer_cfg = config.trainer.copy()
eval_trainer_cfg.accelerator = ‘gpu’ if torch.cuda.is_available() else ‘cpu’ # it is safer to perform evaluation on single GPU as PT is buggy with the last batch on multi-GPUs eval_trainer_cfg.strategy = None # ‘ddp’ is buggy with test process in the current PT, it looks like it has been fixed in the latest master eval_trainer = pl.Trainer(**eval_trainer_cfg)

eval_trainer.test(model=eval_model, verbose=False) # test_dataloaders=eval_dataloader,

提取检查点的路径。

checkpoint_path =
trainer.checkpoint_callback.best_model_path

创建评估模型并加载检查点。

infer_model =
nemo_nlp.models.TextClassificationModel.load_from_checkpoint(checkpoint_path=checkpoint_path)

将模型移动到所需的设备进行推理。如果可用,我们将模型移动到“cuda”,否则将使用“cpu”。

if torch.cuda.is_available(): infer_model.to(“cuda”) else: infer_model.to(“cpu”)

定义推理查询列表。

queries = [‘by the end of no such thing the audience , like beatrice , has a watchful affection for the monster .’, ‘director rob marshall went out gunning to make a great one .’, ‘uneasy mishmash of styles and genres .’] # max_seq_length=512 is the maximum length BERT supports. results = infer_model.classifytext(queries=queries, batch_size=3, max_seq_length=512) print(‘The prediction results of some sample queries with the trained model:’) for query, result in zip(queries, results): print(f’Query : {query}’) print(f’Predicted label: {result}’)

以下是模型的预测结果:

The prediction results of some sample queries with the trained model: Query : by the end of no such thing the audience , like beatrice , has a watchful affection for the monster . Predicted label: 1 Query : director rob marshall went out gunning to make a great one . Predicted label: 1 Query: uneasy mishmash of styles and genres . Predicted label: 0 For our 3 examples, the model predicted the results correctly, where 1 means that the sentiment of the sentence was positive and 0 means that it was negative.

使用 NVIDIA NeMo
在本教程中,我们解释了 NVIDIA NeMo 是什么以及它的主要重点是增强机器学习领域。我们还解释了它的一些模块,例如自动语音识别、自然语言处理和文本到语音, 它们是文本分类中较小的子字段。最后,我们使用 NVIDIA NeMo 构建了一个能够预测给定文本的情感含义的自然语言处理模型。

随着对话式人工智能的兴起,NVIDIA 的 NeMo 等机器学习工具包变得越来越可靠。通过允许其用户轻松训练他们的模型,它可能值得一试。

来源:科技狠活与软件技术

声明:本站部分文章及图片转载于互联网,内容版权归原作者所有,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2022年8月18日
下一篇 2022年8月18日

相关推荐