SlitherCode commited on
Commit
8aa2894
·
verified ·
1 Parent(s): 55bfd70

Upload ParchmentForCausalLM

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ParchmentForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_parchment.ParchmentConfig",
7
+ "AutoModelForCausalLM": "modeling_parchment.ParchmentForCausalLM"
8
+ },
9
+ "bos_token_id": 100257,
10
+ "d_ff": 3072,
11
+ "d_model": 768,
12
+ "dtype": "float32",
13
+ "eos_token_id": 100257,
14
+ "hidden_size": 768,
15
+ "max_seq_len": 1024,
16
+ "model_type": "parchment",
17
+ "n_heads": 12,
18
+ "n_layers": 12,
19
+ "num_attention_heads": 12,
20
+ "num_hidden_layers": 12,
21
+ "pad_token_id": 100257,
22
+ "rms_norm_eps": 1e-06,
23
+ "rope_base": 10000.0,
24
+ "tie_word_embeddings": true,
25
+ "transformers_version": "5.8.1",
26
+ "vocab_size": 100277
27
+ }
configuration_parchment.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class ParchmentConfig(PretrainedConfig):
5
+ model_type = "parchment"
6
+
7
+ def __init__(
8
+ self,
9
+ vocab_size: int = 100277,
10
+ d_model: int = 768,
11
+ n_heads: int = 12,
12
+ n_layers: int = 12,
13
+ max_seq_len: int = 1024,
14
+ rms_norm_eps: float = 1e-6,
15
+ rope_base: float = 10000.0,
16
+ tie_word_embeddings: bool = True,
17
+ **kwargs,
18
+ ):
19
+ self.vocab_size = vocab_size
20
+ self.d_model = d_model
21
+ self.n_heads = n_heads
22
+ self.n_layers = n_layers
23
+ self.max_seq_len = max_seq_len
24
+ self.rms_norm_eps = rms_norm_eps
25
+ self.rope_base = rope_base
26
+ # aliases expected by transformers internals
27
+ self.num_hidden_layers = n_layers
28
+ self.hidden_size = d_model
29
+ self.num_attention_heads = n_heads
30
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 100257,
4
+ "eos_token_id": 100257,
5
+ "output_attentions": false,
6
+ "output_hidden_states": false,
7
+ "pad_token_id": 100257,
8
+ "transformers_version": "5.8.1"
9
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dcc18db160983dd44f101dccaff6ea556ee587de8397b8e5d76f9c9f5e13eafb
3
+ size 647880264
modeling_parchment.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from transformers import PreTrainedModel
6
+ from transformers.generation import GenerationMixin
7
+ from transformers.modeling_outputs import CausalLMOutputWithPast
8
+
9
+ from .configuration_parchment import ParchmentConfig
10
+
11
+
12
+ class Embeddings(nn.Module):
13
+ def __init__(self, vocab_size, d_model):
14
+ super().__init__()
15
+ self.embeds = nn.Embedding(vocab_size, d_model)
16
+ nn.init.normal_(self.embeds.weight, mean=0, std=d_model ** -0.5)
17
+
18
+ def forward(self, token_ids):
19
+ return self.embeds(token_ids)
20
+
21
+
22
+ class RoPE(nn.Module):
23
+ def __init__(self, d_k, max_seq_len, base=10000.0):
24
+ super().__init__()
25
+ self.max_seq_len = max_seq_len
26
+ # persistent=True so inv_freq is saved/loaded via from_pretrained
27
+ inv_freq = 1.0 / (base ** (torch.arange(0, d_k, 2).float() / d_k))
28
+ self.register_buffer("inv_freq", inv_freq, persistent=True)
29
+ self._cos_cache: torch.Tensor | None = None
30
+ self._sin_cache: torch.Tensor | None = None
31
+
32
+ def _build_cache(self, device: torch.device, dtype: torch.dtype):
33
+ t = torch.arange(self.max_seq_len, device=device, dtype=torch.float32)
34
+ freqs = torch.outer(t, self.inv_freq.to(device, torch.float32))
35
+ emb = torch.cat([freqs, freqs], dim=-1)
36
+ self._cos_cache = emb.cos()[None, None].to(dtype)
37
+ self._sin_cache = emb.sin()[None, None].to(dtype)
38
+
39
+ def rotate_half(self, x):
40
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
41
+ return torch.cat([-x2, x1], dim=-1)
42
+
43
+ def forward(self, q, k):
44
+ if self._cos_cache is None or self._cos_cache.device != q.device or self._cos_cache.dtype != q.dtype:
45
+ self._build_cache(q.device, q.dtype)
46
+ seq = q.shape[2]
47
+ cos = self._cos_cache[:, :, :seq]
48
+ sin = self._sin_cache[:, :, :seq]
49
+ q = (q * cos) + (self.rotate_half(q) * sin)
50
+ k = (k * cos) + (self.rotate_half(k) * sin)
51
+ return q, k
52
+
53
+
54
+ class RMSNorm(nn.Module):
55
+ def __init__(self, d_model, eps=1e-6):
56
+ super().__init__()
57
+ self.scale = nn.Parameter(torch.ones(d_model))
58
+ self.eps = eps
59
+
60
+ def forward(self, x):
61
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.scale
62
+
63
+
64
+ class MultiHeadAttention(nn.Module):
65
+ def __init__(self, n_heads, d_model, max_seq_len, rope_base):
66
+ super().__init__()
67
+ self.n_heads = n_heads
68
+ self.d_k = d_model // n_heads
69
+ self.d_model = d_model
70
+ self.W_Q = nn.Linear(d_model, d_model, bias=False)
71
+ self.W_K = nn.Linear(d_model, d_model, bias=False)
72
+ self.W_V = nn.Linear(d_model, d_model, bias=False)
73
+ self.W_O = nn.Linear(d_model, d_model, bias=False)
74
+ self.rope = RoPE(self.d_k, max_seq_len, base=rope_base)
75
+ self.W_O.RESIDUAL_SCALE_INIT = True
76
+
77
+ def forward(self, x):
78
+ B, T, _ = x.shape
79
+ Q = self.W_Q(x).view(B, T, self.n_heads, self.d_k).permute(0, 2, 1, 3)
80
+ K = self.W_K(x).view(B, T, self.n_heads, self.d_k).permute(0, 2, 1, 3)
81
+ V = self.W_V(x).view(B, T, self.n_heads, self.d_k).permute(0, 2, 1, 3)
82
+ Q, K = self.rope(Q, K)
83
+ out = F.scaled_dot_product_attention(Q, K, V, is_causal=True)
84
+ out = out.permute(0, 2, 1, 3).contiguous().view(B, T, self.d_model)
85
+ return self.W_O(out)
86
+
87
+
88
+ class SwiGLU(nn.Module):
89
+ def __init__(self, d_model):
90
+ super().__init__()
91
+ hidden = int(2 / 3 * 4 * d_model)
92
+ hidden = (hidden + 63) // 64 * 64
93
+ self.w1 = nn.Linear(d_model, hidden, bias=False)
94
+ self.w2 = nn.Linear(hidden, d_model, bias=False)
95
+ self.w3 = nn.Linear(d_model, hidden, bias=False)
96
+ self.w2.RESIDUAL_SCALE_INIT = True
97
+
98
+ def forward(self, x):
99
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
100
+
101
+
102
+ class TransformerBlock(nn.Module):
103
+ def __init__(self, d_model, n_heads, max_seq_len, rope_base):
104
+ super().__init__()
105
+ self.attn = MultiHeadAttention(n_heads, d_model, max_seq_len, rope_base)
106
+ self.ff = SwiGLU(d_model)
107
+ self.norm1 = RMSNorm(d_model)
108
+ self.norm2 = RMSNorm(d_model)
109
+
110
+ def forward(self, x):
111
+ x = x + self.attn(self.norm1(x))
112
+ x = x + self.ff(self.norm2(x))
113
+ return x
114
+
115
+
116
+ class ParchmentModel(PreTrainedModel):
117
+ config_class = ParchmentConfig
118
+ base_model_prefix = "model"
119
+
120
+ def __init__(self, config: ParchmentConfig):
121
+ super().__init__(config)
122
+ self.embeddings = Embeddings(config.vocab_size, config.d_model)
123
+ self.blocks = nn.ModuleList([
124
+ TransformerBlock(config.d_model, config.n_heads, config.max_seq_len, config.rope_base)
125
+ for _ in range(config.n_layers)
126
+ ])
127
+ self.norm = RMSNorm(config.d_model, eps=config.rms_norm_eps)
128
+ self.post_init()
129
+
130
+ def _init_weights(self, module):
131
+ if isinstance(module, nn.Linear):
132
+ std = 0.02
133
+ if hasattr(module, "RESIDUAL_SCALE_INIT"):
134
+ std /= math.sqrt(2 * self.config.n_layers)
135
+ nn.init.normal_(module.weight, mean=0.0, std=std)
136
+ if module.bias is not None:
137
+ nn.init.zeros_(module.bias)
138
+ elif isinstance(module, nn.Embedding):
139
+ nn.init.normal_(module.weight, mean=0, std=self.config.d_model ** -0.5)
140
+
141
+ def forward(self, input_ids: torch.LongTensor) -> torch.Tensor:
142
+ x = self.embeddings(input_ids)
143
+ for block in self.blocks:
144
+ x = block(x)
145
+ return self.norm(x)
146
+
147
+
148
+ class ParchmentForCausalLM(PreTrainedModel, GenerationMixin):
149
+ config_class = ParchmentConfig
150
+ base_model_prefix = "model"
151
+ _tied_weights_keys = {"lm_head.weight": "model.embeddings.embeds.weight"}
152
+ _keys_to_ignore_on_load_missing = [r"lm_head\.weight", r".*\.rope\."]
153
+ _supports_cache_class = False
154
+ _supports_static_cache = False
155
+
156
+ def __init__(self, config: ParchmentConfig):
157
+ super().__init__(config)
158
+ self.model = ParchmentModel(config)
159
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
160
+ self.post_init()
161
+
162
+ def get_input_embeddings(self):
163
+ return self.model.embeddings.embeds
164
+
165
+ def set_input_embeddings(self, value):
166
+ self.model.embeddings.embeds = value
167
+
168
+ def get_output_embeddings(self):
169
+ return self.lm_head
170
+
171
+ def set_output_embeddings(self, value):
172
+ self.lm_head = value
173
+
174
+ def _init_weights(self, module):
175
+ self.model._init_weights(module)
176
+
177
+ def forward(
178
+ self,
179
+ input_ids: torch.LongTensor,
180
+ attention_mask: torch.Tensor | None = None,
181
+ labels: torch.LongTensor | None = None,
182
+ **kwargs,
183
+ ) -> CausalLMOutputWithPast:
184
+ hidden = self.model(input_ids)
185
+ logits = self.lm_head(hidden)
186
+
187
+ loss = None
188
+ if labels is not None:
189
+ shift_logits = logits[:, :-1, :].contiguous()
190
+ shift_labels = labels[:, 1:].contiguous()
191
+ loss = F.cross_entropy(
192
+ shift_logits.view(-1, self.config.vocab_size),
193
+ shift_labels.view(-1),
194
+ )
195
+
196
+ return CausalLMOutputWithPast(loss=loss, logits=logits)
197
+
198
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs):
199
+ return {
200
+ "input_ids": input_ids[:, -self.config.max_seq_len:],
201
+ "attention_mask": attention_mask,
202
+ }