Error : (GATHER) failed to prepare
Hi @alkaf-ahmed,

I have reproduced the issue with TF 2.15. It is observed that the issue is with the representative data. Make sure the key you're using to yield data in your representative_data_gen_reg function matches the actual input name in your model. You need to reshape the input. Please try this fix
```
def representative_data_gen_reg():
# Approach 1 
#yield [x[40:80].reshape(40)] 
# Approach 2 
  for i in x[70:80] : 
    yield {"dense_112_input": i.reshape(1,-1)}
```

Thank You
 This issue is stale because it has been open for 7 days with no activity. It will be closed if no further activity occurs. Thank you. This issue was closed because it has been inactive for 7 days since being marked as stale. Please reopen if you'd like to work on this further.
Hello, 

I'm working on colab and I'm trying to adapt the following tutorial on TFLite :
 
https://www.tensorflow.org/lite/performance/post_training_integer_quant 

In the tutorial, the MNIST dataset is used, so when making a "representative_dataset " function, the following function is used : 

```
def representative_data_gen():
  for input_value in tf.data.Dataset.from_tensor_slices(train_images).batch(1).take(100):
    # Model has only one input so each data point has one element.
    yield [input_value]
```
I completly undersatnd why this is done (at least I hope I'm) so I tried to adapt the tutorial to another NN on regression which is vary basic but here the input to the NN so the "representative_dataset " function will be different as well. 

I'm trying to do that just so I undersatnd well how to work with TFLite, hence the simple NN that doesn't necessarily serve at anything. 

## ML code
Here's the code for the data and the learning : 

```
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,100)
y = np.exp(-5/x)
e = np.random.randn(100)
y = y+0.05*e
plt.plot(x,y,'o')
plt.show()

x = x.reshape(-1,1)
y = y.reshape(-1,1)


def reg_model() : 
  activ = 'tanh'
    # Define the model architecture
  model = tf.keras.Sequential([
    tf.keras.layers.Dense(100, input_shape=(x.shape), activation=activ),
    tf.keras.layers.Dense(100, activation=activ),
    tf.keras.layers.Dense(100, activation=activ),
    tf.keras.layers.Dense(100, activation=activ),
    tf.keras.layers.Dense(100, activation=activ),
    tf.keras.layers.Dense(100, activation=activ),
    tf.keras.layers.Dense(100, activation=activ),
    tf.keras.layers.Dense(1)
  ])

  # Train the digit classification model
  model.compile(optimizer='adam',
                loss=tf.keras.losses.mean_absolute_error)
  
  model.fit(
    x,
    y,
    epochs=20,
    validation_data=(x, y)
  ) 

  return model 

model = reg_model() 
``` 

## Code causing the error 
Here's where I have a problem : 

```
def representative_data_gen_reg():
# Approach 1 
  yield [x[40:80].reshape(40)] 
# Approach 2 
  # for i in x[40:80] : 
  #   yield {"val": i}
  
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_data_gen_reg

tflite_model_quant_wb = converter.convert()
```

## Error logs
Here's the error for **Approach 1** : 

```
INFO:tensorflow:Assets written to: /tmp/tmpa3xvd3rp/assets
/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert.py:953: UserWarning: Statistics for quantized inputs were expected, but not specified; continuing anyway.
  warnings.warn(

---------------------------------------------------------------------------

RuntimeError                              Traceback (most recent call last)

[<ipython-input-157-c4893ade4d26>](https://localhost:8080/#) in <cell line: 19>()
     17 converter.representative_dataset = representative_data_gen_reg
     18 
---> 19 tflite_model_quant_wb = converter.convert()

12 frames

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in wrapper(self, *args, **kwargs)
   1137   def wrapper(self, *args, **kwargs):
   1138     # pylint: disable=protected-access
-> 1139     return self._convert_and_export_metrics(convert_func, *args, **kwargs)
   1140     # pylint: enable=protected-access
   1141 

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in _convert_and_export_metrics(self, convert_func, *args, **kwargs)
   1091     self._save_conversion_params_metric()
   1092     start_time = time.process_time()
-> 1093     result = convert_func(self, *args, **kwargs)
   1094     elapsed_time_ms = (time.process_time() - start_time) * 1000
   1095     if result:

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in convert(self)
   1599         Invalid quantization parameters.
   1600     """
-> 1601     saved_model_convert_result = self._convert_as_saved_model()
   1602     if saved_model_convert_result:
   1603       return saved_model_convert_result

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in _convert_as_saved_model(self)
   1580       )
   1581       if self.saved_model_dir:
-> 1582         return super(TFLiteKerasModelConverterV2, self).convert(
   1583             graph_def, input_tensors, output_tensors
   1584         )

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in convert(self, graph_def, input_tensors, output_tensors)
   1376     )
   1377 
-> 1378     return self._optimize_tflite_model(
   1379         result, self._quant_mode, quant_io=self.experimental_new_quantizer
   1380     )

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py](https://localhost:8080/#) in wrapper(*args, **kwargs)
    213       except Exception as error:
    214         report_error_message(str(error))
--> 215         raise error from None  # Re-throws the exception.
    216 
    217     return wrapper

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py](https://localhost:8080/#) in wrapper(*args, **kwargs)
    203     def wrapper(*args, **kwargs):
    204       try:
--> 205         return func(*args, **kwargs)
    206       except ConverterError as converter_error:
    207         if converter_error.errors:

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in _optimize_tflite_model(self, model, quant_mode, quant_io)
   1035         q_allow_float = quant_mode.is_allow_float()
   1036         q_variable_quantization = quant_mode.enable_mlir_variable_quantization
-> 1037         model = self._quantize(
   1038             model,
   1039             q_in_type,

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in _quantize(self, result, input_type, output_type, activations_type, bias_type, allow_float, enable_variable_quantization)
    733     )
    734     if self._experimental_calibrate_only or self.experimental_new_quantizer:
--> 735       calibrated = calibrate_quantize.calibrate(
    736           self.representative_dataset.input_gen
    737       )

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py](https://localhost:8080/#) in wrapper(*args, **kwargs)
    213       except Exception as error:
    214         report_error_message(str(error))
--> 215         raise error from None  # Re-throws the exception.
    216 
    217     return wrapper

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py](https://localhost:8080/#) in wrapper(*args, **kwargs)
    203     def wrapper(*args, **kwargs):
    204       try:
--> 205         return func(*args, **kwargs)
    206       except ConverterError as converter_error:
    207         if converter_error.errors:

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/optimize/calibrator.py](https://localhost:8080/#) in calibrate(self, dataset_gen)
    252     Args:
    253       dataset_gen: A generator that generates calibration samples.
--> 254     """
    255     self._feed_tensors(dataset_gen, resize_input=True)
    256     return self._calibrator.Calibrate()

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/optimize/calibrator.py](https://localhost:8080/#) in _feed_tensors(self, dataset_gen, resize_input)
    141                 [list(s.shape) for s in input_array], signature_key
    142             )
--> 143           else:
    144             self._calibrator.Prepare([list(s.shape) for s in input_array])
    145         else:

RuntimeError: gather index out of boundsNode number 1 (GATHER) failed to prepare.
```

Here's the error for **Approach 2** : 

```
INFO:tensorflow:Assets written to: /tmp/tmpxk5_dx3j/assets
/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert.py:953: UserWarning: Statistics for quantized inputs were expected, but not specified; continuing anyway.
  warnings.warn(

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

[<ipython-input-158-52485a584b65>](https://localhost:8080/#) in <cell line: 19>()
     17 converter.representative_dataset = representative_data_gen_reg
     18 
---> 19 tflite_model_quant_wb = converter.convert()

13 frames

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in wrapper(self, *args, **kwargs)
   1137   def wrapper(self, *args, **kwargs):
   1138     # pylint: disable=protected-access
-> 1139     return self._convert_and_export_metrics(convert_func, *args, **kwargs)
   1140     # pylint: enable=protected-access
   1141 

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in _convert_and_export_metrics(self, convert_func, *args, **kwargs)
   1091     self._save_conversion_params_metric()
   1092     start_time = time.process_time()
-> 1093     result = convert_func(self, *args, **kwargs)
   1094     elapsed_time_ms = (time.process_time() - start_time) * 1000
   1095     if result:

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in convert(self)
   1599         Invalid quantization parameters.
   1600     """
-> 1601     saved_model_convert_result = self._convert_as_saved_model()
   1602     if saved_model_convert_result:
   1603       return saved_model_convert_result

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in _convert_as_saved_model(self)
   1580       )
   1581       if self.saved_model_dir:
-> 1582         return super(TFLiteKerasModelConverterV2, self).convert(
   1583             graph_def, input_tensors, output_tensors
   1584         )

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in convert(self, graph_def, input_tensors, output_tensors)
   1376     )
   1377 
-> 1378     return self._optimize_tflite_model(
   1379         result, self._quant_mode, quant_io=self.experimental_new_quantizer
   1380     )

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py](https://localhost:8080/#) in wrapper(*args, **kwargs)
    213       except Exception as error:
    214         report_error_message(str(error))
--> 215         raise error from None  # Re-throws the exception.
    216 
    217     return wrapper

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py](https://localhost:8080/#) in wrapper(*args, **kwargs)
    203     def wrapper(*args, **kwargs):
    204       try:
--> 205         return func(*args, **kwargs)
    206       except ConverterError as converter_error:
    207         if converter_error.errors:

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in _optimize_tflite_model(self, model, quant_mode, quant_io)
   1035         q_allow_float = quant_mode.is_allow_float()
   1036         q_variable_quantization = quant_mode.enable_mlir_variable_quantization
-> 1037         model = self._quantize(
   1038             model,
   1039             q_in_type,

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py](https://localhost:8080/#) in _quantize(self, result, input_type, output_type, activations_type, bias_type, allow_float, enable_variable_quantization)
    733     )
    734     if self._experimental_calibrate_only or self.experimental_new_quantizer:
--> 735       calibrated = calibrate_quantize.calibrate(
    736           self.representative_dataset.input_gen
    737       )

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py](https://localhost:8080/#) in wrapper(*args, **kwargs)
    213       except Exception as error:
    214         report_error_message(str(error))
--> 215         raise error from None  # Re-throws the exception.
    216 
    217     return wrapper

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py](https://localhost:8080/#) in wrapper(*args, **kwargs)
    203     def wrapper(*args, **kwargs):
    204       try:
--> 205         return func(*args, **kwargs)
    206       except ConverterError as converter_error:
    207         if converter_error.errors:

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/optimize/calibrator.py](https://localhost:8080/#) in calibrate(self, dataset_gen)
    252     Args:
    253       dataset_gen: A generator that generates calibration samples.
--> 254     """
    255     self._feed_tensors(dataset_gen, resize_input=True)
    256     return self._calibrator.Calibrate()

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/optimize/calibrator.py](https://localhost:8080/#) in _feed_tensors(self, dataset_gen, resize_input)
    119         if self._interpreter is None:
    120           self._interpreter = Interpreter(model_content=self._model_content)
--> 121         signature_key = None
    122         input_array = self._create_input_array_from_dict(None, sample)
    123       elif isinstance(sample, list):

[/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/optimize/calibrator.py](https://localhost:8080/#) in _create_input_array_from_dict(self, signature_key, inputs)
     92         key=lambda item: item[1]["index"],
     93     )
---> 94     for input_name, _ in input_details:
     95       input_array.append(inputs[input_name])
     96     return input_array

KeyError: 'dense_74_input'
```


In the doc's it's advised to use the second approach to make the function : 
https://www.tensorflow.org/lite/performance/post_training_quantization 

But when I did that I just got `KeyError: 'dense_74_input' `. So any idea where I missed up ? 

Thanks for any help 