transformer.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from tinygrad import Tensor
  2. class TransformerBlock:
  3. def __init__(self, embed_dim, num_heads, ff_dim, prenorm=False, act=lambda x: x.relu(), dropout=0.1):
  4. assert embed_dim % num_heads == 0, "embed_dim must be divisible by num_heads"
  5. self.num_heads = num_heads
  6. self.head_size = embed_dim // num_heads
  7. self.prenorm, self.act = prenorm, act
  8. self.dropout = dropout
  9. self.query = (Tensor.scaled_uniform(embed_dim, embed_dim), Tensor.zeros(embed_dim))
  10. self.key = (Tensor.scaled_uniform(embed_dim, embed_dim), Tensor.zeros(embed_dim))
  11. self.value = (Tensor.scaled_uniform(embed_dim, embed_dim), Tensor.zeros(embed_dim))
  12. self.out = (Tensor.scaled_uniform(embed_dim, embed_dim), Tensor.zeros(embed_dim))
  13. self.ff1 = (Tensor.scaled_uniform(embed_dim, ff_dim), Tensor.zeros(ff_dim))
  14. self.ff2 = (Tensor.scaled_uniform(ff_dim, embed_dim), Tensor.zeros(embed_dim))
  15. self.ln1 = (Tensor.ones(embed_dim), Tensor.zeros(embed_dim))
  16. self.ln2 = (Tensor.ones(embed_dim), Tensor.zeros(embed_dim))
  17. def attn(self, x):
  18. # x: (bs, time, embed_dim) -> (bs, time, embed_dim)
  19. query, key, value = [x.linear(*y).reshape(shape=(x.shape[0], -1, self.num_heads, self.head_size)).transpose(1,2) for y in [self.query, self.key, self.value]]
  20. attention = Tensor.scaled_dot_product_attention(query, key, value).transpose(1,2)
  21. return attention.reshape(shape=(x.shape[0], -1, self.num_heads * self.head_size)).linear(*self.out)
  22. def __call__(self, x):
  23. if self.prenorm:
  24. x = x + self.attn(x.layernorm().linear(*self.ln1)).dropout(self.dropout)
  25. x = x + self.act(x.layernorm().linear(*self.ln2).linear(*self.ff1)).linear(*self.ff2).dropout(self.dropout)
  26. else:
  27. x = x + self.attn(x).dropout(self.dropout)
  28. x = x.layernorm().linear(*self.ln1)
  29. x = x + self.act(x.linear(*self.ff1)).linear(*self.ff2).dropout(self.dropout)
  30. x = x.layernorm().linear(*self.ln2)
  31. return x
  32. class Transformer:
  33. def __init__(self, syms, maxlen, layers, embed_dim, num_heads, ff_dim):
  34. self.maxlen, self.syms = maxlen, syms
  35. self.embed = Tensor.scaled_uniform(maxlen+syms, embed_dim, requires_grad=False)
  36. self.tbs = [TransformerBlock(embed_dim, num_heads, ff_dim) for _ in range(layers)]
  37. self.final = Tensor.scaled_uniform(embed_dim, syms)
  38. def forward(self, x):
  39. bs = x.shape[0]
  40. maxlen_eye = Tensor.eye(x.shape[1])
  41. maxlen_eye = maxlen_eye.unsqueeze(0).expand([bs, *maxlen_eye.shape])
  42. onehot_feat = x.one_hot(self.syms)
  43. onehot = maxlen_eye.cat(onehot_feat, dim=2).flatten(end_dim=1)
  44. x = onehot.dot(self.embed).reshape((bs, x.shape[1], -1))
  45. x = x.sequential(self.tbs)
  46. x = x.reshape((-1, x.shape[-1])).dot(self.final).log_softmax()
  47. return x.reshape((bs, -1, x.shape[-1]))