when i run this code: import tensorflow as tf import numpy as np Hyperparameters…
- User
when i run this code: import tensorflow as tf import numpy as np
Hyperparameters
batch_size = 96 block_size = 20 max_iters = 200 eval_interval = 100 learning_rate = 1e-3 device = 'cuda:0' if tf.test.is_gpu_available() else 'cpu' eval_iters = 20 # Changed to 20 for consistency with eval_interval n_embd = 16 n_head = 2 n_layer = 2 dropout_rate = 0.0 # Renamed from dropout for clarity
hidden_nodes = 20
tf.random.set_seed(1337)
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) n = int(0.9 * len(data)) train_data = data[:n] val_data = data[n:]
@tf.function def get_batch(split): data = train_data if split == 'train' else val_data ix = np.random.randint(0, len(data) - block_size, size=(batch_size,)) x = np.array([data[i:i + block_size] for i in ix]) y = np.array([data[i + 1:i + block_size + 1] for i in ix]) return x, y
@tf.keras.utils.register_keras_serializable() 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.token_embedding_table = tf.keras.layers.Embedding(vocab_size, n_embd) self.position_embedding_table = tf.keras.layers.Embedding(block_size, n_embd) self.blocks = [self._build_block(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)
def _build_block(self, n_embd, n_head): head_size = n_embd // n_head # Bug fixed, removed '+ 1' return tf.keras.Sequential([ tf.keras.layers.LayerNormalization(epsilon=1e-6), tf.keras.layers.MultiHeadAttention(num_heads=n_head, key_dim=head_size), tf.keras.layers.Dense(4 * n_embd, activation='relu'), tf.keras.layers.Dense(n_embd) ]) 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 idxvocab_size = len(set(data))
- Assistant
The error is occurring because TensorFlow tensors do not support direct conversion to NumPy arrays within the TensorFlow computational graph. When you attempt to perform NumPy operations on
tf.Tensorobjects, such as those created bytf.function, you will encounter this error because TensorFlow tensors do not have a value outside of the TensorFlow session context.The
get_batchfunction calls thenumpy.random.randintfunction withlen(data) - block_sizeas one of its arguments. Since is decorated with , the tensor is part of the TensorFlow graph, and you cannot perform NumPy operations on it directly. - User
I got this error: Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\reweight-gpt-main\reweight-gpt-tensorflow.py", line 120, in inputs, targets = get_batch('train') File "c:\Users\Dell-PC\Desktop\Projets\reweight-gpt-main\reweight-gpt-tensorflow.py", line 113, in tensor_function return numpy_function(*tensor_args, **kwargs) File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\util\traceback_utils.py", line 153, in error_handler raise e.with_traceback(filtered_tb) from None File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\eager\polymorphic_function\autograph_util.py", line 52, in autograph_handler raise e.ag_error_metadata.to_exception(e) tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: in user code:
File "c:\Users\Dell-PC\Desktop\Projets\reweight-gpt-main\reweight-gpt-tensorflow.py", line 33, in get_batch * x = np.array([data[i:i + block_size] for i in ix]) OperatorNotAllowedInGraphError: Iterating over a symbolic `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying touse an unsupported feature.
- Assistant
Apologies for the confusion, I made an error in the previous instructions. Since we need to keep all operations within the TensorFlow realm when using
@tf.function, we cannot use NumPy's slicing to generatexandywithin the function. Instead, we must use TensorFlow's native operations for indexing and slicing. - User
- Assistant