#@title 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.

"""
Explanation: <a href="https://colab.research.google.com/github/mandarup/deeplearning/blob/master/models/curiousbot_char_rnn_v1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Copyright 2018 The TensorFlow Authors.
End of explanation
"""


from google.colab import drive
drive.mount('/content/drive/')

# !pip install tf-nightly


# NOTE:  do not use \  for escaping whitespaces. keras saver does not like this.

datadir = "/content/drive/My Drive/Colab Notebooks/data"
checkpoints_dir = "/content/drive/My Drive/Colab Notebooks/checkpoints/curiousbot/char_rnn/v1"

# model_name = 'char_rnn.h5'
# gdrive_model_url = f'https://drive.google.com/open?id=1agl4U7LrI7parmIMAW4UESayJqEXK187/{model_name}'
# gdrive_model_url

# path_to_model = tf.keras.utils.get_file('char_rnn.h5', drive_url + '/char_rnn.h5')

!ls "/content/drive/"

# %%sh
# pwd
# ls
# rm -rf /content/drive/My\ Drive/Colab\ Notebooks/checkpoints/seq2seq_conversation_rnn
# mkdir  /content/drive/My\ Drive/Colab\ Notebooks/checkpoints/seq2seq_conversation_rnn
# ls
# # cd "/content/drive/My\ Drive/Colab\ Notebooks/checkpoints"
# # ls

#!touch  $checkpoints_dir/.keep

# !pip install tf-nightly

"""
Explanation: Text generation using a RNN with eager execution
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/sequences/text_generation"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td><td>
<a target="_blank"  href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/sequences/text_generation.ipynb">
    <img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>  
</td><td>
<a target="_blank"  href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/sequences/text_generation.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a></td></table>
End of explanation
"""


from __future__ import absolute_import, division, print_function

import tensorflow as tf
tf.enable_eager_execution()
EAGER_MODE_ON = tf.executing_eagerly()

import numpy as np
import os
import time
import dill

"""
Explanation: This tutorial demonstrates how to generate text using a character-based RNN. We will work with a dataset of Shakespeare's writing from Andrej Karpathy's The Unreasonable Effectiveness of Recurrent Neural Networks. Given a sequence of characters from this data ("Shakespear"), train a model to predict the next character in the sequence ("e"). Longer sequences of text can be generated by calling the model repeatedly.
Note: Enable GPU acceleration to execute this notebook faster. In Colab: Runtime > Change runtime type > Hardware acclerator > GPU. If running locally make sure TensorFlow version >= 1.11.
This tutorial includes runnable code implemented using tf.keras and eager execution. The following is sample output when the model in this tutorial trained for 30 epochs, and started with the string "Q":
<pre>
QUEENE:
I had thought thou hadst a Roman; for the oracle,
Thus by All bids the man against the word,
Which are so weak of care, by old care done;
Your children were in your holy love,
And the precipitation through the bleeding throne.

BISHOP OF ELY:
Marry, and will, my lord, to weep in such a one were prettiest;
Yet now I was adopted heir
Of the world's lamentable day,
To watch the next way with his father with his face?

ESCALUS:
The cause why then we are all resolved more sons.

VOLUMNIA:
O, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, it is no sin it should be dead,
And love and pale as any will to that word.

QUEEN ELIZABETH:
But how long have I heard the soul for this world,
And show his hands of life be proved to stand.

PETRUCHIO:
I say he look'd on, if I must be content
To stay him from the fatal of our country's bliss.
His lordship pluck'd from this sentence then for prey,
And then let us twain, being the moon,
were she such a case as fills m
</pre>

While some of the sentences are grammatical, most do not make sense. The model has not learned the meaning of words, but consider:


The model is character-based. When training started, the model did not know how to spell an English word, or that words were even a unit of text.


The structure of the output resembles a play—blocks of text generally begin with a speaker name, in all capital letters similar to the dataset.


As demonstrated below, the model is trained on small batches of text (100 characters each), and is still able to generate a longer sequence of text with coherent structure.


Setup
Import TensorFlow and other libraries
End of explanation
"""


