sdkjfgndjfg commited on
Commit
d3ee2f3
·
verified ·
1 Parent(s): 0f34dd4

Upload 7 files

Browse files
README.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: apache-2.0
5
+ tags:
6
+ - gpt
7
+ - text-generation
8
+ - causal-lm
9
+ - pytorch
10
+ - safetensors
11
+ - custom-trained
12
+ ---
13
+
14
+ # gpt-model-2-decoder-100000-tiny-stories-fp16
15
+
16
+ A custom GPT-style language model trained from scratch using PyTorch.
17
+
18
+ ## Model Details
19
+
20
+ | Parameter | Value |
21
+ |-----------|-------|
22
+ | Architecture | GPT (Decoder-only Transformer) |
23
+ | Hidden size (`d_model`) | 768 |
24
+ | Attention heads | 8 |
25
+ | Transformer blocks | 1 |
26
+ | Max sequence length | 1024 |
27
+ | Vocabulary size | 32000 |
28
+ | Dropout | 0.2 |
29
+
30
+ ## Tokenizer
31
+
32
+ Custom BPE tokenizer trained with the HuggingFace `tokenizers` library.
33
+
34
+ **Special tokens:** `<|endoftext|>` · `<|pad|>` · `<|unk|>`
35
+
36
+ ## Quick Start
37
+
38
+ You can easily load this model and tokenizer using the `transformers` library. Because the model uses a custom architecture, you must pass `trust_remote_code=True`.
39
+
40
+ ```python
41
+ import torch
42
+ from transformers import AutoModelForCausalLM, AutoTokenizer
43
+
44
+ # Load tokenizer and model
45
+ tokenizer = AutoTokenizer.from_pretrained("sdkjfgndjfg/gpt-model-2-decoder-100000-tiny-stories-fp16", trust_remote_code=True)
46
+ model = AutoModelForCausalLM.from_pretrained("sdkjfgndjfg/gpt-model-2-decoder-100000-tiny-stories-fp16", trust_remote_code=True)
47
+
48
+ # Set up device
49
+ device = "cuda" if torch.cuda.is_available() else "cpu"
50
+ model.to(device)
51
+
52
+ # Generate text
53
+ prompt = "The transformer is based on"
54
+ inputs = tokenizer(prompt, return_tensors="pt").to(device)
55
+ output_ids = model.generate(
56
+ **inputs,
57
+ max_new_tokens=50,
58
+ do_sample=True,
59
+ temperature=0.8,
60
+ pad_token_id=tokenizer.eos_token_id
61
+ )
62
+
63
+ print(tokenizer.decode(output_ids[0], skip_special_tokens=True))
64
+ ```
65
+
66
+ ## Training Details
67
+
68
+ - **Optimizer**: AdamW (lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
69
+ - **Scheduler**: CosineAnnealingLR (eta_min=1e-5)
70
+ - **Loss**: CrossEntropyLoss (next-token prediction)
71
+ - **Gradient clipping**: max_norm=1.0
72
+
73
+ ## License
74
+
75
+ Apache 2.0
config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "GPTCustomForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "modeling_gpt_custom.GPTCustomConfig",
7
+ "AutoModelForCausalLM": "modeling_gpt_custom.GPTCustomForCausalLM"
8
+ },
9
+ "d_model": 768,
10
+ "dropout": 0.2,
11
+ "dtype": "float32",
12
+ "is_decoder": true,
13
+ "max_seq_len": 1024,
14
+ "model_type": "gpt-custom",
15
+ "num_heads": 8,
16
+ "number_of_transformer_block": 1,
17
+ "transformers_version": "5.13.1",
18
+ "vocab_size": 32000
19
+ }
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.13.1"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad530812d6fe637ece6944fa122f6f1725f66c3630c6a2dd6f0fdbd18117a8e7
3
+ size 236502600
modeling_gpt_custom.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Required for AutoModelForCausalLM(trust_remote_code=True) to know how to build your custom PyTorch architecture.
3
+ (Note: Big companies like Meta/Mistral don't upload files like this because they merge their architecture code directly into the official `transformers` GitHub repository.)
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from transformers import PretrainedConfig, PreTrainedModel
11
+ from transformers.generation import GenerationMixin
12
+ from transformers.modeling_outputs import CausalLMOutput
13
+
14
+ class GPTCustomConfig(PretrainedConfig):
15
+ model_type = "gpt-custom"
16
+ attribute_map = {
17
+ "num_hidden_layers": "number_of_transformer_block",
18
+ "hidden_size": "d_model",
19
+ "num_attention_heads": "num_heads",
20
+ }
21
+
22
+ def __init__(
23
+ self,
24
+ vocab_size: int = 32000,
25
+ d_model: int = 768,
26
+ num_heads: int = 8,
27
+ number_of_transformer_block: int = 6,
28
+ max_seq_len: int = 1024,
29
+ dropout: float = 0.2,
30
+ **kwargs,
31
+ ) -> None:
32
+ super().__init__(**kwargs)
33
+ self.vocab_size = vocab_size
34
+ self.d_model = d_model
35
+ self.num_heads = num_heads
36
+ self.number_of_transformer_block = number_of_transformer_block
37
+ self.max_seq_len = max_seq_len
38
+ self.dropout = dropout
39
+
40
+ class _GPTBlock(nn.Module):
41
+ def __init__(self, config: GPTCustomConfig) -> None:
42
+ super().__init__()
43
+ self.layer_norm_1 = nn.LayerNorm(config.d_model)
44
+ self.layer_norm_2 = nn.LayerNorm(config.d_model)
45
+ self.multihead_attention = nn.MultiheadAttention(
46
+ embed_dim=config.d_model,
47
+ num_heads=config.num_heads,
48
+ batch_first=True,
49
+ )
50
+ self.gelu = nn.GELU()
51
+ self.ffn_1 = nn.Linear(config.d_model, config.d_model * 4)
52
+ self.ffn_2 = nn.Linear(config.d_model * 4, config.d_model)
53
+ self.mha_drop = nn.Dropout(config.dropout)
54
+ self.ffn_drop = nn.Dropout(config.dropout)
55
+ self.register_buffer(
56
+ "causal_mask",
57
+ torch.triu(
58
+ torch.full((config.max_seq_len, config.max_seq_len), float("-inf")),
59
+ diagonal=1,
60
+ ),
61
+ )
62
+
63
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
64
+ _, seq_len, _ = x.size()
65
+ ln1 = self.layer_norm_1(x)
66
+ attn_out, _ = self.multihead_attention(
67
+ ln1, ln1, ln1,
68
+ attn_mask=self.causal_mask[:seq_len, :seq_len],
69
+ )
70
+ x = x + self.mha_drop(attn_out)
71
+ ln2 = self.layer_norm_2(x)
72
+ ff_out = self.ffn_2(self.gelu(self.ffn_1(ln2)))
73
+ return x + self.ffn_drop(ff_out)
74
+
75
+ class GPTCustomForCausalLM(PreTrainedModel, GenerationMixin):
76
+ config_class = GPTCustomConfig
77
+
78
+ def __init__(self, config: GPTCustomConfig) -> None:
79
+ super().__init__(config)
80
+ self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)
81
+ self.positional_encoding = nn.Embedding(config.max_seq_len, config.d_model)
82
+ self.emb_dropout = nn.Dropout(config.dropout)
83
+ self.transformer_blocks = nn.ModuleList(
84
+ [_GPTBlock(config) for _ in range(config.number_of_transformer_block)]
85
+ )
86
+ self.layer_norm_final = nn.LayerNorm(config.d_model)
87
+ self.final_linear_layer = nn.Linear(config.d_model, config.vocab_size, bias=False)
88
+ self.final_linear_layer.weight = self.token_embedding.weight
89
+ self.config.is_decoder = True
90
+ self.post_init()
91
+
92
+ def forward(
93
+ self,
94
+ input_ids: torch.Tensor,
95
+ attention_mask: torch.Tensor | None = None,
96
+ labels: torch.Tensor | None = None,
97
+ **kwargs,
98
+ ) -> CausalLMOutput:
99
+ batch_size, seq_len = input_ids.shape
100
+ position_ids = (
101
+ torch.arange(seq_len, device=input_ids.device)
102
+ .unsqueeze(0)
103
+ .expand(batch_size, -1)
104
+ )
105
+ x = self.token_embedding(input_ids) + self.positional_encoding(position_ids)
106
+ x = self.emb_dropout(x)
107
+ for block in self.transformer_blocks:
108
+ x = block(x)
109
+ logits = self.final_linear_layer(self.layer_norm_final(x))
110
+ loss = None
111
+ if labels is not None:
112
+ shift_logits = logits[..., :-1, :].contiguous()
113
+ shift_labels = labels[..., 1:].contiguous()
114
+ loss = nn.functional.cross_entropy(
115
+ shift_logits.view(-1, self.config.vocab_size),
116
+ shift_labels.view(-1),
117
+ )
118
+ return CausalLMOutput(loss=loss, logits=logits)
119
+
120
+ def get_input_embeddings(self) -> nn.Embedding:
121
+ return self.token_embedding
122
+
123
+ def set_input_embeddings(self, value: nn.Embedding) -> None:
124
+ self.token_embedding = value
125
+
126
+ def prepare_inputs_for_generation(
127
+ self,
128
+ input_ids: torch.Tensor,
129
+ **kwargs,
130
+ ) -> dict:
131
+ return {"input_ids": input_ids}
132
+
133
+ def tie_weights(self, **kwargs) -> None:
134
+ self.final_linear_layer.weight = self.token_embedding.weight
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|endoftext|>",
4
+ "eos_token": "<|endoftext|>",
5
+ "is_local": true,
6
+ "local_files_only": false,
7
+ "model_max_length": 1024,
8
+ "pad_token": "<|pad|>",
9
+ "tokenizer_class": "TokenizersBackend",
10
+ "unk_token": "<|unk|>"
11
+ }