ereniko commited on
Commit
453c3c1
·
verified ·
1 Parent(s): a201df5

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_ivme.py +130 -0
modeling_ivme.py CHANGED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from transformers import PretrainedConfig, PreTrainedModel
5
+ from transformers.modeling_outputs import CausalLMOutputWithPast
6
+
7
+ class IvmeConfig(PretrainedConfig):
8
+ model_type = "ivme"
9
+ def __init__(self, vocab_size=16000, context_len=1024, tie_word_embeddings=True, **kwargs):
10
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
11
+ self.vocab_size = vocab_size
12
+ self.context_len = context_len
13
+ self.tie_word_embeddings = tie_word_embeddings
14
+ self.hidden_dim = 384
15
+ self.n_layers = 10
16
+ self.n_heads = 6
17
+ self.dropout = 0.0
18
+ self.ffn_mult = 4.0
19
+ self.norm_eps = 1e-05
20
+ self.rope_theta = 10000.0
21
+ self.head_dim = 64
22
+
23
+ class RMSNorm(nn.Module):
24
+ def __init__(self, dim: int, eps: float = 1e-5):
25
+ super().__init__()
26
+ self.eps = eps
27
+ self.weight = nn.Parameter(torch.ones(dim))
28
+ def forward(self, x):
29
+ pow_x = x.pow(2).mean(-1, keepdim=True)
30
+ return x * torch.rsqrt(pow_x + self.eps) * self.weight
31
+
32
+ def precompute_rope_freqs(dim: int, max_seq_len: int, theta: float = 10000.0):
33
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
34
+ t = torch.arange(max_seq_len, dtype=torch.float32)
35
+ freqs = torch.outer(t, inv_freq)
36
+ return torch.polar(torch.ones_like(freqs), freqs)
37
+
38
+ class CausalSelfAttention(nn.Module):
39
+ def __init__(self, hidden_dim: int, n_heads: int, dropout: float = 0.0):
40
+ super().__init__()
41
+ self.n_heads = n_heads
42
+ self.head_dim = hidden_dim // n_heads
43
+ self.wq = nn.Linear(hidden_dim, hidden_dim, bias=False)
44
+ self.wk = nn.Linear(hidden_dim, hidden_dim, bias=False)
45
+ self.wv = nn.Linear(hidden_dim, hidden_dim, bias=False)
46
+ self.wo = nn.Linear(hidden_dim, hidden_dim, bias=False)
47
+ self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
48
+
49
+ def forward(self, x, rope_freqs):
50
+ B, T, C = x.shape
51
+ q, k, v = self.wq(x), self.wk(x), self.wv(x)
52
+ q = q.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
53
+ k = k.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
54
+ v = v.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
55
+
56
+ q_complex = torch.view_as_complex(q.float().reshape(*q.shape[:-1], -1, 2))
57
+ k_complex = torch.view_as_complex(k.float().reshape(*k.shape[:-1], -1, 2))
58
+ freqs = rope_freqs[:T].view(1, 1, T, -1).to(q_complex.device)
59
+
60
+ q = torch.view_as_real(q_complex * freqs).flatten(3).to(x.dtype)
61
+ k = torch.view_as_real(k_complex * freqs).flatten(3).to(x.dtype)
62
+ v = v.to(x.dtype)
63
+
64
+ scores = torch.matmul(q, k.transpose(-2, -1)) / (self.head_dim ** 0.5)
65
+ mask = torch.full((T, T), float("-inf"), device=x.device).triu(1)
66
+ scores = scores + mask
67
+ probs = torch.softmax(scores, dim=-1).to(x.dtype)
68
+ probs = self.dropout(probs)
69
+
70
+ output = torch.matmul(probs, v)
71
+ output = output.transpose(1, 2).contiguous().view(B, T, C)
72
+ return self.wo(output)
73
+
74
+ class SwiGLU(nn.Module):
75
+ def __init__(self, hidden_dim: int, ffn_mult: float = 1.0):
76
+ super().__init__()
77
+ hidden_features = int(2 * hidden_dim * 4 / 3)
78
+ hidden_features = int(ffn_mult * hidden_features)
79
+ self.w1 = nn.Linear(hidden_dim, hidden_features, bias=False)
80
+ self.w2 = nn.Linear(hidden_features, hidden_dim, bias=False)
81
+ self.w3 = nn.Linear(hidden_dim, hidden_features, bias=False)
82
+ def forward(self, x):
83
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
84
+
85
+ class TransformerBlock(nn.Module):
86
+ def __init__(self, cfg):
87
+ super().__init__()
88
+ self.attn_norm = RMSNorm(cfg.hidden_dim, eps=cfg.norm_eps)
89
+ self.attn = CausalSelfAttention(cfg.hidden_dim, cfg.n_heads, cfg.dropout)
90
+ self.ffn_norm = RMSNorm(cfg.hidden_dim, eps=cfg.norm_eps)
91
+ self.ffn = SwiGLU(cfg.hidden_dim, cfg.ffn_mult)
92
+ def forward(self, x, rope_freqs):
93
+ x = x + self.attn(self.attn_norm(x), rope_freqs)
94
+ x = x + self.ffn(self.ffn_norm(x))
95
+ return x
96
+
97
+ class IvmeConversateV2HF(PreTrainedModel):
98
+ config_class = IvmeConfig
99
+ base_model_prefix = "model"
100
+
101
+ def __init__(self, config):
102
+ super().__init__(config)
103
+ self.config = config
104
+
105
+ self.tok_embed = nn.Embedding(config.vocab_size, config.hidden_dim)
106
+ self.blocks = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
107
+ self.final_norm = RMSNorm(config.hidden_dim, eps=config.norm_eps)
108
+ self.lm_head = nn.Linear(config.hidden_dim, config.vocab_size, bias=False)
109
+
110
+ if config.tie_word_embeddings:
111
+ self.lm_head.weight = self.tok_embed.weight
112
+
113
+ rope_freqs = precompute_rope_freqs(config.hidden_dim // config.n_heads, config.context_len, config.rope_theta)
114
+ self.register_buffer("rope_freqs", rope_freqs, persistent=False)
115
+
116
+ self.post_init()
117
+
118
+ def forward(self, input_ids=None, labels=None, **kwargs):
119
+ B, T = input_ids.shape
120
+ x = self.tok_embed(input_ids)
121
+ for block in self.blocks:
122
+ x = block(x, self.rope_freqs)
123
+ x = self.final_norm(x)
124
+ logits = self.lm_head(x)
125
+
126
+ loss = None
127
+ if labels is not None:
128
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1), ignore_index=-1)
129
+
130
+ return CausalLMOutputWithPast(loss=loss, logits=logits)