PhysiQuanty commited on
Commit
4cc2013
·
verified ·
1 Parent(s): 97140a5

Upload 9 files

Browse files
config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "rne_tiny_gpt",
3
+ "architectures": [
4
+ "RNETinyGPTModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_rne_tiny_gpt.RNETinyGPTConfig",
8
+ "AutoModel": "modeling_rne_tiny_gpt.RNETinyGPTModel"
9
+ },
10
+ "vocab_size": 32768,
11
+ "ctx_len": 4096,
12
+ "max_position_embeddings": 4096,
13
+ "n_layer": 4,
14
+ "num_hidden_layers": 4,
15
+ "n_head": 4,
16
+ "num_attention_heads": 4,
17
+ "n_embd": 384,
18
+ "hidden_size": 384,
19
+ "dropout": 0.0,
20
+ "pad_token_id": 0,
21
+ "sep_token_id": 3,
22
+ "pooling": "mean",
23
+ "normalize_embeddings": true,
24
+ "attention_backend": "torch",
25
+ "torch_fallback": false,
26
+ "torch_dtype": "bfloat16",
27
+ "transformers_version": "custom"
28
+ }
configuration_rne_tiny_gpt.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class RNETinyGPTConfig(PretrainedConfig):
5
+ model_type = "rne_tiny_gpt"
6
+
7
+ def __init__(
8
+ self,
9
+ vocab_size=32768,
10
+ ctx_len=4096,
11
+ n_layer=4,
12
+ n_head=4,
13
+ n_embd=384,
14
+ dropout=0.0,
15
+ pad_token_id=0,
16
+ sep_token_id=3,
17
+ pooling="mean",
18
+ normalize_embeddings=True,
19
+ attention_backend="sage",
20
+ torch_fallback=False,
21
+ **kwargs,
22
+ ):
23
+ super().__init__(
24
+ pad_token_id=pad_token_id,
25
+ sep_token_id=sep_token_id,
26
+ **kwargs,
27
+ )
28
+
29
+ self.vocab_size = int(vocab_size)
30
+ self.ctx_len = int(ctx_len)
31
+ self.max_position_embeddings = int(ctx_len)
32
+
33
+ self.n_layer = int(n_layer)
34
+ self.n_head = int(n_head)
35
+ self.n_embd = int(n_embd)
36
+
37
+ self.num_hidden_layers = int(n_layer)
38
+ self.num_attention_heads = int(n_head)
39
+ self.hidden_size = int(n_embd)
40
+
41
+ self.dropout = float(dropout)
42
+ self.pooling = str(pooling)
43
+ self.normalize_embeddings = bool(normalize_embeddings)
44
+ self.attention_backend = str(attention_backend)
45
+ self.torch_fallback = bool(torch_fallback)
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "pad_token_id": 0,
3
+ "sep_token_id": 3
4
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d761488ad84788bd5f9f5ca3e4c10661c08d76c43616e7fac1e1b6832258e81
3
+ size 67650336
modeling_rne_tiny_gpt.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from transformers import PreTrainedModel
8
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
9
+
10
+ from .configuration_rne_tiny_gpt import RNETinyGPTConfig
11
+
12
+
13
+ class CausalSelfAttention(nn.Module):
14
+ def __init__(self, config: RNETinyGPTConfig):
15
+ super().__init__()
16
+
17
+ if config.n_embd % config.n_head != 0:
18
+ raise ValueError("n_embd must be divisible by n_head")
19
+
20
+ self.n_head = config.n_head
21
+ self.head_dim = config.n_embd // config.n_head
22
+ self.attention_backend = getattr(config, "attention_backend", "sage")
23
+ self.torch_fallback = bool(getattr(config, "torch_fallback", False))
24
+
25
+ if self.attention_backend not in ("sage", "torch"):
26
+ raise ValueError("attention_backend must be 'sage' or 'torch'")
27
+
28
+ if self.attention_backend == "sage" and self.head_dim not in (64, 96, 128):
29
+ raise ValueError(f"SageAttention requires head_dim in [64, 96, 128], got {self.head_dim}.")
30
+
31
+ if self.attention_backend == "sage" and config.dropout != 0.0:
32
+ raise ValueError("SageAttention strict mode requires dropout=0.0")
33
+
34
+ self.qkv = nn.Linear(config.n_embd, 3 * config.n_embd, bias=False)
35
+ self.proj = nn.Linear(config.n_embd, config.n_embd, bias=False)
36
+ self.dropout = nn.Dropout(config.dropout)
37
+
38
+ mask = torch.tril(torch.ones(config.ctx_len, config.ctx_len, dtype=torch.bool))
39
+ self.register_buffer("mask", mask.view(1, 1, config.ctx_len, config.ctx_len), persistent=False)
40
+
41
+ self.sageattn = None
42
+ if self.attention_backend == "sage":
43
+ try:
44
+ from sageattention import sageattn
45
+ self.sageattn = sageattn
46
+ except Exception as exc:
47
+ if self.torch_fallback:
48
+ self.attention_backend = "torch"
49
+ self.sageattn = None
50
+ else:
51
+ raise RuntimeError(
52
+ "Ce modèle a été entraîné avec SageAttention. "
53
+ "Installe sageattention: pip install sageattention"
54
+ ) from exc
55
+
56
+ def _torch_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, t: int) -> torch.Tensor:
57
+ scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
58
+ scores = scores.masked_fill(self.mask[:, :, :t, :t] == 0, float("-inf"))
59
+ att = F.softmax(scores.float(), dim=-1).to(q.dtype)
60
+ att = self.dropout(att)
61
+ y = att @ v
62
+ return y
63
+
64
+ def _sage_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor):
65
+ if self.sageattn is None:
66
+ raise RuntimeError("SageAttention demandé mais sageattn est None")
67
+ if not q.is_cuda:
68
+ if self.torch_fallback:
69
+ return None
70
+ raise RuntimeError(
71
+ "SageAttention exige CUDA. Passe le modèle sur CUDA avec model.cuda(), "
72
+ "ou active torch_fallback dans config.json."
73
+ )
74
+ q = q.contiguous()
75
+ k = k.contiguous()
76
+ v = v.contiguous()
77
+ return self.sageattn(q, k, v, tensor_layout="HND", is_causal=True)
78
+
79
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
80
+ b, t, c = x.shape
81
+ qkv = self.qkv(x)
82
+ q, k, v = qkv.chunk(3, dim=-1)
83
+ q = q.view(b, t, self.n_head, self.head_dim).transpose(1, 2).contiguous()
84
+ k = k.view(b, t, self.n_head, self.head_dim).transpose(1, 2).contiguous()
85
+ v = v.view(b, t, self.n_head, self.head_dim).transpose(1, 2).contiguous()
86
+
87
+ if self.attention_backend == "sage":
88
+ y = self._sage_attention(q, k, v)
89
+ if y is None:
90
+ y = self._torch_attention(q, k, v, t)
91
+ else:
92
+ y = self._torch_attention(q, k, v, t)
93
+
94
+ y = y.transpose(1, 2).contiguous().view(b, t, c)
95
+ y = self.proj(y)
96
+ return y
97
+
98
+
99
+ class MLP(nn.Module):
100
+ def __init__(self, config: RNETinyGPTConfig):
101
+ super().__init__()
102
+ self.fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=False)
103
+ self.proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=False)
104
+ self.dropout = nn.Dropout(config.dropout)
105
+
106
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
107
+ x = self.fc(x)
108
+ x = F.gelu(x)
109
+ x = self.proj(x)
110
+ x = self.dropout(x)
111
+ return x
112
+
113
+
114
+ class Block(nn.Module):
115
+ def __init__(self, config: RNETinyGPTConfig):
116
+ super().__init__()
117
+ self.ln1 = nn.LayerNorm(config.n_embd)
118
+ self.attn = CausalSelfAttention(config)
119
+ self.ln2 = nn.LayerNorm(config.n_embd)
120
+ self.mlp = MLP(config)
121
+
122
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
123
+ x = x + self.attn(self.ln1(x))
124
+ x = x + self.mlp(self.ln2(x))
125
+ return x
126
+
127
+
128
+ class RNETinyGPTPreTrainedModel(PreTrainedModel):
129
+ config_class = RNETinyGPTConfig
130
+ base_model_prefix = "rne_tiny_gpt"
131
+ supports_gradient_checkpointing = False
132
+
133
+ def _init_weights(self, module):
134
+ if isinstance(module, nn.Linear):
135
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
136
+ if module.bias is not None:
137
+ nn.init.zeros_(module.bias)
138
+ if isinstance(module, nn.Embedding):
139
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
140
+
141
+
142
+ class RNETinyGPTModel(RNETinyGPTPreTrainedModel):
143
+ def __init__(self, config: RNETinyGPTConfig):
144
+ super().__init__(config)
145
+ self.tok_emb = nn.Embedding(config.vocab_size, config.n_embd)
146
+ self.pos_emb = nn.Embedding(config.ctx_len, config.n_embd)
147
+ self.drop = nn.Dropout(config.dropout)
148
+ self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)])
149
+ self.ln_f = nn.LayerNorm(config.n_embd)
150
+ self.post_init()
151
+
152
+ def _mean_pool(self, hidden: torch.Tensor, attention_mask: Optional[torch.Tensor], input_ids: torch.Tensor) -> torch.Tensor:
153
+ if attention_mask is None:
154
+ mask = input_ids.ne(self.config.pad_token_id)
155
+ else:
156
+ mask = attention_mask.bool()
157
+ mask = mask.unsqueeze(-1).to(hidden.dtype)
158
+ summed = (hidden * mask).sum(dim=1)
159
+ denom = mask.sum(dim=1).clamp(min=1.0)
160
+ return summed / denom
161
+
162
+ def _last_pool(self, hidden: torch.Tensor, attention_mask: Optional[torch.Tensor], input_ids: torch.Tensor) -> torch.Tensor:
163
+ if attention_mask is None:
164
+ mask = input_ids.ne(self.config.pad_token_id)
165
+ else:
166
+ mask = attention_mask.bool()
167
+ lengths = mask.sum(dim=1).clamp(min=1)
168
+ last_pos = lengths - 1
169
+ batch_idx = torch.arange(input_ids.size(0), device=input_ids.device)
170
+ return hidden[batch_idx, last_pos, :]
171
+
172
+ def forward(
173
+ self,
174
+ input_ids: torch.LongTensor,
175
+ attention_mask: Optional[torch.Tensor] = None,
176
+ return_dict: Optional[bool] = True,
177
+ **kwargs,
178
+ ):
179
+ b, t = input_ids.shape
180
+ if t > self.config.ctx_len:
181
+ raise ValueError(f"Input length {t} > ctx_len {self.config.ctx_len}. Truncate before calling the model.")
182
+
183
+ pos = torch.arange(0, t, dtype=torch.long, device=input_ids.device).unsqueeze(0)
184
+ x = self.tok_emb(input_ids) + self.pos_emb(pos)
185
+ x = self.drop(x)
186
+ for block in self.blocks:
187
+ x = block(x)
188
+ hidden = self.ln_f(x)
189
+
190
+ if self.config.pooling == "last":
191
+ pooled = self._last_pool(hidden, attention_mask, input_ids)
192
+ else:
193
+ pooled = self._mean_pool(hidden, attention_mask, input_ids)
194
+
195
+ pooled = pooled.float()
196
+ if self.config.normalize_embeddings:
197
+ pooled = F.normalize(pooled, p=2, dim=-1)
198
+
199
+ if not return_dict:
200
+ return (hidden, pooled)
201
+
202
+ return BaseModelOutputWithPooling(
203
+ last_hidden_state=hidden,
204
+ pooler_output=pooled,
205
+ hidden_states=None,
206
+ attentions=None,
207
+ )
208
+
209
+ @torch.no_grad()
210
+ def encode(self, input_ids: torch.LongTensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
211
+ out = self.forward(input_ids=input_ids, attention_mask=attention_mask, return_dict=True)
212
+ return out.pooler_output
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ safetensors
4
+ tokenizers
5
+ sageattention
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "unk_token": "[UNK]",
3
+ "pad_token": "[PAD]",
4
+ "cls_token": "[CLS]",
5
+ "sep_token": "[SEP]",
6
+ "mask_token": "[MASK]"
7
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tokenizer_class": "PreTrainedTokenizerFast",
3
+ "model_max_length": 4096,
4
+ "padding_side": "right",
5
+ "truncation_side": "right",
6
+ "clean_up_tokenization_spaces": false,
7
+ "unk_token": "[UNK]",
8
+ "pad_token": "[PAD]",
9
+ "cls_token": "[CLS]",
10
+ "sep_token": "[SEP]",
11
+ "mask_token": "[MASK]"
12
+ }