Skip to content

load_model - the two structures don't have the same nested structure #14345

Closed

Description

@eyalshafran

I trained a model and saved it using:
model.save("model_name")
I then call
model = tf.keras.models.load_model("model_name")
and get a "The two structures don't have the same nested structure." error. The structure that the model is expecting upon loading is not what I defined in the model.

My model:

roberta_layer = TFRobertaModel.from_pretrained('roberta-base')

ids = tf.keras.layers.Input((64,), dtype=tf.int32)
att = tf.keras.layers.Input((64,), dtype=tf.int32)

roberta_inputs = [ids, att]

sequence_output,pooled_output = roberta_layer(roberta_inputs)

# unigram
x1 = tf.keras.layers.Conv1D(32,1,activation='relu')(sequence_output)
x1 = tf.keras.layers.GlobalMaxPool1D()(x1)

# bigram
x2 = tf.keras.layers.Conv1D(32,2,activation='relu')(sequence_output)
x2 = tf.keras.layers.GlobalMaxPool1D()(x2)

# trigram
x3 = tf.keras.layers.Conv1D(32,3,activation='relu')(sequence_output)
x3 = tf.keras.layers.GlobalMaxPool1D()(x3)

concat = tf.keras.layers.Concatenate()([x1,x2,x3])
concat = tf.keras.layers.Dropout(0.5)(concat)

outputs = tf.keras.layers.Dense(11, activation='sigmoid')(concat)

model = tf.keras.Model(inputs=roberta_inputs, outputs=outputs)

I'm using tf 2.4.0
and transformers 3.5.1

The full error is:
The two structures don't have the same nested structure.

First structure: type=dict str={'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='inputs/input_ids')}

Second structure: type=list str=[TensorSpec(shape=(None, 64), dtype=tf.int32, name='inputs/0'), TensorSpec(shape=(None, 64), dtype=tf.int32, name='inputs/1')]

More specifically: The two namedtuples don't have the same sequence type. First structure type=dict str={'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='inputs/input_ids')} has type dict, while second structure type=list str=[TensorSpec(shape=(None, 64), dtype=tf.int32, name='inputs/0'), TensorSpec(shape=(None, 64), dtype=tf.int32, name='inputs/1')] has type list

During handling of the above exception, another exception occurred:

