Почему моя Трансформерная Языковая Модель генерирует бессмысленный текст?
Краткое содержание
Я сейчас изучаю Трансформеры, поэтому проверьте мое понимание. Я попытался реализовать небольшой языковую модель на основе Трансформера и сравнил ее с языковой моделью на базе RNN. Вот код Трансформера ниже; я использую встроенный слой PyTorch для Transformer Encoder: класс TransformerLM_1(nn.Module): def __init__(self, head, vocab_size, embedding_size, dropout = 0.1, device = 'cpu', pad_idx = 0, start_idx = 1, end_idx = 2, unk_idx = 3): super(TransformerLM_1, self).__init__() self.head = head self.embedding_size = embedding_size self.vocab_size = vocab_size self.device = device self.embed = WordEmbedding(self.vocab_size, self.embedding_size, pad_idx) self.postional_encoding = PostionalEncoding(embedding_size, device) self.decoder = nn.TransformerEncoderLayer(self.embedding_size, self.head) self.out_linear = nn.Linear(self.embedding_size, vocab_size) self.dropout
Полный текст
Задано 5 лет, 3 месяца назад Изменено сегодня Просмотрено 257 раз
Задано 5 лет, 3 месяца назад
0 $\begingroup$ Сейчас я изучаю Трансформеры, поэтому проверьте мое понимание. Я попытался реализовать небольшую языковую модель на основе трансформера и сравнил ее с языковой моделью на основе RNN. Вот код для трансформера ниже; я использую встроенный слой PyTorch для Трансформатора Encoder: class TransformerLM_1(nn.Module): def __init__(self, head, vocab_size, embedding_size, dropout = 0.1, device = 'cpu', pad_idx = 0, start_idx = 1, end_idx = 2, unk_idx = 3): super(TransformerLM_1, self).__init__() self.head = head self.embedding_size = embedding_size self.vocab_size = vocab_size self.device = device self.embed = WordEmbedding(self.vocab_size, self.embedding_size, pad_idx) self.postional_encoding = PostionalEncoding(embedding_size, device) self.decoder = nn.TransformerEncoderLayer(self.embedding_size, self.head) self.out_linear = nn.Linear(self.embedding_size, vocab_size) self.dropout = dropout self.pad_idx = pad_idx self.start_idx = start_idx self.end_idx = end_idx self.unk_idx = unk_idx self.device = device def make_src_mask(self, src_sz): mask = (torch.triu(torch.ones(src_sz, src_sz)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0, 10e-20).masked_fill(mask == 1, float(0.0)) mask = mask.to(self.device) return mask def forward(self, x): dec_in = x.clone()[:, :-1] src_mask = self.make_src_mask(dec_in.size()[1]) src = self.embed(dec_in) src = self.postional_encoding(src) src = src.transpose(0,1) transformer_out = self.decoder(src, src_mask) out = self.out_linear(transformer_out) return out Я использую teacher forcing, чтобы ускорить сходимость. На основании того, что я видел из результатов, текст, генерируемый моделью RNN, лучше чем текст, генерируемый трансформером. Вот образец сгенерированного текста с ожидаемым Ожидаемое: у вас должен был быть слепо не видеть сценарий там для чего он и есть и будет продолжаться в течение месяцев и даже лет как часть южной каролины, что получила удар, который красный крест ожидает обойдется этой организацией на некоторые $ n миллионов. Предсказанное: некоторые быть были были быть $ это общий был может было имеет быть что что быть для того что быть к тому что быть в том что это быть к Ожидаемое: citicorp и chase пытаются собрать вместе новую более низкую ставку
Предсказанное: a являются carries n't to the together with jersey than Ожидаемое: it ' s amazing the amount of money that goes up their nose out to the dog track or to the tables in las vegas mr . katz says
Предсказанное: it ' s comeback money of the in mr to their and of mr
Предсказанное: or or mr the money Ожидаемое: moreover while asian and middle eastern investors gold and help its price silver does n't have the same dealers say
Предсказанное: the production the routes of its Ожидаемое: a board of control spokesman said the board had not seen the claim and declined to comment
Предсказанное: the board said declined of said Ожидаемое: property capital trust said it dropped its plan to liquidate because it was n't able to realize the value it had expected
Предсказанное: the claims markets said its was n ribut to sell insolvent of was n't disclosed to sell its plan Ожидаемое: similarly honda motor co . ' s sales are so brisk that workers they have n't had a saturday off in years despite the government ' s encouragement of more leisure activity
Предсказанное: the honda ' credit . s s ribut. s Ожидаемое: we expect a big market in the future so in the long term it will be profitable
Предсказанное: it can it ribut board Ожидаемое: u . k . composite or insurers which some equity analysts said might be heavily hit by the earthquake disaster helped support the london market by showing only narrow losses in early trading
Предсказанное: the . s . s trading sell said which traders market said the be able in the earthquake Ожидаемое: