(
model, inputStr, getAttention = false)
| 153 | * dtype `float32` and shape `[]`. |
| 154 | */ |
| 155 | export async function runSeq2SeqInference( |
| 156 | model, inputStr, getAttention = false) { |
| 157 | return tf.tidy(() => { |
| 158 | const encoderInput = dateFormat.encodeInputDateStrings([inputStr]); |
| 159 | const decoderInput = tf.buffer([1, dateFormat.OUTPUT_LENGTH]); |
| 160 | decoderInput.set(dateFormat.START_CODE, 0, 0); |
| 161 | |
| 162 | for (let i = 1; i < dateFormat.OUTPUT_LENGTH; ++i) { |
| 163 | const predictOut = model.predict( |
| 164 | [encoderInput, decoderInput.toTensor()]); |
| 165 | const output = predictOut.argMax(2).dataSync()[i - 1]; |
| 166 | predictOut.dispose(); |
| 167 | decoderInput.set(output, 0, i); |
| 168 | } |
| 169 | |
| 170 | const output = {outputStr: ''}; |
| 171 | |
| 172 | // The `tf.Model` instance used for the final time step varies depending on |
| 173 | // whether the attention matrix is requested or not. |
| 174 | let finalStepModel = model; |
| 175 | if (getAttention) { |
| 176 | // If the attention matrix is requested, construct a two-output model. |
| 177 | // - The 1st output is the original decoder output. |
| 178 | // - The 2nd output is the attention matrix. |
| 179 | finalStepModel = tf.model({ |
| 180 | inputs: model.inputs, |
| 181 | outputs: model.outputs.concat([model.getLayer('attention').output]) |
| 182 | }); |
| 183 | } |
| 184 | |
| 185 | const finalPredictOut = finalStepModel.predict( |
| 186 | [encoderInput, decoderInput.toTensor()]); |
| 187 | let decoderFinalOutput; // The decoder's final output. |
| 188 | if (getAttention) { |
| 189 | decoderFinalOutput = finalPredictOut[0]; |
| 190 | output.attention = finalPredictOut[1]; |
| 191 | } else { |
| 192 | decoderFinalOutput = finalPredictOut; |
| 193 | } |
| 194 | decoderFinalOutput = |
| 195 | decoderFinalOutput.argMax(2).dataSync()[dateFormat.OUTPUT_LENGTH - 1]; |
| 196 | |
| 197 | for (let i = 1; i < decoderInput.shape[1]; ++i) { |
| 198 | output.outputStr += dateFormat.OUTPUT_VOCAB[decoderInput.get(0, i)]; |
| 199 | } |
| 200 | output.outputStr += dateFormat.OUTPUT_VOCAB[decoderFinalOutput]; |
| 201 | return output; |
| 202 | }); |
| 203 | } |
no test coverage detected