"""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()