kcarnold commited on
Commit
65b683f
1 Parent(s): 7a29ce2
Files changed (2) hide show
  1. next_token.py +68 -0
  2. requirements.txt +2 -0
next_token.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import transformers
7
+ import pandas as pd
8
+
9
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
+
11
+ from transformers import MarianMTModel, MarianTokenizer
12
+ model_name = 'Helsinki-NLP/opus-mt-ROMANCE-en'
13
+
14
+ @st.cache_resource
15
+ def get_tokenizer(model_name):
16
+ return MarianTokenizer.from_pretrained(model_name)
17
+
18
+ @st.cache_resource
19
+ def get_model(model_name):
20
+ return MarianMTModel.from_pretrained(model_name).to(device)
21
+
22
+ tokenizer = get_tokenizer(model_name)
23
+ model = get_model(model_name)
24
+
25
+ print(f"The model has {model.num_parameters():,d} parameters.")
26
+
27
+ input_text = st.text_input("Enter text to translate", "Hola, mi nombre es Juan")
28
+ input_text = input_text.strip()
29
+ if not input_text:
30
+ st.stop()
31
+
32
+ output_so_far = st.text_input("Enter text translated so far", "Hello, my")
33
+
34
+ input_ids = tokenizer(input_text, return_tensors="pt").input_ids.to(device)
35
+
36
+ # tokenize the output so far
37
+ with tokenizer.as_target_tokenizer():
38
+ output_tokens = tokenizer.tokenize(output_so_far)
39
+ decoder_input_ids = tokenizer.convert_tokens_to_ids(output_tokens)
40
+
41
+ # Add the start token
42
+ decoder_input_ids = [model.config.decoder_start_token_id] + decoder_input_ids
43
+
44
+ with torch.no_grad():
45
+ model_output = model(
46
+ input_ids = input_ids,
47
+ decoder_input_ids = torch.tensor([decoder_input_ids]).to(device))
48
+
49
+
50
+ last_token_logits = model_output.logits[0, -1].cpu()
51
+ assert len(last_token_logits.shape) == 1
52
+ most_likely_tokens = last_token_logits.topk(k=5)
53
+
54
+ probs = last_token_logits.softmax(dim=-1)
55
+ probs_for_likely_tokens = probs[most_likely_tokens.indices]
56
+
57
+ with tokenizer.as_target_tokenizer():
58
+ probs_table = pd.DataFrame({
59
+ 'token': [tokenizer.decode(token_id) for token_id in most_likely_tokens.indices],
60
+ 'id': most_likely_tokens.indices,
61
+ 'probability': probs_for_likely_tokens,
62
+ 'logprob': probs_for_likely_tokens.log(),
63
+ 'cumulative probability': probs_for_likely_tokens.cumsum(0)
64
+ })
65
+
66
+
67
+ st.write(probs_table)
68
+ st.write(model.config.decoder_start_token_id)
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ transformers
2
+ pandas