14import torch
15import torch.nn as nn
16
17from labml import experiment, tracker
18from labml.configs import option
19from labml_helpers.module import Module
20from labml_helpers.train_valid import BatchIndex
21from labml_nn.experiments.nlp_autoregression import NLPAutoRegressionConfigs
24class AutoregressiveModel(Module):
29 def __init__(self, n_vocab: int, d_model: int, transformer: Module):
30 super().__init__()
令牌嵌入模块
32 self.src_embed = nn.Embedding(n_vocab, d_model)
变压器
34 self.transformer = transformer
最后一层
36 self.generator = nn.Linear(d_model, n_vocab)
37 self.mask = None
39 def forward(self, x: torch.Tensor):
初始化后续掩码
41 if self.mask is None or self.mask.size(0) != len(x):
42 from labml_nn.transformers.utils import subsequent_mask
43 self.mask = subsequent_mask(len(x)).to(x.device)
令牌嵌入
45 x = self.src_embed(x)
用它穿过变压器
47 res, counts, route_prob, n_dropped, route_prob_max = self.transformer(x, self.mask)
生成下一个令牌的日志
49 res = self.generator(res)
51 return res, counts, route_prob, n_dropped, route_prob_max
54class Configs(NLPAutoRegressionConfigs):
63 model: AutoregressiveModel
64 transformer: Module
令牌嵌入大小
67 d_model: int = 128
注意头数量
69 heads: int = 4
辍学概率
71 dropout: float = 0.0
FFN 隐藏层中的要素数量
73 d_ff: int = 256
变压器层数
75 n_layers: int = 6
专家人数
77 n_experts: int = 4
负载平衡系数
79 load_balancing_loss_ceof = 0.01
是否按路由概率缩放所选智能交易输出
81 is_scale_prob: bool = True
是否丢弃代币
83 drop_tokens: bool = False
确定每种型号容量的容量系数
85 capacity_factor: float = 1.0
87 def init(self):
88 super().init()
初始化跟踪指示器
90 tracker.set_scalar("lb_loss.*", False)
91 tracker.set_scalar("route.*", False)
92 tracker.set_scalar("dropped.*", False)
94 def step(self, batch: any, batch_idx: BatchIndex):
将数据移动到设备
100 data, target = batch[0].to(self.device), batch[1].to(self.device)
在训练模式下更新全局步长(处理的令牌数)
103 if self.mode.is_train:
104 tracker.add_global_step(data.shape[0] * data.shape[1])
是否捕获模型输出
107 with self.mode.update(is_log_activations=batch_idx.is_last):
获取模型输出。
109 output, counts, route_prob, n_dropped, route_prob_max = self.model(data)
计算和交叉熵损失
112 cross_entropy_loss = self.loss_func(output, target)
当前批次中已处理的令牌总数
114 total = counts.sum(dim=-1, keepdims=True)
发送给每个 EA 的代币的分数是其中的argmax等于的代币计数。
118 route_frac = counts / total
平均路由概率
121 route_prob = route_prob / total
负载均衡损失是单层的损失,这里我们取的是所有层的损失总和。
126 load_balancing_loss = self.n_experts * (route_frac * route_prob).sum()
追踪统计数据
129 tracker.add('dropped.', total.new_tensor(n_dropped) / total)
130 tracker.add('route.min.', route_frac.min())
131 tracker.add('route.max.', route_frac.max())
132 tracker.add('route.std.', route_frac.std())
133 tracker.add('route.max_prob.', route_prob_max)
134 tracker.add("loss.", cross_entropy_loss)
135 tracker.add("lb_loss.", load_balancing_loss)
合并亏损。负载均衡损失乘以系数,该系数设置为类似的小值。
140 loss = cross_entropy_loss + self.load_balancing_loss_ceof * load_balancing_loss
计算和记录精度
143 self.accuracy(output, target)
144 self.accuracy.track()
训练模型
147 if self.mode.is_train:
计算梯度
149 loss.backward()
剪辑渐变
151 torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=self.grad_norm_clip)
采取优化器步骤
153 self.optimizer.step()
记录每个纪元最后一批的模型参数和梯度
155 if batch_idx.is_last:
156 tracker.add('model', self.model)
清除渐变
158 self.optimizer.zero_grad()
保存跟踪的指标
161 tracker.save()
164@option(Configs.model)
165def autoregressive_model(c: Configs):
169 m = AutoregressiveModel(c.n_tokens, c.d_model, c.transformer)
170 return m.to(c.device)
173@option(Configs.transformer)
174def switch_transformer(c: Configs):
178 from labml_nn.transformers.switch import SwitchTransformer, SwitchTransformerLayer, SwitchFeedForward
179 from labml_nn.transformers import MultiHeadAttention
180 from labml_nn.transformers.feed_forward import FeedForward
181
182 return SwitchTransformer(
183 SwitchTransformerLayer(d_model=c.d_model,
184 attn=MultiHeadAttention(c.heads, c.d_model, c.dropout),
185 feed_forward=SwitchFeedForward(capacity_factor=c.capacity_factor,
186 drop_tokens=c.drop_tokens,
187 is_scale_prob=c.is_scale_prob,
188 n_experts=c.n_experts,
189 expert=FeedForward(c.d_model, c.d_ff, c.dropout),
190 d_model=c.d_model),
191 dropout_prob=c.dropout),
192 c.n_layers)
195def main():
创建实验
200 experiment.create(name="switch_transformer", comment='')
创建配置
202 conf = Configs()
装载配置
204 experiment.configs(conf,
要覆盖的配置字典
206 {'tokenizer': 'character',
207 'text': 'tiny_shakespeare',
208 'optimizer.learning_rate': 1.,
209 'optimizer.optimizer': 'Noam',
210 'prompt': 'It is',
211 'prompt_separator': '',
212
213 'transformer': 'switch_transformer',
214 'n_experts': 4,
215
216 'drop_tokens': True,
217 'capacity_factor': 1.2,
218
219 'train_loader': 'shuffled_train_loader',
220 'valid_loader': 'shuffled_valid_loader',
221
222 'seq_len': 64,
223 'epochs': 128,
224 'batch_size': 32,
225 'inner_iterations': 25,
226 })
设置用于保存和加载的模型
229 experiment.add_pytorch_models({'model': conf.model})
开始实验
232 with experiment.start():
TrainValidConfigs.run
234 conf.run()
238if __name__ == '__main__':
239 main()