Text Generation
Transformers
PyTorch
Safetensors
French
gopu
feature-extraction
transformer
mixture-of-experts
Mixture of Experts
french
custom-architecture
conversational
custom_code
Instructions to use Mauricio-100/locgi with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Mauricio-100/locgi with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Mauricio-100/locgi", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Mauricio-100/locgi", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Mauricio-100/locgi with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Mauricio-100/locgi" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Mauricio-100/locgi", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/Mauricio-100/locgi
- SGLang
How to use Mauricio-100/locgi 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 "Mauricio-100/locgi" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Mauricio-100/locgi", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'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 "Mauricio-100/locgi" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Mauricio-100/locgi", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use Mauricio-100/locgi with Docker Model Runner:
docker model run hf.co/Mauricio-100/locgi
Update modeling_gopu.py
Browse files- modeling_gopu.py +106 -8
modeling_gopu.py
CHANGED
|
@@ -1,9 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
| 3 |
import torch.nn.functional as F
|
| 4 |
-
from transformers import PreTrainedModel
|
|
|
|
|
|
|
| 5 |
from .configuration_gopu import GopuConfig
|
| 6 |
|
|
|
|
| 7 |
class LightSelfAttention(nn.Module):
|
| 8 |
def __init__(self, hidden_dim, n_heads):
|
| 9 |
super().__init__()
|
|
@@ -27,6 +52,7 @@ class LightSelfAttention(nn.Module):
|
|
| 27 |
out = (attn @ v).transpose(1, 2).contiguous().view(B, T, C)
|
| 28 |
return self.o_proj(out)
|
| 29 |
|
|
|
|
| 30 |
class LightMoE(nn.Module):
|
| 31 |
def __init__(self, hidden_dim, n_experts, ffn_mult=2):
|
| 32 |
super().__init__()
|
|
@@ -50,6 +76,7 @@ class LightMoE(nn.Module):
|
|
| 50 |
out = out + mask * top1_gate * expert(x)
|
| 51 |
return out
|
| 52 |
|
|
|
|
| 53 |
class GopuBlockMoE(nn.Module):
|
| 54 |
def __init__(self, hidden_dim, n_heads, n_experts):
|
| 55 |
super().__init__()
|
|
@@ -63,14 +90,31 @@ class GopuBlockMoE(nn.Module):
|
|
| 63 |
x = x + self.moe(self.norm2(x))
|
| 64 |
return x
|
| 65 |
|
|
|
|
| 66 |
class GopuPreTrainedModel(PreTrainedModel):
|
| 67 |
config_class = GopuConfig
|
| 68 |
base_model_prefix = "gopu"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
class GopuTransformerLite(GopuPreTrainedModel):
|
| 71 |
def __init__(self, config: GopuConfig):
|
| 72 |
super().__init__(config)
|
| 73 |
-
self.config = config
|
| 74 |
self.embedding = nn.Embedding(config.vocab_size, config.hidden_dim)
|
| 75 |
self.pos_embedding = nn.Embedding(config.max_seq_len, config.hidden_dim)
|
| 76 |
self.blocks = nn.ModuleList([
|
|
@@ -79,12 +123,66 @@ class GopuTransformerLite(GopuPreTrainedModel):
|
|
| 79 |
])
|
| 80 |
self.norm_out = nn.LayerNorm(config.hidden_dim)
|
| 81 |
self.fc_out = nn.Linear(config.hidden_dim, config.vocab_size)
|
|
|
|
| 82 |
|
| 83 |
-
def
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
for block in self.blocks:
|
| 88 |
h = block(h)
|
| 89 |
h = self.norm_out(h)
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
modeling_gopu.py
|
| 3 |
+
|
| 4 |
+
Wrapper transformers pour GopuTransformerLite (attention + MoE) :
|
| 5 |
+
- forward() façon GPT2 : accepte labels, calcule la loss causale décalée
|
| 6 |
+
en interne (shift logits/labels), retourne CausalLMOutputWithPast.
|
| 7 |
+
- generate() fonctionne via GenerationMixin (pas de KV-cache implémenté :
|
| 8 |
+
chaque étape recalcule la séquence entière -> plus lent que GPT2/Llama,
|
| 9 |
+
mais correct).
|
| 10 |
+
- LIMITE IMPORTANTE : la position embedding est de taille fixe
|
| 11 |
+
config.max_seq_len (32 par défaut à l'entraînement actuel). Le contexte
|
| 12 |
+
total (prompt + génération) ne peut pas dépasser cette valeur. Ce n'est
|
| 13 |
+
pas un bug de ce wrapper, c'est une contrainte de l'architecture entraînée.
|
| 14 |
+
- Pas de vrai masque de padding dans l'attention (seulement le masque
|
| 15 |
+
causal) -> génération batch>1 avec padding non garantie correcte,
|
| 16 |
+
utilise plutôt batch_size=1 pour l'inférence.
|
| 17 |
+
|
| 18 |
+
IMPORTANT : ce fichier DOIT contenir la classe GopuForCausalLM en entier.
|
| 19 |
+
Si tu le modifies, vérifie qu'elle est toujours présente avant de repusher
|
| 20 |
+
(build_transformers_package_v2.py fait cette vérification automatiquement).
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
import torch
|
| 24 |
import torch.nn as nn
|
| 25 |
import torch.nn.functional as F
|
| 26 |
+
from transformers import PreTrainedModel, GenerationMixin
|
| 27 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 28 |
+
|
| 29 |
from .configuration_gopu import GopuConfig
|
| 30 |
|
| 31 |
+
|
| 32 |
class LightSelfAttention(nn.Module):
|
| 33 |
def __init__(self, hidden_dim, n_heads):
|
| 34 |
super().__init__()
|
|
|
|
| 52 |
out = (attn @ v).transpose(1, 2).contiguous().view(B, T, C)
|
| 53 |
return self.o_proj(out)
|
| 54 |
|
| 55 |
+
|
| 56 |
class LightMoE(nn.Module):
|
| 57 |
def __init__(self, hidden_dim, n_experts, ffn_mult=2):
|
| 58 |
super().__init__()
|
|
|
|
| 76 |
out = out + mask * top1_gate * expert(x)
|
| 77 |
return out
|
| 78 |
|
| 79 |
+
|
| 80 |
class GopuBlockMoE(nn.Module):
|
| 81 |
def __init__(self, hidden_dim, n_heads, n_experts):
|
| 82 |
super().__init__()
|
|
|
|
| 90 |
x = x + self.moe(self.norm2(x))
|
| 91 |
return x
|
| 92 |
|
| 93 |
+
|
| 94 |
class GopuPreTrainedModel(PreTrainedModel):
|
| 95 |
config_class = GopuConfig
|
| 96 |
base_model_prefix = "gopu"
|
| 97 |
+
main_input_name = "input_ids"
|
| 98 |
+
supports_gradient_checkpointing = False
|
| 99 |
+
|
| 100 |
+
def _init_weights(self, module):
|
| 101 |
+
if isinstance(module, nn.Linear):
|
| 102 |
+
module.weight.data.normal_(mean=0.0, std=0.02)
|
| 103 |
+
if module.bias is not None:
|
| 104 |
+
module.bias.data.zero_()
|
| 105 |
+
elif isinstance(module, nn.Embedding):
|
| 106 |
+
module.weight.data.normal_(mean=0.0, std=0.02)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class GopuForCausalLM(GopuPreTrainedModel, GenerationMixin):
|
| 110 |
+
"""
|
| 111 |
+
Interface façon GPT2LMHeadModel : forward(input_ids, labels=...) calcule
|
| 112 |
+
la loss causale (next-token prediction) en interne. Compatible avec
|
| 113 |
+
model.generate(), Trainer, pipeline("text-generation", ...).
|
| 114 |
+
"""
|
| 115 |
|
|
|
|
| 116 |
def __init__(self, config: GopuConfig):
|
| 117 |
super().__init__(config)
|
|
|
|
| 118 |
self.embedding = nn.Embedding(config.vocab_size, config.hidden_dim)
|
| 119 |
self.pos_embedding = nn.Embedding(config.max_seq_len, config.hidden_dim)
|
| 120 |
self.blocks = nn.ModuleList([
|
|
|
|
| 123 |
])
|
| 124 |
self.norm_out = nn.LayerNorm(config.hidden_dim)
|
| 125 |
self.fc_out = nn.Linear(config.hidden_dim, config.vocab_size)
|
| 126 |
+
self.post_init()
|
| 127 |
|
| 128 |
+
def get_input_embeddings(self):
|
| 129 |
+
return self.embedding
|
| 130 |
+
|
| 131 |
+
def set_input_embeddings(self, value):
|
| 132 |
+
self.embedding = value
|
| 133 |
+
|
| 134 |
+
def forward(
|
| 135 |
+
self,
|
| 136 |
+
input_ids=None,
|
| 137 |
+
attention_mask=None,
|
| 138 |
+
labels=None,
|
| 139 |
+
past_key_values=None, # accepté pour compat generate(), pas utilisé (pas de cache)
|
| 140 |
+
use_cache=False,
|
| 141 |
+
output_attentions=False,
|
| 142 |
+
output_hidden_states=False,
|
| 143 |
+
return_dict=True,
|
| 144 |
+
**kwargs,
|
| 145 |
+
):
|
| 146 |
+
B, T = input_ids.shape
|
| 147 |
+
if T > self.config.max_seq_len:
|
| 148 |
+
raise ValueError(
|
| 149 |
+
f"Séquence de longueur {T} > max_seq_len={self.config.max_seq_len}. "
|
| 150 |
+
f"Ce modèle a une position embedding de taille fixe, il ne peut pas "
|
| 151 |
+
f"traiter un contexte plus long que celui utilisé à l'entraînement."
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
positions = torch.arange(T, device=input_ids.device).unsqueeze(0)
|
| 155 |
+
h = self.embedding(input_ids) + self.pos_embedding(positions)
|
| 156 |
for block in self.blocks:
|
| 157 |
h = block(h)
|
| 158 |
h = self.norm_out(h)
|
| 159 |
+
logits = self.fc_out(h)
|
| 160 |
+
|
| 161 |
+
loss = None
|
| 162 |
+
if labels is not None:
|
| 163 |
+
# Convention causale standard façon GPT2 : on décale d'un cran.
|
| 164 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 165 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 166 |
+
loss = F.cross_entropy(
|
| 167 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 168 |
+
shift_labels.view(-1),
|
| 169 |
+
ignore_index=self.config.pad_token_id,
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
if not return_dict:
|
| 173 |
+
return (loss, logits) if loss is not None else (logits,)
|
| 174 |
+
|
| 175 |
+
return CausalLMOutputWithPast(
|
| 176 |
+
loss=loss,
|
| 177 |
+
logits=logits,
|
| 178 |
+
past_key_values=None,
|
| 179 |
+
hidden_states=None,
|
| 180 |
+
attentions=None,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 184 |
+
# Pas de KV-cache -> on repasse la séquence entière à chaque étape,
|
| 185 |
+
# tronquée à max_seq_len (fenêtre glissante) pour rester dans la limite.
|
| 186 |
+
if input_ids.shape[1] > self.config.max_seq_len:
|
| 187 |
+
input_ids = input_ids[:, -self.config.max_seq_len:]
|
| 188 |
+
return {"input_ids": input_ids}
|