Write an interactive visualization code of self attention of Transformer in HTML and Javascript without any libraries.
Use an example sentence "The quick brown fox"
When hovering over a token, visualize the edges whose thickness are proportional to attention score
THe edges should be curved and should not overlap each other
Make sure that the edges start and end from each token center
When clicked on a token, show the value of attention scores
Visualize this nicely in a latex-rendered vector notation. Put each token next to the score. Make sure the Latex rendering is well-aligned.
When clicked again, remove the attention score vector
have vertical spacing of 50px at the top
Assistant
Here is an interactive visualization of self-attention for the sentence "The quick brown fox" implemented in HTML and JavaScript without any external libraries:
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Self-Attention Visualization</title>
<style>
body {
margin: 0;
padding: 0;
}
#container {
position: relative;
margin-top: 50px; /* Vertical spacing of 50px at the top */
text-align: center;
font-size: 24px;
}
.token {
display: inline-block;
position: relative;
padding: 5px;
cursor: pointer;
}
#svgContainer {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none; /* Allow mouse events to pass through */
overflow: visible;
}
#attentionVector {
margin-top: 20px;
text-align: center;
font-size: 20px;
}
.math-equation {
display: inline-block;
text-align: left;
font-family: 'Times New Roman', Times, serif;
}
.vector-bracket {
font-size: 24px;
vertical-align: top;
}
.vector-content {
display: inline-block;
}
.vector-row {
line-height: 1.5;
}
</style>
</head>
<body>
<div id="container">
<!-- Tokens -->
<span class="token" data-index="0">The</span>
<span class="token" data-index="1">quick</span>
<span class="token" data-index="2">brown</span>
<span class="token" data-index="3">fox</span>
<!-- SVG container for attention lines -->
<svg id="svgContainer"></svg>
<!-- Attention vector display -->
<div id="attentionVector"></div>
</div>
<script>
// Define tokens and attention scores
const tokens = ['The', 'quick', 'brown', 'fox'];
const attentionScores = [
[0.1, 0.4, 0.3, 0.2], // From "The"
[0.3, 0.1, 0.4, 0.2], // From "quick"
[0.25, 0.25, 0.25, 0.25], // From "brown"
[0.4, 0.1, 0.2, 0.3], // From "fox"
];
// Variables to track attention vector display
let attentionVectorVisible = false;
let lastClickedTokenIndex = null;
// Get references to elements
const svgContainer = document.getElementById('svgContainer');
const attentionVector = document.getElementById('attentionVector');
const tokenElements = document.getElementsByClassName('token');
// Add event listeners to tokens
for (let i = 0; i < tokenElements.length; i++) {
const tokenElement = tokenElements[i];
tokenElement.addEventListener('mouseenter', function() {
const index = parseInt(this.getAttribute('data-index'));
drawAttentionLines(index);
});
tokenElement.addEventListener('mouseleave', function() {
clearAttentionLines();
});
tokenElement.addEventListener('click', function() {
const index = parseInt(this.getAttribute('data-index'));
if (attentionVectorVisible && lastClickedTokenIndex === index) {
// Hide the attention vector
attentionVector.innerHTML = '';
attentionVectorVisible = false;
lastClickedTokenIndex = null;
} else {
// Show the attention vector
showAttentionVector(index);
attentionVectorVisible = true;
lastClickedTokenIndex = index;
}
});
}
// Function to get token positions relative to the container
function getTokenPositions() {
const positions = [];
const containerRect = document.getElementById('container').getBoundingClientRect();
for (let i = 0; i < tokenElements.length; i++) {
const tokenElement = tokenElements[i];
const rect = tokenElement.getBoundingClientRect();
const x = rect.left + rect.width / 2 - containerRect.left;
const y = rect.top + rect.height / 2 - containerRect.top;
positions.push({ x, y });
}
return positions;
}
// Function to draw attention lines
function drawAttentionLines(index) {
// Clear previous lines
clearAttentionLines();
const positions = getTokenPositions();
// Set SVG size
const containerRect = document.getElementById('container').getBoundingClientRect();
svgContainer.setAttribute('width', containerRect.width);
svgContainer.setAttribute('height', containerRect.height);
const svgNS = "http://www.w3.org/2000/svg";
// Get starting position
const startPos = positions[index];
for (let i = 0; i < positions.length; i++) {
const endPos = positions[i];
const score = attentionScores[index][i];
// Don't draw if score is zero
if (score > 0) {
const path = document.createElementNS(svgNS, 'path');
path.setAttribute('fill', 'none');
path.setAttribute('stroke', 'rgba(0,0,255,0.5)');
path.setAttribute('stroke-width', score * 10); // Adjust multiplier for suitable thickness
// Calculate curvature to prevent overlapping
let curvature = 50 + Math.abs(index - i) * 20; // Adjust as needed
// Curvature direction
curvature = -curvature;
const controlPoint1 = {
x: startPos.x,
y: startPos.y + curvature
};
const controlPoint2 = {
x: endPos.x,
y: endPos.y + curvature
};
const d = `M ${startPos.x},${startPos.y} C ${controlPoint1.x},${controlPoint1.y} ${controlPoint2.x},${controlPoint2.y} ${endPos.x},${endPos.y}`;
path.setAttribute('d', d);
svgContainer.appendChild(path);
}
}
}
// Function to clear attention lines
function clearAttentionLines() {
while (svgContainer.firstChild) {
svgContainer.removeChild(svgContainer.firstChild);
}
}
// Function to display the attention vector
function showAttentionVector(index) {
// Build the vector component
let vectorHTML = '<div class="math-equation">';
vectorHTML += '<span class="vector-bracket">[</span>';
vectorHTML += '<div class="vector-content">';
for (let i = 0; i < tokens.length; i++) {
vectorHTML += '<div class="vector-row">' + attentionScores[index][i].toFixed(2) + '</div>';
}
vectorHTML += '</div>';
vectorHTML += '<span class="vector-bracket">]</span>';
vectorHTML += '</div>';
// Build tokens alongside scores
let tokensHTML = '<div style="display: inline-block; text-align: left; margin-left: 20px;">';
for (let i = 0; i < tokens.length; i++) {
tokensHTML += '<div class="vector-row">' + tokens[i] + '</div>';
}
tokensHTML += '</div>';
// Combine into a nicely aligned display
attentionVector.innerHTML = `
<div style="display: inline-flex; justify-content: center; align-items: flex-start;">
${vectorHTML}
${tokensHTML}
</div>
`;
}
</script>
</body>
</html>
Instructions:
Hover over a token: When you move your mouse over a word (token), curved edges will appear connecting it to all other tokens. The thickness of each edge is proportional to the attention score between the tokens.
Curved edges: The edges are designed as curved lines to prevent overlapping and start and end at the center of each token.
Click on a token: Clicking on a word will display its attention scores in a vector notation next to the tokens. The scores are aligned with their corresponding tokens for clarity.
Click again: Clicking the same token again will remove the attention scores from the display.
Visualization Details:
Attention Lines: The thickness of the lines is scaled by the attention scores (multiplied by 10 for visibility). The lines use cubic Bézier curves to create smooth, curved edges.
Attention Vector Display: The attention scores are displayed in a vector-like format using simple HTML and CSS to mimic LaTeX rendering. Each score is aligned with its corresponding token.
Layout: There's a 50px vertical space at the top of the container as specified. All elements are centered and aligned for a clean visualization.
Note: This implementation uses pure HTML, CSS, and JavaScript without any external libraries, adhering to your requirements. The attention scores are hardcoded for demonstration purposes and can be adjusted as needed.