# path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt')
# path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://drive.google.com/open?id=1Gzqr6tqUKEqpTsQt6pbbrSr9XIAC-nSp')

path_to_file = os.path.join(datadir, 'cornell-movie-dialogs-corpus','formatted_movie_lines.txt')

"""
Explanation: Download the Shakespeare dataset
Change the following line to run this code on your own data.
End of explanation
"""


# Read, then decode for py2 compat.
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')
# length of text is the number of characters in it
print ('Length of text: {} characters'.format(len(text)))

# Take a look at the first 250 characters in text
print(text[:250])

# The unique characters in the file
vocab = sorted(set(text))
print ('{} unique characters'.format(len(vocab)))

"""
Explanation: Read the data
First, look in the text.
End of explanation
"""


# Creating a mapping from unique characters to indices
char2idx = {u:i for i, u in enumerate(vocab)}
idx2char = np.array(vocab)

text_as_int = np.array([char2idx[c] for c in text])

"""
Explanation: Process the text
Vectorize the text
Before training, we need to map strings to a numerical representation. Create two lookup tables: one mapping characters to numbers, and another for numbers to characters.
End of explanation
"""


print('{')
for char,_ in zip(char2idx, range(20)):
    print('  {:4s}: {:3d},'.format(repr(char), char2idx[char]))
print('  ...\n}')

# Show how the first 13 characters from the text are mapped to integers
print ('{} ---- characters mapped to int ---- > {}'.format(repr(text[:13]), text_as_int[:13]))

"""
Explanation: Now we have an integer representation for each character. Notice that we mapped the character as indexes from 0 to len(unique).
End of explanation
"""


# The maximum length sentence we want for a single input in characters
seq_length = 100
examples_per_epoch = len(text)//seq_length

# Create training examples / targets
char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)

if EAGER_MODE_ON:
    for i in char_dataset.take(5):
      print(idx2char[i.numpy()])

"""
Explanation: The prediction task
Given a character, or a sequence of characters, what is the most probable next character? This is the task we're training the model to perform. The input to the model will be a sequence of characters, and we train the model to predict the output—the following character at each time step.
Since RNNs maintain an internal state that depends on the previously seen elements, given all the characters computed until this moment, what is the next character?
Create training examples and targets
Next divide the text into example sequences. Each input sequence will contain seq_length characters from the text. 
For each input sequence, the corresponding targets contain the same length of text, except shifted one character to the right. 
So break the text into chunks of seq_length+1. For example, say seq_length is 4 and our text is "Hello". The input sequence would be "Hell", and the target sequence "ello".
To do this first use the tf.data.Dataset.from_tensor_slices function to convert the text vector into a stream of character indices.
End of explanation
"""


sequences = char_dataset.batch(seq_length+1, drop_remainder=True)


if EAGER_MODE_ON:
    for item in sequences.take(5):
      print(repr(''.join(idx2char[item.numpy()])))

"""
Explanation: The batch method lets us easily convert these individual characters to sequences of the desired size.
End of explanation
"""


def split_input_target(chunk):
    input_text = chunk[:-1]
    target_text = chunk[1:]
    return input_text, target_text

dataset = sequences.map(split_input_target)

"""
Explanation: For each sequence, duplicate and shift it to form the input and target text by using the map method to apply a simple function to each batch:
End of explanation
"""


if EAGER_MODE_ON:
    for input_example, target_example in  dataset.take(2):
      print ('Input data: ', repr(''.join(idx2char[input_example.numpy()])))
      print ('Target data:', repr(''.join(idx2char[target_example.numpy()])))

"""
Explanation: Print the first examples input and target values:
End of explanation
"""


if EAGER_MODE_ON:
    for i, (input_idx, target_idx) in enumerate(zip(input_example[:5], target_example[:5])):
        print("Step {:4d}".format(i))
        print("  input: {} ({:s})".format(input_idx, repr(idx2char[input_idx])))
        print("  expected output: {} ({:s})".format(target_idx, repr(idx2char[target_idx])))

"""
Explanation: Each index of these vectors are processed as one time step. For the input at time step 0, the model receives the index for "F" and trys to predict the index for "i" as the next character. At the next timestep, it does the same thing but the RNN considers the previous step context in addition to the current input character.
End of explanation
"""


