Madras1 commited on
Commit
0e38c84
·
verified ·
1 Parent(s): 389d69f

Export TinyGPT checkpoint step 46000

Browse files
README.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - pt
4
+ library_name: transformers
5
+ pipeline_tag: text-generation
6
+ tags:
7
+ - pt-br
8
+ - portuguese
9
+ - tinygpt
10
+ - custom-code
11
+ ---
12
+
13
+ # TinyGPT PT-BR v1
14
+
15
+ Modelo causal pequeno treinado em JAX/Flax/Orbax e exportado para o Hugging Face com `safetensors`.
16
+
17
+ ## Arquitetura
18
+
19
+ - `hidden_size`: 768
20
+ - `num_hidden_layers`: 12
21
+ - `num_attention_heads`: 8
22
+ - `intermediate_size`: 2048
23
+ - `max_position_embeddings`: 1024
24
+ - `vocab_size`: 32000
25
+
26
+ ## Origem
27
+
28
+ Checkpoint convertido do treino JAX TPU do projeto local. Este repositório usa `trust_remote_code=True`.
29
+
30
+ ## Uso
31
+
32
+ ```python
33
+ from transformers import AutoTokenizer, AutoModelForCausalLM
34
+
35
+ repo_id = "Madras1/tinygpt-ptbr-v1"
36
+ tokenizer = AutoTokenizer.from_pretrained(repo_id, trust_remote_code=True)
37
+ model = AutoModelForCausalLM.from_pretrained(repo_id, trust_remote_code=True)
38
+ ```
config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "TinyGPTForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_tinygpt.TinyGPTConfig",
7
+ "AutoModelForCausalLM": "modeling_tinygpt.TinyGPTForCausalLM"
8
+ },
9
+ "bos_token_id": 1,
10
+ "dropout": 0.1,
11
+ "dtype": "float32",
12
+ "eos_token_id": 2,
13
+ "hidden_size": 768,
14
+ "intermediate_size": 2048,
15
+ "layer_norm_eps": 1e-06,
16
+ "max_position_embeddings": 1024,
17
+ "model_type": "tinygpt",
18
+ "num_attention_heads": 8,
19
+ "num_hidden_layers": 12,
20
+ "pad_token_id": 2,
21
+ "tie_word_embeddings": false,
22
+ "transformers_version": "5.0.0",
23
+ "vocab_size": 32000
24
+ }
configuration_tinygpt.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+
3
+
4
+ class TinyGPTConfig(PretrainedConfig):
5
+ model_type = "tinygpt"
6
+
7
+ def __init__(
8
+ self,
9
+ vocab_size=32000,
10
+ hidden_size=768,
11
+ num_hidden_layers=18,
12
+ num_attention_heads=8,
13
+ intermediate_size=2048,
14
+ max_position_embeddings=1024,
15
+ dropout=0.1,
16
+ layer_norm_eps=1e-6,
17
+ bos_token_id=1,
18
+ eos_token_id=2,
19
+ pad_token_id=0,
20
+ tie_word_embeddings=False,
21
+ **kwargs,
22
+ ):
23
+ self.vocab_size = vocab_size
24
+ self.hidden_size = hidden_size
25
+ self.num_hidden_layers = num_hidden_layers
26
+ self.num_attention_heads = num_attention_heads
27
+ self.intermediate_size = intermediate_size
28
+ self.max_position_embeddings = max_position_embeddings
29
+ self.dropout = dropout
30
+ self.layer_norm_eps = layer_norm_eps
31
+ self.tie_word_embeddings = tie_word_embeddings
32
+ super().__init__(
33
+ bos_token_id=bos_token_id,
34
+ eos_token_id=eos_token_id,
35
+ pad_token_id=pad_token_id,
36
+ tie_word_embeddings=tie_word_embeddings,
37
+ **kwargs,
38
+ )
export_meta.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checkpoint_root": "/content/drive/MyDrive/ckpts",
3
+ "step": 46000,
4
+ "tokenizer_source": "mistralai/Mistral-7B-v0.1",
5
+ "config": {
6
+ "vocab_size": 32000,
7
+ "hidden_size": 768,
8
+ "num_hidden_layers": 12,
9
+ "num_attention_heads": 8,
10
+ "intermediate_size": 2048,
11
+ "max_position_embeddings": 1024,
12
+ "dropout": 0.1,
13
+ "layer_norm_eps": 1e-06,
14
+ "tie_word_embeddings": false,
15
+ "return_dict": true,
16
+ "output_hidden_states": false,
17
+ "dtype": "float32",
18
+ "chunk_size_feed_forward": 0,
19
+ "is_encoder_decoder": false,
20
+ "architectures": [
21
+ "TinyGPTForCausalLM"
22
+ ],
23
+ "id2label": {
24
+ "0": "LABEL_0",
25
+ "1": "LABEL_1"
26
+ },
27
+ "label2id": {
28
+ "LABEL_0": 0,
29
+ "LABEL_1": 1
30
+ },
31
+ "problem_type": null,
32
+ "_name_or_path": "",
33
+ "transformers_version": "5.0.0",
34
+ "bos_token_id": 1,
35
+ "eos_token_id": 2,
36
+ "pad_token_id": 2,
37
+ "auto_map": {
38
+ "AutoConfig": "configuration_tinygpt.TinyGPTConfig",
39
+ "AutoModelForCausalLM": "modeling_tinygpt.TinyGPTForCausalLM"
40
+ },
41
+ "model_type": "tinygpt",
42
+ "output_attentions": false
43
+ }
44
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa399e868e28dd1dca44d79820d6f248785996edb07ed2b2dc6a91d216febe62
3
+ size 464372152
modeling_tinygpt.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional, Tuple
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from transformers.modeling_outputs import CausalLMOutputWithPast
8
+ from transformers.modeling_utils import PreTrainedModel
9
+
10
+ from configuration_tinygpt import TinyGPTConfig
11
+
12
+
13
+ class TinyGPTRMSNorm(nn.Module):
14
+ def __init__(self, hidden_size: int, eps: float = 1e-6):
15
+ super().__init__()
16
+ self.weight = nn.Parameter(torch.ones(hidden_size))
17
+ self.eps = eps
18
+
19
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
20
+ variance = x.float().pow(2).mean(dim=-1, keepdim=True)
21
+ x = x * torch.rsqrt(variance + self.eps)
22
+ return x * self.weight
23
+
24
+
25
+ class TinyGPTAttention(nn.Module):
26
+ def __init__(self, config: TinyGPTConfig):
27
+ super().__init__()
28
+ self.hidden_size = config.hidden_size
29
+ self.num_heads = config.num_attention_heads
30
+ self.head_dim = self.hidden_size // self.num_heads
31
+ if self.head_dim * self.num_heads != self.hidden_size:
32
+ raise ValueError("hidden_size must be divisible by num_attention_heads")
33
+
34
+ self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=True)
35
+ self.k_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=True)
36
+ self.v_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=True)
37
+ self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=True)
38
+ self.dropout = nn.Dropout(config.dropout)
39
+
40
+ def _shape(self, x: torch.Tensor) -> torch.Tensor:
41
+ batch, seq_len, _ = x.size()
42
+ return x.view(batch, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
43
+
44
+ def forward(
45
+ self,
46
+ hidden_states: torch.Tensor,
47
+ attention_mask: Optional[torch.Tensor] = None,
48
+ ) -> torch.Tensor:
49
+ q = self._shape(self.q_proj(hidden_states))
50
+ k = self._shape(self.k_proj(hidden_states))
51
+ v = self._shape(self.v_proj(hidden_states))
52
+
53
+ attn_scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
54
+
55
+ seq_len = hidden_states.size(1)
56
+ causal_mask = torch.triu(
57
+ torch.ones(seq_len, seq_len, device=hidden_states.device, dtype=torch.bool),
58
+ diagonal=1,
59
+ )
60
+ attn_scores = attn_scores.masked_fill(causal_mask, torch.finfo(attn_scores.dtype).min)
61
+
62
+ if attention_mask is not None:
63
+ key_mask = attention_mask[:, None, None, :].to(torch.bool)
64
+ attn_scores = attn_scores.masked_fill(~key_mask, torch.finfo(attn_scores.dtype).min)
65
+
66
+ attn_probs = F.softmax(attn_scores, dim=-1, dtype=torch.float32).to(hidden_states.dtype)
67
+ attn_probs = self.dropout(attn_probs)
68
+
69
+ attn_output = torch.matmul(attn_probs, v)
70
+ attn_output = attn_output.transpose(1, 2).contiguous().view(
71
+ hidden_states.size(0), seq_len, self.hidden_size
72
+ )
73
+ return self.out_proj(attn_output)
74
+
75
+
76
+ class TinyGPTMLP(nn.Module):
77
+ def __init__(self, config: TinyGPTConfig):
78
+ super().__init__()
79
+ self.fc_in = nn.Linear(config.hidden_size, config.intermediate_size, bias=True)
80
+ self.fc_out = nn.Linear(config.intermediate_size, config.hidden_size, bias=True)
81
+ self.dropout = nn.Dropout(config.dropout)
82
+
83
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
84
+ hidden_states = self.fc_in(hidden_states)
85
+ hidden_states = F.gelu(hidden_states)
86
+ hidden_states = self.fc_out(hidden_states)
87
+ return self.dropout(hidden_states)
88
+
89
+
90
+ class TinyGPTBlock(nn.Module):
91
+ def __init__(self, config: TinyGPTConfig):
92
+ super().__init__()
93
+ self.attn_norm = TinyGPTRMSNorm(config.hidden_size, eps=config.layer_norm_eps)
94
+ self.attn = TinyGPTAttention(config)
95
+ self.mlp_norm = TinyGPTRMSNorm(config.hidden_size, eps=config.layer_norm_eps)
96
+ self.mlp = TinyGPTMLP(config)
97
+
98
+ def forward(
99
+ self,
100
+ hidden_states: torch.Tensor,
101
+ attention_mask: Optional[torch.Tensor] = None,
102
+ ) -> torch.Tensor:
103
+ hidden_states = hidden_states + self.attn(self.attn_norm(hidden_states), attention_mask)
104
+ hidden_states = hidden_states + self.mlp(self.mlp_norm(hidden_states))
105
+ return hidden_states
106
+
107
+
108
+ class TinyGPTPreTrainedModel(PreTrainedModel):
109
+ config_class = TinyGPTConfig
110
+ base_model_prefix = "model"
111
+ supports_gradient_checkpointing = False
112
+ _no_split_modules = ["TinyGPTBlock"]
113
+
114
+ def _init_weights(self, module):
115
+ if isinstance(module, nn.Linear):
116
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
117
+ if module.bias is not None:
118
+ nn.init.zeros_(module.bias)
119
+ elif isinstance(module, nn.Embedding):
120
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
121
+
122
+
123
+ class TinyGPTModel(TinyGPTPreTrainedModel):
124
+ def __init__(self, config: TinyGPTConfig):
125
+ super().__init__(config)
126
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
127
+ self.position_embeddings = nn.Parameter(
128
+ torch.zeros(config.max_position_embeddings, config.hidden_size)
129
+ )
130
+ self.dropout = nn.Dropout(config.dropout)
131
+ self.layers = nn.ModuleList(
132
+ [TinyGPTBlock(config) for _ in range(config.num_hidden_layers)]
133
+ )
134
+ self.final_norm = TinyGPTRMSNorm(config.hidden_size, eps=config.layer_norm_eps)
135
+ self.post_init()
136
+
137
+ def forward(
138
+ self,
139
+ input_ids: torch.LongTensor,
140
+ attention_mask: Optional[torch.Tensor] = None,
141
+ ) -> torch.Tensor:
142
+ seq_len = input_ids.size(1)
143
+ hidden_states = self.embed_tokens(input_ids) + self.position_embeddings[:seq_len]
144
+ hidden_states = self.dropout(hidden_states)
145
+
146
+ for layer in self.layers:
147
+ hidden_states = layer(hidden_states, attention_mask=attention_mask)
148
+
149
+ hidden_states = self.final_norm(hidden_states)
150
+ return hidden_states
151
+
152
+
153
+ class TinyGPTForCausalLM(TinyGPTPreTrainedModel):
154
+ _tied_weights_keys = []
155
+
156
+ def __init__(self, config: TinyGPTConfig):
157
+ super().__init__(config)
158
+ self.model = TinyGPTModel(config)
159
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
160
+ self.post_init()
161
+
162
+ def get_input_embeddings(self):
163
+ return self.model.embed_tokens
164
+
165
+ def set_input_embeddings(self, value):
166
+ self.model.embed_tokens = value
167
+
168
+ def get_output_embeddings(self):
169
+ return self.lm_head
170
+
171
+ def set_output_embeddings(self, new_embeddings):
172
+ self.lm_head = new_embeddings
173
+
174
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs):
175
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
176
+
177
+ def forward(
178
+ self,
179
+ input_ids: Optional[torch.LongTensor] = None,
180
+ attention_mask: Optional[torch.Tensor] = None,
181
+ labels: Optional[torch.LongTensor] = None,
182
+ **kwargs,
183
+ ) -> CausalLMOutputWithPast:
184
+ hidden_states = self.model(input_ids=input_ids, attention_mask=attention_mask)
185
+ logits = self.lm_head(hidden_states)
186
+
187
+ loss = None
188
+ if labels is not None:
189
+ shift_logits = logits[:, :-1, :].contiguous()
190
+ shift_labels = labels[:, 1:].contiguous()
191
+ loss = F.cross_entropy(
192
+ shift_logits.view(-1, shift_logits.size(-1)),
193
+ shift_labels.view(-1),
194
+ ignore_index=self.config.pad_token_id,
195
+ )
196
+
197
+ return CausalLMOutputWithPast(
198
+ loss=loss,
199
+ logits=logits,
200
+ past_key_values=None,
201
+ hidden_states=None,
202
+ attentions=None,
203
+ )
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": null,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<s>",
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "</s>",
7
+ "extra_special_tokens": [],
8
+ "is_local": false,
9
+ "legacy": false,
10
+ "model_max_length": 1000000000000000019884624838656,
11
+ "pad_token": "</s>",
12
+ "sp_model_kwargs": {},
13
+ "spaces_between_special_tokens": false,
14
+ "tokenizer_class": "TokenizersBackend",
15
+ "unk_token": "<unk>",
16
+ "use_default_system_prompt": false
17
+ }