binary_segment_transitions.cc 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /* Copyright 2016 Google Inc. All Rights Reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ==============================================================================*/
  12. #include "syntaxnet/binary_segment_state.h"
  13. #include "syntaxnet/parser_features.h"
  14. #include "syntaxnet/parser_state.h"
  15. #include "syntaxnet/parser_transitions.h"
  16. #include "syntaxnet/term_frequency_map.h"
  17. namespace syntaxnet {
  18. // Given an input of utf8 characters, the BinarySegmentTransitionSystem
  19. // conducts word segmentation by performing one of the following two actions:
  20. // -START: starts a new word with the token at state.input, and also advances
  21. // the state.input.
  22. // -MERGE: adds the token at state.input to its prevous word, and also advances
  23. // state.input.
  24. //
  25. // Also see nlp/saft/components/segmentation/transition/binary-segment-state.h
  26. // for examples on handling spaces.
  27. class BinarySegmentTransitionSystem : public ParserTransitionSystem {
  28. public:
  29. BinarySegmentTransitionSystem() {}
  30. ParserTransitionState *NewTransitionState(bool train_mode) const override {
  31. return new BinarySegmentState();
  32. }
  33. // Action types for the segmentation-transition system.
  34. enum ParserActionType {
  35. START = 0,
  36. MERGE = 1,
  37. CARDINAL = 2
  38. };
  39. static int StartAction() { return 0; }
  40. static int MergeAction() { return 1; }
  41. // The system always starts a new word by default.
  42. ParserAction GetDefaultAction(const ParserState &state) const override {
  43. return START;
  44. }
  45. // Returns the number of action types.
  46. int NumActionTypes() const override {
  47. return CARDINAL;
  48. }
  49. // Returns the number of possible actions.
  50. int NumActions(int num_labels) const override {
  51. return CARDINAL;
  52. }
  53. // Returns the next gold action for a given state according to the underlying
  54. // annotated sentence. The training data for the transition system is created
  55. // by the binary-segmenter-data task. If a token's break_level is NO_BREAK,
  56. // then it is a MERGE, START otherwise. The only exception is that the first
  57. // token in a sentence for the transition sysytem is always a START.
  58. ParserAction GetNextGoldAction(const ParserState &state) const override {
  59. if (state.Next() == 0) return StartAction();
  60. const Token &token = state.GetToken(state.Next());
  61. return (token.break_level() != Token::NO_BREAK ?
  62. StartAction() : MergeAction());
  63. }
  64. // Both START and MERGE can be applied to any tokens in the sentence.
  65. bool IsAllowedAction(
  66. ParserAction action, const ParserState &state) const override {
  67. return true;
  68. }
  69. // Performs the specified action on a given parser state, without adding the
  70. // action to the state's history.
  71. void PerformActionWithoutHistory(
  72. ParserAction action, ParserState *state) const override {
  73. // Note when the action is less than 0, it is treated as a START.
  74. if (action < 0 || action == StartAction()) {
  75. MutableTransitionState(state)->AddStart(state->Next(), state);
  76. }
  77. state->Advance();
  78. }
  79. // Allows backoff to best allowable transition.
  80. bool BackOffToBestAllowableTransition() const override { return true; }
  81. // A state is a deterministic state iff no tokens have been consumed.
  82. bool IsDeterministicState(const ParserState &state) const override {
  83. return state.Next() == 0;
  84. }
  85. // For binary segmentation, a state is a final state iff all tokens have been
  86. // consumed.
  87. bool IsFinalState(const ParserState &state) const override {
  88. return state.EndOfInput();
  89. }
  90. // Returns a string representation of a parser action.
  91. string ActionAsString(
  92. ParserAction action, const ParserState &state) const override {
  93. return action == StartAction() ? "START" : "MERGE";
  94. }
  95. // Downcasts the TransitionState in ParserState to an BinarySegmentState.
  96. static BinarySegmentState *MutableTransitionState(ParserState *state) {
  97. return static_cast<BinarySegmentState *>(state->mutable_transition_state());
  98. }
  99. };
  100. REGISTER_TRANSITION_SYSTEM("binary-segment-transitions",
  101. BinarySegmentTransitionSystem);
  102. // Parser feature locator that returns the token in the sentence that is
  103. // argument() positions from the provided focus token.
  104. class OffsetFeatureLocator : public ParserIndexLocator<OffsetFeatureLocator> {
  105. public:
  106. // Update the current focus to a new location. If the initial focus or new
  107. // focus is outside the range of the sentence, returns -2.
  108. void UpdateArgs(const WorkspaceSet &workspaces, const ParserState &state,
  109. int *focus) const {
  110. if (*focus < -1 || *focus >= state.sentence().token_size()) {
  111. *focus = -2;
  112. return;
  113. }
  114. int new_focus = *focus + argument();
  115. if (new_focus < -1 || new_focus >= state.sentence().token_size()) {
  116. *focus = -2;
  117. return;
  118. }
  119. *focus = new_focus;
  120. }
  121. };
  122. REGISTER_PARSER_IDX_FEATURE_FUNCTION("offset", OffsetFeatureLocator);
  123. // Feature function that returns the id of bigram constructed by concatenating
  124. // word fields of tokens at focus and focus + 1.
  125. class CharBigramFunction : public ParserIndexFeatureFunction {
  126. public:
  127. void Setup(TaskContext *context) override {
  128. input_map_ = context->GetInput("char-ngram-map", "text", "");
  129. }
  130. void Init(TaskContext *context) override {
  131. min_freq_ = GetIntParameter("char-bigram-min-freq", 2);
  132. bigram_map_.Load(TaskContext::InputFile(*input_map_), min_freq_, -1);
  133. unknown_id_ = bigram_map_.Size();
  134. outside_id_ = unknown_id_ + 1;
  135. set_feature_type(
  136. new ResourceBasedFeatureType<CharBigramFunction>(name(), this, {}));
  137. }
  138. int64 NumValues() const {
  139. return outside_id_ + 1;
  140. }
  141. // Returns the string representation of the given feature value.
  142. string GetFeatureValueName(FeatureValue value) const {
  143. if (value == outside_id_) return "<OUTSIDE>";
  144. if (value == unknown_id_) return "<UNKNOWN>";
  145. return bigram_map_.GetTerm(value);
  146. }
  147. FeatureValue Compute(const WorkspaceSet &workspaces, const ParserState &state,
  148. int focus, const FeatureVector *result) const override {
  149. if (focus < 0 || focus >= state.sentence().token_size() - 1) {
  150. return outside_id_;
  151. }
  152. const int start = state.GetToken(focus).start();
  153. const int length = state.GetToken(focus + 1).end() - start + 1;
  154. CHECK_GT(length, 0);
  155. CHECK_LE(start + length, state.sentence().text().size());
  156. const char *data = state.sentence().text().data() + start;
  157. return bigram_map_.LookupIndex(string(data, length), unknown_id_);
  158. }
  159. private:
  160. // Task input for the word to id map. Not owned.
  161. TaskInput *input_map_ = nullptr;
  162. TermFrequencyMap bigram_map_;
  163. // Special ids of unknown words and out-of-range.
  164. int unknown_id_ = 0;
  165. int outside_id_ = 0;
  166. // Minimum frequency for term map.
  167. int min_freq_ = 2;
  168. };
  169. REGISTER_PARSER_IDX_FEATURE_FUNCTION("char-bigram", CharBigramFunction);
  170. // Feature function that returns the id of the n-th most recently constructed
  171. // word. Note that the argument, n, should be larger than 0. When equals to 0,
  172. // it points to the word which is not yet completed.
  173. class LastWordFeatureFunction : public ParserFeatureFunction {
  174. public:
  175. void Setup(TaskContext *context) override {
  176. input_word_map_ = context->GetInput("word-map", "text", "");
  177. }
  178. void Init(TaskContext *context) override {
  179. min_freq_ = GetIntParameter("min-freq", 0);
  180. max_num_terms_ = GetIntParameter("max-num-terms", 0);
  181. word_map_.Load(
  182. TaskContext::InputFile(*input_word_map_), min_freq_, max_num_terms_);
  183. unknown_id_ = word_map_.Size();
  184. outside_id_ = unknown_id_ + 1;
  185. set_feature_type(
  186. new ResourceBasedFeatureType<LastWordFeatureFunction>(
  187. name(), this, {}));
  188. }
  189. int64 NumValues() const {
  190. return outside_id_ + 1;
  191. }
  192. // Returns the string representation of the given feature value.
  193. string GetFeatureValueName(FeatureValue value) const {
  194. if (value == outside_id_) return "<OUTSIDE>";
  195. if (value == unknown_id_) return "<UNKNOWN>";
  196. DCHECK_GE(value, 0);
  197. DCHECK_LT(value, word_map_.Size());
  198. return word_map_.GetTerm(value);
  199. }
  200. FeatureValue Compute(const WorkspaceSet &workspaces, const ParserState &state,
  201. const FeatureVector *result) const override {
  202. // n should be larger than 0, since the current word is still under
  203. // construction.
  204. const int n = argument();
  205. CHECK_GT(n, 0);
  206. const auto *segment_state = static_cast<const BinarySegmentState *>(
  207. state.transition_state());
  208. if (n >= segment_state->NumStarts(state)) {
  209. return outside_id_;
  210. }
  211. const auto &sentence = state.sentence();
  212. const int start = segment_state->LastStart(n, state);
  213. const int end = segment_state->LastStart(n - 1, state) - 1;
  214. CHECK_GE(end, start);
  215. const int start_offset = state.GetToken(start).start();
  216. const int length = state.GetToken(end).end() - start_offset + 1;
  217. const auto *data = sentence.text().data() + start_offset;
  218. return word_map_.LookupIndex(string(data, length), unknown_id_);
  219. }
  220. private:
  221. // Task input for the word to id map. Not owned.
  222. TaskInput *input_word_map_ = nullptr;
  223. TermFrequencyMap word_map_;
  224. // Special ids of unknown words and out-of-range.
  225. int unknown_id_ = 0;
  226. int outside_id_ = 0;
  227. // Minimum frequency for term map.
  228. int min_freq_;
  229. // Maximum number of terms for term map.
  230. int max_num_terms_;
  231. };
  232. REGISTER_PARSER_FEATURE_FUNCTION("last-word", LastWordFeatureFunction);
  233. } // namespace syntaxnet