-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoftmax.ts
More file actions
34 lines (30 loc) · 848 Bytes
/
softmax.ts
File metadata and controls
34 lines (30 loc) · 848 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Softmax: Convert logits to probabilities
*
* Formula: prob[i] = exp(logit[i]) / sum(exp(logit[j]) for all j)
*
* Uses max subtraction for numerical stability:
* exp(x - max) prevents overflow for large logits
*
* @param logits Logits array
* @returns Probability distribution (sums to 1.0)
*/
export function softmax(logits: Float32Array): Float32Array {
const probs = new Float32Array(logits.length);
// Find max for numerical stability
let maxLogit = -Infinity;
for (let i = 0; i < logits.length; i++) {
if (logits[i] > maxLogit) maxLogit = logits[i];
}
// Compute exp and sum
let sum = 0;
for (let i = 0; i < logits.length; i++) {
probs[i] = Math.exp(logits[i] - maxLogit);
sum += probs[i];
}
// Normalize
for (let i = 0; i < logits.length; i++) {
probs[i] /= sum;
}
return probs;
}