QuantaSparkLabs commited on
Commit
59ea527
·
verified ·
1 Parent(s): 6a5f63a

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "F_ID": 42,
3
+ "M_ID": 49,
4
+ "architectures": [
5
+ "FirstNameGenderForCausalLM"
6
+ ],
7
+ "attention_backend": "pytorch",
8
+ "auto_map": {
9
+ "AutoConfig": "modeling_firstname_gender.FirstNameGenderConfig",
10
+ "AutoModel": "modeling_firstname_gender.FirstNameGenderForCausalLM",
11
+ "AutoModelForCausalLM": "modeling_firstname_gender.FirstNameGenderForCausalLM"
12
+ },
13
+ "bos_token_id": 2,
14
+ "ctx_len": 20,
15
+ "dropout": 0.0,
16
+ "dtype": "float32",
17
+ "eos_token_id": 3,
18
+ "hidden_size": 384,
19
+ "max_position_embeddings": 20,
20
+ "model_type": "firstname_gender",
21
+ "n_embd": 384,
22
+ "n_head": 4,
23
+ "n_layer": 4,
24
+ "num_attention_heads": 4,
25
+ "num_hidden_layers": 4,
26
+ "pad_token_id": 0,
27
+ "transformers_version": "5.10.2",
28
+ "use_cache": false,
29
+ "vocab_size": 32768
30
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:706d118f19b2808209911f99dbe6ac495ead204370cf8358fd3210bde43117c1
3
+ size 129036560
modeling_firstname_gender.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from transformers import PreTrainedModel, PretrainedConfig
7
+ from transformers.modeling_outputs import CausalLMOutput
8
+
9
+
10
+ _SAGE_ATTN = None
11
+ _SAGE_AVAILABLE = False
12
+ _SAGE_IMPORT_ERROR = None
13
+
14
+ try:
15
+ from sageattention import sageattn
16
+ _SAGE_ATTN = sageattn
17
+ _SAGE_AVAILABLE = True
18
+ except Exception as e:
19
+ _SAGE_IMPORT_ERROR = repr(e)
20
+ _SAGE_ATTN = None
21
+ _SAGE_AVAILABLE = False
22
+
23
+
24
+ class FirstNameGenderConfig(PretrainedConfig):
25
+ model_type = "firstname_gender"
26
+
27
+ def __init__(
28
+ self,
29
+ vocab_size=32768,
30
+ ctx_len=20,
31
+ n_layer=4,
32
+ n_head=4,
33
+ n_embd=256,
34
+ dropout=0.0,
35
+ bos_token_id=None,
36
+ eos_token_id=None,
37
+ pad_token_id=0,
38
+ F_ID=42,
39
+ M_ID=49,
40
+ attention_backend="sage",
41
+ **kwargs,
42
+ ):
43
+ super().__init__(
44
+ bos_token_id=bos_token_id,
45
+ eos_token_id=eos_token_id,
46
+ pad_token_id=pad_token_id,
47
+ **kwargs,
48
+ )
49
+
50
+ self.vocab_size = vocab_size
51
+ self.ctx_len = ctx_len
52
+ self.max_position_embeddings = ctx_len
53
+ self.n_layer = n_layer
54
+ self.n_head = n_head
55
+ self.n_embd = n_embd
56
+ self.hidden_size = n_embd
57
+ self.num_hidden_layers = n_layer
58
+ self.num_attention_heads = n_head
59
+ self.dropout = dropout
60
+ self.F_ID = F_ID
61
+ self.M_ID = M_ID
62
+ self.attention_backend = attention_backend
63
+
64
+
65
+ def sageattention_available():
66
+ return bool(_SAGE_AVAILABLE and _SAGE_ATTN is not None)
67
+
68
+
69
+ def sageattention_import_error():
70
+ return _SAGE_IMPORT_ERROR
71
+
72
+
73
+ class CausalSelfAttention(nn.Module):
74
+ def __init__(self, config):
75
+ super().__init__()
76
+
77
+ if config.n_embd % config.n_head != 0:
78
+ raise ValueError("n_embd must be divisible by n_head")
79
+
80
+ self.config = config
81
+ self.n_head = config.n_head
82
+ self.head_dim = config.n_embd // config.n_head
83
+
84
+ self.qkv = nn.Linear(config.n_embd, 3 * config.n_embd, bias=False)
85
+ self.proj = nn.Linear(config.n_embd, config.n_embd, bias=False)
86
+ self.dropout = nn.Dropout(config.dropout)
87
+
88
+ mask = torch.tril(torch.ones(config.ctx_len, config.ctx_len))
89
+ self.register_buffer(
90
+ "mask",
91
+ mask.view(1, 1, config.ctx_len, config.ctx_len),
92
+ persistent=False,
93
+ )
94
+
95
+ def _forward_sage(self, q, k, v):
96
+ y = _SAGE_ATTN(
97
+ q,
98
+ k,
99
+ v,
100
+ tensor_layout="HND",
101
+ is_causal=True,
102
+ )
103
+
104
+ return y
105
+
106
+ def _forward_pytorch(self, q, k, v, t):
107
+ scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
108
+ scores = scores.masked_fill(
109
+ self.mask[:, :, :t, :t] == 0,
110
+ torch.finfo(scores.dtype).min,
111
+ )
112
+
113
+ att = F.softmax(scores, dim=-1)
114
+ att = self.dropout(att)
115
+
116
+ y = att @ v
117
+
118
+ return y
119
+
120
+ def forward(self, x):
121
+ b, t, c = x.shape
122
+
123
+ qkv = self.qkv(x)
124
+ q, k, v = qkv.chunk(3, dim=-1)
125
+
126
+ q = q.view(b, t, self.n_head, self.head_dim).transpose(1, 2).contiguous()
127
+ k = k.view(b, t, self.n_head, self.head_dim).transpose(1, 2).contiguous()
128
+ v = v.view(b, t, self.n_head, self.head_dim).transpose(1, 2).contiguous()
129
+
130
+ use_sage = (
131
+ getattr(self.config, "attention_backend", "sage") == "sage"
132
+ and sageattention_available()
133
+ and q.is_cuda
134
+ )
135
+
136
+ if use_sage:
137
+ try:
138
+ y = self._forward_sage(q, k, v)
139
+ except Exception:
140
+ y = self._forward_pytorch(q, k, v, t)
141
+ else:
142
+ y = self._forward_pytorch(q, k, v, t)
143
+
144
+ y = y.transpose(1, 2).contiguous().view(b, t, c)
145
+ y = self.proj(y)
146
+
147
+ return y
148
+
149
+
150
+ class MLP(nn.Module):
151
+ def __init__(self, config):
152
+ super().__init__()
153
+
154
+ self.fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=False)
155
+ self.proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=False)
156
+ self.dropout = nn.Dropout(config.dropout)
157
+
158
+ def forward(self, x):
159
+ x = self.fc(x)
160
+ x = F.gelu(x)
161
+ x = self.proj(x)
162
+ x = self.dropout(x)
163
+
164
+ return x
165
+
166
+
167
+ class Block(nn.Module):
168
+ def __init__(self, config):
169
+ super().__init__()
170
+
171
+ self.ln1 = nn.LayerNorm(config.n_embd)
172
+ self.attn = CausalSelfAttention(config)
173
+ self.ln2 = nn.LayerNorm(config.n_embd)
174
+ self.mlp = MLP(config)
175
+
176
+ def forward(self, x):
177
+ x = x + self.attn(self.ln1(x))
178
+ x = x + self.mlp(self.ln2(x))
179
+
180
+ return x
181
+
182
+
183
+ class FirstNameGenderForCausalLM(PreTrainedModel):
184
+ config_class = FirstNameGenderConfig
185
+ base_model_prefix = "model"
186
+ supports_gradient_checkpointing = False
187
+
188
+ def __init__(self, config):
189
+ super().__init__(config)
190
+
191
+ self.config = config
192
+
193
+ self.tok_emb = nn.Embedding(config.vocab_size, config.n_embd)
194
+ self.pos_emb = nn.Embedding(config.ctx_len, config.n_embd)
195
+ self.drop = nn.Dropout(config.dropout)
196
+
197
+ self.blocks = nn.ModuleList(
198
+ [Block(config) for _ in range(config.n_layer)]
199
+ )
200
+
201
+ self.ln_f = nn.LayerNorm(config.n_embd)
202
+ self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
203
+
204
+ self.head.weight = self.tok_emb.weight
205
+
206
+ def get_input_embeddings(self):
207
+ return self.tok_emb
208
+
209
+ def set_input_embeddings(self, value):
210
+ self.tok_emb = value
211
+ self.head.weight = self.tok_emb.weight
212
+
213
+ def get_output_embeddings(self):
214
+ return self.head
215
+
216
+ def set_output_embeddings(self, new_embeddings):
217
+ self.head = new_embeddings
218
+
219
+ def get_attention_backend(self):
220
+ if getattr(self.config, "attention_backend", "sage") == "sage" and sageattention_available():
221
+ return "sageattention"
222
+
223
+ return "pytorch"
224
+
225
+ def forward(
226
+ self,
227
+ input_ids=None,
228
+ attention_mask=None,
229
+ labels=None,
230
+ **kwargs,
231
+ ):
232
+ if input_ids is None:
233
+ raise ValueError("input_ids is required")
234
+
235
+ b, t = input_ids.shape
236
+
237
+ if t > self.config.ctx_len:
238
+ input_ids = input_ids[:, -self.config.ctx_len:]
239
+ t = input_ids.shape[1]
240
+
241
+ if labels is not None:
242
+ labels = labels[:, -self.config.ctx_len:]
243
+
244
+ pos = torch.arange(
245
+ 0,
246
+ t,
247
+ dtype=torch.long,
248
+ device=input_ids.device,
249
+ ).unsqueeze(0)
250
+
251
+ x = self.tok_emb(input_ids) + self.pos_emb(pos)
252
+ x = self.drop(x)
253
+
254
+ for block in self.blocks:
255
+ x = block(x)
256
+
257
+ x = self.ln_f(x)
258
+ logits = self.head(x)
259
+
260
+ loss = None
261
+
262
+ if labels is not None:
263
+ loss = F.cross_entropy(
264
+ logits.reshape(-1, logits.size(-1)),
265
+ labels.reshape(-1),
266
+ ignore_index=-100,
267
+ )
268
+
269
+ return CausalLMOutput(
270
+ loss=loss,
271
+ logits=logits,
272
+ )
273
+
274
+ @torch.no_grad()
275
+ def predict_gender(self, input_ids):
276
+ out = self.forward(input_ids=input_ids)
277
+ logits = out.logits
278
+
279
+ non_pad = input_ids.ne(self.config.pad_token_id)
280
+ lengths = non_pad.sum(dim=1).clamp(min=1)
281
+ last_pos = lengths - 1
282
+
283
+ batch_idx = torch.arange(input_ids.size(0), device=input_ids.device)
284
+ last_logits = logits[batch_idx, last_pos, :]
285
+
286
+ fm_logits = torch.stack(
287
+ [
288
+ last_logits[:, self.config.F_ID],
289
+ last_logits[:, self.config.M_ID],
290
+ ],
291
+ dim=-1,
292
+ )
293
+
294
+ probs = F.softmax(fm_logits.float(), dim=-1)
295
+ pred_idx = probs.argmax(dim=-1)
296
+
297
+ return pred_idx, probs
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "[BOS]",
4
+ "clean_up_tokenization_spaces": false,
5
+ "eos_token": "[EOS]",
6
+ "is_local": false,
7
+ "local_files_only": false,
8
+ "lowercase": false,
9
+ "mask_token": "[MASK]",
10
+ "max_length": null,
11
+ "model_max_length": 20,
12
+ "pad_to_multiple_of": null,
13
+ "pad_token": "[PAD]",
14
+ "pad_token_type_id": 0,
15
+ "padding_side": "right",
16
+ "tokenizer_class": "TokenizersBackend",
17
+ "truncation_side": "right",
18
+ "unk_token": "[UNK]",
19
+ "vocab_size": 32768
20
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05727dced653438df160bb8641a235f1f6a29b67eb049c96044874005d6eb0e8
3
+ size 5201