56m commited on
Commit
02420d2
·
verified ·
1 Parent(s): a8b2987

Create modeling_dumbmath.py

Browse files
Files changed (1) hide show
  1. modeling_dumbmath.py +120 -0
modeling_dumbmath.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from transformers import PreTrainedModel
5
+ from transformers.modeling_outputs import CausalLMOutputWithPast
6
+ from .configuration_dumbmath import DumbMathConfig
7
+
8
+ # ---------------------------------------------------------
9
+ # あなたのコンポーネント定義 (そのまま使用)
10
+ # ---------------------------------------------------------
11
+ class RMSNorm(nn.Module):
12
+ def __init__(self, dim, eps=1e-6):
13
+ super().__init__()
14
+ self.eps = eps
15
+ self.weight = nn.Parameter(torch.ones(dim))
16
+
17
+ def forward(self, x):
18
+ variance = x.pow(2).mean(-1, keepdim=True)
19
+ return x * torch.rsqrt(variance + self.eps) * self.weight
20
+
21
+ class SwiGLUMLP(nn.Module):
22
+ def __init__(self, d_model, d_ff):
23
+ super().__init__()
24
+ self.w_gate = nn.Linear(d_model, d_ff, bias=False)
25
+ self.w_up = nn.Linear(d_model, d_ff, bias=False)
26
+ self.w_down = nn.Linear(d_ff, d_model, bias=False)
27
+
28
+ def forward(self, x):
29
+ return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
30
+
31
+ class MultiHeadAttention(nn.Module):
32
+ def __init__(self, d_model, n_heads):
33
+ super().__init__()
34
+ self.n_heads = n_heads
35
+ self.d_model = d_model
36
+ self.head_dim = d_model // n_heads
37
+
38
+ self.q_proj = nn.Linear(d_model, d_model, bias=False)
39
+ self.k_proj = nn.Linear(d_model, d_model, bias=False)
40
+ self.v_proj = nn.Linear(d_model, d_model, bias=False)
41
+ self.out_proj = nn.Linear(d_model, d_model, bias=False)
42
+
43
+ def forward(self, x):
44
+ b, t, c = x.size()
45
+ q = self.q_proj(x).view(b, t, self.n_heads, self.head_dim).transpose(1, 2)
46
+ k = self.k_proj(x).view(b, t, self.n_heads, self.head_dim).transpose(1, 2)
47
+ v = self.v_proj(x).view(b, t, self.n_heads, self.head_dim).transpose(1, 2)
48
+
49
+ attn_out = F.scaled_dot_product_attention(q, k, v, attn_mask=None, is_causal=True)
50
+ attn_out = attn_out.transpose(1, 2).contiguous().view(b, t, c)
51
+ return self.out_proj(attn_out)
52
+
53
+ class DecoderBlock(nn.Module):
54
+ def __init__(self, d_model, n_heads, d_ff):
55
+ super().__init__()
56
+ self.attn_norm = RMSNorm(d_model)
57
+ self.attn = MultiHeadAttention(d_model, n_heads)
58
+ self.ffn_norm = RMSNorm(d_model)
59
+ self.ffn = SwiGLUMLP(d_model, d_ff)
60
+
61
+ def forward(self, x):
62
+ x = x + self.attn(self.attn_norm(x))
63
+ x = x + self.ffn(self.ffn_norm(x))
64
+ return x
65
+
66
+ # ---------------------------------------------------------
67
+ # Hugging Face規格のラッパークラス
68
+ # ---------------------------------------------------------
69
+ class DumbMathForCausalLM(PreTrainedModel):
70
+ config_class = DumbMathConfig
71
+ base_model_prefix = "model"
72
+
73
+ def __init__(self, config):
74
+ super().__init__(config)
75
+ self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)
76
+ self.pos_embedding = nn.Parameter(torch.zeros(1, config.max_len, config.d_model))
77
+
78
+ self.layers = nn.ModuleList([
79
+ DecoderBlock(config.d_model, config.n_heads, config.d_ff) for _ in range(config.n_layers)
80
+ ])
81
+
82
+ self.ln_f = RMSNorm(config.d_model)
83
+ self.head = nn.Linear(config.d_model, config.vocab_size, bias=False)
84
+
85
+ # 重み初期化の適用
86
+ self.post_init()
87
+
88
+ def get_input_embeddings(self):
89
+ return self.token_embedding
90
+
91
+ def set_input_embeddings(self, value):
92
+ self.token_embedding = value
93
+
94
+ def forward(self, input_ids, labels=None, attention_mask=None, **kwargs):
95
+ b, t = input_ids.size()
96
+ x = self.token_embedding(input_ids) + self.pos_embedding[:, :t, :]
97
+
98
+ for layer in self.layers:
99
+ x = layer(x)
100
+
101
+ x = self.ln_f(x)
102
+ logits = self.head(x)
103
+
104
+ # ロス計算(Trainerに対応)
105
+ loss = None
106
+ if labels is not None:
107
+ # 標準的なCausal LMのロス計算(右シフト処理はTrainerが自動実行またはここで対応)
108
+ shift_logits = logits[..., :-1, :].contiguous()
109
+ shift_labels = labels[..., 1:].contiguous()
110
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
111
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
112
+
113
+ return CausalLMOutputWithPast(
114
+ loss=loss,
115
+ logits=logits
116
+ )
117
+
118
+ # 推論時(model.generate)に必要なメソッド定義
119
+ def prepare_inputs_for_generation(self, input_ids, **kwargs):
120
+ return {"input_ids": input_ids}