1

When input the same image, in Google ViT model output.last_hidden_state is not equal to output.hidden_states[-1] ? I tried in Bert, the outputs are the same.

feature_extractor = ViTFeatureExtractor.from_pretrained('google/vit-base-patch16-224-in21k')

model = ViTModel.from_pretrained('google/vit-base-patch16-224-in21k')
inputs = feature_extractor(images=[image], return_tensors="pt")
outputs = model(pixel_values=inputs['pixel_values'], output_hidden_states=True)

vec1 = outputs.hidden_states[-1][0, 0, :]
vec2 = outputs.last_hidden_state[0, 0, :]

in my mind, vec1 should be the same as vec2. But the fact is they are not the same at all.

1 Answer 1

0

The difference is that the layernorm is applied to the last_hidden_state.

The following is an excerpt of the last 15 lines or so of ViTModel's forward method. For sequence_output, which is assigned to last_hidden_state, layernorm is applied to the output from the encoder.

sequence_output = encoder_outputs[0]
sequence_output = self.layernorm(sequence_output)
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None

if not return_dict:
    head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
    return head_outputs + encoder_outputs[1:]

return BaseModelOutputWithPooling(
    last_hidden_state=sequence_output,
    pooler_output=pooled_output,
    hidden_states=encoder_outputs.hidden_states,
    attentions=encoder_outputs.attentions,
)

If we apply layernorm to hidden_state[-1], we can confirm that the same value is obtained. Please refer to the notebook I made in Colab. vit_huggingface

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.