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
Download Scripts/Script_EntrainementLocal_Ptit_SLM_Poc03.py from MisterAI/Ptit_SLM_Poc03: direct link, hf CLI and curl.
- Browser
- Download file 17.9 kB
-
https://huggingface.co/MisterAI/Ptit_SLM_Poc03/resolve/main/Scripts/Script_EntrainementLocal_Ptit_SLM_Poc03.py
- Command line
-
hf download hf://MisterAI/Ptit_SLM_Poc03/Scripts/Script_EntrainementLocal_Ptit_SLM_Poc03.py
-
curl -L -o Script_EntrainementLocal_Ptit_SLM_Poc03.py https://huggingface.co/MisterAI/Ptit_SLM_Poc03/resolve/main/Scripts/Script_EntrainementLocal_Ptit_SLM_Poc03.py
17.9 kB
| ##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, | |
| ) | |
| 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() | |