Text Generation
Transformers
Safetensors
Arabic
arabic-gpt
feature-extraction
torch
custom
GPT
custom_code
Run this model with HF Jobs
Run alphatechlogics/FaseehGPT 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/alphatechlogics/FaseehGPT. 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/alphatechlogics/FaseehGPT 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/alphatechlogics/FaseehGPT. 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/alphatechlogics/FaseehGPT. 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 alphatechlogics/FaseehGPT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use alphatechlogics/FaseehGPT with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="alphatechlogics/FaseehGPT", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("alphatechlogics/FaseehGPT", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use alphatechlogics/FaseehGPT with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "alphatechlogics/FaseehGPT" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "alphatechlogics/FaseehGPT", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/alphatechlogics/FaseehGPT
- SGLang
How to use alphatechlogics/FaseehGPT 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 "alphatechlogics/FaseehGPT" \ --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": "alphatechlogics/FaseehGPT", "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 "alphatechlogics/FaseehGPT" \ --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": "alphatechlogics/FaseehGPT", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use alphatechlogics/FaseehGPT with Docker Model Runner:
docker model run hf.co/alphatechlogics/FaseehGPT
Update modeling_arabic-gpt.py
Browse files9 unmodified lines101112131415161717 unmodified lines35363738394041424328 unmodified lines727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291309 unmodified linesfrom transformers import PreTrainedModelfrom transformers import PretrainedConfigfrom transformers import PretrainedConfigclass ArabicGPTConfig(PretrainedConfig):model_type = "arabic-gpt"17 unmodified linesself.tie_word_embeddings = Trueimport torchimport torch.nn as nnfrom transformers import PreTrainedModelclass ArabicGPTModel(PreTrainedModel):config_class = ArabicGPTConfig28 unmodified linesdef tie_weights(self):self.model.lm_head.weight = self.model.token_embedding.weightclass ArabicGPTConfig(PretrainedConfig):model_type = "arabic-gpt"def __init__(self,vocab_size=32000,max_seq_len=1024,embed_dim=768,num_heads=12,num_layers=12,ff_dim=3072,dropout=0.1,**kwargs):super().__init__(**kwargs)self.vocab_size = vocab_sizeself.max_seq_len = max_seq_lenself.embed_dim = embed_dimself.num_heads = num_headsself.num_layers = num_layersself.ff_dim = ff_dimself.dropout = dropoutself.tie_word_embeddings = Trueclass ArabicGPTModel(PreTrainedModel):config_class = ArabicGPTConfigdef __init__(self, config: ArabicGPTConfig):super().__init__(config)self.model = ArabicGPT(vocab_size=config.vocab_size,max_seq_len=config.max_seq_len,embed_dim=config.embed_dim,num_heads=config.num_heads,num_layers=config.num_layers,ff_dim=config.ff_dim,dropout=config.dropout,)def forward(self, x):return self.model(x)def generate(self, prompt_ids, max_new_tokens, temperature=1.0, top_k=50, top_p=0.9):return self.model.generate(prompt_ids, max_new_tokens, temperature=1.0, top_k=50, top_p=0.9)def get_input_embeddings(self):return self.model.token_embeddingdef set_input_embeddings(self, new_embeddings):self.model.token_embedding = new_embeddingsdef get_output_embeddings(self):return self.model.lm_headdef tie_weights(self):self.model.lm_head.weight = self.model.token_embedding.weight9 unmodified lines10111213141517 unmodified lines33343536373828 unmodified lines6768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742759 unmodified linesfrom transformers import PreTrainedModelfrom transformers import PretrainedConfigclass ArabicGPTConfig(PretrainedConfig):model_type = "arabic-gpt"17 unmodified linesself.tie_word_embeddings = Trueclass ArabicGPTModel(PreTrainedModel):config_class = ArabicGPTConfig28 unmodified linesdef tie_weights(self):self.model.lm_head.weight = self.model.token_embedding.weight# Part 2: GPT Model Implementationclass AttentionHead(nn.Module):def __init__(self, embed_dim, head_dim, mask=True):super().__init__()self.q = nn.Linear(embed_dim, head_dim)self.k = nn.Linear(embed_dim, head_dim)self.v = nn.Linear(embed_dim, head_dim)self.mask = maskself.scale = head_dim ** -0.5def forward(self, x):# x shape: (batch, seq_len, embed_dim)batch_size, seq_len, _ = x.shape# Linear projectionsq = self.q(x) # (batch, seq_len, head_dim)k = self.k(x) # (batch, seq_len, head_dim)v = self.v(x) # (batch, seq_len, head_dim)# Compute attention scoresattn = torch.bmm(q, k.transpose(1, 2)) * self.scale # (batch, seq_len, seq_len)# Apply causal mask for decoderif self.mask:mask = torch.triu(torch.ones(seq_len, seq_len, device=x.device), diagonal=1).bool()attn.masked_fill_(mask, float('-inf'))# Apply softmax and get weighted valuesattn = F.softmax(attn, dim=-1)output = torch.bmm(attn, v) # (batch, seq_len, head_dim)return outputclass MultiHeadAttention(nn.Module):def __init__(self, embed_dim, num_heads, mask=True):super().__init__()self.heads = nn.ModuleList([AttentionHead(embed_dim, embed_dim // num_heads, mask)for _ in range(num_heads)])self.linear = nn.Linear(embed_dim, embed_dim)def forward(self, x):# Concatenate outputs from all headsheads_output = torch.cat([head(x) for head in self.heads], dim=-1)# Final linear projectionoutput = self.linear(heads_output)return outputclass FeedForward(nn.Module):def __init__(self, embed_dim, ff_dim):super().__init__()self.net = nn.Sequential(nn.Linear(embed_dim, ff_dim),nn.GELU(),nn.Linear(ff_dim, embed_dim))def forward(self, x):return self.net(x)class TransformerBlock(nn.Module):def __init__(self, embed_dim, num_heads, ff_dim, dropout=0.1):super().__init__()self.attn = MultiHeadAttention(embed_dim, num_heads)self.ff = FeedForward(embed_dim, ff_dim)self.norm1 = nn.LayerNorm(embed_dim)self.norm2 = nn.LayerNorm(embed_dim)self.dropout = nn.Dropout(dropout)def forward(self, x):# Self-attention with residual connection and layer normattn_output = self.attn(self.norm1(x))x = x + self.dropout(attn_output)# Feed-forward with residual connection and layer normff_output = self.ff(self.norm2(x))x = x + self.dropout(ff_output)return xclass ArabicGPT(nn.Module):def __init__(self, vocab_size, max_seq_len=1024, embed_dim=768, num_heads=12,num_layers=12, ff_dim=3072, dropout=0.1):super().__init__()self.max_seq_len = max_seq_lenself.token_embedding = nn.Embedding(vocab_size, embed_dim)self.position_embedding = nn.Embedding(max_seq_len, embed_dim)# Transformer blocksself.blocks = nn.ModuleList([TransformerBlock(embed_dim, num_heads, ff_dim, dropout)for _ in range(num_layers)])# Final layer normself.norm = nn.LayerNorm(embed_dim)# Language model headself.lm_head = nn.Linear(embed_dim, vocab_size, bias=False)# Share weights between token embedding and LM head# self.lm_head.weight = self.token_embedding.weight# Initialize weightsself.apply(self._init_weights)def _init_weights(self, module):if isinstance(module, nn.Linear):torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)if module.bias is not None:torch.nn.init.zeros_(module.bias)elif isinstance(module, nn.Embedding):torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)elif isinstance(module, nn.LayerNorm):torch.nn.init.zeros_(module.bias)torch.nn.init.ones_(module.weight)def forward(self, x):# x shape: (batch, seq_len)batch_size, seq_len = x.shape# Get positionspositions = torch.arange(0, seq_len, device=x.device).unsqueeze(0).expand(batch_size, -1)# Get token and position embeddingstoken_embed = self.token_embedding(x)pos_embed = self.position_embedding(positions)# Combine embeddingsx = token_embed + pos_embed# Apply transformer blocksfor block in self.blocks:x = block(x)# Apply final layer normx = self.norm(x)# Get logitslogits = self.lm_head(x)return logitsdef generate(self, prompt_ids, max_new_tokens, temperature=1.0, top_k=50, top_p=0.9):"""Generate text using the model."""self.eval()with torch.no_grad():# Convert prompt to tensor if neededif not isinstance(prompt_ids, torch.Tensor):prompt_ids = torch.tensor(prompt_ids, dtype=torch.long)# Move to device and add batch dimension if neededif len(prompt_ids.shape) == 1:prompt_ids = prompt_ids.unsqueeze(0)prompt_ids = prompt_ids.to(next(self.parameters()).device)# Start with promptgenerated_ids = prompt_ids.clone()# Generate new tokensfor _ in range(max_new_tokens):# Take last context up to max sequence lengthinput_ids = generated_ids[:, -self.max_seq_len:]# Get logits for next tokenlogits = self(input_ids)next_token_logits = logits[:, -1, :]# Apply temperatureif temperature > 0:next_token_logits = next_token_logits / temperature# Apply top-k filteringif top_k > 0:indices_to_remove = next_token_logits < torch.topk(next_token_logits, top_k)[0][..., -1, None]next_token_logits[indices_to_remove] = float('-inf')# Apply top-p (nucleus) filteringif top_p < 1.0:sorted_logits, sorted_indices = torch.sort(next_token_logits, descending=True)cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)# Remove tokens with cumulative probability above the thresholdsorted_indices_to_remove = cumulative_probs > top_p# Shift the indices to the right to keep the first token above thresholdsorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()sorted_indices_to_remove[..., 0] = 0indices_to_remove = sorted_indices[sorted_indices_to_remove]next_token_logits[:, indices_to_remove] = float('-inf')# Sample next tokenprobs = F.softmax(next_token_logits, dim=-1)next_token = torch.multinomial(probs, num_samples=1)# Append next token to generatedgenerated_ids = torch.cat([generated_ids, next_token], dim=1)# Stop if EOS tokenif next_token.item() == 2: # Standard EOS token idbreakreturn generated_ids
modeling_arabic-gpt.py+194-49