I need to avoid this error: tensorflow.python error.framework.errors_impl.InternalError: Failed copying input tensor from /job:localhost/replica:0/task:0/device:CPU:0 to /job:localhost/replica:0/task:0/device:GPU:0 in order to run _EagerConst: Dst tensor is not initialized. It is connected with the acquisition of my 3060 memory, in order to avoid it, I have to do Embedding layer calculations on the CPU, but how? I tried run full model on CPU, and its works fine, but very slow. For example, if I reduce the number of neurons in all layers to 128, then I can use 8000 sentences (data_list[:8000] instead of 6000 for example below) for training, but I have ~ 20000 of them.
My model:
class CPUEmbedding(Embedding):
@tf_utils.shape_type_conversion
def build(self, input_shape):
with ops.device('cpu:0'):
self.embeddings = self.add_weight(
shape=(self.input_dim, self.output_dim),
initializer=self.embeddings_initializer,
name='embeddings',
regularizer=self.embeddings_regularizer,
constraint=self.embeddings_constraint)
self.built = True
print('Embedding starts on cpu')
model = Sequential()
model.add(CPUEmbedding(19260, 256, input_length=163))
model.add(LSTM(256, return_sequences=True)) # the output will be a sequence of the same length
model.add(Dropout(0.2))
model.add(LSTM(512))
model.add(Dropout(0.2))
model.add(Dense(self.total_words, activation='softmax'))
adam = Adam(learning_rate=0.001)
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['acc'])
Model summary:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
cpu_embedding (CPUEmbedding (None, 163, 256) 4930560
)
lstm (LSTM) (None, 163, 256) 525312
dropout (Dropout) (None, 163, 256) 0
lstm_1 (LSTM) (None, 512) 1574912
dropout_1 (Dropout) (None, 512) 0
dense (Dense) (None, 19260) 9880380
=================================================================
Total params: 16,911,164
Trainable params: 16,911,164
Non-trainable params: 0
A model that you can run, but first you will need to download some big book
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Embedding, LSTM, Dense, Dropout
from keras.preprocessing.text import Tokenizer
from keras.models import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
import numpy as np
tokenizer = Tokenizer()
# Book with len > 1 000 000 words
with open('text.txt', encoding='utf-8') as f:
data = f.read().replace('\ufeff', '')
data_list = data.lower().split("\n")
tokenizer.fit_on_texts(data_list)
total_words = len(tokenizer.word_index) + 1
print('Words number:', total_words)
input_sequences = []
for line in data_list:
token_list = tokenizer.texts_to_sequences([line])[0]
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i + 1]
input_sequences.append(n_gram_sequence)
max_sequence_len = max([len(x) for x in input_sequences])
input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))
X, labels = input_sequences[:, :-1], input_sequences[:, -1]
Y = to_categorical(labels, num_classes=total_words)
model = Sequential()
model.add(Embedding(total_words, 256, input_length=max_sequence_len - 1))
model.add(LSTM(256, return_sequences=True))
model.add(Dropout(0.1))
model.add(LSTM(512))
model.add(Dropout(0.1))
model.add(Dense(total_words, activation='softmax'))
adam = Adam(lr=0.001)
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['acc'])
history = model.fit(x=X, y=Y, batch_size=128, epochs=1000)
Versions:
1)
- OS: Windows 10
- Cuda: 11.6 (latest, from nvidia site)
- python: 3.9
- tensorflow: 2.8
- starts in: cmd
- GPU: 3060
- OS: Windows 11
- Cuda: downloaded by conda
- python: 3.8
- tensorflow: 2.6
- starts in: conda
- GPU: 1060 Ti