From 1083b075843da569f56a86030e412b2586710d85 Mon Sep 17 00:00:00 2001 From: Armand Date: Mon, 6 Apr 2026 18:36:09 -0400 Subject: [PATCH] Fix neural network output corruption from reused result buffers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MatrixProduct and MatrixProductTranspose accumulate into a result buffer using +=, but never zero it first. When callers pass a pre-allocated buffer (as FeedForwardNetwork.CalculateOutputs does with tempResults on every tick), values from previous forward passes accumulate indefinitely instead of being computed fresh. The bug is masked by sigmoid activation saturation — after a few ticks the accumulated values grow so large that sigmoid maps everything near 0 or 1 regardless. This effectively corrupts the network's ability to produce nuanced, input-dependent outputs and limits creatures to simple repetitive motions rather than adaptive behavior. Fix: zero each result element before the inner accumulation loop. Co-Authored-By: Claude Opus 4.6 (1M context) --- Assets/Scripts/Util/MatrixUtils.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Assets/Scripts/Util/MatrixUtils.cs b/Assets/Scripts/Util/MatrixUtils.cs index c4920485..5390bee0 100644 --- a/Assets/Scripts/Util/MatrixUtils.cs +++ b/Assets/Scripts/Util/MatrixUtils.cs @@ -44,9 +44,11 @@ public static float[][] MatrixProduct(float[][] lhs, float[][] rhs, float[][] re result = CreateMatrix2D(aRows, bCols); for (int i = 0; i < aRows; ++i) // each row of A - for (int j = 0; j < bCols; ++j) // each col of B + for (int j = 0; j < bCols; ++j) { // each col of B + result[i][j] = 0f; for (int k = 0; k < aCols; ++k) result[i][j] += lhs[i][k] * rhs[k][j]; + } return result; } @@ -63,9 +65,11 @@ public static float[] MatrixProduct(float[][] matrixA, float[] vectorB, float[] if (result == null) result = new float[aRows]; - for (int i = 0; i < aRows; ++i) // each row of A + for (int i = 0; i < aRows; ++i) { // each row of A + result[i] = 0f; for (int k = 0; k < aCols; ++k) result[i] += matrixA[i][k] * vectorB[k]; + } return result; } @@ -85,9 +89,11 @@ public static float[] MatrixProductTranspose(float[][] matrixA, float[] vectorB, if (result == null) result = new float[aRows]; - for (int i = 0; i < aRows; ++i) // each row of A + for (int i = 0; i < aRows; ++i) { // each row of A + result[i] = 0f; for (int k = 0; k < aCols; ++k) result[i] += matrixA[k][i] * vectorB[k]; + } return result; }