File size: 1,071 Bytes
9c890d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reuse decoder key/value projections within one inference clip."""

from contextlib import contextmanager


@contextmanager
def cache_decoder_projections(decoder):
    if decoder.training:
        raise ValueError("Decoder projection caching is inference-only")
    originals = []
    for block in decoder.cross_blocks:
        module = block.attn.kv
        original = module.forward
        state = {}

        def cached_forward(value, original=original, state=state):
            signature = (tuple(value.shape), value.dtype, value.device)
            if "output" not in state:
                state.update(signature=signature, output=original(value))
            elif state["signature"] != signature:
                raise ValueError("Encoder context changed inside an inference clip")
            return state["output"]

        module.forward = cached_forward
        originals.append((module, original, state))
    try:
        yield
    finally:
        for module, original, state in originals:
            module.forward = original
            state.clear()