|
39 | 39 | # test_qdq_utils_fp8.py::test_fused_q[bf16,fp16] fails if this script runs after the int4 test, but not before. |
40 | 40 |
|
41 | 41 |
|
| 42 | +def test_safe_cupy_array_all_paths(monkeypatch): |
| 43 | + """Test safe_cupy_array covering all code paths including ml_dtypes handling""" |
| 44 | + # Test 1: When ml_dtypes import fails (covers ImportError path) |
| 45 | + # Temporarily remove ml_dtypes from sys.modules |
| 46 | + import sys |
| 47 | + |
| 48 | + if "ml_dtypes" in sys.modules: |
| 49 | + ml_dtypes_backup = sys.modules["ml_dtypes"] |
| 50 | + monkeypatch.delitem(sys.modules, "ml_dtypes") |
| 51 | + else: |
| 52 | + ml_dtypes_backup = None |
| 53 | + |
| 54 | + tensor = np.array([1, 2, 3, 4], dtype=np.int8) |
| 55 | + result = int4.safe_cupy_array(tensor) |
| 56 | + assert isinstance(result, np.ndarray) # Should return numpy array |
| 57 | + |
| 58 | + # Restore ml_dtypes if it existed |
| 59 | + if ml_dtypes_backup: |
| 60 | + sys.modules["ml_dtypes"] = ml_dtypes_backup |
| 61 | + |
| 62 | + # Test 2: When ml_dtypes exists and tensor has ml_dtypes.int4 dtype |
| 63 | + try: |
| 64 | + import ml_dtypes |
| 65 | + |
| 66 | + # Create a mock tensor with int4 dtype |
| 67 | + class MockInt4Tensor: |
| 68 | + def __init__(self, data): |
| 69 | + self.data = data |
| 70 | + self.dtype = ml_dtypes.int4 |
| 71 | + self.shape = data.shape |
| 72 | + |
| 73 | + def astype(self, dtype): |
| 74 | + return self.data.astype(dtype) |
| 75 | + |
| 76 | + def __array__(self): |
| 77 | + return self.data |
| 78 | + |
| 79 | + mock_tensor = MockInt4Tensor(np.array([1, 2, 3, 4], dtype=np.int8)) |
| 80 | + print(mock_tensor.dtype) |
| 81 | + result = int4.safe_cupy_array(mock_tensor) |
| 82 | + assert isinstance(result, np.ndarray) |
| 83 | + assert result.dtype == np.int8 |
| 84 | + except ImportError: |
| 85 | + # ml_dtypes not available, skip this part |
| 86 | + pass |
| 87 | + |
| 88 | + # Test 3: Normal case with regular numpy array |
| 89 | + tensor = np.array([1, 2, 3, 4], dtype=np.int8) |
| 90 | + result = int4.safe_cupy_array(tensor) |
| 91 | + # Should work normally |
| 92 | + assert isinstance(result, (np.ndarray, type(tensor))) |
| 93 | + |
| 94 | + |
42 | 95 | def test_int4_awq(tmp_path): |
43 | 96 | def _forward_loop(model, dataloader): |
44 | 97 | """Forward loop for calibration.""" |
|
0 commit comments