Here's an HTML and JavaScript code for an interactive visualization of self-attention of a Transformer, based on your specifications.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Self-Attention Visualization</title>
<style>
body {
margin: 0;
padding: 50px 0 0 0; /* 50px spacing at the top */
text-align: center;
position: relative;
}
.token {
display: inline-block;
margin: 0 10px;
position: relative;
cursor: pointer;
font-size: 24px;
}
#svgContainer {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none; /* Allows pointer events to pass through */
}
.attention-scores {
margin-top: 20px;
font-size: 20px;
text-align: center;
line-height: 1.2;
}
.attention-scores div {
display: inline-block;
vertical-align: top;
}
.attention-scores .vector {
text-align: left;
}
.attention-scores .vector div {
padding: 2px 0;
}
</style>
</head>
<body>
<div id="sentence"></div>
<svg id="svgContainer"></svg>
<div id="attentionScores" class="attention-scores"></div>
<script>
var tokens = ["The", "quick", "brown", "fox"];
var attentionScores = {
"The": [0.1, 0.4, 0.3, 0.2],
"quick": [0.2, 0.1, 0.5, 0.2],
"brown": [0.3, 0.3, 0.1, 0.3],
"fox": [0.25, 0.25, 0.25, 0.25]
};
var sentenceDiv = document.getElementById('sentence');
tokens.forEach(function(token) {
var span = document.createElement('span');
span.classList.add('token');
span.textContent = token;
span.addEventListener('mouseover', handleMouseOver);
span.addEventListener('mouseout', handleMouseOut);
span.addEventListener('click', handleClick);
sentenceDiv.appendChild(span);
});
var tokenElements = document.querySelectorAll('.token');
function handleMouseOver(event) {
var targetToken = event.target.textContent;
var targetIndex = tokens.indexOf(targetToken);
var scores = attentionScores[targetToken];
var svg = document.getElementById('svgContainer');
svg.innerHTML = ''; // Clear previous lines
var svgRect = svg.getBoundingClientRect();
var targetRect = event.target.getBoundingClientRect();
var targetX = (targetRect.left + targetRect.width / 2) - svgRect.left;
var targetY = (targetRect.top + targetRect.height / 2) - svgRect.top;
tokenElements.forEach(function(tokenElement, index) {
var tokenRect = tokenElement.getBoundingClientRect();
var tokenX = (tokenRect.left + tokenRect.width / 2) - svgRect.left;
var tokenY = (tokenRect.top + tokenRect.height / 2) - svgRect.top;
if(tokenElement !== event.target) {
var score = scores[index];
var thickness = score * 10; // Adjust scaling factor as needed
// Adjust control points to avoid overlapping
var deltaIndex = index - targetIndex;
var curveHeight = -100 - (Math.abs(deltaIndex) * 20);
var controlPointX = (targetX + tokenX) / 2;
var controlPointY = ((targetY + tokenY) / 2) + curveHeight;
var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('fill', 'none');
path.setAttribute('stroke', 'black');
path.setAttribute('stroke-width', thickness);
var d = 'M' + targetX + ',' + targetY +
' Q' + controlPointX + ',' + controlPointY +
' ' + tokenX + ',' + tokenY;
path.setAttribute('d', d);
svg.appendChild(path);
}
});
}
function handleMouseOut(event) {
var svg = document.getElementById('svgContainer');
svg.innerHTML = ''; // Clear the lines
}
function handleClick(event) {
var targetToken = event.target.textContent;
var scores = attentionScores[targetToken];
var attentionDiv = document.getElementById('attentionScores');
if(event.target.dataset.scoresVisible === 'true') {
// Hide attention scores
attentionDiv.innerHTML = '';
event.target.dataset.scoresVisible = 'false';
} else {
// Show attention scores
attentionDiv.innerHTML = ''; // Clear previous scores
var container = document.createElement('div');
container.style.display = 'inline-block';
var leftBracket = document.createElement('div');
leftBracket.textContent = '[';
leftBracket.style.display = 'inline-block';
leftBracket.style.verticalAlign = 'top';
leftBracket.style.fontSize = '30px';
leftBracket.style.lineHeight = '1';
var vectorDiv = document.createElement('div');
vectorDiv.classList.add('vector');
vectorDiv.style.display = 'inline-block';
tokens.forEach(function(token, index) {
var entryDiv = document.createElement('div');
var tokenSpan = document.createElement('span');
tokenSpan.textContent = token + ': ';
tokenSpan.style.fontWeight = 'bold';
var scoreSpan = document.createElement('span');
scoreSpan.textContent = scores[index].toFixed(2);
entryDiv.appendChild(tokenSpan);
entryDiv.appendChild(scoreSpan);
vectorDiv.appendChild(entryDiv);
});
var rightBracket = document.createElement('div');
rightBracket.textContent = ']';
rightBracket.style.display = 'inline-block';
rightBracket.style.verticalAlign = 'top';
rightBracket.style.fontSize = '30px';
rightBracket.style.lineHeight = '1';
container.appendChild(leftBracket);
container.appendChild(vectorDiv);
container.appendChild(rightBracket);
attentionDiv.appendChild(container);
event.target.dataset.scoresVisible = 'true';
}
}
</script>
</body>
</html>
Instructions:
- Save the above code into an HTML file (e.g.,
attention_visualization.html).
- Open the HTML file in a modern web browser to view the interactive visualization.
Features:
- Token Visualization: The sentence "The quick brown fox" is displayed, with each word as a clickable token.
- Hover Interaction: When you hover over a token, edges are drawn between the token and all other tokens.
- The thickness of each edge is proportional to the attention score between the tokens.
- Edges are curved and adjusted to not overlap each other.
- Edges start and end at the center of each token.
- Click Interaction: When you click on a token:
- The attention scores are displayed in a vector notation next to each token.
- The scores are nicely formatted and aligned.
- Clicking the token again will hide the attention scores.
- Spacing: There is a vertical spacing of 50px at the top of the page.
Notes:
- The code uses plain HTML, CSS, and JavaScript without any external libraries.
- The attention scores are predefined and can be modified in the
attentionScores object.
- Due to the absence of LaTeX rendering libraries, the attention scores are formatted to resemble vector notation using HTML and CSS.
Feel free to modify the tokens or attention scores to suit your needs.