Download examples/visualizer_code/source/evaluation/decoder_kv_cache.py from facebook/SCALE4D: direct link, hf CLI and curl.
- Browser
- Download file 1.07 kB
-
https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/evaluation/decoder_kv_cache.py
- Command line
-
hf download hf://facebook/SCALE4D/examples/visualizer_code/source/evaluation/decoder_kv_cache.py
-
curl -L -o decoder_kv_cache.py https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/evaluation/decoder_kv_cache.py
1.07 kB
| """Reuse decoder key/value projections within one inference clip.""" | |
| from contextlib import 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() | |