File size: 7,002 Bytes
60b53a6
 
33f0de1
6696db2
33f0de1
60b53a6
3c28324
60b53a6
3c28324
9787d82
33f0de1
ea35578
2759f98
33f0de1
 
19de71a
 
 
6696db2
 
 
 
 
 
 
 
 
60b53a6
 
 
33f0de1
 
 
60b53a6
3c28324
33f0de1
bdd35f2
3c28324
 
 
 
 
 
 
391d3d3
 
3c28324
 
 
 
bdd35f2
 
 
6696db2
3226776
33f0de1
6696db2
bdd35f2
 
 
391d3d3
33f0de1
bdd35f2
 
bd87014
bdd35f2
3226776
 
e1ef0ab
 
 
3226776
63afc3f
3226776
bdd35f2
e1ef0ab
 
 
bd87014
 
63afc3f
e1ef0ab
 
bd87014
0c7cad3
bd87014
3226776
 
 
 
 
 
 
 
 
391d3d3
3226776
 
 
 
 
3c28324
3226776
 
 
 
 
 
3c28324
bdd35f2
3226776
33f0de1
 
 
 
 
bd87014
 
33f0de1
 
 
e1ef0ab
bd87014
 
 
 
e1ef0ab
bd87014
 
e1ef0ab
33f0de1
 
60b53a6
bd87014
3c28324
e1ef0ab
bd87014
 
e1ef0ab
bd87014
 
e1ef0ab
bd87014
3c28324
 
 
33f0de1
bdd35f2
 
 
3226776
19de71a
33f0de1
bd87014
33f0de1
 
 
 
 
 
 
 
 
 
 
0c7cad3
3226776
33f0de1
3226776
33f0de1
3c28324
bd87014
3c28324
33f0de1
63afc3f
3c28324
3226776
33f0de1
 
 
3226776
 
bd87014
33f0de1
 
3c28324
33f0de1
bd87014
60b53a6
0c7cad3
 
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
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from huggingface_hub import login
import os
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import time

# Authentification
login(token=os.environ["HF_TOKEN"])

# Liste des modèles
models = [
    "meta-llama/Llama-2-13b-hf",
    "meta-llama/Llama-2-7b-hf",
    "meta-llama/Llama-2-70b-hf",
    "meta-llama/Meta-Llama-3-8B",
    "meta-llama/Llama-3.2-3B",
    "meta-llama/Llama-3.1-8B",
    "mistralai/Mistral-7B-v0.1",
    "mistralai/Mixtral-8x7B-v0.1",
    "mistralai/Mistral-7B-v0.3",
    "google/gemma-2-2b",
    "google/gemma-2-9b",
    "google/gemma-2-27b",
    "croissantllm/CroissantLLMBase"
]

# Variables globales
model = None
tokenizer = None

def load_model(model_name, progress=gr.Progress()):
    global model, tokenizer
    try:
        for i in progress.tqdm(range(100)):
            time.sleep(0.01)  # Simuler le chargement
            if i == 25:
                tokenizer = AutoTokenizer.from_pretrained(model_name)
            elif i == 75:
                model = AutoModelForCausalLM.from_pretrained(
                    model_name, 
                    torch_dtype=torch.float32,
                    device_map="cpu",
                    attn_implementation="eager"
                )
                if tokenizer.pad_token is None:
                    tokenizer.pad_token = tokenizer.eos_token
        return f"Modèle {model_name} chargé avec succès."
    except Exception as e:
        return f"Erreur lors du chargement du modèle : {str(e)}"

def analyze_next_token(input_text, temperature, top_p, top_k):
    global model, tokenizer
    
    if model is None or tokenizer is None:
        return "Veuillez d'abord charger un modèle.", None, None

    inputs = tokenizer(input_text, return_tensors="pt", padding=True, truncation=True, max_length=512)
    
    try:
        with torch.no_grad():
            outputs = model(**inputs, output_attentions=True)
        
        last_token_logits = outputs.logits[0, -1, :]
        probabilities = torch.nn.functional.softmax(last_token_logits, dim=-1)
        
        # Obtenir les 10 tokens les plus probables
        top_k = 10
        top_probs, top_indices = torch.topk(probabilities, top_k)
        top_words = [tokenizer.decode([idx.item()]).strip() for idx in top_indices]
        prob_data = {word: prob.item() for word, prob in zip(top_words, top_probs)}
        
        # Créer un texte explicatif
        prob_text = "Prochains tokens les plus probables :\n\n"
        for word, prob in prob_data.items():
            escaped_word = word.replace("<", "&lt;").replace(">", "&gt;")
            prob_text += f"{escaped_word}: {prob:.2%}\n"
        
        # Créer les visualisations
        prob_plot = plot_probabilities(prob_data)
        attention_plot = plot_attention(inputs["input_ids"][0], outputs.attentions)
        
        return prob_text, attention_plot, prob_plot
    except Exception as e:
        return f"Erreur lors de l'analyse : {str(e)}", None, None

def generate_text(input_text, temperature, top_p, top_k):
    global model, tokenizer
    
    if model is None or tokenizer is None:
        return "Veuillez d'abord charger un modèle."

    inputs = tokenizer(input_text, return_tensors="pt", padding=True, truncation=True, max_length=512)
    
    try:
        with torch.no_grad():
            outputs = model.generate(
                **inputs,
                max_new_tokens=1,
                temperature=temperature,
                top_p=top_p,
                top_k=top_k
            )
        
        generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
        return generated_text  # Retourne l'input + le nouveau mot
    except Exception as e:
        return f"Erreur lors de la génération : {str(e)}"

def plot_probabilities(prob_data):
    words = list(prob_data.keys())
    probs = list(prob_data.values())
    
    fig, ax = plt.subplots(figsize=(12, 6))
    bars = ax.bar(range(len(words)), probs, color='lightgreen')
    ax.set_title("Probabilités des tokens suivants les plus probables")
    ax.set_xlabel("Tokens")
    ax.set_ylabel("Probabilité")
    
    ax.set_xticks(range(len(words)))
    ax.set_xticklabels(words, rotation=45, ha='right')
    
    for i, (bar, word) in enumerate(zip(bars, words)):
        height = bar.get_height()
        ax.text(i, height, f'{word}\n{height:.2%}',
                ha='center', va='bottom', rotation=0)
    
    plt.tight_layout()
    return fig

def plot_attention(input_ids, attention_outputs):
    input_tokens = tokenizer.convert_ids_to_tokens(input_ids)
    
    # Prendre la moyenne des attentions sur toutes les couches et têtes
    attention = torch.mean(torch.cat(attention_outputs), dim=(0, 1)).cpu().numpy()
    
    fig, ax = plt.subplots(figsize=(12, 10))
    sns.heatmap(attention, annot=True, cmap="YlOrRd", xticklabels=input_tokens, yticklabels=input_tokens, ax=ax)
    
    ax.set_title("Carte d'attention moyenne")
    plt.tight_layout()
    return fig

def reset():
    global model, tokenizer
    model = None
    tokenizer = None
    return "", 1.0, 1.0, 50, None, None, None, None

with gr.Blocks() as demo:
    gr.Markdown("# Analyse et génération de texte")
    
    with gr.Accordion("Sélection du modèle"):
        model_dropdown = gr.Dropdown(choices=models, label="Choisissez un modèle")
        load_button = gr.Button("Charger le modèle")
        load_output = gr.Textbox(label="Statut du chargement")
    
    with gr.Row():
        temperature = gr.Slider(0.1, 2.0, value=1.0, label="Température")
        top_p = gr.Slider(0.1, 1.0, value=1.0, label="Top-p")
        top_k = gr.Slider(1, 100, value=50, step=1, label="Top-k")
    
    input_text = gr.Textbox(label="Texte d'entrée", lines=3)
    analyze_button = gr.Button("Analyser le prochain token")
    
    next_token_probs = gr.Textbox(label="Probabilités du prochain token")
    
    with gr.Row():
        attention_plot = gr.Plot(label="Visualisation de l'attention")
        prob_plot = gr.Plot(label="Probabilités des tokens suivants")
    
    generate_button = gr.Button("Générer le prochain mot")
    generated_text = gr.Textbox(label="Texte généré")
    
    reset_button = gr.Button("Réinitialiser")
    
    load_button.click(load_model, inputs=[model_dropdown], outputs=[load_output])
    analyze_button.click(analyze_next_token, 
                         inputs=[input_text, temperature, top_p, top_k], 
                         outputs=[next_token_probs, attention_plot, prob_plot])
    generate_button.click(generate_text, 
                          inputs=[input_text, temperature, top_p, top_k], 
                          outputs=[generated_text])
    reset_button.click(reset, 
                       outputs=[input_text, temperature, top_p, top_k, next_token_probs, attention_plot, prob_plot, generated_text])

if __name__ == "__main__":
    demo.launch()