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: 17,896 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 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 | ##Script_EntrainementLocal_Ptit_SLM_Poc03.py
"""
Ptit_SLM_Poc03 - Fine-tuning supervisé (SFT) local
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 : python Script_EntrainementLocal_Ptit_SLM_Poc03.py
Format des jeux de données (dans DOSSIER_JEUX_DE_DONNEES) :
- fichiers .jsonl : une ligne JSON par exemple, par ex.
{"instruction": "Écris une phrase sur la mer.", "reponse": "La mer est calme ce soir."}
- fichiers .json : une liste d'objets de même forme
Les noms des balises acceptées se règlent avec CHAMPS_ENTREE et CHAMPS_SORTIE.
Format des exemples (variable MODE_CONVERSATION) :
True : [CLS] [USER] entrée [ASSISTANT] sortie [SEP]
False : [CLS] entrée + SEPARATEUR_ENTREE_SORTIE + sortie [SEP]
Si MASQUER_ENTREE est True, seule la sortie est apprise (l'entrée sert de contexte).
"""
import os
import json
import math
import shutil
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from safetensors.torch import load_file, save_file
from tokenizers import Tokenizer
# ======================================================================
# PARAMÉTRAGE (variables à modifier selon vos besoins)
# ======================================================================
# Dossier contenant model.safetensors, tokenizer.json et config.json du modèle de départ
DOSSIER_MODELE = "."
# Dossier contenant vos fichiers .jsonl ou .json
DOSSIER_JEUX_DE_DONNEES = "./Jeux_De_Donnees"
# Dossier où le modèle fine-tuné est enregistré (le modèle de départ n'est jamais modifié)
DOSSIER_SORTIE_MODELE = "./Ptit_SLM_Poc03_SFT"
# Fichiers copiés du modèle de départ vers le dossier de sortie (les poids sont réécrits à part)
FICHIERS_A_COPIER = [
"config.json",
"generation_config.json",
"configuration_ptit_slm.py",
"modeling_ptit_slm.py",
"tokenizer.json",
"tokenizer_config.json",
"special_tokens_map.json",
]
# 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
# True : calcul en bfloat16 sur GPU compatible (plus rapide, moins de mémoire)
PRECISION_MIXTE = True
# Graine aléatoire pour reproduire un entraînement
GRAINE = 42
# Balises acceptées pour le texte d'ENTRÉE (la question, la consigne, le contexte).
# Pour chaque ligne du jeu de données, la première balise présente et non vide est utilisée.
# Ce texte sert de contexte au modèle et, si MASQUER_ENTREE est True, il est ignoré dans la perte.
# Une ligne peut n'avoir aucune balise d'entrée : le modèle apprend alors la sortie seule.
CHAMPS_ENTREE = ["instruction", "question", "prompt"]
# Balises acceptées pour le texte de SORTIE (la réponse que le modèle doit apprendre).
# Pour chaque ligne, la première balise présente et non vide est utilisée.
# Une ligne sans aucune balise de sortie est ignorée.
CHAMPS_SORTIE = ["reponse", "answer", "completion"]
# True : format conversation [USER] / [ASSISTANT] ; False : entrée et sortie collées
MODE_CONVERSATION = True
# Noms des tokens spéciaux utilisés en mode conversation
TOKEN_UTILISATEUR = "[USER]"
TOKEN_ASSISTANT = "[ASSISTANT]"
# Texte inséré entre l'entrée et la sortie (uniquement si MODE_CONVERSATION est False)
SEPARATEUR_ENTREE_SORTIE = "\n"
# True : la perte n'est calculée que sur la sortie ; False : sur tout le texte
MASQUER_ENTREE = True
# Longueur maximale d'un exemple (les exemples plus longs sont tronqués)
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
# Part des exemples réservée à la validation (0 pour désactiver)
PROPORTION_VALIDATION = 0.05
# Paramètres d'entraînement
NOMBRE_EPOCHS = 3
TAILLE_LOT = 4
ETAPES_ACCUMULATION_GRADIENT = 4
TAUX_APPRENTISSAGE = 2e-5
DECROISSANCE_POIDS = 0.01
ETAPES_ECHAUFFEMENT = 50
NORME_MAX_GRADIENT = 1.0
# Affiche la perte toutes les N étapes d'optimisation
FREQUENCE_AFFICHAGE = 10
# 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'inférence)
# ======================================================================
# 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))
# ======================================================================
# DONNÉES
# ======================================================================
# Renvoie le texte de la première balise de la liste présente et non vide, sinon ""
def premier_champ_present(objet, liste_champs):
for nom_champ in liste_champs:
valeur = objet.get(nom_champ)
if valeur is not None and str(valeur).strip():
return str(valeur).strip()
return ""
# Lit tous les fichiers .jsonl et .json du dossier et renvoie une liste de (entree, sortie)
def lire_jeux_de_donnees():
paires = []
for nom_fichier in sorted(os.listdir(DOSSIER_JEUX_DE_DONNEES)):
chemin = os.path.join(DOSSIER_JEUX_DE_DONNEES, nom_fichier)
if nom_fichier.endswith(".jsonl"):
with open(chemin, "r", encoding="utf-8") as fichier:
objets = [json.loads(ligne) for ligne in fichier if ligne.strip()]
elif nom_fichier.endswith(".json"):
with open(chemin, "r", encoding="utf-8") as fichier:
objets = json.load(fichier)
else:
continue
for objet in objets:
entree = premier_champ_present(objet, CHAMPS_ENTREE)
sortie = premier_champ_present(objet, CHAMPS_SORTIE)
if sortie:
paires.append((entree, sortie))
print(f"Lu : {nom_fichier} ({len(objets)} lignes)")
return paires
# Transforme une paire (entree, sortie) en ids de tokens et étiquettes (-100 = ignoré)
def preparer_exemple(tokenizer, entree, sortie, id_utilisateur, id_assistant):
ids_entree = tokenizer.encode(
entree + (SEPARATEUR_ENTREE_SORTIE if entree and not MODE_CONVERSATION else ""),
add_special_tokens=False,
).ids
if MODE_CONVERSATION:
ids_entree = [ID_TOKEN_DEBUT, id_utilisateur] + ids_entree + [id_assistant]
else:
ids_entree = [ID_TOKEN_DEBUT] + ids_entree
ids_sortie = tokenizer.encode(sortie, add_special_tokens=False).ids + [ID_TOKEN_FIN]
ids = (ids_entree + ids_sortie)[:LONGUEUR_CONTEXTE]
if MASQUER_ENTREE:
etiquettes = ([-100] * len(ids_entree) + ids_sortie)[:LONGUEUR_CONTEXTE]
else:
etiquettes = list(ids)
return ids, etiquettes
# Assemble un lot en complétant à droite (le masque causal rend le remplissage sans effet)
def assembler_lot(exemples):
longueur_max = max(len(ids) for ids, _ in exemples)
lot_ids = []
lot_etiquettes = []
for ids, etiquettes in exemples:
reste = longueur_max - len(ids)
lot_ids.append(ids + [ID_TOKEN_REMPLISSAGE] * reste)
lot_etiquettes.append(etiquettes + [-100] * reste)
return torch.tensor(lot_ids), torch.tensor(lot_etiquettes)
# ======================================================================
# ENTRAÎNEMENT
# ======================================================================
# Perte de prédiction du token suivant, calculée en float32
def calculer_perte(modele, ids, etiquettes):
logits = modele(ids)
return F.cross_entropy(
logits[:, :-1].reshape(-1, logits.shape[-1]).float(),
etiquettes[:, 1:].reshape(-1),
ignore_index=-100,
)
@torch.no_grad()
def evaluer(modele, chargeur, peripherique, contexte_calcul):
modele.eval()
somme_pertes = 0.0
nombre_lots = 0
for ids, etiquettes in chargeur:
ids, etiquettes = ids.to(peripherique), etiquettes.to(peripherique)
with contexte_calcul():
perte = calculer_perte(modele, ids, etiquettes)
somme_pertes += perte.item()
nombre_lots += 1
modele.train()
return somme_pertes / max(nombre_lots, 1)
# Enregistre les poids (mêmes noms de clés qu'à l'origine) et copie config, code et tokenizer
def sauvegarder(modele):
os.makedirs(DOSSIER_SORTIE_MODELE, exist_ok=True)
poids = {
cle: valeur.detach().cpu().contiguous()
for cle, valeur in modele.state_dict().items()
}
save_file(
poids,
os.path.join(DOSSIER_SORTIE_MODELE, "model.safetensors"),
metadata={"format": "pt"},
)
for nom_fichier in FICHIERS_A_COPIER:
source = os.path.join(DOSSIER_MODELE, nom_fichier)
if os.path.isfile(source):
shutil.copy2(source, os.path.join(DOSSIER_SORTIE_MODELE, nom_fichier))
print(f"Modèle enregistré dans : {DOSSIER_SORTIE_MODELE}")
def main():
random.seed(GRAINE)
torch.manual_seed(GRAINE)
appliquer_configuration()
peripherique = torch.device(
"cuda" if UTILISER_GPU and torch.cuda.is_available() else "cpu"
)
utiliser_bf16 = (
PRECISION_MIXTE
and peripherique.type == "cuda"
and torch.cuda.is_bf16_supported()
)
print(f"Périphérique : {peripherique} (bfloat16 : {utiliser_bf16})")
# Contexte de calcul : autocast bfloat16 si possible, sinon calcul normal
def contexte_calcul():
if utiliser_bf16:
return torch.autocast(device_type="cuda", dtype=torch.bfloat16)
return torch.autocast(device_type=peripherique.type, enabled=False)
tokenizer = Tokenizer.from_file(os.path.join(DOSSIER_MODELE, "tokenizer.json"))
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(f"Erreur : {TOKEN_UTILISATEUR} ou {TOKEN_ASSISTANT} absent du tokenizer.")
return
paires = lire_jeux_de_donnees()
if not paires:
print("Aucun exemple trouvé : vérifiez DOSSIER_JEUX_DE_DONNEES et les noms de champs.")
return
exemples = [
preparer_exemple(tokenizer, e, s, id_utilisateur, id_assistant)
for e, s in paires
]
random.shuffle(exemples)
nombre_validation = int(len(exemples) * PROPORTION_VALIDATION)
exemples_validation = exemples[:nombre_validation]
exemples_entrainement = exemples[nombre_validation:]
print(
f"Exemples : {len(exemples_entrainement)} entraînement, "
f"{len(exemples_validation)} validation"
)
chargeur_entrainement = DataLoader(
exemples_entrainement,
batch_size=TAILLE_LOT,
shuffle=True,
collate_fn=assembler_lot,
)
chargeur_validation = DataLoader(
exemples_validation,
batch_size=TAILLE_LOT,
shuffle=False,
collate_fn=assembler_lot,
)
modele = ModelePtitSLM()
# strict=True : toute clé manquante ou inattendue lève une erreur explicite
modele.load_state_dict(
load_file(os.path.join(DOSSIER_MODELE, "model.safetensors")), strict=True
)
modele.to(peripherique)
modele.train()
optimiseur = torch.optim.AdamW(
modele.parameters(),
lr=TAUX_APPRENTISSAGE,
weight_decay=DECROISSANCE_POIDS,
)
etapes_par_epoch = math.ceil(len(chargeur_entrainement) / ETAPES_ACCUMULATION_GRADIENT)
etapes_totales = etapes_par_epoch * NOMBRE_EPOCHS
# Taux d'apprentissage : montée linéaire puis descente en cosinus jusqu'à 10 %
def facteur_taux(etape):
if etape < ETAPES_ECHAUFFEMENT:
return (etape + 1) / ETAPES_ECHAUFFEMENT
progression = (etape - ETAPES_ECHAUFFEMENT) / max(
1, etapes_totales - ETAPES_ECHAUFFEMENT
)
return 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * min(progression, 1.0)))
planificateur = torch.optim.lr_scheduler.LambdaLR(optimiseur, facteur_taux)
etape = 0
for epoch in range(1, NOMBRE_EPOCHS + 1):
somme_pertes = 0.0
nombre_pertes = 0
optimiseur.zero_grad()
for indice_lot, (ids, etiquettes) in enumerate(chargeur_entrainement, start=1):
ids, etiquettes = ids.to(peripherique), etiquettes.to(peripherique)
with contexte_calcul():
perte = calculer_perte(modele, ids, etiquettes)
(perte / ETAPES_ACCUMULATION_GRADIENT).backward()
somme_pertes += perte.item()
nombre_pertes += 1
fin_accumulation = indice_lot % ETAPES_ACCUMULATION_GRADIENT == 0
dernier_lot = indice_lot == len(chargeur_entrainement)
if fin_accumulation or dernier_lot:
torch.nn.utils.clip_grad_norm_(modele.parameters(), NORME_MAX_GRADIENT)
optimiseur.step()
planificateur.step()
optimiseur.zero_grad()
etape += 1
if etape % FREQUENCE_AFFICHAGE == 0:
print(
f"Epoch {epoch}/{NOMBRE_EPOCHS} | étape {etape}/{etapes_totales} | "
f"perte {somme_pertes / nombre_pertes:.4f} | "
f"taux {planificateur.get_last_lr()[0]:.2e}"
)
somme_pertes = 0.0
nombre_pertes = 0
if nombre_validation > 0:
perte_validation = evaluer(modele, chargeur_validation, peripherique, contexte_calcul)
print(f"Epoch {epoch} terminée | perte de validation : {perte_validation:.4f}")
sauvegarder(modele)
print("Entraînement terminé.")
if __name__ == "__main__":
main()
|