Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a stateful LSTM model to predict without specifying the same batch_size as I trained it?

I tried to set stateful=True to train my LSTM model and it worked.

But I have to reshape my input to the same batch_size that I set for the first layer, which is a must for stateful RNN, or I will get an error: InvalidArgumentError: Invalid input_h shape.

I set the batch_size as 64, but I want to only input one start sentence to generate text. If I have to provide input with batch_size=64, I need to prepare for 64 sentences, which is ridiculous.

It worked well if I did not set the stateful=True, but I need to improve the performance. In this case, how can I use a stateful LSTM model without matching the batch_size I set?

The model I defined

seq_length = 100
batch_size = 64
epochs = 3

vocab_size = len(vocab) # 65
embedding_dim = 256
rnn_units = 1024

def bi_lstm(vocab_size, embedding_dim, batch_size, rnn_units):
  model = keras.models.Sequential([
      keras.layers.Embedding(vocab_size, embedding_dim,
                  batch_input_shape = (batch_size, None)),
      keras.layers.Bidirectional(
          keras.layers.LSTM(units = rnn_units, 
                  return_sequences = True,
                  stateful = True,
                  recurrent_initializer = "glorot_uniform"
      )),
      keras.layers.Dense(vocab_size),
  ])
  return model

I made a simple test like this, and it showed me the error.

for x, y in seq_dataset.take(1):
  x = x[:-10,:] # change the batch size from 64 to 54, it worked well if I del this line
  print(x.shape)
  pred = model(x)
  print(pred.shape)
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-98-99323ee3e09d> in <module>()
      2   x = x[:-10,:]
      3   print(x.shape)
----> 4   pred = model(x)
      5   print(pred.shape)

14 frames
/tensorflow-2.0.0/python3.6/tensorflow_core/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
    889           with base_layer_utils.autocast_context_manager(
    890               self._compute_dtype):
--> 891             outputs = self.call(cast_inputs, *args, **kwargs)
    892           self._handle_activity_regularization(inputs, outputs)
    893           self._set_mask_metadata(inputs, outputs, input_masks)

/tensorflow-2.0.0/python3.6/tensorflow_core/python/keras/engine/sequential.py in call(self, inputs, training, mask)
    254       if not self.built:
    255         self._init_graph_network(self.inputs, self.outputs, name=self.name)
--> 256       return super(Sequential, self).call(inputs, training=training, mask=mask)
    257 
    258     outputs = inputs  # handle the corner case where self.layers is empty

/tensorflow-2.0.0/python3.6/tensorflow_core/python/keras/engine/network.py in call(self, inputs, training, mask)
    706     return self._run_internal_graph(
    707         inputs, training=training, mask=mask,
--> 708         convert_kwargs_to_constants=base_layer_utils.call_context().saving)
    709 
    710   def compute_output_shape(self, input_shape):

/tensorflow-2.0.0/python3.6/tensorflow_core/python/keras/engine/network.py in _run_internal_graph(self, inputs, training, mask, convert_kwargs_to_constants)
    858 
    859           # Compute outputs.
--> 860           output_tensors = layer(computed_tensors, **kwargs)
    861 
    862           # Update tensor_dict.

/tensorflow-2.0.0/python3.6/tensorflow_core/python/keras/layers/wrappers.py in __call__(self, inputs, initial_state, constants, **kwargs)
    526 
    527     if initial_state is None and constants is None:
--> 528       return super(Bidirectional, self).__call__(inputs, **kwargs)
    529 
    530     # Applies the same workaround as in `RNN.__call__`

/tensorflow-2.0.0/python3.6/tensorflow_core/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
    889           with base_layer_utils.autocast_context_manager(
    890               self._compute_dtype):
--> 891             outputs = self.call(cast_inputs, *args, **kwargs)
    892           self._handle_activity_regularization(inputs, outputs)
    893           self._set_mask_metadata(inputs, outputs, input_masks)

/tensorflow-2.0.0/python3.6/tensorflow_core/python/keras/layers/wrappers.py in call(self, inputs, training, mask, initial_state, constants)
    640 
    641       y = self.forward_layer(forward_inputs,
--> 642                              initial_state=forward_state, **kwargs)
    643       y_rev = self.backward_layer(backward_inputs,
    644                                   initial_state=backward_state, **kwargs)

