Yasu-Okuda commited on
Commit
32db06e
·
verified ·
1 Parent(s): 820c194

Upload GPT

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +18 -0
  3. generation_config.json +6 -0
  4. model.safetensors +3 -0
  5. modeling_gpt.py +249 -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,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "GPT"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "modeling_gpt.GPTConfig",
7
+ "AutoModelForCausalLM": "modeling_gpt.GPT"
8
+ },
9
+ "dtype": "float32",
10
+ "emb_dim": 768,
11
+ "head_num": 12,
12
+ "layer_num": 12,
13
+ "max_context_len": 1024,
14
+ "micro_batch": 1,
15
+ "model_type": "custom_gpt2",
16
+ "transformers_version": "5.12.0",
17
+ "vocab_size": 50304
18
+ }
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "output_attentions": false,
4
+ "output_hidden_states": false,
5
+ "transformers_version": "5.12.0"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84b73804e3dda3fb92ef6f2bc7d214857b0f6ede6542b2dc4cb682287633cd68
3
+ size 548251520
modeling_gpt.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+
3
+ import torch
4
+ from torch import nn as nn, optim
5
+ from torch.nn import functional as F
6
+ import torch
7
+ from torch.nn.attention import sdpa_kernel, SDPBackend
8
+ from transformers import (
9
+ GenerationMixin,
10
+ PreTrainedConfig,
11
+ PreTrainedModel,
12
+ )
13
+ from transformers.modeling_outputs import CausalLMOutput
14
+
15
+ class GPTConfig(PreTrainedConfig):
16
+ """
17
+ Attributes
18
+ ----------
19
+ vocab_size : int
20
+ 語彙数
21
+ max_context_len : int, default = 1024
22
+ 最大コンテキスト長
23
+ layer_num : int
24
+ Transformerブロックの層数
25
+ head_dim : int
26
+ Attentionの次元数
27
+ emb_dim : int
28
+ 埋め込み次元数
29
+ micro_batch : int, default = 1
30
+ 何バッチ毎に進めるか?
31
+ """
32
+
33
+ model_type = "custom_gpt2"
34
+
35
+ def __init__(self, vocab_size: int = 50304, max_context_len: int = 1024, layer_num: int = 12, head_num: int = 12, emb_dim: int = 768, micro_batch: int = 1, **kwargs) -> None:
36
+ super().__init__(**kwargs)
37
+ self.vocab_size: int = vocab_size
38
+ self.max_context_len: int = max_context_len
39
+ self.layer_num: int = layer_num
40
+ self.head_num: int = head_num
41
+ self.emb_dim: int = emb_dim
42
+ self.micro_batch: int = micro_batch
43
+
44
+
45
+ class CasualSelfAttention(nn.Module):
46
+ def __init__(self, config: GPTConfig) -> None:
47
+ super().__init__()
48
+ assert config.emb_dim % config.head_num == 0, (
49
+ f"埋め込み次元数がヘッドの数で割り切れません!"
50
+ )
51
+ # すべてのヘッドに対するkey, query, valueの投影を、バッチ処理で行う
52
+ # (B, T, C) -> (B, T, 3C)
53
+ self.c_attn = nn.Linear(config.emb_dim, 3 * config.emb_dim)
54
+ # output projection
55
+ self.c_proj = nn.Linear(config.emb_dim, config.emb_dim)
56
+ self.c_proj.NANOGPT_SCALE_INIT = 1 # type: ignore
57
+ # 正規化
58
+ self.head_num = config.head_num
59
+ self.emb_dim = config.emb_dim
60
+ # Attention Mask
61
+ self.register_buffer(
62
+ "mask",
63
+ torch.tril(torch.ones(config.max_context_len, config.max_context_len)).view(
64
+ 1, 1, config.max_context_len, config.max_context_len
65
+ ),
66
+ )
67
+
68
+ def forward(self, x: torch.Tensor, use_cache=None, attention_mask=None, **kwargs) -> torch.Tensor:
69
+ B, T, C = x.size()
70
+ qkv: torch.Tensor = self.c_attn(x)
71
+ q, k, v = qkv.split(self.emb_dim, dim=2)
72
+ # 軽量化のためにreshapeではなくviewを使用
73
+ # 次元を入れ替え(B, head_num, T, head_dim)
74
+ # Bとhead_numをバッチとして扱う
75
+ k = k.view(B, T, self.head_num, C // self.head_num).transpose(1, 2)
76
+ q = q.view(B, T, self.head_num, C // self.head_num).transpose(1, 2)
77
+ v = v.view(B, T, self.head_num, C // self.head_num).transpose(1, 2)
78
+
79
+ # Attention
80
+ # attn = (q @ k.transpose(-2, -1)) * (k.size(-1) ** -1)
81
+ # attn = attn.masked_fill(self.mask[:, :, :T, :T] == 0, float("-inf")) # type: ignore
82
+ # attn = F.softmax(attn, dim=-1)
83
+ # y = attn @ v
84
+
85
+ with sdpa_kernel(
86
+ [
87
+ SDPBackend.FLASH_ATTENTION,
88
+ SDPBackend.CUDNN_ATTENTION,
89
+ SDPBackend.EFFICIENT_ATTENTION,
90
+ SDPBackend.MATH,
91
+ SDPBackend.ERROR,
92
+ ]
93
+ ):
94
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
95
+
96
+ # (B, T, head_num, head_dim) -> (B, head_num, T, head_dim) -> 各headを結合 -> (B, T, C)
97
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
98
+ y = self.c_proj(y)
99
+
100
+ return y
101
+
102
+
103
+ class MLP(nn.Module):
104
+ def __init__(self, config: GPTConfig) -> None:
105
+ super().__init__()
106
+
107
+ self.c_fc: nn.Linear = nn.Linear(config.emb_dim, 4 * config.emb_dim)
108
+ self.gelu = nn.GELU(approximate="tanh")
109
+ self.c_proj: nn.Linear = nn.Linear(4 * config.emb_dim, config.emb_dim)
110
+ self.c_proj.NANOGPT_SCALE_INIT = 1 # type: ignore
111
+
112
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
113
+ x = self.c_fc(x)
114
+ x = self.gelu(x)
115
+ x = self.c_proj(x)
116
+ return x
117
+
118
+
119
+ class Block(nn.Module):
120
+ def __init__(self, config: GPTConfig) -> None:
121
+ super().__init__()
122
+ # 埋め込み次元を平均0, 分散1に正規化して学習を安定化させる
123
+ self.ln_1 = nn.LayerNorm(config.emb_dim)
124
+ self.attn = CasualSelfAttention(config)
125
+ # 埋め込み次元を平均0, 分散1に正規化して学習を安定化させる
126
+ self.ln_2 = nn.LayerNorm(config.emb_dim)
127
+ self.mlp = MLP(config)
128
+
129
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
130
+ # Attention is all you needではAttention後に正規化を行っていたが、GPT-2ではPre Normに変更
131
+ x = x + self.attn(self.ln_1(x))
132
+ x = x + self.mlp(self.ln_2(x))
133
+ return x
134
+
135
+
136
+ class GPT(PreTrainedModel, GenerationMixin):
137
+ config_class = GPTConfig
138
+
139
+ # HFにWeight tyingを宣言する
140
+ _tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"}
141
+
142
+ def __init__(self, config: GPTConfig) -> None:
143
+ super().__init__(config)
144
+ self.config: GPTConfig = config
145
+
146
+
147
+
148
+ self.transformer = nn.ModuleDict(
149
+ dict(
150
+ wte=nn.Embedding(config.vocab_size, config.emb_dim),
151
+ wpe=nn.Embedding(config.max_context_len, config.emb_dim),
152
+ h=nn.ModuleList([Block(config) for _ in range(config.layer_num)]),
153
+ ln_f=nn.LayerNorm(config.emb_dim),
154
+ )
155
+ )
156
+ self.lm_head = nn.Linear(config.emb_dim, config.vocab_size, bias=False)
157
+
158
+ # 重みを共有する
159
+ self.transformer.wte.weight = self.lm_head.weight # type: ignore
160
+
161
+ self.apply(self._init_weight)
162
+
163
+ def _init_weight(self, module: nn.Module) -> None:
164
+ """
165
+ 重みの初期化を行う
166
+ """
167
+ if isinstance(module, nn.Linear):
168
+ std = 0.02
169
+ if hasattr(module, "NANOGPT_SCALE_INIT"):
170
+ std *= (2 * self.config.layer_num) ** -0.5
171
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
172
+ if module.bias is not None:
173
+ torch.nn.init.zeros_(module.bias)
174
+ elif isinstance(module, nn.Embedding):
175
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.2)
176
+
177
+ def forward(
178
+ self, input_ids: torch.Tensor, labels: torch.Tensor | None = None
179
+ ) -> CausalLMOutput:
180
+ B, T = input_ids.size()
181
+ assert T <= self.config.max_context_len, f"最大コンテキスト長をオーバー!"
182
+
183
+ position: torch.Tensor = torch.arange(
184
+ 0, T, dtype=torch.long, device=input_ids.device
185
+ )
186
+ position_emb: torch.Tensor = self.transformer.wpe(position) # type: ignore
187
+ token_emb: torch.Tensor = self.transformer.wte(input_ids) # type: ignore
188
+
189
+ x: torch.Tensor = token_emb + position_emb
190
+
191
+ block: Block
192
+ for block in self.transformer.h: # type: ignore
193
+ x = block(x)
194
+ x = self.transformer.ln_f(x) # type: ignore
195
+
196
+ # (B, T, vocab_size)
197
+ logits: torch.Tensor = self.lm_head(x)
198
+
199
+ # トレーニング用
200
+ loss = None
201
+ if labels is not None:
202
+ # view(-1, SOME)はSOME行になるように列を自動で調節する
203
+ # (B, T, vocab_size) -> (B * T, vocab_size)
204
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1))
205
+
206
+ return CausalLMOutput(loss, logits) # type: ignore
207
+
208
+ def configure_optimizer(self, weight_decay: float, device: str) -> optim.AdamW:
209
+ # 学習が必要なパラメーターをまとめる
210
+ param_dict = {
211
+ parameter_name: parameter
212
+ for parameter_name, parameter in self.named_parameters()
213
+ }
214
+ param_dict = {
215
+ parameter_name: parameter
216
+ for parameter_name, parameter in param_dict.items()
217
+ if parameter.requires_grad
218
+ }
219
+ # 最適化グループを作成する
220
+ # 2次元であるパラメーターのみ対象
221
+ decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
222
+ no_decay_params = [p for n, p in param_dict.items() if p.dim() < 2]
223
+ optim_group = [
224
+ {"params": decay_params, "weight_decay": weight_decay},
225
+ {"params": no_decay_params, "weight_decay": 0.0},
226
+ ]
227
+
228
+ num_decay_params = sum(p.numel() for p in decay_params)
229
+ num_no_decay_params = sum(p.numel() for p in no_decay_params)
230
+
231
+ print(
232
+ f"減衰を行うテンソル: {len(decay_params)}, with {num_decay_params:,}パラメーター"
233
+ )
234
+ print(
235
+ f"減衰を行わないテンソル: {len(no_decay_params)}, with {num_no_decay_params:,}パラメーター"
236
+ )
237
+
238
+ # AdamWを使う
239
+ is_fused = "fused" in inspect.signature(torch.optim.AdamW).parameters
240
+ can_use_fused = is_fused and "cuda" in device
241
+ print("Fused AdamWを使用中") if can_use_fused else print(
242
+ "Fused AdamWは使用できません"
243
+ )
244
+
245
+ optimizer = optim.AdamW(
246
+ optim_group, lr=3e-4, betas=(0.9, 0.95), eps=1e-8, fused=can_use_fused
247
+ )
248
+
249
+ return optimizer