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

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. config.json +8 -8
  2. model.safetensors +2 -2
  3. modeling_ivme.py +0 -174
  4. tokenizer_config.json +1 -7
config.json CHANGED
@@ -6,17 +6,17 @@
6
  "vocab_size": 16000,
7
  "context_len": 1024,
8
  "tie_word_embeddings": true,
 
 
 
 
 
9
  "hidden_dim": 384,
10
  "n_layers": 10,
11
  "n_heads": 6,
12
  "dropout": 0.0,
13
- "ffn_mult": 1.0,
14
  "norm_eps": 1e-05,
15
  "rope_theta": 10000.0,
16
- "head_dim": 64,
17
- "auto_map": {
18
- "AutoConfig": "modeling_ivme.IvmeConfig",
19
- "AutoModelForCausalLM": "modeling_ivme.IvmeConversateV2HF"
20
- },
21
- "transformers_version": "4.41.0"
22
- }
 
6
  "vocab_size": 16000,
7
  "context_len": 1024,
8
  "tie_word_embeddings": true,
9
+ "auto_map": {
10
+ "AutoConfig": "modeling_ivme.IvmeConfig",
11
+ "AutoModelForCausalLM": "modeling_ivme.IvmeConversateV2HF"
12
+ },
13
+ "transformers_version": "4.41.0",
14
  "hidden_dim": 384,
15
  "n_layers": 10,
16
  "n_heads": 6,
17
  "dropout": 0.0,
18
+ "ffn_mult": 4.0,
19
  "norm_eps": 1e-05,
20
  "rope_theta": 10000.0,
21
+ "head_dim": 64
22
+ }
 
 
 
 
 
