Text Generation
Transformers
Safetensors
French
ptit_slm
ptit-slm
from-scratch
post-norm
custom_code
experimental
Instructions to use MisterAI/Ptit_SLM_Poc03 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use MisterAI/Ptit_SLM_Poc03 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="MisterAI/Ptit_SLM_Poc03", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("MisterAI/Ptit_SLM_Poc03", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use MisterAI/Ptit_SLM_Poc03 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "MisterAI/Ptit_SLM_Poc03" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "MisterAI/Ptit_SLM_Poc03", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/MisterAI/Ptit_SLM_Poc03
- SGLang
How to use MisterAI/Ptit_SLM_Poc03 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 "MisterAI/Ptit_SLM_Poc03" \ --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": "MisterAI/Ptit_SLM_Poc03", "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 "MisterAI/Ptit_SLM_Poc03" \ --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": "MisterAI/Ptit_SLM_Poc03", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use MisterAI/Ptit_SLM_Poc03 with Docker Model Runner:
docker model run hf.co/MisterAI/Ptit_SLM_Poc03
File size: 13,572 Bytes
aa4bb13 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | ##Script_InferenceLocale_Ptit_SLM_Poc03.py
"""
Ptit_SLM_Poc03 - Inférence locale en terminal (boucle continue)
Modèle : SLM ~50M paramètres, Transformer décodeur POST-NORM, entraîné from scratch.
Auteur : MisterAI - Licence AGPLv3 - POC expérimental.
Dépendances : torch, safetensors, tokenizers (rien d'autre).
Utilisation Depuis venvPoc03 :
source venvPoc03/bin/activate
python -m Scripts.Script_InferenceLocale_Ptit_SLM_Poc03
Commandes dans la boucle :
/effacer vide le contexte et repart de zéro
/quitter ferme le programme
/aide rappelle les commandes
Le contexte s'accumule de tour en tour jusqu'à LONGUEUR_CONTEXTE tokens,
puis il faut taper /effacer.
Deux modes (variable MODE_CONVERSATION) :
True : format [CLS] [USER] question [ASSISTANT] réponse [SEP]
False : le modèle continue simplement le texte saisi
"""
import os
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file
from tokenizers import Tokenizer
# ======================================================================
# PARAMÉTRAGE (variables à modifier selon vos besoins)
# ======================================================================
# Dossier contenant model.safetensors, tokenizer.json et config.json
DOSSIER_MODELE = "."
# True : lit l'architecture dans config.json ; False : utilise les valeurs de ce script
LIRE_CONFIG_JSON = True
# True : utilise le GPU si CUDA est disponible, sinon le CPU est utilisé automatiquement
UTILISER_GPU = True
# Graine aléatoire (None pour une génération différente à chaque lancement)
GRAINE = None
# True : format conversation [USER] / [ASSISTANT] ; False : complétion de texte brut
MODE_CONVERSATION = True
# Noms des tokens spéciaux utilisés en mode conversation
TOKEN_UTILISATEUR = "[USER]"
TOKEN_ASSISTANT = "[ASSISTANT]"
# Créativité : 0 = déterministe (glouton), 0.4 = sage, 1.0 = très créatif
TEMPERATURE = 0.4
# Ne garde que les K tokens les plus probables (0 pour désactiver)
TOP_K = 40
# Ne garde que les tokens couvrant cette probabilité cumulée (1.0 pour désactiver)
TOP_P = 1.0
# Pénalité contre les répétitions (1.0 = aucune, 1.1 à 1.3 = utile pour un petit modèle)
PENALITE_REPETITION = 1.1
# Nombre de derniers tokens du contexte pris en compte par la pénalité de répétition
FENETRE_PENALITE_REPETITION = 128
# Nombre maximum de tokens générés à chaque tour
NOMBRE_TOKENS_MAX_PAR_REPONSE = 200
# Contexte fiable du modèle (il a surtout été entraîné à 1024)
LONGUEUR_CONTEXTE = 1024
# Identifiants des tokens spéciaux : [CLS] début, [SEP] fin, [PAD] remplissage
ID_TOKEN_DEBUT = 1
ID_TOKEN_FIN = 2
ID_TOKEN_REMPLISSAGE = 3
# Hyperparamètres de l'architecture (écrasés par config.json si LIRE_CONFIG_JSON est True)
TAILLE_VOCABULAIRE = 32768
DIMENSION_MODELE = 512
NOMBRE_COUCHES = 8
NOMBRE_TETES = 8
DIMENSION_FFN = 2048
TAUX_DROPOUT = 0.1
EPSILON_NORMALISATION = 1e-5
LONGUEUR_POSITIONS_MAX = 8192
# ======================================================================
# LECTURE DE config.json
# ======================================================================
# Remplace les variables globales d'architecture par celles de config.json
def appliquer_configuration():
global TAILLE_VOCABULAIRE, DIMENSION_MODELE, NOMBRE_COUCHES, NOMBRE_TETES
global DIMENSION_FFN, TAUX_DROPOUT, EPSILON_NORMALISATION, LONGUEUR_POSITIONS_MAX
global LONGUEUR_CONTEXTE, ID_TOKEN_DEBUT, ID_TOKEN_FIN, ID_TOKEN_REMPLISSAGE
chemin = os.path.join(DOSSIER_MODELE, "config.json")
if not LIRE_CONFIG_JSON or not os.path.isfile(chemin):
print("config.json non utilisé : valeurs du script conservées.")
return
with open(chemin, "r", encoding="utf-8") as fichier:
config = json.load(fichier)
TAILLE_VOCABULAIRE = config.get("vocab_size", TAILLE_VOCABULAIRE)
DIMENSION_MODELE = config.get("hidden_size", DIMENSION_MODELE)
NOMBRE_COUCHES = config.get("num_hidden_layers", NOMBRE_COUCHES)
NOMBRE_TETES = config.get("num_attention_heads", NOMBRE_TETES)
DIMENSION_FFN = config.get("intermediate_size", DIMENSION_FFN)
TAUX_DROPOUT = config.get("dropout", TAUX_DROPOUT)
EPSILON_NORMALISATION = config.get("layer_norm_eps", EPSILON_NORMALISATION)
LONGUEUR_POSITIONS_MAX = config.get("max_position_embeddings", LONGUEUR_POSITIONS_MAX)
LONGUEUR_CONTEXTE = config.get("max_context", LONGUEUR_CONTEXTE)
ID_TOKEN_DEBUT = config.get("bos_token_id", ID_TOKEN_DEBUT)
ID_TOKEN_FIN = config.get("eos_token_id", ID_TOKEN_FIN)
ID_TOKEN_REMPLISSAGE = config.get("pad_token_id", ID_TOKEN_REMPLISSAGE)
print("Configuration lue dans config.json")
# ======================================================================
# ARCHITECTURE (identique au script d'entraînement)
# ======================================================================
# Un bloc POST-NORM : x = norm1(x + attention(x)) puis x = norm2(x + ffn(x))
class BlocTransformer(nn.Module):
def __init__(self):
super().__init__()
self.attention = nn.MultiheadAttention(
DIMENSION_MODELE, NOMBRE_TETES, batch_first=True
)
self.norm1 = nn.LayerNorm(DIMENSION_MODELE, eps=EPSILON_NORMALISATION)
self.norm2 = nn.LayerNorm(DIMENSION_MODELE, eps=EPSILON_NORMALISATION)
self.feed_forward = nn.Sequential(
nn.Linear(DIMENSION_MODELE, DIMENSION_FFN),
nn.GELU(),
nn.Linear(DIMENSION_FFN, DIMENSION_MODELE),
nn.Dropout(TAUX_DROPOUT),
)
self.dropout = nn.Dropout(TAUX_DROPOUT)
def forward(self, x, masque_causal):
sortie_attention, _ = self.attention(
x, x, x, attn_mask=masque_causal, need_weights=False
)
x = self.norm1(x + self.dropout(sortie_attention))
x = self.norm2(x + self.dropout(self.feed_forward(x)))
return x
# Le modèle complet : embeddings, positions apprises, blocs, norme finale, tête avec biais
class ModelePtitSLM(nn.Module):
def __init__(self):
super().__init__()
self.embed = nn.Embedding(TAILLE_VOCABULAIRE, DIMENSION_MODELE)
self.pos_embed = nn.Embedding(LONGUEUR_POSITIONS_MAX, DIMENSION_MODELE)
self.dropout = nn.Dropout(TAUX_DROPOUT)
self.layers = nn.ModuleList([BlocTransformer() for _ in range(NOMBRE_COUCHES)])
self.ln_f = nn.LayerNorm(DIMENSION_MODELE, eps=EPSILON_NORMALISATION)
self.head = nn.Linear(DIMENSION_MODELE, TAILLE_VOCABULAIRE, bias=True)
def forward(self, ids):
longueur = ids.shape[1]
positions = torch.arange(longueur, device=ids.device)
x = self.dropout(self.embed(ids) + self.pos_embed(positions))
# Masque causal booléen : True = position interdite
masque_causal = torch.triu(
torch.ones(longueur, longueur, dtype=torch.bool, device=ids.device),
diagonal=1,
)
for bloc in self.layers:
x = bloc(x, masque_causal)
return self.head(self.ln_f(x))
# ======================================================================
# CHARGEMENT
# ======================================================================
def charger_modele(peripherique):
chemin_poids = os.path.join(DOSSIER_MODELE, "model.safetensors")
modele = ModelePtitSLM()
# strict=True : toute clé manquante ou inattendue lève une erreur explicite
modele.load_state_dict(load_file(chemin_poids), strict=True)
modele.to(peripherique)
# Mode évaluation : désactive le dropout
modele.eval()
return modele
def charger_tokenizer():
return Tokenizer.from_file(os.path.join(DOSSIER_MODELE, "tokenizer.json"))
# ======================================================================
# GÉNÉRATION
# ======================================================================
# Choisit le prochain token à partir des logits (pénalité, température, top-k, top-p)
def choisir_token(logits, contexte_ids):
if PENALITE_REPETITION != 1.0 and contexte_ids:
for id_token in set(contexte_ids[-FENETRE_PENALITE_REPETITION:]):
valeur = logits[id_token]
logits[id_token] = (
valeur / PENALITE_REPETITION
if valeur > 0
else valeur * PENALITE_REPETITION
)
# Température nulle : choix du token le plus probable
if TEMPERATURE <= 0:
return int(torch.argmax(logits))
logits = logits / TEMPERATURE
if TOP_K > 0:
seuil = torch.topk(logits, min(TOP_K, logits.shape[-1])).values[-1]
logits[logits < seuil] = float("-inf")
probabilites = F.softmax(logits, dim=-1)
if TOP_P < 1.0:
probas_triees, indices_tries = torch.sort(probabilites, descending=True)
cumul = torch.cumsum(probas_triees, dim=-1)
a_retirer = (cumul - probas_triees) > TOP_P
probas_triees[a_retirer] = 0.0
probabilites = torch.zeros_like(probabilites).scatter_(
0, indices_tries, probas_triees
)
probabilites = probabilites / probabilites.sum()
return int(torch.multinomial(probabilites, 1))
# Génère la suite du contexte token par token et l'affiche au fil de l'eau
# Renvoie True si le modèle s'est arrêté de lui-même en produisant le token de fin
@torch.no_grad()
def generer(modele, tokenizer, contexte_ids, peripherique):
ids_generes = []
texte_affiche = ""
fin_produite = False
while (
len(contexte_ids) < LONGUEUR_CONTEXTE
and len(ids_generes) < NOMBRE_TOKENS_MAX_PAR_REPONSE
):
entree = torch.tensor([contexte_ids], device=peripherique)
logits = modele(entree)[0, -1].float()
id_suivant = choisir_token(logits, contexte_ids)
if id_suivant == ID_TOKEN_FIN:
fin_produite = True
break
contexte_ids.append(id_suivant)
ids_generes.append(id_suivant)
# On attend d'avoir un caractère UTF-8 complet avant d'afficher
texte = tokenizer.decode(ids_generes)
if not texte.endswith("\ufffd"):
print(texte[len(texte_affiche):], end="", flush=True)
texte_affiche = texte
texte_final = tokenizer.decode(ids_generes)
print(texte_final[len(texte_affiche):], flush=True)
return fin_produite
# ======================================================================
# BOUCLE PRINCIPALE
# ======================================================================
def afficher_aide():
print("Commandes : /effacer (nouveau contexte), /quitter, /aide")
if MODE_CONVERSATION:
print("Tapez votre message : le modèle répond.")
else:
print("Tapez un texte : le modèle en écrit la suite.")
def main():
if GRAINE is not None:
torch.manual_seed(GRAINE)
appliquer_configuration()
peripherique = torch.device(
"cuda" if UTILISER_GPU and torch.cuda.is_available() else "cpu"
)
print(f"Périphérique : {peripherique}")
print(f"Chargement depuis : {DOSSIER_MODELE}")
modele = charger_modele(peripherique)
tokenizer = charger_tokenizer()
id_utilisateur = tokenizer.token_to_id(TOKEN_UTILISATEUR)
id_assistant = tokenizer.token_to_id(TOKEN_ASSISTANT)
if MODE_CONVERSATION and (id_utilisateur is None or id_assistant is None):
print("Tokens de conversation introuvables dans le tokenizer : mode complétion activé.")
mode_conversation = False
else:
mode_conversation = MODE_CONVERSATION
nombre_parametres = sum(p.numel() for p in modele.parameters())
print(f"Modèle prêt ({nombre_parametres / 1e6:.1f}M paramètres)")
afficher_aide()
contexte_ids = [ID_TOKEN_DEBUT]
while True:
print(f"\n[contexte : {len(contexte_ids)}/{LONGUEUR_CONTEXTE} tokens]")
try:
saisie = input("> ")
except (EOFError, KeyboardInterrupt):
print("\nAu revoir.")
break
commande = saisie.strip().lower()
if commande == "/quitter":
print("Au revoir.")
break
if commande == "/aide":
afficher_aide()
continue
if commande == "/effacer":
contexte_ids = [ID_TOKEN_DEBUT]
print("Contexte effacé.")
continue
if not saisie.strip():
continue
if len(contexte_ids) >= LONGUEUR_CONTEXTE:
print(f"Limite de {LONGUEUR_CONTEXTE} tokens atteinte : tapez /effacer.")
continue
ids_saisie = tokenizer.encode(saisie, add_special_tokens=False).ids
if mode_conversation:
ids_saisie = [id_utilisateur] + ids_saisie + [id_assistant]
if len(contexte_ids) + len(ids_saisie) >= LONGUEUR_CONTEXTE:
print(
f"Texte trop long pour la place restante "
f"({LONGUEUR_CONTEXTE - len(contexte_ids)} tokens). "
f"Raccourcissez-le ou tapez /effacer."
)
continue
contexte_ids.extend(ids_saisie)
fin_produite = generer(modele, tokenizer, contexte_ids, peripherique)
# En conversation, on referme le tour pour que le contexte reste bien structuré
if mode_conversation and fin_produite and len(contexte_ids) < LONGUEUR_CONTEXTE:
contexte_ids.append(ID_TOKEN_FIN)
if len(contexte_ids) >= LONGUEUR_CONTEXTE:
print(f"\nLimite de {LONGUEUR_CONTEXTE} tokens atteinte : tapez /effacer.")
if __name__ == "__main__":
main()
|