Instructions to use strectelite/PebbleGPT-320M-Instruct with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use strectelite/PebbleGPT-320M-Instruct with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="strectelite/PebbleGPT-320M-Instruct", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("strectelite/PebbleGPT-320M-Instruct", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use strectelite/PebbleGPT-320M-Instruct with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "strectelite/PebbleGPT-320M-Instruct" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "strectelite/PebbleGPT-320M-Instruct", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/strectelite/PebbleGPT-320M-Instruct
- SGLang
How to use strectelite/PebbleGPT-320M-Instruct with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "strectelite/PebbleGPT-320M-Instruct" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "strectelite/PebbleGPT-320M-Instruct", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "strectelite/PebbleGPT-320M-Instruct" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "strectelite/PebbleGPT-320M-Instruct", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use strectelite/PebbleGPT-320M-Instruct with Docker Model Runner:
docker model run hf.co/strectelite/PebbleGPT-320M-Instruct
Upload folder using huggingface_hub
Browse files- SwiGLU.py +16 -0
- attention.py +102 -0
- block.py +33 -0
- config.json +27 -0
- configuration.py +48 -0
- generation_config.json +6 -0
- model.safetensors +3 -0
- modeling.py +178 -0
- tokenizer.json +0 -0
- tokenizer_config.json +34 -0
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,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
layer_idx: int = 0):
|
| 10 |
+
super().__init__()
|
| 11 |
+
assert num_heads % num_kv_heads == 0, "num_heads must be divisible by num_kv_heads"
|
| 12 |
+
|
| 13 |
+
self.layer_idx = layer_idx
|
| 14 |
+
self.hidden_size = hidden_size
|
| 15 |
+
self.num_heads = num_heads
|
| 16 |
+
self.num_kv_heads = num_kv_heads
|
| 17 |
+
self.head_dim = hidden_size // num_heads
|
| 18 |
+
self.max_seq_len = max_seq_len
|
| 19 |
+
self.rope_base = rope_base
|
| 20 |
+
|
| 21 |
+
self.W_Q = nn.Linear(hidden_size, num_heads * self.head_dim, bias=False)
|
| 22 |
+
self.W_K = nn.Linear(hidden_size, num_kv_heads * self.head_dim, bias=False)
|
| 23 |
+
self.W_V = nn.Linear(hidden_size, num_kv_heads * self.head_dim, bias=False)
|
| 24 |
+
self.W_O = nn.Linear(num_heads * self.head_dim, hidden_size, bias=False)
|
| 25 |
+
|
| 26 |
+
# RoPE tables are derived from rope_base and head_dim on first use.
|
| 27 |
+
# Deliberately NOT registered as buffers: they aren't in the state
|
| 28 |
+
# dict, and from_pretrained zero-fills or skips non-persistent buffers,
|
| 29 |
+
# which silently turns RoPE into the identity.
|
| 30 |
+
self._rope_cache: tuple[torch.Tensor, torch.Tensor] | None = None
|
| 31 |
+
|
| 32 |
+
def _get_rope(self, seq_len: int, device, dtype):
|
| 33 |
+
"""cos/sin tables covering [0, seq_len), cached and grown as needed."""
|
| 34 |
+
cache = self._rope_cache
|
| 35 |
+
if (cache is not None
|
| 36 |
+
and cache[0].size(0) >= seq_len
|
| 37 |
+
and cache[0].device == device
|
| 38 |
+
and cache[0].dtype == dtype):
|
| 39 |
+
return cache[0][:seq_len], cache[1][:seq_len]
|
| 40 |
+
|
| 41 |
+
n = max(seq_len, self.max_seq_len)
|
| 42 |
+
inv_freq = 1.0 / (self.rope_base ** (
|
| 43 |
+
torch.arange(0, self.head_dim, 2, device=device, dtype=torch.float32)
|
| 44 |
+
/ self.head_dim))
|
| 45 |
+
positions = torch.arange(n, device=device, dtype=torch.float32)
|
| 46 |
+
freqs = torch.outer(positions, inv_freq)
|
| 47 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 48 |
+
cos, sin = emb.cos().to(dtype), emb.sin().to(dtype)
|
| 49 |
+
self._rope_cache = (cos, sin)
|
| 50 |
+
return cos[:seq_len], sin[:seq_len]
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def _rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 54 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 55 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 56 |
+
|
| 57 |
+
@classmethod
|
| 58 |
+
def _apply_rope(cls, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 59 |
+
return (x * cos) + (cls._rotate_half(x) * sin)
|
| 60 |
+
|
| 61 |
+
def forward(self, x: torch.Tensor, past_key_values=None, past_len: int = 0):
|
| 62 |
+
"""past_key_values is a transformers Cache object, or None.
|
| 63 |
+
|
| 64 |
+
RoPE is applied before caching, so cached keys already carry their
|
| 65 |
+
position — new tokens must be offset by past_len.
|
| 66 |
+
"""
|
| 67 |
+
B, T, _ = x.shape
|
| 68 |
+
|
| 69 |
+
# 1. Projections
|
| 70 |
+
Q = self.W_Q(x)
|
| 71 |
+
K = self.W_K(x)
|
| 72 |
+
V = self.W_V(x)
|
| 73 |
+
|
| 74 |
+
# 2. Reshape into heads: [B, T, H*d_h] -> [B, H, T, d_h]
|
| 75 |
+
Q = Q.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
|
| 76 |
+
K = K.view(B, T, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 77 |
+
V = V.view(B, T, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 78 |
+
|
| 79 |
+
# 3. RoPE — these tokens sit at positions [past_len, past_len + T)
|
| 80 |
+
cos_all, sin_all = self._get_rope(past_len + T, Q.device, Q.dtype)
|
| 81 |
+
cos = cos_all[past_len:past_len + T].unsqueeze(0).unsqueeze(0)
|
| 82 |
+
sin = sin_all[past_len:past_len + T].unsqueeze(0).unsqueeze(0)
|
| 83 |
+
Q = self._apply_rope(Q, cos, sin)
|
| 84 |
+
K = self._apply_rope(K, cos, sin)
|
| 85 |
+
|
| 86 |
+
# 4. Cache.update appends and returns the full accumulated K/V
|
| 87 |
+
if past_key_values is not None:
|
| 88 |
+
K, V = past_key_values.update(K, V, self.layer_idx)
|
| 89 |
+
|
| 90 |
+
# 5. Expand KV heads to match Q heads (GQA)
|
| 91 |
+
repeats = self.num_heads // self.num_kv_heads
|
| 92 |
+
K = K.repeat_interleave(repeats, dim=1)
|
| 93 |
+
V = V.repeat_interleave(repeats, dim=1)
|
| 94 |
+
|
| 95 |
+
# 6. Attention. With a cache, T == 1 while K spans the full context —
|
| 96 |
+
# is_causal on a non-square score matrix would mask incorrectly.
|
| 97 |
+
# A single query legitimately attends to everything cached.
|
| 98 |
+
O = F.scaled_dot_product_attention(Q, K, V, is_causal=(T > 1))
|
| 99 |
+
|
| 100 |
+
# 7. Merge heads and project out
|
| 101 |
+
O = O.transpose(1, 2).contiguous().view(B, T, self.num_heads * self.head_dim)
|
| 102 |
+
return self.W_O(O)
|
block.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
layer_idx: int = 0):
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.attn_norm = nn.RMSNorm(hidden_size, eps=norm_eps)
|
| 15 |
+
self.attn = GQA(
|
| 16 |
+
hidden_size=hidden_size,
|
| 17 |
+
num_heads=num_heads,
|
| 18 |
+
num_kv_heads=num_kv_heads,
|
| 19 |
+
max_seq_len=max_seq_len,
|
| 20 |
+
rope_base=rope_base,
|
| 21 |
+
layer_idx=layer_idx,
|
| 22 |
+
)
|
| 23 |
+
self.mlp_norm = nn.RMSNorm(hidden_size, eps=norm_eps)
|
| 24 |
+
self.mlp = SwiGLU(
|
| 25 |
+
hidden_size=hidden_size,
|
| 26 |
+
intermediate_size=intermediate_size,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def forward(self, x: torch.Tensor, past_key_values=None, past_len: int = 0):
|
| 30 |
+
x = x + self.attn(self.attn_norm(x),
|
| 31 |
+
past_key_values=past_key_values, past_len=past_len)
|
| 32 |
+
x = x + self.mlp(self.mlp_norm(x))
|
| 33 |
+
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.16.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)
|
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.16.1"
|
| 6 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9aa323edf706213784350dea96df0a74ee6772810f1ae75d3032da194c1f6916
|
| 3 |
+
size 1283679472
|
modeling.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HF PreTrainedModel wrapper around PebbleGPT's blocks.
|
| 2 |
+
|
| 3 |
+
Used for evaluation, generation, and Hub publishing. Training uses the plain
|
| 4 |
+
PebbleGPT class in model.py — attribute names match, so checkpoints load into
|
| 5 |
+
either without key remapping.
|
| 6 |
+
|
| 7 |
+
KV caching uses the transformers Cache object directly rather than legacy
|
| 8 |
+
tuples: Cache.update(k, v, layer_idx) appends and returns the accumulated
|
| 9 |
+
keys/values, which is the stable API across versions.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from transformers import PreTrainedModel
|
| 15 |
+
from transformers.generation import GenerationMixin
|
| 16 |
+
from transformers.cache_utils import DynamicCache
|
| 17 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 18 |
+
|
| 19 |
+
from .block import TransformerBlock
|
| 20 |
+
from .configuration import PebbleGPTConfig
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class PebbleGPTForCausalLM(PreTrainedModel, GenerationMixin):
|
| 24 |
+
config_class = PebbleGPTConfig
|
| 25 |
+
base_model_prefix = "pebblegpt"
|
| 26 |
+
supports_gradient_checkpointing = False
|
| 27 |
+
_no_split_modules = ["TransformerBlock"]
|
| 28 |
+
_tied_weights_keys = {"proj_head.weight": "token_embedding.weight"}
|
| 29 |
+
|
| 30 |
+
def __init__(self, config: PebbleGPTConfig):
|
| 31 |
+
super().__init__(config)
|
| 32 |
+
|
| 33 |
+
self.token_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 34 |
+
|
| 35 |
+
self.blocks = nn.ModuleList([
|
| 36 |
+
TransformerBlock(
|
| 37 |
+
hidden_size=config.hidden_size,
|
| 38 |
+
num_heads=config.num_heads,
|
| 39 |
+
num_kv_heads=config.num_kv_heads,
|
| 40 |
+
intermediate_size=config.intermediate_size,
|
| 41 |
+
max_seq_len=config.max_seq_len,
|
| 42 |
+
rope_base=config.rope_base,
|
| 43 |
+
norm_eps=config.norm_eps,
|
| 44 |
+
layer_idx=i,
|
| 45 |
+
)
|
| 46 |
+
for i in range(config.num_hidden_layers)
|
| 47 |
+
])
|
| 48 |
+
|
| 49 |
+
self.final_norm = nn.RMSNorm(config.hidden_size, eps=config.norm_eps)
|
| 50 |
+
self.proj_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 51 |
+
|
| 52 |
+
self.post_init()
|
| 53 |
+
if config.tie_word_embeddings:
|
| 54 |
+
self.proj_head.weight = self.token_embedding.weight
|
| 55 |
+
|
| 56 |
+
# --- HF plumbing -------------------------------------------------
|
| 57 |
+
|
| 58 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 59 |
+
if isinstance(module, nn.Linear):
|
| 60 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 61 |
+
if module.bias is not None:
|
| 62 |
+
nn.init.zeros_(module.bias)
|
| 63 |
+
elif isinstance(module, nn.Embedding):
|
| 64 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 65 |
+
|
| 66 |
+
def get_input_embeddings(self):
|
| 67 |
+
return self.token_embedding
|
| 68 |
+
|
| 69 |
+
def set_input_embeddings(self, value):
|
| 70 |
+
self.token_embedding = value
|
| 71 |
+
|
| 72 |
+
def get_output_embeddings(self):
|
| 73 |
+
return self.proj_head
|
| 74 |
+
|
| 75 |
+
def set_output_embeddings(self, value):
|
| 76 |
+
self.proj_head = value
|
| 77 |
+
|
| 78 |
+
def _tie_weights(self):
|
| 79 |
+
if self.config.tie_word_embeddings:
|
| 80 |
+
self.proj_head.weight = self.token_embedding.weight
|
| 81 |
+
|
| 82 |
+
# --- generation --------------------------------------------------
|
| 83 |
+
|
| 84 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
|
| 85 |
+
"""With a populated cache, only the new tokens need a forward pass."""
|
| 86 |
+
past_len = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 87 |
+
if past_len > 0:
|
| 88 |
+
input_ids = input_ids[:, past_len:]
|
| 89 |
+
return {
|
| 90 |
+
"input_ids": input_ids,
|
| 91 |
+
"past_key_values": past_key_values,
|
| 92 |
+
"use_cache": kwargs.get("use_cache", True),
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
def can_generate(self) -> bool:
|
| 96 |
+
return True
|
| 97 |
+
|
| 98 |
+
# --- forward -----------------------------------------------------
|
| 99 |
+
|
| 100 |
+
def forward(self,
|
| 101 |
+
input_ids: torch.LongTensor | None = None,
|
| 102 |
+
attention_mask: torch.Tensor | None = None,
|
| 103 |
+
position_ids: torch.LongTensor | None = None,
|
| 104 |
+
past_key_values=None,
|
| 105 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 106 |
+
labels: torch.LongTensor | None = None,
|
| 107 |
+
use_cache: bool | None = None,
|
| 108 |
+
output_attentions: bool | None = None,
|
| 109 |
+
output_hidden_states: bool | None = None,
|
| 110 |
+
return_dict: bool | None = None,
|
| 111 |
+
**kwargs) -> CausalLMOutputWithPast:
|
| 112 |
+
"""Attention is always causal, so attention_mask and position_ids are
|
| 113 |
+
accepted for interface compatibility and ignored."""
|
| 114 |
+
return_dict = return_dict if return_dict is not None else True
|
| 115 |
+
use_cache = use_cache if use_cache is not None else False
|
| 116 |
+
|
| 117 |
+
if use_cache and past_key_values is None:
|
| 118 |
+
past_key_values = DynamicCache()
|
| 119 |
+
|
| 120 |
+
past_len = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 121 |
+
|
| 122 |
+
if inputs_embeds is not None:
|
| 123 |
+
x = inputs_embeds
|
| 124 |
+
elif input_ids is not None:
|
| 125 |
+
x = self.token_embedding(input_ids)
|
| 126 |
+
else:
|
| 127 |
+
raise ValueError("provide either input_ids or inputs_embeds")
|
| 128 |
+
|
| 129 |
+
hidden_states = [] if output_hidden_states else None
|
| 130 |
+
|
| 131 |
+
for block in self.blocks:
|
| 132 |
+
if output_hidden_states:
|
| 133 |
+
hidden_states.append(x)
|
| 134 |
+
x = block(x, past_key_values=past_key_values, past_len=past_len)
|
| 135 |
+
|
| 136 |
+
x = self.final_norm(x)
|
| 137 |
+
if output_hidden_states:
|
| 138 |
+
hidden_states.append(x)
|
| 139 |
+
|
| 140 |
+
logits = self.proj_head(x)
|
| 141 |
+
|
| 142 |
+
loss = None
|
| 143 |
+
if labels is not None:
|
| 144 |
+
# HF convention: labels are unshifted, the model shifts internally
|
| 145 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 146 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 147 |
+
loss = nn.functional.cross_entropy(
|
| 148 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 149 |
+
shift_labels.view(-1),
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
if not return_dict:
|
| 153 |
+
out = (logits,)
|
| 154 |
+
if use_cache:
|
| 155 |
+
out += (past_key_values,)
|
| 156 |
+
return ((loss,) + out) if loss is not None else out
|
| 157 |
+
|
| 158 |
+
return CausalLMOutputWithPast(
|
| 159 |
+
loss=loss,
|
| 160 |
+
logits=logits,
|
| 161 |
+
past_key_values=past_key_values if use_cache else None,
|
| 162 |
+
hidden_states=tuple(hidden_states) if output_hidden_states else None,
|
| 163 |
+
attentions=None,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def from_training_checkpoint(ckpt_path,
|
| 168 |
+
config: PebbleGPTConfig | None = None,
|
| 169 |
+
device: str = "cpu") -> PebbleGPTForCausalLM:
|
| 170 |
+
"""Load a PebbleGPT training checkpoint into the HF wrapper."""
|
| 171 |
+
state = torch.load(ckpt_path, map_location=device, weights_only=False)
|
| 172 |
+
model = PebbleGPTForCausalLM(config or PebbleGPTConfig())
|
| 173 |
+
missing, unexpected = model.load_state_dict(state["model"], strict=False)
|
| 174 |
+
if missing:
|
| 175 |
+
print(f"missing keys: {missing}")
|
| 176 |
+
if unexpected:
|
| 177 |
+
print(f"unexpected keys: {unexpected}")
|
| 178 |
+
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": "<|endoftext|>",
|
| 31 |
+
"tokenizer_class": "GPT2Tokenizer",
|
| 32 |
+
"unk_token": "<|endoftext|>",
|
| 33 |
+
"vocab_size": 49152
|
| 34 |
+
}
|