T2TPredictor.cpp 7 KB
Newer Older
1
/* NiuTrans.Tensor - an open-source tensor library
xiaotong committed
2
 * Copyright (C) 2019, Natural Language Processing Lab, Northestern University.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * $Created by: XIAO Tong (xiaotong@mail.neu.edu.cn) 2019-03-13
 */

xiaotong committed
22
#include "T2TPredictor.h"
23 24 25
#include "../../tensor/core/CHeader.h"

using namespace nts;
xiaotong committed
26 27 28

namespace transformer
{
xiaotong committed
29 30

/* constructor */
xiaotong committed
31 32 33
T2TStateBundle::T2TStateBundle()
{
    states = NULL;
xiaotong committed
34
    isStart = false;
xiaotong committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
}

/* de-constructor */
T2TStateBundle::~T2TStateBundle()
{
    if(states != NULL)
        delete[] states;
}

/* 
create states 
>> num - number of states
*/
void T2TStateBundle::MakeStates(int num)
{
    CheckNTErrors(num > 0, "invalid number");

    if(states != NULL)
        delete[] states;

    states = new T2TState[num];

57 58
    for(int i = 0; i < num; i++){
        states[i].prediction = -1;
59
        states[i].pid = T2T_PID_EMPTY;
xiaotong committed
60 61
        states[i].isEnd = false;
        states[i].isStart = false;
62
        states[i].isCompleted = false;
63 64 65 66
        states[i].prob = 0;
        states[i].probPath = 0;
        states[i].modelScore = 0;
        states[i].nstep = 0;
xiaotong committed
67
        states[i].last = NULL;
68
    }
69 70

    stateNum = num;
xiaotong committed
71 72 73
}

/* constructor */
xiaotong committed
74 75
T2TPredictor::T2TPredictor()
{
76
    startSymbol = -1;
xiaotong committed
77 78 79 80 81 82 83 84
}

/* de-constructor */
T2TPredictor::~T2TPredictor()
{
}

/* 
xiaotong committed
85 86
create an initial state 
>> model - the t2t model
87
>> top - the top-most layer of the network
xiaotong committed
88 89
>> input - input of the network
>> beamSize - beam size
xiaotong committed
90 91
>> state - the state to be initialized
*/
xiaotong committed
92
void T2TPredictor::Create(T2TModel * model, XTensor * top, const XTensor * input, int beamSize, T2TStateBundle * state)
xiaotong committed
93
{
94 95
    state->layersEnc.Clear();
    state->layersDec.Clear();
xiaotong committed
96

97 98 99
    XTensor * encoding = XLink::SearchNode(top, ENCODING_NAME);
    CheckNTErrors(encoding != NULL, "No encoding layers found!");

100 101
    state->layersEnc.Add(encoding);
    state->layersDec.Add(NULL);
xiaotong committed
102 103 104 105 106 107

    int dims[MAX_TENSOR_DIM_NUM];
    for (int i = 0; i < input->order - 1; i++)
        dims[i] = input->GetDim(i);
    dims[input->order - 1] = beamSize;

108 109 110
    InitTensor(&state->probPath, input->order, dims, X_FLOAT, input->devID);
    InitTensor(&state->nstep, input->order, dims, X_FLOAT, input->devID);
    InitTensor(&state->endMark, input->order, dims, X_INT, input->devID);
xiaotong committed
111 112 113

    state->probPath.SetZeroAll();
    state->nstep.SetZeroAll();
xiaotong committed
114
    state->endMark.SetZeroAll();
xiaotong committed
115 116

    state->stateNum = 0;
xiaotong committed
117
}
118

119 120 121 122 123 124 125 126
/*
set start symbol
>> symbol - the symbol (in integer)
*/
void T2TPredictor::SetStartSymbol(int symbol)
{
    startSymbol = symbol;
}
xiaotong committed
127 128

/* 
xiaotong committed
129 130
read a state 
>> model - the t2t model that keeps the network created so far
xiaotong committed
131
>> state - a set of states. It keeps
xiaotong committed
132 133
             1) hypotheses (states)
             2) probablities of hypotheses
134
             3) parts of the network for expanding toward the next state
xiaotong committed
135
*/
xiaotong committed
136
void T2TPredictor::Read(T2TModel * model, T2TStateBundle * state)
xiaotong committed
137 138
{
    m = model;
xiaotong committed
139
    s = state;
xiaotong committed
140 141 142 143 144
}

/*
predict the next state
>> next - next states (assuming that the current state has been read)
145 146 147
>> encoding - encoder output
>> inputEnc - input of the encoder
>> paddingEnc - padding of the encoder
xiaotong committed
148
*/
149
void T2TPredictor::Predict(T2TStateBundle * next, XTensor * encoding,
xiaotong committed
150
                           XTensor * inputEnc, XTensor * paddingEnc)
xiaotong committed
151
{
xiaotong committed
152 153
    int dims[MAX_TENSOR_DIM_NUM];

154 155
    next->layersEnc.Clear();
    next->layersDec.Clear();
156
    
xiaotong committed
157 158 159
    AttDecoder &decoder = *m->decoder;
    
    /* word indices of previous positions */
160
    XTensor * inputLast = (XTensor*)s->layersDec.GetItem(0);
xiaotong committed
161 162

    /* word indices of positions up to next state */
xiaotong committed
163
    XTensor inputDec;
xiaotong committed
164

165 166
    /* the first token */
    XTensor first;
xiaotong committed
167 168
    
    CheckNTErrors(inputEnc->order >= 2, "Wrong order of the tensor!");
xiaotong committed
169 170 171 172
    for(int i = 0; i < inputEnc->order - 1; i++)
        dims[i] = inputEnc->GetDim(i);
    dims[inputEnc->order - 1] = 1;

173
    InitTensor(&first, inputEnc->order, dims, X_INT, inputEnc->devID);
174
    _SetDataFixedInt(&first, startSymbol);
xiaotong committed
175 176

    /* add a new word into the input sequence of the decoder side */
177
    if (inputLast == NULL) {
178 179
        inputDec = Identity(first);
    }
xiaotong committed
180
    else{
xiaotong committed
181
        inputDec = GeneratePaths(s);
182
        inputDec.SetDevice(inputEnc->devID);
183

xiaotong committed
184
        inputDec = Concatenate(first, inputDec, inputDec.order - 1);
xiaotong committed
185
    }
xiaotong committed
186 187

    /* prediction probabilities */
188
    XTensor &output = next->prob;
xiaotong committed
189 190
    XTensor decoding;
    XTensor decodingStep;
191
    
xiaotong committed
192 193 194 195
    for(int i = 0; i < inputDec.order - 1; i++)
        dims[i] = inputDec.GetDim(i);
    dims[inputDec.order - 1] = inputDec.GetDim(-1);
    
196
    XTensor paddingDec;
197
    InitTensor(&paddingDec, inputDec.order, dims, X_INT, paddingEnc->devID);
198 199 200 201 202 203 204
    SetDataFixedInt(paddingDec, 1);
    
    XTensor maskDec;
    XTensor maskEncDec;
    
    /* decoder mask */
    m->MakeMTMaskDec(*inputEnc, inputDec, *paddingEnc, paddingDec, maskDec, maskEncDec);
xiaotong committed
205

xiaotong committed
206 207 208 209 210 211 212 213
    /* make the decoding network */
    decoding = decoder.Make(inputDec, *encoding, maskDec, maskEncDec, false);

    XTensor selectSrc;
    XTensor selectTgt;

    CheckNTErrors(decoding.order >= 2, "The tensor must be of order 2 or larger!");

214
    int stride = decoding.GetDim(decoding.order - 2);
xiaotong committed
215

216 217
    InitTensor1D(&selectSrc, 1, X_INT);
    InitTensor1D(&selectTgt, 1, X_INT);
xiaotong committed
218

xiaotong committed
219
    selectSrc.SetInt(stride - 1, 0);
220
    selectTgt.SetInt(0, 0);
xiaotong committed
221

222 223
    selectSrc.SetDevice(decoding.devID);
    selectTgt.SetDevice(decoding.devID);
224
    
xiaotong committed
225 226 227 228 229
    /* the decoder output of the last position */
    decodingStep = CopyIndexed(decoding, decoding.order - 2, selectSrc, selectTgt);

    /* generate the output probabilities */
    m->outputLayer->Make(decodingStep, output);
230
    
231 232 233
    next->layersEnc.AddList(&s->layersEnc);
    next->layersDec.Add(&inputDec);
    next->layersDec.Add(&output);
xiaotong committed
234 235
}

xiaotong committed
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
/* 
generate paths up to the states of the current step 
>> state - state bundle of the current step
*/
XTensor T2TPredictor::GeneratePaths(T2TStateBundle * state)
{
    CheckNTErrors(state->stateNum >= 0, "Illegal state!");

    int distance = -1;
    
    for(int i = 0; i < state->stateNum; i++){
        T2TState * cur = state->states + i;
        int nsteps = 0;

        while(cur != NULL){
            nsteps++;
            cur = cur->last;
        }

        if(nsteps > distance)
            distance = nsteps;
    }

    XTensor path;
260
    InitTensor2D(&path, state->stateNum, distance, X_INT);
xiaotong committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    path.SetZeroAll();

    for(int i = 0; i < state->stateNum; i++){
        T2TState * cur = state->states + i;
        int nsteps = 0;

        while(cur != NULL){
            nsteps++;
            path.Set2DInt(cur->prediction, i, distance - nsteps);
            cur = cur->last;
        }
    }

    return path;
}

xiaotong committed
277
}
278