# Batch size 
BATCH_SIZE = 64
steps_per_epoch = examples_per_epoch//BATCH_SIZE

# Buffer size to shuffle the dataset
# (TF data is designed to work with possibly infinite sequences, 
# so it doesn't attempt to shuffle the entire sequence in memory. Instead, 
# it maintains a buffer in which it shuffles elements).
BUFFER_SIZE = 10000

dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)

dataset

"""
Explanation: Create training batches
We used tf.data to split the text into manageable sequences. But before feeding this data into the model, we need to shuffle the data and pack it into batches.
End of explanation
"""


# Length of the vocabulary in chars
vocab_size = len(vocab)

# # The embedding dimension 
# embedding_dim = 256

# # Number of RNN units
# rnn_units = 1024

# The embedding dimension 
embedding_dim = 256

# Number of RNN units
rnn_units = 1024

"""
Explanation: Build The Model
Use tf.keras.Sequential to define the model. For this simple example three layers are used to define our model:

tf.keras.layers.Embedding: The input layer. A trainable lookup table that will map the numbers of each character to a vector with embedding_dim dimensions;
tf.keras.layers.GRU: A type of RNN with size units=rnn_units (You can also use a LSTM layer here.)
tf.keras.layers.Dense: The output layer, with vocab_size outputs.
End of explanation
"""


# if tf.test.is_gpu_available():
#   rnn = tf.keras.layers.CuDNNGRU
# else:
#   import functools
#   rnn = functools.partial(
#     tf.keras.layers.GRU, recurrent_activation='sigmoid')

# Inference with cpu is not supported if model built with CuDNNGRU, so for now use GRU
import functools
rnn = functools.partial(
    tf.keras.layers.GRU, recurrent_activation='sigmoid')

def build_model(vocab_size=None, embedding_dim=None, rnn_units=None, batch_size=16):
  model = tf.keras.Sequential([
    tf.keras.layers.Embedding(vocab_size, embedding_dim, 
                              batch_input_shape=[batch_size, None]),
    rnn(rnn_units,
        return_sequences=True, 
        recurrent_initializer='glorot_uniform',
        stateful=True),
    tf.keras.layers.Dense(vocab_size)
  ])
  return model

model = build_model(
  vocab_size = len(vocab), 
  embedding_dim=embedding_dim, 
  rnn_units=rnn_units, 
  batch_size=BATCH_SIZE)

"""
Explanation: Next define a function to build the model.
Use CuDNNGRU if running on GPU.
End of explanation
"""


if EAGER_MODE_ON:
    for input_example_batch, target_example_batch in dataset.take(1): 
      example_batch_predictions = model(input_example_batch)
      print(example_batch_predictions.shape, "# (batch_size, sequence_length, vocab_size)")

"""
Explanation: For each character the model looks up the embedding, runs the GRU one timestep with the embedding as input, and applies the dense layer to generate logits predicting the log-liklihood of the next character:

Try the model
Now run the model to see that it behaves as expected.
First check the shape of the output:
End of explanation
"""


model.summary()

from IPython.display import SVG
#import keras
import tensorflow as tf
# from tensorflow.keras.utils import model_to_dot
from keras.utils import vis_utils


SVG(vis_utils.model_to_dot(model).create(prog='dot', format='svg'))

#tf.keras.utils.plot_model(model)

"""
Explanation: In the above example the sequence length of the input is 100 but the model can be run on inputs of any length:
End of explanation
"""


sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1)
sampled_indices = tf.squeeze(sampled_indices,axis=-1).numpy()

"""
Explanation: To get actual predictions from the model we need to sample from the output distribution, to get actual character indices. This distribution is defined by the logits over the character vocabulary. 
Note: It is important to sample from this distribution as taking the argmax of the distribution can easily get the model stuck in a loop.
Try it for the first example in the batch:
End of explanation
"""


sampled_indices

"""
Explanation: This gives us, at each timestep, a prediction of the next character index:
End of explanation
"""


