beam_reader_ops.cc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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 <algorithm>
  13. #include <deque>
  14. #include <map>
  15. #include <memory>
  16. #include <string>
  17. #include <utility>
  18. #include <vector>
  19. #include "syntaxnet/base.h"
  20. #include "syntaxnet/parser_state.h"
  21. #include "syntaxnet/parser_transitions.h"
  22. #include "syntaxnet/sentence_batch.h"
  23. #include "syntaxnet/sentence.pb.h"
  24. #include "syntaxnet/shared_store.h"
  25. #include "syntaxnet/sparse.pb.h"
  26. #include "syntaxnet/task_context.h"
  27. #include "syntaxnet/task_spec.pb.h"
  28. #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
  29. #include "tensorflow/core/framework/op_kernel.h"
  30. #include "tensorflow/core/framework/tensor.h"
  31. #include "tensorflow/core/framework/tensor_shape.h"
  32. #include "tensorflow/core/lib/core/status.h"
  33. #include "tensorflow/core/lib/io/inputbuffer.h"
  34. #include "tensorflow/core/platform/env.h"
  35. using tensorflow::DEVICE_CPU;
  36. using tensorflow::DT_BOOL;
  37. using tensorflow::DT_FLOAT;
  38. using tensorflow::DT_INT32;
  39. using tensorflow::DT_INT64;
  40. using tensorflow::DT_STRING;
  41. using tensorflow::DataType;
  42. using tensorflow::OpKernel;
  43. using tensorflow::OpKernelConstruction;
  44. using tensorflow::OpKernelContext;
  45. using tensorflow::TTypes;
  46. using tensorflow::Tensor;
  47. using tensorflow::TensorShape;
  48. using tensorflow::errors::FailedPrecondition;
  49. using tensorflow::errors::InvalidArgument;
  50. namespace syntaxnet {
  51. // Wraps ParserState so that the history of transitions (actions
  52. // performed and the beam slot they were performed in) are recorded.
  53. struct ParserStateWithHistory {
  54. public:
  55. // New state with an empty history.
  56. explicit ParserStateWithHistory(const ParserState &s) : state(s.Clone()) {}
  57. // New state obtained by cloning the given state and applying the given
  58. // action. The given beam slot and action are appended to the history.
  59. ParserStateWithHistory(const ParserStateWithHistory &next,
  60. const ParserTransitionSystem &transitions, int32 slot,
  61. int32 action, float score)
  62. : state(next.state->Clone()),
  63. slot_history(next.slot_history),
  64. action_history(next.action_history),
  65. score_history(next.score_history) {
  66. transitions.PerformAction(action, state.get());
  67. slot_history.push_back(slot);
  68. action_history.push_back(action);
  69. score_history.push_back(score);
  70. }
  71. std::unique_ptr<ParserState> state;
  72. std::vector<int32> slot_history;
  73. std::vector<int32> action_history;
  74. std::vector<float> score_history;
  75. private:
  76. TF_DISALLOW_COPY_AND_ASSIGN(ParserStateWithHistory);
  77. };
  78. struct BatchStateOptions {
  79. // Maximum number of parser states in a beam.
  80. int max_beam_size;
  81. // Number of parallel sentences to decode.
  82. int batch_size;
  83. // Argument prefix for context parameters.
  84. string arg_prefix;
  85. // Corpus name to read from from context inputs.
  86. string corpus_name;
  87. // Whether we allow weights in SparseFeatures protos.
  88. bool allow_feature_weights;
  89. // Whether beams should be considered alive until all states are final, or
  90. // until the gold path falls off.
  91. bool continue_until_all_final;
  92. // Whether to skip to a new sentence after each training step.
  93. bool always_start_new_sentences;
  94. // Parameter for deciding which tokens to score.
  95. string scoring_type;
  96. };
  97. // Encapsulates the environment needed to parse with a beam, keeping a
  98. // record of path histories.
  99. class BeamState {
  100. public:
  101. // The agenda is keyed by a tuple that is the score followed by an
  102. // int that is -1 if the path coincides with the gold path and 0
  103. // otherwise. The lexicographic ordering of the keys therefore
  104. // ensures that for all paths sharing the same score, the gold path
  105. // will always be at the bottom. This situation can occur at the
  106. // onset of training when all weights are zero and therefore all
  107. // paths have an identically zero score.
  108. typedef std::pair<double, int> KeyType;
  109. typedef std::multimap<KeyType, std::unique_ptr<ParserStateWithHistory>>
  110. AgendaType;
  111. typedef std::pair<const KeyType, std::unique_ptr<ParserStateWithHistory>>
  112. AgendaItem;
  113. typedef Eigen::Tensor<float, 2, Eigen::RowMajor, Eigen::DenseIndex>
  114. ScoreMatrixType;
  115. // The beam can be
  116. // - ALIVE: parsing is still active, features are being output for at least
  117. // some slots in the beam.
  118. // - DYING: features should be output for this beam only one more time, then
  119. // the beam will be DEAD. This state is reached when the gold path falls
  120. // out of the beam and features have to be output one last time.
  121. // - DEAD: parsing is not active, features are not being output and the no
  122. // actions are taken on the states.
  123. enum State { ALIVE = 0, DYING = 1, DEAD = 2 };
  124. explicit BeamState(const BatchStateOptions &options) : options_(options) {}
  125. void Reset() {
  126. if (options_.always_start_new_sentences ||
  127. gold_ == nullptr || transition_system_->IsFinalState(*gold_)) {
  128. AdvanceSentence();
  129. }
  130. slots_.clear();
  131. if (gold_ == nullptr) {
  132. state_ = DEAD; // EOF has been reached.
  133. } else {
  134. gold_->set_is_gold(true);
  135. slots_.emplace(KeyType(0.0, -1), std::unique_ptr<ParserStateWithHistory>(
  136. new ParserStateWithHistory(*gold_)));
  137. state_ = ALIVE;
  138. }
  139. }
  140. void UpdateAllFinal() {
  141. all_final_ = true;
  142. for (const AgendaItem &item : slots_) {
  143. if (!transition_system_->IsFinalState(*item.second->state)) {
  144. all_final_ = false;
  145. break;
  146. }
  147. }
  148. if (all_final_) {
  149. state_ = DEAD;
  150. }
  151. }
  152. // This method updates the beam. For all elements of the beam, all
  153. // allowed transitions are scored and insterted into a new beam. The
  154. // beam size is capped by discarding the lowest scoring slots at any
  155. // given time. There is one exception to this process: the gold path
  156. // is forced to remain in the beam at all times, even if it scores
  157. // low. This is to ensure that the gold path can be used for
  158. // training at the moment it would otherwise fall off (and be absent
  159. // from) the beam.
  160. void Advance(const ScoreMatrixType &scores) {
  161. // If the beam was in the state of DYING, it is now DEAD.
  162. if (state_ == DYING) state_ = DEAD;
  163. // When to stop advancing depends on the 'continue_until_all_final' arg.
  164. if (!IsAlive() || gold_ == nullptr) return;
  165. AdvanceGold();
  166. const int score_rows = scores.dimension(0);
  167. const int num_actions = scores.dimension(1);
  168. // Advance beam.
  169. AgendaType previous_slots;
  170. previous_slots.swap(slots_);
  171. CHECK_EQ(state_, ALIVE);
  172. int slot = 0;
  173. for (AgendaItem &item : previous_slots) {
  174. {
  175. ParserState *current = item.second->state.get();
  176. VLOG(2) << "Slot: " << slot;
  177. VLOG(2) << "Parser state: " << current->ToString();
  178. VLOG(2) << "Parser state cumulative score: " << item.first.first << " "
  179. << (item.first.second < 0 ? "golden" : "");
  180. }
  181. if (!transition_system_->IsFinalState(*item.second->state)) {
  182. // Not a final state.
  183. for (int action = 0; action < num_actions; ++action) {
  184. // Is action allowed?
  185. if (!transition_system_->IsAllowedAction(action,
  186. *item.second->state)) {
  187. continue;
  188. }
  189. CHECK_LT(slot, score_rows);
  190. MaybeInsertWithNewAction(item, slot, scores(slot, action), action);
  191. PruneBeam();
  192. }
  193. } else {
  194. // Final state: no need to advance.
  195. MaybeInsert(&item);
  196. PruneBeam();
  197. }
  198. ++slot;
  199. }
  200. UpdateAllFinal();
  201. }
  202. void PopulateFeatureOutputs(
  203. std::vector<std::vector<std::vector<SparseFeatures>>> *features) {
  204. for (const AgendaItem &item : slots_) {
  205. VLOG(2) << "State: " << item.second->state->ToString();
  206. std::vector<std::vector<SparseFeatures>> f =
  207. features_->ExtractSparseFeatures(*workspace_, *item.second->state);
  208. for (size_t i = 0; i < f.size(); ++i) (*features)[i].push_back(f[i]);
  209. }
  210. }
  211. int BeamSize() const { return slots_.size(); }
  212. bool IsAlive() const { return state_ == ALIVE; }
  213. bool IsDead() const { return state_ == DEAD; }
  214. bool AllFinal() const { return all_final_; }
  215. // The current contents of the beam.
  216. AgendaType slots_;
  217. // Which batch this refers to.
  218. int beam_id_ = 0;
  219. // Sentence batch reader.
  220. SentenceBatch *sentence_batch_ = nullptr;
  221. // Label map.
  222. const TermFrequencyMap *label_map_ = nullptr;
  223. // Transition system.
  224. const ParserTransitionSystem *transition_system_ = nullptr;
  225. // Feature extractor.
  226. const ParserEmbeddingFeatureExtractor *features_ = nullptr;
  227. // Feature workspace set.
  228. WorkspaceSet *workspace_ = nullptr;
  229. // Internal workspace registry for use in feature extraction.
  230. WorkspaceRegistry *workspace_registry_ = nullptr;
  231. // ParserState used to get gold actions.
  232. std::unique_ptr<ParserState> gold_;
  233. private:
  234. // Creates a new ParserState if there's another sentence to be read.
  235. void AdvanceSentence() {
  236. gold_.reset();
  237. if (sentence_batch_->AdvanceSentence(beam_id_)) {
  238. gold_.reset(new ParserState(sentence_batch_->sentence(beam_id_),
  239. transition_system_->NewTransitionState(true),
  240. label_map_));
  241. workspace_->Reset(*workspace_registry_);
  242. features_->Preprocess(workspace_, gold_.get());
  243. }
  244. }
  245. void AdvanceGold() {
  246. gold_action_ = -1;
  247. if (!transition_system_->IsFinalState(*gold_)) {
  248. gold_action_ = transition_system_->GetNextGoldAction(*gold_);
  249. if (transition_system_->IsAllowedAction(gold_action_, *gold_)) {
  250. // In cases where the gold annotation is incompatible with the
  251. // transition system, the action returned as gold might be not allowed.
  252. transition_system_->PerformAction(gold_action_, gold_.get());
  253. }
  254. }
  255. }
  256. // Removes the first non-gold beam element if the beam is larger than
  257. // the maximum beam size. If the gold element was at the bottom of the
  258. // beam, sets the beam state to DYING, otherwise leaves the state alone.
  259. void PruneBeam() {
  260. if (static_cast<int>(slots_.size()) > options_.max_beam_size) {
  261. auto bottom = slots_.begin();
  262. if (!options_.continue_until_all_final &&
  263. bottom->second->state->is_gold()) {
  264. state_ = DYING;
  265. ++bottom;
  266. }
  267. slots_.erase(bottom);
  268. }
  269. }
  270. // Inserts an item in the beam if
  271. // - the item is gold,
  272. // - the beam is not full, or
  273. // - the item's new score is greater than the lowest score in the beam after
  274. // the score has been incremented by given delta_score.
  275. // Inserted items have slot, delta_score and action appended to their history.
  276. void MaybeInsertWithNewAction(const AgendaItem &item, const int slot,
  277. const double delta_score, const int action) {
  278. const double score = item.first.first + delta_score;
  279. const bool is_gold =
  280. item.second->state->is_gold() && action == gold_action_;
  281. if (is_gold || static_cast<int>(slots_.size()) < options_.max_beam_size ||
  282. score > slots_.begin()->first.first) {
  283. const KeyType key{score, -static_cast<int>(is_gold)};
  284. slots_.emplace(key, std::unique_ptr<ParserStateWithHistory>(
  285. new ParserStateWithHistory(
  286. *item.second, *transition_system_, slot,
  287. action, delta_score)))
  288. ->second->state->set_is_gold(is_gold);
  289. }
  290. }
  291. // Inserts an item in the beam if
  292. // - the item is gold,
  293. // - the beam is not full, or
  294. // - the item's new score is greater than the lowest score in the beam.
  295. // The history of inserted items is left untouched.
  296. void MaybeInsert(AgendaItem *item) {
  297. const bool is_gold = item->second->state->is_gold();
  298. const double score = item->first.first;
  299. if (is_gold || static_cast<int>(slots_.size()) < options_.max_beam_size ||
  300. score > slots_.begin()->first.first) {
  301. slots_.emplace(item->first, std::move(item->second));
  302. }
  303. }
  304. // Limits the number of slots on the beam.
  305. const BatchStateOptions &options_;
  306. int gold_action_ = -1;
  307. State state_ = ALIVE;
  308. bool all_final_ = false;
  309. TF_DISALLOW_COPY_AND_ASSIGN(BeamState);
  310. };
  311. // Encapsulates the state of a batch of beams. It is an object of this
  312. // type that will persist through repeated Op evaluations as the
  313. // multiple steps are computed in sequence.
  314. class BatchState {
  315. public:
  316. explicit BatchState(const BatchStateOptions &options)
  317. : options_(options), features_(options.arg_prefix) {}
  318. ~BatchState() { SharedStore::Release(label_map_); }
  319. void Init(TaskContext *task_context) {
  320. // Create sentence batch.
  321. sentence_batch_.reset(
  322. new SentenceBatch(BatchSize(), options_.corpus_name));
  323. sentence_batch_->Init(task_context);
  324. // Create transition system.
  325. transition_system_.reset(ParserTransitionSystem::Create(task_context->Get(
  326. tensorflow::strings::StrCat(options_.arg_prefix, "_transition_system"),
  327. "arc-standard")));
  328. transition_system_->Setup(task_context);
  329. transition_system_->Init(task_context);
  330. // Create label map.
  331. string label_map_path =
  332. TaskContext::InputFile(*task_context->GetInput("label-map"));
  333. label_map_ = SharedStoreUtils::GetWithDefaultName<TermFrequencyMap>(
  334. label_map_path, 0, 0);
  335. // Setup features.
  336. features_.Setup(task_context);
  337. features_.Init(task_context);
  338. features_.RequestWorkspaces(&workspace_registry_);
  339. // Create workspaces.
  340. workspaces_.resize(BatchSize());
  341. // Create beams.
  342. beams_.clear();
  343. for (int beam_id = 0; beam_id < BatchSize(); ++beam_id) {
  344. beams_.emplace_back(options_);
  345. beams_[beam_id].beam_id_ = beam_id;
  346. beams_[beam_id].sentence_batch_ = sentence_batch_.get();
  347. beams_[beam_id].transition_system_ = transition_system_.get();
  348. beams_[beam_id].label_map_ = label_map_;
  349. beams_[beam_id].features_ = &features_;
  350. beams_[beam_id].workspace_ = &workspaces_[beam_id];
  351. beams_[beam_id].workspace_registry_ = &workspace_registry_;
  352. }
  353. }
  354. void ResetBeams() {
  355. for (BeamState &beam : beams_) {
  356. beam.Reset();
  357. }
  358. // Rewind if no states remain in the batch (we need to rewind the corpus).
  359. if (sentence_batch_->size() == 0) {
  360. ++epoch_;
  361. VLOG(2) << "Starting epoch " << epoch_;
  362. sentence_batch_->Rewind();
  363. }
  364. }
  365. // Resets the offset vectors required for a single run because we're
  366. // starting a new matrix of scores.
  367. void ResetOffsets() {
  368. beam_offsets_.clear();
  369. step_offsets_ = {0};
  370. UpdateOffsets();
  371. }
  372. void AdvanceBeam(const int beam_id,
  373. const TTypes<float>::ConstMatrix &scores) {
  374. const int offset = beam_offsets_.back()[beam_id];
  375. Eigen::array<Eigen::DenseIndex, 2> offsets = {offset, 0};
  376. Eigen::array<Eigen::DenseIndex, 2> extents = {
  377. beam_offsets_.back()[beam_id + 1] - offset, NumActions()};
  378. BeamState::ScoreMatrixType beam_scores = scores.slice(offsets, extents);
  379. beams_[beam_id].Advance(beam_scores);
  380. }
  381. void UpdateOffsets() {
  382. beam_offsets_.emplace_back(BatchSize() + 1, 0);
  383. std::vector<int> &offsets = beam_offsets_.back();
  384. for (int beam_id = 0; beam_id < BatchSize(); ++beam_id) {
  385. // If the beam is ALIVE or DYING (but not DEAD), we want to
  386. // output the activations.
  387. const BeamState &beam = beams_[beam_id];
  388. const int beam_size = beam.IsDead() ? 0 : beam.BeamSize();
  389. offsets[beam_id + 1] = offsets[beam_id] + beam_size;
  390. }
  391. const int output_size = offsets.back();
  392. step_offsets_.push_back(step_offsets_.back() + output_size);
  393. }
  394. tensorflow::Status PopulateFeatureOutputs(OpKernelContext *context) {
  395. const int feature_size = FeatureSize();
  396. std::vector<std::vector<std::vector<SparseFeatures>>> features(
  397. feature_size);
  398. for (int beam_id = 0; beam_id < BatchSize(); ++beam_id) {
  399. if (!beams_[beam_id].IsDead()) {
  400. beams_[beam_id].PopulateFeatureOutputs(&features);
  401. }
  402. }
  403. CHECK_EQ(features.size(), feature_size);
  404. Tensor *output;
  405. const int total_slots = beam_offsets_.back().back();
  406. for (int i = 0; i < feature_size; ++i) {
  407. std::vector<std::vector<SparseFeatures>> &f = features[i];
  408. CHECK_EQ(total_slots, f.size());
  409. if (total_slots == 0) {
  410. TF_RETURN_IF_ERROR(
  411. context->allocate_output(i, TensorShape({0, 0}), &output));
  412. } else {
  413. const int size = f[0].size();
  414. TF_RETURN_IF_ERROR(context->allocate_output(
  415. i, TensorShape({total_slots, size}), &output));
  416. for (int j = 0; j < total_slots; ++j) {
  417. CHECK_EQ(size, f[j].size());
  418. for (int k = 0; k < size; ++k) {
  419. if (!options_.allow_feature_weights && f[j][k].weight_size() > 0) {
  420. return FailedPrecondition(
  421. "Feature weights are not allowed when allow_feature_weights "
  422. "is set to false.");
  423. }
  424. output->matrix<string>()(j, k) = f[j][k].SerializeAsString();
  425. }
  426. }
  427. }
  428. }
  429. return tensorflow::Status::OK();
  430. }
  431. // Returns the offset (i.e. row number) of a particular beam at a
  432. // particular step in the final concatenated score matrix.
  433. int GetOffset(const int step, const int beam_id) const {
  434. return step_offsets_[step] + beam_offsets_[step][beam_id];
  435. }
  436. int FeatureSize() const { return features_.embedding_dims().size(); }
  437. int NumActions() const {
  438. return transition_system_->NumActions(label_map_->Size());
  439. }
  440. int BatchSize() const { return options_.batch_size; }
  441. const BeamState &Beam(const int i) const { return beams_[i]; }
  442. int Epoch() const { return epoch_; }
  443. const string &ScoringType() const { return options_.scoring_type; }
  444. private:
  445. const BatchStateOptions options_;
  446. // How many times the document source has been rewound.
  447. int epoch_ = 0;
  448. // Batch of sentences, and the corresponding parser states.
  449. std::unique_ptr<SentenceBatch> sentence_batch_;
  450. // Transition system.
  451. std::unique_ptr<ParserTransitionSystem> transition_system_;
  452. // Label map for transition system..
  453. const TermFrequencyMap *label_map_;
  454. // Typed feature extractor for embeddings.
  455. ParserEmbeddingFeatureExtractor features_;
  456. // Batch: WorkspaceSet objects.
  457. std::vector<WorkspaceSet> workspaces_;
  458. // Internal workspace registry for use in feature extraction.
  459. WorkspaceRegistry workspace_registry_;
  460. std::deque<BeamState> beams_;
  461. std::vector<std::vector<int>> beam_offsets_;
  462. // Keeps track of the slot offset of each step.
  463. std::vector<int> step_offsets_;
  464. TF_DISALLOW_COPY_AND_ASSIGN(BatchState);
  465. };
  466. // Creates a BeamState and hooks it up with a parser. This Op needs to
  467. // remain alive for the duration of the parse.
  468. class BeamParseReader : public OpKernel {
  469. public:
  470. explicit BeamParseReader(OpKernelConstruction *context) : OpKernel(context) {
  471. string file_path;
  472. int feature_size;
  473. BatchStateOptions options;
  474. OP_REQUIRES_OK(context, context->GetAttr("task_context", &file_path));
  475. OP_REQUIRES_OK(context, context->GetAttr("feature_size", &feature_size));
  476. OP_REQUIRES_OK(context,
  477. context->GetAttr("beam_size", &options.max_beam_size));
  478. OP_REQUIRES_OK(context,
  479. context->GetAttr("batch_size", &options.batch_size));
  480. OP_REQUIRES_OK(context,
  481. context->GetAttr("arg_prefix", &options.arg_prefix));
  482. OP_REQUIRES_OK(context,
  483. context->GetAttr("corpus_name", &options.corpus_name));
  484. OP_REQUIRES_OK(context, context->GetAttr("allow_feature_weights",
  485. &options.allow_feature_weights));
  486. OP_REQUIRES_OK(context,
  487. context->GetAttr("continue_until_all_final",
  488. &options.continue_until_all_final));
  489. OP_REQUIRES_OK(context,
  490. context->GetAttr("always_start_new_sentences",
  491. &options.always_start_new_sentences));
  492. // Reads task context from file.
  493. string data;
  494. OP_REQUIRES_OK(context, ReadFileToString(tensorflow::Env::Default(),
  495. file_path, &data));
  496. TaskContext task_context;
  497. OP_REQUIRES(context,
  498. TextFormat::ParseFromString(data, task_context.mutable_spec()),
  499. InvalidArgument("Could not parse task context at ", file_path));
  500. OP_REQUIRES(
  501. context, options.batch_size > 0,
  502. InvalidArgument("Batch size ", options.batch_size, " too small."));
  503. options.scoring_type = task_context.Get(
  504. tensorflow::strings::StrCat(options.arg_prefix, "_scoring"), "");
  505. // Create batch state.
  506. batch_state_.reset(new BatchState(options));
  507. batch_state_->Init(&task_context);
  508. // Check number of feature groups matches the task context.
  509. const int required_size = batch_state_->FeatureSize();
  510. OP_REQUIRES(
  511. context, feature_size == required_size,
  512. InvalidArgument("Task context requires feature_size=", required_size));
  513. // Set expected signature.
  514. std::vector<DataType> output_types(feature_size, DT_STRING);
  515. output_types.push_back(DT_INT64);
  516. output_types.push_back(DT_INT32);
  517. OP_REQUIRES_OK(context, context->MatchSignature({}, output_types));
  518. }
  519. void Compute(OpKernelContext *context) override {
  520. mutex_lock lock(mu_);
  521. // Write features.
  522. batch_state_->ResetBeams();
  523. batch_state_->ResetOffsets();
  524. batch_state_->PopulateFeatureOutputs(context);
  525. // Forward the beam state vector.
  526. Tensor *output;
  527. const int feature_size = batch_state_->FeatureSize();
  528. OP_REQUIRES_OK(context, context->allocate_output(feature_size,
  529. TensorShape({}), &output));
  530. output->scalar<int64>()() = reinterpret_cast<int64>(batch_state_.get());
  531. // Output number of epochs.
  532. OP_REQUIRES_OK(context, context->allocate_output(feature_size + 1,
  533. TensorShape({}), &output));
  534. output->scalar<int32>()() = batch_state_->Epoch();
  535. }
  536. private:
  537. // mutex to synchronize access to Compute.
  538. mutex mu_;
  539. // The object whose handle will be passed among the Ops.
  540. std::unique_ptr<BatchState> batch_state_;
  541. TF_DISALLOW_COPY_AND_ASSIGN(BeamParseReader);
  542. };
  543. REGISTER_KERNEL_BUILDER(Name("BeamParseReader").Device(DEVICE_CPU),
  544. BeamParseReader);
  545. // Updates the beam based on incoming scores and outputs new feature vectors
  546. // based on the updated beam.
  547. class BeamParser : public OpKernel {
  548. public:
  549. explicit BeamParser(OpKernelConstruction *context) : OpKernel(context) {
  550. int feature_size;
  551. OP_REQUIRES_OK(context, context->GetAttr("feature_size", &feature_size));
  552. // Set expected signature.
  553. std::vector<DataType> output_types(feature_size, DT_STRING);
  554. output_types.push_back(DT_INT64);
  555. output_types.push_back(DT_BOOL);
  556. OP_REQUIRES_OK(context,
  557. context->MatchSignature({DT_INT64, DT_FLOAT}, output_types));
  558. }
  559. void Compute(OpKernelContext *context) override {
  560. BatchState *batch_state =
  561. reinterpret_cast<BatchState *>(context->input(0).scalar<int64>()());
  562. const TTypes<float>::ConstMatrix scores = context->input(1).matrix<float>();
  563. VLOG(2) << "Scores: " << scores;
  564. CHECK_EQ(scores.dimension(1), batch_state->NumActions());
  565. // In AdvanceBeam we use beam_offsets_[beam_id] to determine the slice of
  566. // scores that should be used for advancing, but beam_offsets_[beam_id] only
  567. // exists for beams that have a sentence loaded.
  568. const int batch_size = batch_state->BatchSize();
  569. for (int beam_id = 0; beam_id < batch_size; ++beam_id) {
  570. batch_state->AdvanceBeam(beam_id, scores);
  571. }
  572. batch_state->UpdateOffsets();
  573. // Forward the beam state unmodified.
  574. Tensor *output;
  575. const int feature_size = batch_state->FeatureSize();
  576. OP_REQUIRES_OK(context, context->allocate_output(feature_size,
  577. TensorShape({}), &output));
  578. output->scalar<int64>()() = context->input(0).scalar<int64>()();
  579. // Output the new features of all the slots in all the beams.
  580. OP_REQUIRES_OK(context, batch_state->PopulateFeatureOutputs(context));
  581. // Output whether the beams are alive.
  582. OP_REQUIRES_OK(
  583. context, context->allocate_output(feature_size + 1,
  584. TensorShape({batch_size}), &output));
  585. for (int beam_id = 0; beam_id < batch_size; ++beam_id) {
  586. output->vec<bool>()(beam_id) = batch_state->Beam(beam_id).IsAlive();
  587. }
  588. }
  589. private:
  590. TF_DISALLOW_COPY_AND_ASSIGN(BeamParser);
  591. };
  592. REGISTER_KERNEL_BUILDER(Name("BeamParser").Device(DEVICE_CPU), BeamParser);
  593. // Extracts the paths for the elements of the current beams and returns
  594. // indices into a scoring matrix that is assumed to have been
  595. // constructed along with the beam search.
  596. class BeamParserOutput : public OpKernel {
  597. public:
  598. explicit BeamParserOutput(OpKernelConstruction *context) : OpKernel(context) {
  599. // Set expected signature.
  600. OP_REQUIRES_OK(context,
  601. context->MatchSignature(
  602. {DT_INT64}, {DT_INT32, DT_INT32, DT_INT32, DT_FLOAT}));
  603. }
  604. void Compute(OpKernelContext *context) override {
  605. BatchState *batch_state =
  606. reinterpret_cast<BatchState *>(context->input(0).scalar<int64>()());
  607. const int num_actions = batch_state->NumActions();
  608. const int batch_size = batch_state->BatchSize();
  609. // Vectors for output.
  610. //
  611. // Each step of each batch:path gets its index computed and a
  612. // unique path id assigned.
  613. std::vector<int32> indices;
  614. std::vector<int32> path_ids;
  615. // Each unique path gets a batch id and a slot (in the beam)
  616. // id. These are in effect the row and column of the final
  617. // 'logits' matrix going to CrossEntropy.
  618. std::vector<int32> beam_ids;
  619. std::vector<int32> slot_ids;
  620. // To compute the cross entropy we also need the slot id of the
  621. // gold path, one per batch.
  622. std::vector<int32> gold_slot(batch_size, -1);
  623. // For good measure we also output the path scores as computed by
  624. // the beam decoder, so it can be compared in tests with the path
  625. // scores computed via the indices in TF. This has the same length
  626. // as beam_ids and slot_ids.
  627. std::vector<float> path_scores;
  628. // The scores tensor has, conceptually, four dimensions: 1. number
  629. // of steps, 2. batch size, 3. number of paths on the beam at that
  630. // step, and 4. the number of actions scored. However this is not
  631. // a true tensor since the size of the beam at each step may not
  632. // be equal among all steps and among all batches. Only the batch
  633. // size and number of actions is fixed.
  634. int path_id = 0;
  635. for (int beam_id = 0; beam_id < batch_size; ++beam_id) {
  636. // This occurs at the end of the corpus, when there aren't enough
  637. // sentences to fill the batch.
  638. if (batch_state->Beam(beam_id).gold_ == nullptr) continue;
  639. // Populate the vectors that will index into the concatenated
  640. // scores tensor.
  641. int slot = 0;
  642. for (const auto &item : batch_state->Beam(beam_id).slots_) {
  643. beam_ids.push_back(beam_id);
  644. slot_ids.push_back(slot);
  645. path_scores.push_back(item.first.first);
  646. VLOG(2) << "PATH SCORE @ beam_id:" << beam_id << " slot:" << slot
  647. << " : " << item.first.first << " " << item.first.second;
  648. VLOG(2) << "SLOT HISTORY: "
  649. << utils::Join(item.second->slot_history, " ");
  650. VLOG(2) << "SCORE HISTORY: "
  651. << utils::Join(item.second->score_history, " ");
  652. VLOG(2) << "ACTION HISTORY: "
  653. << utils::Join(item.second->action_history, " ");
  654. // Record where the gold path ended up.
  655. if (item.second->state->is_gold()) {
  656. CHECK_EQ(gold_slot[beam_id], -1);
  657. gold_slot[beam_id] = slot;
  658. }
  659. for (size_t step = 0; step < item.second->slot_history.size(); ++step) {
  660. const int step_beam_offset = batch_state->GetOffset(step, beam_id);
  661. const int slot_index = item.second->slot_history[step];
  662. const int action_index = item.second->action_history[step];
  663. indices.push_back(num_actions * (step_beam_offset + slot_index) +
  664. action_index);
  665. path_ids.push_back(path_id);
  666. }
  667. ++slot;
  668. ++path_id;
  669. }
  670. // One and only path must be the golden one.
  671. CHECK_GE(gold_slot[beam_id], 0);
  672. }
  673. const int num_ix_elements = indices.size();
  674. Tensor *output;
  675. OP_REQUIRES_OK(context, context->allocate_output(
  676. 0, TensorShape({2, num_ix_elements}), &output));
  677. auto indices_and_path_ids = output->matrix<int32>();
  678. for (size_t i = 0; i < indices.size(); ++i) {
  679. indices_and_path_ids(0, i) = indices[i];
  680. indices_and_path_ids(1, i) = path_ids[i];
  681. }
  682. const int num_path_elements = beam_ids.size();
  683. OP_REQUIRES_OK(context,
  684. context->allocate_output(
  685. 1, TensorShape({2, num_path_elements}), &output));
  686. auto beam_and_slot_ids = output->matrix<int32>();
  687. for (size_t i = 0; i < beam_ids.size(); ++i) {
  688. beam_and_slot_ids(0, i) = beam_ids[i];
  689. beam_and_slot_ids(1, i) = slot_ids[i];
  690. }
  691. OP_REQUIRES_OK(context, context->allocate_output(
  692. 2, TensorShape({batch_size}), &output));
  693. std::copy(gold_slot.begin(), gold_slot.end(), output->vec<int32>().data());
  694. OP_REQUIRES_OK(context, context->allocate_output(
  695. 3, TensorShape({num_path_elements}), &output));
  696. std::copy(path_scores.begin(), path_scores.end(),
  697. output->vec<float>().data());
  698. }
  699. private:
  700. TF_DISALLOW_COPY_AND_ASSIGN(BeamParserOutput);
  701. };
  702. REGISTER_KERNEL_BUILDER(Name("BeamParserOutput").Device(DEVICE_CPU),
  703. BeamParserOutput);
  704. // Computes eval metrics for the best path in the input beams.
  705. class BeamEvalOutput : public OpKernel {
  706. public:
  707. explicit BeamEvalOutput(OpKernelConstruction *context) : OpKernel(context) {
  708. // Set expected signature.
  709. OP_REQUIRES_OK(context,
  710. context->MatchSignature({DT_INT64}, {DT_INT32, DT_STRING}));
  711. }
  712. void Compute(OpKernelContext *context) override {
  713. int num_tokens = 0;
  714. int num_correct = 0;
  715. int all_final = 0;
  716. BatchState *batch_state =
  717. reinterpret_cast<BatchState *>(context->input(0).scalar<int64>()());
  718. const int batch_size = batch_state->BatchSize();
  719. vector<Sentence> documents;
  720. for (int beam_id = 0; beam_id < batch_size; ++beam_id) {
  721. if (batch_state->Beam(beam_id).gold_ != nullptr &&
  722. batch_state->Beam(beam_id).AllFinal()) {
  723. ++all_final;
  724. const auto &item = *batch_state->Beam(beam_id).slots_.rbegin();
  725. ComputeTokenAccuracy(*item.second->state, batch_state->ScoringType(),
  726. &num_tokens, &num_correct);
  727. documents.push_back(item.second->state->sentence());
  728. item.second->state->AddParseToDocument(&documents.back());
  729. }
  730. }
  731. Tensor *output;
  732. OP_REQUIRES_OK(context,
  733. context->allocate_output(0, TensorShape({2}), &output));
  734. auto eval_metrics = output->vec<int32>();
  735. eval_metrics(0) = num_tokens;
  736. eval_metrics(1) = num_correct;
  737. const int output_size = documents.size();
  738. OP_REQUIRES_OK(context, context->allocate_output(
  739. 1, TensorShape({output_size}), &output));
  740. for (int i = 0; i < output_size; ++i) {
  741. output->vec<string>()(i) = documents[i].SerializeAsString();
  742. }
  743. }
  744. private:
  745. // Tallies the # of correct and incorrect tokens for a given ParserState.
  746. void ComputeTokenAccuracy(const ParserState &state,
  747. const string &scoring_type,
  748. int *num_tokens, int *num_correct) {
  749. for (int i = 0; i < state.sentence().token_size(); ++i) {
  750. const Token &token = state.GetToken(i);
  751. if (utils::PunctuationUtil::ScoreToken(token.word(), token.tag(),
  752. scoring_type)) {
  753. ++*num_tokens;
  754. if (state.IsTokenCorrect(i)) ++*num_correct;
  755. }
  756. }
  757. }
  758. TF_DISALLOW_COPY_AND_ASSIGN(BeamEvalOutput);
  759. };
  760. REGISTER_KERNEL_BUILDER(Name("BeamEvalOutput").Device(DEVICE_CPU),
  761. BeamEvalOutput);
  762. } // namespace syntaxnet