Instructions to use Serdar404/RecGPT-10M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Serdar404/RecGPT-10M with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Serdar404/RecGPT-10M", trust_remote_code=True)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Serdar404/RecGPT-10M", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Serdar404/RecGPT-10M with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Serdar404/RecGPT-10M" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Serdar404/RecGPT-10M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Serdar404/RecGPT-10M
- SGLang
How to use Serdar404/RecGPT-10M 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 "Serdar404/RecGPT-10M" \ --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": "Serdar404/RecGPT-10M", "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 "Serdar404/RecGPT-10M" \ --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": "Serdar404/RecGPT-10M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Serdar404/RecGPT-10M with Docker Model Runner:
docker model run hf.co/Serdar404/RecGPT-10M
Upload RecGPT-10M main checkpoint
Browse files- config.json +24 -0
- model.safetensors +3 -0
- modeling_recgpt.py +345 -0
- tokenizer.json +0 -0
- tokenizer_config.json +8 -0
- train_config.json +74 -0
config.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"RecGPTForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "modeling_recgpt.RecGPTConfig",
|
| 7 |
+
"AutoModelForCausalLM": "modeling_recgpt.RecGPTForCausalLM"
|
| 8 |
+
},
|
| 9 |
+
"dtype": "float32",
|
| 10 |
+
"embedding_size": 192,
|
| 11 |
+
"head_dim": 64,
|
| 12 |
+
"hidden_size": 768,
|
| 13 |
+
"intermediate_size": 12288,
|
| 14 |
+
"is_decoder": true,
|
| 15 |
+
"max_position_embeddings": 1024,
|
| 16 |
+
"model_type": "recgpt",
|
| 17 |
+
"num_heads": 12,
|
| 18 |
+
"pad_token_id": 0,
|
| 19 |
+
"recursive_depth": 16,
|
| 20 |
+
"tie_word_embeddings": false,
|
| 21 |
+
"transformers_version": "5.9.0",
|
| 22 |
+
"use_cache": false,
|
| 23 |
+
"vocab_size": 32768
|
| 24 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:728d0a6bdbdc63b69cb17a90ac0b39288b8925aaa65e3e6a030de01fc88e7268
|
| 3 |
+
size 136689008
|
modeling_recg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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from torch import nn
|
| 8 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
| 9 |
+
from transformers import initialization as init
|
| 10 |
+
from transformers.modeling_outputs import CausalLMOutput
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class RecGPTConfig(PretrainedConfig):
|
| 14 |
+
model_type = "recgpt"
|
| 15 |
+
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
vocab_size: int = 32768,
|
| 19 |
+
hidden_size: int = 640,
|
| 20 |
+
embedding_size: int = 192, # Allows for factorized embeddings, only makes sense at babylm scale.
|
| 21 |
+
head_dim: int = 64,
|
| 22 |
+
intermediate_size: int = 10240,
|
| 23 |
+
recursive_depth: int = 16,
|
| 24 |
+
max_position_embeddings: int = 1024,
|
| 25 |
+
pad_token_id: int = 0, # Padding is determined by segment_ids, this is only used for embeddings/HF metadata.
|
| 26 |
+
tie_word_embeddings: bool = False, # Tied embeddings greatly hurt performance for recursive models.
|
| 27 |
+
**kwargs,
|
| 28 |
+
):
|
| 29 |
+
super().__init__(
|
| 30 |
+
pad_token_id=pad_token_id,
|
| 31 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 32 |
+
**kwargs,
|
| 33 |
+
)
|
| 34 |
+
if hidden_size % head_dim != 0:
|
| 35 |
+
raise ValueError("hidden_size must be divisible by head_dim.")
|
| 36 |
+
|
| 37 |
+
self.vocab_size = vocab_size
|
| 38 |
+
self.hidden_size = hidden_size
|
| 39 |
+
self.embedding_size = embedding_size
|
| 40 |
+
self.head_dim = head_dim
|
| 41 |
+
self.num_heads = hidden_size // head_dim
|
| 42 |
+
self.intermediate_size = intermediate_size
|
| 43 |
+
self.recursive_depth = recursive_depth
|
| 44 |
+
self.max_position_embeddings = max_position_embeddings
|
| 45 |
+
self.is_decoder = True
|
| 46 |
+
self.use_cache = False
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class RMSNorm(nn.Module):
|
| 50 |
+
def __init__(self, hidden_size: int, eps: float = 1e-6, use_bias: bool = False):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 53 |
+
self.bias = nn.Parameter(torch.zeros(hidden_size)) if use_bias else None
|
| 54 |
+
self.eps = eps
|
| 55 |
+
|
| 56 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 57 |
+
x = F.rms_norm(x, (x.size(-1),), self.weight, self.eps)
|
| 58 |
+
if self.bias is not None:
|
| 59 |
+
x = x + self.bias
|
| 60 |
+
return x
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class RotaryEmbedding(nn.Module):
|
| 64 |
+
def __init__(self, head_dim: int, max_position_embeddings: int, theta: float):
|
| 65 |
+
super().__init__()
|
| 66 |
+
if head_dim % 2 != 0:
|
| 67 |
+
raise ValueError("RoPE requires an even head dimension.")
|
| 68 |
+
|
| 69 |
+
self.head_dim = head_dim
|
| 70 |
+
self.max_position_embeddings = max_position_embeddings
|
| 71 |
+
self.theta = theta
|
| 72 |
+
|
| 73 |
+
# We register these as buffers to ensure they get moved to device together with the model.
|
| 74 |
+
self.register_buffer("cos", torch.empty(max_position_embeddings, head_dim // 2), persistent=False)
|
| 75 |
+
self.register_buffer("sin", torch.empty(max_position_embeddings, head_dim // 2), persistent=False)
|
| 76 |
+
self.reset_parameters()
|
| 77 |
+
|
| 78 |
+
def reset_parameters(self) -> None:
|
| 79 |
+
inv_freq = 1.0 / (
|
| 80 |
+
self.theta
|
| 81 |
+
** (
|
| 82 |
+
torch.arange(0, self.head_dim, 2, device=self.cos.device, dtype=torch.float32)
|
| 83 |
+
/ self.head_dim
|
| 84 |
+
)
|
| 85 |
+
)
|
| 86 |
+
positions = torch.arange(self.max_position_embeddings, device=self.cos.device, dtype=torch.float32)
|
| 87 |
+
freqs = torch.outer(positions, inv_freq)
|
| 88 |
+
init.copy_(self.cos, freqs.cos())
|
| 89 |
+
init.copy_(self.sin, freqs.sin())
|
| 90 |
+
|
| 91 |
+
def forward(self, x: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor:
|
| 92 |
+
cos = self.cos[position_ids].unsqueeze(2).to(dtype=x.dtype)
|
| 93 |
+
sin = self.sin[position_ids].unsqueeze(2).to(dtype=x.dtype)
|
| 94 |
+
x_even = x[..., 0::2]
|
| 95 |
+
x_odd = x[..., 1::2]
|
| 96 |
+
|
| 97 |
+
out = torch.empty_like(x)
|
| 98 |
+
out[..., 0::2] = x_even * cos - x_odd * sin
|
| 99 |
+
out[..., 1::2] = x_odd * cos + x_even * sin
|
| 100 |
+
return out
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _select_flex_backend(device: torch.device) -> str:
|
| 104 |
+
if device.type != "cuda":
|
| 105 |
+
raise RuntimeError("RecGPT attention requires a CUDA/ROCm accelerator.")
|
| 106 |
+
if torch.version.hip is None:
|
| 107 |
+
major, _ = torch.cuda.get_device_capability(device)
|
| 108 |
+
if major >= 9:
|
| 109 |
+
return "FLASH"
|
| 110 |
+
return "TRITON"
|
| 111 |
+
|
| 112 |
+
ROPE_THETA = 10000.0
|
| 113 |
+
|
| 114 |
+
class SelfAttention(nn.Module):
|
| 115 |
+
def __init__(self, config: RecGPTConfig):
|
| 116 |
+
super().__init__()
|
| 117 |
+
self.config = config
|
| 118 |
+
self.num_heads = config.num_heads
|
| 119 |
+
self.head_dim = config.head_dim
|
| 120 |
+
|
| 121 |
+
# One fused projection for QKV.
|
| 122 |
+
self.qkv = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=False)
|
| 123 |
+
self.out = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 124 |
+
# Zero init (Idea from modded-nanogpt speedrun, empirically seems to work well).
|
| 125 |
+
nn.init.zeros_(self.out.weight)
|
| 126 |
+
self.rope = RotaryEmbedding(self.head_dim, config.max_position_embeddings, ROPE_THETA)
|
| 127 |
+
|
| 128 |
+
# Gated Attention (https://arxiv.org/pdf/2505.06708)
|
| 129 |
+
# SDPAHeadwiseGate: per-head sigmoid gate applied to attention output.
|
| 130 |
+
# Empirically, attention gating should benefit us since we don't use any <|BOS|> token during training,
|
| 131 |
+
# meaning the model has no attention sinks. GA should reduce the need for attention sinks.
|
| 132 |
+
self.gate = nn.Linear(config.hidden_size, self.num_heads, bias=True)
|
| 133 |
+
nn.init.zeros_(self.gate.weight)
|
| 134 |
+
|
| 135 |
+
# Since the gated attention paper finds that the model converges toward a more sparse gate,
|
| 136 |
+
# we initialize the gate bias with 0.0 (so the sigmoid of the bias is 0.5).
|
| 137 |
+
# 0.5 is right in the middle, not too high to start with default behavior, not too low to enforce sparsity early on.
|
| 138 |
+
# TODO: Rewrite this comment more clearly
|
| 139 |
+
# TODO: Re-consider if bias is even necessary
|
| 140 |
+
nn.init.constant_(self.gate.bias, 0.0)
|
| 141 |
+
|
| 142 |
+
def forward(
|
| 143 |
+
self,
|
| 144 |
+
x: torch.Tensor,
|
| 145 |
+
position_ids: torch.Tensor,
|
| 146 |
+
block_mask,
|
| 147 |
+
backend: str,
|
| 148 |
+
) -> torch.Tensor:
|
| 149 |
+
from torch.nn.attention.flex_attention import flex_attention
|
| 150 |
+
|
| 151 |
+
batch_size, seq_len, hidden_size = x.shape
|
| 152 |
+
# Project to QKV and reshape to [B, T, 3, H, D].
|
| 153 |
+
qkv = self.qkv(x).view(batch_size, seq_len, 3, self.num_heads, self.head_dim)
|
| 154 |
+
q, k, v = qkv.unbind(dim=2)
|
| 155 |
+
|
| 156 |
+
# Unparameterized QK norm. We used parameterized QK norms in the old repo,
|
| 157 |
+
# but this lean version keeps them fixed for now.
|
| 158 |
+
q = F.rms_norm(q, (self.head_dim,))
|
| 159 |
+
k = F.rms_norm(k, (self.head_dim,))
|
| 160 |
+
|
| 161 |
+
# Pick cos/sin for each token position, then broadcast over heads.
|
| 162 |
+
q = self.rope(q, position_ids).transpose(1, 2)
|
| 163 |
+
k = self.rope(k, position_ids).transpose(1, 2)
|
| 164 |
+
v = v.transpose(1, 2)
|
| 165 |
+
|
| 166 |
+
y = flex_attention(q, k, v, block_mask=block_mask, kernel_options={"BACKEND": backend})
|
| 167 |
+
gate = torch.sigmoid(self.gate(x)).view(batch_size, seq_len, self.num_heads, 1)
|
| 168 |
+
y = y.transpose(1, 2) * gate
|
| 169 |
+
y = y.contiguous().view(batch_size, seq_len, hidden_size)
|
| 170 |
+
return self.out(y)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class MLP(nn.Module):
|
| 174 |
+
def __init__(self, config: RecGPTConfig):
|
| 175 |
+
super().__init__()
|
| 176 |
+
self.up = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 177 |
+
self.down = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 178 |
+
# Standard dense ReLU^2 MLP with zero init output
|
| 179 |
+
# (Idea from modded-nanogpt speedrun, empirically seems to work well).
|
| 180 |
+
nn.init.zeros_(self.down.weight)
|
| 181 |
+
|
| 182 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 183 |
+
return self.down(F.relu(self.up(x)).square())
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class RecGPTForCausalLM(PreTrainedModel):
|
| 187 |
+
config_class = RecGPTConfig
|
| 188 |
+
base_model_prefix = "model"
|
| 189 |
+
|
| 190 |
+
def __init__(self, config: RecGPTConfig):
|
| 191 |
+
super().__init__(config)
|
| 192 |
+
self.use_factorized = config.embedding_size != config.hidden_size
|
| 193 |
+
|
| 194 |
+
# Factorized Embeddings (https://arxiv.org/pdf/1909.11942)
|
| 195 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
|
| 196 |
+
if self.use_factorized:
|
| 197 |
+
self.e_to_h = nn.Linear(config.embedding_size, config.hidden_size, bias=False)
|
| 198 |
+
self.h_to_e = nn.Linear(config.hidden_size, config.embedding_size, bias=False)
|
| 199 |
+
if not config.tie_word_embeddings:
|
| 200 |
+
self.lm_head = nn.Linear(config.embedding_size, config.vocab_size, bias=False)
|
| 201 |
+
|
| 202 |
+
# This is the main recursive model idea: attention and MLP weights are
|
| 203 |
+
# reused at every depth. The norms are depth-specific.
|
| 204 |
+
self.attn = SelfAttention(config)
|
| 205 |
+
self.mlp = MLP(config)
|
| 206 |
+
self.attn_norms = nn.ModuleList([RMSNorm(config.hidden_size, use_bias=True) for _ in range(config.recursive_depth)])
|
| 207 |
+
self.mlp_norms = nn.ModuleList([RMSNorm(config.hidden_size, use_bias=True) for _ in range(config.recursive_depth)])
|
| 208 |
+
self.final_norm = RMSNorm(config.hidden_size)
|
| 209 |
+
|
| 210 |
+
self.post_init()
|
| 211 |
+
if config.tie_word_embeddings:
|
| 212 |
+
self.tie_weights()
|
| 213 |
+
|
| 214 |
+
def _init_weights(self, module: nn.Module):
|
| 215 |
+
if isinstance(module, RotaryEmbedding):
|
| 216 |
+
module.reset_parameters()
|
| 217 |
+
|
| 218 |
+
def get_input_embeddings(self):
|
| 219 |
+
return self.embed_tokens
|
| 220 |
+
|
| 221 |
+
def set_input_embeddings(self, value):
|
| 222 |
+
self.embed_tokens = value
|
| 223 |
+
|
| 224 |
+
def get_output_embeddings(self):
|
| 225 |
+
return getattr(self, "lm_head", None)
|
| 226 |
+
|
| 227 |
+
def set_output_embeddings(self, value):
|
| 228 |
+
self.lm_head = value
|
| 229 |
+
|
| 230 |
+
def forward( # Everything expected in shape [batch, seq_len]
|
| 231 |
+
self,
|
| 232 |
+
input_ids: torch.Tensor,
|
| 233 |
+
segment_ids: Optional[torch.Tensor] = None, # We use segment_ids for our packed training
|
| 234 |
+
attention_mask: Optional[torch.Tensor] = None, # But we also support attention_mask for compatibility with HF transformers stack.
|
| 235 |
+
labels: Optional[torch.Tensor] = None,
|
| 236 |
+
return_dict: Optional[bool] = None,
|
| 237 |
+
output_hidden_states: Optional[bool] = None,
|
| 238 |
+
return_hidden_and_embed: Optional[bool] = None,
|
| 239 |
+
**kwargs,
|
| 240 |
+
) -> CausalLMOutput | tuple[torch.Tensor, ...]:
|
| 241 |
+
# Training uses one packed, block-masked sequence per microbatch, so B is always 1.
|
| 242 |
+
# We keep the batch dimension because HF expects it.
|
| 243 |
+
if input_ids.dim() != 2:
|
| 244 |
+
raise ValueError("input_ids must have shape [batch, seq_len].")
|
| 245 |
+
if segment_ids is not None and segment_ids.shape != input_ids.shape:
|
| 246 |
+
raise ValueError("segment_ids must match input_ids shape.")
|
| 247 |
+
if attention_mask is not None and segment_ids is None: # Compatibility with HF transformers stack. Ignored if segment_ids are provided.
|
| 248 |
+
if attention_mask.shape != input_ids.shape:
|
| 249 |
+
raise ValueError("attention_mask must match input_ids shape when segment_ids is not provided.")
|
| 250 |
+
# Assumes standard binary attention mask where 1 indicates a real token and 0 indicates padding.
|
| 251 |
+
# Converts to segment_ids where padding is -1 and real tokens are >= 0.
|
| 252 |
+
assert ((attention_mask == 0) | (attention_mask == 1)).all()
|
| 253 |
+
segment_ids = attention_mask.to(device=input_ids.device, dtype=torch.long) - 1
|
| 254 |
+
if segment_ids is None:
|
| 255 |
+
segment_ids = torch.zeros_like(input_ids)
|
| 256 |
+
|
| 257 |
+
assert segment_ids.device == input_ids.device # If segment_ids are passed explicitly, they should be on the same device.
|
| 258 |
+
|
| 259 |
+
# Construct position_ids from segment_ids
|
| 260 |
+
valid = segment_ids >= 0
|
| 261 |
+
seq_positions = torch.arange(input_ids.size(1), device=input_ids.device, dtype=torch.long).unsqueeze(0)
|
| 262 |
+
|
| 263 |
+
# This marks where a valid segment starts. A token is a segment start if:
|
| 264 |
+
# - It's valid
|
| 265 |
+
# - Either it is the first token, or its segment_id differs from the previous token.
|
| 266 |
+
segment_starts = valid & torch.cat(
|
| 267 |
+
[
|
| 268 |
+
torch.ones(segment_ids.size(0), 1, device=input_ids.device, dtype=torch.bool), # First token
|
| 269 |
+
segment_ids[:, 1:] != segment_ids[:, :-1], # Segment ID changes
|
| 270 |
+
],
|
| 271 |
+
dim=1,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
# Put each segment start's absolute index at the start token, then cummax fills the latest start index across that segment.
|
| 275 |
+
# Subtracting it from the absolute token index gives local positions per segment.
|
| 276 |
+
segment_start_positions = torch.where(segment_starts, seq_positions, 0).cummax(dim=-1).values
|
| 277 |
+
position_ids = (seq_positions - segment_start_positions).masked_fill(~valid, 0)
|
| 278 |
+
|
| 279 |
+
from torch.nn.attention.flex_attention import create_block_mask
|
| 280 |
+
|
| 281 |
+
batch_size, seq_len = input_ids.shape
|
| 282 |
+
|
| 283 |
+
def mask_mod(b, h, q_idx, kv_idx):
|
| 284 |
+
"""
|
| 285 |
+
FlexAttention calls mask_mod with scalar/block index tensors and uses the
|
| 286 |
+
result to build a block-sparse attention mask. This is the only place where
|
| 287 |
+
document boundaries are enforced.
|
| 288 |
+
|
| 289 |
+
segment_ids[b, t] >= 0 means a real token. segment_ids[b, t] == -1 means
|
| 290 |
+
padding. Tokens can only attend causally within the same segment, so packed
|
| 291 |
+
documents in the same row still have hard attention boundaries.
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
valid = segment_ids[b, q_idx] >= 0
|
| 295 |
+
same_segment = segment_ids[b, q_idx] == segment_ids[b, kv_idx]
|
| 296 |
+
causal = kv_idx <= q_idx
|
| 297 |
+
return valid & same_segment & causal
|
| 298 |
+
|
| 299 |
+
# BlockMask is built once per forward and reused at every recursive depth.
|
| 300 |
+
block_mask = create_block_mask(
|
| 301 |
+
mask_mod,
|
| 302 |
+
B=batch_size,
|
| 303 |
+
H=self.config.num_heads,
|
| 304 |
+
Q_LEN=seq_len,
|
| 305 |
+
KV_LEN=seq_len,
|
| 306 |
+
device=input_ids.device,
|
| 307 |
+
)
|
| 308 |
+
backend = _select_flex_backend(input_ids.device)
|
| 309 |
+
|
| 310 |
+
x = self.embed_tokens(input_ids)
|
| 311 |
+
if self.use_factorized:
|
| 312 |
+
x = self.e_to_h(x)
|
| 313 |
+
if return_hidden_and_embed:
|
| 314 |
+
e = x
|
| 315 |
+
for attn_norm, mlp_norm in zip(self.attn_norms, self.mlp_norms):
|
| 316 |
+
# We do pre-norm and QK norm.
|
| 317 |
+
# We used to do a Gemma 3 style post-norm, but removed it to improve stability
|
| 318 |
+
# and keep the residual stream norm in check. Seems to work fine.
|
| 319 |
+
# Update: Tried KEEL norm paper with residual scaling, it hurt performance.
|
| 320 |
+
x = x + self.attn(attn_norm(x), position_ids, block_mask, backend)
|
| 321 |
+
x = x + self.mlp(mlp_norm(x))
|
| 322 |
+
|
| 323 |
+
x = self.final_norm(x) # Final normalized hidden state before output projection.
|
| 324 |
+
if self.use_factorized:
|
| 325 |
+
y = self.h_to_e(x)
|
| 326 |
+
else:
|
| 327 |
+
y = x
|
| 328 |
+
if hasattr(self, "lm_head"):
|
| 329 |
+
logits = self.lm_head(y)
|
| 330 |
+
else:
|
| 331 |
+
logits = F.linear(y, self.embed_tokens.weight)
|
| 332 |
+
|
| 333 |
+
loss = None
|
| 334 |
+
if labels is not None:
|
| 335 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1), ignore_index=-100)
|
| 336 |
+
|
| 337 |
+
use_return_dict = self.config.use_return_dict if return_dict is None else return_dict
|
| 338 |
+
output_hidden_states = self.config.output_hidden_states if output_hidden_states is None else output_hidden_states
|
| 339 |
+
if use_return_dict:
|
| 340 |
+
return CausalLMOutput(loss=loss, logits=logits, hidden_states=(x,) if output_hidden_states else None)
|
| 341 |
+
if loss is None:
|
| 342 |
+
return (logits,) # [batch, seq_len, vocab_size]
|
| 343 |
+
if return_hidden_and_embed:
|
| 344 |
+
return (loss, logits, x, e) # logits: [batch, seq_len, vocab_size], x: [batch, seq_len, hidden_size], e: [batch, seq_len, hidden_size]
|
| 345 |
+
return (loss, logits)
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"is_local": true,
|
| 4 |
+
"local_files_only": false,
|
| 5 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 6 |
+
"pad_token": "<pad>",
|
| 7 |
+
"tokenizer_class": "TokenizersBackend"
|
| 8 |
+
}
|
train_config.json
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"dataset": "s33c67-10m.parquet",
|
| 3 |
+
"tokenizer": "s33c67-10m-bpe",
|
| 4 |
+
"run_name": "recgpt-10m-submission",
|
| 5 |
+
"seed": 0,
|
| 6 |
+
"data_seed": 0,
|
| 7 |
+
"microbatch_tok": 32768,
|
| 8 |
+
"total_batch_tok": 32768,
|
| 9 |
+
"sequence_len": 256,
|
| 10 |
+
"epochs": 10,
|
| 11 |
+
"checkpoint_track": "strict-small",
|
| 12 |
+
"max_tokens": -1,
|
| 13 |
+
"lr_embed": 0.005,
|
| 14 |
+
"lr_block": 0.02,
|
| 15 |
+
"min_lr": 0.0,
|
| 16 |
+
"wd_adam": 0.005,
|
| 17 |
+
"wd_muon": 0.1,
|
| 18 |
+
"adam_beta1": 0.9,
|
| 19 |
+
"adam_beta2": 0.997,
|
| 20 |
+
"muon_momentum": 0.95,
|
| 21 |
+
"warmup_ratio": 0.0,
|
| 22 |
+
"cooldown_ratio": 0.2,
|
| 23 |
+
"max_grad_norm": 2.0,
|
| 24 |
+
"nl_mult": 0.01,
|
| 25 |
+
"nl_depth": 2,
|
| 26 |
+
"nl_hidden": -1,
|
| 27 |
+
"nl_intermediate": 5120,
|
| 28 |
+
"nl_lr": 0.004,
|
| 29 |
+
"nl_wd": 0.01,
|
| 30 |
+
"nl_momentum": 0.95,
|
| 31 |
+
"torch_compile": true,
|
| 32 |
+
"use_wandb": true,
|
| 33 |
+
"wandb_project": "bblm26-recgpt",
|
| 34 |
+
"log_every": 10,
|
| 35 |
+
"model_config": {
|
| 36 |
+
"transformers_version": "5.9.0",
|
| 37 |
+
"architectures": [
|
| 38 |
+
"RecGPTForCausalLM"
|
| 39 |
+
],
|
| 40 |
+
"output_hidden_states": false,
|
| 41 |
+
"return_dict": true,
|
| 42 |
+
"dtype": "float32",
|
| 43 |
+
"chunk_size_feed_forward": 0,
|
| 44 |
+
"is_encoder_decoder": false,
|
| 45 |
+
"id2label": {
|
| 46 |
+
"0": "LABEL_0",
|
| 47 |
+
"1": "LABEL_1"
|
| 48 |
+
},
|
| 49 |
+
"label2id": {
|
| 50 |
+
"LABEL_0": 0,
|
| 51 |
+
"LABEL_1": 1
|
| 52 |
+
},
|
| 53 |
+
"problem_type": null,
|
| 54 |
+
"_name_or_path": "",
|
| 55 |
+
"pad_token_id": 0,
|
| 56 |
+
"tie_word_embeddings": false,
|
| 57 |
+
"vocab_size": 32768,
|
| 58 |
+
"hidden_size": 768,
|
| 59 |
+
"embedding_size": 192,
|
| 60 |
+
"head_dim": 64,
|
| 61 |
+
"num_heads": 12,
|
| 62 |
+
"intermediate_size": 12288,
|
| 63 |
+
"recursive_depth": 16,
|
| 64 |
+
"max_position_embeddings": 1024,
|
| 65 |
+
"is_decoder": true,
|
| 66 |
+
"use_cache": false,
|
| 67 |
+
"auto_map": {
|
| 68 |
+
"AutoConfig": "modeling_recgpt.RecGPTConfig",
|
| 69 |
+
"AutoModelForCausalLM": "modeling_recgpt.RecGPTForCausalLM"
|
| 70 |
+
},
|
| 71 |
+
"model_type": "recgpt",
|
| 72 |
+
"output_attentions": false
|
| 73 |
+
}
|
| 74 |
+
}
|