Skip to content
Back to skills

Kv Cache Prefix Scoring

ASecurity

Shares KV cache from a common prefix (context+question) across multiple answer suffixes for efficient multi-choice scoring.

  • 61 stars
  • 0 votes
  • 0 copies
  • 5 views
  • Added September 12, 2026
documentationpythongit

Security analysis

A100/100

Scanned September 12, 2026

npx -y skills add wenmin-wu/ds-skills --skill kv-cache-prefix-scoring --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Kv Cache Prefix Scoring?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Kv Cache Prefix Scoring
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/wenmin-wu-kv-cache-prefix-scoring/badge)](https://www.skillsdirectory.com/skills/wenmin-wu-kv-cache-prefix-scoring)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: llm-kv-cache-prefix-scoring
description: >
  Shares KV cache from a common prefix (context+question) across multiple answer suffixes for efficient multi-choice scoring.
---
# KV Cache Prefix Scoring

## Overview

For multiple-choice QA, the context and question are shared across all answer options. Compute the KV cache once for this shared prefix, then score each answer suffix by expanding the cache. This avoids redundant computation — scoring 5 options costs ~1.2x of a single forward pass instead of 5x.

## Quick Start

```python
import torch

def score_options(model, prefix_ids, suffix_ids_list):
    """Score multiple suffixes against a shared prefix."""
    with torch.no_grad():
        # Forward pass on shared prefix — cache the KV states
        prefix_out = model(prefix_ids, use_cache=True)
        kv_cache = prefix_out.past_key_values

        scores = []
        for suffix_ids in suffix_ids_list:
            # Expand cache to match suffix batch
            expanded_kv = [(k.expand_as(k), v.expand_as(v)) for k, v in kv_cache]
            out = model(suffix_ids, past_key_values=expanded_kv)
            # Score = mean log-prob of suffix tokens
            logprobs = torch.log_softmax(out.logits[:, :-1], dim=-1)
            token_scores = logprobs.gather(2, suffix_ids[:, 1:].unsqueeze(-1))
            scores.append(token_scores.mean().item())
    return scores
```

## Workflow

1. Tokenize shared prefix (context + question)
2. Run single forward pass to get KV cache
3. For each answer option, run forward pass with cached KV states
4. Score each option by mean log-probability of suffix tokens
5. Rank options by score

## Key Decisions

- **Memory**: Cache is ~2x model hidden size per layer; fits for models up to 13B on T4
- **Scoring metric**: Mean log-prob normalizes for option length differences
- **Batch suffixes**: If GPU memory allows, batch all suffixes in one pass
- **Applicability**: Any LLM multiple-choice or ranking task

## References

- Kaggle LLM Science Exam (Kaggle)
- Source: [platypus2-70b-with-wikipedia-rag](https://www.kaggle.com/code/simjeg/platypus2-70b-with-wikipedia-rag)

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.