code: # Copyright 2019 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.
  # ==============================================================================
  """Functions and classes related to optimization (weight updates)."""
  
  from __future__ import absolute_import
  from __future__ import division
  from __future__ import print_function
  
  import re
  
  import tensorflow as tf
  
  
  class WarmUp(tf.keras.optimizers.schedules.LearningRateSchedule):
    """Applys a warmup schedule on a given learning rate decay schedule."""
  
    def __init__(
        self,
        initial_learning_rate,
        decay_schedule_fn,
        warmup_steps,
        power=1.0,
        name=None):
      super(WarmUp, self).__init__()
      self.initial_learning_rate = initial_learning_rate
      self.warmup_steps = warmup_steps
      self.power = power
      self.decay_schedule_fn = decay_schedule_fn
      self.name = name
  
    def __call__(self, step):
      with tf.name_scope(self.name or 'WarmUp') as name:
        # Implements polynomial warmup. i.e., if global_step < warmup_steps, the
        # learning rate will be `global_step/num_warmup_steps * init_lr`.
        global_step_float = tf.cast(step, tf.float32)
        warmup_steps_float = tf.cast(self.warmup_steps, tf.float32)
        warmup_percent_done = global_step_float / warmup_steps_float
        warmup_learning_rate = (
            self.initial_learning_rate *
            tf.math.pow(warmup_percent_done, self.power))
        return tf.cond(global_step_float < warmup_steps_float,
                       lambda: warmup_learning_rate,
                       lambda: self.decay_schedule_fn(step),
                       name=name)
  
    def get_config(self):
      return {
          'initial_learning_rate': self.initial_learning_rate,
          'decay_schedule_fn': self.decay_schedule_fn,
          'warmup_steps': self.warmup_steps,
          'power': self.power,
          'name': self.name
      }
  
  
  def create_optimizer(init_lr, num_train_steps, num_warmup_steps):
    """Creates an optimizer with learning rate schedule."""
    # Implements linear decay of the learning rate.
    learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay(
        initial_learning_rate=init_lr,
        decay_steps=num_train_steps,
        end_learning_rate=0.0)
    if num_warmup_steps:
      learning_rate_fn = WarmUp(initial_learning_rate=init_lr,
                                decay_schedule_fn=learning_rate_fn,
                                warmup_steps=num_warmup_steps)
    optimizer = AdamWeightDecay(
        learning_rate=learning_rate_fn,
        weight_decay_rate=0.01,
        beta_1=0.9,
        beta_2=0.999,
        epsilon=1e-6,
        exclude_from_weight_decay=['layer_norm', 'bias'])
    return optimizer
  
  
  class AdamWeightDecay(tf.keras.optimizers.Adam):
    """Adam enables L2 weight decay and clip_by_global_norm on gradients.
  
    Just adding the square of the weights to the loss function is *not* the
    correct way of using L2 regularization/weight decay with Adam, since that will
    interact with the m and v parameters in strange ways.
  
    Instead we want ot decay the weights in a manner that doesn't interact with
    the m/v parameters. This is equivalent to adding the square of the weights to
    the loss with plain (non-momentum) SGD.
    """
  
    def __init__(self,
                 learning_rate=0.001,
                 beta_1=0.9,
                 beta_2=0.999,
                 epsilon=1e-7,
                 amsgrad=False,
                 weight_decay_rate=0.0,
                 include_in_weight_decay=None,
                 exclude_from_weight_decay=None,
                 name='AdamWeightDecay',
                 **kwargs):
      super(AdamWeightDecay, self).__init__(
          learning_rate, beta_1, beta_2, epsilon, amsgrad, name, **kwargs)
      self.weight_decay_rate = weight_decay_rate
      self._include_in_weight_decay = include_in_weight_decay
      self._exclude_from_weight_decay = exclude_from_weight_decay
  
    @classmethod
    def from_config(cls, config):
      """Creates an optimizer from its config with WarmUp custom object."""
      custom_objects = {'WarmUp': WarmUp}
      return super(AdamWeightDecay, cls).from_config(
          config, custom_objects=custom_objects)
  
    def _prepare_local(self, var_device, var_dtype, apply_state):
      super(AdamWeightDecay, self)._prepare_local(var_device, var_dtype,
                                                  apply_state)
      apply_state['weight_decay_rate'] = tf.constant(
          self.weight_decay_rate, name='adam_weight_decay_rate')
  
    def _decay_weights_op(self, var, learning_rate, apply_state):
      do_decay = self._do_use_weight_decay(var.name)
      if do_decay:
        return var.assign_sub(
            learning_rate * var *
            apply_state['weight_decay_rate'],
            use_locking=self._use_locking)
      return tf.no_op()
  
    def apply_gradients(self, grads_and_vars, name=None):
      grads, tvars = list(zip(*grads_and_vars))
      (grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0)
      return super(AdamWeightDecay, self).apply_gradients(zip(grads, tvars))
  
    def _get_lr(self, var_device, var_dtype, apply_state):
      """Retrieves the learning rate with the given state."""
      if apply_state is None:
        return self._decayed_lr_t[var_dtype], {}
  
      apply_state = apply_state or {}
      coefficients = apply_state.get((var_device, var_dtype))
      if coefficients is None:
        coefficients = self._fallback_apply_state(var_device, var_dtype)
        apply_state[(var_device, var_dtype)] = coefficients
  
      return coefficients['lr_t'], dict(apply_state=apply_state)
  
    def _resource_apply_dense(self, grad, var, apply_state=None):
      lr_t, kwargs = self._get_lr(var.device, var.dtype.base_dtype, apply_state)
      decay = self._decay_weights_op(var, lr_t, apply_state)
      with tf.control_dependencies([decay]):
        return super(AdamWeightDecay, self)._resource_apply_dense(
            grad, var, **kwargs)
  
    def _resource_apply_sparse(self, grad, var, indices, apply_state=None):
      lr_t, kwargs = self._get_lr(var.device, var.dtype.base_dtype, apply_state)
      decay = self._decay_weights_op(var, lr_t, apply_state)
      with tf.control_dependencies([decay]):
        return super(AdamWeightDecay, self)._resource_apply_sparse(
            grad, var, indices, **kwargs)
  
    def get_config(self):
      config = super(AdamWeightDecay, self).get_config()
      config.update({
          'weight_decay_rate': self.weight_decay_rate,
      })
      return config
  
    def _do_use_weight_decay(self, param_name):
      """Whether to use L2 weight decay for `param_name`."""
      if self.weight_decay_rate == 0:
        return False
  
      if self._include_in_weight_decay:
        for r in self._include_in_weight_decay:
          if re.search(r, param_name) is not None:
            return True
  
      if self._exclude_from_weight_decay:
        for r in self._exclude_from_weight_decay:
          if re.search(r, param_name) is not None:
            return False
      return True
   # Copyright 2017 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.
  # ==============================================================================
  
  """Functions to make unit testing easier."""
  
  import StringIO
  import numpy as np
  from PIL import Image as PILImage
  import tensorflow as tf
  
  
  def create_random_image(image_format, shape):
    """Creates an image with random values.
  
    Args:
      image_format: An image format (PNG or JPEG).
      shape: A tuple with image shape (including channels).
  
    Returns:
      A tuple (<numpy ndarray>, <a string with encoded image>)
    """
    image = np.random.randint(low=0, high=255, size=shape, dtype='uint8')
    io = StringIO.StringIO()
    image_pil = PILImage.fromarray(image)
    image_pil.save(io, image_format, subsampling=0, quality=100)
    return image, io.getvalue()
  
  
  def create_serialized_example(name_to_values):
    """Creates a tf.Example proto using a dictionary.
  
    It automatically detects type of values and define a corresponding feature.
  
    Args:
      name_to_values: A dictionary.
  
    Returns:
      tf.Example proto.
    """
    example = tf.train.Example()
    for name, values in name_to_values.items():
      feature = example.features.feature[name]
      if isinstance(values[0], str):
        add = feature.bytes_list.value.extend
      elif isinstance(values[0], float):
        add = feature.float32_list.value.extend
      elif isinstance(values[0], int):
        add = feature.int64_list.value.extend
      else:
        raise AssertionError('Unsupported type: %s' % type(values[0]))
      add(values)
    return example.SerializeToString()
   # 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.
  # ==============================================================================
  """Test Subtokenizer and string helper methods."""
  
  import collections
  import tempfile
  
  import tensorflow as tf  # pylint: disable=g-bad-import-order
  
  from official.transformer.utils import tokenizer
  
  
  class SubtokenizerTest(tf.test.TestCase):
  
    def _init_subtokenizer(self, vocab_list):
      temp_file = tempfile.NamedTemporaryFile(delete=False)
      with tf.io.gfile.GFile(temp_file.name, "w") as w:
        for subtoken in vocab_list:
          w.write("'%s'" % subtoken)
          w.write("\n")
      return tokenizer.Subtokenizer(temp_file.name, reserved_tokens=[])
  
    def test_encode(self):
      vocab_list = ["123_", "test", "ing_"]
      subtokenizer = self._init_subtokenizer(vocab_list)
      s = "testing 123"
      encoded_list = subtokenizer.encode(s)
      self.assertEqual([1, 2, 0], encoded_list)
  
    def test_decode(self):
      vocab_list = ["123_", "test", "ing_"]
      subtokenizer = self._init_subtokenizer(vocab_list)
      encoded_list = [1, 2, 0]  # testing 123
      decoded_str = subtokenizer.decode(encoded_list)
      self.assertEqual("testing 123", decoded_str)
  
    def test_subtoken_ids_to_tokens(self):
      vocab_list = ["123_", "test", "ing_"]
      subtokenizer = self._init_subtokenizer(vocab_list)
      encoded_list = [1, 2, 0]  # testing 123
      token_list = subtokenizer._subtoken_ids_to_tokens(encoded_list)
      self.assertEqual([u"testing", u"123"], token_list)
  
  
  class StringHelperTest(tf.test.TestCase):
  
    def test_split_string_to_tokens(self):
      text = "test? testing 123."
  
      tokens = tokenizer._split_string_to_tokens(text)
      self.assertEqual(["test", "? ", "testing", "123", "."], tokens)
  
    def test_join_tokens_to_string(self):
      tokens = ["test", "? ", "testing", "123", "."]
  
      s = tokenizer._join_tokens_to_string(tokens)
      self.assertEqual("test? testing 123.", s)
  
    def test_escape_token(self):
      token = u"abc_\\4"
      alphabet = set("abc_\\u;")
  
      escaped_token = tokenizer._escape_token(token, alphabet)
      self.assertEqual("abc\\u\\\\\\52;_", escaped_token)
  
    def test_unescape_token(self):
      escaped_token = u"Underline: \\u, Backslash: \\\\, Unicode: \\52;"
  
      unescaped_token = tokenizer._unescape_token(escaped_token)
      self.assertEqual(
          "Underline: _, Backslash: \\, Unicode: 4", unescaped_token)
  
    def test_list_to_index_dict(self):
      lst = ["test", "strings"]
  
      d = tokenizer._list_to_index_dict(lst)
      self.assertDictEqual({"test": 0, "strings": 1}, d)
  
    def test_split_token_to_subtokens(self):
      token = "abc"
      subtoken_dict = {"a": 0, "b": 1, "c": 2, "ab": 3}
      max_subtoken_length = 2
  
      subtokens = tokenizer._split_token_to_subtokens(
          token, subtoken_dict, max_subtoken_length)
      self.assertEqual(["ab", "c"], subtokens)
  
    def test_generate_alphabet_dict(self):
      s = ["testing", "123"]
      reserved_tokens = ["???"]
  
      alphabet = tokenizer._generate_alphabet_dict(s, reserved_tokens)
      self.assertIn("?", alphabet)
      self.assertIn("t", alphabet)
      self.assertIn("e", alphabet)
      self.assertIn("s", alphabet)
      self.assertIn("i", alphabet)
      self.assertIn("n", alphabet)
      self.assertIn("g", alphabet)
      self.assertIn("1", alphabet)
      self.assertIn("2", alphabet)
      self.assertIn("3", alphabet)
  
    def test_count_and_gen_subtokens(self):
      token_counts = {"abc": 5}
      alphabet = set("abc_")
      subtoken_dict = {"a": 0, "b": 1, "c": 2, "_": 3}
      max_subtoken_length = 2
  
      subtoken_counts = tokenizer._count_and_gen_subtokens(
          token_counts, alphabet, subtoken_dict, max_subtoken_length)
  
      self.assertIsInstance(subtoken_counts, collections.defaultdict)
      self.assertDictEqual(
          {"a": 5, "b": 5, "c": 5, "_": 5, "ab": 5, "bc": 5, "c_": 5,
           "abc": 5, "bc_": 5, "abc_": 5}, subtoken_counts)
  
    def test_filter_and_bucket_subtokens(self):
      subtoken_counts = collections.defaultdict(
          int, {"a": 2, "b": 4, "c": 1, "ab": 6, "ac": 3, "abbc": 5})
      min_count = 3
  
      subtoken_buckets = tokenizer._filter_and_bucket_subtokens(
          subtoken_counts, min_count)
  
      self.assertEqual(len(subtoken_buckets[0]), 0)
      self.assertEqual(set("b"), subtoken_buckets[1])
      self.assertEqual(set(["ab", "ac"]), subtoken_buckets[2])
      self.assertEqual(len(subtoken_buckets[3]), 0)
      self.assertEqual(set(["abbc"]), subtoken_buckets[4])
  
    def test_gen_new_subtoken_list(self):
      subtoken_counts = collections.defaultdict(
          int, {"translate": 10, "t": 40, "tr": 16, "tra": 12})
      min_count = 5
      alphabet = set("translate")
      reserved_tokens = ["reserved", "tokens"]
  
      subtoken_list, max_token_length = tokenizer._gen_new_subtoken_list(
          subtoken_counts, min_count, alphabet, reserved_tokens)
  
      # Check that "tra" isn"t in the list (its count should be decremented to 2,
      # so it should not be added to the canddiate list).
      self.assertNotIn("tra", subtoken_list)
  
      self.assertIn("tr", subtoken_list)
      self.assertIn("t", subtoken_list)
  
      self.assertEqual(len("translate"), max_token_length)
  
    def test_generate_subtokens(self):
      token_counts = {"ab": 1, "bc": 3, "abc": 5}
      alphabet = set("abc_")
      min_count = 100
      num_iterations = 1
      reserved_tokens = ["reserved", "tokens"]
  
      vocab_list = tokenizer._generate_subtokens(
          token_counts, alphabet, min_count, num_iterations, reserved_tokens)
  
      # Check that reserved tokens are at the front of the list
      self.assertEqual(vocab_list[:2], reserved_tokens)
  
      # Check that each character in alphabet is in the vocab list
      for c in alphabet:
        self.assertIn(c, vocab_list)
  
  
  if __name__ == "__main__":
    tf.test.main()
  
apis: tensorflow.no_op tensorflow.clip_by_global_norm tensorflow.keras.optimizers.schedules.PolynomialDecay tensorflow.cast tensorflow.name_scope tensorflow.math.pow tensorflow.constant tensorflow.control_dependencies
apis: numpy.random.randint tensorflow.train.Example
apis: tensorflow.test.main tensorflow.io.gfile.GFile