bu1 commited on
Commit
cf68036
·
verified ·
1 Parent(s): 2acef95

Upload model

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