print("Input: \n", repr("".join(idx2char[input_example_batch[0]])))
print()
print("Next Char Predictions: \n", repr("".join(idx2char[sampled_indices ])))

"""
Explanation: Decode these to see the text predicted by this untrained model:
End of explanation
"""


def loss(labels, logits):
  return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)

example_batch_loss  = loss(target_example_batch, example_batch_predictions)
print("Prediction shape: ", example_batch_predictions.shape, " # (batch_size, sequence_length, vocab_size)") 
print("scalar_loss:      ", example_batch_loss.numpy().mean())

"""
Explanation: Train the model
At this point the problem can be treated as a standard classification problem. Given the previous RNN state, and the input this time step, predict the class of the next character.
Attach an optimizer, and a loss function
The standard tf.keras.losses.sparse_softmax_crossentropy loss function works in this case because it is applied across the last dimension of the predictions. 
Because our model returns logits, we need to set the from_logits flag.
End of explanation
"""


model.compile(
    optimizer = tf.train.AdamOptimizer(),
    loss = loss)

# model.reset_states()
# input_eval = [char2idx[s] for s in 'teststring']
# model(input_eval)

"""
Explanation: Configure the training procedure using the tf.keras.Model.compile method. We'll use tf.train.AdamOptimizer with default arguments and the loss function.
End of explanation
"""


# Directory where the checkpoints will be saved
# checkpoint_dirs = './training_checkpoints'
# Name of the checkpoint files
checkpoint_prefix = os.path.join(checkpoints_dir, "ckpt_{epoch}.ckpt")

checkpoint_callback=tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_prefix,
    save_weights_only=True,
    #save_best_only=True
)

if not os.path.exists(checkpoints_dir):
    os.makedirs(checkpoints_dir)
os.path.exists(checkpoints_dir)

"""
Explanation: Configure checkpoints
Use a tf.keras.callbacks.ModelCheckpoint to ensure that checkpoints are saved during training:
End of explanation
"""


# model.load_weights(tf.train.latest_checkpoint(checkpoints_dir))

EPOCHS=10

#model.save_weights(checkpoint_prefix.format(epoch=0))
history = model.fit(dataset.repeat(), epochs=EPOCHS, steps_per_epoch=steps_per_epoch, 
                    callbacks=[checkpoint_callback])

model.save_weights(os.path.join(checkpoints_dir, 'char_rnn.h5'))

# # Fetch the Keras session and save the model
# # The signature definition is defined by the input and output tensors,
# # and stored with the default serving key
# import tempfile
# from tensorflow import keras

# MODEL_DIR = tempfile.gettempdir()
# version = 1
# export_path = os.path.join(MODEL_DIR, str(version))
# print('export_path = {}\n'.format(export_path))
# if os.path.isdir(export_path):
#   print('\nAlready saved a model, cleaning up\n')
#   !rm -r {export_path}

# tf.saved_model.simple_save(
#     tf.keras.backend.get_session(),
#     export_path,
#     inputs={'input_text': model.input},
#     #outputs={t.name:t for t in model.outputs}
#     outputs={'output_text': model.output}
#     )

# print('\nSaved model:')
# !ls -l {export_path}

saved_model_path = os.path.join(checkpoints_dir, 'char_rnn_savedmodel.h5')

tf.contrib.saved_model.save_keras_model(
    model,
    saved_model_path,
    custom_objects=None,
    as_text=None
)


# model_name = os.path.join(checkpoints_dir, 'char_rnn.h5')



# model_name = os.path.join(checkpoints_dir, 'char_rnn.h5')
# model.save(model_name)

# gdrive_model_url = 'https://drive.google.com/open?id=1-5-rdGJkj2cFWnMo7H_Pz1D8lX44Lhnr'

# path_to_file = tf.keras.utils.get_file(model_name, gdrive_model_url)
# inference_model = tf.keras.models.load_model(path_to_file)

# inference_model = tf.keras.models.load_model(model_name)

# inference_model.compile(
#     optimizer = tf.train.AdamOptimizer(),
#     loss = loss)

# model

"""
Explanation: Execute the training
To keep training time reasonable, use 3 epochs to train the model. In Colab, set the runtime to GPU for faster training.
End of explanation
"""


