xiaoyewuz-Ruster commited on
Commit
c3fd734
·
verified ·
1 Parent(s): b686230

Upload TextGenerationPipeline

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,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ZZJRabbit22ForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "zzjrabbit22.ZZJRabbit22Config",
7
+ "AutoModelForCausalLM": "zzjrabbit22.ZZJRabbit22ForCausalLM"
8
+ },
9
+ "eos_token_id": 0,
10
+ "hidden_size": 1024,
11
+ "model_type": "zzjrabbit22",
12
+ "num_attention_heads": 8,
13
+ "num_layers": 12,
14
+ "pad_token_id": 0,
15
+ "torch_dtype": "float32",
16
+ "transformers_version": "4.53.0",
17
+ "vocab_size": 30000
18
+ }
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "eos_token_id": 0,
4
+ "pad_token_id": 0,
5
+ "transformers_version": "4.53.0"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26866d5bc502fe16f89183c817b279db87d17246b51ced7fe695cf8378769ac4
3
+ size 682448056
special_tokens_map.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "eos_token": {
3
+ "content": "<eos>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "pad_token": {
10
+ "content": "<eos>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ }
16
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<eos>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ }
11
+ },
12
+ "auto_map": {
13
+ "AutoTokenizer": [
14
+ "zzjrabbit22.ZZJRabbit22Tokenizer",
15
+ null
16
+ ]
17
+ },
18
+ "clean_up_tokenization_spaces": false,
19
+ "eos_token": "<eos>",
20
+ "extra_special_tokens": {},
21
+ "model_max_length": 1000000000000000019884624838656,
22
+ "pad_token": "<eos>",
23
+ "tokenizer_class": "ZZJRabbit22Tokenizer"
24
+ }
zzjrabbit22.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os.path
3
+ from typing import Optional, Union
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from tokenizers import Tokenizer
8
+ from transformers import (
9
+ GenerationMixin,
10
+ PretrainedConfig,
11
+ PreTrainedModel,
12
+ PreTrainedTokenizer,
13
+ )
14
+ from transformers.modeling_outputs import BaseModelOutput, CausalLMOutput
15
+
16
+
17
+ class ZZJRabbit22Config(PretrainedConfig):
18
+ model_type = "zzjrabbit22"
19
+
20
+ def __init__(
21
+ self,
22
+ num_layers: int = 12,
23
+ num_attention_heads: int = 8,
24
+ vocab_size: int = 10000,
25
+ hidden_size: int = 1024,
26
+ **kwargs,
27
+ ):
28
+ self.num_layers = num_layers
29
+ self.num_attention_heads = num_attention_heads
30
+ self.vocab_size = vocab_size
31
+ self.hidden_size = hidden_size
32
+ assert hidden_size % num_attention_heads == 0
33
+ super().__init__(**kwargs)
34
+
35
+
36
+ class ZZJRabbit22PE(nn.Module):
37
+ def __init__(self, hidden_size: int, max_len: int = 32768):
38
+ super().__init__()
39
+ pe = torch.zeros(max_len, hidden_size)
40
+ position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
41
+ div_term = torch.exp(
42
+ torch.arange(0, hidden_size, 2).float() * (-math.log(10000.0) / hidden_size)
43
+ )
44
+ pe[:, 0::2] = torch.sin(position * div_term)
45
+ pe[:, 1::2] = torch.cos(position * div_term)
46
+ pe = pe.unsqueeze(0).transpose(0, 1)
47
+ self.register_buffer("pe", pe)
48
+
49
+ def forward(self, x: torch.Tensor):
50
+ return x + self.pe[: x.size(0), :]
51
+
52
+
53
+ class ZZJRabbit22Attention(nn.Module):
54
+ def __init__(self, config: ZZJRabbit22Config):
55
+ super().__init__()
56
+ self.config = config
57
+ self.head_dim = config.hidden_size // config.num_attention_heads
58
+ self.q_proj = nn.Linear(config.hidden_size, config.hidden_size)
59
+ self.k_proj = nn.Linear(config.hidden_size, config.hidden_size)
60
+ self.v_proj = nn.Linear(config.hidden_size, config.hidden_size)
61
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size)
62
+ self.dropout = nn.Dropout(0.1)
63
+
64
+ def forward(
65
+ self,
66
+ x: torch.Tensor,
67
+ key_padding_mask: Optional[torch.BoolTensor] = None,
68
+ attn_mask: Optional[torch.BoolTensor] = None,
69
+ ):
70
+ batch_size = x.size(0)
71
+ Q = (
72
+ self.q_proj(x)
73
+ .view(batch_size, -1, self.config.num_attention_heads, self.head_dim)
74
+ .transpose(1, 2)
75
+ )
76
+ K = (
77
+ self.k_proj(x)
78
+ .view(batch_size, -1, self.config.num_attention_heads, self.head_dim)
79
+ .transpose(1, 2)
80
+ )
81
+ V = (
82
+ self.v_proj(x)
83
+ .view(batch_size, -1, self.config.num_attention_heads, self.head_dim)
84
+ .transpose(1, 2)
85
+ )
86
+ scores = torch.matmul(Q, K.transpose(-2, -1)) / torch.sqrt(
87
+ torch.tensor(self.head_dim, dtype=torch.float32)
88
+ )
89
+ if key_padding_mask is not None:
90
+ scores = scores.masked_fill(
91
+ key_padding_mask.view(batch_size, 1, 1, -1), float("-inf")
92
+ )
93
+ if attn_mask is not None:
94
+ scores = scores.masked_fill(attn_mask, float("-inf"))
95
+ attn_weights = nn.functional.softmax(scores, dim=-1)
96
+ attn_weights = self.dropout(attn_weights)
97
+ context = torch.matmul(attn_weights, V)
98
+ context = context.transpose(1, 2).contiguous()
99
+ context = context.view(batch_size, -1, self.config.hidden_size)
100
+ return self.out_proj(context)
101
+
102
+
103
+ class ZZJRabbit22Layer(nn.Module):
104
+ def __init__(self, config: ZZJRabbit22Config):
105
+ super().__init__()
106
+ self.attn = ZZJRabbit22Attention(config)
107
+ self.l1 = nn.Linear(config.hidden_size, config.hidden_size)
108
+ self.l2 = nn.Linear(config.hidden_size, config.hidden_size)
109
+ self.activate = nn.ReLU()
110
+ self.norm = nn.RMSNorm(config.hidden_size)
111
+
112
+ def forward(
113
+ self, x: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
114
+ ) -> torch.Tensor:
115
+ key_padding_mask = None
116
+ attn_mask = None
117
+ if self.training:
118
+ attn_mask = torch.gt(
119
+ torch.triu(torch.ones(x.size(-2), x.size(-2), device=x.device), 1), 0
120
+ )
121
+ if attention_mask is not None:
122
+ key_padding_mask = torch.lt(attention_mask, 1)
123
+ attn = self.attn(
124
+ x,
125
+ key_padding_mask=key_padding_mask,
126
+ attn_mask=attn_mask,
127
+ )[0]
128
+ x = self.norm(x + attn)
129
+ o = self.l1(x)
130
+ o = self.activate(o)
131
+ o = self.l2(o)
132
+ return self.norm(x + o)
133
+
134
+
135
+ class ZZJRabbit22Model(PreTrainedModel):
136
+ config_class = ZZJRabbit22Config
137
+
138
+ def __init__(self, config: ZZJRabbit22Config, **kwargs):
139
+ super().__init__(config, **kwargs)
140
+ self.config = config
141
+ self.emb = nn.Embedding(config.vocab_size, config.hidden_size)
142
+ self.pe = ZZJRabbit22PE(config.hidden_size)
143
+ self.layers = nn.ModuleList(
144
+ [ZZJRabbit22Layer(config) for _ in range(config.num_layers)]
145
+ )
146
+
147
+ def forward(
148
+ self,
149
+ input_ids: torch.Tensor,
150
+ return_dict: Optional[bool] = None,
151
+ attention_mask: Optional[torch.Tensor] = None,
152
+ **kwargs,
153
+ ):
154
+ res = self.emb(input_ids)
155
+ res = self.pe(res)
156
+ res = res
157
+ for l in self.layers:
158
+ res = l(res, attention_mask)
159
+ if not return_dict:
160
+ return (res,)
161
+ else:
162
+ return BaseModelOutput(res)
163
+
164
+
165
+ class ZZJRabbit22ForCausalLM(PreTrainedModel, GenerationMixin):
166
+ config_class = ZZJRabbit22Config
167
+
168
+ def __init__(self, config, **kwargs):
169
+ super().__init__(config, **kwargs)
170
+ self.model = ZZJRabbit22Model(config, **kwargs)
171
+ self.l = nn.Linear(config.hidden_size, config.vocab_size)
172
+
173
+ def forward(
174
+ self,
175
+ input_ids: torch.Tensor,
176
+ return_dict: Optional[bool] = None,
177
+ labels: Optional[torch.Tensor] = None,
178
+ attention_mask: Optional[torch.Tensor] = None,
179
+ logits_to_keep: Union[int, torch.Tensor] = 0,
180
+ **kwargs,
181
+ ):
182
+ # print(input_ids, return_dict, labels, attention_mask, logits_to_keep, kwargs)
183
+ hidden = self.model(input_ids=input_ids, attention_mask=attention_mask)[0]
184
+ logits = self.l(
185
+ hidden[
186
+ :,
187
+ slice(-logits_to_keep, None)
188
+ if isinstance(logits_to_keep, int)
189
+ else logits_to_keep,
190
+ :,
191
+ ]
192
+ )
193
+ if labels is not None:
194
+ loss = self.loss_function(
195
+ logits=logits,
196
+ labels=labels,
197
+ vocab_size=self.config.vocab_size,
198
+ **kwargs,
199
+ )
200
+ print(loss)
201
+ if not return_dict:
202
+ return (loss, logits) if labels is not None else (logits,)
203
+ else:
204
+ return (
205
+ CausalLMOutput(logits=logits, loss=loss)
206
+ if labels is not None
207
+ else CausalLMOutput(logits=logits)
208
+ )
209
+
210
+ @classmethod
211
+ def can_generate(cls):
212
+ return True
213
+
214
+ def prepare_inputs_for_generation(self, input_ids, **kwargs):
215
+ return {"input_ids": input_ids}
216
+
217
+
218
+ class ZZJRabbit22Tokenizer(PreTrainedTokenizer):
219
+ vocab_files_names = {"tokenizers_file": "tokenizer.json"}
220
+
221
+ def __init__(self, tokenizers_file, **kwargs):
222
+ self.internal = Tokenizer.from_file(tokenizers_file)
223
+ super().__init__(**kwargs)
224
+
225
+ def get_vocab(self):
226
+ return {self.internal.id_to_token(i): i for i in range(self.vocab_size)}
227
+
228
+ def tokenize(self, text, **kwargs):
229
+ return self.internal.encode(text).tokens
230
+
231
+ def convert_tokens_to_ids(self, tokens):
232
+ return (
233
+ self.internal.token_to_id(tokens)
234
+ if isinstance(tokens, str)
235
+ else [self.internal.token_to_id(t) for t in tokens]
236
+ )
237
+
238
+ def decode(self, tokens, skip_special_tokens=True, **kwargs):
239
+ if isinstance(tokens, torch.Tensor):
240
+ tokens = tokens.tolist()
241
+ return self.internal.decode(tokens, skip_special_tokens=skip_special_tokens)
242
+
243
+ @property
244
+ def vocab_size(self):
245
+ return self.internal.get_vocab_size()
246
+
247
+ def save_vocabulary(self, path, *args, **kwargs) -> tuple[str]:
248
+ p = os.path.join(path, "tokenizer.json")
249
+ self.internal.save(p)
250
+ return (p,)