Transformer by Hand
Posted: Wed Jul 10, 2024 12:09 pm
https://x.com/ProfTomYeh/status/1809939766907228334
Code: Select all | Expand
// Transformer by hand
function Main()
local aInput := { { 1, 1, 1, 1, 1 },;
{ 1, 0, 0, 1, -1 },;
{ 1, 1, 1, 1, 2 },;
{ 0, 1, 0, 0, 1 } }
local aAWM := { { 1, 1, 0, 1, 0 },;
{ 1, 0, 1, 1, 0 },;
{ 0, 0, 1, 1, 0 },;
{ 0, 1, 0, 0, 1 },;
{ 0, 1, 1, 0, 1 } }
local aAWF := MatMul( aInput, aAWM )
local aWB := { { 1, 0, 0, 1, 3 },;
{ 0, 1, 1, 1, 4 },;
{ 1, 1, -1, 1, -1 } }
local aWB2 := { { 1, 0, 1, -1 },;
{ -1, 0, 1, 7 },;
{ 1, -1, 0, 2 },;
{ 0, 1, -1, -1 } }
local aWBxaAWF, aReLU, aWB2xaReLU
AAdd( aAWF, { 1, 1, 1, 1, 1 } )
aWBxaAWF = MatMul( aWB, aAWF )
aReLU = ReLU( aWBxaAWF )
AAdd( aReLU, { 1, 1, 1, 1, 1 } )
aWB2xaReLU = MatMul( aWB2, aReLU )
? ReLU( aWB2xaReLU )
return nil
function MatMul( aMatrix1, aMatrix2 )
local nRowsA := Len( aMatrix1 )
local nColsA := Len( aMatrix1[ 1 ] )
local nColsB := Len( aMatrix2[ 1 ] )
local aMatrixResult := Array( nRowsA, nColsB )
local i, j, k
for i := 1 to nRowsA
for j := 1 to nColsB
aMatrixResult[ i, j ] := 0
for k := 1 to nColsA
aMatrixResult[ i, j ] += aMatrix1[ i, k ] * aMatrix2[ k, j ]
next
next
next
return aMatrixResult
function ReLU( aMatrix )
LOCAL aOutput := AClone( aMatrix )
LOCAL i, j
FOR i := 1 TO Len( aOutput )
FOR j := 1 TO Len( aOutput[ i ] )
aOutput[ i ][ j ] := Max( 0, aOutput[ i ][ j ] )
NEXT
NEXT
RETURN aOutput