Transformer 模型实现数字反转任务
来源标题:Transformer Digit Reversal
一段可视化代码展示了 Transformer 模型的编解码器结构,用于处理数字反转任务。代码按 Encoder 和 Decoder 分组渲染节点与连线,并支持点击节点触发交互。
以下正文由 AI 翻译自 Hacker News 最新(原文版权归原站所有),可能存在偏差,重要内容请以原文为准。
'+escape(a.label+" → "+b.label)+''; }).join(''); const boxes=nodes.map((n,i)=>{ const fill=n.selected?"#fde100":n.external?"#f5f5f5":colors.node; const interactive=n.action!==undefined; return ''+escape(n.tooltip??n.label)+''+ ''+ ''+escape(n.label)+''+ (n.sub?''+escape(n.sub)+'':'')+''; }).join(''); const labels=lanes.map(([x,y,label])=>''+escape(label)+'').join(''); target.innerHTML=''+labels+paths+boxes+''; target.querySelectorAll('[data-index]').forEach(button=>{ const act=()=>activate(nodes[+button.dataset.index].action); button.onclick=act; button.onkeydown=e=>{ if(e.key==="Enter"||e.key===" "){e.preventDefault();act();} }; }); function overview(){ const groups=[...new Set(d.nodes.map(n=>n.group))]; const nodes=[], edges=new Set(); const groupLabel=g=>g.replace(/^(Encoder|Decoder) \d+ · /,"").replace(/^(Encoder|Decoder) input$/,"Input"); const laneX={Encoder:82,Decoder:252}; for(const side of Object.keys(laneX)){ const lane=groups.filter(g=>g.startsWith(side)); lane.forEach((g,i)=>{ nodes.push({id:g,action:g,label:groupLabel(g), sub:i?g.split(" · ")[0]:(side==="Encoder"?d.source:d.tokens).map(tokenText).join(" "), selected:activeGroup===g,x:laneX[side],y:44+i53,w:136,h:36}); }); const predictionY=Math.max(...nodes.map(n=>n.y))+53; nodes.push({id:"Prediction",action:"Prediction",label:"Scores and loss",selected:activeGroup==="Prediction", x:laneX.Decoder,y:predictionY,w:136,h:36}); for(const n of d.nodes){ for(const parent of n.parents){ const group=d.nodes[parent].group; if(group!==n.group){edges.add(group+"|"+n.group);} drawGraph($("graph"),nodes,[...edges].map(e=>e.split("|")),334,predictionY+26,openGroup, [[laneX.Encoder,15,"Encoder"],[laneX.Decoder,15,"Decoder"]]); function openGroup(group){ activeGroup=group; layer=null; row=col=0; repaint(); $("operations").querySelector('[role=button]')?.focus({preventScroll:true}); function operationMap(){ if(activeGroup===null){ $("module-panel").hidden=true; return; $("module-panel").hidden=false; $("module-title").textContent=activeGroup; const local=d.nodes.flatMap((n,i)=>n.group===activeGroup?[i]:[]); const localSet=new Set(local); const external=[...new Set(local.flatMap(i=>d.nodes[i].parents.filter(p=>!localSet.has(p))))]; const levels=new Map(external.map(i=>[i,0])); const rows=external.length?[external]:[]; const edges=[]; for(const i of local){ const parents=[...new Set(d.nodes[i].parents)]; const level=parents.length?1+Math.max(...parents.map(p=>levels.get(p))):0; levels.set(i,level); (rows[level]??=[]).push(i); edges.push(...parents.map(p=>[p,i])); const {width,height,stage,gutter}=dimensions; const columnWidth=width+gutter; const headFor=i=>+(d.nodes[i].name.match(/ · head (\d+)$/)?.[1]??0); const headCount=Math.max(0,...local.map(headFor)); const maxPerHead=Math.max(1,...rows.flatMap(ids=>{ const counts=new Map(); for(const i of ids){ const head=headFor(i); if(head){counts.set(head,(counts.get(head)??0)+1);} return [...counts.values()]; })); const headWidth=maxPerHeadcolumnWidth; const canvasWidth=Math.max(300,headCount*headWidth+gutter, Math.max(...rows.map(ids=>ids.length))columnWidth+gutter); const nodes=rows.flatMap((ids,level)=>ids.map((i,index)=>{ const n=d.nodes[i],foreign=!localSet.has(i); const parts=n.name.split(" · "), head=foreign?0:headFor(i); const siblings=head?ids.filter(j=>headFor(j)===head):ids; const laneCenter=head?gutter/2+(head-.5)headWidth:canvasWidth/2; const x=laneCenter+(siblings.indexOf(i)-(siblings.length-1)/2)columnWidth; return {id:i,action:i,label:parts[0],sub:foreign?n.group.split(" · ").at(-1):parts[1], tooltip:n.group+" · "+n.name,accessible:foreign?n.group+" · "+n.name:n.name, external:foreign,selected:layer===i,x,y:24+levelstage,w:width,h:height}; })); drawGraph($("operations"),nodes,edges,canvasWidth,rows.lengthstage,select); // Keep dense heads legible on narrow panes by allowing horizontal scroll. $("operations").querySelector("svg").style.minWidth=Math.min(canvasWidth,720)+"px"; function tokenText(value){return value===d.bos?"":value===d.eos?"":String(value);} function repaint(){ overview();operationMap(); $("inspector").hidden=layer===null; if(layer!==null){matrix();} function select(i,r=row,c=col){ layer=i; activeGroup=d.nodes[i].group; row=r;col=c; parameterCell=null; repaint(); function direction(reverse){ back=reverse; $("forward").setAttribute("aria-pressed",!reverse); $("backward").setAttribute("aria-pressed",reverse); repaint(); $("forward").onclick=()=>direction(false); $("backward").onclick=()=>direction(true); // Expand the forward formula for one selected tensor cell. function calc(n,r,c){ const [a,b]=n.parents.map(i=>d.nodes[i].v); const p=d.params[n.layer+".weight"], bias=d.params[n.layer+".bias"]?.before; const terms=xs=>detail("Show all "+xs.length+" terms",xs.join(" + ")); const weightRow=(n.output_start??0)+c; switch(n.kind){ case "embedding":return 'embedding['+token(n.tokens[r])+', '+c+'] × √'+d.width+' = '+f(p.before[n.tokens[r]][c])+' × √'+d.width; case "position":{ const power=2Math.floor(c/2)/d.width, angle=r/10000**power; return (c%2?'cos':'sin')+'('+r+' / 10000^'+f(power)+') = '+(c%2?'cos':'sin')+'('+f(angle)+')'; case "add":return f(a[r][c])+' + '+f(b[r][c]); case "linear":{ const inputs=a[r].length, outputs=n.v[r].length; return equation("("+a.length+" × "+inputs+") · ("+inputs+" × "+outputs+") → ("+ a.length+" × "+outputs+")")+ 'PyTorch stores W as '+outputs+' × '+inputs+'. Transposing swaps the indices, so Wᵀ[k,c] = W[c,k]. '+ 'Take the dot product with column '+c+' and add bias '+f(bias[weightRow])+'.'+ terms(a[r].map((x,j)=>f(x)+' × '+f(p.before[weightRow][j]))); case "slice":return 'Copy projected feature '+(n.start+c)+' at row '+r+'.'; case "dot":return 'Sum the products and divide by √'+a[r].length+'.'+terms(a[r].map((x,j)=>f(x)+' × '+f(b[c][j])));
(原文较长,此处译出前 6000 字,完整内容请点「打开原文」。)
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。