import torch import torch.nn as nn import torch.nn.functional as F from transformers import PreTrainedModel from transformers.modeling_outputs import CausalLMOutputWithPast from .configuration_dumbmath import DumbMathConfig # --------------------------------------------------------- # あなたのコンポーネント定義 (そのまま使用) # --------------------------------------------------------- class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim)) def forward(self, x): variance = x.pow(2).mean(-1, keepdim=True) return x * torch.rsqrt(variance + self.eps) * self.weight class SwiGLUMLP(nn.Module): def __init__(self, d_model, d_ff): super().__init__() self.w_gate = nn.Linear(d_model, d_ff, bias=False) self.w_up = nn.Linear(d_model, d_ff, bias=False) self.w_down = nn.Linear(d_ff, d_model, bias=False) def forward(self, x): return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x)) class MultiHeadAttention(nn.Module): def __init__(self, d_model, n_heads): super().__init__() self.n_heads = n_heads self.d_model = d_model self.head_dim = d_model // n_heads self.q_proj = nn.Linear(d_model, d_model, bias=False) self.k_proj = nn.Linear(d_model, d_model, bias=False) self.v_proj = nn.Linear(d_model, d_model, bias=False) self.out_proj = nn.Linear(d_model, d_model, bias=False) def forward(self, x): b, t, c = x.size() q = self.q_proj(x).view(b, t, self.n_heads, self.head_dim).transpose(1, 2) k = self.k_proj(x).view(b, t, self.n_heads, self.head_dim).transpose(1, 2) v = self.v_proj(x).view(b, t, self.n_heads, self.head_dim).transpose(1, 2) attn_out = F.scaled_dot_product_attention(q, k, v, attn_mask=None, is_causal=True) attn_out = attn_out.transpose(1, 2).contiguous().view(b, t, c) return self.out_proj(attn_out) class DecoderBlock(nn.Module): def __init__(self, d_model, n_heads, d_ff): super().__init__() self.attn_norm = RMSNorm(d_model) self.attn = MultiHeadAttention(d_model, n_heads) self.ffn_norm = RMSNorm(d_model) self.ffn = SwiGLUMLP(d_model, d_ff) def forward(self, x): x = x + self.attn(self.attn_norm(x)) x = x + self.ffn(self.ffn_norm(x)) return x # --------------------------------------------------------- # Hugging Face規格のラッパークラス # --------------------------------------------------------- class DumbMathForCausalLM(PreTrainedModel): config_class = DumbMathConfig base_model_prefix = "model" def __init__(self, config): super().__init__(config) self.token_embedding = nn.Embedding(config.vocab_size, config.d_model) self.pos_embedding = nn.Parameter(torch.zeros(1, config.max_len, config.d_model)) self.layers = nn.ModuleList([ DecoderBlock(config.d_model, config.n_heads, config.d_ff) for _ in range(config.n_layers) ]) self.ln_f = RMSNorm(config.d_model) self.head = nn.Linear(config.d_model, config.vocab_size, bias=False) # 重み初期化の適用 self.post_init() def get_input_embeddings(self): return self.token_embedding def set_input_embeddings(self, value): self.token_embedding = value def forward(self, input_ids, labels=None, attention_mask=None, **kwargs): b, t = input_ids.size() x = self.token_embedding(input_ids) + self.pos_embedding[:, :t, :] for layer in self.layers: x = layer(x) x = self.ln_f(x) logits = self.head(x) # ロス計算(Trainerに対応) loss = None if labels is not None: # 標準的なCausal LMのロス計算(右シフト処理はTrainerが自動実行またはここで対応) shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() loss_fct = nn.CrossEntropyLoss(ignore_index=-100) loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)) return CausalLMOutputWithPast( loss=loss, logits=logits ) # 推論時(model.generate)に必要なメソッド定義 def prepare_inputs_for_generation(self, input_ids, **kwargs): return {"input_ids": input_ids}