# import glob
# checkpoint = sorted(glob.glob(os.path.join(checkpoints_dir,  '*')))[-1]
# checkpoint

del model

checkpoint = tf.train.latest_checkpoint(checkpoints_dir )
checkpoint

# model = tf.keras.models.load_model(checkpoint)

# import json
# with open(os.path.join(checkpoints_dir, 'build_params.json'), 'w') as fp:
#     json.dump({'vocab_size': vocab_size,'embedding_dim': embedding_dim,
#                'rnn_units': rnn_units,
#                'char2idx' : {u:i for i, u in enumerate(vocab)},
#                'idx2char' : np.array(vocab),
#                'text_as_int': np.array([char2idx[c] for c in text]) }, fp)

#with open(os.path.join(checkpoints_dir, 'build_params.pkl'), 'w') as fp:

# dill.dump({'vocab_size': vocab_size,'embedding_dim': embedding_dim,
#            'rnn_units': rnn_units,
#            'char2idx' : {u:i for i, u in enumerate(vocab)},
#            'idx2char' : np.array(vocab),
#            'text_as_int': np.array([char2idx[c] for c in text]) }, 
#          open(os.path.join(checkpoints_dir, 'build_params.pkl'), 'w'))


out = {'vocab_size': vocab_size,'embedding_dim': embedding_dim,
           'rnn_units': rnn_units,
           'char2idx' : {u:i for i, u in enumerate(vocab)},
           'idx2char' : np.array(vocab),
           'text_as_int': np.array([char2idx[c] for c in text]) }
with open(os.path.join(checkpoints_dir, 'build_params.pkl'), 'wb') as f:
    dill.dump(out, f)

with open(os.path.join(checkpoints_dir, 'build_params.pkl'), 'rb') as f:
    params = dill.load(f)
params.keys()

# with open(os.path.join(checkpoints_dir, 'build_params.pkl'), 'r') as fp:
#     params = json.load(fp)
# params

# model = build_model(vocab_size, embedding_dim, rnn_units, batch_size=1)
model =build_model(params.get('vocab_size'),
                        params.get('embedding_dim'),
                        params.get('rnn_units'),
                        batch_size=1)


model.load_weights(tf.train.latest_checkpoint(checkpoints_dir))

model.build(tf.TensorShape([1, None]))

# model.reset_states()
# input_eval = [char2idx[s] for s in 'teststring']
# model( tf.expand_dims(input_eval, 0))

# # Save entire model to a HDF5 file
# # model.save('my_model.h5')

# # Recreate the exact same model, including weights and optimizer.
# model = tf.keras.models.load_model(checkpoint)


# inference_model.summary()

# del inference_model

"""
Explanation: Generate text
Restore the latest checkpoint
To keep this prediction step simple, use a batch size of 1.
Because of the way the RNN state is passed from timestep to timestep, the model only accepts a fixed batch size once built. 
To run the model with a different batch_size, we need to rebuild the model and restore the weights from the checkpoint.
End of explanation
"""


def generate_text(model, start_string, char2idx, idx2char, num_generate=20):
  # Evaluation step (generating text using the learned model)

  # Number of characters to generate
  #num_generate = 1000

  # Converting our start string to numbers (vectorizing) 
  input_eval = [char2idx[s] for s in start_string]
  input_eval = tf.expand_dims(input_eval, 0)
  print(input_eval)

  # Empty string to store our results
  text_generated = []

  # Low temperatures results in more predictable text.
  # Higher temperatures results in more surprising text.
  # Experiment to find the best setting.
  temperature = 1.0

  # Here batch size == 1
  model.reset_states()
  for i in range(num_generate):
      #predictions = model(input_eval)
      predictions = model(input_eval)

      # remove the batch dimension
      predictions = tf.squeeze(predictions, 0)
        

      # using a multinomial distribution to predict the word returned by the model
      predictions = predictions / temperature
      predicted_id = tf.multinomial(predictions, num_samples=1)[-1,0].numpy()
      
      # We pass the predicted word as the next input to the model
      # along with the previous hidden state
      input_eval = tf.expand_dims([predicted_id], 0)
      
      text_generated.append(idx2char[predicted_id])

  return ''.join(text_generated)

