Skip to content

feat: add KV-cache support for incremental decode#10

Open
GoooIce wants to merge 1 commit into
ShadowLLM:mainfrom
GoooIce:feat/kv-cache-support
Open

feat: add KV-cache support for incremental decode#10
GoooIce wants to merge 1 commit into
ShadowLLM:mainfrom
GoooIce:feat/kv-cache-support

Conversation

@GoooIce

@GoooIce GoooIce commented Jul 16, 2026

Copy link
Copy Markdown

ShadowPEFT previously forced use_cache=False in all forward passes, requiring full-sequence recompute at every generation step. This was an implementation limitation, not a mathematical one — the injection and update modules are per-token pure functions with no cross-token recurrence.

This commit enables cached generation:

  • ShadowPeftModel: add _shadow_cache internal state, conditionalize cache disabling in forward/forward_with_shadow, add shadow_cache parameter to _compute_initial_shadow_hidden
  • ShadowForCausalLM: remove forced use_cache=False, fix generation hooks (prepare_inputs_for_generation now slices input_ids for decode steps), propagate past_key_values in output, add get/set_experts_implementation for transformers 5.x compatibility
  • Add experiment/verify_cached_decode_alignment.py PoC (maxdiff ~1e-7)
  • Add tests/test_cached_decode.py (6 tests: generate alignment, prefill+decode, step-by-step logits, backward compat, shadow logits)

Verified: generate(use_cache=True) produces identical token sequences to generate(use_cache=False). Default use_cache=False path is unchanged.

ShadowPEFT previously forced use_cache=False in all forward passes,
requiring full-sequence recompute at every generation step. This was
an implementation limitation, not a mathematical one — the injection
and update modules are per-token pure functions with no cross-token
recurrence.

This commit enables cached generation:

- ShadowPeftModel: add _shadow_cache internal state, conditionalize
  cache disabling in forward/forward_with_shadow, add shadow_cache
  parameter to _compute_initial_shadow_hidden
- ShadowForCausalLM: remove forced use_cache=False, fix generation
  hooks (prepare_inputs_for_generation now slices input_ids for
  decode steps), propagate past_key_values in output, add
  get/set_experts_implementation for transformers 5.x compatibility
- Add experiment/verify_cached_decode_alignment.py PoC (maxdiff ~1e-7)
- Add tests/test_cached_decode.py (6 tests: generate alignment,
  prefill+decode, step-by-step logits, backward compat, shadow logits)

Verified: generate(use_cache=True) produces identical token sequences
to generate(use_cache=False). Default use_cache=False path is unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant