From 23b80bda93b2d193b807c27b884d6cbebb980243 Mon Sep 17 00:00:00 2001 From: lanqing431 <359744414+lanqing431@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:29:04 -0500 Subject: [PATCH] fix: stabilize Softmax for large finite inputs --- Maths/Softmax.js | 8 +++----- Maths/test/Softmax.test.js | 13 +++++++++++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/Maths/Softmax.js b/Maths/Softmax.js index 66363c4436..842ec85e6d 100644 --- a/Maths/Softmax.js +++ b/Maths/Softmax.js @@ -1,13 +1,11 @@ // Wikipedia: https://en.wikipedia.org/wiki/Softmax_function const Softmax = (inputs) => { - const eulerExpOfAllInputs = inputs.map((input) => Math.exp(input)) + const maxInput = inputs.reduce((maximum, input) => Math.max(maximum, input)) + const eulerExpOfAllInputs = inputs.map((input) => Math.exp(input - maxInput)) const sumOfEulerExpOfAllInputs = eulerExpOfAllInputs.reduce((a, b) => a + b) - return inputs.map((input) => { - const eulerExpInputs = Math.exp(input) - return eulerExpInputs / sumOfEulerExpOfAllInputs - }) + return eulerExpOfAllInputs.map((value) => value / sumOfEulerExpOfAllInputs) } export { Softmax } diff --git a/Maths/test/Softmax.test.js b/Maths/test/Softmax.test.js index 179697bcf7..911ab1e3cd 100644 --- a/Maths/test/Softmax.test.js +++ b/Maths/test/Softmax.test.js @@ -1,6 +1,19 @@ import { Softmax } from '../Softmax' describe('Softmax', () => { + it.each([1000, -1000])( + 'should normalize finite logits with a common offset of %i', + (offset) => { + const expected = Softmax([0, 1, 2]) + const actual = Softmax([offset, offset + 1, offset + 2]) + actual.forEach((value, index) => { + expect(Number.isFinite(value)).toBe(true) + expect(value).toBeCloseTo(expected[index], 14) + }) + expect(actual.reduce((sum, value) => sum + value, 0)).toBeCloseTo(1, 14) + } + ) + it('should return equal distribution of 1 for equal input values', () => { expect(Softmax([1, 1])).toEqual([0.5, 0.5]) expect(Softmax([1, 1, 1, 1])).toEqual([0.25, 0.25, 0.25, 0.25])