-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtest_predict.py
More file actions
2016 lines (1642 loc) · 96.2 KB
/
Copy pathtest_predict.py
File metadata and controls
2016 lines (1642 loc) · 96.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ------------------------------------------------------------------------
# RF-DETR
# Copyright (c) 2025 Roboflow. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
import io
import warnings
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock, patch
import numpy as np
import PIL.Image
import pytest
import requests
import supervision as sv
import torch
import torchvision.transforms.functional as F # noqa: N812
import rfdetr.detr as detr_module
from rfdetr import RFDETRNano, RFDETRSegNano
from rfdetr.detr import RFDETR
from rfdetr.utilities.keypoints import precision_cholesky_to_pixel_covariance
from tests._online import is_online
from .helpers import _DummyModel, _DummyRFDETR
_HTTP_IMAGE_URL = "http://images.cocodataset.org/val2017/000000397133.jpg"
_HTTP_HOST = "images.cocodataset.org"
_HTTP_PORT = 80
class TestPredictReturnTypes:
"""``RFDETR.predict()`` API contract tests using synthetic images.
Quality is not assessed here — see ``tests/benchmarks/test_inference_coco.py``.
"""
def test_detection_returns_sv_detections(self) -> None:
"""Detection model returns a list of ``sv.Detections``."""
img = PIL.Image.new("RGB", (640, 640), color=(128, 128, 128))
model = RFDETRNano(pretrain_weights=None)
detections = model.predict([img, img], threshold=0.3)
assert isinstance(detections, list), "predict() must return a list for multiple inputs"
assert all(isinstance(d, sv.Detections) for d in detections), "Each result must be sv.Detections"
def test_segmentation_returns_sv_detections_with_masks(self) -> None:
"""Segmentation model returns ``sv.Detections`` with the mask field always set."""
img = PIL.Image.new("RGB", (640, 640), color=(128, 128, 128))
model = RFDETRSegNano(pretrain_weights=None)
detections = model.predict([img, img], threshold=0.3)
assert isinstance(detections, list), "predict() must return a list for multiple inputs"
assert all(isinstance(d, sv.Detections) for d in detections), "Each result must be sv.Detections"
assert all(d.mask is not None for d in detections), (
"Segmentation predict() must always set the mask field, even when no objects are detected"
)
def test_keypoint_single_and_batch_return_sv_keypoints(self) -> None:
"""Keypoint model returns one KeyPoints for one image and list[KeyPoints] for multiple images."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
model.model = _DummyModel(labels=[0, 1], include_keypoints=True)
single = model.predict(img)
batch = model.predict([img, img])
assert isinstance(single, sv.KeyPoints)
assert isinstance(batch, list)
assert all(isinstance(result, sv.KeyPoints) for result in batch)
class TestPredictScoreThresholdEquivalence:
"""The mask pre-filter perf path must not change ``predict()``'s final output."""
def test_mask_prefilter_output_equivalent_at_predict_boundary(self) -> None:
"""``predict()`` masks/boxes/scores must be bit-identical whether the mask pre-filter runs or not.
The optimization forwards ``predict(threshold=...)`` into ``PostProcess`` so below-threshold masks skip
upsampling. Disabling the pre-filter (``score_threshold=None``) makes ``PostProcess`` upsample every mask and
lets ``predict()``'s own downstream filter drop them instead. The two paths must produce the same
``Detections``, proving the pre-filter drops only rows ``predict()`` itself discards — the equivalence that the
unit test at ``_postprocess_masks`` level asserts, now verified end-to-end through the real ``predict()`` path.
"""
img = PIL.Image.new("RGB", (640, 640), color=(128, 128, 128))
model = RFDETRSegNano(pretrain_weights=None)
threshold = 0.3
optimized = model.predict(img, threshold=threshold)
real_postprocess = model.model.postprocess
def postprocess_without_prefilter(predictions, target_sizes, score_threshold=None):
return real_postprocess(predictions, target_sizes, score_threshold=None)
model.model.postprocess = postprocess_without_prefilter
baseline = model.predict(img, threshold=threshold)
np.testing.assert_array_equal(optimized.xyxy, baseline.xyxy)
np.testing.assert_array_equal(optimized.confidence, baseline.confidence)
np.testing.assert_array_equal(optimized.class_id, baseline.class_id)
np.testing.assert_array_equal(optimized.mask, baseline.mask)
class _TupleOutputModelContext:
"""Model context whose forward returns a 3-tuple, mirroring ``forward_export()`` after ``inference()``.
Regression fixture for GitHub #1208: ``predict()`` mislabels the tuple's third element as ``pred_masks`` instead of
``pred_keypoints`` because it reads a nonexistent ``model.model_config`` attribute instead of ``model.args``.
"""
def __init__(self) -> None:
self.device = torch.device("cpu")
self.resolution = 28
self.class_names = ["object"]
self.args = SimpleNamespace(use_grouppose_keypoints=True, num_keypoints_per_class=[17])
self.model = torch.nn.Identity()
self.inference_model = self._forward
self.captured_predictions: dict[str, torch.Tensor] | None = None
self.captured_score_threshold: float | None = None
def _forward(self, batch_tensor: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
batch = batch_tensor.shape[0]
boxes = torch.tensor([[[0.5, 0.5, 0.2, 0.2]]] * batch)
logits = torch.full((batch, 1, 1), 10.0)
keypoints = torch.full((batch, 1, 17, 3), 0.5)
return boxes, logits, keypoints
def postprocess(
self,
predictions: dict[str, torch.Tensor],
target_sizes: torch.Tensor,
score_threshold: float | None = None,
) -> list[dict[str, torch.Tensor]]:
self.captured_predictions = predictions
self.captured_score_threshold = score_threshold
batch = target_sizes.shape[0]
results = []
for _ in range(batch):
result: dict[str, torch.Tensor] = {
"scores": torch.tensor([0.9]),
"labels": torch.tensor([0]),
"boxes": torch.tensor([[0.0, 0.0, 1.0, 1.0]]),
}
if "pred_keypoints" in predictions:
result["keypoints"] = torch.full((1, 17, 3), 0.5)
results.append(result)
return results
def _make_optimized_keypoint_model() -> tuple[RFDETR, _TupleOutputModelContext]:
"""Build a ``_DummyRFDETR`` wired to look like it already ran ``inference()``.
Examples:
>>> model, stub = _make_optimized_keypoint_model()
>>> model._is_optimized_for_inference
True
>>> isinstance(stub, _TupleOutputModelContext)
True
"""
model = _DummyRFDETR()
stub = _TupleOutputModelContext()
model.model = stub
model._is_optimized_for_inference = True
model._optimized_resolution = stub.resolution
model._optimized_has_been_compiled = False
model._optimized_dtype = torch.float32
return model, stub
class TestPredictOptimizedInferenceKeypoints:
"""Regression tests for GitHub #1208: inference() breaks keypoint predict()."""
def test_tuple_output_labels_third_slot_as_keypoints_not_masks(self) -> None:
"""The 3rd tuple slot must be labeled pred_keypoints, not pred_masks, when use_grouppose_keypoints=True."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model, stub = _make_optimized_keypoint_model()
model.predict(img)
assert stub.captured_predictions is not None
assert "pred_keypoints" in stub.captured_predictions
assert "pred_masks" not in stub.captured_predictions
def test_optimized_keypoint_model_predict_returns_sv_keypoints(self) -> None:
"""Predict() must return sv.KeyPoints, not sv.Detections, for an optimized keypoint model."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model, _stub = _make_optimized_keypoint_model()
result = model.predict(img)
assert isinstance(result, sv.KeyPoints), (
f"expected sv.KeyPoints for optimized keypoint model, got {type(result)}"
)
def test_predict_forwards_threshold_to_postprocess(self) -> None:
"""Predict must pass its public threshold to post-processing before mask work begins."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model, stub = _make_optimized_keypoint_model()
model.predict(img, threshold=0.31)
assert stub.captured_score_threshold == 0.31
def test_predict_accepts_image_url() -> None:
if not is_online(_HTTP_HOST, _HTTP_PORT):
pytest.skip("Offline environment, skipping HTTP predict URL test.")
model = _DummyRFDETR()
detections = model.predict(_HTTP_IMAGE_URL)
assert isinstance(detections, sv.Detections)
assert detections.xyxy.shape == (1, 4)
class TestPredictSourceData:
"""Verify ``predict()`` source metadata behavior."""
def test_source_image_included_by_default(self) -> None:
"""source_image remains included by default for API compatibility."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
detections = model.predict(img)
assert "source_image" in detections.metadata
assert isinstance(detections.metadata["source_image"], np.ndarray)
assert detections.metadata["source_image"].shape == (48, 64, 3)
assert np.array_equal(detections.data["source_shape"], np.array([[48, 64]]))
def test_source_image_included_by_default_tensor(self) -> None:
"""Tensor input keeps source_image by default for API compatibility."""
tensor = torch.rand(3, 48, 64)
model = _DummyRFDETR()
detections = model.predict(tensor)
assert "source_image" in detections.metadata
assert isinstance(detections.metadata["source_image"], np.ndarray)
assert detections.metadata["source_image"].dtype == np.uint8
assert detections.metadata["source_image"].shape == (48, 64, 3)
assert np.array_equal(detections.data["source_shape"], np.array([[48, 64]]))
def test_source_image_can_be_disabled(self) -> None:
"""include_source_image=False omits source_image for memory-sensitive paths."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
detections = model.predict(img, include_source_image=False)
assert "source_image" not in detections.metadata
assert np.array_equal(detections.data["source_shape"], np.array([[48, 64]]))
def test_source_image_from_pil(self) -> None:
"""PIL input stores the original image as a numpy array."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
detections = model.predict(img, include_source_image=True)
assert "source_image" in detections.metadata
assert isinstance(detections.metadata["source_image"], np.ndarray)
assert detections.metadata["source_image"].shape == (48, 64, 3)
def test_source_shape_from_pil(self) -> None:
"""PIL input stores source_shape as a per-detection numpy array."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
detections = model.predict(img)
assert "source_shape" in detections.data
assert isinstance(detections.data["source_shape"], np.ndarray)
assert detections.data["source_shape"].dtype == np.int64
assert detections.data["source_shape"].shape == (len(detections), 2)
assert np.array_equal(detections.data["source_shape"][0], [48, 64])
def test_source_image_from_tensor(self) -> None:
"""Tensor input stores the original image as a uint8 numpy array."""
tensor = torch.rand(3, 48, 64)
model = _DummyRFDETR()
detections = model.predict(tensor, include_source_image=True)
assert "source_image" in detections.metadata
assert isinstance(detections.metadata["source_image"], np.ndarray)
assert detections.metadata["source_image"].dtype == np.uint8
assert detections.metadata["source_image"].shape == (48, 64, 3)
@pytest.mark.gpu
@pytest.mark.parametrize(
("dtype", "shape", "expected_transfer_dtype"),
[
pytest.param(torch.float16, (3, 48, 64), torch.uint8, id="float16"),
pytest.param(torch.float32, (3, 48, 64), torch.uint8, id="float32"),
pytest.param(torch.float64, (3, 48, 64), torch.uint8, id="float64"),
pytest.param(torch.float32, (3, 1, 64), torch.float32, id="degenerate_height"),
pytest.param(torch.float32, (3, 48, 1), torch.float32, id="degenerate_width"),
],
)
def test_cuda_source_image_transfers_exact_bytes(
self,
dtype: torch.dtype,
shape: tuple[int, int, int],
expected_transfer_dtype: torch.dtype,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The default public path transfers uint8 storage without changing source metadata."""
values = torch.rand(shape, generator=torch.Generator().manual_seed(20260821))
boundary_count = min(256, values.numel())
values.view(-1)[:boundary_count] = torch.arange(boundary_count, dtype=torch.float32) / 255
tensor = values.to(device="cuda", dtype=dtype)
expected = (tensor.permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)
expected_source_shape = (shape[1], shape[2], shape[0])
transferred_dtypes: list[torch.dtype] = []
original_cpu = torch.Tensor.cpu
def record_source_transfer(image: torch.Tensor) -> torch.Tensor:
"""Record the source-image transfer dtype before delegating to PyTorch.
Examples:
This closure requires CUDA and is covered by the enclosing GPU test:
>>> record_source_transfer(torch.zeros(3, 48, 64, device="cuda")) # doctest: +SKIP
"""
if image.device.type == "cuda" and tuple(image.shape) == expected_source_shape:
transferred_dtypes.append(image.dtype)
return original_cpu(image)
monkeypatch.setattr(torch.Tensor, "cpu", record_source_transfer)
detections = _DummyRFDETR().predict(tensor)
actual = detections.metadata["source_image"]
assert transferred_dtypes == [expected_transfer_dtype]
assert actual.shape == expected.shape
assert actual.dtype == expected.dtype
assert actual.strides == expected.strides
assert actual.flags.owndata == expected.flags.owndata
assert actual.flags.writeable == expected.flags.writeable
assert actual.tobytes() == expected.tobytes()
@pytest.mark.gpu
def test_cuda_source_image_transfers_exact_bytes_strided_input(self) -> None:
"""The fast path matches the previous NumPy path byte-for-byte for a non-contiguous CUDA tensor."""
values = torch.rand((3, 96, 128), generator=torch.Generator().manual_seed(20260821))
tensor = values.to(device="cuda", dtype=torch.float32)[:, ::2, ::2]
assert not tensor.is_contiguous()
expected = (tensor.permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)
detections = _DummyRFDETR().predict(tensor)
actual = detections.metadata["source_image"]
assert actual.shape == expected.shape
assert actual.dtype == expected.dtype
assert actual.strides == expected.strides
assert actual.flags.owndata == expected.flags.owndata
assert actual.flags.writeable == expected.flags.writeable
assert actual.tobytes() == expected.tobytes()
@pytest.mark.gpu
def test_cuda_source_image_nan_conversion_emits_no_warning(self) -> None:
"""The on-device cast does not emit NumPy's incidental invalid-cast RuntimeWarning that the old CPU cast did."""
tensor = torch.full((3, 4, 5), torch.nan, device="cuda", dtype=torch.float32)
expected = np.zeros((4, 5, 3), dtype=np.uint8)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
detections = _DummyRFDETR().predict(tensor)
assert caught == []
assert "source_image" in detections.metadata
actual = detections.metadata["source_image"]
assert actual.shape == expected.shape
assert actual.dtype == expected.dtype
assert actual.tobytes() == expected.tobytes()
def test_tensor_with_negative_values_raises(self) -> None:
"""Tensor with negative pixel values raises ValueError."""
tensor = torch.full((3, 48, 64), -0.1)
model = _DummyRFDETR()
with pytest.raises(ValueError, match="below 0"):
model.predict(tensor)
def test_source_image_batch(self) -> None:
"""Batch predict stores a source_image per detection."""
img1 = PIL.Image.new("RGB", (64, 48), color=(100, 100, 100))
img2 = PIL.Image.new("RGB", (32, 24), color=(200, 200, 200))
model = _DummyRFDETR()
detections_list = model.predict([img1, img2], include_source_image=True)
assert isinstance(detections_list, list)
assert detections_list[0].metadata["source_image"].shape == (48, 64, 3)
assert detections_list[1].metadata["source_image"].shape == (24, 32, 3)
assert np.array_equal(detections_list[0].data["source_shape"], np.array([[48, 64]]))
assert np.array_equal(detections_list[1].data["source_shape"], np.array([[24, 32]]))
def test_source_shape_survives_detections_iteration(self) -> None:
"""Iterating sv.Detections must not raise TypeError and must yield correct values.
Regression test for https://github.com/roboflow/rf-detr/issues/963. supervision's Detections.__iter__ calls
get_data_item() on every data value, which requires array-like types — storing source_shape as a Python tuple
raised TypeError: Unsupported data type for key 'source_shape': <class 'tuple'>.
"""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
detections = model.predict(img)
# sv.Detections.__iter__ yields (xyxy, mask, confidence, class_id, tracker_id, data)
iterated = list(detections)
assert len(iterated) == len(detections)
# Each iterated element's data dict must contain a 1-D [h, w] array
for det_tuple in iterated:
data = det_tuple[-1]
assert np.array_equal(data["source_shape"], [48, 64])
def test_source_image_survives_boolean_index(self) -> None:
"""Boolean-mask indexing must not raise IndexError when source_image is present.
Regression test for https://github.com/roboflow/rf-detr/issues/968. source_image was stored as (H, W, C) in
detections.data; supervision's __getitem__ tried to index it with a per-detection boolean mask, raising
IndexError because H != N.
"""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
model.model = _DummyModel(labels=[0, 1]) # 2 detections
detections = model.predict(img) # include_source_image=True by default
# Boolean-mask filtering — the pattern from issue #968
mask = detections.confidence > 0.5
filtered = detections[mask]
assert len(filtered) == int(mask.sum())
# source_image must survive the index operation unchanged (not dropped, not sliced)
assert "source_image" in filtered.metadata
assert filtered.metadata["source_image"].shape == (48, 64, 3)
def test_source_image_survives_class_id_boolean_index(self) -> None:
"""Boolean index on class_id must not raise IndexError — exact issue #968 pattern.
The reporter used ``detections.class_id == 1`` to filter by class, producing a partial boolean mask (1 of 2
detections). This is the primary reproduction path from the original bug report.
"""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
model.model = _DummyModel(labels=[0, 1]) # class_id 0 and 1
detections = model.predict(img)
# Exact pattern from issue #968: filter by class_id
mask = detections.class_id == 1 # partial mask — 1 of 2 detections
filtered = detections[mask]
assert len(filtered) == 1
assert "source_image" in filtered.metadata
assert filtered.metadata["source_image"].shape == (48, 64, 3)
def test_source_image_survives_integer_index(self) -> None:
"""Integer indexing must pass metadata["source_image"] through unchanged."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
model.model = _DummyModel(labels=[0, 1]) # 2 detections
detections = model.predict(img)
single = detections[0]
assert "source_image" in single.metadata
assert single.metadata["source_image"].shape == (48, 64, 3)
def test_predict_keypoints_return_supervision_keypoints(self) -> None:
"""Keypoint predictions return ``sv.KeyPoints`` after threshold filtering."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
model.model = _DummyModel(labels=[0, 1], include_keypoints=True)
key_points = model.predict(img)
assert isinstance(key_points, sv.KeyPoints)
assert key_points.xy.shape == (2, 17, 2)
assert np.allclose(key_points.xy, 0.5)
assert np.allclose(key_points.keypoint_confidence, 0.5)
np.testing.assert_array_equal(key_points.visible, np.full((2, 17), True))
np.testing.assert_array_equal(key_points.class_id, np.array([0, 1]))
np.testing.assert_allclose(key_points.data["xyxy"], np.array([[0, 0, 1, 1], [0, 0, 1, 1]], dtype=np.float32))
np.testing.assert_allclose(key_points.detection_confidence, np.array([0.9, 0.9], dtype=np.float32))
assert "keypoint_precision_cholesky" in key_points.data
keypoint_precision = key_points.data["keypoint_precision_cholesky"]
assert isinstance(keypoint_precision, np.ndarray)
assert keypoint_precision.shape == (2, 17, 3)
assert np.allclose(keypoint_precision, 0.25)
assert "covariance" in key_points.data
np.testing.assert_allclose(
key_points.data["covariance"],
precision_cholesky_to_pixel_covariance(
precision_cholesky=keypoint_precision, source_shape=key_points.data["source_shape"]
),
rtol=1e-4,
atol=1e-6,
)
def test_predict_keypoints_empty_threshold_return_supervision_keypoints(self) -> None:
"""Keypoint predictions remain ``sv.KeyPoints`` when all detections are filtered."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
model.model = _DummyModel(labels=[0, 1], include_keypoints=True)
key_points = model.predict(img, threshold=1.1)
assert isinstance(key_points, sv.KeyPoints)
assert len(key_points) == 0
assert key_points.xy.shape == (0, 17, 2)
assert key_points.keypoint_confidence.shape == (0, 17)
assert key_points.detection_confidence.shape == (0,)
assert key_points.visible.shape == (0, 17)
np.testing.assert_allclose(key_points.data["xyxy"], np.empty((0, 4), dtype=np.float32))
assert key_points.as_detections().is_empty()
def test_predict_non_keypoint_no_keypoints_key_in_data(self) -> None:
"""Non-keypoint predictions do not attach keypoint fields."""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
detections = model.predict(img)
assert "keypoints" not in detections.data
assert not hasattr(detections, "keypoints")
def test_source_shape_survives_detections_indexing(self) -> None:
"""Integer and boolean-mask indexing of sv.Detections must work correctly.
Regression test for https://github.com/roboflow/rf-detr/issues/963. MeanAveragePrecision.compute() uses
__getitem__ (not just __iter__) on Detections objects — both paths go through get_data_item() and would have
crashed on the old tuple format.
"""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
model.model = _DummyModel(labels=[0, 1]) # 2 detections
detections = model.predict(img)
# Integer indexing: detections[i] returns a Detections with 1 element
single = detections[0]
assert np.array_equal(single.data["source_shape"], np.array([[48, 64]]))
# Boolean-mask indexing: used by supervision metrics to filter detections
mask = detections.confidence > 0.5
filtered = detections[mask]
assert filtered.data["source_shape"].shape == (int(mask.sum()), 2)
assert np.all(filtered.data["source_shape"] == np.array([48, 64]))
def test_source_shape_correct_for_zero_detections(self) -> None:
"""source_shape must have shape (0, 2) when threshold filters all detections.
Regression test for https://github.com/roboflow/rf-detr/issues/963. The zero-detection path must not raise and
must produce an empty array, not a scalar or a (1, 2) array.
"""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
# confidence=0.9 < 1.1 → all detections filtered
detections = model.predict(img, threshold=1.1)
assert "source_shape" in detections.data
assert isinstance(detections.data["source_shape"], np.ndarray)
assert detections.data["source_shape"].shape == (0, 2)
def test_source_shape_correct_for_multiple_detections(self) -> None:
"""source_shape must have shape (N, 2) for N detections, each row [height, width].
Regression test for https://github.com/roboflow/rf-detr/issues/963.
"""
img = PIL.Image.new("RGB", (64, 48), color=(128, 128, 128))
model = _DummyRFDETR()
model.model = _DummyModel(labels=[0, 1]) # 2 detections
detections = model.predict(img)
assert "source_shape" in detections.data
assert isinstance(detections.data["source_shape"], np.ndarray)
assert detections.data["source_shape"].shape == (2, 2)
assert np.all(detections.data["source_shape"] == np.array([48, 64]))
class TestPredictImagePinning:
"""``predict()`` should pin CPU-resident image tensors before an accelerator transfer.
A pageable-memory ``.to(device)`` copy onto CUDA is meaningfully slower than a pinned-memory one because the CUDA
driver has to pin the source buffer itself first. But ``Tensor.pin_memory()`` only accepts CPU tensors: a caller who
already placed the input tensor on the model's own accelerator (a legitimate use of the tensor-input path, e.g. to
skip a host round-trip) must never have that tensor routed through ``pin_memory()``, and a CPU-only target device
gets no benefit from pinning at all.
"""
def test_cpu_tensor_inputs_transfer_pinned_buffers_to_cuda_non_blocking(self) -> None:
"""Every CPU input transfers its own pinned buffer to CUDA and reaches the model boundary.
The pinning call returns a different tensor, so this catches the regression where ``predict()`` pins an input
but transfers the original pageable tensor instead. CUDA allocation is intercepted so this dispatch contract
also runs in CPU-only CI; the separate value-parity test exercises the real CUDA transfer.
"""
model = _DummyRFDETR()
model.model.device = torch.device("cuda", 0)
source_tensors = [torch.zeros(3, 48, 64), torch.ones(3, 48, 64)]
pinned_tensors = [
torch.full_like(source_tensors[0], 0.25),
torch.full_like(source_tensors[1], 0.75),
]
transferred_tensors = [
torch.full_like(source_tensors[0], 0.125),
torch.full_like(source_tensors[1], 0.875),
]
real_to = torch.Tensor.to
real_tensor = torch.tensor
pinned_inputs: list[torch.Tensor] = []
cuda_transfer_sources: list[torch.Tensor] = []
model_inputs: list[torch.Tensor] = []
def pin_spy(self: torch.Tensor, *args: object, **kwargs: object) -> torch.Tensor:
"""Return the distinct pseudo-pinned buffer paired with a source tensor.
Examples:
This test-local closure requires its enclosing tensors.
>>> pin_spy(source_tensors[0]) # doctest: +SKIP
"""
source_index = next(
(index for index, source_tensor in enumerate(source_tensors) if self is source_tensor),
None,
)
assert source_index is not None, "pin_memory() must be called on an original input tensor"
pinned_inputs.append(self)
return pinned_tensors[source_index]
def to_spy(self: torch.Tensor, *args: object, **kwargs: object) -> torch.Tensor:
"""Return a distinct pseudo-CUDA buffer for each pinned transfer source.
Examples:
This test-local closure requires its enclosing tensors.
>>> to_spy(pinned_tensors[0], torch.device("cuda"), non_blocking=True) # doctest: +SKIP
"""
if args and isinstance(args[0], torch.device) and args[0].type == "cuda":
cuda_transfer_sources.append(self)
transfer_index = next(
(index for index, pinned_tensor in enumerate(pinned_tensors) if self is pinned_tensor),
None,
)
if transfer_index is not None:
assert kwargs.get("non_blocking") is True
return transferred_tensors[transfer_index]
return self
return real_to(self, *args, **kwargs)
def tensor_spy(data: object, **kwargs: object) -> torch.Tensor:
"""Redirect CUDA target-size construction to CPU for the simulated transfer.
Examples:
This test-local closure requires the captured real tensor constructor.
>>> tensor_spy([[48, 64]], device=torch.device("cuda")) # doctest: +SKIP
"""
device = kwargs.get("device")
if isinstance(device, torch.device) and device.type == "cuda":
kwargs["device"] = torch.device("cpu")
return real_tensor(data, **kwargs)
def capture_model_input(_module: torch.nn.Module, args: tuple[torch.Tensor, ...]) -> None:
"""Capture the normalized batch delivered to the model boundary.
Examples:
This test-local closure requires the enclosing capture list.
>>> capture_model_input(torch.nn.Identity(), (torch.zeros(1, 3, 28, 28),)) # doctest: +SKIP
"""
model_inputs.append(args[0].detach().clone())
model_module = model.model.model
assert model_module is not None
with model_module.register_forward_pre_hook(capture_model_input):
with (
patch.object(torch.Tensor, "pin_memory", pin_spy),
patch.object(torch.Tensor, "to", to_spy),
patch.object(torch, "tensor", tensor_spy),
):
model.predict(source_tensors)
assert len(pinned_inputs) == len(source_tensors)
assert all(pinned_input is source_tensor for pinned_input, source_tensor in zip(pinned_inputs, source_tensors))
assert len(cuda_transfer_sources) == len(pinned_tensors)
assert all(
cuda_transfer_source is pinned_tensor
for cuda_transfer_source, pinned_tensor in zip(cuda_transfer_sources, pinned_tensors)
)
assert len(model_inputs) == 1
captured_batch = model_inputs[0].cpu()
expected_batch = torch.stack(
[
(
torch.full((3, model.model.resolution, model.model.resolution), value)
- torch.tensor(model.means)[:, None, None]
)
/ torch.tensor(model.stds)[:, None, None]
for value in (0.125, 0.875)
]
)
torch.testing.assert_close(captured_batch, expected_batch)
@pytest.mark.gpu
def test_pinned_non_blocking_transfer_preserves_values(self) -> None:
"""Pinning + non_blocking must not change the transferred values versus a plain, blocking .to()."""
torch.manual_seed(0)
source = torch.rand(3, 48, 64)
device = torch.device("cuda", 0)
plain = source.to(device)
pinned = source.pin_memory().to(device, non_blocking=True)
torch.cuda.synchronize()
assert torch.equal(plain, pinned)
@pytest.mark.gpu
def test_already_cuda_tensor_input_is_not_pinned(self) -> None:
"""A tensor the caller already placed on the accelerator must never be routed through pin_memory()."""
model = _DummyRFDETR()
model.model.device = torch.device("cuda", 0)
tensor = torch.rand(3, 48, 64, device="cuda")
pin_spy = MagicMock(side_effect=AssertionError("pin_memory() must not be called on a CUDA tensor"))
with patch.object(torch.Tensor, "pin_memory", pin_spy):
model.predict(tensor) # must not raise: pin_memory() on a CUDA tensor would itself raise RuntimeError
pin_spy.assert_not_called()
def test_cpu_target_device_does_not_pin(self) -> None:
"""A CPU-only target device gets no benefit from pinning, so it must be skipped entirely."""
model = _DummyRFDETR() # _DummyModel defaults to a CPU device
tensor = torch.rand(3, 48, 64)
pin_spy = MagicMock(side_effect=AssertionError("pin_memory() must not be called for a CPU target device"))
with patch.object(torch.Tensor, "pin_memory", pin_spy):
model.predict(tensor)
pin_spy.assert_not_called()
@pytest.mark.gpu
def test_cuda_tensor_input_to_cpu_model_is_not_non_blocking(self) -> None:
"""A tensor already on CUDA moving to a CPU-device model must use a blocking transfer.
``non_blocking=True`` only pays off, and is only safe without an explicit sync, when the destination is CUDA —
matching ``transfer_batch_to_device()`` in ``training/module_data.py``. Here the ``.to()`` call allocates a
fresh, unpinned CPU tensor as its destination, so an async D2H copy could leave that tensor holding an in-flight
(partially written) result if read before the copy stream drains.
"""
model = _DummyRFDETR() # _DummyModel defaults to a CPU device
tensor = torch.rand(3, 48, 64, device="cuda")
real_to = torch.Tensor.to
captured: list[bool] = []
def to_spy(self: torch.Tensor, *args: object, **kwargs: object) -> torch.Tensor:
if self is tensor:
captured.append(bool(kwargs.get("non_blocking", False)))
return real_to(self, *args, **kwargs)
with patch.object(torch.Tensor, "to", to_spy):
model.predict(tensor)
assert captured, "expected predict() to move the image tensor with .to()"
assert not any(captured), "CUDA tensor -> CPU-model transfer must not set non_blocking=True"
class TestPredictUint8Conversion:
"""The fused uint8 path must retain torchvision's exact conversion semantics."""
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])
@pytest.mark.parametrize("grayscale", [False, True])
def test_converter_is_bit_exact_for_supported_default_dtypes(self, dtype: torch.dtype, grayscale: bool) -> None:
"""Layout/dtype fusion and in-place division produce the same raw floating-point bits."""
rng = np.random.default_rng(20260821)
image = rng.integers(0, 256, size=(17, 29, 3), dtype=np.uint8)[:, ::2]
if grayscale:
image = image[:, :, 0]
previous_dtype = torch.get_default_dtype()
try:
torch.set_default_dtype(dtype)
expected = F.to_tensor(image)
actual = detr_module._uint8_chw_to_float(
detr_module._uint8_image_to_chw_view(image), torch.tensor(255, dtype=dtype)
)
finally:
torch.set_default_dtype(previous_dtype)
assert actual.dtype == expected.dtype
assert actual.shape == expected.shape
assert actual.stride() == expected.stride()
assert actual.contiguous().view(torch.uint8).equal(expected.contiguous().view(torch.uint8))
@pytest.mark.parametrize(
"image",
[
pytest.param(PIL.Image.new("RGB", (29, 17), color=(1, 127, 255)), id="pil_rgb"),
pytest.param(np.full((17, 29, 3), 127, dtype=np.uint8), id="numpy_uint8"),
],
)
@pytest.mark.parametrize("include_source_image", [False, True])
def test_predict_uses_fused_path_for_uint8_images(self, image: object, include_source_image: bool) -> None:
"""PIL and valid uint8 NumPy inputs do not fall back to torchvision's allocating path."""
model = _DummyRFDETR()
to_tensor_spy = MagicMock(side_effect=AssertionError("uint8 input unexpectedly used F.to_tensor"))
with patch("rfdetr.detr.F.to_tensor", to_tensor_spy):
model.predict(image, include_source_image=include_source_image)
to_tensor_spy.assert_not_called()
@pytest.mark.parametrize(
"image",
[
pytest.param(np.full((17, 29), 127, dtype=np.uint8), id="numpy_uint8_grayscale"),
pytest.param(np.full((17, 29, 1), 127, dtype=np.uint8), id="numpy_uint8_single_channel_hwc"),
],
)
def test_predict_uses_fused_path_for_single_channel_uint8_images(self, image: np.ndarray[Any, Any]) -> None:
"""One-channel uint8 images use the fused converter at the public ``predict()`` boundary."""
model = _DummyRFDETR()
model.model_config.num_channels = 1
model.means = model.means[:1]
model.stds = model.stds[:1]
to_tensor_spy = MagicMock(side_effect=AssertionError("uint8 input unexpectedly used F.to_tensor"))
with (
patch("rfdetr.detr._uint8_image_to_chw_view", wraps=detr_module._uint8_image_to_chw_view) as converter_spy,
patch("rfdetr.detr.F.to_tensor", to_tensor_spy),
):
model.predict(image)
converter_spy.assert_called_once_with(image)
to_tensor_spy.assert_not_called()
def test_converter_matches_torchvision_for_contiguous_single_channel_hwc(self) -> None:
"""A freshly-allocated (not sliced) ``(H, W, 1)`` array exercises ``num_channels=1`` models
(``ModelConfig.num_channels``, ``config.py``).
Unlike a channel-sliced view, this array is already C-contiguous on input, which is exactly when torchvision's
own ``to_tensor`` leaves the size-1 leading dimension's stride un-normalized -- so equivalence is checked on
every dimension that actually has memory-layout meaning (size > 1), plus dtype/shape/contiguity/raw bits.
"""
rng = np.random.default_rng(20260821)
image = rng.integers(0, 256, size=(17, 29, 1), dtype=np.uint8)
expected = F.to_tensor(image)
actual = detr_module._uint8_chw_to_float(detr_module._uint8_image_to_chw_view(image), torch.tensor(255.0))
assert actual.dtype == expected.dtype
assert actual.shape == expected.shape
assert actual.is_contiguous() == expected.is_contiguous()
assert actual.stride()[1:] == expected.stride()[1:]
assert actual.contiguous().view(torch.uint8).equal(expected.contiguous().view(torch.uint8))
def test_predict_reuses_pil_source_array_for_conversion(self) -> None:
"""Default PIL prediction converts the same NumPy allocation retained as source metadata."""
model = _DummyRFDETR()
image = PIL.Image.new("RGB", (29, 17), color=(1, 127, 255))
with patch("rfdetr.detr._uint8_image_to_chw_view", wraps=detr_module._uint8_image_to_chw_view) as converter_spy:
detections = model.predict(image)
converter_spy.assert_called_once()
assert converter_spy.call_args.args[0] is detections.metadata["source_image"]
def test_predict_keeps_original_readonly_numpy_as_tensor_source(self) -> None:
"""NumPy conversion retains the caller's storage, so it still triggers ``torch.from_numpy``'s not-writable
``UserWarning`` exactly like ``F.to_tensor`` would on the same array."""
model = _DummyRFDETR()
image = np.full((17, 29, 3), 127, dtype=np.uint8)
image.flags.writeable = False
with (
patch("rfdetr.detr._uint8_image_to_chw_view", wraps=detr_module._uint8_image_to_chw_view) as converter_spy,
pytest.warns(UserWarning, match="not writable"),
):
detections = model.predict(image)
converter_spy.assert_called_once()
assert converter_spy.call_args.args[0] is image
assert detections.metadata["source_image"] is not image
assert detections.metadata["source_image"].flags.writeable
def test_deferred_widening_is_bit_exact_for_every_byte_value(self) -> None:
"""The 0-dim divisor keeps IEEE-754 division, which a Python scalar does not on CUDA.
``Tensor.div_(255)`` is evaluated on CUDA as a multiplication by ``1/255``; that rounds differently from the
CPU's division for just under half of all byte values (126 of 256). Since ``predict()`` now widens after the
transfer, the divisor must be a 0-dim tensor for the accelerator result to stay byte-for-byte equal to
torchvision's host-side conversion.
"""
image = np.arange(256, dtype=np.uint8).reshape(16, 16, 1).repeat(3, axis=2)
chw = detr_module._uint8_image_to_chw_view(image)
assert detr_module._uint8_chw_to_float(chw, torch.tensor(255.0)).equal(F.to_tensor(image))
@pytest.mark.gpu
def test_deferred_widening_is_bit_exact_on_real_cuda(self) -> None:
"""The reciprocal-multiplication gap this fix avoids only manifests on real CUDA hardware.
``test_deferred_widening_is_bit_exact_for_every_byte_value`` above proves the divisor swap is correct on
CPU, where scalar and tensor division already agree bit-for-bit; it cannot exercise the CUDA-specific
``Tensor.div_(255)`` reciprocal path this fix replaces. This test runs the same view/pin/transfer/widen
sequence ``predict()`` uses on a real CUDA device and compares it against the host-computed reference.
"""
image = np.arange(256, dtype=np.uint8).reshape(16, 16, 1).repeat(3, axis=2)
expected = F.to_tensor(image)
chw = detr_module._uint8_image_to_chw_view(image).pin_memory().to("cuda", non_blocking=True)
scale = torch.tensor(255, device=chw.device, dtype=torch.get_default_dtype())
actual = detr_module._uint8_chw_to_float(chw, scale).cpu()
assert actual.equal(expected)
def test_one_divisor_serves_every_image_of_a_multi_image_call(self) -> None:
"""`predict()` builds the divisor once per call and reuses it for the rest of the batch.
The in-place division has to consume the freshly widened copy, not the shared divisor, or the second and later
images of a multi-image call would be scaled by an already-divided value.
"""
scale = torch.tensor(255, dtype=torch.get_default_dtype())
dark = np.full((4, 5, 3), 51, dtype=np.uint8)
bright = np.full((4, 5, 3), 255, dtype=np.uint8)
first = detr_module._uint8_chw_to_float(detr_module._uint8_image_to_chw_view(dark), scale)
second = detr_module._uint8_chw_to_float(detr_module._uint8_image_to_chw_view(bright), scale)
assert first.equal(F.to_tensor(dark))
assert second.equal(F.to_tensor(bright))
assert scale.equal(torch.tensor(255, dtype=torch.get_default_dtype()))
def test_uint8_images_cross_the_device_boundary_unwidened(self) -> None:
"""Only the 1-byte-per-channel storage is transferred; the widening runs after the copy."""
model = _DummyRFDETR()
model.model.device = torch.device("cuda", 0)
real_to = torch.Tensor.to
real_tensor = torch.tensor
transferred_dtypes: list[torch.dtype] = []
def to_spy(self: torch.Tensor, *args: object, **kwargs: object) -> torch.Tensor:
"""Record the dtype of each simulated CUDA transfer and keep the result on CPU.
Examples:
This test-local closure requires its enclosing capture list.
>>> to_spy(torch.zeros(3), torch.device("cuda")) # doctest: +SKIP
"""
if args and isinstance(args[0], torch.device) and args[0].type == "cuda":
transferred_dtypes.append(self.dtype)
return self
return real_to(self, *args, **kwargs)
def tensor_spy(data: object, **kwargs: object) -> torch.Tensor:
"""Redirect CUDA target-size construction to CPU for the simulated transfer.
Examples:
This test-local closure requires the captured real tensor constructor.
>>> tensor_spy([[48, 64]], device=torch.device("cuda")) # doctest: +SKIP
"""
device = kwargs.get("device")
if isinstance(device, torch.device) and device.type == "cuda":
kwargs["device"] = torch.device("cpu")
return real_tensor(data, **kwargs)
with (
patch.object(torch.Tensor, "pin_memory", lambda self: self),
patch.object(torch.Tensor, "to", to_spy),
patch.object(torch, "tensor", tensor_spy),
):
model.predict(np.full((17, 29, 3), 127, dtype=np.uint8))
assert transferred_dtypes == [torch.uint8]
def test_predict_keeps_torchvision_fallback_for_float_numpy(self) -> None:
"""Non-uint8 NumPy inputs retain torchvision's no-scaling conversion semantics."""
model = _DummyRFDETR()
image = np.full((17, 29, 3), 0.5, dtype=np.float32)
with patch("rfdetr.detr.F.to_tensor", wraps=F.to_tensor) as to_tensor_spy:
model.predict(image)
to_tensor_spy.assert_called_once_with(image)
def test_predict_keeps_torchvision_fallback_for_invalid_uint8_numpy_rank(self) -> None:
"""A uint8 NumPy input outside the documented 2-D/3-D shape keeps torchvision's validation error."""
model = _DummyRFDETR()
image = np.zeros((1, 3, 17, 29), dtype=np.uint8)
with (
patch("rfdetr.detr.F.to_tensor", wraps=F.to_tensor) as to_tensor_spy,
pytest.raises(ValueError, match="2/3 dimensional"),
):
model.predict(image)
to_tensor_spy.assert_called_once_with(image)
class TestPredictPixelRangeValidation:
"""``predict()`` must still reject out-of-[0, 1]-range tensor inputs, now that the range check is deferred (see the
``pending_checks`` comment in ``detr.py``) instead of raised inline, per image, inside the conversion loop."""
def test_raises_for_pixel_value_above_one(self) -> None:
"""A tensor with any pixel above 1 still raises after the range check moved off the hot path."""
model = _DummyRFDETR()
img = torch.zeros(3, 8, 8)
img[0, 0, 0] = 1.5
with pytest.raises(ValueError, match="pixel values above 1"):
model.predict(img)
def test_valid_images_do_not_raise(self) -> None:
"""A batch of in-range tensors must not raise, deferred check included."""
model = _DummyRFDETR()
img = torch.full((3, 8, 8), 0.5)
model.predict([img, img]) # must not raise
@pytest.mark.parametrize(
"image",
[
pytest.param(PIL.Image.new("F", (8, 8), color=10_000.0), id="pil"),
pytest.param(np.full((8, 8, 3), 255, dtype=np.uint8), id="uint8_numpy"),
],
)
def test_known_valid_converted_image_skips_range_scans(self, image: PIL.Image.Image | np.ndarray[Any, Any]) -> None:
"""PIL conversion and uint8 NumPy scaling already guarantee values in [0, 1]."""
model = _DummyRFDETR()