Refactor attention for SigLIP based models (#36981)
* Update Siglip attention implementation * Update tests for Siglip * Remove one level of indentation * Update test to be more specific * Fixup * Idefics2 * Idefics3 * Emu3 * SmolVLM * Phi4 (just init small update) * Idefics2 (test fix) * Update siglip2 tests * Update eager * trigger * Clean up * Transfer inputs to device in test * Fixing test * Fixing test * Revert contiguous * Remove unused is_flash_attn_2_available * Move flaky to specific models
This commit is contained in:
committed by
GitHub
parent
24e311f42b
commit
3249c5dc15
@@ -3457,7 +3457,7 @@ class ModelTesterMixin:
|
||||
):
|
||||
# TODO: we shouldn't need to do this skip, i.e. the test would be composable from the model tester. CLIP-like
|
||||
# models have a custom mixin, which we detect to skip this test.
|
||||
if not any(".ModelTesterMixin" in str(base) for base in self.__class__.__bases__):
|
||||
if any(".CLIPModelTesterMixin" in str(base) for base in self.__class__.__bases__):
|
||||
self.skipTest(reason="CLIP-like models have a different `test_eager_matches_sdpa_inference`")
|
||||
|
||||
if not self.has_attentions:
|
||||
@@ -3549,206 +3549,213 @@ class ModelTesterMixin:
|
||||
model_eager = model_class.from_pretrained(**model_from_pretrained_kwargs, attn_implementation="eager")
|
||||
model_eager = model_eager.eval().to(torch_device, dtype=torch_dtype)
|
||||
|
||||
set_model_for_less_flaky_test(model_eager)
|
||||
set_model_for_less_flaky_test(model_sdpa)
|
||||
set_model_for_less_flaky_test(model_eager)
|
||||
set_model_for_less_flaky_test(model_sdpa)
|
||||
|
||||
can_output_attn = "output_attentions" in inspect.signature(model_sdpa.forward).parameters
|
||||
if not (self.has_attentions and can_output_attn) and output_attentions:
|
||||
self.skipTest(reason="Model does not support output_attentions")
|
||||
can_output_attn = "output_attentions" in inspect.signature(model_sdpa.forward).parameters
|
||||
if not (self.has_attentions and can_output_attn) and output_attentions:
|
||||
self.skipTest(reason="Model does not support output_attentions")
|
||||
|
||||
# TODO: if we can also check with `batch_size=1` without being flaky?
|
||||
for batch_size in [7]:
|
||||
# musicgen decoder models; TODO: find better abstraction
|
||||
if hasattr(self.model_tester, "num_codebooks") and not hasattr(model_eager, "text_encoder"):
|
||||
# TODO: if we can also check with `batch_size=1` without being flaky?
|
||||
for batch_size in [7]:
|
||||
# musicgen decoder models; TODO: find better abstraction
|
||||
if hasattr(self.model_tester, "num_codebooks") and not hasattr(model_eager, "text_encoder"):
|
||||
input_data_batch_size = batch_size * self.model_tester.num_codebooks
|
||||
else:
|
||||
input_data_batch_size = batch_size
|
||||
|
||||
processed_inputs = {}
|
||||
processed_inputs[model.main_input_name] = inputs_dict[model.main_input_name]
|
||||
|
||||
for key in getattr(self, "additional_model_inputs", []):
|
||||
processed_inputs[key] = inputs_dict[key]
|
||||
|
||||
for key, value in processed_inputs.items():
|
||||
if torch.is_floating_point(value):
|
||||
value = value.to(torch_dtype)
|
||||
|
||||
# extend value to have at least `input_data_batch_size` elements
|
||||
if value.shape[0] < input_data_batch_size:
|
||||
size = (input_data_batch_size - value.shape[0], *value.shape[1:])
|
||||
if torch.is_floating_point(value):
|
||||
extension = torch.rand(size=size, dtype=value.dtype, device=torch_device)
|
||||
else:
|
||||
extension = torch.randint(high=5, size=size, dtype=value.dtype, device=torch_device)
|
||||
value = torch.cat((value, extension), dim=0).to(torch_device)
|
||||
|
||||
processed_inputs[key] = value[:input_data_batch_size]
|
||||
|
||||
if not use_attention_mask:
|
||||
dummy_attention_mask = None
|
||||
else:
|
||||
dummy_attention_mask = inputs_dict.get("attention_mask", None)
|
||||
if dummy_attention_mask is None:
|
||||
if is_encoder_decoder:
|
||||
seqlen = inputs_dict.get(
|
||||
"decoder_input_ids", processed_inputs[model.main_input_name]
|
||||
).shape[-1]
|
||||
else:
|
||||
seqlen = processed_inputs[model.main_input_name].shape[-1]
|
||||
dummy_attention_mask = torch.ones(batch_size, seqlen).to(torch.int64).to(torch_device)
|
||||
|
||||
# extend dummy_attention_mask to have at least `batch_size` elements
|
||||
if dummy_attention_mask.shape[0] < batch_size:
|
||||
size = (batch_size - dummy_attention_mask.shape[0], *dummy_attention_mask.shape[1:])
|
||||
extension = torch.ones(size=size, dtype=dummy_attention_mask.dtype, device=torch_device)
|
||||
dummy_attention_mask = torch.cat((dummy_attention_mask, extension), dim=0)
|
||||
|
||||
dummy_attention_mask = dummy_attention_mask[:batch_size].to(torch_device)
|
||||
|
||||
dummy_attention_mask[:] = 1
|
||||
if padding_side == "left":
|
||||
dummy_attention_mask[-1, :2] = 0
|
||||
dummy_attention_mask[-1, 2:] = 1
|
||||
elif padding_side == "right":
|
||||
dummy_attention_mask[-1, -2:] = 0
|
||||
dummy_attention_mask[-1, :-2] = 1
|
||||
|
||||
if is_encoder_decoder:
|
||||
# musicgen encoder-decoder models; TODO: find better abstraction
|
||||
if hasattr(self.model_tester, "num_codebooks"):
|
||||
input_data_batch_size = batch_size * self.model_tester.num_codebooks
|
||||
else:
|
||||
input_data_batch_size = batch_size
|
||||
|
||||
dummy_input = inputs_dict[model.main_input_name]
|
||||
decoder_input_ids = inputs_dict.get("decoder_input_ids", processed_inputs[model.main_input_name])
|
||||
decoder_input_ids = decoder_input_ids[:input_data_batch_size]
|
||||
if decoder_input_ids.shape[0] != input_data_batch_size:
|
||||
extension = torch.ones(
|
||||
input_data_batch_size - decoder_input_ids.shape[0],
|
||||
*decoder_input_ids.shape[1:],
|
||||
dtype=decoder_input_ids.dtype,
|
||||
device=torch_device,
|
||||
)
|
||||
decoder_input_ids = torch.cat((decoder_input_ids, extension), dim=0)
|
||||
decoder_input_ids = decoder_input_ids.to(torch_device)
|
||||
|
||||
if dummy_input.dtype in [torch.float32, torch.bfloat16, torch.float16]:
|
||||
dummy_input = dummy_input.to(torch_dtype)
|
||||
|
||||
dummy_input = dummy_input[:input_data_batch_size]
|
||||
if dummy_input.shape[0] != input_data_batch_size:
|
||||
if dummy_input.dtype in [torch.float32, torch.bfloat16, torch.float16]:
|
||||
extension = torch.rand(
|
||||
input_data_batch_size - dummy_input.shape[0],
|
||||
*dummy_input.shape[1:],
|
||||
dtype=torch_dtype,
|
||||
device=torch_device,
|
||||
)
|
||||
dummy_input = torch.cat((dummy_input, extension), dim=0).to(torch_device)
|
||||
else:
|
||||
extension = torch.randint(
|
||||
high=5,
|
||||
size=(input_data_batch_size - dummy_input.shape[0], *dummy_input.shape[1:]),
|
||||
dtype=dummy_input.dtype,
|
||||
device=torch_device,
|
||||
)
|
||||
dummy_input = torch.cat((dummy_input, extension), dim=0).to(torch_device)
|
||||
|
||||
if not use_attention_mask:
|
||||
dummy_attention_mask = None
|
||||
else:
|
||||
dummy_attention_mask = inputs_dict.get("attention_mask", None)
|
||||
if dummy_attention_mask is None:
|
||||
if is_encoder_decoder:
|
||||
seqlen = inputs_dict.get("decoder_input_ids", dummy_input).shape[-1]
|
||||
else:
|
||||
seqlen = dummy_input.shape[-1]
|
||||
dummy_attention_mask = torch.ones(batch_size, seqlen).to(torch.int64).to(torch_device)
|
||||
|
||||
dummy_attention_mask = dummy_attention_mask[:batch_size]
|
||||
if dummy_attention_mask.shape[0] != batch_size:
|
||||
extension = torch.ones(
|
||||
batch_size - dummy_attention_mask.shape[0],
|
||||
*dummy_attention_mask.shape[1:],
|
||||
dtype=dummy_attention_mask.dtype,
|
||||
device=torch_device,
|
||||
)
|
||||
dummy_attention_mask = torch.cat((dummy_attention_mask, extension), dim=0)
|
||||
dummy_attention_mask = dummy_attention_mask.to(torch_device)
|
||||
|
||||
dummy_attention_mask[:] = 1
|
||||
if padding_side == "left":
|
||||
dummy_attention_mask[-1, :2] = 0
|
||||
dummy_attention_mask[-1, 2:] = 1
|
||||
elif padding_side == "right":
|
||||
dummy_attention_mask[-1, -2:] = 0
|
||||
dummy_attention_mask[-1, :-2] = 1
|
||||
|
||||
if is_encoder_decoder:
|
||||
# musicgen encoder-decoder models; TODO: find better abstraction
|
||||
if hasattr(self.model_tester, "num_codebooks"):
|
||||
input_data_batch_size = batch_size * self.model_tester.num_codebooks
|
||||
else:
|
||||
input_data_batch_size = batch_size
|
||||
|
||||
decoder_input_ids = inputs_dict.get("decoder_input_ids", dummy_input)[:input_data_batch_size]
|
||||
if decoder_input_ids.shape[0] != input_data_batch_size:
|
||||
extension = torch.ones(
|
||||
input_data_batch_size - decoder_input_ids.shape[0],
|
||||
*decoder_input_ids.shape[1:],
|
||||
dtype=decoder_input_ids.dtype,
|
||||
device=torch_device,
|
||||
)
|
||||
decoder_input_ids = torch.cat((decoder_input_ids, extension), dim=0)
|
||||
decoder_input_ids = decoder_input_ids.to(torch_device)
|
||||
|
||||
# TODO: never an `attention_mask` arg here?
|
||||
processed_inputs = {
|
||||
model.main_input_name: dummy_input,
|
||||
# TODO: never an `attention_mask` arg here?
|
||||
processed_inputs.update(
|
||||
{
|
||||
"decoder_input_ids": decoder_input_ids,
|
||||
"decoder_attention_mask": dummy_attention_mask,
|
||||
"output_hidden_states": True,
|
||||
}
|
||||
else:
|
||||
processed_inputs = {
|
||||
model.main_input_name: dummy_input,
|
||||
)
|
||||
else:
|
||||
processed_inputs.update(
|
||||
{
|
||||
"output_hidden_states": True,
|
||||
}
|
||||
)
|
||||
|
||||
# Otherwise fails for e.g. WhisperEncoderModel
|
||||
if "attention_mask" in inspect.signature(model_eager.forward).parameters:
|
||||
processed_inputs["attention_mask"] = dummy_attention_mask
|
||||
# Otherwise fails for e.g. WhisperEncoderModel
|
||||
if "attention_mask" in inspect.signature(model_eager.forward).parameters:
|
||||
processed_inputs["attention_mask"] = dummy_attention_mask
|
||||
|
||||
if (
|
||||
self.has_attentions
|
||||
and "output_attentions" in inspect.signature(model_sdpa.forward).parameters
|
||||
):
|
||||
processed_inputs["output_attentions"] = output_attentions
|
||||
if "bool_masked_pos" in inspect.signature(model_eager.forward).parameters:
|
||||
dummy_mask = torch.ones((self.model_tester.num_masks,))
|
||||
if self.has_attentions and "output_attentions" in inspect.signature(model_sdpa.forward).parameters:
|
||||
processed_inputs["output_attentions"] = output_attentions
|
||||
if "bool_masked_pos" in inspect.signature(model_eager.forward).parameters:
|
||||
dummy_mask = torch.ones((self.model_tester.num_masks,))
|
||||
|
||||
# In case of additional token (like class) we define a custom `mask_length`
|
||||
if hasattr(self.model_tester, "mask_length"):
|
||||
mask_length = self.model_tester.mask_length - dummy_mask.size(0)
|
||||
else:
|
||||
mask_length = self.model_tester.seq_length - dummy_mask.size(0)
|
||||
dummy_mask = torch.cat([dummy_mask, torch.zeros(mask_length)])
|
||||
dummy_bool_masked_pos = dummy_mask.expand(batch_size, -1).bool()
|
||||
processed_inputs["bool_masked_pos"] = dummy_bool_masked_pos.to(torch_device)
|
||||
|
||||
if "noise" in inspect.signature(model_eager.forward).parameters:
|
||||
np.random.seed(2)
|
||||
num_patches = int((self.model_tester.image_size // self.model_tester.patch_size) ** 2)
|
||||
noise = np.random.uniform(size=(batch_size, num_patches))
|
||||
processed_inputs["noise"] = torch.from_numpy(noise)
|
||||
|
||||
# TODO: test gradients as well (& for FA2 as well!)
|
||||
with torch.no_grad():
|
||||
with sdpa_kernel(
|
||||
enable_flash=enable_kernels,
|
||||
enable_math=True,
|
||||
enable_mem_efficient=enable_kernels,
|
||||
):
|
||||
prepared_inputs = self._prepare_for_class(processed_inputs, model_class)
|
||||
outputs_eager = model_eager(**prepared_inputs)
|
||||
outputs_sdpa = model_sdpa(**prepared_inputs)
|
||||
|
||||
# TODO: rename logits -> hidden_states
|
||||
if hasattr(outputs_eager, "vision_hidden_states"):
|
||||
logits_eager = outputs_eager.vision_hidden_states[-1]
|
||||
logits_sdpa = outputs_sdpa.vision_hidden_states[-1]
|
||||
elif hasattr(outputs_eager, "audio_values"):
|
||||
logits_eager = outputs_eager.audio_values
|
||||
logits_sdpa = outputs_sdpa.audio_values
|
||||
# In case of additional token (like class) we define a custom `mask_length`
|
||||
if hasattr(self.model_tester, "mask_length"):
|
||||
mask_length = self.model_tester.mask_length - dummy_mask.size(0)
|
||||
else:
|
||||
logits_eager = (
|
||||
outputs_eager.decoder_hidden_states[-1]
|
||||
if hasattr(outputs_eager, "decoder_hidden_states")
|
||||
else outputs_eager.hidden_states[-1]
|
||||
)
|
||||
logits_sdpa = (
|
||||
outputs_sdpa.decoder_hidden_states[-1]
|
||||
if hasattr(outputs_sdpa, "decoder_hidden_states")
|
||||
else outputs_sdpa.hidden_states[-1]
|
||||
)
|
||||
mask_length = self.model_tester.seq_length - dummy_mask.size(0)
|
||||
dummy_mask = torch.cat([dummy_mask, torch.zeros(mask_length)])
|
||||
dummy_bool_masked_pos = dummy_mask.expand(batch_size, -1).bool()
|
||||
processed_inputs["bool_masked_pos"] = dummy_bool_masked_pos.to(torch_device)
|
||||
|
||||
if torch_device in ["cpu", "cuda"]:
|
||||
atol = atols[torch_device, enable_kernels, torch_dtype]
|
||||
rtol = rtols[torch_device, enable_kernels, torch_dtype]
|
||||
elif torch_device == "xpu":
|
||||
# As of PyTorch 2.5 XPU backend supports only torch.nn.attention.SDPBackend.MATH
|
||||
# which is implemented on PyTorch level using aten operators and is
|
||||
# device agnostic with respect to implementation of each aten operator.
|
||||
atol = atols["cuda", False, torch_dtype]
|
||||
rtol = rtols["cuda", False, torch_dtype]
|
||||
else:
|
||||
atol = 1e-7
|
||||
rtol = 1e-4
|
||||
if "noise" in inspect.signature(model_eager.forward).parameters:
|
||||
np.random.seed(2)
|
||||
num_patches = int((self.model_tester.image_size // self.model_tester.patch_size) ** 2)
|
||||
noise = np.random.uniform(size=(batch_size, num_patches))
|
||||
processed_inputs["noise"] = torch.from_numpy(noise)
|
||||
|
||||
# Masked tokens output slightly deviates - we don't mind that.
|
||||
if use_attention_mask:
|
||||
_logits_sdpa = torch.zeros_like(input=logits_sdpa)
|
||||
_logits_eager = torch.zeros_like(input=logits_eager)
|
||||
# TODO: test gradients as well (& for FA2 as well!)
|
||||
with torch.no_grad():
|
||||
with sdpa_kernel(
|
||||
enable_flash=enable_kernels,
|
||||
enable_math=True,
|
||||
enable_mem_efficient=enable_kernels,
|
||||
):
|
||||
prepared_inputs = self._prepare_for_class(processed_inputs, model_class)
|
||||
prepared_inputs = {
|
||||
k: v.to(torch_device) if isinstance(v, torch.Tensor) else v
|
||||
for k, v in prepared_inputs.items()
|
||||
}
|
||||
outputs_eager = model_eager(**prepared_inputs)
|
||||
outputs_sdpa = model_sdpa(**prepared_inputs)
|
||||
|
||||
_logits_sdpa[:-1] = logits_sdpa[:-1]
|
||||
_logits_eager[:-1] = logits_eager[:-1]
|
||||
if "logits_per_text" in outputs_eager:
|
||||
key = "logits_per_text"
|
||||
elif "vision_hidden_states" in outputs_eager:
|
||||
key = "vision_hidden_states"
|
||||
elif "audio_values" in outputs_eager:
|
||||
key = "audio_values"
|
||||
elif "decoder_hidden_states" in outputs_eager:
|
||||
key = "decoder_hidden_states"
|
||||
elif "logits" in outputs_eager and "Classification" in model_class.__name__:
|
||||
key = "logits"
|
||||
else:
|
||||
key = "hidden_states"
|
||||
|
||||
if padding_side == "left":
|
||||
_logits_sdpa[-1:, 2:] = logits_sdpa[-1:, 2:]
|
||||
_logits_eager[-1:, 2:] = logits_eager[-1:, 2:]
|
||||
# TODO: rename logits -> hidden_states
|
||||
logits_eager = outputs_eager[key]
|
||||
logits_sdpa = outputs_sdpa[key]
|
||||
|
||||
elif padding_side == "right":
|
||||
_logits_sdpa[-1:, 2:] = logits_sdpa[-1:, :-2]
|
||||
_logits_eager[-1:, 2:] = logits_eager[-1:, :-2]
|
||||
if key in ["vision_hidden_states", "decoder_hidden_states", "hidden_states"]:
|
||||
logits_eager = logits_eager[-1]
|
||||
logits_sdpa = logits_sdpa[-1]
|
||||
|
||||
logits_sdpa = _logits_sdpa
|
||||
logits_eager = _logits_eager
|
||||
if key == "logits_per_text":
|
||||
nan_mask = torch.isnan(logits_eager)
|
||||
logits_eager[nan_mask] = 0
|
||||
logits_sdpa[nan_mask] = 0
|
||||
|
||||
results = [
|
||||
torch.allclose(_logits_sdpa, _logits_eager, atol=atol, rtol=rtol)
|
||||
for (_logits_sdpa, _logits_eager) in zip(logits_sdpa, logits_eager)
|
||||
]
|
||||
# If 80% batch elements have matched results, it's fine
|
||||
if np.mean(results) < 0.8:
|
||||
mean_relative_diff = ((logits_sdpa - logits_eager).abs() / (logits_eager.abs() + 1e-12)).mean()
|
||||
raise ValueError(
|
||||
f"mean relative difference: {mean_relative_diff:.3e}, torch atol = {atol}, torch rtol = "
|
||||
f"{rtol}"
|
||||
)
|
||||
if torch_device in ["cpu", "cuda"]:
|
||||
atol = atols[torch_device, enable_kernels, torch_dtype]
|
||||
rtol = rtols[torch_device, enable_kernels, torch_dtype]
|
||||
elif torch_device == "xpu":
|
||||
# As of PyTorch 2.5 XPU backend supports only torch.nn.attention.SDPBackend.MATH
|
||||
# which is implemented on PyTorch level using aten operators and is
|
||||
# device agnostic with respect to implementation of each aten operator.
|
||||
atol = atols["cuda", False, torch_dtype]
|
||||
rtol = rtols["cuda", False, torch_dtype]
|
||||
else:
|
||||
atol = 1e-7
|
||||
rtol = 1e-4
|
||||
|
||||
# Masked tokens output slightly deviates - we don't mind that.
|
||||
if use_attention_mask:
|
||||
_logits_sdpa = torch.zeros_like(input=logits_sdpa)
|
||||
_logits_eager = torch.zeros_like(input=logits_eager)
|
||||
|
||||
_logits_sdpa[:-1] = logits_sdpa[:-1]
|
||||
_logits_eager[:-1] = logits_eager[:-1]
|
||||
|
||||
if padding_side == "left":
|
||||
_logits_sdpa[-1:, 2:] = logits_sdpa[-1:, 2:]
|
||||
_logits_eager[-1:, 2:] = logits_eager[-1:, 2:]
|
||||
|
||||
elif padding_side == "right":
|
||||
_logits_sdpa[-1:, 2:] = logits_sdpa[-1:, :-2]
|
||||
_logits_eager[-1:, 2:] = logits_eager[-1:, :-2]
|
||||
|
||||
logits_sdpa = _logits_sdpa
|
||||
logits_eager = _logits_eager
|
||||
|
||||
results = [
|
||||
torch.allclose(_logits_sdpa, _logits_eager, atol=atol, rtol=rtol)
|
||||
for (_logits_sdpa, _logits_eager) in zip(logits_sdpa, logits_eager)
|
||||
]
|
||||
# If 80% batch elements have matched results, it's fine
|
||||
if np.mean(results) < 0.8:
|
||||
mean_relative_diff = ((logits_sdpa - logits_eager).abs() / (logits_eager.abs() + 1e-12)).mean()
|
||||
raise ValueError(
|
||||
f"mean relative difference for {key}: {mean_relative_diff:.3e}, torch atol = {atol}, torch rtol = "
|
||||
f"{rtol}"
|
||||
)
|
||||
|
||||
@require_torch_sdpa
|
||||
@require_torch_gpu
|
||||
|
||||
Reference in New Issue
Block a user