MCPcopy Create free account
hub / github.com/pytorch/executorch / export_kv_cache

Method export_kv_cache

extension/llm/modules/test/test_kv_cache.py:112–148  ·  view source on GitHub ↗
(
        self,
        kv_cache: torch.nn.Module,
    )

Source from the content-addressed store, hash-verified

110 self.assertTrue(et_k_cache[0][prefill_seq_len + 1][0][0] == 0)
111
112 def export_kv_cache(
113 self,
114 kv_cache: torch.nn.Module,
115 ) -> torch.export.ExportedProgram:
116 # Wrapper since torch.export only exports forward().
117 class EtCacheWrapper(torch.nn.Module):
118 def __init__(self, kv_cache: torch.nn.Module):
119 super().__init__()
120 self.kv_cache = kv_cache
121
122 def forward(self, k_val: torch.Tensor, v_val: torch.Tensor):
123 return self.kv_cache.update(k_val, v_val)
124
125 dim = torch.export.Dim("seq_len_dim", min=1, max=self.max_seq_len)
126 exported_kv_cache = torch.export.export(
127 EtCacheWrapper(self.et_kv_cache),
128 (
129 torch.Tensor(self.batch_size, 3, self.num_kv_heads, self.head_dim),
130 torch.Tensor(self.batch_size, 3, self.num_kv_heads, self.head_dim),
131 ), # 3 as example prefill seq_len.
132 dynamic_shapes={
133 "k_val": {
134 0: torch.export.Dim.STATIC,
135 1: dim,
136 2: torch.export.Dim.STATIC,
137 3: torch.export.Dim.STATIC,
138 },
139 "v_val": {
140 0: torch.export.Dim.STATIC,
141 1: dim,
142 2: torch.export.Dim.STATIC,
143 3: torch.export.Dim.STATIC,
144 },
145 },
146 strict=True,
147 )
148 return exported_kv_cache
149
150 def test_kv_cache_eager(self):
151 self._test_kv_cache(self.et_kv_cache.update)

Callers 4

test_kv_cache_exportMethod · 0.95
test_kv_cache_edgeMethod · 0.95

Calls 3

EtCacheWrapperClass · 0.85
TensorMethod · 0.80
exportMethod · 0.45

Tested by

no test coverage detected