translate.py 7.34 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Copyright 2018 The TensorFlow Authors. 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.
# ==============================================================================
"""Translate text or files using trained transformer model."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
21
import numpy as np
22
23
import tensorflow as tf

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
24
from tensorflow.python.distribute import values
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from official.transformer.utils import tokenizer

_EXTRA_DECODE_LENGTH = 100
_BEAM_SIZE = 4
_ALPHA = 0.6


def _get_sorted_inputs(filename):
  """Read and sort lines from the file sorted by decreasing length.

  Args:
    filename: String name of file to read inputs from.
  Returns:
    Sorted list of inputs, and dictionary mapping original index->sorted index
    of each element.
  """
  with tf.io.gfile.GFile(filename) as f:
    records = f.read().split("\n")
    inputs = [record.strip() for record in records]
    if not inputs[-1]:
      inputs.pop()

  input_lens = [(i, len(line.split())) for i, line in enumerate(inputs)]
  sorted_input_lens = sorted(input_lens, key=lambda x: x[1], reverse=True)

  sorted_inputs = [None] * len(sorted_input_lens)
  sorted_keys = [0] * len(sorted_input_lens)
  for i, (index, _) in enumerate(sorted_input_lens):
    sorted_inputs[i] = inputs[index]
    sorted_keys[index] = i
  return sorted_inputs, sorted_keys


def _encode_and_add_eos(line, subtokenizer):
  """Encode line with subtokenizer, and add EOS id to the end."""
  return subtokenizer.encode(line) + [tokenizer.EOS_ID]


def _trim_and_decode(ids, subtokenizer):
  """Trim EOS and PAD tokens from ids, and decode to return a string."""
  try:
    index = list(ids).index(tokenizer.EOS_ID)
    return subtokenizer.decode(ids[:index])
  except ValueError:  # No EOS found in sequence
    return subtokenizer.decode(ids)


A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
72
73
74
75
76
77
78
def translate_file(model,
                   params,
                   subtokenizer,
                   input_file,
                   output_file=None,
                   print_all_translations=True,
                   distribution_strategy=None):
79
80
81
  """Translate lines in file, and save to output file if specified.

  Args:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
82
83
84
85
86
87
88
89
90
91
    model: A Keras model, used to generate the translations.
    params: A dictionary, containing the translation related parameters.
    subtokenizer: A subtokenizer object, used for encoding and decoding source
      and translated lines.
    input_file: A file containing lines to translate.
    output_file: A file that stores the generated translations.
    print_all_translations: A bool. If true, all translations are printed to
      stdout.
    distribution_strategy: A distribution strategy, used to perform inference
      directly with tf.function instead of Keras model.predict().
92
93
94
95

  Raises:
    ValueError: if output file is invalid.
  """
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
96
  batch_size = params["decode_batch_size"]
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

  # Read and sort inputs by length. Keep dictionary (original index-->new index
  # in sorted list) to write translations in the original order.
  sorted_inputs, sorted_keys = _get_sorted_inputs(input_file)
  total_samples = len(sorted_inputs)
  num_decode_batches = (total_samples - 1) // batch_size + 1

  def input_generator():
    """Yield encoded strings from sorted_inputs."""
    for i in range(num_decode_batches):
      lines = [
          sorted_inputs[j + i * batch_size]
          for j in range(batch_size)
          if j + i * batch_size < total_samples
      ]
      lines = [_encode_and_add_eos(l, subtokenizer) for l in lines]
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
113
114
115
      if distribution_strategy:
        for j in range(batch_size - len(lines)):
          lines.append([tokenizer.EOS_ID])
116
      batch = tf.keras.preprocessing.sequence.pad_sequences(
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
117
118
119
120
          lines,
          maxlen=params["decode_max_length"],
          dtype="int32",
          padding="post")
121
122
123
124
      tf.compat.v1.logging.info("Decoding batch %d out of %d.", i,
                                num_decode_batches)
      yield batch

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
125
126
127
128
129
130
  @tf.function
  def predict_step(inputs):
    """Decoding step function for TPU runs."""

    def _step_fn(inputs):
      """Per replica step function."""
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
131
132
133
134
      tag = inputs[0]
      val_inputs = inputs[1]
      val_outputs, _ = model([val_inputs], training=False)
      return tag, val_outputs
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
135
136
137

    return distribution_strategy.experimental_run_v2(_step_fn, args=(inputs,))

138
  translations = []
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
139
140
141
  if distribution_strategy:
    num_replicas = distribution_strategy.num_replicas_in_sync
    local_batch_size = params["decode_batch_size"] // num_replicas
142
  for i, text in enumerate(input_generator()):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
143
144
    if distribution_strategy:
      text = np.reshape(text, [num_replicas, local_batch_size, -1])
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
145
146
      # Add tag to the input of each replica with the reordering logic after
      # outputs, to ensure the output order matches the input order.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
147
      text = [
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
148
149
          [tf.convert_to_tensor(tag), tf.convert_to_tensor(per_replica_text)]
          for tag, per_replica_text in enumerate(text)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
150
151
152
      ]
      # pylint: disable=protected-access
      text = values.PerReplica(distribution_strategy.extended._device_map, text)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
153
      outputs = distribution_strategy.experimental_local_results(
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
154
          predict_step(text))
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
155
156
157
158
159
160
161
162
163
      tags, unordered_val_outputs = outputs[0]
      tags = [tag.numpy() for tag in tags._values]
      unordered_val_outputs = [
          val_output.numpy() for val_output in unordered_val_outputs._values]
      # pylint: enable=protected-access
      val_outputs = [None] * len(tags)
      for k in range(len(tags)):
        val_outputs[tags[k]] = unordered_val_outputs[k]
      val_outputs = np.reshape(val_outputs, [params["decode_batch_size"], -1])
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
164
165
    else:
      val_outputs, _ = model.predict(text)
166
167
168

    length = len(val_outputs)
    for j in range(length):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
169
170
171
172
173
174
175
      if j + i * batch_size < total_samples:
        translation = _trim_and_decode(val_outputs[j], subtokenizer)
        translations.append(translation)
        if print_all_translations:
          tf.compat.v1.logging.info(
              "Translating:\n\tInput: %s\n\tOutput: %s" %
              (sorted_inputs[j + i * batch_size], translation))
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198

  # Write translations in the order they appeared in the original file.
  if output_file is not None:
    if tf.io.gfile.isdir(output_file):
      raise ValueError("File output is a directory, will not save outputs to "
                       "file.")
    tf.compat.v1.logging.info("Writing to file %s" % output_file)
    with tf.compat.v1.gfile.Open(output_file, "w") as f:
      for i in sorted_keys:
        f.write("%s\n" % translations[i])


def translate_from_text(model, subtokenizer, txt):
  encoded_txt = _encode_and_add_eos(txt, subtokenizer)
  result = model.predict(encoded_txt)
  outputs = result["outputs"]
  tf.compat.v1.logging.info("Original: \"%s\"" % txt)
  translate_from_input(outputs, subtokenizer)


def translate_from_input(outputs, subtokenizer):
  translation = _trim_and_decode(outputs, subtokenizer)
  tf.compat.v1.logging.info("Translation: \"%s\"" % translation)