Here are a handful of “visual” demos you can code up to showcase various LLM capabilities—from inner workings (attention, embeddings) to higher-level reasoning (chains of thought, agents). Feel free to pick one (or mix & match!) and hack on it with your favorite LLM (OpenAI, Llama, Bloom…).
1. Attention-Head Heatmaps (BertViz) 🔥
Show token-to-token attention scores in an interactive web UI.
pip install transformers bertviz torch
from transformers import AutoTokenizer, AutoModel
from bertviz import head_view
model_name = "gpt2" # or any HF‐compatible transformer
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name, output_attentions=True)
text = "The quick brown fox jumps over the lazy dog."
inputs = tokenizer(text, return_tensors='pt')
outputs = model(**inputs)
# launches a small HTML visualization in your browser
head_view(attentions=outputs.attentions,
tokens=tokenizer.convert_ids_to_tokens(inputs["input_ids"][0]))
→ Explore each layer & attention head with hover/zoom.
2. Embedding Projector (t-SNE / UMAP + Plotly) 🎨
Plot sentence‐ or token‐embeddings in 2D/3D and cluster them by semantic similarity.
import plotly.express as px
from sklearn.manifold import TSNE
from transformers import AutoTokenizer, AutoModel
# 1. get embeddings
texts = ["I love pizza.", "Pasta is great!", "The sky is blue.", "Roses are red."]
tok = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
mdl = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
embs = mdl(**tok(texts, padding=True, return_tensors="pt"))[0][:,0,:].detach().numpy()
# 2. reduce
proj = TSNE(n_components=2).fit_transform(embs)
# 3. plot
fig = px.scatter(x=proj[:,0], y=proj[:,1], text=texts, title="t-SNE on Sentence Embeddings")
fig.show()
→ Interactively hover to see which sentences cluster together.
3. Chain-of-Thought Graphs (Graphviz / NetworkX) 🧠
Visualize how an LLM breaks down a problem into sub-steps.
digraph CoT {
node [shape=box, style=filled, color="#EFEFEF"];
“Q: Solve 12*34?” -> “Step1: 12*30 = 360” -> “Step2: 12*4 = 48”
“Step1: 12*30 = 360” -> “Sum = 360 + 48”
“Sum = 408” -> “A: 408”
}
Render via:
pip install graphviz
# save above as cot.dot
dot -Tpng cot.dot -o cot.png
→ Shows each reasoning bubble and how they link.
4. LangChain Agent Trace (Chain Visualizer) 🤖
When you use LangChain’s tools/agents, it can spit out a Graphviz trace:
from langchain import OpenAI, LLMChain
from langchain.agents import initialize_agent, Tool
tools = [Tool(name="Calculator", func=lambda x: eval(x), description="math")]
llm = OpenAI(temperature=0)
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
# This prints a .gv file in the working dir
agent.run("What is 17*23 plus 5?")
Open the generated agent.gv in a Graphviz viewer to see each Thought → Action → Observation step.
5. Token-Generation Trace with Streamlit + ECharts 📈
Build a small web app to show probabilities/top-k for each generated token in real time.
pip install streamlit openai
# app.py
import streamlit as st, openai
openai.api_key = "…"
st.title("LLM Token Generation Trace")
prompt = st.text_area("Prompt", "The meaning of life is")
if st.button("Generate"):
resp = openai.ChatCompletion.create(
model="gpt-4o-mini", prompt=prompt, max_tokens=20, stream=True)
tokens = []; probs = []
for chunk in resp:
tok = chunk.choices[0].delta.get("content", "")
# simulate a probability (for demo)
p = 0.9 - 0.01*len(tokens)
tokens.append(tok); probs.append(max(p, 0.01))
st.write(f"{tok!r} – prob: {p:.2f}")
st.line_chart(probs)
Run with streamlit run app.py.
6. Similarity-Heatmap Across Multiple Prompts 🗞️
Test how varying prompts affect embeddings or answer style:
import seaborn as sns, matplotlib.pyplot as plt
from sklearn.metrics.pairwise import cosine_similarity
prompts = ["Define chain of thought", "Explain reasoning steps", "What is chain-of-thought?"]
# embed each prompt as before into `embs`
sim = cosine_similarity(embs, embs)
sns.heatmap(sim, annot=True, cmap="Blues", xticklabels=prompts, yticklabels=prompts)
plt.title("Prompt Similarity Heatmap")
plt.show()
→ Visually cluster near-duplicate prompts.
7. 3D Transformer Architecture (TensorSpace.js) 🕹️
If you really want to wow ’em, embed your transformer into a webpage:
<script src="https://cdn.jsdelivr.net/npm/tensorspace@1.0.0/dist/tensorspace.min.js"></script>
<script>
const modelConfig = { /* JSON describing layers, heads… */ };
const viewer = new ts.ModelViewer();
viewer.model = new ts.models.Transformer(modelConfig);
document.body.appendChild(viewer.domElement);
</script>
→ Rotate/zoom each multi-head attention block in 3D!
8. Explainability with SHAP / LIME 🕵️
Use SHAP to attribute which words influenced the LLM’s decision (e.g. sentiment or classification).
pip install shap
import shap
# wrap your LLM prediction fn for classification, then...
explainer = shap.Explainer(predict_fn, tokenizer)
shap_values = explainer(["I hated the movie", "I loved the movie"])
shap.plots.text(shap_values[0])
Pick any of the above to demo live—your audience can see the “black-box” become a whiteboard. 🎉 Which one catches your eye? Or do you want code deeper on a specific demo?