Activity

  1. wildangunawan commented on Jan 28, 2021

    @wildangunawan

    I'm having the same issue with TF 2.4.1 and Transformers 4.2.2.

    First structure also have shape=(None, 5) while second structure is shape=(None, maximum length of a sequence).

    Edit:

    Workaround for BERT: Save your model as .h5 instead of .tf. I didn't test this for other but it might worth a try.

  2. tarrade commented on May 7, 2021

    @tarrade

    Same issue with TF 2.5.0-rc3 and Transformer 4.5.1.

    Using out of the box Bert classifier:
    model = TFBertForSequenceClassification.from_pretrained(bert-base-multilingual-uncased',num_labels=2)
    then traning the model and then trying to save it give me the same error

    TypeError: The two structures don't have the same nested structure.
    
    First structure: type=dict str={'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='input_ids/input_ids')}
    
    Second structure: type=list str=[TensorSpec(shape=(None, 128), dtype=tf.int32, name='input_ids/0')]
    

    saving the mode .hd5 results in the same error message we reloading the model:
    model.save('bert_input.hd5')

  3. tarrade commented on May 7, 2021

    @tarrade

    Same issue with tensorflow 2.5.0-rc3
    Using Huggingface save/load is working fine

    model.save_pretrained('bert_input')
    reconstructed_model = TFBertForSequenceClassification.from_pretrained('bert_input')
    

    But this is not we need for tf.serving.

    It seems some class/function definition are not saved with the model so reloading the model will not work. Maybe there are some paramters to set to have this working ? (Stackoverflow)

  4. chenlongzhen commented on May 8, 2021

    @chenlongzhen

    Same issue

  5. samsatp commented on Aug 12, 2021

    @samsatp

    Same issue with transformers 4.6.1 and tensorflow 2.4.1

    I built the model as the following.

    Model: "model_1"
    __________________________________________________________________________________________________
    Layer (type)                    Output Shape         Param #     Connected to                     
    ==================================================================================================
    input_4 (InputLayer)            [(None, 512)]        0                                            
    __________________________________________________________________________________________________
    input_3 (InputLayer)            [(None, 512)]        0                                            
    __________________________________________________________________________________________________
    tf_distil_bert_model_1 (TFDisti TFBaseModelOutput(la 66362880    input_4[0][0]                    
                                                                     input_3[0][0]                    
    __________________________________________________________________________________________________
    bidirectional_1 (Bidirectional) (None, 128)          320256      tf_distil_bert_model_1[1][7]     
    __________________________________________________________________________________________________
    dense_2 (Dense)                 (None, 16)           2064        bidirectional_1[0][0]            
    __________________________________________________________________________________________________
    dropout_58 (Dropout)            (None, 16)           0           dense_2[0][0]                    
    __________________________________________________________________________________________________
    dense_3 (Dense)                 (None, 10)           170         dropout_58[0][0]                 
    ==================================================================================================
    Total params: 66,685,370
    Trainable params: 322,490
    Non-trainable params: 66,362,880
    __________________________________________________________________________________________________
    

    Then, it's trained and save as SavedModel. But when load it back, it's an error.

    The two structures don't have the same nested structure.
    
    First structure: type=dict str={'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='input_ids/input_ids')}
    
    Second structure: type=dict str={'input_ids': TensorSpec(shape=(None, 512), dtype=tf.int32, name='input_ids/input_ids'), 'attention_mask': TensorSpec(shape=(None, 512), dtype=tf.int32, name='input_ids/attention_mask')}
    
    More specifically: The two dictionaries don't have the same set of keys. First structure has keys type=list str=['input_ids'], while second structure has keys type=list str=['input_ids', 'attention_mask']
    Entire first structure:
    {'input_ids': .}
    Entire second structure:
    {'input_ids': ., 'attention_mask': .}
    
  6. samsatp commented on Aug 12, 2021

    @samsatp

    I finally solved this issue by using tf.saved_model.save(model, path_to_dir) instead of model.save(path_to_dir) or tf.keras.models.save_model(model, path_to_dir).

    followed by this guide: https://www.tensorflow.org/guide/saved_model

  7. jvishnuvardhan commented on Sep 21, 2021

    @jvishnuvardhan
    Contributor

    @eyalshafran Can you share a simple standalone code to reproduce the issue? Did you try recent TF/Keras versions? Thanks!

  8. google-ml-butler commented on Sep 28, 2021

    @google-ml-butler

    This issue has been automatically marked as stale because it has no recent activity. It will be closed if no further activity occurs. Thank you.

  9. GiovanniGedosal commented on Oct 3, 2021

    @GiovanniGedosal

    Same issue

  10. 20 remaining items

  11. YanlongLai commented on May 17, 2022

    @YanlongLai

    It is not working for me. The first structure is still fixed on 5

    First structure: type=dict str={'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='input_ids')}
    
    Second structure: type=dict str={'attention_mask': TensorSpec(shape=(None, 32), dtype=tf.int32, name='inputs/attention_mask'), 'input_ids': TensorSpec(shape=(None, 32), dtype=tf.int32, name='inputs/input_ids')}
    
  12. google-ml-butler commented on May 24, 2022

    @google-ml-butler

    This issue has been automatically marked as stale because it has no recent activity. It will be closed if no further activity occurs. Thank you.

  13. gowthamkpr commented on Jun 4, 2022

    @gowthamkpr
    Collaborator

    @eyalshafran I tried to replicate this issue with transformers 4.11.3 and tensorflow 2.8.2 and running into a different error. Here's the gist. Also as mentioned above can you please use tf.saved_model.load() instead of tf.keras.models.load_model() .

    If you think this is still a bug please create a different issue with working example and will look into it.
    Thanks!

  14. google-ml-butler commented on Jun 11, 2022

    @google-ml-butler

    This issue has been automatically marked as stale because it has no recent activity. It will be closed if no further activity occurs. Thank you.

  15. google-ml-butler commented on Jun 19, 2022

    @google-ml-butler

    Closing as stale. Please reopen if you'd like to work on this further.

  16. google-ml-butler commented on Jun 19, 2022

    @google-ml-butler

    Are you satisfied with the resolution of your issue?
    Yes
    No

  17. MrKZZ commented on Aug 3, 2022

    @MrKZZ

    Even I am facing the same issue.

    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-10-3a1d333d606b> in <module>()
    ----> 1 ner_model_2 = pickle.load(open('ner_model_2.pkl', 'rb'))
    
    2 frames
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/util/nest.py in assert_same_structure(nest1, nest2, check_types, expand_composites)
        533                   "Entire first structure:\n%s\n"
        534                   "Entire second structure:\n%s"
    --> 535                   % (str(e), str1, str2))
        536 
        537 
    
    ValueError: The two structures don't have the same nested structure.
    
    First structure: type=tuple str=(({'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='input_ids/input_ids')}, None, None, None, None, None, None, None, None, None, None, None, None, False), {})
    
    Second structure: type=tuple str=((TensorSpec(shape=(None, 384), dtype=tf.int32, name='input_ids'), TensorSpec(shape=(None, 384), dtype=tf.int32, name='attention_mask'), TensorSpec(shape=(None, 384), dtype=tf.int32, name='token_type_ids'), None, None, None, None, None, None, None, None, None, None, False), {})
    
    More specifically: Substructure "type=dict str={'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='input_ids/input_ids')}" is a sequence, while substructure "type=TensorSpec str=TensorSpec(shape=(None, 384), dtype=tf.int32, name='input_ids')" is not
    Entire first structure:
    (({'input_ids': .}, ., ., ., ., ., ., ., ., ., ., ., ., .), {})
    Entire second structure:
    ((., ., ., ., ., ., ., ., ., ., ., ., ., .), {})
    

    I have figured out a way to overcome this problem. Instead of saving the model using model.save or tf.keras.models.save_model(), try saving the model weights using model.save_weights('model_weight.h5') during the training process.

    At the prediction or testing phase, you need to create the model (architecture) manually, the same way you did in the training phase, and then load the weights to it.

    I try your mention, save_weights, create the model, and load_weights, but get this error:

    ValueError: Unable to load weights saved in HDF5 format into a subclassed Model which has not created its variables yet. Call the Model first, then load the weights.

    Similar, I build my model using transformers. In init function, I build a albert and load weight by from_pretrained()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions