juanesvelez commited on
Commit
d742495
1 Parent(s): 98c78fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -33
app.py CHANGED
@@ -1,42 +1,54 @@
1
  import solara
 
2
  import torch
3
  import torch.nn.functional as F
4
  import pandas as pd
5
  from transformers import AutoTokenizer, AutoModelForCausalLM
6
 
7
- # Cargar el modelo y el tokenizer
8
- model_name = "datificate/gpt2-small-spanish"
9
- model = AutoModelForCausalLM.from_pretrained(model_name)
10
- tokenizer = AutoTokenizer.from_pretrained(model_name)
11
-
12
- text = solara.reactive("Escribe algo en español")
13
-
14
  @solara.component
15
  def Page():
16
- with solara.Column(margin=10):
17
- solara.Markdown("# Predicción del Próximo Token")
18
- solara.Markdown("Ingrese un texto en español y vea las predicciones para el próximo token.")
19
-
20
- def on_action_cell(column, row_index):
21
- text.value += tokenizer.decode(top_10.indices[0][row_index])
22
-
23
- cell_actions = [solara.CellAction(icon="mdi-thumb-up", name="Seleccionar", on_click=on_action_cell)]
24
-
25
- solara.InputText("Ingrese texto:", value=text, continuous_update=True)
26
-
27
- if text.value != "":
28
- tokens = tokenizer.encode(text.value, return_tensors="pt")
29
- outputs = model.generate(tokens, max_new_tokens=1, output_scores=True, return_dict_in_generate=True, pad_token_id=tokenizer.eos_token_id)
30
- scores = F.softmax(outputs.scores[0], dim=-1)
31
- top_10 = torch.topk(scores, 10)
32
-
33
- df = pd.DataFrame({
34
- "probs": [f"{value:.2%}" for value in top_10.values[0]],
35
- "next token ID": top_10.indices[0].numpy(),
36
- "predicted next token": [tokenizer.decode([idx]) for idx in top_10.indices[0]]
37
- })
38
-
39
- solara.Markdown("### Predicción")
40
- solara.DataFrame(df, items_per_page=10, cell_actions=cell_actions)
41
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  Page()
 
1
  import solara
2
+ import random
3
  import torch
4
  import torch.nn.functional as F
5
  import pandas as pd
6
  from transformers import AutoTokenizer, AutoModelForCausalLM
7
 
8
+ tokenizer = AutoTokenizer.from_pretrained('datificate/gpt2-small-spanish')
9
+ model = AutoModelForCausalLM.from_pretrained('datificate/gpt2-small-spanish')
10
+ text1 = solara.reactive("Never gonna give you up, never gonna let you")
 
 
 
 
11
  @solara.component
12
  def Page():
13
+ with solara.Column(margin=10):
14
+ solara.Markdown("#Next token prediction visualization")
15
+ solara.Markdown("I built this tool to help me understand autoregressive language models. For any given text, it gives the top 10 candidates to be the next token with their respective probabilities. The language model I'm using is the smallest version of GPT-2, with 124M parameters.")
16
+ def on_action_cell(column, row_index):
17
+ text1.value += tokenizer.decode(top_10.indices[0][row_index])
18
+ cell_actions = [solara.CellAction(icon="mdi-thumb-up", name="Select", on_click=on_action_cell)]
19
+ solara.InputText("Enter text:", value=text1, continuous_update=True)
20
+ if text1.value != "":
21
+ tokens = tokenizer.encode(text1.value, return_tensors="pt")
22
+ spans1 = ""
23
+ spans2 = ""
24
+ for i, token in enumerate(tokens[0]):
25
+ random.seed(i)
26
+ random_color = ''.join([random.choice('0123456789ABCDEF') for k in range(6)])
27
+ spans1 += " " + f"<span style='font-family: helvetica; color: #{random_color}'>{token}</span>"
28
+ spans2 += " " + f"""<span style="
29
+ padding: 6px;
30
+ border-right: 3px solid white;
31
+ line-height: 3em;
32
+ font-family: courier;
33
+ background-color: #{random_color};
34
+ color: white;
35
+ position: relative;
36
+ "><span style="
37
+ position: absolute;
38
+ top: 5.5ch;
39
+ line-height: 1em;
40
+ left: -0.5px;
41
+ font-size: 0.45em"> {token}</span>{tokenizer.decode([token])}</span>"""
42
+ solara.Markdown(f'{spans2}')
43
+ solara.Markdown(f'{spans1}')
44
+ outputs = model.generate(tokens, max_new_tokens=1, output_scores=True, return_dict_in_generate=True, pad_token_id=tokenizer.eos_token_id)
45
+ scores = F.softmax(outputs.scores[0], dim=-1)
46
+ top_10 = torch.topk(scores, 10)
47
+ df = pd.DataFrame()
48
+ df["probs"] = top_10.values[0]
49
+ df["probs"] = [f"{value:.2%}" for value in df["probs"].values]
50
+ df["next token ID"] = [top_10.indices[0][i].numpy() for i in range(10)]
51
+ df["predicted next token"] = [tokenizer.decode(top_10.indices[0][i]) for i in range(10)]
52
+ solara.Markdown("###Prediction")
53
+ solara.DataFrame(df, items_per_page=10, cell_actions=cell_actions)
54
  Page()