bu1 commited on
Commit
da43675
·
verified ·
1 Parent(s): 32102d6

Upload model

Browse files
Files changed (4) hide show
  1. README.md +199 -0
  2. config.json +25 -0
  3. model.safetensors +3 -0
  4. modeling_IQtransformer.py +281 -0
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,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "transformerModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "modeling_IQtransformer.transformerConfig",
7
+ "AutoModelForCausalLM": "modeling_IQtransformer.transformerModel"
8
+ },
9
+ "dropout": 0.1,
10
+ "ffn_num_hiddens": 64,
11
+ "ffn_num_input": 32,
12
+ "key_size": 32,
13
+ "model_type": "IQsignal_transformer",
14
+ "norm_shape": [
15
+ 32
16
+ ],
17
+ "num_heads": 4,
18
+ "num_hiddens": 32,
19
+ "num_layers": 1,
20
+ "query_size": 32,
21
+ "torch_dtype": "float32",
22
+ "transformers_version": "4.45.2",
23
+ "value_size": 32,
24
+ "vocab_size": 32
25
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7072cbbabdab8bb637ea49fd5e0970f57758ac3c4501b3ce062b032cd97b813
3
+ size 44340
modeling_IQtransformer.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PreTrainedModel
2
+ import torch
3
+ from torch import nn
4
+ import math
5
+
6
+ from transformers import PretrainedConfig
7
+
8
+ # 把transformerConfig和transformerModel都放在一个文件中,避免类别不匹配引起的错误
9
+
10
+ class transformerConfig(PretrainedConfig):
11
+ model_type = "IQsignal_transformer"
12
+
13
+ def __init__(
14
+ self,
15
+ vocab_size : int = 32,
16
+ key_size : int = 32,
17
+ query_size : int = 32,
18
+ value_size : int = 32,
19
+ num_hiddens : int = 32,
20
+ norm_shape : int = [32],
21
+ ffn_num_input : int = 32,
22
+ ffn_num_hiddens : int = 64,
23
+ num_heads : int = 4,
24
+ num_layers : int = 1,
25
+ dropout : int = 0.1,
26
+
27
+ **kwargs,
28
+ ):
29
+ self.vocab_size = vocab_size
30
+ self.key_size = key_size
31
+ self.query_size = query_size
32
+ self.value_size = value_size
33
+ self.num_hiddens = num_hiddens
34
+ self.norm_shape = norm_shape
35
+ self.ffn_num_input = ffn_num_input
36
+ self.ffn_num_hiddens = ffn_num_hiddens
37
+ self.num_heads = num_heads
38
+ self.num_layers = num_layers
39
+ self.dropout = dropout
40
+
41
+ super().__init__(**kwargs)
42
+
43
+ class PositionWiseFFN(nn.Module):
44
+ """基于位置的前馈网络"""
45
+ def __init__(self, ffn_num_input, ffn_num_hiddens, ffn_num_outputs,
46
+ **kwargs):
47
+ super(PositionWiseFFN, self).__init__(**kwargs)
48
+ self.dense1 = nn.Linear(ffn_num_input, ffn_num_hiddens)
49
+ self.relu = nn.ReLU()
50
+ self.dense2 = nn.Linear(ffn_num_hiddens, ffn_num_outputs)
51
+
52
+ def forward(self, X):
53
+ return self.dense2(self.relu(self.dense1(X)))
54
+
55
+
56
+ class AddNorm(nn.Module):
57
+ """残差连接后进行层规范化"""
58
+ def __init__(self, normalized_shape, dropout, **kwargs):
59
+ super(AddNorm, self).__init__(**kwargs)
60
+ self.dropout = nn.Dropout(dropout)
61
+ self.ln = nn.LayerNorm(normalized_shape)
62
+
63
+ def forward(self, X, Y):
64
+ return self.ln(self.dropout(Y) + X)
65
+
66
+ def masked_softmax(X, valid_lens):
67
+ """通过在最后一个轴上掩蔽元素来执行softmax操作
68
+
69
+ Defined in :numref:`sec_attention-scoring-functions`"""
70
+ # X:3D张量,valid_lens:1D或2D张量
71
+ if valid_lens is None:
72
+ return nn.functional.softmax(X, dim=-1)
73
+ else:
74
+ shape = X.shape
75
+ if valid_lens.dim() == 1:
76
+ valid_lens = torch.repeat_interleave(valid_lens, shape[1])
77
+ else:
78
+ valid_lens = valid_lens.reshape(-1)
79
+ # 最后一轴上被掩蔽的元素使用一个非常大的负值替换,从而其softmax输出为0
80
+ X = sequence_mask(X.reshape(-1, shape[-1]), valid_lens,
81
+ value=-1e6)
82
+ return nn.functional.softmax(X.reshape(shape), dim=-1)
83
+
84
+ def transpose_qkv(X, num_heads):
85
+ """为了多注意力头的并行计算而变换形状
86
+
87
+ Defined in :numref:`sec_multihead-attention`"""
88
+ # 输入X的形状:(batch_size,查询或者“键-值”对的个数,num_hiddens)
89
+ # 输出X的形状:(batch_size,查询或者“键-值”对的个数,num_heads,
90
+ # num_hiddens/num_heads)
91
+ X = X.reshape(X.shape[0], X.shape[1], num_heads, -1)
92
+
93
+ # 输出X的形状:(batch_size,num_heads,查询或者“键-值”对的个数,
94
+ # num_hiddens/num_heads)
95
+ X = X.permute(0, 2, 1, 3)
96
+
97
+ # 最终输出的形状:(batch_size*num_heads,查询或者“键-值”对的个数,
98
+ # num_hiddens/num_heads)
99
+ return X.reshape(-1, X.shape[2], X.shape[3])
100
+
101
+
102
+ def transpose_output(X, num_heads):
103
+ """逆转transpose_qkv函数的操作
104
+
105
+ Defined in :numref:`sec_multihead-attention`"""
106
+ X = X.reshape(-1, num_heads, X.shape[1], X.shape[2])
107
+ X = X.permute(0, 2, 1, 3)
108
+ return X.reshape(X.shape[0], X.shape[1], -1)
109
+
110
+ def sequence_mask(X, valid_len, value=0):
111
+ """在序列中屏蔽不相关的项
112
+
113
+ Defined in :numref:`sec_seq2seq_decoder`"""
114
+ maxlen = X.size(1)
115
+ mask = torch.arange((maxlen), dtype=torch.float32,
116
+ device=X.device)[None, :] < valid_len[:, None]
117
+ X[~mask] = value
118
+ return X
119
+
120
+ class DotProductAttention(nn.Module):
121
+ """缩放点积注意力
122
+
123
+ Defined in :numref:`subsec_additive-attention`"""
124
+ def __init__(self, dropout, **kwargs):
125
+ super(DotProductAttention, self).__init__(**kwargs)
126
+ self.dropout = nn.Dropout(dropout)
127
+
128
+ # queries的形状:(batch_size,查询的个数,d)
129
+ # keys的形状:(batch_size,“键-值”对的个数,d)
130
+ # values的形状:(batch_size,“键-值”对的个数,值的维度)
131
+ # valid_lens的形状:(batch_size,)或者(batch_size,查询的个数)
132
+ def forward(self, queries, keys, values, valid_lens=None):
133
+ d = queries.shape[-1]
134
+ # 设置transpose_b=True为了交换keys的最后两个维度
135
+ scores = torch.bmm(queries, keys.transpose(1,2)) / math.sqrt(d)
136
+ self.attention_weights = masked_softmax(scores, valid_lens)
137
+ return torch.bmm(self.dropout(self.attention_weights), values)
138
+
139
+ class MultiHeadAttention(nn.Module):
140
+ """多头注意力
141
+
142
+ Defined in :numref:`sec_multihead-attention`"""
143
+ def __init__(self, key_size, query_size, value_size, num_hiddens,
144
+ num_heads, dropout, bias=False, **kwargs):
145
+ super(MultiHeadAttention, self).__init__(**kwargs)
146
+ self.num_heads = num_heads
147
+ self.attention = DotProductAttention(dropout)
148
+ self.W_q = nn.Linear(query_size, num_hiddens, bias=bias)
149
+ self.W_k = nn.Linear(key_size, num_hiddens, bias=bias)
150
+ self.W_v = nn.Linear(value_size, num_hiddens, bias=bias)
151
+ self.W_o = nn.Linear(num_hiddens, num_hiddens, bias=bias)
152
+
153
+ def forward(self, queries, keys, values, valid_lens):
154
+ # queries,keys,values的形状:
155
+ # (batch_size,查询或者“键-值”对的个数,num_hiddens)
156
+ # valid_lens 的形状:
157
+ # (batch_size,)或(batch_size,查询的个数)
158
+ # 经过变换后,输出的queries,keys,values 的形状:
159
+ # (batch_size*num_heads,查询或者“键-值”对的个数,
160
+ # num_hiddens/num_heads)
161
+ queries = transpose_qkv(self.W_q(queries), self.num_heads)
162
+ keys = transpose_qkv(self.W_k(keys), self.num_heads)
163
+ values = transpose_qkv(self.W_v(values), self.num_heads)
164
+
165
+ if valid_lens is not None:
166
+ # 在轴0,将第一项(标量或者矢量)复制num_heads次,
167
+ # 然后如此复制第二项,然后诸如此类。
168
+ valid_lens = torch.repeat_interleave(
169
+ valid_lens, repeats=self.num_heads, dim=0)
170
+
171
+ # output的形状:(batch_size*num_heads,查询的个数,
172
+ # num_hiddens/num_heads)
173
+ output = self.attention(queries, keys, values, valid_lens)
174
+
175
+ # output_concat的形状:(batch_size,查询的个数,num_hiddens)
176
+ output_concat = transpose_output(output, self.num_heads)
177
+ return self.W_o(output_concat)
178
+
179
+ class EncoderBlock(nn.Module):
180
+ """Transformer编码器块"""
181
+ def __init__(self, key_size, query_size, value_size, num_hiddens,
182
+ norm_shape, ffn_num_input, ffn_num_hiddens, num_heads,
183
+ dropout, use_bias=False, **kwargs):
184
+ super(EncoderBlock, self).__init__(**kwargs)
185
+ self.attention = MultiHeadAttention(
186
+ key_size, query_size, value_size, num_hiddens, num_heads, dropout,
187
+ use_bias)
188
+ self.addnorm1 = AddNorm(norm_shape, dropout)
189
+ self.ffn = PositionWiseFFN(
190
+ ffn_num_input, ffn_num_hiddens, num_hiddens)
191
+ self.addnorm2 = AddNorm(norm_shape, dropout)
192
+
193
+ def forward(self, X, valid_lens):
194
+ Y = self.addnorm1(X, self.attention(X, X, X, valid_lens))
195
+ return self.addnorm2(Y, self.ffn(Y))
196
+
197
+ class Encoder(nn.Module):
198
+ """编码器-解码器架构的基本编码器接口"""
199
+ def __init__(self, **kwargs):
200
+ super(Encoder, self).__init__(**kwargs)
201
+
202
+ def forward(self, X, *args):
203
+ raise NotImplementedError
204
+
205
+ class transformerModel(PreTrainedModel):
206
+
207
+ config_class = transformerConfig
208
+
209
+ def __init__(self, config):
210
+ super().__init__(config)
211
+
212
+ self.num_hiddens = config.num_hiddens
213
+ self.Linear = nn.Linear(config.vocab_size, config.vocab_size)
214
+ # self.embedding = nn.Embedding(vocab_size, num_hiddens) # 将输入vocab_size的维度 转化为 想要的num_hiddens维度
215
+ # self.pos_encoding = d2l.PositionalEncoding(num_hiddens, dropout)
216
+ self.ln = nn.LayerNorm(config.norm_shape)
217
+ self.blks = nn.Sequential()
218
+ for i in range(config.num_layers):
219
+ self.blks.add_module("block" + str(i),
220
+ EncoderBlock(config.key_size, config.query_size, config.value_size, config.num_hiddens,
221
+ config.norm_shape, config.ffn_num_input, config.ffn_num_hiddens,
222
+ config.num_heads, config.dropout))
223
+
224
+ self.l1 = nn.Linear(64, 16)
225
+ self.l2 = nn.Linear(16, 5)
226
+
227
+ def forward(self, X, valid_lens, *args):
228
+ # 因为位置编码值在-1和1之间,
229
+ # 因此嵌入值乘以嵌入维度的平方根进行缩放,
230
+ # 然后再与位置编码相加。
231
+ X = self.ln(self.Linear(X).to(torch.float32))
232
+ self.attention_weights = [None] * len(self.blks)
233
+ for i, blk in enumerate(self.blks):
234
+ X = blk(X, valid_lens)
235
+ self.attention_weights[
236
+ i] = blk.attention.attention.attention_weights
237
+
238
+ X = self.l1(torch.reshape(X, [8, 64]))
239
+ X = self.l2(X)
240
+ return X
241
+
242
+ # class TransformerEncoder(nn.Module):
243
+ # """Transformer编码器"""
244
+ # def __init__(self, vocab_size, key_size, query_size, value_size,
245
+ # num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens,
246
+ # num_heads, num_layers, dropout, use_bias=False, **kwargs):
247
+ # super(TransformerEncoder, self).__init__(**kwargs)
248
+ # self.num_hiddens = num_hiddens
249
+ # self.Linear = nn.Linear(vocab_size,vocab_size)
250
+ # # self.embedding = nn.Embedding(vocab_size, num_hiddens) # 将输入vocab_size的维度 转化为 想要的num_hiddens维度
251
+ # # self.pos_encoding = d2l.PositionalEncoding(num_hiddens, dropout)
252
+ # self.ln = nn.LayerNorm(vocab_size)
253
+ # self.blks = nn.Sequential()
254
+ # for i in range(num_layers):
255
+ # self.blks.add_module("block"+str(i),
256
+ # EncoderBlock(key_size, query_size, value_size, num_hiddens,
257
+ # norm_shape, ffn_num_input, ffn_num_hiddens,
258
+ # num_heads, dropout, use_bias))
259
+ #
260
+ # self.l1 = nn.Linear(64, 16)
261
+ # self.l2 = nn.Linear(16, 5)
262
+ #
263
+ # def forward(self, X, valid_lens, *args):
264
+ # # 因为位置编码值在-1和1之间,
265
+ # # 因此嵌入值乘以嵌入维度的平方根进行缩放,
266
+ # # 然后再与位置编码相加。
267
+ # X = self.ln(self.Linear(X))
268
+ # self.attention_weights = [None] * len(self.blks)
269
+ # for i, blk in enumerate(self.blks):
270
+ # X = blk(X, valid_lens)
271
+ # self.attention_weights[
272
+ # i] = blk.attention.attention.attention_weights
273
+ #
274
+ # X = self.l1(torch.reshape(X,[8, 64]))
275
+ # X = self.l2(X)
276
+ # return X
277
+
278
+
279
+
280
+
281
+