In large language model (LLM) serving systems, a prefix cache stores previously computed key-value (KV) pairs for token sequences that have already been processed. When a new prompt shares a common prefix with a cached entry, the system can skip recomputing those tokens, significantly reducing latency and compute cost.
Implement a function that calculates the prefix cache hit rate given a list of incoming tokenized prompts and a list of cached token prefixes.
For each prompt, determine the longest cached prefix that exactly matches the beginning of that prompt. A cached prefix matches a prompt if the prompt starts with that exact sequence of token IDs. Sum up all matched (cached) tokens across all prompts and compute the hit rate as the ratio of cached tokens to total tokens.
Input:
Output:
If there are no tokens (empty prompts list or all prompts are empty), hit_rate should be 0.0.