Repository Public MIT Research preview
1"""Tests de la démonstration S03 : chaque nombre affiché dans les diapositives et les figures est vérifié ici."""2from __future__ import annotations34import math5import subprocess6import sys7from pathlib import Path89import pytest1011SESSION = Path(__file__).resolve().parents[2]12sys.path.insert(0, str(SESSION / "demos" / "src"))1314from atlas_s03.attention import (MASQUE, appliquer_masque_causal, attention, combiner_valeurs, # noqa: E40215 matrice_scores, nombre_de_scores, poids_attention, produit_scalaire, softmax)16from atlas_s03.decodage import distribution_suivant, plus_probable # noqa: E40217from atlas_s03.donnees import (CANDIDATS, FICHES, PENTE_POSITION, PHRASE_CUISINE, PHRASE_DROIT, # noqa: E40218 PHRASE_MELANGEE)19from atlas_s03.visualisation import carte_texte, trame # noqa: E4022021DEMO = SESSION / "demos" / "src" / "atlas_s03" / "demo.py"222324def arrondis(valeurs, n=2):25 return [round(v, n) for v in valeurs]262728def test_produit_scalaire():29 assert produit_scalaire((1, 1), (2, 0)) == 2 # diapositive S03-D1230 assert produit_scalaire((1, 1), (0, 0)) == 031 assert produit_scalaire((1, 1), (0.5, 0.5)) == 132 with pytest.raises(ValueError):33 produit_scalaire((1, 2), (1, 2, 3))343536def test_softmax():37 p = softmax([2.0, 0.0, 1.0])38 assert math.isclose(sum(p), 1.0)39 assert arrondis(p, 3) == [0.665, 0.090, 0.245]40 assert softmax([0.0, 0.0]) == [0.5, 0.5] # scores égaux, poids égaux41 assert softmax([5.0, MASQUE]) == [1.0, 0.0] # une position masquée reçoit exactement 042 assert softmax([]) == []43 with pytest.raises(ValueError):44 softmax([MASQUE, MASQUE])454647def test_exemple_guide_ligne_avocat():48 """Diapositives S03-D12 à S03-D14, figure S03-F01 : scores, exponentielles, poids, nouveau vecteur."""49 r = attention(PHRASE_DROIT, FICHES)50 assert r["scores"][-1] == [2.0, 0.0, 1.0]51 exponentielles = [math.exp(s) for s in r["scores"][-1]]52 assert arrondis(exponentielles) == [7.39, 1.0, 2.72]53 assert round(sum(exponentielles), 2) == 11.1154 assert arrondis(r["poids"][-1]) == [0.67, 0.09, 0.24]55 assert arrondis(r["sorties"][-1]) == [1.58, 0.24]56 # Le calcul à la main, avec les poids arrondis à deux décimales, donne le même résultat affiché.57 assert round(0.67 * 2 + 0.09 * 0 + 0.24 * 1, 2) == 1.58 and round(0.24 * 1, 2) == 0.24585960def test_phrase_cuisine_symetrique():61 r = attention(PHRASE_CUISINE, FICHES)62 assert r["scores"][-1] == [2.0, 0.0, 1.0]63 assert arrondis(r["poids"][-1]) == [0.67, 0.09, 0.24]64 assert arrondis(r["sorties"][-1]) == [0.24, 1.58]656667def test_masque_causal_matrice_triangulaire():68 """Figure S03-F02 et diapositive S03-D18."""69 avec = attention(PHRASE_DROIT, FICHES)["poids"]70 assert [arrondis(ligne) for ligne in avec] == [[1.0, 0.0, 0.0], [0.5, 0.5, 0.0], [0.67, 0.09, 0.24]]71 assert all(avec[i][j] == 0.0 for i in range(3) for j in range(3) if j > i)72 assert all(math.isclose(sum(ligne), 1.0) for ligne in avec)73 sans = attention(PHRASE_DROIT, FICHES, masque_causal=False)["poids"]74 assert [arrondis(ligne) for ligne in sans] == [[0.74, 0.10, 0.16], [0.33, 0.33, 0.33], [0.67, 0.09, 0.24]]75 assert all(math.isclose(a, b) for a, b in zip(avec[-1], sans[-1])) # la dernière ligne ne change pas76 scores = appliquer_masque_causal(matrice_scores([(1.0,)] * 3, [(1.0,)] * 3))77 assert scores[0][1] == MASQUE and scores[0][2] == MASQUE and scores[1][2] == MASQUE and scores[2][0] == 1.0787980def test_deuxieme_ligne_requete_nulle():81 r = attention(PHRASE_DROIT, FICHES)82 assert r["scores"][1][:2] == [0.0, 0.0]83 assert r["poids"][1][:2] == [0.5, 0.5]84 assert r["sorties"][1] == (1.0, 0.0)85 assert r["sorties"][0] == (2.0, 0.0) # premier jeton : il ne voit que lui-même868788def test_sans_position_l_ordre_est_invisible():89 """Figure S03-F04 : pour le dernier jeton, mélanger ce qui précède ne change rien."""90 a = attention(PHRASE_DROIT, FICHES)91 b = attention(PHRASE_MELANGEE, FICHES)92 assert sorted(PHRASE_DROIT) == sorted(PHRASE_MELANGEE) and PHRASE_DROIT != PHRASE_MELANGEE93 assert all(math.isclose(x, y) for x, y in zip(a["sorties"][-1], b["sorties"][-1]))94 assert arrondis(b["poids"][-1]) == [0.09, 0.67, 0.24]959697def test_avec_position_l_ordre_compte():98 a = attention(PHRASE_DROIT, FICHES, pente_position=PENTE_POSITION)99 b = attention(PHRASE_MELANGEE, FICHES, pente_position=PENTE_POSITION)100 assert PENTE_POSITION == 1.0101 assert a["scores"][-1] == [0.0, -1.0, 1.0] and b["scores"][-1] == [-2.0, 1.0, 1.0] # note de la diapositive S03-D20102 assert arrondis(a["poids"][-1]) == [0.24, 0.09, 0.67]103 assert arrondis(b["poids"][-1]) == [0.02, 0.49, 0.49]104 assert arrondis(a["sorties"][-1]) == [1.15, 0.67]105 assert arrondis(b["sorties"][-1]) == [1.46, 0.49]106107108def test_decodage():109 """Figure S03-F05, diapositives S03-D22 et S03-D23."""110 droit = distribution_suivant(attention(PHRASE_DROIT, FICHES)["sorties"][-1], CANDIDATS)111 cuisine = distribution_suivant(attention(PHRASE_CUISINE, FICHES)["sorties"][-1], CANDIDATS)112 sans = distribution_suivant(FICHES["avocat"]["valeur"], CANDIDATS)113 assert list(droit) == ["réputé", "mûr", "."]114 assert arrondis(droit.values()) == [0.68, 0.18, 0.14]115 assert arrondis(cuisine.values()) == [0.18, 0.68, 0.14]116 assert arrondis(sans.values()) == [0.42, 0.42, 0.16]117 assert plus_probable(droit) == "réputé" and plus_probable(cuisine) == "mûr"118 for d in (droit, cuisine, sans):119 assert math.isclose(sum(d.values()), 1.0)120121122def test_mise_a_l_echelle_pour_aller_plus_loin():123 """Diapositive S03-D16 : diviser les scores par la racine de 2 adoucit les poids."""124 r = attention(PHRASE_DROIT, FICHES, echelle=True)125 assert arrondis(r["scores"][-1]) == [1.41, 0.0, 0.71]126 assert arrondis(r["poids"][-1]) == [0.58, 0.14, 0.28]127128129def test_nombre_de_scores():130 """Diapositive S03-D24 : le nombre de produits scalaires croît comme le carré de la longueur."""131 assert nombre_de_scores(3) == 6 and nombre_de_scores(3, masque_causal=False) == 9132 assert nombre_de_scores(1000) == 500_500133 r = attention(PHRASE_DROIT, FICHES)134 assert sum(s != MASQUE for ligne in r["scores"] for s in ligne) == 6135136137def test_fonctions_de_base_coherentes():138 poids = poids_attention([[0.0, MASQUE], [0.0, 0.0]])139 assert poids == [[1.0, 0.0], [0.5, 0.5]]140 assert combiner_valeurs(poids, [(2.0, 0.0), (0.0, 4.0)]) == [(2.0, 0.0), (1.0, 2.0)]141142143def test_visualisation_texte():144 lignes = carte_texte(PHRASE_DROIT, attention(PHRASE_DROIT, FICHES)["poids"])145 assert len(lignes) == 4 and lignes[1].count("masqué") == 2 and lignes[2].count("masqué") == 1146 assert "0.67" in lignes[3] and "0.09" in lignes[3] and "0.24" in lignes[3]147 assert len(trame(1.0)) == 4 and trame(0.0).strip() == ""148 assert all(len(ligne) <= 68 for ligne in lignes)149150151def test_demo_s_execute_et_affiche_les_lignes_des_diapositives():152 sortie = subprocess.run([sys.executable, str(DEMO)], capture_output=True, text=True, check=True).stdout153 for ligne in (" cabinet 2.0 7.389 0.665 ################",154 " d' 0.0 1.000 0.090 ##",155 " avocat 1.0 2.718 0.245 ######",156 " total 11.107 1.000",157 " nouveau vecteur d'« avocat » : (1.58, 0.24) [droit, cuisine]",158 " même calcul dans « salade d' avocat » : (0.24, 1.58)",159 " cabinet 0.74 ++++ 0.10 .... 0.16 ....",160 " cabinet 1.00 #### masqué masqué",161 " d' 0.50 ==== 0.50 ==== masqué",162 " avocat 0.67 ++++ 0.09 .... 0.24 ::::",163 " d' cabinet avocat -> (1.58, 0.24) identique : ordre invisible",164 " d' cabinet avocat -> (1.46, 0.49) différent : l'ordre compte",165 " sans attention réputé 0.42 mûr 0.42 . 0.16",166 " cabinet d' avocat réputé 0.68 mûr 0.18 . 0.14 -> réputé",167 " salade d' avocat réputé 0.18 mûr 0.68 . 0.14 -> mûr"):168 assert ligne in sortie, ligne169 assert all(len(ligne) <= 68 for ligne in sortie.splitlines())170 assert all(ligne == ligne.rstrip() for ligne in sortie.splitlines())171172173def test_demo_documentee_a_jour_et_mode_anime_identique():174 sortie = subprocess.run([sys.executable, str(DEMO)], capture_output=True, text=True, check=True).stdout175 assert sortie.strip() in (SESSION / "demos" / "README.md").read_text(encoding="utf-8")176 source = DEMO.read_text(encoding="utf-8")177 assert "PAUSE_SECONDES = 0.6" in source # le mode animé ne change que le rythme d'affichage178 import atlas_s03.demo as demo179 demo.PAUSE_SECONDES = 0.0180 import contextlib181 import io182 tampon = io.StringIO()183 with contextlib.redirect_stdout(tampon):184 demo.main(animer=True)185 assert tampon.getvalue() == sortie186187188def test_donnees_de_figures_a_jour():189 script = SESSION / "demos" / "src" / "atlas_s03" / "exporter_donnees_figure.py"190 assert subprocess.run([sys.executable, str(script), "--check"]).returncode == 0191 f01 = (SESSION / "figures" / "src" / "S03-F01-donnees.tex").read_text(encoding="utf-8")192 for attendu in ("STval@F01-poids-1\\endcsname{0,67}%", "STval@F01-poids-2\\endcsname{0,09}%",193 "STval@F01-poids-3\\endcsname{0,24}", "STval@F01-sortie\\endcsname{(1,58 ; 0,24)}",194 "STval@F01-exp-total\\endcsname{11,11}"):195 assert attendu in f01, attendu196197198def test_aucune_bibliotheque_externe():199 autorises = {"__future__", "math", "sys", "time", "pathlib", "atlas_s03"}200 for fichier in (SESSION / "demos" / "src" / "atlas_s03").glob("*.py"):201 for ligne in fichier.read_text(encoding="utf-8").splitlines():202 mots = ligne.split()203 if len(mots) >= 2 and mots[0] in ("import", "from") and not ligne.startswith(" "):204 assert mots[1].split(".")[0] in autorises, f"{fichier.name} : {ligne}"205