# inference_model.reset_states()
# input_eval = [char2idx[s] for s in 'teststring']
# inference_model( tf.expand_dims(input_eval, 0))

# print(generate_text(inference_model, start_string=u"ROMEO: "))

print(generate_text(model, u"hi how are you?", char2idx, idx2char, num_generate=100))

"""
Explanation: The prediction loop
The following code block generates the text:


It Starts by choosing a start string, initializing the RNN state and setting the number of characters to generate.


Get the prediction distribution of the next character using the start string and the RNN state.


Then, use a multinomial distribution to calculate the index of the predicted character. Use this predicted character as our next input to the model.


The RNN state returned by the model is fed back into the model so that it now has more context, instead than only one word. After predicting the next word, the modified RNN states are again fed back into the model, which is how it learns as it gets more context from the previously predicted words.



Looking at the generated text, you'll see the model knows when to capitalize, make paragraphs and imitates a Shakespeare-like writing vocabulary. With the small number of training epochs, it has not yet learned to form coherent sentences.
End of explanation
"""


model = build_model(
  vocab_size = len(vocab), 
  embedding_dim=embedding_dim, 
  rnn_units=rnn_units, 
  batch_size=BATCH_SIZE)

optimizer = tf.train.AdamOptimizer()

# Training step
EPOCHS = 5

for epoch in range(EPOCHS):
    start = time.time()
    
    # initializing the hidden state at the start of every epoch
    # initally hidden is None
    hidden = model.reset_states()
    
    for (batch_n, (inp, target)) in enumerate(dataset):
          with tf.GradientTape() as tape:
              # feeding the hidden state back into the model
              # This is the interesting step
              predictions = model(inp)
              loss = tf.losses.sparse_softmax_cross_entropy(target, predictions)
              
          grads = tape.gradient(loss, model.trainable_variables)
          optimizer.apply_gradients(zip(grads, model.trainable_variables))

          if batch_n % 100 == 0:
              template = 'Epoch {} Batch {} Loss {:.4f}'
              print(template.format(epoch+1, batch_n, loss))
          #if batch_n % 10 == 1:
          #    print(generate_text(model, 'ROMEO: ', char2idx, idx2char, num_generate=25))

    # saving (checkpoint) the model every 5 epochs
    if (epoch + 1) % 1 == 0:
        model.save_weights(checkpoint_prefix.format(epoch=epoch))

    print ('Epoch {} Loss {:.4f}'.format(epoch+1, loss))
    print ('Time taken for 1 epoch {} sec\n'.format(time.time() - start))

model.save_weights(checkpoint_prefix.format(epoch=epoch))

model = build_model(vocab_size, embedding_dim, rnn_units, batch_size=1)

model.load_weights(tf.train.latest_checkpoint(checkpoints_dir))

model.build(tf.TensorShape([1, None]))
print(generate_text(model, u"ROMEO: ", char2idx, idx2char))

"""
Explanation: The easiest thing you can do to improve the results it to train it for longer (try EPOCHS=30).
You can also experiment with a different start string, or try adding another RNN layer to improve the model's accuracy, or adjusting the temperature parameter to generate more or less random predictions.
Advanced: Customized Training
The above training procedure is simple, but does not give you much control.
So now that you've seen how to run the model manually let's unpack the training loop, and implement it ourselves. This gives a starting point if, for example, to implement curriculum learning to help stabilize the model's open-loop output. 
We will use tf.GradientTape to track the gradiends. You can learn more about this approach by reading the eager execution guide.
The procedure works as follows:


First, initialize the RNN state. We do this by calling the tf.keras.Model.reset_states method.


Next, iterate over the dataset (batch by batch) and calculate the predictions associated with each.


Open a tf.GradientTape, and calculate the predictions and loss in that context.


Calculate the gradients of the loss with respect to the model variables using the tf.GradientTape.grads method.


Finally, take a step downwards by using the optimizer's tf.train.Optimizer.apply_gradients method.
End of explanation
"""


