火车反馈变压器

这会训练一个用于自动回归的反馈变压器模型。您可以选择原始反馈变压器,也可以选择预先计算密钥和值的新版本。

这是一本 Colab 笔记本,用于在 Tiny Shakespeare 数据集上训练反馈转换器。

Open In Colab

18import torch
19from torch import nn
20
21from labml import experiment
22from labml.configs import option
23from labml.utils.pytorch import get_modules
24from labml_helpers.module import Module
25
26from labml_nn.experiments.nlp_autoregression import NLPAutoRegressionConfigs
27from labml_nn.transformers import Encoder, Generator, TransformerConfigs
28from labml_nn.transformers.utils import subsequent_mask

自动回归模型

31class AutoregressiveModel(Module):
36    def __init__(self, n_vocab: int, d_model: int, transformer: Module):
37        super().__init__()

令牌嵌入模块

39        self.src_embed = nn.Embedding(n_vocab, d_model)
40        self.transformer = transformer
41        self.generator = nn.Linear(d_model, n_vocab)
43    def forward(self, x: torch.Tensor):

嵌入代币

45        x = self.src_embed(x)

用它穿过变压器

47        res = self.transformer(x)

生成下一个令牌的日志

49        return self.generator(res), None

配置

当我们开始实验时,默认配置可以而且将会被覆盖

52class Configs(NLPAutoRegressionConfigs):
59    model: AutoregressiveModel
60
61    d_model: int = 512
62    heads: int = 8
63    dropout: float = 0.0
64    d_ff: int = 2048
65    n_layers: int = 6
68@option(Configs.model)
69def feedback_transformer(c: Configs):
73    from labml_nn.transformers.feedback import FeedbackTransformer, FeedbackTransformerLayer, \
74        FeedbackAttention, FeedForward
75
76    return AutoregressiveModel(
77        c.n_tokens, c.d_model,
78        FeedbackTransformer(
79            FeedbackTransformerLayer(d_model=c.d_model,
80                                     attn=FeedbackAttention(c.heads, c.d_model, c.dropout),
81                                     feed_forward=FeedForward(c.d_model, c.d_ff, c.dropout),
82                                     dropout_prob=c.dropout),
83            c.n_layers)).to(c.device)
使用@@

预先计算的键和值创建更新的反馈转换器

86@option(Configs.model)
87def feedback_transformer_kv(c: Configs):
91    from labml_nn.transformers.feedback import FeedbackTransformerKV, FeedbackTransformerLayer, \
92        FeedbackAttention, FeedForward
93
94    return AutoregressiveModel(
95        c.n_tokens, c.d_model,
96        FeedbackTransformerKV(
97            FeedbackTransformerLayer(d_model=c.d_model,
98                                     attn=FeedbackAttention(c.heads, c.d_model, c.dropout,
99                                                            is_kv_precomputed=True),
100                                     feed_forward=FeedForward(c.d_model, c.d_ff, c.dropout),
101                                     dropout_prob=c.dropout),
102            c.n_layers, c.d_model, c.heads)).to(c.device)
105def main():

创建实验

107    experiment.create(name="feedback_transformer")

创建配置

109    conf = Configs()

装载配置

111    experiment.configs(conf,

要覆盖的配置字典

113                       {'tokenizer': 'character',
114                        'text': 'tiny_shakespeare',
115                        'optimizer.learning_rate': 1.0,
116                        'optimizer.optimizer': 'Noam',
117                        'prompt': 'It is',
118                        'prompt_separator': '',

feedback_transformer 用于原装反馈变压器

121                        'model': 'feedback_transformer_kv',
122
123                        'train_loader': 'shuffled_train_loader',
124                        'valid_loader': 'shuffled_valid_loader',
125
126                        'seq_len': 128,
127                        'epochs': 128,
128                        'batch_size': 64,
129                        'inner_iterations': 25})

设置用于保存和加载的模型

132    experiment.add_pytorch_models(get_modules(conf))

开始实验

135    with experiment.start():

运行训练循环

137        conf.run()
138
139
140if __name__ == '__main__':
141    main()