Train Autoregressive Transformer

This trains a simple transformer model for auto-regression.

12import torch
13from labml import experiment
14from labml.configs import option
15from labml.utils.pytorch import get_modules
16from labml_helpers.module import Module
17
18from labml_nn.experiments.nlp_autoregression import NLPAutoRegressionConfigs
19from labml_nn.transformers import Encoder, Generator, TransformerConfigs
20from labml_nn.transformers.utils import subsequent_mask

Auto regressive model

23class AutoregressiveModel(Module):
28    def __init__(self, src_embed: Module, encoder: Encoder, generator: Generator, *,
29                 is_save_ff_input: bool = False):
30        super().__init__()

Token embedding module

32        self.src_embed = src_embed

Transformer based encoder

34        self.encoder = encoder

Whether the last layer of the encoder should save the input to the feed-forward layer. This is out , the embedding of the context.

38        self.encoder.layers[-1].is_save_ff_input = is_save_ff_input

Next token generation layer; this give logits of the the next token

41        self.generator = generator

This will be initialized on the first call

43        self.src_mask = None

Retrieve saved

45    @property
46    def ff_input(self) -> torch.Tensor:
50        return self.encoder.layers[-1].ff_input
52    def forward(self, src: torch.Tensor):

Create subsequent mask, so that the transformer can only pay attention to past tokens.

54        if self.src_mask is None or self.src_mask.size(0) != len(src):
55            self.src_mask = subsequent_mask(len(src)).to(src.device)

Embed the tokens (src ) and run it through the the transformer

57        res = self.encoder(self.src_embed(src), self.src_mask)

Generate logits of the next token

59        return self.generator(res), None

Configurations

The default configs can and will be over-ridden when we start the experiment

62class Configs(NLPAutoRegressionConfigs):
69    transformer: TransformerConfigs
70    model: AutoregressiveModel
71
72    is_save_ff_input = False

Initialize the auto-regressive model

75@option(Configs.model)
76def autoregressive_model(c: Configs):
80    m = AutoregressiveModel(

Get the source token embedding layer, encoder and final token generator from configurable transformer

83        src_embed=c.transformer.src_embed,
84        encoder=c.transformer.encoder,
85        generator=c.transformer.generator,

Whether to save

87        is_save_ff_input=c.is_save_ff_input)
88    return m.to(c.device)

Initialize the configurable transformer encoder for our autoregressive model

91@option(Configs.transformer)
92def transformer_c(c: Configs):
96    tc = TransformerConfigs()
97    tc.n_src_vocab = c.n_tokens
98    tc.n_tgt_vocab = c.n_tokens
99
100    return tc
103def main():

Create experiment

105    experiment.create(name="knn_lm")

Create configs

107    conf = Configs()

Load configurations

109    experiment.configs(conf,

A dictionary of configurations to override

111                       {'tokenizer': 'character',
112                        'prompt_separator': '',
113                        'prompt': 'It is ',
114                        'text': 'tiny_shakespeare',
115
116                        'optimizer.optimizer': 'Noam',
117                        'optimizer.learning_rate': 1.,
118                        'optimizer.d_model': 256,
119
120                        'seq_len': 1024,
121                        'epochs': 128,
122                        'batch_size': 6,
123                        'inner_iterations': 10,

Transformer configurations

126                        'transformer.d_model': 256,
127                        'transformer.ffn.d_ff': 1024,
128                        'transformer.n_heads': 8,
129                        'transformer.n_layers': 6})

This is needed to initialize models

132    conf.n_tokens = conf.text.n_tokens

Set models for saving and loading

135    experiment.add_pytorch_models(get_modules(conf))

Start the experiment

138    with experiment.start():

TrainValidConfigs.run

140        conf.run()
141
142
143if __name__ == '__main__':
144    main()