strectelite commited on
Commit
d05ccba
·
verified ·
1 Parent(s): c55ea07

Upload folder using huggingface_hub

Browse files
Files changed (10) hide show
  1. README.md +56 -0
  2. SwiGLU.py +16 -0
  3. attention.py +66 -0
  4. block.py +30 -0
  5. config.json +27 -0
  6. configuration.py +48 -0
  7. model.safetensors +3 -0
  8. modeling.py +153 -0
  9. tokenizer.json +0 -0
  10. tokenizer_config.json +34 -0
README.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ pipeline_tag: text-generation
6
+ ---
7
+
8
+ # PebbleGPT-320M
9
+
10
+ A 320M-parameter dense transformer pretrained from scratch on 10B tokens.
11
+ Base model — it continues text, it does not follow instructions.
12
+
13
+ ## Architecture
14
+
15
+ - 24 layers, hidden size 1024, intermediate 2816
16
+ - Grouped Query Attention: 16 query heads, 4 KV heads (ratio 4)
17
+ - RoPE (theta 10000), SwiGLU, RMSNorm, tied embeddings
18
+ - 2048 context, SmolLM2 tokenizer (49,152 vocab)
19
+
20
+ ## Training data (10B tokens)
21
+
22
+ | Source | Share |
23
+ |---|---|
24
+ | FineWeb-Edu | 42.5% |
25
+ | DCLM-Edu (edu_int_score >= 3) | 42.5% |
26
+ | Python-Edu | 10% |
27
+ | FineMath-4+ | 5% |
28
+
29
+ ## Training
30
+
31
+ AdamW (beta 0.9/0.95, weight decay 0.1 excluding embeddings), WSD schedule
32
+ with peak LR 5e-4 and 10% decay, 2000 warmup steps. 19,073 steps at 524,288
33
+ tokens per step. ~18 hours on a single H100 SXM at ~35% MFU.
34
+
35
+ Final training loss: **2.507** (perplexity ~12.3)
36
+
37
+ ## Results
38
+
39
+ | Benchmark | Score |
40
+ |---|---|
41
+ | HellaSwag (acc_norm) | 30.5 |
42
+ | PIQA | 55.5 |
43
+ | ARC-easy (acc_norm) | 37.7 |
44
+
45
+ ## Usage
46
+
47
+ ```python
48
+ from transformers import AutoModelForCausalLM, AutoTokenizer
49
+
50
+ model = AutoModelForCausalLM.from_pretrained(
51
+ "strectelite/PebbleGPT-320M", trust_remote_code=True
52
+ )
53
+ tok = AutoTokenizer.from_pretrained("strectelite/PebbleGPT-320M")
54
+ ```
55
+
56
+ Note: no KV cache implemented yet, so generation is slow.
SwiGLU.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ class SwiGLU(nn.Module):
7
+ def __init__(self, hidden_size: int = 1024, intermediate_size: int = 2816):
8
+ super().__init__()
9
+ self.gate = nn.Linear(hidden_size, intermediate_size, bias=False)
10
+ self.content = nn.Linear(hidden_size, intermediate_size, bias=False)
11
+ self.swish = F.silu
12
+ self.down = nn.Linear(intermediate_size, hidden_size, bias=False)
13
+
14
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
15
+ return self.down(self.swish(self.gate(x)) * self.content(x))
16
+
attention.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ class GQA(nn.Module):
7
+ def __init__(self, hidden_size: int = 1024, num_heads: int = 16, num_kv_heads: int = 4,
8
+ max_seq_len: int = 2048, rope_base: float = 10000.0):
9
+ super().__init__()
10
+ assert num_heads % num_kv_heads == 0, "num_heads must be divisible by num_kv_heads"
11
+
12
+ self.hidden_size = hidden_size
13
+ self.num_heads = num_heads
14
+ self.num_kv_heads = num_kv_heads
15
+ self.head_dim = hidden_size // num_heads
16
+
17
+ self.W_Q = nn.Linear(hidden_size, num_heads * self.head_dim, bias=False)
18
+ self.W_K = nn.Linear(hidden_size, num_kv_heads * self.head_dim, bias=False)
19
+ self.W_V = nn.Linear(hidden_size, num_kv_heads * self.head_dim, bias=False)
20
+ self.W_O = nn.Linear(num_heads * self.head_dim, hidden_size, bias=False)
21
+
22
+ cos, sin = self._precompute_rope(self.head_dim, max_seq_len, rope_base)
23
+ self.register_buffer("rope_cos", cos, persistent=False)
24
+ self.register_buffer("rope_sin", sin, persistent=False)
25
+
26
+ @staticmethod
27
+ def _precompute_rope(head_dim, max_seq_len, base):
28
+ inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
29
+ positions = torch.arange(max_seq_len).float()
30
+ freqs = torch.outer(positions, inv_freq)
31
+ emb = torch.cat((freqs, freqs), dim=-1)
32
+ return emb.cos(), emb.sin()
33
+
34
+ @staticmethod
35
+ def _rotate_half(x: torch.Tensor) -> torch.Tensor:
36
+ x1, x2 = x.chunk(2, dim=-1)
37
+ return torch.cat((-x2, x1), dim=-1)
38
+
39
+ @classmethod
40
+ def _apply_rope(cls, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
41
+ return (x * cos) + (cls._rotate_half(x) * sin)
42
+
43
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
44
+ B, T, _ = x.shape
45
+
46
+ Q = self.W_Q(x)
47
+ K = self.W_K(x)
48
+ V = self.W_V(x)
49
+
50
+ Q = Q.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
51
+ K = K.view(B, T, self.num_kv_heads, self.head_dim).transpose(1, 2)
52
+ V = V.view(B, T, self.num_kv_heads, self.head_dim).transpose(1, 2)
53
+
54
+ cos = self.rope_cos[:T].unsqueeze(0).unsqueeze(0)
55
+ sin = self.rope_sin[:T].unsqueeze(0).unsqueeze(0)
56
+ Q = self._apply_rope(Q, cos, sin)
57
+ K = self._apply_rope(K, cos, sin)
58
+
59
+ repeats = self.num_heads // self.num_kv_heads
60
+ K = K.repeat_interleave(repeats, dim=1)
61
+ V = V.repeat_interleave(repeats, dim=1)
62
+
63
+ O = F.scaled_dot_product_attention(Q, K, V, is_causal=True)
64
+
65
+ O = O.transpose(1, 2).contiguous().view(B, T, self.num_heads * self.head_dim)
66
+ return self.W_O(O)
block.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from .attention import GQA
5
+ from .SwiGLU import SwiGLU
6
+
7
+
8
+ class TransformerBlock(nn.Module):
9
+ def __init__(self, hidden_size: int = 1024, intermediate_size: int = 2816,
10
+ num_heads: int = 16, num_kv_heads: int = 4, max_seq_len: int = 2048,
11
+ rope_base: float = 10000.0, norm_eps: float = 1e-6):
12
+ super().__init__()
13
+ self.attn_norm = nn.RMSNorm(hidden_size, eps=norm_eps)
14
+ self.attn = GQA(
15
+ hidden_size=hidden_size,
16
+ num_heads=num_heads,
17
+ num_kv_heads=num_kv_heads,
18
+ max_seq_len=max_seq_len,
19
+ rope_base=rope_base,
20
+ )
21
+ self.mlp_norm = nn.RMSNorm(hidden_size, eps=norm_eps)
22
+ self.mlp = SwiGLU(
23
+ hidden_size=hidden_size,
24
+ intermediate_size=intermediate_size,
25
+ )
26
+
27
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
28
+ x = x + self.attn(self.attn_norm(x))
29
+ x = x + self.mlp(self.mlp_norm(x))
30
+ return x
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "PebbleGPTForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration.PebbleGPTConfig",
7
+ "AutoModelForCausalLM": "modeling.PebbleGPTForCausalLM"
8
+ },
9
+ "dtype": "float32",
10
+ "hidden_size": 1024,
11
+ "intermediate_size": 2816,
12
+ "max_position_embeddings": 2048,
13
+ "max_seq_len": 2048,
14
+ "model_type": "pebblegpt",
15
+ "norm_eps": 1e-06,
16
+ "num_attention_heads": 16,
17
+ "num_heads": 16,
18
+ "num_hidden_layers": 24,
19
+ "num_key_value_heads": 4,
20
+ "num_kv_heads": 4,
21
+ "rms_norm_eps": 1e-06,
22
+ "rope_base": 10000.0,
23
+ "rope_theta": 10000.0,
24
+ "tie_word_embeddings": true,
25
+ "transformers_version": "5.15.1",
26
+ "vocab_size": 49152
27
+ }
configuration.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HF-compatible config for PebbleGPT.
2
+
3
+ Defaults mirror PebbleGPT's so a training checkpoint loads without remapping.
4
+ """
5
+
6
+ from transformers import PretrainedConfig
7
+
8
+
9
+ class PebbleGPTConfig(PretrainedConfig):
10
+ model_type = "pebblegpt"
11
+
12
+ def __init__(self,
13
+ vocab_size: int = 49152,
14
+ hidden_size: int = 1024,
15
+ num_hidden_layers: int = 24,
16
+ num_heads: int = 16,
17
+ num_kv_heads: int = 4,
18
+ intermediate_size: int = 2816,
19
+ max_seq_len: int = 2048,
20
+ rope_base: float = 10000.0,
21
+ norm_eps: float = 1e-6,
22
+ tie_word_embeddings: bool = True,
23
+ **kwargs):
24
+ self.vocab_size = vocab_size
25
+ self.hidden_size = hidden_size
26
+ self.num_hidden_layers = num_hidden_layers
27
+ self.num_heads = num_heads
28
+ self.num_kv_heads = num_kv_heads
29
+ self.intermediate_size = intermediate_size
30
+ self.max_seq_len = max_seq_len
31
+ self.rope_base = rope_base
32
+ self.norm_eps = norm_eps
33
+
34
+ # Aliases some HF tooling looks for.
35
+ self.num_attention_heads = num_heads
36
+ self.num_key_value_heads = num_kv_heads
37
+ self.max_position_embeddings = max_seq_len
38
+ self.rope_theta = rope_base
39
+ self.rms_norm_eps = norm_eps
40
+
41
+ # `pebblegpt` isn't a registered transformers architecture, so exports
42
+ # carry their own source and load via trust_remote_code.
43
+ self.auto_map = {
44
+ "AutoConfig": "configuration.PebbleGPTConfig",
45
+ "AutoModelForCausalLM": "modeling.PebbleGPTForCausalLM",
46
+ }
47
+
48
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b838bfb0c963ae78af04b2a78a0211a03adb21f1863012c35a026f075da066ce
3
+ size 1283679472
modeling.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HF PreTrainedModel wrapper around PebbleGPT's blocks.
2
+
3
+ Used for evaluation (LightEval) and Hub publishing. Training uses the plain
4
+ PebbleGPT class in model.py — attribute names match, so checkpoints load
5
+ into either without key remapping.
6
+
7
+ Generation is not supported yet: attention has no KV cache, so generate()
8
+ would be unusably slow. That's fine for the multiple-choice benchmarks
9
+ (HellaSwag, PIQA, ARC, MMLU), which only need forward passes.
10
+ """
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from transformers import PreTrainedModel
15
+ from transformers.modeling_outputs import CausalLMOutputWithPast
16
+
17
+ from .block import TransformerBlock
18
+ from .configuration import PebbleGPTConfig
19
+
20
+
21
+ class PebbleGPTForCausalLM(PreTrainedModel):
22
+ config_class = PebbleGPTConfig
23
+ base_model_prefix = "pebblegpt"
24
+ supports_gradient_checkpointing = False
25
+ _no_split_modules = ["TransformerBlock"]
26
+ _tied_weights_keys = {"proj_head.weight": "token_embedding.weight"}
27
+
28
+ def __init__(self, config: PebbleGPTConfig):
29
+ super().__init__(config)
30
+
31
+ self.token_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
32
+
33
+ self.blocks = nn.ModuleList([
34
+ TransformerBlock(
35
+ hidden_size=config.hidden_size,
36
+ num_heads=config.num_heads,
37
+ num_kv_heads=config.num_kv_heads,
38
+ intermediate_size=config.intermediate_size,
39
+ max_seq_len=config.max_seq_len,
40
+ rope_base=config.rope_base,
41
+ norm_eps=config.norm_eps,
42
+ )
43
+ for _ in range(config.num_hidden_layers)
44
+ ])
45
+
46
+ self.final_norm = nn.RMSNorm(config.hidden_size, eps=config.norm_eps)
47
+ self.proj_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
48
+
49
+ self.post_init()
50
+ if config.tie_word_embeddings:
51
+ self.proj_head.weight = self.token_embedding.weight
52
+
53
+ # --- HF plumbing -------------------------------------------------
54
+
55
+ def _init_weights(self, module: nn.Module) -> None:
56
+ if isinstance(module, nn.Linear):
57
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
58
+ if module.bias is not None:
59
+ nn.init.zeros_(module.bias)
60
+ elif isinstance(module, nn.Embedding):
61
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
62
+
63
+ def get_input_embeddings(self):
64
+ return self.token_embedding
65
+
66
+ def set_input_embeddings(self, value):
67
+ self.token_embedding = value
68
+
69
+ def get_output_embeddings(self):
70
+ return self.proj_head
71
+
72
+ def set_output_embeddings(self, value):
73
+ self.proj_head = value
74
+
75
+ def _tie_weights(self):
76
+ if self.config.tie_word_embeddings:
77
+ self.proj_head.weight = self.token_embedding.weight
78
+
79
+ # --- forward -----------------------------------------------------
80
+
81
+ def forward(self,
82
+ input_ids: torch.LongTensor | None = None,
83
+ attention_mask: torch.Tensor | None = None,
84
+ position_ids: torch.LongTensor | None = None,
85
+ past_key_values=None,
86
+ inputs_embeds: torch.FloatTensor | None = None,
87
+ labels: torch.LongTensor | None = None,
88
+ use_cache: bool | None = None,
89
+ output_attentions: bool | None = None,
90
+ output_hidden_states: bool | None = None,
91
+ return_dict: bool | None = None,
92
+ **kwargs) -> CausalLMOutputWithPast:
93
+ """Attention is always causal, so attention_mask / position_ids /
94
+ past_key_values are accepted for interface compatibility and ignored."""
95
+ return_dict = return_dict if return_dict is not None else True
96
+
97
+ if inputs_embeds is not None:
98
+ x = inputs_embeds
99
+ elif input_ids is not None:
100
+ x = self.token_embedding(input_ids)
101
+ else:
102
+ raise ValueError("provide either input_ids or inputs_embeds")
103
+
104
+ hidden_states = [] if output_hidden_states else None
105
+
106
+ for block in self.blocks:
107
+ if output_hidden_states:
108
+ hidden_states.append(x)
109
+ x = block(x)
110
+
111
+ x = self.final_norm(x)
112
+ if output_hidden_states:
113
+ hidden_states.append(x)
114
+
115
+ logits = self.proj_head(x)
116
+
117
+ loss = None
118
+ if labels is not None:
119
+ # HF convention: labels are unshifted, the model shifts internally
120
+ shift_logits = logits[..., :-1, :].contiguous()
121
+ shift_labels = labels[..., 1:].contiguous()
122
+ loss = nn.functional.cross_entropy(
123
+ shift_logits.view(-1, shift_logits.size(-1)),
124
+ shift_labels.view(-1),
125
+ )
126
+
127
+ if not return_dict:
128
+ out = (logits,)
129
+ if output_hidden_states:
130
+ out += (tuple(hidden_states),)
131
+ return ((loss,) + out) if loss is not None else out
132
+
133
+ return CausalLMOutputWithPast(
134
+ loss=loss,
135
+ logits=logits,
136
+ past_key_values=None,
137
+ hidden_states=tuple(hidden_states) if output_hidden_states else None,
138
+ attentions=None,
139
+ )
140
+
141
+
142
+ def from_training_checkpoint(ckpt_path,
143
+ config: PebbleGPTConfig | None = None,
144
+ device: str = "cpu") -> PebbleGPTForCausalLM:
145
+ """Load a PebbleGPT training checkpoint into the HF wrapper."""
146
+ state = torch.load(ckpt_path, map_location=device, weights_only=False)
147
+ model = PebbleGPTForCausalLM(config or PebbleGPTConfig())
148
+ missing, unexpected = model.load_state_dict(state["model"], strict=False)
149
+ if missing:
150
+ print(f"missing keys: {missing}")
151
+ if unexpected:
152
+ print(f"unexpected keys: {unexpected}")
153
+ return model.to(device).eval()
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|endoftext|>",
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|endoftext|>",
7
+ "errors": "replace",
8
+ "extra_special_tokens": [
9
+ "<|endoftext|>",
10
+ "<|im_start|>",
11
+ "<|im_end|>",
12
+ "<repo_name>",
13
+ "<reponame>",
14
+ "<file_sep>",
15
+ "<filename>",
16
+ "<gh_stars>",
17
+ "<issue_start>",
18
+ "<issue_comment>",
19
+ "<issue_closed>",
20
+ "<jupyter_start>",
21
+ "<jupyter_text>",
22
+ "<jupyter_code>",
23
+ "<jupyter_output>",
24
+ "<jupyter_script>",
25
+ "<empty_output>"
26
+ ],
27
+ "is_local": false,
28
+ "local_files_only": false,
29
+ "model_max_length": 8192,
30
+ "pad_token": null,
31
+ "tokenizer_class": "GPT2Tokenizer",
32
+ "unk_token": "<|endoftext|>",
33
+ "vocab_size": 49152
34
+ }