Home | History | Annotate | Download | only in kernels
      1 /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
      2 
      3 Licensed under the Apache License, Version 2.0 (the "License");
      4 you may not use this file except in compliance with the License.
      5 You may obtain a copy of the License at
      6 
      7     http://www.apache.org/licenses/LICENSE-2.0
      8 
      9 Unless required by applicable law or agreed to in writing, software
     10 distributed under the License is distributed on an "AS IS" BASIS,
     11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 See the License for the specific language governing permissions and
     13 limitations under the License.
     14 ==============================================================================*/
     15 
     16 // Generate a list of skip grams from an input.
     17 //
     18 // Options:
     19 //   ngram_size: num of words for each output item.
     20 //   max_skip_size: max num of words to skip.
     21 //                  The op generates ngrams when it is 0.
     22 //   include_all_ngrams: include all ngrams with size up to ngram_size.
     23 //
     24 // Input:
     25 //   A string tensor to generate n-grams.
     26 //   Dim = {1}
     27 //
     28 // Output:
     29 //   A list of strings, each of which contains ngram_size words.
     30 //   Dim = {num_ngram}
     31 
     32 #include <ctype.h>
     33 #include <string>
     34 #include <vector>
     35 
     36 #include "tensorflow/lite/c/builtin_op_data.h"
     37 #include "tensorflow/lite/c/c_api_internal.h"
     38 #include "tensorflow/lite/kernels/kernel_util.h"
     39 #include "tensorflow/lite/kernels/op_macros.h"
     40 #include "tensorflow/lite/string_util.h"
     41 
     42 namespace tflite {
     43 namespace ops {
     44 namespace builtin {
     45 
     46 namespace {
     47 
     48 TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
     49   TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
     50   TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
     51 
     52   TF_LITE_ENSURE_EQ(context, GetInput(context, node, 0)->type, kTfLiteString);
     53   TF_LITE_ENSURE_EQ(context, GetOutput(context, node, 0)->type, kTfLiteString);
     54   return kTfLiteOk;
     55 }
     56 
     57 bool ShouldIncludeCurrentNgram(const TfLiteSkipGramParams* params, int size) {
     58   if (size <= 0) {
     59     return false;
     60   }
     61   if (params->include_all_ngrams) {
     62     return size <= params->ngram_size;
     63   } else {
     64     return size == params->ngram_size;
     65   }
     66 }
     67 
     68 bool ShouldStepInRecursion(const TfLiteSkipGramParams* params,
     69                            const std::vector<int>& stack, int stack_idx,
     70                            int num_words) {
     71   // If current stack size and next word enumeration are within valid range.
     72   if (stack_idx < params->ngram_size && stack[stack_idx] + 1 < num_words) {
     73     // If this stack is empty, step in for first word enumeration.
     74     if (stack_idx == 0) {
     75       return true;
     76     }
     77     // If next word enumeration are within the range of max_skip_size.
     78     // NOTE: equivalent to
     79     //   next_word_idx = stack[stack_idx] + 1
     80     //   next_word_idx - stack[stack_idx-1] <= max_skip_size + 1
     81     if (stack[stack_idx] - stack[stack_idx - 1] <= params->max_skip_size) {
     82       return true;
     83     }
     84   }
     85   return false;
     86 }
     87 
     88 TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
     89   auto* params = reinterpret_cast<TfLiteSkipGramParams*>(node->builtin_data);
     90 
     91   // Split sentence to words.
     92   std::vector<StringRef> words;
     93   tflite::StringRef strref = tflite::GetString(GetInput(context, node, 0), 0);
     94   int prev_idx = 0;
     95   for (int i = 1; i < strref.len; i++) {
     96     if (isspace(*(strref.str + i))) {
     97       if (i > prev_idx && !isspace(*(strref.str + prev_idx))) {
     98         words.push_back({strref.str + prev_idx, i - prev_idx});
     99       }
    100       prev_idx = i + 1;
    101     }
    102   }
    103   if (strref.len > prev_idx) {
    104     words.push_back({strref.str + prev_idx, strref.len - prev_idx});
    105   }
    106 
    107   // Generate n-grams recursively.
    108   tflite::DynamicBuffer buf;
    109   if (words.size() < params->ngram_size) {
    110     buf.WriteToTensorAsVector(GetOutput(context, node, 0));
    111     return kTfLiteOk;
    112   }
    113 
    114   // Stack stores the index of word used to generate ngram.
    115   // The size of stack is the size of ngram.
    116   std::vector<int> stack(params->ngram_size, 0);
    117   // Stack index that indicates which depth the recursion is operating at.
    118   int stack_idx = 1;
    119   int num_words = words.size();
    120 
    121   while (stack_idx >= 0) {
    122     if (ShouldStepInRecursion(params, stack, stack_idx, num_words)) {
    123       // When current depth can fill with a new word
    124       // and the new word is within the max range to skip,
    125       // fill this word to stack, recurse into next depth.
    126       stack[stack_idx]++;
    127       stack_idx++;
    128       if (stack_idx < params->ngram_size) {
    129         stack[stack_idx] = stack[stack_idx - 1];
    130       }
    131     } else {
    132       if (ShouldIncludeCurrentNgram(params, stack_idx)) {
    133         // Add n-gram to tensor buffer when the stack has filled with enough
    134         // words to generate the ngram.
    135         std::vector<StringRef> gram(stack_idx);
    136         for (int i = 0; i < stack_idx; i++) {
    137           gram[i] = words[stack[i]];
    138         }
    139         buf.AddJoinedString(gram, ' ');
    140       }
    141       // When current depth cannot fill with a valid new word,
    142       // and not in last depth to generate ngram,
    143       // step back to previous depth to iterate to next possible word.
    144       stack_idx--;
    145     }
    146   }
    147 
    148   buf.WriteToTensorAsVector(GetOutput(context, node, 0));
    149   return kTfLiteOk;
    150 }
    151 }  // namespace
    152 
    153 TfLiteRegistration* Register_SKIP_GRAM() {
    154   static TfLiteRegistration r = {nullptr, nullptr, Prepare, Eval};
    155   return &r;
    156 }
    157 
    158 }  // namespace builtin
    159 }  // namespace ops
    160 }  // namespace tflite
    161