Can Multi-Turn Semantic Caching Really Cut 40% of Inference Cost? A New arXiv Paper Turns Reuse Into Learnable Risk

TL;DR: arXiv 2611.01077, submitted 2026-10-31, runs a solid experiment: with 1000 cache entries, multi-turn semantic caching avoids 35-41% of generation cost and cuts estimated latency by 19-35%, measured on real conversation logs (SocraTeach math tutoring, Taskmaster-3 movie ticketing), not synthetic toys. The bigger point: "similar means reuse" is mostly wrong in multi-turn dialogue (source: arXiv:2611.01077, submitted 2026-10-31).

Why single-turn similarity fails in multi-turn

Classic semantic caching embeds the request and reuses an old answer for a similar one. That works for single turns, but "similar" in a conversation depends on the whole history, while an embedding only sees the current line.

The paper measures request-plus-history embedding similarity across five workloads and gets an AUC of just 0.62-0.74 for "can we reuse". The harshest case: in SocraTeach, the same follow-up question with a different history is safe to reuse only 22% of the time. In math tutoring, "what to explain next" depends heavily on how far the proof has progressed.

Modeling "can we reuse" as a learnable risk

The paper turns the reuse decision into two quantities:

  • Compatibility mask chi(z,u): rules out never-usable pairs (e.g. force key equality).
  • Reuse risk r(z,u): the probability that, in state z, the cached answer a(u) is "unacceptable" to the judge or user.

Reuse loss is rho(z,u) = min(1, gamma * r(z,u)) when compatible, else 1; gamma converts risk into normalized cost. The label Y comes from a reuse judge: the paper uses GPT-4o-mini at temperature 0 to decide whether a cached answer is acceptable for the current request plus history.

The optimal serving rule is intuitive: call the LLM only when its expected cost c(z) is less than or equal to the reuse loss rho(z,u); otherwise return the cache. In other words, it is not "similar, so return cache", but "does the generation cost the cache avoids outweigh the risk of a wrong reuse".

Budgeted admission and two algorithms

The cache holds at most k entries; the problem becomes minimizing expected loss over all subsets of size at most k. Two algorithms:

  • CUCB-SC-MT (offline): builds a layered epsilon-net from logs, estimates state weights, fits cost and risk with KRR, then Reverse Greedy picks representatives, with a suboptimality guarantee.
  • CLCB-LS-MT (online): per-conversation snapshots, low switching (updates the cache only at conversation boundaries), samples judge labels with probability zeta to update risk, regret O(sqrt(N)).

The core insight: caching is a budget trade-off -- spend capacity on states with high reuse value and low risk, not on the most similar requests.

The numbers: 35-41% saved at 1000 entries

Method (k=1000)Taskmaster-3 SCASocraTeach SCA
CLCB-LS-MT (this paper)35.0%41.0%
ContextCache17.9%25.1%
ElastiCache-MT22.3%0.8%
vCache14.7%0.7%

SCA (Safe Cost Avoided) is the share of cost saved by safe hits. On latency, CLCB-LS-MT drives estimated serving latency down to 0.80-0.85x t_LLM on Taskmaster-3 and 0.65-0.70x on SocraTeach -- a 19-35% cut.

Build one yourself (Python, stdlib only)

This runs with no numpy or sklearn. The idea: represent queries and context as bag-of-words vectors, estimate reuse risk with a tiny logistic regression that learns online from a proxy judge, and admit a cache hit only when the LLM cost beats the risk-adjusted cost.

import math

def embed(text):
    v = {}
    for w in text.lower().split():
        v[w] = v.get(w, 0) + 1
    return v

def cosine(a, b):
    keys = set(a) | set(b)
    num = sum(a.get(k, 0) * b.get(k, 0) for k in keys)
    da = math.sqrt(sum(x * x for x in a.values()))
    db = math.sqrt(sum(x * x for x in b.values()))
    return num / (da * db) if da and db else 0.0

