(
args:
{inputs: SoftmaxInputs, backend: MathBackendCPU, attrs: SoftmaxAttrs})
| 27 | import {sum} from './Sum'; |
| 28 | |
| 29 | export 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 | |
| 79 | export const softmaxConfig: KernelConfig = { |
| 80 | kernelName: Softmax, |
no test coverage detected
searching dependent graphs…