Repository Public MIT Research preview
1"""Tests de la démonstration S02 : chaque chiffre affiché dans les diapositives et les figures est vérifié ici."""2from __future__ import annotations34import math5import subprocess6import sys7from pathlib import Path89SESSION = Path(__file__).resolve().parents[2]10sys.path.insert(0, str(SESSION / "demos" / "src"))1112from atlas_s02.corpus import (CORPUS, NOMBRE_FUSIONS, PHRASE_CONNUE, PHRASE_RARE, PHRASES_NOUVELLES, # noqa: E40213 SCENARIO_FICTIF)14from atlas_s02.cout import bilan, cout, delai, occupation # noqa: E40215from atlas_s02.echantillonnage import (appliquer_temperature, compter_tirages, garder_k_premiers, generer, # noqa: E40216 glouton)17from atlas_s02.entrainement import entrainer_apres, evaluer, nombre_parametres, softmax, surprise # noqa: E40218from atlas_s02.jetons import (JETON_INCONNU, apprendre_fusions, construire_vocabulaire, decouper, decouper_mot, # noqa: E40219 encoder, phrases_en_jetons)20from atlas_s02.modele import compter_suites, distribution_suivant, vocabulaire # noqa: E40221from atlas_s02.plongements import similarite # noqa: E4022223FUSIONS = apprendre_fusions(CORPUS, NOMBRE_FUSIONS)24VOCAB = construire_vocabulaire(CORPUS, FUSIONS)25APRES_LE = distribution_suivant(compter_suites(CORPUS, 1), ("le",))262728# ---- Section 1 : jetons ---------------------------------------------------------------------------2930def test_sept_premieres_fusions(): # diapositive S02-D0731 assert [(g + " + " + d, n) for (g, d), n in FUSIONS[:7]] == [32 ("l + e", 19), ("c + h", 10), ("a + n", 9), ("u + r", 9), ("i + s", 8), ("a + t", 6), ("ch + at", 6)]333435def test_taille_du_vocabulaire(): # S02-D07 : 41 = 19 lettres + point + 20 fusions + inconnu36 lettres = {c for phrase in CORPUS for mot in phrase.split() for c in mot}37 assert len(lettres) == 20 and "." in lettres38 assert len(FUSIONS) == 20 and len(VOCAB) == 41 and VOCAB[JETON_INCONNU] == 0394041def test_decoupages_des_diapositives(): # S02-D09, S02-D2442 assert decouper(PHRASE_CONNUE, FUSIONS) == "le chat dort sur le t ap is .".split()43 assert decouper(PHRASE_RARE, FUSIONS) == "le chat o n dort sur la ch a is e .".split()44 assert len(PHRASE_CONNUE.split()) == len(PHRASE_RARE.split()) == 745 assert decouper_mot("chaton", FUSIONS) == ["chat", "o", "n"] # S02-D23 : trois jetons464748def test_identifiants_et_lettre_inconnue(): # figure S02-F0149 assert encoder("le chaton dort sur le", FUSIONS, VOCAB) == [21, 27, 14, 13, 40, 31, 21]50 assert encoder("le zèbre", FUSIONS, VOCAB) == [21, 0, 0, 0, 16, 5]51 for phrase in CORPUS + [PHRASE_RARE]:52 assert "".join(decouper(phrase, FUSIONS)) == phrase.replace(" ", "")535455def test_exercice_avec_sept_fusions(): # S02-D3056 sept = FUSIONS[:7]57 assert decouper("le chien", sept) == ["le", "ch", "i", "e", "n"]58 assert decouper("la chatte", sept) == ["l", "a", "chat", "t", "e"]596061def test_generation_par_jetons_de_la_figure(): # figure S02-F01, étapes 4 à 662 suites = compter_suites(phrases_en_jetons(CORPUS, FUSIONS), 2)63 assert distribution_suivant(suites, ("sur", "le")) == {"t": 0.6, "c": 0.4}64 assert distribution_suivant(suites, ("le", "t")) == {"ap": 1.0}65 assert distribution_suivant(suites, ("t", "ap")) == {"is": 1.0}666768def test_similarites(): # S02-D1069 valeurs = [round(similarite(CORPUS, "chat", autre), 2) for autre in ("chien", "tapis", "souris", "dort")]70 assert valeurs == [0.98, 0.75, 0.17, 0.0]71 assert math.isclose(similarite(CORPUS, "chat", "chat"), 1.0)727374# ---- Section 2 : entraînement, inférence, paramètres ---------------------------------------------7576def test_entrainement_reduit_la_surprise(): # S02-D1277 h = entrainer_apres(CORPUS, "le", 1000)78 assert [round(h[e]["perte"], 3) for e in (0, 10, 100, 1000)] == [2.890, 2.143, 1.815, 1.772]79 assert [round(h[e]["distribution"]["chat"], 3) for e in (0, 10, 100, 1000)] == [0.056, 0.240, 0.310, 0.315]80 assert all(a["perte"] > b["perte"] for a, b in zip(h, h[1:]))81 assert len(vocabulaire(CORPUS)) == 18 and math.isclose(h[0]["distribution"]["chat"], 1 / 18)82 assert math.isclose(h[0]["perte"], surprise(1 / 18)) and round(6 / 19, 3) == 0.31683 plancher = sum(p * surprise(p) for p in APRES_LE.values())84 assert h[1000]["perte"] > plancher and h[1000]["perte"] - plancher < 0.0385 assert math.isclose(sum(softmax([0.3, -1.0, 2.0])), 1.0)868788def test_plus_de_parametres_pas_meilleur(): # S02-D15, S02-D2489 e = {n: evaluer(CORPUS, PHRASES_NOUVELLES, n) for n in (1, 2, 3)}90 assert [e[n]["parametres"] for n in (1, 2, 3)] == [324, 5832, 104976]91 assert [(e[n]["prevus"], e[n]["predictions"]) for n in (1, 2, 3)] == [(34, 34), (23, 28), (11, 22)]92 assert [round(100 * e[n]["prevus"] / e[n]["predictions"]) for n in (1, 2, 3)] == [100, 82, 50]93 assert e[3]["parametres"] // e[1]["parametres"] == 324 and nombre_parametres(18, 1) == 32494 assert e[3]["cases_remplies"] < 0.001 * e[3]["parametres"] # presque toutes les cases restent vides95 assert not set(PHRASES_NOUVELLES) & set(CORPUS)969798# ---- Section 3 : échantillonnage ------------------------------------------------------------------99100def test_temperature_exemple_guide(): # S02-D17101 d = distribution_suivant(compter_suites(CORPUS, 2), ("sur", "le"))102 assert d == {"tapis": 0.6, "canapé": 0.4}103 assert [round(appliquer_temperature(d, t)["tapis"], 2) for t in (0.5, 1.0, 2.0)] == [0.69, 0.60, 0.55]104 assert [round(appliquer_temperature(d, t)["canapé"], 2) for t in (0.5, 1.0, 2.0)] == [0.31, 0.40, 0.45]105 assert round(0.6 ** 2 + 0.4 ** 2, 2) == 0.52106107108def test_temperature_figure(): # figure S02-F03, S02-D25109 froid, chaud = appliquer_temperature(APRES_LE, 0.5), appliquer_temperature(APRES_LE, 2.0)110 assert [round(p, 3) for p in froid.values()] == [0.507, 0.225, 0.127, 0.056, 0.056, 0.014, 0.014]111 assert [round(p, 3) for p in chaud.values()] == [0.222, 0.182, 0.157, 0.128, 0.128, 0.091, 0.091]112 for d in (froid, chaud, appliquer_temperature(APRES_LE, 1.0)):113 assert math.isclose(sum(d.values()), 1.0) and list(d) == list(APRES_LE) # l'ordre ne change jamais114 assert all(math.isclose(appliquer_temperature(APRES_LE, 1.0)[m], p) for m, p in APRES_LE.items())115116117def test_exercice_temperature(): # S02-D30 et laboratoire, parcours A118 d = appliquer_temperature({"souris": 0.8, "cuisine": 0.2}, 0.5)119 assert [round(p, 2) for p in d.values()] == [0.94, 0.06]120 d = appliquer_temperature({"souris": 0.8, "cuisine": 0.2}, 2.0)121 assert [round(p, 2) for p in d.values()] == [0.67, 0.33]122123124def test_glouton_tourne_en_rond(): # S02-D19125 un_mot = compter_suites(CORPUS, 1)126 assert glouton(APRES_LE) == "chat"127 assert " ".join(generer(un_mot, ["le"], None)) == "le chat dort sur le chat dort sur le chat dort sur"128 assert generer(un_mot, ["le"], None) == generer(un_mot, ["le"], None, graine=99) # aucun hasard129130131def test_generations_affichees(): # S02-D25132 un_mot = compter_suites(CORPUS, 1)133 assert " ".join(generer(un_mot, ["le"], 0.5, 1)) == "le chat mange sur le chat dort sur le chat dort sur"134 assert " ".join(generer(un_mot, ["le"], 2.0, 1)) == "le chat regarde le chien joue dans la cuisine ."135 for graine in range(30):136 texte = generer(un_mot, ["le"], 2.0, graine)137 assert len(texte) <= 12 and (texte[-1] == "." or len(texte) == 12)138139140def test_tirages_et_troncature(): # S02-D16141 tirages = compter_tirages(APRES_LE, 1000, graine=1)142 assert sum(tirages.values()) == 1000 and tirages["chat"] == 298 and tirages["grenier"] == 59143 assert round(APRES_LE["chat"], 2) == 0.32144 k3 = garder_k_premiers(APRES_LE, 3)145 assert set(k3) == {"chat", "chien", "tapis"} and math.isclose(k3["chat"], 6 / 13)146147148# ---- Section 4 : coût, délai, contexte (scénario fictif) ----------------------------------------149150def test_facture_fictive(): # S02-D21151 s, b = SCENARIO_FICTIF, bilan(SCENARIO_FICTIF)152 assert (s["documents"], s["jetons_consigne"], s["jetons_document"], s["jetons_reponse"]) == (200, 120, 1800, 250)153 assert (s["prix_entree_par_million"], s["prix_sortie_par_million"]) == (2.0, 8.0)154 assert (b["jetons_entree"], b["jetons_sortie"]) == (384000, 50000)155 assert b["jetons_entree"] + b["jetons_sortie"] == 434000156 assert [f"{b[k]:.2f}" for k in ("cout_entree", "cout_sortie", "cout_total")] == ["0.77", "0.40", "1.17"]157 assert round(100 * b["part_sortie_jetons"]) == 12 and round(100 * b["part_sortie_cout"]) == 34158 assert math.isclose(cout(1_000_000, 0, 2.0, 8.0), 2.0) and math.isclose(cout(0, 1_000_000, 2.0, 8.0), 8.0)159160161def test_delai_fictif(): # S02-D22162 b = bilan(SCENARIO_FICTIF)163 assert math.isclose(b["delai_par_appel_s"], 6.85) and round(b["delai_total_min"], 1) == 22.8164 assert delai(500, 0.6, 40.0) > delai(250, 0.6, 40.0)165166167def test_budget_de_contexte(): # figure S02-F04168 b = bilan(SCENARIO_FICTIF)169 assert b["occupation"] == {"jetons": 2170, "part": 0.5425, "libres": 1830, "deborde": False}170 assert b["occupation_long"]["jetons"] == 4870 and b["occupation_long"]["libres"] == -870171 assert b["occupation_long"]["deborde"] and not occupation(700, 300, 1000)["deborde"]172173174# ---- Cohérence d'ensemble -------------------------------------------------------------------------175176def test_demo_s_execute_et_affiche_les_lignes_des_diapositives():177 sortie = subprocess.run([sys.executable, str(SESSION / "demos" / "src" / "atlas_s02" / "demo.py")],178 capture_output=True, text=True, check=True).stdout179 for ligne in (" fusion 7 : ch + at -> chat (vue 6 fois)", " « le chaton dort sur la chaise . »",180 " 7 mots -> 12 jetons", " le | chat | o | n | dort | sur | la | ch | a | is | e | .",181 " contexte de 3 mots : 104 976 paramètres ; mots prévus 11/22 (50%)",182 " mot T = 0.5 T = 1 T = 2", " chat 0.507 0.316 0.222",183 " grenier 0.014 0.053 0.091",184 " choix glouton : le chat dort sur le chat dort sur le chat dort sur ...",185 " T = 0.5 graine 1 : le chat mange sur le chat dort sur le chat dort sur",186 " T = 2.0 graine 1 : le chat regarde le chien joue dans la cuisine ."):187 assert ligne in sortie, ligne188 assert sortie.strip() in (SESSION / "demos" / "README.md").read_text(encoding="utf-8")189190191def test_lignes_de_terminal_des_diapositives_sont_reelles():192 """Toute ligne d'un bloc AtlasTerminal du diaporama (sauf la commande) figure dans la sortie réelle."""193 import re194 sortie = subprocess.run([sys.executable, str(SESSION / "demos" / "src" / "atlas_s02" / "demo.py")],195 capture_output=True, text=True, check=True).stdout196 trouvees = 0197 for fichier in sorted((SESSION / "slides" / "sections").glob("*.tex")):198 for bloc in re.findall(r"\\begin\{AtlasTerminal\}\{[^}]*\}\n(.*?)\\end\{AtlasTerminal\}",199 fichier.read_text(encoding="utf-8"), flags=re.S):200 for ligne in bloc.splitlines():201 if ligne.strip() and not ligne.startswith("$ "):202 assert ligne in sortie, f"{fichier.name} : {ligne!r}"203 trouvees += 1204 assert trouvees >= 10205206207def test_donnees_de_figure_a_jour():208 script = SESSION / "demos" / "src" / "atlas_s02" / "exporter_donnees_figure.py"209 assert subprocess.run([sys.executable, str(script), "--check"]).returncode == 0210 f01 = (SESSION / "figures" / "src" / "S02-F01-donnees.tex").read_text(encoding="utf-8")211 assert "le/21,chat/27,o/14,n/13,dort/40,sur/31,le/21" in f01 and "\\def\\AtlasFigMotProduit{tapis}" in f01212 f04 = (SESSION / "figures" / "src" / "S02-F04-donnees.tex").read_text(encoding="utf-8")213 assert "\\def\\AtlasFigDepassement{870}" in f04 and "\\def\\AtlasFigPart{54}" in f04214215216def test_nombres_du_quiz(): # quizzes/questions.yaml : Q01, Q03, Q10217 assert decouper("le chaton dort", FUSIONS) == ["le", "chat", "o", "n", "dort"]218 assert math.isclose(cout(100 * 1000, 0, 2.0, 8.0), 0.20) and math.isclose(cout(0, 100 * 200, 2.0, 8.0), 0.16)219 assert math.isclose(cout(100 * 1000, 100 * 200, 2.0, 8.0), 0.36)220 assert math.isclose(cout(120000, 0, 2.0, 8.0), 0.24) and math.isclose(cout(0, 120000, 2.0, 8.0), 0.96)221 assert occupation(120 + 4500, 250, 4000)["libres"] == -870222 assert [round(p, 2) for p in (APRES_LE["chat"], appliquer_temperature(APRES_LE, 2.0)["chat"])] == [0.32, 0.22]223 assert [round(p, 2) for p in (APRES_LE["grenier"], appliquer_temperature(APRES_LE, 2.0)["grenier"])] == [0.05, 0.09]224