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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tensorflow as tf
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
path_to_file = tf.keras.utils.get_file('logs4.txt', 'https://raw.githubusercontent.com/wadethegreat68/toxigon-repo/main/scraper.txt')
|
| 7 |
+
# Read, then decode for py2 compat.
|
| 8 |
+
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')
|
| 9 |
+
# length of text is the number of characters in it
|
| 10 |
+
print(f'Length of text: {len(text)} characters')
|
| 11 |
+
# Take a look at the first 250 characters in text
|
| 12 |
+
print(text[:250])
|
| 13 |
+
vocab = sorted(set(text))
|
| 14 |
+
print(f'{len(vocab)} unique characters')
|
| 15 |
+
example_texts = ['abcdefg', 'xyz']
|
| 16 |
+
|
| 17 |
+
chars = tf.strings.unicode_split(example_texts, input_encoding='UTF-8')
|
| 18 |
+
|
| 19 |
+
ids_from_chars = tf.keras.layers.StringLookup(
|
| 20 |
+
vocabulary=list(vocab), mask_token=None)
|
| 21 |
+
ids = ids_from_chars(chars)
|
| 22 |
+
chars_from_ids = tf.keras.layers.StringLookup(
|
| 23 |
+
vocabulary=ids_from_chars.get_vocabulary(), invert=True, mask_token=None)
|
| 24 |
+
chars = chars_from_ids(ids)
|
| 25 |
+
tf.strings.reduce_join(chars, axis=-1).numpy()
|
| 26 |
+
def text_from_ids(ids):
|
| 27 |
+
return tf.strings.reduce_join(chars_from_ids(ids), axis=-1)
|
| 28 |
+
all_ids = ids_from_chars(tf.strings.unicode_split(text, 'UTF-8'))
|
| 29 |
+
ids_dataset = tf.data.Dataset.from_tensor_slices(all_ids)
|
| 30 |
+
for ids in ids_dataset.take(10):
|
| 31 |
+
print(chars_from_ids(ids).numpy().decode('utf-8'))
|
| 32 |
+
seq_length = 100
|
| 33 |
+
examples_per_epoch = len(text)//(seq_length+1)
|
| 34 |
+
sequences = ids_dataset.batch(seq_length+1, drop_remainder=True)
|
| 35 |
+
|
| 36 |
+
for seq in sequences.take(1):
|
| 37 |
+
print(chars_from_ids(seq))
|
| 38 |
+
for seq in sequences.take(5):
|
| 39 |
+
print(text_from_ids(seq).numpy())
|
| 40 |
+
def split_input_target(sequence):
|
| 41 |
+
input_text = sequence[:-1]
|
| 42 |
+
target_text = sequence[1:]
|
| 43 |
+
return input_text, target_text
|
| 44 |
+
dataset = sequences.map(split_input_target)
|
| 45 |
+
for input_example, target_example in dataset.take(1):
|
| 46 |
+
print("Input :", text_from_ids(input_example).numpy())
|
| 47 |
+
print("Target:", text_from_ids(target_example).numpy())
|
| 48 |
+
# Batch size
|
| 49 |
+
BATCH_SIZE = 64
|
| 50 |
+
|
| 51 |
+
# Buffer size to shuffle the dataset
|
| 52 |
+
# (TF data is designed to work with possibly infinite sequences,
|
| 53 |
+
# so it doesn't attempt to shuffle the entire sequence in memory. Instead,
|
| 54 |
+
# it maintains a buffer in which it shuffles elements).
|
| 55 |
+
BUFFER_SIZE = 10000
|
| 56 |
+
dataset = (
|
| 57 |
+
dataset
|
| 58 |
+
.shuffle(BUFFER_SIZE)
|
| 59 |
+
.batch(BATCH_SIZE, drop_remainder=True)
|
| 60 |
+
.prefetch(tf.data.experimental.AUTOTUNE))
|
| 61 |
+
# Length of the vocabulary in chars
|
| 62 |
+
vocab_size = len(vocab)
|
| 63 |
+
|
| 64 |
+
# The embedding dimension
|
| 65 |
+
embedding_dim = 256
|
| 66 |
+
|
| 67 |
+
# Number of RNN units
|
| 68 |
+
rnn_units = 1024
|
| 69 |
+
class MyModel(tf.keras.Model):
|
| 70 |
+
def __init__(self, vocab_size, embedding_dim, rnn_units):
|
| 71 |
+
super().__init__(self)
|
| 72 |
+
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
|
| 73 |
+
self.gru = tf.keras.layers.GRU(rnn_units,
|
| 74 |
+
return_sequences=True,
|
| 75 |
+
return_state=True)
|
| 76 |
+
self.dense = tf.keras.layers.Dense(vocab_size)
|
| 77 |
+
|
| 78 |
+
def call(self, inputs, states=None, return_state=False, training=False):
|
| 79 |
+
x = inputs
|
| 80 |
+
x = self.embedding(x, training=training)
|
| 81 |
+
if states is None:
|
| 82 |
+
states = self.gru.get_initial_state(x)
|
| 83 |
+
x, states = self.gru(x, initial_state=states, training=training)
|
| 84 |
+
x = self.dense(x, training=training)
|
| 85 |
+
|
| 86 |
+
if return_state:
|
| 87 |
+
return x, states
|
| 88 |
+
else:
|
| 89 |
+
return x
|
| 90 |
+
class CustomTraining(MyModel):
|
| 91 |
+
@tf.function
|
| 92 |
+
def train_step(self, inputs):
|
| 93 |
+
inputs, labels = inputs
|
| 94 |
+
with tf.GradientTape() as tape:
|
| 95 |
+
predictions = self(inputs, training=True)
|
| 96 |
+
loss = self.loss(labels, predictions)
|
| 97 |
+
grads = tape.gradient(loss, model.trainable_variables)
|
| 98 |
+
self.optimizer.apply_gradients(zip(grads, model.trainable_variables))
|
| 99 |
+
|
| 100 |
+
return {'loss': loss}
|
| 101 |
+
model = CustomTraining(
|
| 102 |
+
vocab_size=len(ids_from_chars.get_vocabulary()),
|
| 103 |
+
embedding_dim=embedding_dim,
|
| 104 |
+
rnn_units=rnn_units)
|
| 105 |
+
for input_example_batch, target_example_batch in dataset.take(1):
|
| 106 |
+
example_batch_predictions = model(input_example_batch)
|
| 107 |
+
print(example_batch_predictions.shape, "# (batch_size, sequence_length, vocab_size)")
|
| 108 |
+
model.summary()
|
| 109 |
+
sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1)
|
| 110 |
+
sampled_indices = tf.squeeze(sampled_indices, axis=-1).numpy()
|
| 111 |
+
loss = tf.losses.SparseCategoricalCrossentropy(from_logits=True)
|
| 112 |
+
example_batch_mean_loss = loss(target_example_batch, example_batch_predictions)
|
| 113 |
+
print("Prediction shape: ", example_batch_predictions.shape, " # (batch_size, sequence_length, vocab_size)")
|
| 114 |
+
print("Mean loss: ", example_batch_mean_loss)
|
| 115 |
+
tf.exp(example_batch_mean_loss).numpy()
|
| 116 |
+
model.compile(optimizer = tf.keras.optimizers.Adadelta(),
|
| 117 |
+
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))
|
| 118 |
+
# Directory where the checkpoints will be saved
|
| 119 |
+
checkpoint_dir = './training_checkpoints'
|
| 120 |
+
# Name of the checkpoint files
|
| 121 |
+
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}")
|
| 122 |
+
|
| 123 |
+
checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
|
| 124 |
+
filepath=checkpoint_prefix,
|
| 125 |
+
save_weights_only=True)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
EPOCHS = 45
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
history = model.fit(dataset, epochs=100)
|
| 133 |
+
class OneStep(tf.keras.Model):
|
| 134 |
+
def __init__(self, model, chars_from_ids, ids_from_chars, temperature=1.0):
|
| 135 |
+
super().__init__()
|
| 136 |
+
self.temperature = temperature
|
| 137 |
+
self.model = model
|
| 138 |
+
self.chars_from_ids = chars_from_ids
|
| 139 |
+
self.ids_from_chars = ids_from_chars
|
| 140 |
+
|
| 141 |
+
# Create a mask to prevent "[UNK]" from being generated.
|
| 142 |
+
skip_ids = self.ids_from_chars(['[UNK]'])[:, None]
|
| 143 |
+
sparse_mask = tf.SparseTensor(
|
| 144 |
+
# Put a -inf at each bad index.
|
| 145 |
+
values=[-float('inf')]*len(skip_ids),
|
| 146 |
+
indices=skip_ids,
|
| 147 |
+
# Match the shape to the vocabulary
|
| 148 |
+
dense_shape=[len(ids_from_chars.get_vocabulary())])
|
| 149 |
+
self.prediction_mask = tf.sparse.to_dense(sparse_mask)
|
| 150 |
+
|
| 151 |
+
@tf.function
|
| 152 |
+
def generate_one_step(self, inputs, states=None):
|
| 153 |
+
# Convert strings to token IDs.
|
| 154 |
+
input_chars = tf.strings.unicode_split(inputs, 'UTF-8')
|
| 155 |
+
input_ids = self.ids_from_chars(input_chars).to_tensor()
|
| 156 |
+
|
| 157 |
+
# Run the model.
|
| 158 |
+
# predicted_logits.shape is [batch, char, next_char_logits]
|
| 159 |
+
predicted_logits, states = self.model(inputs=input_ids, states=states,
|
| 160 |
+
return_state=True)
|
| 161 |
+
# Only use the last prediction.
|
| 162 |
+
predicted_logits = predicted_logits[:, -1, :]
|
| 163 |
+
predicted_logits = predicted_logits/self.temperature
|
| 164 |
+
# Apply the prediction mask: prevent "[UNK]" from being generated.
|
| 165 |
+
predicted_logits = predicted_logits + self.prediction_mask
|
| 166 |
+
|
| 167 |
+
# Sample the output logits to generate token IDs.
|
| 168 |
+
predicted_ids = tf.random.categorical(predicted_logits, num_samples=1)
|
| 169 |
+
predicted_ids = tf.squeeze(predicted_ids, axis=-1)
|
| 170 |
+
|
| 171 |
+
# Convert from token ids to characters
|
| 172 |
+
predicted_chars = self.chars_from_ids(predicted_ids)
|
| 173 |
+
|
| 174 |
+
# Return the characters and model state.
|
| 175 |
+
return predicted_chars, states
|
| 176 |
+
one_step_model = OneStep(model, chars_from_ids, ids_from_chars)
|
| 177 |
+
start = time.time()
|
| 178 |
+
states = None
|
| 179 |
+
next_char = tf.constant(['toxitron said'])
|
| 180 |
+
result = [next_char]
|
| 181 |
+
|
| 182 |
+
for n in range(100):
|
| 183 |
+
next_char, states = one_step_model.generate_one_step(next_char, states=states)
|
| 184 |
+
result.append(next_char)
|
| 185 |
+
|
| 186 |
+
result = tf.strings.join(result)
|
| 187 |
+
end = time.time()
|
| 188 |
+
print(result[0].numpy().decode('utf-8'), '\n\n' + '_'*80)
|
| 189 |
+
print('\nRun time:', end - start)
|
| 190 |
+
tf.saved_model.save(one_step_model, 'one_step')
|