|
7 | 7 | flatten_unflatten_for_dynamic_shapes, |
8 | 8 | make_dynamic_cache, |
9 | 9 | make_encoder_decoder_cache, |
| 10 | + make_hybrid_cache, |
10 | 11 | make_mamba_cache, |
11 | 12 | make_sliding_window_cache, |
12 | 13 | make_static_cache, |
13 | 14 | ) |
| 15 | +from onnx_diagnostic.helpers.torch_helper import torch_deepcopy |
14 | 16 | from onnx_diagnostic.export import CoupleInputsDynamicShapes |
15 | 17 | from onnx_diagnostic.torch_export_patches.patch_inputs import ( |
16 | 18 | convert_dynamic_axes_into_dynamic_shapes, |
@@ -209,6 +211,45 @@ def test_unflatten_flatten_static_cache(self): |
209 | 211 | self.string_type(unflat, with_shape=True), |
210 | 212 | ) |
211 | 213 |
|
| 214 | + def test_make_hybrid_cache(self): |
| 215 | + cache = make_hybrid_cache( |
| 216 | + [ |
| 217 | + (torch.rand((4, 5, 6, 7)), torch.rand((4, 5, 6, 7))), |
| 218 | + (torch.rand((4, 5, 6, 7)), torch.rand((4, 5, 6, 7))), |
| 219 | + (torch.rand((4, 5, 6, 7)), torch.rand((4, 5, 6, 7))), |
| 220 | + ], |
| 221 | + ) |
| 222 | + text = self.string_type(cache, with_shape=True) |
| 223 | + self.assertEqual( |
| 224 | + "HybridCache(key_cache=#3[T1s4x5x6x7,T1s4x5x6x7,T1s4x5x6x7], " |
| 225 | + "value_cache=#3[T1s4x5x6x7,T1s4x5x6x7,T1s4x5x6x7])", |
| 226 | + text, |
| 227 | + ) |
| 228 | + self.assertEqual(0, max_diff(cache, cache)["abs"]) |
| 229 | + self.assertEqual(0, max_diff(cache, torch_deepcopy(cache))["abs"]) |
| 230 | + |
| 231 | + def test_unflatten_flatten_hybrid_cache(self): |
| 232 | + with torch_export_patches(patch_transformers=True): |
| 233 | + c2 = make_hybrid_cache( |
| 234 | + [ |
| 235 | + (torch.rand((4, 5, 6, 7)), torch.rand((4, 5, 6, 7))), |
| 236 | + (torch.rand((4, 5, 6, 7)), torch.rand((4, 5, 6, 7))), |
| 237 | + (torch.rand((4, 5, 6, 7)), torch.rand((4, 5, 6, 7))), |
| 238 | + ], |
| 239 | + ) |
| 240 | + self.assertEqual(0, max_diff(c2, c2)["abs"]) |
| 241 | + self.assertIsInstance(c2, transformers.cache_utils.HybridCache) |
| 242 | + flat, _spec = torch.utils._pytree.tree_flatten(c2) |
| 243 | + self.assertIsInstance(flat, list) |
| 244 | + self.assertEqual(len(flat), 6) |
| 245 | + unflat = flatten_unflatten_for_dynamic_shapes(c2) |
| 246 | + self.assertIsInstance(unflat, list) |
| 247 | + self.assertEqual(len(unflat), 2) |
| 248 | + self.assertEqual( |
| 249 | + "#2[#3[T1s4x5x6x7,T1s4x5x6x7,T1s4x5x6x7],#3[T1s4x5x6x7,T1s4x5x6x7,T1s4x5x6x7]]", |
| 250 | + self.string_type(unflat, with_shape=True), |
| 251 | + ) |
| 252 | + |
212 | 253 |
|
213 | 254 | if __name__ == "__main__": |
214 | 255 | unittest.main(verbosity=2) |
0 commit comments