<commit_before># Lint as: python3
# Copyright 2019 Google LLC
#
# 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
#
#      https://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 training a classification model with Keras optimizers."""

import os

from absl import app
from absl import flags
from absl import logging
import numpy as np
from pyiree.tf.support import tf_test_utils
from pyiree.tf.support import tf_utils
import tensorflow as tf

FLAGS = flags.FLAGS
flags.DEFINE_string(
    "optimizer", "sgd",
    "One of 'adadelta', 'adagrad', 'adam', 'adamax', 'ftrl', 'nadam', "
    "'rmsprop' or 'sgd'")

SAMPLES_PER_SPIRAL = 8
INPUT_DIM = 2
NUM_CLASSES = 4
BATCH_SIZE = NUM_CLASSES * SAMPLES_PER_SPIRAL


def get_spiral_dataset(samples_per_spiral: int,
                       noise_scale: float = 0,
                       shuffle: bool = True):
  """Creates a dataset with four spiral arms."""
  t = np.linspace(0, 1, samples_per_spiral, dtype=np.float32)
  cos_term = t * np.sin(2 * np.pi * t)
  sin_term = t * np.cos(2 * np.pi * t)
  spirals = [
      np.stack([sin_term, cos_term], axis=-1),
      np.stack([-sin_term, -cos_term], axis=-1),
      np.stack([-cos_term, sin_term], axis=-1),
      np.stack([cos_term, -sin_term], axis=-1)
  ]
  inputs = np.concatenate(spirals)
  inputs = inputs + np.random.normal(scale=noise_scale, size=inputs.shape)
  labels = np.concatenate([i * np.ones_like(t) for i in range(4)])

  if shuffle:
    # Shuffle by batch dim.
    index = np.arange(inputs.shape[0])
    np.random.shuffle(index)
    inputs = inputs[index]
    labels = labels[index]

  return inputs, labels


class ClassificationTrainingModule(tf.Module):
  """A module for model training."""

  def __init__(self):
    inputs = tf.keras.layers.Input(INPUT_DIM)
    x = tf.keras.layers.Dense(NUM_CLASSES)(inputs)
    outputs = tf.keras.layers.Softmax()(x)
    self.model = tf.keras.Model(inputs, outputs)
    print(self.model)

    self.loss = tf.keras.losses.SparseCategoricalCrossentropy()
    self.optimizer = tf.keras.optimizers.get(FLAGS.optimizer)

  @tf.function(input_signature=[
      tf.TensorSpec([BATCH_SIZE, INPUT_DIM], tf.float32),
      tf.TensorSpec([BATCH_SIZE], tf.float32)
  ])
  def train_on_batch(self, inputs, labels):
    with tf.GradientTape() as tape:
      probs = self.model(inputs, training=True)
      loss = self.loss(labels, probs)
    variables = self.model.trainable_variables
    gradients = tape.gradient(loss, variables)
    self.optimizer.apply_gradients(zip(gradients, variables))
    return loss


class ClassificationTrainingTest(tf_test_utils.TracedModuleTestCase):

  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self._modules = tf_test_utils.compile_tf_module(
        ClassificationTrainingModule, exported_names=["train_on_batch"])

  def test_train_on_batch(self):

    def train_on_batch(module):
      inputs, labels = get_spiral_dataset(SAMPLES_PER_SPIRAL, noise_scale=0.05)
      module.train_on_batch(inputs, labels)
<commit_msg>Remove undeleted print statement (#3637)<commit_after># Lint as: python3
# Copyright 2019 Google LLC
#
# 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
#
#      https://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 training a classification model with Keras optimizers."""

import os

from absl import app
from absl import flags
from absl import logging
import numpy as np
from pyiree.tf.support import tf_test_utils
from pyiree.tf.support import tf_utils
import tensorflow as tf

FLAGS = flags.FLAGS
flags.DEFINE_string(
    "optimizer", "sgd",
    "One of 'adadelta', 'adagrad', 'adam', 'adamax', 'ftrl', 'nadam', "
    "'rmsprop' or 'sgd'")

SAMPLES_PER_SPIRAL = 8
INPUT_DIM = 2
NUM_CLASSES = 4
BATCH_SIZE = NUM_CLASSES * SAMPLES_PER_SPIRAL


def get_spiral_dataset(samples_per_spiral: int,
                       noise_scale: float = 0,
                       shuffle: bool = True):
  """Creates a dataset with four spiral arms."""
  t = np.linspace(0, 1, samples_per_spiral, dtype=np.float32)
  cos_term = t * np.sin(2 * np.pi * t)
  sin_term = t * np.cos(2 * np.pi * t)
  spirals = [
      np.stack([sin_term, cos_term], axis=-1),
      np.stack([-sin_term, -cos_term], axis=-1),
      np.stack([-cos_term, sin_term], axis=-1),
      np.stack([cos_term, -sin_term], axis=-1)
  ]
  inputs = np.concatenate(spirals)
  inputs = inputs + np.random.normal(scale=noise_scale, size=inputs.shape)
  labels = np.concatenate([i * np.ones_like(t) for i in range(4)])

  if shuffle:
    # Shuffle by batch dim.
    index = np.arange(inputs.shape[0])
    np.random.shuffle(index)
    inputs = inputs[index]
    labels = labels[index]

  return inputs, labels


class ClassificationTrainingModule(tf.Module):
  """A module for model training."""

  def __init__(self):
    inputs = tf.keras.layers.Input(INPUT_DIM)
    x = tf.keras.layers.Dense(NUM_CLASSES)(inputs)
    outputs = tf.keras.layers.Softmax()(x)
    self.model = tf.keras.Model(inputs, outputs)

    self.loss = tf.keras.losses.SparseCategoricalCrossentropy()
    self.optimizer = tf.keras.optimizers.get(FLAGS.optimizer)

  @tf.function(input_signature=[
      tf.TensorSpec([BATCH_SIZE, INPUT_DIM], tf.float32),
      tf.TensorSpec([BATCH_SIZE], tf.float32)
  ])
  def train_on_batch(self, inputs, labels):
    with tf.GradientTape() as tape:
      probs = self.model(inputs, training=True)
      loss = self.loss(labels, probs)
    variables = self.model.trainable_variables
    gradients = tape.gradient(loss, variables)
    self.optimizer.apply_gradients(zip(gradients, variables))
    return loss


class ClassificationTrainingTest(tf_test_utils.TracedModuleTestCase):

  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self._modules = tf_test_utils.compile_tf_module(
        ClassificationTrainingModule, exported_names=["train_on_batch"])

  def test_train_on_batch(self):

    def train_on_batch(module):
      inputs, labels = get_spiral_dataset(SAMPLES_PER_SPIRAL, noise_scale=0.05)
      module.train_on_batch(inputs, labels)

{'fraction_non_alphanumeric': 0.11487949199018617, 'fraction_numerical': 0.009813825948910377, 'mean_word_length': 3.8906139731827807, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7152048', 'n_tokens_mistral': 2365, 'n_tokens_neox': 2267, 'n_words': 595}