Repository: huggingface/transformers
Pull request: fix(utils): Make torch_compilable_check compatible with torch.export strict mode

### What does this PR do?

The following issue was identified and fixed in this PR:

→ **Reasoning:** The impact of this fix goes beyond `Mask2Former` and `DeformableDetr` and should fix any model that uses `torch_compilable_check`. Most users run models in eager where the fn works just fine; only `torch._check_with` only breaks during export tracing. `Mask2Former` already has test coverage for `torch.export.export()` functionality and it currently fails ([check CI for failing test_modeling_mask2former.py::Mask2FormerModelIntegrationTest::test_export](https://github.com/huggingface/transformers/actions/runs/22291700571/job/64480399485)), this should fix that.
→ I decided to pick one other pattern to prove that this fix generalizes to other models without regressions using `torch_compilable_check` and add test coverage for it. Picked `DeformableDetr` because it uses the same deformable attn pattern as in `Mask2Former` ([same torch_compilable_check() call in DeformableDetrMultiscaleDeformableAttention](https://github.com/huggingface/transformers/blob/main/src/transformers/models/deformable_detr/modeling_deformable_detr.py#L576-L579) as in [Mask2FormerPixelDecoderEncoderMultiscaleDeformableAttention](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mask2former/modeling_mask2former.py#L942-L945)) and didn't have coverage for an export test yet. Again for the test as well, I followed the canonical pattern from [Mask2FormerModelIntegrationTest::test_export](https://github.com/huggingface/transformers/blob/main/tests/models/mask2former/test_modeling_mask2former.py#L533-L555).
→ For more details on reproducing the bug and the output screenshots, please visit the linked issue!

Fixes #44265.

**Added DeformableDetr test before the fix (feel free to cross-check; this error is reproducible):**

<img width="600" height="600" alt="1" src="https://github.com/user-attachments/assets/57c58767-0c25-4b9b-8e6a-7a6aa8ea1b6d" /><br>

**Added DeformableDetr test after the fix (feel free to cross-check):**

<img width="600" height="200" alt="3" src="https://github.com/user-attachments/assets/7e42d5b6-49ed-4ecf-b8cb-961f7d081675" />

### Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [x] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [x] Did you fix any necessary existing tests?
- [x] Did you write any new necessary tests?

Changed files:
filename: src/transformers/utils/import_utils.py
patch: @@ -1444,7 +1444,9 @@ def msg_callable():
     if isinstance(cond, torch.Tensor):
         torch._check_tensor_all_with(error_type, cond, msg_callable)
     else:
-        torch._check_with(error_type, cond, msg_callable)
+        if not cond:
+            raise error_type(msg_callable())
+        torch._check(cond)
 
 
 @lru_cache

filename: tests/models/deformable_detr/test_modeling_deformable_detr.py
patch: @@ -19,6 +19,8 @@
 import unittest
 from functools import cached_property
 
+import pytest
+
 from transformers import DeformableDetrConfig, ResNetConfig, is_torch_available, is_vision_available
 from transformers.testing_utils import (
     require_timm,
@@ -741,3 +743,25 @@ def test_inference_object_detection_head_equivalence_cpu_accelerator(self):
             [[-9.9160, -4.2876, -6.4985], [-9.6945, -4.0855, -6.8031], [-10.0665, -5.8471, -7.7001]]
         )
         assert torch.allclose(cpu_outputs.logits[0, :3, :3], expected_logits, atol=2e-4)
+
+    @pytest.mark.torch_export_test
+    def test_export(self):
+        model = DeformableDetrForObjectDetection.from_pretrained("SenseTime/deformable-detr").to(torch_device).eval()
+        image_processor = self.default_image_processor
+        image = prepare_img()
+        inputs = image_processor(image, return_tensors="pt").to(torch_device)
+
+        exported_program = torch.export.export(
+            model,
+            args=(inputs["pixel_values"], inputs["pixel_mask"]),
+            strict=True,
+        )
+        with torch.no_grad():
+            eager_outputs = model(inputs["pixel_values"], inputs["pixel_mask"])
+            exported_outputs = exported_program.module().forward(inputs["pixel_values"], inputs["pixel_mask"])
+        self.assertEqual(eager_outputs.logits.shape, exported_outputs.logits.shape)
+        torch.testing.assert_close(eager_outputs.logits, exported_outputs.logits, rtol=TOLERANCE, atol=TOLERANCE)
+        self.assertEqual(eager_outputs.pred_boxes.shape, exported_outputs.pred_boxes.shape)
+        torch.testing.assert_close(
+            eager_outputs.pred_boxes, exported_outputs.pred_boxes, rtol=TOLERANCE, atol=TOLERANCE
+        )