# minimal logistic regression: features = [query sim, history cosine, bias]
w = [0.0, 0.0, 0.0]

def risk(feat):
    z = sum(wi * fi for wi, fi in zip(w, feat))
    return 1.0 / (1.0 + math.exp(-z))

def judge_proxy(q_new, h_new, q_old, h_old):
    # proxy judge: same turn and highly overlapping history means reusable
    sq = cosine(embed(q_new), embed(q_old))
    sh = cosine(embed(" ".join(h_new)), embed(" ".join(h_old)))
    return 0 if (sq > 0.9 and sh > 0.85) else 1

COST_LLM = 1.0
GAMMA = 1.0
cache = []          # each: (q_text, h_text, answer)
total = 0.0
saved = 0.0
lr = 0.1

def serve(q_text, hist):
    global total, saved
    qv, hv = embed(q_text), embed(" ".join(hist))
    best, bsim = None, -1.0
    for item in cache:
        s = cosine(qv, embed(item[0]))
        if s > bsim:
            best, bsim = item, s
    if best is not None:
        feat = [bsim, cosine(hv, embed(" ".join(best[1]))), 1.0]
        rho = min(1.0, GAMMA * risk(feat))
        if COST_LLM <= rho:        # calling the LLM is cheaper
            ans = "gen:" + q_text
        else:
            ans = best[2]          # reuse the cache
            saved += COST_LLM
        y = judge_proxy(q_text, hist, best[0], best[1])
        err = y - risk(feat)
        for i in range(len(w)):
            w[i] += lr * err * feat[i]
    else:
        ans = "gen:" + q_text
    total += COST_LLM
    cache.append((q_text, hist, ans))
    return ans

for i in range(200):
    h = ["order ticket %d" % i]
    serve("what is the price", h)
    serve("confirm the seat", h)
    serve("thank you", h)
print("cost saved: %.1f%%" % (100.0 * saved / total))

A cache in front of an OpenAI-compatible endpoint

The same logic drops in front of any /v1/chat/completions call. This FastAPI middleware caches by cheap similarity and a risk gate; swap the cheap embed for a real embedding model in production.

# pip install fastapi uvicorn
from fastapi import FastAPI, Request
import math

app = FastAPI()
store = []   # (emb, completion)

def cheap_embed(messages):
    v = {}
    for m in messages:
        for w in m.get("content", "").lower().split():
            v[w] = v.get(w, 0) + 1
    return v

def cosine(a, b):
    num = sum(a.get(k, 0) * b.get(k, 0) for k in set(a) | set(b))
    da = math.sqrt(sum(x * x for x in a.values()))
    db = math.sqrt(sum(x * x for x in b.values()))
    return num / (da * db) if da and db else 0.0

@app.post("/v1/chat/completions")
async def chat(req: Request):
    body = await req.json()
    emb = cheap_embed(body.get("messages", []))
    for e, comp in store:
        if cosine(emb, e) >= 0.92:
            comp["_cached"] = True
            return comp
    result = {"choices": [{"message": {"role": "assistant",
                 "content": "call upstream here"}}]}
    store.append((emb, result))
    return result

Where to use it

Semantic caching pays off in high-repeat, low-tolerance-cost settings: customer support, tutoring, fixed-flow Q and A. In multi-turn dialogue, stop forcing single-turn similarity; either adopt the paper risk learning or at least group by conversation state before comparing. Evict low-hit entries (say by a reuse-risk threshold) and spend capacity on high-value states.

Further reading

Commentaires

Ce site est uniquement frontal : pas de backend ni de compte. Les commentaires vont sur GitHub Issues, Discussions ou par e-mail.

Collez ceci dans l'issue ou l'e-mail pour m'aider à localiser le problème ; cela n'inclut rien de ce que vous avez saisi

Aussi :Voir les commentaires existants · Commentaires par e-mail (sans compte GitHub) :278975598@qq.com