Skip to content

Commit

Permalink
Update glyphnet.
Browse files Browse the repository at this point in the history
  • Loading branch information
ameritusweb committed Mar 7, 2024
1 parent 9396163 commit 341433a
Show file tree
Hide file tree
Showing 10 changed files with 616 additions and 127 deletions.
41 changes: 19 additions & 22 deletions examples/gravnet/ParallelReverseAutoDiff.GravNetExample/GlyphNet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,24 +147,20 @@ public void ApplyGradients()
/// Make a forward pass through the computation graph.
/// </summary>
/// <returns>The gradient of the loss wrt the output.</returns>
public (Matrix, Matrix, Matrix, Matrix, Matrix, Matrix, Matrix, Matrix, Matrix, Matrix) Forward(Matrix input, Matrix rotationTargets, double targetAngle)
public (Matrix, (Matrix Loss, Matrix Gradient)[]) Forward(Matrix input, Matrix rotationTargets)
{

var gatNet = this.GlyphNetwork;
gatNet.TargetAngle = targetAngle;
gatNet.InitializeState();
gatNet.RotationTargets.Replace(rotationTargets.ToArray());
gatNet.AutomaticForwardPropagate(input);
var output = gatNet.Output;
var glyph = gatNet.Glyph;
var targetedSum0 = gatNet.TargetedSum0;
var targetedSum1 = gatNet.TargetedSum1;

int maxMag0 = 0;
int maxMag1 = 0;
for (int i = 0; i < 15; i++)
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 15; j++)
for (int j = 0; j < 8; j++)
{
if (rotationTargets[i, j] == 1)
{
Expand All @@ -179,29 +175,30 @@ public void ApplyGradients()

Console.WriteLine($"Max Mag 0: {maxMag0}, Max Mag 1: {maxMag1}");

SquaredArclengthEuclideanLossOperation arclengthLoss0 = SquaredArclengthEuclideanLossOperation.Instantiate(gatNet);
var loss0 = arclengthLoss0.Forward(targetedSum0, (3 * Math.PI) / 4d, 0);
var gradient0 = arclengthLoss0.Backward();

SquaredArclengthEuclideanLossOperation arclengthLoss1 = SquaredArclengthEuclideanLossOperation.Instantiate(gatNet);
var loss1 = arclengthLoss1.Forward(targetedSum1, (1 * Math.PI) / 4d, 1);
var gradient1 = arclengthLoss1.Backward();

SquaredArclengthEuclideanMagnitudeLossOperation arclengthLoss = SquaredArclengthEuclideanMagnitudeLossOperation.Instantiate(gatNet);
var loss = arclengthLoss.Forward(output, targetAngle, 225);
var gradient = arclengthLoss.Backward();
(Matrix Loss, Matrix Gradient)[] values = new (Matrix Loss, Matrix Gradient)[64];
for (int i = 0; i < 64; ++i)
{
Matrix m = new Matrix(1, 2);
m[0, 0] = glyph[i, 0];
m[0, 1] = glyph[i, 1];
SquaredArclengthEuclideanLossOperation arclengthLoss = SquaredArclengthEuclideanLossOperation.Instantiate(gatNet);
var loss = arclengthLoss.Forward(m, rotationTargets[i / 8, i % 8] == 1 ? (3 * Math.PI) / 4d : Math.PI / 4d);
var gradient = arclengthLoss.Backward();
values[i].Loss = loss;
values[i].Gradient = gradient;
}

return (gradient, gradient0, gradient1, output, targetedSum0, targetedSum1, glyph, loss, loss0, loss1);
return (glyph, values);
}

/// <summary>
/// The backward pass through the computation graph.
/// </summary>
/// <param name="gradientOfLossWrtOutput">The gradient of the loss wrt the output.</param>
/// <param name="gradients">The gradient of the loss wrt the output.</param>
/// <returns>A task.</returns>
public async Task<Matrix> Backward(Matrix gradientOfLossWrtOutput, Matrix gradient0, Matrix gradient1)
public async Task<Matrix> Backward((Matrix Loss, Matrix Gradient)[] gradients)
{
return await this.GlyphNetwork.AutomaticBackwardPropagate(gradientOfLossWrtOutput, gradient0, gradient1);
return await this.GlyphNetwork.AutomaticBackwardPropagate(gradients);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,19 @@ await files.WithRepeatAsync(async (pngFile, token) =>
int uIndex = file.IndexOf("_");
var prefix = file.Substring(0, uIndex);
var glyphFile = pngFile.Replace("\\" + prefix, "\\" + prefix + "_glyph").Replace("svg\\", "svg-glyph\\");
Node[,] glyphNodes = ImageSerializer.DeserializeImageWithoutAntiAlias(glyphFile);
Matrix rotationTargets = new Matrix(15, 15);
Vector3[] glyphs = new Vector3[225];
//var glyphFile = pngFile.Replace("\\" + prefix, "\\" + prefix + "_glyph").Replace("svg\\", "svg-glyph\\");
//Node[,] glyphNodes = ImageSerializer.DeserializeImageWithoutAntiAlias(glyphFile);
var glyphNodes = AnalyzeImageSections(interpolated);
Matrix rotationTargets = new Matrix(8, 8);
Vector3[] glyphs = new Vector3[64];
int m = 0;
for (int k = 0; k < 15; ++k)
for (int k = 0; k < 8; ++k)
{
for (int l = 0; l < 15; ++l)
for (int l = 0; l < 8; ++l)
{
rotationTargets[k, l] = glyphNodes[k, l].IsForeground ? 1d : 0d;
rotationTargets[k, l] = glyphNodes[k, l];
glyphs[m] = new Vector3(0f, 0f, (float)rotationTargets[k, l]);
m++;
}
Expand All @@ -73,30 +76,31 @@ await files.WithRepeatAsync(async (pngFile, token) =>
i++;
var res = net.Forward(matrix, rotationTargets, Math.PI / 4d);
var gradient = res.Item1;
var gradient0 = res.Item2;
var gradient1 = res.Item3;
var output = res.Item4;
var o0 = res.Item5;
var o1 = res.Item6;
var glyph = res.Item7;
var loss = res.Item8;
var loss0 = res.Item9;
var loss1 = res.Item10;
for (int j = 0; j < 225; ++j)
var res = net.Forward(matrix, rotationTargets);
var glyph = res.Item1;
var gradients = res.Item2;
//var gradient1 = res.Item3;
//var output = res.Item4;
//var o0 = res.Item5;
//var o1 = res.Item6;
//var glyph = res.Item7;
//var loss = res.Item8;
//var loss0 = res.Item9;
//var loss1 = res.Item10;
for (int j = 0; j < 64; ++j)
{
glyphs[j].X = (float)glyph[j, 0];
glyphs[j].Y = (float)glyph[j, 1];
}
Console.WriteLine($"Iteration {i} Output X: {output[0, 0]}, Output Y: {output[0, 1]}, Grad: {gradient[0, 0]}, {gradient[0, 1]}");
Console.WriteLine($"Loss: {loss[0, 0]}");
Console.WriteLine($"O0 X: {o0[0, 0]}, O0 Y: {o0[0, 1]}, Loss 0: {loss0[0, 0]}");
Console.WriteLine($"O1 X: {o1[0, 0]}, O1 Y: {o1[0, 1]}, Loss 1: {loss1[0, 0]}");
await net.Backward(gradient, gradient0, gradient1);
//Console.WriteLine($"Iteration {i} Output X: {output[0, 0]}, Output Y: {output[0, 1]}, Grad: {gradient[0, 0]}, {gradient[0, 1]}");
Console.WriteLine($"Iteration {i} Glyph: {glyphs[0].X}, {glyphs[0].Y}");
Console.WriteLine($"Loss: {gradients.Sum(x => x.Loss[0, 0])}");
//Console.WriteLine($"O0 X: {o0[0, 0]}, O0 Y: {o0[0, 1]}, Loss 0: {loss0[0, 0]}");
//Console.WriteLine($"O1 X: {o1[0, 0]}, O1 Y: {o1[0, 1]}, Loss 1: {loss1[0, 0]}");
await net.Backward(gradients);
net.ApplyGradients();
//}
Expand All @@ -121,5 +125,41 @@ await files.WithRepeatAsync(async (pngFile, token) =>
CudaBlas.Instance.Dispose();
}
}

private int[,] AnalyzeImageSections(Node[,] interpolated)
{
// Assuming Node is a custom type with a GrayValue property.
// Size of the output matrix.
const int outputSize = 8;
// Calculate section size based on the input image dimensions and desired output matrix size.
int sectionWidth = interpolated.GetLength(0) / outputSize;
int sectionHeight = interpolated.GetLength(1) / outputSize;

// Initialize the output matrix.
int[,] sectionAnalysis = new int[outputSize, outputSize];

// Process each section.
for (int sectionX = 0; sectionX < outputSize; sectionX++)
{
for (int sectionY = 0; sectionY < outputSize; sectionY++)
{
// Calculate the start and end indices for the section.
int startX = sectionX * sectionWidth;
int startY = sectionY * sectionHeight;
int endX = startX + sectionWidth;
int endY = startY + sectionHeight;

// Flatten the section into a single collection for easier analysis.
var sectionPixels = Enumerable.Range(startX, sectionWidth).SelectMany(
x => Enumerable.Range(startY, sectionHeight),
(x, y) => (256d - interpolated[x, y].GrayValue) / (255d));

// Determine if 40% or more of the pixels in the section are greater than 0.5.
sectionAnalysis[sectionX, sectionY] = sectionPixels.Count(val => val > 0.5) >= sectionPixels.Count() * 0.4 ? 1 : 0;
}
}

return sectionAnalysis;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -129,24 +129,6 @@
"type": "ElementwiseVectorCartesianGlyphOperation",
"inputs": [ "vector_attention", "vector_queries_attention", "summation_weights_square" ],
"setResultTo": "Glyph"
},
{
"id": "targeted_sum_0",
"type": "ElementwiseVectorCartesianTargetedSumOperation",
"inputs": [ "glyph", "RotationTargets", "Target0" ],
"setResultTo": "TargetedSum0"
},
{
"id": "targeted_sum_1",
"type": "ElementwiseVectorCartesianTargetedSumOperation",
"inputs": [ "glyph", "RotationTargets", "Target1" ],
"setResultTo": "TargetedSum1"
},
{
"id": "output",
"type": "ElementwiseVectorCartesianRotationAndSumOperation",
"inputs": [ "glyph", "RotationTargets" ],
"setResultTo": "Output"
}
]
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
{
"timeSteps": [
{
"startOperations": [
{
"id": "angles_square",
"type": "ElementwiseSquareOperation",
"inputs": [ "Angles" ],
"gradientResultTo": [ "DAngles" ]
},
{
"id": "vectorize_input",
"type": "VectorizeOperation",
"inputs": [ "Input", "angles_square" ]
},
{
"id": "projection_vectors_square",
"type": "ElementwiseSquareOperation",
"inputs": [ "ProjectionVectors" ],
"gradientResultTo": [ "DProjectionVectors" ]
},
{
"id": "vector_decomposition",
"type": "ElementwiseVectorMiniDecompositionOperation",
"inputs": [ "vectorize_input", "projection_vectors_square", "ProjectionWeights" ],
"gradientResultTo": [ null, null, "DProjectionWeights" ]
},
{
"id": "weight_vectors_square",
"type": "ElementwiseSquareOperation",
"inputs": [ "WeightVectors" ],
"gradientResultTo": [ "DWeightVectors" ]
},
{
"id": "weight_vectors_square2",
"type": "ElementwiseSquareOperation",
"inputs": [ "WeightVectors2" ],
"gradientResultTo": [ "DWeightVectors2" ]
},
{
"id": "weight_square",
"type": "ElementwiseSquareOperation",
"inputs": [ "Weights" ],
"gradientResultTo": [ "DWeights" ]
},
{
"id": "weight_square2",
"type": "ElementwiseSquareOperation",
"inputs": [ "Weights2" ],
"gradientResultTo": [ "DWeights2" ]
},
{
"id": "start_solar_system",
"type": "ElementwiseVectorConstituentMonoMultiplyOperation",
"inputs": [ "vector_decomposition", "weight_vectors_square", "weight_square" ]
},
{
"id": "start_solar_system_2",
"type": "ElementwiseVectorConstituentMonoMultiplyOperation",
"inputs": [ "vector_decomposition", "weight_vectors_square2", "weight_square2" ]
},
{
"id": "vector_add",
"type": "ElementwiseVectorAddOperation",
"inputs": [ "start_solar_system", "start_solar_system_2" ]
},
{
"id": "vector_keys",
"type": "NewGpuMatrixMultiplyOperation",
"inputs": [ "vector_add", "Keys" ],
"gradientResultTo": [ null, "DKeys" ]
},
{
"id": "vector_add_broadcasting",
"type": "MatrixAddBroadcastingOperation",
"inputs": [ "vector_keys", "KB" ],
"gradientResultTo": [ null, "DKB" ]
},
{
"id": "vector_act",
"type": "LeakyReLUOperation",
"inputs": [ "vector_add_broadcasting" ]
},
{
"id": "vector_queries",
"type": "NewGpuMatrixMultiplyOperation",
"inputs": [ "vector_add", "Queries" ],
"gradientResultTo": [ null, "DQueries" ]
},
{
"id": "vector_queries_add_broadcasting",
"type": "MatrixAddBroadcastingOperation",
"inputs": [ "vector_queries", "QB" ],
"gradientResultTo": [ null, "DQB" ]
},
{
"id": "vector_queries_act",
"type": "LeakyReLUOperation",
"inputs": [ "vector_queries_add_broadcasting" ]
},
{
"id": "vector_softmax",
"type": "PairwiseSineSoftmaxOperation",
"inputs": [ "vector_act" ]
},
{
"id": "vector_attention",
"type": "VectorAttentionOperation",
"inputs": [ "vector_add", "vector_softmax" ]
},
{
"id": "vector_queries_softmax",
"type": "PairwiseSineSoftmaxOperation",
"inputs": [ "vector_queries_act" ]
},
{
"id": "vector_queries_attention",
"type": "VectorAttentionOperation",
"inputs": [ "vector_add", "vector_queries_softmax" ]
},
{
"id": "summation_weights_square",
"type": "ElementwiseSquareOperation",
"inputs": [ "SummationWeights" ],
"gradientResultTo": [ "DSummationWeights" ]
},
{
"id": "glyph",
"type": "ElementwiseVectorCartesianGlyphOperation",
"inputs": [ "vector_attention", "vector_queries_attention", "summation_weights_square" ],
"setResultTo": "Glyph"
},
{
"id": "targeted_sum_0",
"type": "ElementwiseVectorCartesianTargetedSumOperation",
"inputs": [ "glyph", "RotationTargets", "Target0" ],
"setResultTo": "TargetedSum0"
},
{
"id": "targeted_sum_1",
"type": "ElementwiseVectorCartesianTargetedSumOperation",
"inputs": [ "glyph", "RotationTargets", "Target1" ],
"setResultTo": "TargetedSum1"
},
{
"id": "output",
"type": "ElementwiseVectorCartesianRotationAndSumOperation",
"inputs": [ "glyph", "RotationTargets" ],
"setResultTo": "Output"
}
]
}
]
}
Loading

0 comments on commit 341433a

Please sign in to comment.