model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:db78dcec9aa219862c3b3ca36372af576ff02696e17c3389e121f3653c4cf591
3
- size 95396368
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb24ff17d2145c4966b780c31dd0ff124f7ab8ec88fdd912ebc50981525a9d96
3
+ size 119972832
modeling_ivme.py CHANGED
@@ -1,174 +0,0 @@
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
- # ==========================================
8
- # 1. RESMİ HUGGING FACE CONFIG SIFINFI
9
- # ==========================================
10
- class IvmeConfig(PretrainedConfig):
11
- model_type = "ivme"
12
-
13
- def __init__(
14
- self,
15
- vocab_size=16000,
16
- context_len=1024,
17
- tie_word_embeddings=True,
18
- hidden_dim=384,
19
- n_layers=10,
20
- n_heads=6,
21
- dropout=0.0,
22
- ffn_mult=1.0,
23
- norm_eps=1e-5,
24
- rope_theta=10000.0,
25
- head_dim=64,
26
- **kwargs
27
- ):
28
- super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
29
- self.vocab_size = vocab_size
30
- self.context_len = context_len
31
- self.hidden_dim = hidden_dim
32
- self.n_layers = n_layers
33
- self.n_heads = n_heads
34
- self.dropout = dropout
35
- self.ffn_mult = ffn_mult
36
- self.norm_eps = norm_eps
37
- self.rope_theta = rope_theta
38
- self.head_dim = head_dim
39
-
40
- # ==========================================
41
- # 2. SİZİN MODELİNİZİN ORİJİNAL MATEMATİKSEL KATMANLARI
42
- # ==========================================
43
- class RMSNorm(nn.Module):
44
- def __init__(self, dim: int, eps: float = 1e-5):
45
- super().__init__()
46
- self.eps = eps
47
- self.weight = nn.Parameter(torch.ones(dim))
48
- def forward(self, x):
49
- pow_x = x.pow(2).mean(-1, keepdim=True)
50
- return x * torch.rsqrt(pow_x + self.eps) * self.weight
51
-
52
- def precompute_rope_freqs(dim: int, max_seq_len: int, theta: float = 10000.0):
53
- inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
54
- t = torch.arange(max_seq_len, dtype=torch.float32)
55
- freqs = torch.outer(t, inv_freq)
56
- return torch.polar(torch.ones_like(freqs), freqs)
57
-
58
- class CausalSelfAttention(nn.Module):
59
- def __init__(self, hidden_dim: int, n_heads: int, dropout: float = 0.0):
60
- super().__init__()
61
- self.n_heads = n_heads
62
- self.head_dim = hidden_dim // n_heads
63
- self.wq = nn.Linear(hidden_dim, hidden_dim, bias=False)
64
- self.wk = nn.Linear(hidden_dim, hidden_dim, bias=False)
65
- self.wv = nn.Linear(hidden_dim, hidden_dim, bias=False)
66
- self.wo = nn.Linear(hidden_dim, hidden_dim, bias=False)
67
- self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
68
-
69
- def forward(self, x, rope_freqs):
70
- B, T, C = x.shape
71
- q, k, v = self.wq(x), self.wk(x), self.wv(x)
72
- q = q.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
73
- k = k.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
74
- v = v.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
75
-
76
- # Dtype Uyuşmazlığını Çözen Güvenli RoPE Hesaplaması
77
- q_complex = torch.view_as_complex(q.float().reshape(*q.shape[:-1], -1, 2))
78
- k_complex = torch.view_as_complex(k.float().reshape(*k.shape[:-1], -1, 2))
79
- freqs = rope_freqs[:T].view(1, 1, T, -1).to(q_complex.device)
80
-
81
- # Girdinin orijinal tipine (bfloat16) güvenli geri dönüş
82
- q = torch.view_as_real(q_complex * freqs).flatten(3).to(x.dtype)
83
- k = torch.view_as_real(k_complex * freqs).flatten(3).to(x.dtype)
84
- v = v.to(x.dtype)
85
-
86
- scores = torch.matmul(q, k.transpose(-2, -1)) / (self.head_dim ** 0.5)
87
- mask = torch.full((T, T), float("-inf"), device=x.device).triu(1)
88
- scores = scores + mask
89
- probs = torch.softmax(scores, dim=-1).to(x.dtype)
90
- probs = self.dropout(probs)
91
-
92
- output = torch.matmul(probs, v)
93
- output = output.transpose(1, 2).contiguous().view(B, T, C)
94
- return self.wo(output)
95
-
96
- class SwiGLU(nn.Module):
97
- def __init__(self, hidden_dim: int, ffn_mult: float = 1.0):
98
- super().__init__()
99
- hidden_features = int(2 * hidden_dim * 4 / 3)
100
- hidden_features = int(ffn_mult * hidden_features)
101
- self.w1 = nn.Linear(hidden_dim, hidden_features, bias=False)
102
- self.w2 = nn.Linear(hidden_features, hidden_dim, bias=False)
103
- self.w3 = nn.Linear(hidden_dim, hidden_features, bias=False)
104
- def forward(self, x):
105
- return self.w2(F.silu(self.w1(x)) * self.w3(x))
106
-
107
- class TransformerBlock(nn.Module):
108
- def __init__(self, cfg):
109
- super().__init__()
110
- self.attn_norm = RMSNorm(cfg.hidden_dim, eps=cfg.norm_eps)
111
- self.attn = CausalSelfAttention(cfg.hidden_dim, cfg.n_heads, cfg.dropout)
112
- self.ffn_norm = RMSNorm(cfg.hidden_dim, eps=cfg.norm_eps)
113
- self.ffn = SwiGLU(cfg.hidden_dim, cfg.ffn_mult)
114
- def forward(self, x, rope_freqs):
115
- x = x + self.attn(self.attn_norm(x), rope_freqs)
116
- x = x + self.ffn(self.ffn_norm(x))
117
- return x
118
-
119
- # ==========================================
120
- # 3. RESMİ HUGGING FACE CAUSAL LM MODEL SINIFI
121
- # ==========================================
122
- class IvmeConversateV2HF(PreTrainedModel):
123
- config_class = IvmeConfig
124
- base_model_prefix = "model"
125
-
126
- def __init__(self, config):
127
- super().__init__(config)
128
- self.config = config
129
-
130
- self.tok_embed = nn.Embedding(config.vocab_size, config.hidden_dim)
131
- self.blocks = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
132
- self.final_norm = RMSNorm(config.hidden_dim, eps=config.norm_eps)
133
- self.lm_head = nn.Linear(config.hidden_dim, config.vocab_size, bias=False)
134
-
135
- if config.tie_word_embeddings:
136
- self.lm_head.weight = self.tok_embed.weight
137
-
138
- rope_freqs = precompute_rope_freqs(config.hidden_dim // config.n_heads, config.context_len, config.rope_theta)
139
- self.register_buffer("rope_freqs", rope_freqs, persistent=False)
140
-
141
- self.post_init()
142
-
143
- def load_state_dict(self, state_dict, strict=False):
144
- """Sözlükteki katman isim uyuşmazlıklarını (Qwen/Llama türevleri) otomatik olarak
145
- sizin orijinal Ivme katmanlarınıza bağlayan can kurtaran akıllı haritalama."""
146
- clean_state_dict = {}
147
- for k, v in state_dict.items():
148
- new_key = k
149
- # Attention Katman Haritalaması
150
- new_key = new_key.replace(".attn.q_proj.", ".attn.wq.")
151
- new_key = new_key.replace(".attn.k_proj.", ".attn.wk.")
152
- new_key = new_key.replace(".attn.v_proj.", ".attn.wv.")
153
- new_key = new_key.replace(".attn.out_proj.", ".attn.wo.")
154
- # FFN Katman Haritalaması
155
- new_key = new_key.replace(".ffn.gate_proj.", ".ffn.w1.")
156
- new_key = new_key.replace(".ffn.down_proj.", ".ffn.w2.")
157
- new_key = new_key.replace(".ffn.up_proj.", ".ffn.w3.")
158
- clean_state_dict[new_key] = v
159
-
160
- return super().load_state_dict(clean_state_dict, strict=False)
161
-
162
- def forward(self, input_ids=None, labels=None, **kwargs):
163
- B, T = input_ids.shape
164
- x = self.tok_embed(input_ids)
165
- for block in self.blocks:
166
- x = block(x, self.rope_freqs)
167
- x = self.final_norm(x)
168
- logits = self.lm_head(x)
169
-
170
- loss = None
171
- if labels is not None:
172
- loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1), ignore_index=-1)
173
-
174
- return CausalLMOutputWithPast(loss=loss, logits=logits)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tokenizer_config.json CHANGED
@@ -1,7 +1 @@
1
- {
2
- "add_bos_token": false,
3
- "add_eos_token": false,
4
- "model_max_length": 1024,
5
- "tokenizer_class": "PreTrainedTokenizerFast",
6
- "clean_up_tokenization_spaces": true
7
- }
 
1
+ {"add_bos_token": false, "add_eos_token": false, "model_max_length": 1024, "tokenizer_class": "PreTrainedTokenizerFast"}