/tensorflow-2.0.0/python3.6/tensorflow_core/python/keras/layers/recurrent.py in __call__(self, inputs, initial_state, constants, **kwargs)
    621 
    622     if initial_state is None and constants is None:
--> 623       return super(RNN, self).__call__(inputs, **kwargs)
    624 
    625     # If any of `initial_state` or `constants` are specified and are Keras

/tensorflow-2.0.0/python3.6/tensorflow_core/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
    889           with base_layer_utils.autocast_context_manager(
    890               self._compute_dtype):
--> 891             outputs = self.call(cast_inputs, *args, **kwargs)
    892           self._handle_activity_regularization(inputs, outputs)
    893           self._set_mask_metadata(inputs, outputs, input_masks)

/tensorflow-2.0.0/python3.6/tensorflow_core/python/keras/layers/recurrent_v2.py in call(self, inputs, mask, training, initial_state)
    959         if can_use_gpu:
    960           last_output, outputs, new_h, new_c, runtime = cudnn_lstm(
--> 961               **cudnn_lstm_kwargs)
    962         else:
    963           last_output, outputs, new_h, new_c, runtime = standard_lstm(

/tensorflow-2.0.0/python3.6/tensorflow_core/python/keras/layers/recurrent_v2.py in cudnn_lstm(inputs, init_h, init_c, kernel, recurrent_kernel, bias, mask, time_major, go_backwards)
   1172     outputs, h, c, _ = gen_cudnn_rnn_ops.cudnn_rnn(
   1173         inputs, input_h=init_h, input_c=init_c, params=params, is_training=True,
-> 1174         rnn_mode='lstm')
   1175 
   1176   last_output = outputs[-1]

/tensorflow-2.0.0/python3.6/tensorflow_core/python/ops/gen_cudnn_rnn_ops.py in cudnn_rnn(input, input_h, input_c, params, rnn_mode, input_mode, direction, dropout, seed, seed2, is_training, name)
    107             input_mode=input_mode, direction=direction, dropout=dropout,
    108             seed=seed, seed2=seed2, is_training=is_training, name=name,
--> 109             ctx=_ctx)
    110       except _core._SymbolicException:
    111         pass  # Add nodes to the TensorFlow graph.

/tensorflow-2.0.0/python3.6/tensorflow_core/python/ops/gen_cudnn_rnn_ops.py in cudnn_rnn_eager_fallback(input, input_h, input_c, params, rnn_mode, input_mode, direction, dropout, seed, seed2, is_training, name, ctx)
    196   "is_training", is_training)
    197   _result = _execute.execute(b"CudnnRNN", 4, inputs=_inputs_flat,
--> 198                              attrs=_attrs, ctx=_ctx, name=name)
    199   _execute.record_gradient(
    200       "CudnnRNN", _inputs_flat, _attrs, _result, name)

/tensorflow-2.0.0/python3.6/tensorflow_core/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     65     else:
     66       message = e.message
---> 67     six.raise_from(core._status_to_exception(e.code, message), None)
     68   except TypeError as e:
     69     keras_symbolic_tensors = [

/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: Invalid input_h shape: [1,64,1024] [1,54,1024] [Op:CudnnRNN]
like image 512
Andy Avatar asked Nov 11 '19 10:11

Andy


1 Answers

When stateful=True, batch_size is indeed needed for the model's logic to work properly.

However, the weights of your model don't need to know the batch_size at all. So, it would be nice if there was some set_batch_size() method, or even nicer, if fit() and predict() could derive it from the input. But unfortunately, this is not the case.

But there is a workaround: Just define another instance of that model and specify batch_size=1 (or whatever number you wish). Then, just assign the trained model's weights to this new model with different batch size:

model64 = bi_lstm(vocab_size, embedding_dim, batch_size=64, rnn_units=rnn_units)
model64.fit(...)
# optional: model64.save_weights('model64_weights.hdf5')

model1 = bi_lstm(vocab_size, embedding_dim, batch_size=1, rnn_units=rnn_units)
model1.set_weights(model64.get_weights()) # or: model1.load_weights('model64_weights.hdf5')
model1.predict(...)

This works because batch_size does not participate in the weights' shapes at all and therefore they are interchangeable.

like image 78
sebrockm Avatar answered Oct 16 '22 22:10

sebrockm