AlexHung29629 commited on
Commit
d7a28b9
·
verified ·
1 Parent(s): 9c6b372

Upload LstmForCausalLM

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,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/home/alex/Workspace/LSTM_LM/lstm_v1/checkpoint-2000",
3
+ "architectures": [
4
+ "LstmForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_lstm.LstmConfig",
8
+ "AutoModelForCausalLM": "modeling_lstm.LstmForCausalLM"
9
+ },
10
+ "bos_token_id": 128000,
11
+ "eos_token_id": 128001,
12
+ "hidden_size": 2048,
13
+ "initializer_gain": 1,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 8192,
16
+ "model_type": "lstm",
17
+ "num_hidden_layers": 2,
18
+ "pad_token_id": 128004,
19
+ "torch_dtype": "bfloat16",
20
+ "transformers_version": "4.47.1",
21
+ "vocab_size": 128256
22
+ }
configuration_lstm.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class LstmConfig(PretrainedConfig):
5
+ model_type = "lstm"
6
+
7
+ def __init__(
8
+ self,
9
+ num_hidden_layers=16,
10
+ hidden_size = 640,
11
+ vocab_size = 128256,
12
+ intermediate_size = 2560,
13
+ pad_token_id = 128004,
14
+ bos_token_id = 128000,
15
+ eos_token_id = 128001,
16
+ initializer_range = 0.02,
17
+ initializer_gain = 1,
18
+ tie_word_embeddings = True,
19
+ **kwargs,
20
+ ):
21
+ self.hidden_size = hidden_size
22
+ self.num_hidden_layers = num_hidden_layers
23
+ self.vocab_size = vocab_size
24
+ self.intermediate_size = intermediate_size
25
+ self.initializer_range = initializer_range
26
+ self.initializer_gain = initializer_gain
27
+ self.tie_word_embeddings = tie_word_embeddings
28
+ super().__init__(
29
+ pad_token_id=pad_token_id,
30
+ bos_token_id=bos_token_id,
31
+ eos_token_id=eos_token_id,
32
+ tie_word_embeddings=tie_word_embeddings,
33
+ **kwargs,
34
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 128000,
4
+ "eos_token_id": 128001,
5
+ "pad_token_id": 128004,
6
+ "transformers_version": "4.47.1"
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c15d74e7f01cbb8e3181ace87b093db3abcd58edfc8d0348f2b77ea9ae56cb0
3
+ size 860903112
modeling_lstm.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ import torch
3
+ from torch import nn
4
+ from transformers import PreTrainedModel, GenerationMixin, AutoConfig, AutoModel, AutoModelForCausalLM
5
+ from transformers.modeling_outputs import BaseModelOutputWithNoAttention, CausalLMOutput
6
+
7
+ from configuration_lstm import LstmConfig
8
+
9
+ class MLP(nn.Module):
10
+ def __init__(self, config: LstmConfig):
11
+ super().__init__()
12
+ self.config = config
13
+ self.hidden_size = config.hidden_size
14
+ self.intermediate_size = config.intermediate_size
15
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
16
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
17
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
18
+ self.act_fn = nn.SiLU()
19
+
20
+ def forward(self, x):
21
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
22
+ return down_proj
23
+
24
+ class LstmLayer(nn.Module):
25
+
26
+ def __init__(self, config: LstmConfig):
27
+ super().__init__()
28
+
29
+ self.lstm = nn.LSTM(config.hidden_size, config.hidden_size, num_layers=1, batch_first=True, bias=False)
30
+ self.mlp = MLP(config)
31
+ self.input_ln = nn.RMSNorm((config.hidden_size,), eps=1e-6)
32
+ self.post_ln = nn.RMSNorm((config.hidden_size,), eps=1e-6)
33
+
34
+ def forward(self, hidden_states):
35
+ lstm_part = self.input_ln(hidden_states)
36
+ lstm_part, _ = self.lstm(lstm_part)
37
+ hidden_states = hidden_states + lstm_part
38
+
39
+ mlp_part = self.post_ln(hidden_states)
40
+ mlp_part = self.mlp(mlp_part)
41
+ return hidden_states + mlp_part
42
+
43
+ class LstmPreTrainedModel(PreTrainedModel):
44
+ config_class = LstmConfig
45
+ base_model_prefix = "model"
46
+ supports_gradient_checkpointing = True
47
+ _no_split_modules = ["LstmLayer"]
48
+
49
+ def _init_weights(self, module):
50
+ std = self.config.initializer_range
51
+ gain = self.config.initializer_gain
52
+ if isinstance(module, nn.Linear):
53
+ #nn.init.normal_(module.weight.data, std=std)
54
+ nn.init.kaiming_uniform_(module.weight.data)
55
+ if module.bias is not None:
56
+ module.bias.data.zero_()
57
+ elif isinstance(module, nn.Embedding):
58
+ nn.init.normal_(module.weight.data, std=std)
59
+ if module.padding_idx is not None:
60
+ module.weight.data[module.padding_idx].zero_()
61
+ elif isinstance(module, nn.RMSNorm):
62
+ module.weight.data.fill_(0.4)
63
+ elif isinstance(module, nn.LSTM):
64
+ for name, param in module.named_parameters():
65
+ if "weight" in name:
66
+ nn.init.xavier_uniform_(param, gain=gain)
67
+ elif "bias" in name:
68
+ with torch.no_grad():
69
+ param.zero_()
70
+
71
+ class LstmModel(LstmPreTrainedModel):
72
+
73
+ def __init__(self, config: LstmConfig):
74
+ super().__init__(config)
75
+ self.padding_idx = config.pad_token_id
76
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
77
+ self.layers = nn.ModuleList(
78
+ [LstmLayer(config) for layer_idx in range(config.num_hidden_layers)]
79
+ )
80
+ self.norm = nn.RMSNorm((config.hidden_size,), eps=1e-6)
81
+ self.gradient_checkpointing = False
82
+
83
+ # Initialize weights and apply final processing
84
+ self.post_init()
85
+
86
+ def forward(
87
+ self,
88
+ input_ids: Optional[torch.LongTensor] = None,
89
+ inputs_embeds: Optional[torch.LongTensor] = None,
90
+ **kwargs,
91
+ ) -> BaseModelOutputWithNoAttention:
92
+ if (input_ids is None) ^ (inputs_embeds is not None):
93
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
94
+
95
+ if inputs_embeds is None:
96
+ hidden_states = self.embed_tokens(input_ids)
97
+
98
+ for block in self.layers:
99
+ if self.gradient_checkpointing and self.training:
100
+ hidden_states = self._gradient_checkpointing_func(
101
+ block.__call__,
102
+ hidden_states,
103
+ )
104
+ else:
105
+ hidden_states = block(hidden_states)
106
+
107
+ last_hidden_state = self.norm(hidden_states)
108
+ return BaseModelOutputWithNoAttention(
109
+ last_hidden_state=last_hidden_state
110
+ )
111
+
112
+ class LstmForCausalLM(LstmPreTrainedModel, GenerationMixin):
113
+ _tied_weights_keys = ["lm_head.weight"]
114
+
115
+ def __init__(self, config: LstmConfig):
116
+ super().__init__(config)
117
+ self.model = LstmModel(config)
118
+ self.vocab_size = config.vocab_size
119
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
120
+
121
+ # Initialize weights and apply final processing
122
+ self.post_init()
123
+
124
+ def get_input_embeddings(self):
125
+ return self.model.embed_tokens
126
+
127
+ def set_input_embeddings(self, value):
128
+ self.model.embed_tokens = value
129
+
130
+ def get_output_embeddings(self):
131
+ return self.lm_head
132
+
133
+ def set_output_embeddings(self, new_embeddings):
134
+ self.lm_head = new_embeddings
135
+
136
+ def set_decoder(self, decoder):
137
+ self.model = decoder
138
+
139
+ def get_decoder(self):
140
+ return self.model
141
+
142
+ def forward(
143
+ self,
144
+ input_ids: torch.LongTensor = None,
145
+ inputs_embeds: Optional[torch.FloatTensor] = None,
146
+ labels: Optional[torch.LongTensor] = None,
147
+ num_logits_to_keep: int = 0,
148
+ **kwargs,
149
+ ):
150
+ if (input_ids is None) ^ (inputs_embeds is not None):
151
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
152
+
153
+ hidden_states = self.model(input_ids, inputs_embeds).last_hidden_state
154
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
155
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
156
+
157
+ loss = None
158
+ if labels is not None:
159
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
160
+
161
+ return CausalLMOutput(
162
+ loss=loss,
163
+ logits=logits,
164
+ )
165
+
166
+ AutoConfig.register("lstm", LstmConfig)
167
+ AutoModel.register(LstmConfig, LstmModel)
168
+ AutoModelForCausalLM.register(LstmConfig, LstmForCausalLM)
169
+ LstmConfig.register_for_auto_class()
170
+ LstmModel.register_for_auto_class("AutoModel")
171
+ LstmForCausalLM.register_for_auto_class("AutoModelForCausalLM")