MCPcopy Create free account
hub / github.com/tensorflow/tfjs / softmax

Function softmax

tfjs-backend-cpu/src/kernels/Softmax.ts:29–77  ·  view source on GitHub ↗
(
    args:
        {inputs: SoftmaxInputs, backend: MathBackendCPU, attrs: SoftmaxAttrs})

Source from the content-addressed store, hash-verified

27import {sum} from './Sum';
28
29export function softmax(
30 args:
31 {inputs: SoftmaxInputs, backend: MathBackendCPU, attrs: SoftmaxAttrs}):
32 TensorInfo {
33 const {inputs, backend, attrs} = args;
34 const {logits} = inputs;
35 const {dim} = attrs;
36
37 const logitsRank = logits.shape.length;
38
39 let $dim = dim;
40 if ($dim === -1) {
41 $dim = logitsRank - 1;
42 }
43 if ($dim !== logitsRank - 1) {
44 throw Error(
45 'Softmax along a non-last dimension is not yet supported. ' +
46 `Logits was rank ${logitsRank} and dim was ${$dim}`);
47 }
48
49 const axes = util.parseAxisParam([$dim], logits.shape);
50 const maxLogit = max({
51 inputs: {x: logits},
52 backend,
53 attrs: {reductionIndices: axes, keepDims: false}
54 });
55 const expandedShape = backend_util.expandShapeToKeepDim(maxLogit.shape, axes);
56
57 const maxLogitReshaped =
58 reshape({inputs: {x: maxLogit}, backend, attrs: {shape: expandedShape}});
59 const a =
60 sub({inputs: {a: logits, b: maxLogitReshaped}, backend}) as TensorInfo;
61 const b = exp({inputs: {x: a}, backend}) as TensorInfo;
62 const sumExp =
63 sum({inputs: {x: b}, backend, attrs: {axis: axes, keepDims: false}});
64 const sumReshaped =
65 reshape({inputs: {x: sumExp}, backend, attrs: {shape: expandedShape}});
66
67 const result = div({inputs: {a: b, b: sumReshaped}, backend}) as TensorInfo;
68
69 backend.disposeIntermediateTensorInfo(maxLogit);
70 backend.disposeIntermediateTensorInfo(maxLogitReshaped);
71 backend.disposeIntermediateTensorInfo(a);
72 backend.disposeIntermediateTensorInfo(b);
73 backend.disposeIntermediateTensorInfo(sumExp);
74 backend.disposeIntermediateTensorInfo(sumReshaped);
75
76 return result;
77}
78
79export const softmaxConfig: KernelConfig = {
80 kernelName: Softmax,

Callers 1

multinomialFunction · 0.90

Calls 5

maxFunction · 0.90
reshapeFunction · 0.90
sumFunction · 0.90
ErrorFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…