Text Generation
Transformers
Safetensors
English
custom_gpt
code
Mixture of Experts
mixture-of-experts
flash-attention
custom-architecture
custom_code
Run this model with HF Jobs
Run AkshithAI/project-828-gpt-base on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/AkshithAI/project-828-gpt-base. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/AkshithAI/project-828-gpt-base on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/AkshithAI/project-828-gpt-base. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/AkshithAI/project-828-gpt-base. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use AkshithAI/project-828-gpt-base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use AkshithAI/project-828-gpt-base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="AkshithAI/project-828-gpt-base", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("AkshithAI/project-828-gpt-base", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use AkshithAI/project-828-gpt-base with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "AkshithAI/project-828-gpt-base" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "AkshithAI/project-828-gpt-base", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/AkshithAI/project-828-gpt-base
- SGLang
How to use AkshithAI/project-828-gpt-base 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 "AkshithAI/project-828-gpt-base" \ --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": "AkshithAI/project-828-gpt-base", "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 "AkshithAI/project-828-gpt-base" \ --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": "AkshithAI/project-828-gpt-base", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use AkshithAI/project-828-gpt-base with Docker Model Runner:
docker model run hf.co/AkshithAI/project-828-gpt-base
Copy from AkshithAI/project-828-gpt
Browse filesFiles changed (10)
- README.mdAdded+140
- config.jsonAdded+35
- generation_config.jsonAdded+12
- merges.txtAdded
- model.safetensorsAdded+3
- modeling_gpt.pyAdded+724
- special_tokens_map.jsonAdded+64
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+358
- vocab.jsonAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140---language: enlibrary_name: transformerslicense: apache-2.0model_name: project-828-gptpipeline_tag: text-generationtags:- code- moe- mixture-of-experts- flash-attention- custom-architecture---
# project-828-gpt
A **398.7M parameter Mixture-of-Experts (MoE)** causal language model optimized for code generation and technical reasoning, pretrained on ~60B tokens.
> **398.7M total parameters, ~286M active per token** — 4 routed experts + 1 shared expert with top-2 routing per token.
## Model Architecture
| Property | Value ||:---|:---|| **Architecture** | Decoder-only Transformer with MoE FFN layers || **Total Parameters** | **398.7M** || **Active Parameters / Token** | **~286M** || **Hidden Dimension ($d_{\text{model}}$)** | 768 || **Intermediate Size ($d_{\text{ff}}$)** | 760 || **Hidden Layers** | 24 || **Attention Heads / KV Heads** | 12 / 6 (GQA 2:1) || **Head Dimension** | 64 || **Routed Experts** | 4 || **Active Experts / Token** | 2 (Top-2) || **Shared Experts** | 1 || **Context Length** | 2048 (extensible to 8192 via YaRN) || **Vocabulary Size** | 49152 || **Precision** | BFloat16 Mixed Precision || **Positional Encoding** | RoPE with YaRN scaling support |
### Parameter Breakdown
| Component | Parameters ||:---|---:|| Embeddings | ~37.7M || Unembedding | ~37.8M || Attention (×24 layers) | ~1.8M each || MoE FFN (×24 layers) | ~11.7M each || Layer Norms + Misc | ~0.07M || **Total** | **398.7M** |
### Key Architectural Features
- **Grouped Query Attention (GQA)**: 12 query heads with 6 key-value heads (2:1 ratio) for memory-efficient attention- **QK-Norm**: RMSNorm applied to query and key projections before RoPE for attention stability- **Auxiliary-Loss-Free MoE Routing**: Sigmoid gating with dynamic bias adjustment ([DeepSeek-V3 paper](https://arxiv.org/abs/2408.15664)) — achieves near-perfect ~25% utilization per expert without auxiliary losses- **SwiGLU Activation with Soft-Clamping**: `limit=7.0` prevents activation explosions during long training runs- **Batched Expert Dispatch**: Sort-and-slice dispatch with `searchsorted` boundaries for contiguous memory access- **RoPE with YaRN Extension**: Base context of 2048 tokens, extensible to 8192 via YaRN scaling
## Training Details
### Phase 1 — Pretraining (~60B tokens)
| Training Config | Value ||:---|:---|| **Hardware** | H200 GPU || **Peak Learning Rate** | 3e-4 || **Min Learning Rate** | 3e-5 || **Scheduler** | WSD (Warmup-Stable-Decay) || **Warmup Steps** | 500 || **Total Steps** | 101,726 || **Effective Batch Size** | 37 × 8 = 296 sequences || **Tokens per Step** | ~0.61M || **Gradient Clipping** | 1.0 |
### Training Data Mix
| Dataset | Weight | Category ||:---|:---:|:---|| `starcoderdata` — Python | 14 | Source Code || `starcoderdata` — JavaScript | 8 | Source Code || `starcoderdata` — Java | 6 | Source Code || `starcoderdata` — TypeScript | 4 | Source Code || `starcoderdata` — C++ | 6 | Source Code || `starcoderdata` — C | 4 | Source Code || `starcoderdata` — C# | 3 | Source Code || `starcoderdata` — Go | 4 | Source Code || `starcoderdata` — Rust | 3 | Source Code || `starcoderdata` — PHP | 3 | Source Code || `fineweb-edu-dedup` | 20 | General Knowledge || `cosmopedia-v2` | 7 | General Knowledge || `wikipedia-en` | 3 | General Knowledge || `finemath-4plus` | 8 | Math / Reasoning || `stackexchange` (programming/CS) | 7 | CS / Engineering |
**Category breakdown**: Source Code 55% · General Knowledge 30% · Math/Reasoning 8% · CS/Engineering 7%
## Quickstart
```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizer
repo_id = "AkshithAI/project-828-gpt"
tokenizer = AutoTokenizer.from_pretrained(repo_id, trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained( repo_id, torch_dtype="bfloat16", device_map="auto", trust_remote_code=True)
prompt = "def binary_search(arr, target):"inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
outputs = model.generate( **inputs, max_new_tokens=200, temperature=0.7, top_p=0.9, do_sample=True, use_cache=False, eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.pad_token_id)print(tokenizer.decode(outputs[0], skip_special_tokens=True))```
## Citation
```bibtex@misc{project828, author = {AkshithAI}, title = {Project 828: MoE Transformer with Training Pipeline}, year = {2025}, publisher = {GitHub}, url = {https://github.com/AkshithAI/project_828}}```1234567891011121314151617181920212223242526272829303132333435{ "architectures": [ "GPTForCausalLM" ], "auto_map": { "AutoConfig": "modeling_gpt.GPTConfig", "AutoModelForCausalLM": "modeling_gpt.GPTForCausalLM" }, "base": 10000, "bos_token_id": 0, "dtype": "float32", "eos_token_id": 0, "ffn_dropout": 0.0, "head_dim": 64, "hidden_dim": 768, "initial_context_len": 2048, "intermediate_size": 760, "is_decoder": true, "max_context_len": 2048, "model_type": "custom_gpt", "ntk_alpha": 1.0, "ntk_beta": 32.0, "num_attn_heads": 12, "num_experts": 4, "num_experts_per_tok": 2, "num_hidden_layers": 24, "num_key_value_heads": 6, "pad_token_id": 4, "route_scale": 1.0, "scaling_factor": 1.0, "tie_word_embeddings": false, "transformers_version": "4.57.1", "update_param": 0.002, "vocab_size": 49152}123456789101112{ "bos_token_id": 0, "do_sample": true, "eos_token_id": 0, "max_new_tokens": 200, "pad_token_id": 4, "repetition_penalty": 1.15, "temperature": 0.7, "top_p": 0.9, "transformers_version": "4.57.1", "use_cache": false}123version https://git-lfs.github.com/spec/v1oid sha256:d64f69d1b9a980328658e6af1fe89d25428bcb53eb59da14dda8b9ace9b9ca25size 1594982616123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724import mathfrom typing import Tuple, Optionalimport torchimport torch.nn as nnimport torch.nn.functional as Ftry: from transformers import PretrainedConfig, PreTrainedModel, GenerationMixinexcept ImportError: from transformers.configuration_utils import PretrainedConfig from transformers.modeling_utils import PreTrainedModel from transformers.generation.utils import GenerationMixinfrom transformers.modeling_outputs import CausalLMOutputWithCrossAttentions
class GPTConfig(PretrainedConfig): model_type = "custom_gpt"
def __init__( self, vocab_size=49152, num_attn_heads=12, num_key_value_heads=6, hidden_dim=768, intermediate_size=760, ffn_dropout=0.0, num_hidden_layers=24, num_experts=4, num_experts_per_tok=2, update_param=2e-3, route_scale=1.0, base=10000, initial_context_len=2048, max_context_len=2048, ntk_alpha=1.0, ntk_beta=32.0, scaling_factor=1.0, pad_token_id=4, bos_token_id=0, eos_token_id=0, tie_word_embeddings=False, is_decoder=True, **kwargs, ): super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, is_decoder=is_decoder, **kwargs, ) self.vocab_size = vocab_size self.num_attn_heads = num_attn_heads self.num_key_value_heads = num_key_value_heads self.hidden_dim = hidden_dim self.intermediate_size = intermediate_size self.ffn_dropout = ffn_dropout self.head_dim = hidden_dim // num_attn_heads self.num_hidden_layers = num_hidden_layers self.num_experts = num_experts self.num_experts_per_tok = num_experts_per_tok self.update_param = update_param self.route_scale = route_scale self.base = base self.initial_context_len = initial_context_len self.max_context_len = max_context_len self.ntk_alpha = ntk_alpha self.ntk_beta = ntk_beta self.scaling_factor = scaling_factor self.auto_map = { "AutoConfig": "modeling_gpt.GPTConfig", "AutoModelForCausalLM": "modeling_gpt.GPTForCausalLM", }
class RMS_Norm(nn.Module): def __init__(self, num_features, eps : float = 1e-8, device : torch.device|None = None ) -> None: """ Normalizing weights along num_features using RMSNorm. Args: num_features: dim along which the weights are normalized eps : a small factor to handle divide-by-zero error config: Optional GPTConfig object """ super().__init__() self.num_features = num_features self.eps = eps self.scale = nn.Parameter(torch.ones(num_features, device=device))
def forward(self,x : torch.Tensor) -> torch.Tensor: t,dtype = x.float(),x.dtype t = t * torch.rsqrt(torch.mean(t**2,dim = -1,keepdim=True) + self.eps) return (t * self.scale).to(dtype)
def swiglu(x, alpha: float = 1.702, limit: float = 7.0): x_glu, x_linear = x.chunk(2, dim=-1) x_glu = x_glu.clamp(min=None, max=limit) x_linear = x_linear.clamp(min=-limit, max=limit) out_glu = x_glu * torch.sigmoid(alpha * x_glu) return out_glu * (x_linear + 1)
class MLPBlock(nn.Module): def __init__(self, config : GPTConfig, device : torch.device|None = None ) -> None: """ Multi-Layer Perceptron Block with SwiGLU activation. Args: config: GPTConfig object containing model hyperparameters device: torch device to place the module on """ super().__init__() self.w1 = nn.Linear( config.hidden_dim, 2 * config.intermediate_size, device = device ) self.w2 = nn.Linear( config.intermediate_size, config.hidden_dim, device = device ) self.w3 = nn.Linear( config.hidden_dim, config.intermediate_size, device = device ) self.dropout = nn.Dropout(config.ffn_dropout) def forward(self,x : torch.Tensor) -> torch.Tensor: return self.w2(self.dropout(swiglu(self.w1(x)) * self.w3(x)))
class Expert(nn.Module): def __init__(self, config : GPTConfig, device : torch.device|None = None ) -> None: """ A Multi-Layer Perceptron Block for Experts in MoE. Args: config: GPTConfig object containing model hyperparameters device: torch device to place the module on """ super().__init__() self.w1 = nn.Linear( config.hidden_dim, 2 * config.intermediate_size, device = device ) self.w2 = nn.Linear( config.intermediate_size, config.hidden_dim, device = device ) self.w3 = nn.Linear( config.hidden_dim, config.intermediate_size, device = device ) self.dropout = nn.Dropout(config.ffn_dropout) def forward(self,x : torch.Tensor) -> torch.Tensor: return self.w2(self.dropout(swiglu(self.w1(x)) * self.w3(x)))
class Gate(nn.Module): def __init__(self, config : GPTConfig, device : torch.device|None = None, layer_idx : int = 0, ) -> None: """ - Router/Gate module for Mixture of Experts. - Loss-Free Balancing, featured by an auxiliary-loss-free load balancing strategy - Per-layer update scaling: deeper layers get more aggressive bias updates (1.0× at layer 0, up to 1.5× at the deepest layer) to counteract deep-layer expert polarization.
Args: config: GPTConfig object containing model hyperparameters device: torch device to place the module on layer_idx: index of this layer (0-indexed), used for per-layer scaling """ super().__init__() self.dim = config.hidden_dim self.topk = config.num_experts_per_tok self.route_scale = config.route_scale self.num_experts = config.num_experts self.router = nn.Linear(config.hidden_dim, config.num_experts, bias = False, device = device) self.register_buffer("bias", torch.zeros(config.num_experts, device=device))
num_layers = config.num_hidden_layers layer_scale = 1.0 + 0.5 * (layer_idx / max(num_layers - 1, 1)) self.effective_update = config.update_param * layer_scale
def update_bias(self, current_load: torch.Tensor) -> None: """Update bias in-place using Loss-Free Balancing rule.""" load_float = current_load.float() e = torch.sign(load_float.mean() - load_float) self.bias.add_(self.effective_update * e) self.bias.clamp_(-10.0, 10.0) def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """See this paper for implementation details: https://arxiv.org/abs/2408.15664""" scores = self.router(x) scores = torch.sigmoid(scores) biased_scores = scores + self.bias.detach().to(scores.dtype) indices = torch.topk(biased_scores, self.topk, dim=-1)[1] current_load = torch.bincount(indices.flatten(), minlength=self.num_experts) weights = scores.gather(1, indices) weights = (weights / weights.sum(dim=-1, keepdim=True)) * self.route_scale
# Bias term update rule if self.training: with torch.no_grad(): self.update_bias(current_load)
return weights.type_as(x), indices, current_load
class MoE(nn.Module): def __init__(self, config : GPTConfig, device : torch.device|None = None, layer_idx : int = 0, ) -> None: """ Mixture of Experts module with shared experts. Args: config: GPTConfig object containing model hyperparameters device: torch device to place the module on layer_idx: index of this layer (0-indexed), passed to Gate for per-layer scaling """ super().__init__() self.dim = config.hidden_dim self.gate = Gate(config, device, layer_idx=layer_idx) self.n_routed_experts = config.num_experts_per_tok self.num_experts = config.num_experts self.experts = nn.ModuleList( [Expert(config,device) for _ in range(config.num_experts)] ) self.shared_experts = MLPBlock(config,device) self.register_buffer( 'expert_counts', torch.zeros(config.num_experts, dtype=torch.long, device = device) ) self.total_tokens = 0
def reset_expert_counts(self): """Reset counters (call periodically during training)""" self.expert_counts.zero_() self.total_tokens = 0 def forward(self, x: torch.Tensor) -> torch.Tensor: inp_shape = x.shape x = x.view(-1, self.dim) xprt_weights, xprt_idxs, counts = self.gate(x)
self.expert_counts += counts self.total_tokens += x.shape[0] * self.n_routed_experts
# ── Batched expert dispatch: sort tokens by expert ID ── # Flatten top-k indices: each token appears k times flat_idx = xprt_idxs.view(-1) # (N*k,) flat_weights = xprt_weights.view(-1, 1) # (N*k, 1) token_idx = torch.arange(x.shape[0], device=x.device) token_idx = token_idx.unsqueeze(1).expand_as(xprt_idxs).reshape(-1) # (N*k,)
# Sort by expert ID for contiguous memory access sort_order = flat_idx.argsort(stable=True) sorted_expert_ids = flat_idx[sort_order] sorted_token_idx = token_idx[sort_order] sorted_weights = flat_weights[sort_order]
# Gather tokens in expert-sorted order (single contiguous gather) sorted_x = x[sorted_token_idx] # (N*k, dim)
# Find boundaries between experts via searchsorted expert_boundaries = torch.searchsorted( sorted_expert_ids.contiguous(), torch.arange(self.num_experts + 1, device=x.device), )
# Run each expert on its contiguous slice sorted_out = torch.zeros_like(sorted_x) for i, expert in enumerate(self.experts): start, end = expert_boundaries[i].item(), expert_boundaries[i + 1].item() if start < end: sorted_out[start:end] = expert(sorted_x[start:end])
# Weighted scatter-add back to original token positions sorted_out = sorted_out * sorted_weights routed_xprt_out = torch.zeros_like(x) routed_xprt_out.scatter_add_( 0, sorted_token_idx.unsqueeze(1).expand_as(sorted_out), sorted_out, )
mlp_out = routed_xprt_out + self.shared_experts(x) return mlp_out.reshape(inp_shape)
def apply_rope(x : torch.Tensor, cos : torch.Tensor, sin : torch.Tensor ) -> torch.Tensor: if cos.dim() == 2: # (seq_len, head_dim//2) -> (1, seq_len, 1, head_dim//2) cos = cos.unsqueeze(0).unsqueeze(-2) sin = sin.unsqueeze(0).unsqueeze(-2) else: # (batch, seq_len, head_dim//2) -> (batch, seq_len, 1, head_dim//2) cos = cos.unsqueeze(-2) sin = sin.unsqueeze(-2) cos = cos.to(x.device).to(x.dtype) sin = sin.to(x.device).to(x.dtype) x1,x2 = torch.chunk(x,2,dim = -1) o1 = x1 * cos - x2 * sin o2 = x1 * sin + x2 * cos return torch.cat([o1,o2],dim = -1)
class RotaryEmbedding(nn.Module): def __init__(self, head_dim : int, base : int, initial_context_len : int = 2048, max_context_len : int = 2048, ntk_alpha : float = 1.0, ntk_beta : float = 32.0, scaling_factor : float = 1.0, device: torch.device | None = None ) -> None: """ Rotary Position Embedding with YaRN scaling support. Args: head_dim: dimension of each attention head base: base frequency for rotary embeddings dtype: data type for computations initial_context_len: original context length for YaRN scaling max_context_len: maximum context length to precompute ntk_alpha: NTK-aware scaling alpha parameter ntk_beta: NTK-aware scaling beta parameter scaling_factor: context length scaling factor device: torch device to place the module on """ super().__init__() self.head_dim = head_dim self.base = base self.initial_context_len = initial_context_len self.ntk_alpha = ntk_alpha self.ntk_beta = ntk_beta self.scaling_factor = scaling_factor self.device = device cos, sin = self.compute_cos_sin(max_context_len) self.register_buffer('cos', cos, persistent=False) self.register_buffer('sin', sin, persistent=False)
def _compute_concentration_and_inv_freq(self) -> Tuple[float,torch.Tensor]: """Refer gpt-oss implemention of YaRN and See YaRN paper for more details: https://arxiv.org/abs/2309.00071""" freq = self.base ** ( torch.arange(0, self.head_dim, 2, dtype=torch.float, device=self.device) / self.head_dim ) if self.scaling_factor > 1.0: concentration = ( 0.1 * math.log(self.scaling_factor) + 1.0 ) # YaRN concentration
d_half = self.head_dim / 2 # NTK by parts low = ( d_half * math.log(self.initial_context_len / (self.ntk_beta * 2 * math.pi)) / math.log(self.base) ) high = ( d_half * math.log(self.initial_context_len / (self.ntk_alpha * 2 * math.pi)) / math.log(self.base) ) assert 0 < low < high < d_half - 1
interpolation = 1.0 / (self.scaling_factor * freq) extrapolation = 1.0 / freq
ramp = ( torch.arange(d_half, device=freq.device) - low ) / (high - low) mask = 1 - ramp.clamp(0, 1)
inv_freq = interpolation * (1 - mask) + extrapolation * mask else: concentration = 1.0 inv_freq = 1.0 / freq
return concentration, inv_freq
def compute_cos_sin(self,num_tokens : int) -> Tuple[torch.Tensor,torch.Tensor]: concentration , inv_freq = self._compute_concentration_and_inv_freq() pos = torch.arange(num_tokens ,device = self.device) freqs = torch.einsum('i,j->ij',pos,inv_freq) cos = freqs.cos() * concentration sin = freqs.sin() * concentration return cos,sin
def forward(self, q : torch.Tensor, k : torch.Tensor, offset : int = 0, position_ids : torch.Tensor | None = None, ) -> Tuple[torch.Tensor,torch.Tensor]: batch_size,seq_len,_,_ = q.shape if position_ids is not None: cos = self.cos[position_ids] sin = self.sin[position_ids] else: cos = self.cos[offset:offset+seq_len,:] sin = self.sin[offset:offset+seq_len,:]
query_shape = q.shape q = q.view(batch_size,seq_len,-1,self.head_dim) q = apply_rope(q,cos,sin) q = q.reshape(query_shape)
key_shape = k.shape k = k.view(batch_size,seq_len,-1,self.head_dim) k = apply_rope(k,cos,sin) k = k.reshape(key_shape)
return q,k
class Attention(nn.Module): def __init__(self, config : GPTConfig, device : torch.device | None = None, inference : bool = False, ) -> None: """ Multi-Head Attention with Grouped Query Attention and Flash Attention. Supports Gemma-2 style logit soft-capping for attention stability. Args: config: GPTConfig object containing model hyperparameters device: torch device to place the module on inference: whether to enable KV caching for inference """ super().__init__() self.n_heads = config.num_attn_heads self.n_kv_heads = config.num_key_value_heads self.head_dim = config.head_dim self.inference = inference self.max_cache_len = config.max_context_len self.wq = nn.Linear( config.hidden_dim, config.num_attn_heads * config.head_dim, device = device ) self.wk = nn.Linear( config.hidden_dim,config.num_key_value_heads * config.head_dim , device = device ) self.wv = nn.Linear( config.hidden_dim,config.num_key_value_heads * config.head_dim , device = device ) self.wo = nn.Linear( config.num_attn_heads * config.head_dim, config.hidden_dim, device = device ) if self.inference: self.register_buffer("cache_k", None, persistent=False) self.register_buffer("cache_v", None, persistent=False) self.q_norm = RMS_Norm(config.head_dim, device = device) self.k_norm = RMS_Norm(config.head_dim, device = device) self.rope = RotaryEmbedding( config.head_dim, config.base, initial_context_len = config.initial_context_len, max_context_len = config.max_context_len, ntk_alpha = config.ntk_alpha, ntk_beta = config.ntk_beta, scaling_factor = config.scaling_factor, device = device ) def reset_cache(self, batch_size: int = 1) -> None: """Allocate (or reallocate) KV cache for the given batch size.""" if self.inference: device = self.wq.weight.device dtype = self.wq.weight.dtype self.cache_k = torch.zeros( batch_size, self.n_kv_heads, self.max_cache_len, self.head_dim, device=device, dtype=dtype, ) self.cache_v = torch.zeros( batch_size, self.n_kv_heads, self.max_cache_len, self.head_dim, device=device, dtype=dtype, )
def forward(self, x : torch.Tensor, start_pos : int = 0, position_ids : torch.Tensor | None = None, attn_mask : torch.Tensor | None = None, ) -> torch.Tensor: batch_size,seq_len,_ = x.shape end_pos = start_pos + seq_len
if self.inference: if self.cache_k is None or self.cache_k.shape[0] != batch_size: self.reset_cache(batch_size) Q,K,V = self.wq(x),self.wk(x),self.wv(x) Q = Q.view(batch_size,seq_len,self.n_heads,self.head_dim) K = K.view(batch_size,seq_len,self.n_kv_heads,self.head_dim) V = V.view(batch_size,seq_len,self.n_kv_heads,self.head_dim) Q,K = self.q_norm(Q),self.k_norm(K) Q,K = self.rope(Q,K,offset = start_pos,position_ids = position_ids)
if self.inference: # Write: transpose small new tokens (B,S,Hkv,D) → (B,Hkv,S,D) self.cache_k[:, :, start_pos:end_pos, :] = K.transpose(1, 2) self.cache_v[:, :, start_pos:end_pos, :] = V.transpose(1, 2) # Read: already in (B, Hkv, end_pos, D) — SDPA format, no transpose K = self.cache_k[:, :, :end_pos, :] V = self.cache_v[:, :, :end_pos, :]
Q = Q.transpose(1, 2) # (B, H, S, D)
is_causal = (seq_len > 1 and attn_mask is None)
attn_out = F.scaled_dot_product_attention( Q, K, V, attn_mask=attn_mask, is_causal=is_causal, enable_gqa=(self.n_heads != self.n_kv_heads), )
attn_out = attn_out.transpose(1, 2) else: Q = Q.transpose(1, 2) K = K.transpose(1, 2) V = V.transpose(1, 2) is_causal = attn_mask is None attn_out = F.scaled_dot_product_attention( Q, K, V, attn_mask=attn_mask, is_causal=is_causal, enable_gqa=(self.n_heads != self.n_kv_heads), ) attn_out = attn_out.transpose(1, 2) attn_out = attn_out.reshape(batch_size,seq_len,-1) attn_out = self.wo(attn_out)
return attn_out class TransformerDecoderBLK(nn.Module): def __init__(self, config : GPTConfig, device : torch.device | None = None, inference : bool = False, layer_idx : int = 0, ) -> None: """ Transformer Decoder Block with pre-normalization. Args: config: GPTConfig object containing model hyperparameters device: torch device to place the module on inference: whether to enable KV caching for inference layer_idx: index of this layer (0-indexed), passed to MoE for per-layer scaling """ super().__init__() self.norm1 = RMS_Norm(config.hidden_dim,device = device) self.norm2 = RMS_Norm(config.hidden_dim,device = device) self.attention = Attention(config,device,inference) self.mlp = MoE(config, device, layer_idx=layer_idx)
def forward(self,x,start_pos : int = 0,position_ids = None,attn_mask = None): x = x + self.attention(self.norm1(x),start_pos,position_ids,attn_mask) x = x + self.mlp(self.norm2(x)) return x class GPT_FLASH(nn.Module): def __init__(self, config : GPTConfig, device : torch.device | None = None, inference : bool = False, ) -> None: """ GPT model with Flash Attention and Mixture of Experts. Args: config: GPTConfig object containing model hyperparameters device: torch device to place the module on inference: whether to enable KV caching for inference """ super().__init__() self.inference = inference self.norm = RMS_Norm(config.hidden_dim,device = device) self.embeddings = nn.Embedding( config.vocab_size, config.hidden_dim, device=device ) self.layers = nn.ModuleList( [TransformerDecoderBLK(config, device, inference, layer_idx=i) for i in range(config.num_hidden_layers)] ) self.unembedding = nn.Linear(config.hidden_dim,config.vocab_size,device = device)
def reset_cache(self, batch_size: int = 1) -> None: """Reset KV caches across all layers. Call before each new generation.""" if self.inference: for layer in self.layers: layer.attention.reset_cache(batch_size)
def forward(self, x : torch.Tensor, start_pos : int = 0, position_ids : torch.Tensor | None = None, attn_mask : torch.Tensor | None = None, ) -> torch.Tensor: x = self.embeddings(x) for layer in self.layers: x = layer(x,start_pos,position_ids,attn_mask) x = self.norm(x) x = self.unembedding(x) return x
def _prepare_mask(attention_mask, input_ids): if attention_mask is None: return None if attention_mask.dim() == 2: if attention_mask.all(): return None batch_size, seq_len = input_ids.shape causal = torch.tril(torch.ones(seq_len, seq_len, dtype=torch.bool, device=input_ids.device)) key_mask = attention_mask.bool().unsqueeze(1).unsqueeze(2) return causal.unsqueeze(0).unsqueeze(0) & key_mask if attention_mask.dtype in (torch.int64, torch.int32): return attention_mask.bool() return attention_mask
class GPTForCausalLM(PreTrainedModel, GenerationMixin): config_class = GPTConfig main_input_name = "input_ids" _supports_cache_class = False
@classmethod def _supports_default_dynamic_cache(cls): return False
def __init__(self, config): super().__init__(config) self.model = GPT_FLASH(config) ignore_idx = config.pad_token_id if config.pad_token_id is not None else -100 self.criterion = nn.CrossEntropyLoss(ignore_index=ignore_idx) self.post_init()
def _init_weights(self, module): pass
def tie_weights(self, **kwargs): return {}
def get_input_embeddings(self): return self.model.embeddings
def set_input_embeddings(self, value): self.model.embeddings = value
def get_output_embeddings(self): return self.model.unembedding
def set_output_embeddings(self, value): self.model.unembedding = value
def prepare_inputs_for_generation(self, input_ids, **kwargs): kwargs.pop("past_key_values", None) kwargs.pop("cache_position", None) return { "input_ids": input_ids, "attention_mask": kwargs.get("attention_mask", None), }
def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs): if not getattr(self, '_rope_ready', False): self._init_rope(input_ids.device) mask = _prepare_mask(attention_mask, input_ids) logits = self.model(input_ids, attn_mask=mask) loss = None if labels is not None: shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() loss = self.criterion( shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1), ) return CausalLMOutputWithCrossAttentions(loss=loss, logits=logits)
def _init_rope(self, device): # Recompute RoPE cos/sin buffers on the correct device. # Non-persistent buffers are not in safetensors and may be empty # after loading with device_map (accelerate creates meta tensors during init). for layer in self.model.layers: rope = layer.attention.rope rope.device = device cos, sin = rope.compute_cos_sin(rope.cos.shape[0]) rope.cos = cos.to(device) rope.sin = sin.to(device) self._rope_ready = True12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364{ "additional_special_tokens": [ "<|endoftext|>", "<fim_prefix>", "<fim_middle>", "<fim_suffix>", "<fim_pad>", "<repo_name>", "<file_sep>", "<issue_start>", "<issue_comment>", "<issue_closed>", "<jupyter_start>", "<jupyter_text>", "<jupyter_code>", "<jupyter_output>", "<jupyter_script>", "<empty_output>", "<code_to_intermediate>", "<intermediate_to_code>", "<pr>", "<pr_status>", "<pr_is_merged>", "<pr_base>", "<pr_file>", "<pr_base_code>", "<pr_diff>", "<pr_diff_hunk>", "<pr_comment>", "<pr_event_id>", "<pr_review>", "<pr_review_state>", "<pr_review_comment>", "<pr_in_reply_to_review_id>", "<pr_in_reply_to_comment_id>", "<pr_diff_hunk_comment_line>", "<NAME>", "<EMAIL>", "<KEY>", "<PASSWORD>" ], "bos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": "<fim_pad>", "unk_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358{ "add_prefix_space": false, "added_tokens_decoder": { "0": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "1": { "content": "<fim_prefix>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "2": { "content": "<fim_middle>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "3": { "content": "<fim_suffix>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "4": { "content": "<fim_pad>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "5": { "content": "<repo_name>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "6": { "content": "<file_sep>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "7": { "content": "<issue_start>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "8": { "content": "<issue_comment>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "9": { "content": "<issue_closed>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "10": { "content": "<jupyter_start>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "11": { "content": "<jupyter_text>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "12": { "content": "<jupyter_code>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "13": { "content": "<jupyter_output>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "14": { "content": "<jupyter_script>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "15": { "content": "<empty_output>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "16": { "content": "<code_to_intermediate>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "17": { "content": "<intermediate_to_code>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "18": { "content": "<pr>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "19": { "content": "<pr_status>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "20": { "content": "<pr_is_merged>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "21": { "content": "<pr_base>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "22": { "content": "<pr_file>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "23": { "content": "<pr_base_code>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "24": { "content": "<pr_diff>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "25": { "content": "<pr_diff_hunk>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "26": { "content": "<pr_comment>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "27": { "content": "<pr_event_id>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "28": { "content": "<pr_review>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "29": { "content": "<pr_review_state>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "30": { "content": "<pr_review_comment>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "31": { "content": "<pr_in_reply_to_review_id>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32": { "content": "<pr_in_reply_to_comment_id>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "33": { "content": "<pr_diff_hunk_comment_line>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "34": { "content": "<NAME>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "35": { "content": "<EMAIL>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "36": { "content": "<KEY>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "37": { "content": "<PASSWORD>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [ "<|endoftext|>", "<fim_prefix>", "<fim_middle>", "<fim_suffix>", "<fim_pad>", "<repo_name>", "<file_sep>", "<issue_start>", "<issue_comment>", "<issue_closed>", "<jupyter_start>", "<jupyter_text>", "<jupyter_code>", "<jupyter_output>", "<jupyter_script>", "<empty_output>", "<code_to_intermediate>", "<intermediate_to_code>", "<pr>", "<pr_status>", "<pr_is_merged>", "<pr_base>", "<pr_file>", "<pr_base_code>", "<pr_diff>", "<pr_diff_hunk>", "<pr_comment>", "<pr_event_id>", "<pr_review>", "<pr_review_state>", "<pr_review_comment>", "<pr_in_reply_to_review_id>", "<pr_in_reply_to_comment_id>", "<pr_diff_hunk_comment_line>", "<NAME>", "<EMAIL>", "<KEY>", "<PASSWORD>" ], "bos_token": "<|endoftext|>", "clean_up_tokenization_spaces": true, "eos_token": "<|endoftext|>", "extra_special_tokens": {}, "model_max_length": 1000000000000000019884624838656, "pad_token": "<fim_pad>", "tokenizer_class": "GPT2Tokenizer", "unk_token": "<|endoftext|>", "vocab_size": 49152}README.mdAdded+140
config.jsonAdded+35
generation_config.jsonAdded+12
merges.txtAdded
model.safetensorsAdded+3
modeling_gpt.pyAdded+724
special_tokens_map.jsonAdded+64
tokenizer.jsonAdded
tokenizer_config.jsonAdded+358
vocab.jsonAdded