Update app.py
Browse files
app.py
CHANGED
@@ -1,38 +1,49 @@
|
|
1 |
import streamlit as st
|
2 |
-
from transformers import
|
3 |
import torch
|
4 |
import matplotlib.pyplot as plt
|
5 |
import seaborn as sns
|
|
|
6 |
|
7 |
-
#
|
8 |
-
st.set_page_config(page_title="Transflower ๐ธ", layout="centered")
|
9 |
-
|
10 |
-
st.markdown(
|
|
|
|
|
|
|
|
|
11 |
|
12 |
# Load model and tokenizer
|
13 |
-
model_name = "
|
14 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
15 |
model = AutoModelForSeq2SeqLM.from_pretrained(model_name, output_attentions=True)
|
16 |
|
17 |
-
#
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
if
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
3 |
import torch
|
4 |
import matplotlib.pyplot as plt
|
5 |
import seaborn as sns
|
6 |
+
import numpy as np
|
7 |
|
8 |
+
# Page setup
|
9 |
+
st.set_page_config(page_title="Transflower ๐ธ", page_icon="๐ผ", layout="centered")
|
10 |
+
|
11 |
+
st.markdown(
|
12 |
+
"<h1 style='text-align: center; color: pink;'>๐ธ Transflower ๐ธ</h1>"
|
13 |
+
"<p style='text-align: center; color: gray;'>A girly and cute app to visualize Transformer magic</p>",
|
14 |
+
unsafe_allow_html=True,
|
15 |
+
)
|
16 |
|
17 |
# Load model and tokenizer
|
18 |
+
model_name = "t5-small"
|
19 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
20 |
model = AutoModelForSeq2SeqLM.from_pretrained(model_name, output_attentions=True)
|
21 |
|
22 |
+
# Input area
|
23 |
+
user_input = st.text_area("๐ผ Enter text to summarize or visualize:", height=200)
|
24 |
+
|
25 |
+
if st.button("โจ Visualize Transformer Magic โจ"):
|
26 |
+
if not user_input.strip():
|
27 |
+
st.warning("Please enter some text to visualize.")
|
28 |
+
else:
|
29 |
+
# Prepare input
|
30 |
+
input_ids = tokenizer.encode("summarize: " + user_input, return_tensors="pt", max_length=512, truncation=True)
|
31 |
+
|
32 |
+
# Forward pass with attentions
|
33 |
+
with torch.no_grad():
|
34 |
+
outputs = model.generate(input_ids, output_attentions=True, return_dict_in_generate=True, output_scores=True)
|
35 |
+
decoded = tokenizer.decode(outputs.sequences[0], skip_special_tokens=True)
|
36 |
+
|
37 |
+
st.subheader("๐ธ Summary:")
|
38 |
+
st.success(decoded)
|
39 |
+
|
40 |
+
# Visualization
|
41 |
+
st.subheader("๐ Attention Heatmap:")
|
42 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
43 |
+
|
44 |
+
# Get decoder self-attention from the last layer
|
45 |
+
attention_data = outputs.attentions[-1] # List of attention tensors from each layer
|
46 |
+
avg_attention = attention_data[0].mean(dim=0).squeeze().detach().numpy() # mean over heads
|
47 |
+
|
48 |
+
sns.heatmap(avg_attention, cmap="coolwarm", ax=ax)
|
49 |
+
st.pyplot(fig)
|