Check this Py code: import tensorflow as tf
import numpy as np
block_size = 20
with open('data/universe.txt', 'r', encoding='utf-8') as f:
text = f.read()
data = np.array([ord(c) for c in text], dtype=np.int32)
vocab_size = len(set(data))
class TransformerBlock(tf.keras.layers.Layer):
def init(self, n_embd, n_head, **kwargs):
# Make sure to forward the ‘kwargs’ to the superclass initializer
super().init(**kwargs)
code
self.ln1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
self.attn = tf.keras.layers.MultiHeadAttention(num_heads=n_head, key_dim=n_embd // n_head)
self.ln2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
self.proj = tf.keras.Sequential([tf.keras.layers.Dense(4 * n_embd, activation="relu"), tf.keras.layers.Dense(n_embd)])
def call(self, x, training):
a = self.ln1(x)
a = self.attn(query=a, key=a, value=a, training=training)
x = x + a
a = self.ln2(x)
a = self.proj(a, training=training)
x = x + a
return x
def get_config(self):
config = super().get_config().copy()
config.update({
"n_embd": self.attn.key_dim * self.attn.num_heads,
"n_head": self.attn.num_heads,
})
return config
I get this error now: Traceback (most recent call last):
File "c:\Users\Dell-PC\Desktop\Projets\reweight-gpt-main\Inference-tf.py", line 110, in
model = tf.keras.models.load_model("Universe-GPT-tf.keras",
File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\saving\saving_api.py", line 230, in load_model
return saving_lib.load_model(
File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\saving\saving_lib.py", line 275, in load_model
raise e
File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\saving\saving_lib.py", line 240, in load_model
model = deserialize_keras_object(
File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\saving\serialization_lib.py", line 704, in deserialize_keras_object
instance = cls.from_config(inner_config)
File "c:\Users\Dell-PC\Desktop\Projets\reweight-gpt-main\Inference-tf.py", line 76, in from_config
return cls(**config)
File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\trackable\base.py", line 204, in _method_wrapper
result = method(self, *args, **kwargs)
File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\utils\generic_utils.py", line 514, in validate_kwargs
raise TypeError(error_message, kwarg)
TypeError: ('Keyword argument not understood:', 'dropout_rate')
Assistant
The error message you are receiving indicates that the argument is not expected within the . This could be for a few reasons. The most likely issue is that the isn't being used within the 's constructor () or anywhere else in the class, and therefore, there's no need to pass it as an argument or store it.
User
@classmethod
def from_config(cls, config, custom_objects=None):
if custom_objects is not None:
with tf.keras.utils.custom_object_scope(custom_objects):
return cls(**config)
return cls(**config)
Assistant
The from_config class method is used to recreate a tf.keras.Model or layer instance from a saved configuration. This method is typically called by tf.keras.models.load_model and other functions that deserialize a model. The purpose of custom_objects is to provide a dictionary that maps names (strings) to custom classes or functions that are used in the model. This is necessary when your model uses custom layers or other custom components that Keras does not recognize natively.
Your provided from_config method appears to be correct. This method checks if any custom objects are provided and ensures they are used to reconstruct the model with the supplied configuration. If no custom objects are required, it simply recreates the model using the configuration alone.
def get_config(self):
config = super().get_config().copy()
config.update({
"vocab_size": self.vocab_size,
"n_embd": self.n_embd,
"block_size": self.block_size,
"n_head": self.n_head,
"n_layer": self.n_layer,
"dropout_rate": self.dropout_rate,
})
return config
@classmethod
def from_config(cls, config, custom_objects=None):
# This ensures custom_objects are taken into account when reconstructing the model
if custom_objects is not None:
with tf.keras.utils.custom_object_scope(custom_objects):
return cls(**config)
return cls(**config)
def call(self, idx, targets=None, training=False):
B, T = tf.shape(idx)[0], tf.shape(idx)[1]
tok_emb = self.token_embedding_table(idx)
pos_emb = self.position_embedding_table(tf.range(T))
x = tok_emb + tf.cast(pos_emb[None, :, :], tok_emb.dtype) # Explicit casting to match dtype
for block in self.blocks:
x = block(x, training=training)
x = self.ln_f(x)
logits = self.lm_head(x)
loss = None
if targets is not None:
loss = self.compute_loss(logits, targets)
return logits, loss
def compute_loss(self, logits, targets):
loss = tf.keras.losses.sparse_categorical_crossentropy(targets, logits, from_logits=True)
return tf.reduce_mean(loss)
def generate(self, idx, max_new_tokens):
for _ in range(max_new_tokens):
logits, _ = self(idx[:, -block_size:], training=False)
logits = logits[:, -1, :]
idx_next = tf.random.categorical(logits, num_samples=1, dtype=tf.int32)
idx = tf.concat([idx, idx_next], axis=1)
return idx
Load the saved model
model = tf.keras.models.load_model("Universe-GPT-tf.keras",
custom_objects={
"GPTLanguageModel": GPTLanguageModel,
"TransformerBlock": TransformerBlock, # Possible that you require this as well
})
Set the maximum number of new tokens to generate
max_new_tokens = 100
Initialize the input sequence with a random starting point
generated_text = ''.join([chr(c) for c in generated_text[0]])
print("Generated Text:")
print(generated_text)
There are a few issues to address in your code:
The init method in the TransformerBlock class should be __init__. It is currently missing the underscores. Also, the second init call inside TransformerBlock should be super().__init__(**kwargs).
In the TransformerBlock class, the proj attribute is a Sequential model and later, when you call a = self.proj(a, training=training), you should remove the training=training part, since Sequential layers are called only with the input tensor a.
The GPTLanguageModel class stores certain attributes like vocab_size, n_embd, block_size, n_head, n_layer, and dropout_rate that it needs to use, but they are not defined in the __init__ method except vocab_size. You should save these attributes as instance variables if you intend to access them later.
The self.blocks attribute in GPTLanguageModel should be a tf.keras.models.Sequential list of TransformerBlock layers so that when the x is passed through each block during the call, TensorFlow keeps track of the layers accordingly.
Here is an updated version of your code with corrections:
python
import tensorflow as tf
import numpy as np
block_size = 20
with open('data/universe.txt', 'r', encoding='utf-8') as f:
text = f.read()
data = np.array([ord(c) for c in text], dtype=np.int32)
vocab_size = len(set(data))
class TransformerBlock(tf.keras.layers.Layer):
def __init__(self, n_embd, n_head, **kwargs):
super().__init__(**kwargs)
self.ln1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
self.attn = tf.keras.layers.MultiHeadAttention(num_heads=n_head, key_dim=n_embd // n_head)
self.ln2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
self.proj = tf.keras.Sequential([tf.keras.layers.Dense(4 * n_embd, activation="relu"), tf.keras.layers.Dense(n_embd)])
def call(self, x, training):
a = self.ln1(x)
a = self.attn(query=a, key=a, value=a)
x = x + a
a = self.ln2(x)
a = self.proj(a)
x = x + a
return x
# The rest of the TransformerBlock class remains the same
class GPTLanguageModel(tf.keras.Model):
def __init__(self, vocab_size, n_embd, block_size, n_head, n_layer, dropout_rate=0.1):
super(GPTLanguageModel, self).__init__()
self.vocab_size = vocab_size
self.n_embd = n_embd
self.block_size = block_size
self.n_head = n_head
self.n_layer = n_layer
self.dropout_rate = dropout_rate
self.token_embedding_table = tf.keras.layers.Embedding(vocab_size, n_embd)
self.position_embedding_table = tf.keras.layers.Embedding(block_size, n_embd)
# Change blocks to be a Sequential model
self.blocks = tf.keras.Sequential([TransformerBlock(n_embd, n_head) for _ in range(n_layer)])
self.ln_f = tf.keras.layers.LayerNormalization(epsilon=1e-6)
self.lm_head = tf.keras.layers.Dense(vocab_size)
# The rest of the GPTLanguageModel class remains the same
# The code to generate text using the model remains the same
Remember to store this updated code in a file and save the model appropriately before trying to load it with tf.keras.models.load_model. The way the model is being loaded assumes that there is a model previously saved at the path "Universe-GPT-tf.keras". If there are any version mismatches or the model has not been saved correctly, you may get an error when loading it.
dropout_rate
GPTLanguageModel
dropout_rate
GPTLanguageModel
__init__
Additionally, in the code provided, the dropout_rate is indeed not being used. If the dropout_rate is unnecessary, you can simply remove it from the class's __init__ method, get_config, and from_config methods.
Here's the corrected __init__ method without the dropout_rate:
And you should ensure that the from_config method doesn't expect the dropout_rate argument as well:
python
@classmethod
def from_config(cls, config, custom_objects=None):
if custom_objects is not None:
with tf.keras.utils.custom_object_scope(custom_objects):
return cls(**config)
return cls(**config)
Make sure to check your code and verify whether the model indeed should have a dropout layer. If it should, then consider implementing the dropout within your Transformer Block or in the GPTLanguageModel, and make use of the dropout_rate variable. If not, then you should remove it as shown above.
After updating your class definitions, you'll need to re-save your model with the correct architecture if you've modified the class definition. You can't load a previously saved model with a class definition that doesn't match the one it was saved with. Make sure to create and train a new instance of the model with the updated class definition and save it again.
If your model contains custom layers or functions not included in the Keras library, such as GPTLanguageModel or TransformerBlock, these must be passed when loading the model. For example:
python
model = tf.keras.models.load_model("Universe-GPT-tf.keras",
custom_objects={
"GPTLanguageModel": GPTLanguageModel,
"TransformerBlock": TransformerBlock,
})
When you call tf.keras.models.load_model with the appropriate custom_objects dict, it should reconstruct your custom model from the saved configuration without any issues, given that the configuration matches the custom classes exactly as they were at the time of saving the model.
Ensure that any other custom components used within your model are also included in custom_objects dictionary when loading the model. Otherwise, Keras will not be able to reconstruct those components, leading to an error. Additionally, if there have been changes to the class definitions that are incompatible with how the model was initially saved, you may need to retrain and resave the model with the updated class definitions.