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 thicknesses are proportional to the attention score.
The edges should be curved and should not overlap each other.
Make sure that the edges start and end from each token's 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
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
<!DOCTYPE html>
<html>
<head>
<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;
padding: 10px;
cursor: pointer;
position: relative;
}
#svgContainer {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
}
.attention-scores {
text-align: center;
margin-top: 20px;
}
.attention-scores table {
margin: 0 auto;
border-collapse: collapse;
}
.attention-scores td {
padding: 5px;
vertical-align: middle;
}
</style>
</head>
<body>
<div id="container">
<div id="svgContainer"></div>
<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>
</div>
<div class="attention-scores" id="attentionScoresContainer"></div>
<script>
var attentionScores = [
[0.1, 0.3, 0.2, 0.4], // From "The"
[0.2, 0.1, 0.5, 0.2], // From "quick"
[0.3, 0.2, 0.1, 0.4], // From "brown"
[0.25, 0.25, 0.25, 0.25] // From "fox"
];
var tokens = ["The", "quick", "brown", "fox"];
var tokenElements = document.querySelectorAll('.token');
var currentDisplayedScoresIndex = null; // To track if attention scores are displayed
tokenElements.forEach(function(tokenEl) {
tokenEl.addEventListener('mouseover', function() {
var index = parseInt(tokenEl.getAttribute('data-index'));
showAttentionEdges(index);
});
tokenEl.addEventListener('mouseout', function() {
removeAttentionEdges();
});
tokenEl.addEventListener('click', function() {
var index = parseInt(tokenEl.getAttribute('data-index'));
toggleAttentionScores(index);
});
});
function showAttentionEdges(index) {
var svgContainer = document.getElementById('svgContainer');
// Clear previous edges
svgContainer.innerHTML = '';
var svgNS = "http://www.w3.org/2000/svg";
var containerRect = document.getElementById('container').getBoundingClientRect();
// Create the SVG element
var svg = document.createElementNS(svgNS, 'svg');
svg.setAttribute('width', containerRect.width);
svg.setAttribute('height', containerRect.height);
svg.style.position = 'absolute';
svg.style.top = '0';
svg.style.left = '0';
svgContainer.appendChild(svg);
var sourceTokenEl = tokenElements[index];
var sourceRect = sourceTokenEl.getBoundingClientRect();
var sourceX = sourceRect.left + sourceRect.width / 2 - containerRect.left;
var sourceY = sourceRect.top + sourceRect.height / 2 - containerRect.top;
for (var i = 0; i < tokens.length; i++) {
var targetTokenEl = tokenElements[i];
var targetRect = targetTokenEl.getBoundingClientRect();
var targetX = targetRect.left + targetRect.width / 2 - containerRect.left;
var targetY = targetRect.top + targetRect.height / 2 - containerRect.top;
var score = attentionScores[index][i];
var path = document.createElementNS(svgNS, 'path');
var curvature = 50 + 20 * Math.abs(i - index); // Adjust curvature to prevent overlap
var controlX1 = sourceX;
var controlY1 = sourceY - curvature;
var controlX2 = targetX;
var controlY2 = targetY - curvature;
var d = `M ${sourceX},${sourceY} C ${controlX1},${controlY1} ${controlX2},${controlY2} ${targetX},${targetY}`;
path.setAttribute('d', d);
path.setAttribute('stroke', 'blue');
path.setAttribute('fill', 'none');
path.setAttribute('stroke-width', score * 10); // Scale for visibility
path.setAttribute('opacity', 0.7);
svg.appendChild(path);
}
// Prevent mouse events on the svg
svgContainer.style.pointerEvents = 'none';
}
function removeAttentionEdges() {
var svgContainer = document.getElementById('svgContainer');
svgContainer.innerHTML = ''; // Clear the SVG content
}
function toggleAttentionScores(index) {
var attentionScoresContainer = document.getElementById('attentionScoresContainer');
if (currentDisplayedScoresIndex === index) {
// Hide the scores
attentionScoresContainer.innerHTML = '';
currentDisplayedScoresIndex = null;
} else {
// Show the scores
currentDisplayedScoresIndex = index;
showAttentionScores(index);
}
}
function showAttentionScores(index) {
var attentionScoresContainer = document.getElementById('attentionScoresContainer');
attentionScoresContainer.innerHTML = ''; // Clear previous scores
var scores = attentionScores[index];
var table = document.createElement('table');
var tbody = document.createElement('tbody');
for (var i = 0; i < tokens.length; i++) {
var tr = document.createElement('tr');
var tdScore = document.createElement('td');
tdScore.textContent = scores[i].toFixed(2);
tdScore.style.paddingRight = '10px';
tdScore.style.textAlign = 'right';
var tdToken = document.createElement('td');
tdToken.textContent = tokens[i];
tr.appendChild(tdScore);
tr.appendChild(tdToken);
tbody.appendChild(tr);
}
table.appendChild(tbody);
attentionScoresContainer.appendChild(table);
}
</script>
</body>
</html>
Explanation:
We first define the tokens and the attention scores between them.
Each token is represented as a <span> with the class token.
When you hover over a token, the showAttentionEdges function is called, which draws curved edges to all other tokens. The thickness of each edge is proportional to the attention score.
The edges are drawn using SVG paths with Bezier curves to ensure they are curved and do not overlap.
The edges start and end from the center of each token.
When you click on a token, the toggleAttentionScores function shows or hides the attention scores in a neatly aligned HTML table, with each token next to its score.
The attention scores are displayed in the attentionScoresContainer div.
We have ensured there is a vertical spacing of 50px at the top by setting margin-top: 50px on the container.
Note: Since we're not allowed to use any libraries, and rendering LaTeX without libraries is impractical, we've displayed the attention scores in a clean HTML table instead. This ensures the scores are well-aligned with the tokens, satisfying the requirement for neat visualization.