Approximate Caching for Efficiently Serving Diffusion Models
Paper · 2023 · Shubham Agarwal, Subrata Mitra, Sarthak Chakraborty et al.
Summary
Generating an image from a written description can require a long sequence of expensive calculations. A diffusion system begins with noise and repeatedly removes some of it while following the description. Even when earlier advances shorten this process, serving many requests still consumes substantial GPU time. “Approximate Caching for Efficiently Serving Diffusion Models” asks whether each request really needs to start at the beginning. Its answer is Nirvana: a serving system that retrieves a partially completed generation from an earlier, related request, then continues processing it under the new description.
The reusable object is neither a finished picture nor a ready-made answer. It is an intermediate state that still contains noise and can therefore be redirected. How far the system can safely jump into the generation process depends on how closely the old and new prompts resemble each other. A loosely related prompt may support only a small shortcut. A very similar prompt may allow a later starting point and greater savings. Nirvana profiles this relationship beforehand, then uses prompt similarity to select a starting point during operation. When the available match is unsuitable, it generates the image from scratch.
The paper also treats caching as a resource-allocation problem. An intermediate state is valuable because of both its likelihood of reuse and the computation it avoids. Nirvana’s eviction policy, Least Computationally Beneficial and Frequently Used, or LCBFU, combines access frequency with the number of generation steps saved. A separate predictor can bypass a remote cache search when a useful match appears unlikely. Together, these mechanisms make the proposal an end-to-end serving design rather than simply an observation that related prompts sometimes share useful intermediate work.
The evaluation uses DiffusionDB and a proprietary production workload called System-X. The headline findings are 21% less GPU computation, 19.8% lower end-to-end latency, and 19% lower amortized monetary cost. Image-quality measurements place Nirvana much closer to generation from scratch than to systems that return an existing picture for a similar prompt. In a study involving 60 participants, the reported positive judgments were 79% for Nirvana, 86% for generation from scratch, and 31% for GPT-Cache. These results support the central distinction: a related image can be a poor final answer while its unfinished generation can still be a useful starting point. They do not establish that similarity guarantees correct reuse, that every workload offers the same savings, or that repeated reuse preserves image diversity indefinitely.
Interesting ideas
Reuse unfinished work. A completed result may be too specific to its original request, whereas an intermediate representation may still permit adaptation. Nirvana exploits that remaining flexibility rather than treating reuse as an all-or-nothing choice. The broader opportunity is to identify checkpoints that retain expensive shared work while leaving request-specific decisions open. This can apply to iterative analysis, search, optimization, and document processing, provided continuation from a checkpoint has a clear meaning.
Choose reuse depth from evidence. The nearest available item is not automatically safe to reuse at every stage. Nirvana separates finding a related request from deciding how much of its computation can be inherited. Offline experiments connect similarity with an acceptable continuation depth. Elsewhere, the same principle suggests measuring how much prior work a new input can safely retain, rather than applying one global shortcut to every apparent match.
Optimize saved work rather than cache hits. A frequently accessed item can save very little computation, while a less popular item can avoid substantial expense. LCBFU makes the distinction explicit by weighting frequency with the benefit of a successful reuse. This reasoning transfers to caches of database plans, parsed documents, prepared analyses, and other objects whose reconstruction costs differ. The useful objective is the resource saved under the actual workload.
Predict when searching is worthwhile. Looking for reusable work has a cost of its own. Nirvana places a lightweight local decision before a more expensive vector search, accepting that some opportunities will be missed in exchange for avoiding unproductive lookups. This pattern is useful when a remote service, large index, or storage layer introduces noticeable overhead. Its value depends on measuring both needless searches and useful searches incorrectly skipped.
Study the request stream before designing the cache. The paper examines how prompt popularity changes, how users repeat or revise requests, and how similarity behaves for long descriptions. Those observations explain why exact repetition is too narrow a basis for caching and why broad similarity can still be misleading. Other systems can benefit from the same sequence: characterize real requests, identify what remains stable, and design reuse around that evidence.
Evaluate adaptation separately from retrieval. Returning the closest stored result and continuing computation from a related state are different procedures. Nirvana compares them using image-quality measurements and human judgments, showing why retrieval speed alone cannot establish a satisfactory service. The transferable lesson is to evaluate the final adapted output, including details that distinguish the current request from its neighbor.
Prefer a conservative fallback when a shortcut is unavailable. Nirvana can abandon reuse, or move to an earlier checkpoint when the preferred one has been evicted. It gives up potential savings to preserve more room for adaptation. The general pattern is useful wherever an optimization has narrower validity than the full procedure: make the shortcut optional, expose its assumptions, and retain a well-defined route for completing the task.
Deep dive: Approximate Caching for Efficiently Serving Diffusion Models
Nirvana reuses intermediate diffusion states to cut image generation costs, balancing prompt similarity, image quality and cache value. · about 37 minutes to read
How Mova uses it
Mova is a small, transparent language system written in Rust. Its native work concerns linguistic structure, explicit knowledge, reasoning, and bounded execution. Nirvana’s image-generation results are not measurements of Mova. The connections below are proposed transfers of mechanisms and evaluation ideas. The status marks compare each proposal with the documented Mova mechanisms; they do not establish implementation history or measured benefit from this paper. In particular, “нове” identifies a proposed addition whose implementation is not established by the available evidence.
Idea: Reuse unfinished analysis rather than a neighboring answer. Where: Introduction, Figure 1, and Section 4.1. Area: data processing. Mova: частково є (shared document parsing and retained graphs in world/src/knowledge/retention/mice.rs). Mova already shares a document representation among specialist readers. A further experiment could identify which intermediate analyses remain reusable after a document or question changes, then recompute the affected interpretation. This is a hypothesis about bounded reuse; sharing a graph for one document does not establish safe reuse across different documents.
Idea: Select reuse depth from measured compatibility. Where: Section 5.3.1 and Figures 9–10. Area: evaluation and execution. Mova: нове. A Mova cache could distinguish reusable tokenization, dependency structure, frames, and contextual conclusions, with separate admission conditions for each. Similar wording would initiate compatibility checks rather than authorize reuse of every layer. Why Mova: its explicit pipeline provides natural checkpoints, so measured reuse could reduce repeated work while keeping the reason for each inherited result visible.
Idea: Retain objects according to avoided computation. Where: Section 5.4. Area: resource scheduling. Mova: нове. A cache of parsed documents, graph observations, or groupant checks could rank entries by observed reuse and measured reconstruction cost. Nirvana’s frequency-times-step score is a starting analogy, not a ready-made formula for Mova, where different stages have unequal costs. Why Mova: a frequently requested cheap result should not automatically displace an expensive reusable analysis.
Idea: Put a cheap eligibility check before an expensive search. Where: Section 5.2. Area: information retrieval. Mova: нове. Before querying a large durable store, Mova could use a deterministic summary of language, source version, task family, and available representation to rule out incompatible searches. Such a gate would need measured false exclusions and lookup savings. Why Mova: logical metadata checks fit its preference for rules and statistics and can avoid unnecessary storage or service calls without requiring a neural predictor.
Idea: Characterize real request streams before choosing cache rules. Where: Section 3 and Figures 5–7. Area: data analysis. Mova: частково є (tools/twin records predicted and actual costs; worker state retains operational outcomes). Mova could additionally measure repeated task families, intervals between related requests, and the persistence of useful document clusters. These statistics would guide cache design, instead of assuming that chronological recency or global frequency captures its workload.
Idea: Compare adapted outputs with directly retrieved outputs. Where: Sections 7.1–7.2 and Table 1. Area: evaluation. Mova: нове. An experiment could compare returning a stored observation, adapting that observation through native checks, and recomputing the analysis. Accuracy, explanation validity, and runtime should all be recorded on the same requests. Why Mova: this would test whether an intermediate representation contributes useful work without allowing a neighboring document’s conclusion to masquerade as the current answer.
Idea: Fall back conservatively when a reusable checkpoint is missing. Where: Section 5.4, handling of holes. Area: execution correctness. Mova: частково є (configured deputy failures and explicit CPU/GPU execution boundaries). A reuse layer could retreat to an earlier validated representation when a later compatible artifact is unavailable. Existing failure handling supports the general principle, but does not demonstrate this particular checkpoint policy.
Idea: Measure which decisions become fixed at each stage. Where: Section 2.2 and Figure 4. Area: syntax and semantics. Mova: нове. Controlled changes to a sentence could reveal when tokenization, attachment, role assignment, or world-state interpretation must be revisited. A changed modifier may leave some structure intact while invalidating a frame. Why Mova: mapping these dependencies would make partial recomputation explicit and help prevent a late-stage shortcut from preserving an obsolete interpretation.
Idea: Treat similarity as a proposal signal rather than equivalence. Where: Section 3 and Figure 6. Area: lexical semantics and reasoning. Mova: частково є (source-bound groupants and finite correspondence checks in docs/hybrid-system.md). Mova already distinguishes observed agreement from proof of equivalence. Applying that boundary to caching would require exact checks for changed entities, quantities, negation, roles, and sources before accepting a reused result.
Idea: Analyze long and short inputs separately. Where: Sections 3 and 7.6, Figure 6, and Table 4. Area: evaluation. Mova: нове. Mova could stratify reuse failures by sentence length, document length, and structural complexity. The relevant hypothesis is that an aggregate match can conceal more consequential differences in a longer input. Why Mova: separate strata can expose a cache that appears reliable overall while failing on detailed instructions or complex sentences.
Idea: Distinguish within-session from cross-session reuse. Where: Section 3 and Figure 7. Area: workload analysis. Mova: нове. Worker logs could reveal whether useful repetition comes from revisions within one task, later returns to the same source, or independent requests sharing a representation. Why Mova: these cases suggest different cache lifetimes and keys, while explicit source and configuration identities can prevent accidental mixing of contexts.
Idea: Measure how quickly useful clusters lose relevance. Where: Section 3 and Figure 5. Area: statistics. Mova: нове. Instead of keeping every once-popular analysis indefinitely, Mova could track whether task or source clusters continue generating reuse opportunities. Cluster definitions would need to preserve meaningful distinctions rather than merely inflate apparent longevity. Why Mova: this can guide eviction and refresh policies for durable operational stores whose contents change over time.
Idea: Profile a quality constraint before enabling a shortcut. Where: Section 4.1, Equation 10, and Section 5.3.1. Area: evaluation gates. Mova: частково є (held-out regression gates for rule revision and measured GPU approximants). A proposed cache should face the same discipline: evaluate final answers and explanations under its declared domain before enabling reuse. The relevant quality criterion would be linguistic or logical correctness, not the paper’s image-alignment measure.
Idea: Separate search cost, retrieval cost, and remaining computation. Where: Section 4.1, Equations 5–11. Area: performance analysis. Mova: частково є (tools/twin and tools/jobs compare estimates with actual resource use). A cache experiment could report these components separately. This would reveal whether an apparently helpful reuse mechanism merely shifts work from native computation to indexing, decompression, or storage access.
Idea: Account for opportunities lost by an early rejection gate. Where: Section 5.2. Area: statistics and evaluation. Mova: нове. A deterministic prefilter could safely send rejected cases through full computation, yet still discard many profitable reuse opportunities. Evaluation should therefore count useful matches that the gate prevented the system from finding. Why Mova: a gate can preserve answer quality while quietly making the proposed optimization ineffective.
Idea: Refresh a gate when its searchable population changes. Where: Section 5.2 and the end of Section 5.4. Area: data lifecycle. Mova: нове. Any summary used to predict cache eligibility should carry the identity of the index it summarizes and be refreshed after relevant mutations. The update condition should come from Mova measurements rather than copying Nirvana’s setting. Why Mova: version-bound summaries fit its provenance discipline and avoid decisions based on stale cache contents.
Idea: Separate searchable metadata from heavy payloads. Where: Sections 4.2 and 5.3. Area: storage. Mova: вже є (tools/dictindex keeps transactional directories separately from compressed posting payloads). Nirvana offers another example of searching a compact representation before fetching a larger object. For Mova, the useful continuation is to measure this separation under actual lookup patterns and preserve the exact identity of the payload returned.
Idea: Admit new reusable material through a defined insertion event. Where: Section 5.4, insertion policy. Area: data admission. Mova: частково є (tools/enrich stages reviewed material separately from admission; tools/dictindex publishes batches transactionally). A cache could likewise distinguish generated artifacts from artifacts authorized for later reuse. A completed worker action should not on its own establish that its output is a valid reusable interpretation.
Idea: Keep eviction synchronized with index membership. Where: Section 5.4, removal of entries without remaining states. Area: storage correctness. Mova: частково є (tools/dictindex coordinates directory and cursor publication). For reusable analyses, deleting payloads should also update the metadata that advertises their availability. Existing transactional indexing is relevant, but it does not establish a general cache eviction mechanism.
Idea: Evaluate cold-start behavior separately from preloaded operation. Where: Sections 7.1 and 7.4. Area: experimental design. Mova: нове. A cache benchmark should report performance before useful representations accumulate and after a declared preload. The preload must remain separate from held-out assessment labels. Why Mova: this avoids attributing mature-store performance to a fresh deployment and preserves the boundary between operational preparation and evaluation leakage.
Idea: Preserve realistic request order. Where: Section 7.1, workload generator. Area: evaluation. Mova: нове. Replaying requests in their observed order would retain the temporal repetition that determines cache usefulness. An additional experiment could then test whether conclusions survive other declared ordering conditions. Why Mova: cache performance depends on what has already been seen, so an arbitrary shuffle can conceal the behavior users would encounter.
Idea: Evaluate response-time variability as well as the average. Where: Section 7.3 and the match-predictor analysis in Section 7.7. Area: performance evaluation. Mova: нове. Native task serving could report latency distributions alongside mean runtime, separating cache hits, rejected searches, and full recomputation. Why Mova: a worker that is typically fast but occasionally delayed by remote searches can be harder to coordinate than its average suggests.
Idea: Include supporting services in the cost calculation. Where: Section 7.3 and Figure 13. Area: operational economics. Mova: частково є (tools/jobs and tools/twin retain resource estimates and measurements). A complete reuse experiment would also include index construction, persistent storage, decompression, and maintenance. The paper’s cloud prices would not transfer to Mova; the reusable idea is to count the infrastructure required to realize the saving.
Idea: Choose a retrieval representation using final utility. Where: Section 7.7 and Table 5. Area: information retrieval. Mova: частково є (tools/dictindex exposes explained frame and collocation selectors). Alternative keys based on lemmas, dependency relations, frames, or source metadata could be compared by useful reuse, final correctness, and search cost. A representation that retrieves more neighbors is not necessarily the one that saves the most valid work.
Idea: Evaluate eviction policy independently from output quality. Where: Section 7.8 and Table 6. Area: evaluation. Mova: нове. Cache-policy comparisons should hold the interpretation procedure constant and measure both saved work and answer correctness. Why Mova: an efficiency gain should come from retaining more useful artifacts, rather than silently changing which analyses or evidence the system accepts.
Idea: Use fresh-generation variability as a reference for approximation. Where: Section 7.2 and Table 1. Area: evaluation methodology. Mova: частково є (deterministic repeated runs and declared CPU/GPU agreement checks). For Mova’s deterministic native path, the expected reference is repeatability rather than image diversity. The transferable idea is to establish the full procedure’s own behavior before judging deviations caused by a shortcut.
Idea: Evaluate the property people actually need. Where: Section 7.2, participant study. Area: human evaluation. Mova: нове. Reviewers could judge whether an explanation supports its answer, whether a dictionary example demonstrates the stated sense, or whether a task report resolves the user’s request. Why Mova: structural validity and aggregate accuracy can miss failures in the usefulness of a specific explanation or evidence example.
Idea: Preserve diversity when reuse concentrates on familiar material. Where: Discussions, image diversity. Area: dictionary coverage and evaluation. Mova: нове. A reuse-heavy evidence workflow could repeatedly surface common senses or familiar sentence patterns. An experiment could reserve fresh retrieval or analysis opportunities and measure coverage of less frequent cases. Why Mova: a free dictionary needs breadth as well as efficient access to already familiar evidence; the paper motivates the risk but does not measure it for lexicography.
Idea: Test behavior under a change in request characteristics. Where: Discussions, change in prompt characteristics. Area: robustness. Mova: частково є (unknown evidence abstains in closed French rules, and unsupported deputy requests retain failures). A cache-specific test could introduce a different language, domain, or source version and check whether reuse decreases appropriately. Existing abstention mechanisms support the principle; they do not prove cache robustness.
Idea: Keep a quality–performance control separate from acceptance truth. Where: Section 5.3.1. Area: operational policy. Mova: частково є (exact CPU execution and declared GPU approximants). Exploratory processing may tolerate a measured approximation, whereas admitted knowledge and formal checks require their own acceptance conditions. Any configurable shortcut should state which result type it affects and what validation remains mandatory.
Idea: Combine reuse with existing optimizations without assuming additive gains. Where: Related Works and Discussions. Area: systems evaluation. Mova: нове. Reuse could be tested alongside compiled rules, compressed storage, or GPU stages, with the combined configuration measured directly. Why Mova: reducing one component can expose another as the dominant cost, so separate successful optimizations do not establish the benefit of their combination.
The problem and its context
Why repeated generation is expensive
Text-to-image generation is presented as a service problem with a demanding computational core. A user writes a description, and the system produces a picture intended to express it. The paper describes increasing adoption in creative workflows and uses production-scale prompt collections to motivate the need for efficient serving. At that scale, a modest reduction in work per request can matter even when the underlying generation procedure remains unchanged.
Diffusion performs generation through repeated refinement. It starts from a noisy state and gradually transforms that state into an image under textual guidance. Earlier formulations could require 1000 iterations. Sampling improvements discussed in the paper bring practical generation towards roughly 50-100 iterations, but the remaining sequence is still costly.
The authors emphasize that the straightforward alternatives have disadvantages. A smaller generator can respond faster but may produce less satisfactory images. A more powerful GPU can reduce waiting time while increasing the cost of the infrastructure. Their measurements compare different Stable Diffusion variants across GPU architectures to illustrate those tradeoffs. Nirvana instead tries to avoid repeating work that a previous request has already performed.
This frames the contribution within efficient computation and compression, although it does not compress the generator itself. It changes where a request enters an existing iterative procedure. The serving system spends storage, search, and maintenance resources in exchange for a reduction in expensive generation work.
What earlier approaches provide
The paper places diffusion alongside earlier image-generation approaches, including variational autoencoding and generative adversarial networks. Its historical discussion is brief. The relevant claim is that diffusion had become attractive for image quality and adherence to descriptions, while creating a substantial serving burden.
Latent diffusion supplies the form used by Nirvana. Rather than performing every operation directly on a full image, generation proceeds through a latent representation: an encoded state that is later decoded into pixels. The cached objects are these intermediate latent states. Their usefulness depends on how much of the final image remains adjustable at the point of retrieval.
The paper also discusses faster samplers, including DDIM, which is used in the implementation. Sampling improvements shorten the path required for an individual generation. Nirvana’s proposal addresses a different source of waste: similar requests repeatedly traversing part of that path.
Other cited techniques reduce parameter storage or execution expense through pruning, lower precision, or distillation. Progressive distillation belongs to this broader effort to make sampling less expensive. The authors describe such techniques as complementary to their serving design. That is a statement about the mechanisms addressing different costs, rather than an experimental demonstration of every possible combination.
Why ordinary retrieval is insufficient
A direct retrieval service searches for an existing image associated with a similar request and returns it. This can be very fast. Its weakness is that the distinction between the current description and its closest stored neighbor may be exactly what the user cares about.
A prompt might change an object, an action, a color, or a background. An embedding can still place it close to the old prompt. Returning the old image preserves the mismatch. Nirvana attempts to use the relationship between the requests without treating them as interchangeable.
Its central premise is that an unfinished generation has a range of possible continuations. Early in the process, substantial adaptation remains possible. Later, more properties are already committed. A serving system can therefore trade the breadth of reusable matches against the amount of computation avoided.
The paper distinguishes this use of intermediate noise from earlier caching of internal layer outputs. It cites work that had already used the term approximate caching, but argues that its cached object and continuation process are different. It also cites continuous-cache work for language prediction as part of the wider caching background. These references establish context; they do not make every cache mechanism equivalent to Nirvana’s.
What the workload reveals
The workload characterization asks whether real requests offer enough similarity to support reuse. On DiffusionDB, the authors cluster prompt embeddings with DBSCAN, varying the neighborhood setting called eps. Tight clusters lose their position among popular clusters quickly. Looser clusters remain relevant longer because they include a wider range of related prompts.
That observation matters because Nirvana does not require an exact repeated description. A cache can remain useful even after a particular wording stops being popular, provided its intermediate states can support related requests. At the same time, broad clusters cannot establish that every member can safely inherit the same amount of computation.
The authors also examine prompts within sessions, across sessions belonging to the same person, and across different users. They find similarity in all these settings. This suggests that a shared service cache can draw value from more than immediate repetition by one user.
The most important warning comes from the comparison of long and short prompts. Similar embedding scores can hide multiple changed attributes, particularly in longer descriptions. Semantic similarity is therefore a retrieval signal with known weaknesses, not a reliable statement that all visual requirements remain the same.
The method, step by step
Begin with a partially reusable generation
Consider a generation process with a fixed number of sampling steps. Starting normally means initializing noise and carrying out the entire sequence under the current prompt. Nirvana instead asks whether a previous request has left a suitable checkpoint after some of those steps.
The checkpoint already contains the effects of earlier computation. Continuing from it avoids repeating that work. The new prompt then guides the remaining sampling, attempting to alter the unfinished image so that the final result matches the current request.
The paper’s horse example makes the distinction concrete. An intermediate state associated with a brown horse can be redirected towards a white horse at K = 10, while the example at K = 15 does not achieve that change. Another illustrated continuation turns the reused state toward a bear at K = 20. These examples show that the ability to change a property is not determined solely by a universal ordering of object, color, and style.
The authors nonetheless observe broad tendencies in their experiments. Layout becomes established relatively early, followed by other image properties. They report that after approximately ∼50% of the generation sequence, attempted changes generally no longer appear in the final result. Nirvana’s default checkpoints stay within the earlier part of the process.
How Nirvana handles a new prompt
The steps in order.
The diagram represents the reuse path. At the prediction and selection stages, a request can instead go directly to complete generation. That fallback is part of the normal algorithm, instead of an exceptional recovery procedure.
The diffusion background
The paper describes a forward process that adds noise and a reverse process that removes it. Using the forward process repeatedly gives a chain of increasingly noisy states.
q(x₁:T | x₀) := ∏ₜ q(xₜ | xₜ₋₁)
Here, x₀ is the original image or representation, xₜ is its state at time t, and x₁:T denotes the sequence through T. The function q describes the forward process. The product means that the probability of the sequence is assembled from its successive transitions, under the Markov assumption that each transition depends on the preceding state.
q(xₜ | xₜ₋₁) := N(xₜ | √(1 − βₜ)xₜ₋₁, βₜI)
N denotes a Gaussian distribution. The schedule value βₜ controls the noise introduced at step t. I is the identity matrix, making βₜI the covariance in this expression. The previous state is scaled before Gaussian noise is added.
The reverse process starts from a noisy distribution and follows learned denoising transitions.
pθ(x₀:T) := p(xT) ∏ₜ pθ(xₜ₋₁ | xₜ)
The function pθ describes reverse transitions governed by learned parameters θ. The term p(xT) supplies the starting distribution. The product combines the denoising transitions leading toward the final clean state.
pθ(xₜ₋₁ | xₜ) := N(xₜ₋₁ | μ̄ₜ, β̄ₜI)
The quantities μ̄ₜ and β̄ₜ describe the reverse transition’s mean and variance in the paper’s notation. Learning makes these transitions capable of recovering image structure. Text conditioning guides the reverse process toward the requested content.
Nirvana does not introduce a new training objective for these transitions. It operates around a generator that already performs them. Its new question is whether a suitable intermediate state from another request can replace the beginning of the current trajectory.
Distinguish process time from skipped work
The paper uses N for the number of inference steps and K for how many initial steps Nirvana skips. This is separate from the xₜ notation, where the diffusion state index tracks noise level. Keeping these meanings distinct helps avoid a common confusion: K measures inherited computation, not the amount of denoising still required.
A checkpoint created after K generation steps leaves N − K steps to run. A larger K can therefore save more computation on a successful reuse. It also leaves less opportunity to correct differences between the old and new prompts.
The default implementation uses N = 50. It stores intermediate states for K values drawn from {5, 10, 15, 20, 25}. The selector chooses among those available checkpoints instead of attempting an arbitrary continuous starting position.
Encode the request and predict a useful search
The embedding generator transforms the prompt into a 768-dimensional CLIP vector. CLIP supplies a representation intended to relate text to visual content. Nirvana uses the vector both to search for prior prompts and to estimate how aggressively a retrieved state may be reused.
Before performing that search, an optional match predictor asks whether the cache is likely to contain a sufficiently close entry. This component runs locally on the CPU. Its purpose is to avoid paying remote lookup overhead for requests that will ultimately require full generation.
The implementation uses a one-class support vector classifier fitted to the prompt vectors currently stored in the database. The paper describes using SGDOneClassSVM and refreshing it as the indexed population changes. This training concerns cache coverage, not image synthesis.
False negatives cause the system to miss a potential optimization and generate from scratch. False positives cause a lookup that may prove unhelpful. These errors have different consequences, so evaluating the predictor requires more than its classification accuracy alone.
Retrieve a neighboring prompt
When the gate permits a lookup, Nirvana sends the new embedding to a vector database. The database returns a nearby cached prompt under cosine similarity, together with metadata pointing to its intermediate states.
The implementation uses Qdrant and an index based on Hierarchical Navigable Small World graphs. The paper treats the particular database as replaceable. The essential role is approximate nearest-neighbor search over prompt vectors, followed by retrieval of the relevant payload.
The intermediate states themselves reside in AWS Elastic File System. Keeping them outside the vector index separates the search representation from the heavier computational artifact. The database locates a candidate; storage supplies the state from which generation can continue.
The paper reports a default intermediate-state size of 144 KB. That figure describes the individual stored representation, whereas the complete deployed cache also includes multiple checkpoints, metadata, and database contents.
Profile the similarity-to-checkpoint rule
The cache selector is calibrated offline. For each candidate K, the authors generate images by continuing from a neighboring prompt’s stored state. They compare the resulting image quality with a threshold and identify a similarity level at which that checkpoint is acceptable in the profiling set.
The quality condition is expressed relative to generation from scratch.
Q(IcK | PcK, PQ) > α · Q(I₀ | PQ)
Q is the chosen quality function. PQ is the new query prompt, while PcK identifies the cached prompt and checkpoint used for continuation. IcK denotes the image produced through that reuse route, and I₀ denotes an image produced without the shortcut. The tolerance α controls how much quality loss is permitted.
The implementation uses CLIPScore for Q and selects α = 0.9. This makes the profiling criterion operational, but it does not turn the resulting rule into a proof that every later image satisfies every requested detail.
For DiffusionDB, the published selector chooses K = 25 when similarity exceeds 0.95. It chooses K = 20 above 0.9, K = 15 above 0.85, K = 10 above 0.75, and K = 5 above 0.65. Otherwise, K = 0 sends the request through complete generation. These are strict greater-than comparisons in the printed logic.
The rule is simple enough to inspect. It also exposes the central assumption: similarity is informative about how much adaptation remains feasible. The workload analysis and long-prompt results show why that assumption is useful but imperfect.
Express the latency trade-off
For a successful reuse, the paper separates vector search, state retrieval, and remaining GPU work.
L = lₛ + C · (N − K)/N + lᵣ
L is end-to-end latency in this analytical account. The term lₛ is vector-search time, lᵣ is retrieval time, and C is the GPU time associated with the complete generation sequence. N and K retain their meanings as total and skipped inference steps.
The expression assumes that remaining generation cost scales with the fraction of steps still executed. It is a useful systems approximation: reuse helps when the avoided generation work is larger than the extra search and retrieval expense.
For a request that searches unsuccessfully, the stated latency is lₛ + C. Storage retrieval occurs only after the system has found an eligible cached entry. A request rejected by the optional predictor avoids that search route and proceeds directly to full generation.
The paper defines h(K) as the share of cases for which a checkpoint at K can support a satisfactory continuation. Increasing K generally reduces that share.
fC = h(K) · K/N
Here, fC is the effective fractional saving in GPU computation for a fixed checkpoint choice. The expression combines how much work a successful hit saves with how often such a hit is usable. Neither a large shortcut nor a high hit rate alone is sufficient.
The authors also distinguish cumulative eligibility from the share assigned to one particular best checkpoint.
hopt(K) = h(K) − h(K′)
K′ is the next larger checkpoint in the available set. The quantity hopt(K) represents cases for which K is the largest usable choice, after cases eligible for the later checkpoint have been removed.
h(min 𝒦) = ∑K∈𝒦 hopt(K)
The set 𝒦 contains the candidate checkpoint values. Its smallest member gives the least demanding reuse option. The sum describes the overall share assigned to some usable cached checkpoint.
The optimization groups search, retrieval, and remaining computation over these checkpoint classes. The printed objective focuses on the weighted cache-use terms; its separate miss discussion remains important when interpreting total workload latency. When search and retrieval are small relative to generation, the dominant component becomes:
min L = ∑K∈𝒦 hopt(K) · C · (N − K)/N
This simplified expression captures the incentive to serve requests from later eligible checkpoints. It does not remove the quality constraint or the need to account for misses in a deployed measurement.
The paper’s illustrative linear case makes the tradeoff explicit.
h(K) = −K/KT + 1
KT is the point beyond which the cached state cannot be usefully redirected under the assumed relationship. This is an analytical example, not a fitted law asserted for every workload.
KOPT = KT/2
KOPT is the single checkpoint maximizing the saving under that linear assumption.
fCmax = KT/(4N)
The quantity fCmax is the maximum fractional compute saving for that same example. The lesson is that the shape of the reuse curve matters: if useful matches remain available farther into generation, the cache can avoid more work.
Manage the cache according to computational value
LCBFU assigns each intermediate state a score.
LCBFU-score(i) = fᵢ × Kᵢ
The item i has access frequency fᵢ and belongs to checkpoint Kᵢ. Frequency measures reuse; Kᵢ measures the generation steps avoided on each successful use. Low-scoring states are eviction candidates.
On a cache miss, complete generation produces new checkpoints for insertion. Once the storage limit has been reached, the maintainer removes low-value states before adding new ones. Its unit of eviction is an intermediate state, so a prompt can retain some checkpoints while losing others.
That partial deletion creates holes. If the selector requests a checkpoint that no longer exists, Nirvana chooses the largest surviving K that does not exceed the desired value. It therefore performs more continuation work than originally planned, preserving additional room for adaptation.
When a prompt has no surviving checkpoints, its vector entry is removed as well. Insertions and deletions are batched, and the match predictor is refreshed against the updated searchable population.
Experiments and results
Setup and workloads
The main generator is a larger Stable Diffusion-based system. The paper describes its parameter count as approximately 1.5 times that of the 2.3B-parameter SDXL reference. SDXL provides that comparison point; the evaluated generator is not simply identified as an unchanged public SDXL release.
Generation uses a 96-pixel latent space and produces images sized 768 × 768 × 3. With N = 50, the reported average generation time is 8.59 seconds on an A10g GPU. The smaller comparison generator has 860M parameters and an average time of 3.05 seconds under the stated setting.
The execution setup places generation and embedding computation on an NVIDIA A10g with 24 GB of GPU memory. Other components run on a machine with 32 CPU cores and 128 GB of memory. The implementation is written in Python with PyTorch and uses AITemplate for inference acceleration.
The paper reports that the deployed generator occupies around 80% of GPU memory at batch size 1, preventing concurrent batching in that configuration. The measured serving improvement should therefore be read in that operating regime.
DiffusionDB contains 2M images associated with 1.5M unique prompts, occupying approximately 1.6 TB. The authors remove NSFW images. System-X covers 8 weeks of production use, with over 7M images and 6.2M unique prompts, occupying roughly 5 TB.
Requests are replayed in timestamp order. Each new request is dispatched after the previous one completes, so the main workload preserves ordering but does not reproduce arbitrary concurrent arrivals. Before that replay begins, the system loads the cache using the initial 10k prompts.
What the comparisons test
The baselines address different ways to reduce serving expense. GPT-Cache uses BERT-based similarity to retrieve an existing image or otherwise generates from scratch. Pinecone uses CLIP text similarity for that retrieval decision. CRS searches using embeddings of stored images.
These retrieval systems test whether an already completed picture is an adequate answer for a related prompt. The smaller generator tests whether reducing the cost of full generation offers a better quality–efficiency compromise.
Nirvana is evaluated both with and without its match predictor. This comparison isolates a serving component that avoids unproductive searches, instead of changing the basic idea of continuing from cached intermediate states.
The quality assessment uses FID, CLIPScore, and PickScore. FID compares image distributions, with lower values preferred. CLIPScore evaluates agreement between text and image, with higher values preferred. PickScore is used as an estimate of human preference, also with higher values preferred.
These measurements answer related but distinct questions. Distributional resemblance does not ensure that a particular object count is correct. Text–image alignment does not fully describe artistic appeal. A preference estimator does not replace direct judgments by participants.
Image quality on DiffusionDB
The main DiffusionDB comparison shows Nirvana retaining substantially more text–image alignment than the retrieval baselines or the smaller generator.
DiffusionDB text–image alignment measured by CLIP Score
Nirvana stays closer to full generation than the retrieval and smaller-generator alternatives.
The numbers
| System or setting | CLIP Score |
|---|---|
| GPT-Cache | 25.84 |
| Pinecone | 24.83 |
| CRS | 24.05 |
| Small Model | 25.64 |
| Nirvana without match predictor | 28.65 |
| Nirvana (this paper) | 28.81 |
| Vanilla | 30.28 |
The corresponding DiffusionDB PickScore is 20.41 for Nirvana and 20.86 for Vanilla. Nirvana without the predictor obtains 20.35. The retrieval alternatives score below those values, consistent with the concern that a related stored image can miss details of the current request.
For FID, Nirvana obtains 4.68, while the version without the predictor obtains 4.94. GPT-Cache records 7.98, Pinecone 10.92, and CRS 8.43. The smaller generator records 11.14.
The paper computes FID against images produced by Vanilla for the same prompts. It also generates separate Vanilla sets using different seeds to establish a reference for variability without changing the generator. That reference spans 6.12-6.92 on DiffusionDB.
Nirvana’s lower FID relative to that reference is evidence of close distributional resemblance under the evaluation. The authors interpret it strongly, but a careful reading should stop short of treating FID as proof that observers cannot distinguish the systems or that every generated picture is equally correct.
Image quality on System-X
System-X supplies a second workload with the same broad ordering. Nirvana records CLIPScore 29.12 and PickScore 20.38, compared with Vanilla’s 30.4 and 20.71. The version without the predictor records CLIPScore 28.94 and PickScore 20.31.
Its FID is 4.15, while the version without the predictor obtains 4.48. The Vanilla reference across seeds spans 5.42-6.12. GPT-Cache, Pinecone, and CRS obtain FID values of 8.15, 10.12, and 8.38 respectively.
The second workload therefore supports the claim that the result is not confined to one public prompt collection. However, System-X is proprietary, and the paper presents most detailed analyses using DiffusionDB. Independent reproduction of the private workload is consequently outside what the reported setup makes available.
Human judgments
The participant study asks whether an image adequately expresses its associated prompt. Each participant sees 15 randomly ordered prompt–image pairs. The allocation includes 5 pairs from each of the compared generation routes, and a prompt is not repeated within a participant’s session.
The study involves 60 participants and draws from around 1000 randomly chosen DiffusionDB prompts. Participants answer Yes or No and may explain a negative judgment.
Participant approval of prompt–image agreement in the user study
Continued generation receives judgments much closer to Vanilla than direct cache retrieval does.
The numbers
| System or setting | positive judgments % |
|---|---|
| GPT-Cache | 31 |
| Nirvana (this paper) | 79 |
| Vanilla | 86 |
These judgments support the practical importance of reconditioning. The related cached image is frequently inadequate as the final response, while further generation can accommodate much of the new request.
They also preserve a visible gap between Nirvana and Vanilla. The study supports a favorable tradeoff, not complete equality. The paper does not report uncertainty intervals for these approval figures or a formal perceptual-equivalence analysis.
Among the optional explanations for negative judgments, the authors report that approximately ∼12% of negative responses included reasons. Of those explanations, 80% concerned GPT-Cache outputs. This is useful qualitative evidence, but it is conditioned on which participants chose to provide explanations.
Computation, latency, and throughput
Nirvana reports an overall cache hit rate of 88% and GPU compute savings of 21%. These quantities should not be confused. Many successful reuses occur at earlier checkpoints and therefore avoid only part of the work.
The checkpoint analysis illustrates this explicitly. At K = 25, the potential saving on an eligible request is 50%, but the reported hit rate is 8%, yielding actual savings of 4% for that contribution. The authors provide these values to show why a large shortcut cannot simply be applied to the entire workload.
The end-to-end latency reduction is 19.8%. This is smaller than the reported GPU saving because the reuse path includes search and retrieval overhead. The decomposition identifies vector search and state retrieval as the main additional latency components.
Throughput improves as well. The evaluation reports approximately ∼1.28 times Vanilla’s throughput both with the bounded LCBFU cache and with a continually growing cache. Elsewhere, the paper summarizes the improvement as 27%. These are the paper’s reported descriptions; they should not be converted into a newly calculated reconciliation.
The bounded comparison uses 1.5 million cached intermediate items. Similar throughput under the growing-cache condition suggests that the proposed retention policy preserves much of the useful reuse opportunity in this experiment.
Monetary cost
The cost analysis includes generation infrastructure, vector search, and state storage. For its GPU-cost estimate, the paper uses an AWS hourly price of $8.144. It assigns $0.12 per hour to the vector database and $0.09 per hour to EFS under its stated storage assumptions.
The reported result is a 19% reduction in amortized cost relative to Vanilla. Including supporting services matters: reduced GPU work would be an incomplete economic result if the index and storage consumed an equal or greater amount elsewhere.
This remains a deployment-specific calculation. The figures depend on the chosen instance, pricing assumptions, throughput, cache population, and storage access pattern. The demonstrated principle is that auxiliary infrastructure can still leave a net saving; the exact percentage is not a universal property of approximate caching.
What the ablations show
The predictor changes more than average lookup overhead
The comparison with Nirvana without the match predictor examines whether avoiding unlikely searches improves serving behavior. The paper reports that the predictor reduces tail latency and allows a substantial share of requests to incur almost no cache-related overhead.
It also changes which requests use cached states. Predicted misses are generated from scratch, so some opportunities for reuse are deliberately abandoned. This explains why the predictor can improve quality slightly while sacrificing some efficiency.
The final quality table reports classifier precision 0.96 and recall 0.95. Another passage describes the operational choice as P = 96 and R = 95. The relevant mechanism is the tradeoff: a more restrictive gate can avoid unhelpful searches while also missing usable cached states.
The paper’s simplified overhead expression combines hit rate and predictor precision. That provides intuition about reducing wasted lookups, but it is not a complete confusion-matrix analysis. The experimental latency distribution is the stronger evidence for the predictor’s practical effect.
Different embeddings produce different reuse opportunities
The embedding comparison is especially useful because quality remains relatively similar while cache utility changes. This shows that representation choice should be judged against the serving objective, not only a downstream quality score.
Reported fractional compute savings with different retrieval embeddings
CLIP text embeddings deliver the largest compute saving in this comparison.
The numbers
| System or setting | fractional compute savings |
|---|---|
| BERT for query and cache | 0.16 |
| CLIP image for cache | 0.18 |
| CLIP text for query and cache (this paper) | 0.23 |
The corresponding hit rates are 0.77 for BERT, 0.84 for the image-embedding configuration, and 0.93 for CLIP text. Their FID values are 4.53, 4.85, and 4.94 respectively.
Those quality values prevent a simplistic conclusion that the representation with the best individual quality metric must be the most useful cache key. The CLIP text choice yields more reusable opportunities under the profiled continuation procedure.
This comparison is specific to the evaluated configurations. It does not establish that CLIP is the best representation for every generator, prompt distribution, or quality requirement.
Eviction should preserve computational benefit
The cache-policy experiments compare LCBFU with FIFO, LRU, and LFU under matching workload conditions. The authors report that LCBFU achieves greater compute savings while keeping hit rate comparable to the recency- and frequency-based alternatives.
This supports the policy’s main argument. An eviction rule can retain many frequently used objects and still discard states that would save more total work. The relevant unit of value is not simply a successful lookup.
The image-quality comparison is reassuring but narrower. With a 1500 GB cache, LCBFU obtains FID 4.94, CLIPScore 28.65, and PickScore 20.41. LFU obtains 4.98, 28.61, and 20.42 on those respective metrics. LRU records 4.82, 28.54, and 20.38.
No one policy dominates every quality measure. The paper’s interpretation is that output quality remains broadly stable, allowing eviction to focus on computational savings. The numerical compute-savings cells for the policy comparison are not recoverable from the displayed text, so precise policy gains should not be invented.
Long prompts reveal disagreement between metrics
For the prompt-length analysis, the paper defines short prompts as those containing fewer than 15 words. Short prompts obtain FID 7.96, whereas long prompts obtain 11.48. That comparison supports the authors’ concern about lengthy descriptions.
CLIPScore moves differently: short prompts obtain 28.48 and long prompts 28.96. The analysis therefore does not show that every metric becomes worse with length. It shows a quality difference under FID alongside a contrary ordering under text–image alignment.
This matters because CLIP participates in both retrieval and quality assessment. A representation may assign high similarity while overlooking a changed attribute. An alignment score based on a related representation may also be insensitive to some of the resulting errors.
The ablation consequently reinforces the need for multiple measurements and concrete inspection. It does not justify replacing every quality question with a single embedding-derived score.
Missing checkpoints reduce savings conservatively
LCBFU can evict one checkpoint while retaining another for the same prompt. The paper reports that the resulting holes affect 4-5% of prompts and describes their performance impact as small.
The response to a hole is deliberately conservative: use an earlier surviving state. That preserves additional generation work rather than selecting a later, less adaptable checkpoint merely because it exists.
The analysis supports a practical maintenance choice. Nirvana does not regenerate every missing state or attempt to eliminate all fragmentation. It tolerates some missed savings to avoid the cost and complexity of rebuilding checkpoints.
Component timing explains where the remaining overhead lies
The latency decomposition identifies the vector database and EFS retrieval as the main reuse overheads. This connects the performance result to the architecture: the shortcut removes GPU iterations but introduces distributed data access.
The paper’s measurements place search on the order of 100 ms and complete generation on the order of 10 s in the discussed setting. That separation makes reuse attractive. A different balance could make search overhead much more consequential.
The decomposition is therefore more informative than a speedup figure alone. It identifies which assumptions would need remeasurement when the generator becomes faster, the database moves farther away, or the storage system changes.
Limitations
Limits the authors explicitly discuss
The authors identify image diversity as a risk. Reusing the same intermediate states can steer successive outputs toward familiar trajectories, especially when incoming prompts are very similar. Good prompt agreement does not on its own establish that users receive a suitably varied set of images.
They suggest changing the denoising seed after retrieval and report that this can help when K < 35. They also propose allowing an ε fraction of requests to use complete generation when reuse becomes too concentrated. These are mitigation directions, not a reported long-running diversity guarantee.
A second stated limitation concerns the underlying generation procedure. Nirvana benefits from a substantial iterative path whose beginning can be inherited. If a different family of generators produces satisfactory images without such a long sequence, there is less redundant work for this cache to remove.
The authors also acknowledge representation weaknesses for long prompts. High embedding similarity can conceal changed nouns, modifiers, counts, or actions. Their cache selector reduces risk through profiling, but it cannot recover distinctions that the similarity signal fails to express.
They discuss workload changes as well. When requests become less like the cache population, Nirvana should use earlier checkpoints or fall back to complete generation. The intended consequence is reduced savings rather than forced reuse. That is a design response to distribution change, not proof that every shift preserves every aspect of quality.
Limits of the quality evidence
The strongest careful-reader limitation is that the quality gate is empirical. A threshold obtained from profiling examples does not establish a universal implication from similarity to safe continuation.
The use of CLIPScore is reasonable for measuring text–image agreement, but it covers only part of what users may require. A picture can capture a scene’s general subject while missing a count, spatial relationship, action, or secondary constraint.
There is also partial dependence between retrieval and evaluation. CLIP text embeddings guide the search, while CLIPScore helps determine the permitted reuse depth. Other metrics and the participant study provide additional evidence, but the shared representation remains relevant when interpreting apparent agreement.
FID measures a relationship between collections of images. It cannot establish that every output matches its prompt, and a low value does not demonstrate perceptual indistinguishability on its own. The paper’s comparison with Vanilla’s seed variability is informative, but its strongest verbal interpretation exceeds what a distributional score alone can prove.
The human study asks a useful practical question, yet it is not an equivalence trial. It reports positive judgments under a particular presentation and prompt sample. The paper does not provide the uncertainty analysis needed to turn the observed proximity into a general claim of equal quality.
Limits of the workload and deployment
The public and private datasets strengthen the evaluation, but the detailed analyses are concentrated on DiffusionDB. System-X cannot be independently reconstructed from the paper’s description alone.
The cache is preloaded for the main workload experiment. That setup measures an operating system with an initial reusable population. It should not be read as the experience of an empty deployment before any useful checkpoints exist.
Request ordering is preserved, but dispatch is sequential: the next request waits for the previous one to finish. This supports measurements of per-request behavior and ordered cache evolution. It does not establish queueing performance under arbitrary bursts, concurrency, or multi-tenant contention.
The generation configuration also lacks concurrent batching because of its reported memory occupancy. A deployment where batching is effective could change the relative benefit of skipping work for individual requests. The paper does not provide that comparison.
Cloud cost is another conditional result. Search, storage, and generation prices can have different proportions in another environment. The reported economic saving demonstrates feasibility under the chosen assumptions, instead of a fixed return from adopting the architecture.
Limits of the analytical account
The latency expressions explain the main tradeoff, but real serving behavior depends on more than skipped iterations. Predictor mistakes, variable retrieval times, cache holes, maintenance traffic, and miss handling all influence the outcome.
The predictor discussion particularly needs careful interpretation. Precision alone does not describe all the opportunities skipped or searches wasted. Recall matters for missed reuse, and the workload’s prevalence of useful matches affects how the classifier translates into system behavior.
The printed optimization focuses on checkpoint classes and their continuation costs. Its separate discussion of cache misses should remain part of any implementation-level accounting. Treating the abbreviated objective as a complete universal latency formula would obscure the requests that still require full generation.
Finally, LCBFU’s score assumes that skipped steps are a useful measure of computational benefit. That is appropriate for the fixed-step configuration studied. It does not automatically account for heterogeneous state sizes, generators with different per-step costs, or changing retrieval expenses.
These limitations do not negate the central result. They define its scope: useful intermediate reuse exists in the measured workloads, and a serving system can exploit it while retaining much of the quality of full generation. Extending that result requires repeating the compatibility, workload, and cost measurements in the new setting.
What came after
No subsequent citing studies are established in the available record. There is therefore no supported basis for naming later extensions, assigning them performance gains, or claiming that Nirvana’s particular design became a standard serving approach.
The paper itself leaves several concrete questions open. One is whether reuse can remain diverse over long operation without surrendering too much computation. Another is whether a richer compatibility test can notice changed attributes that aggregate prompt similarity misses. A further question is how the architecture behaves when generation becomes much faster and search or retrieval consumes a larger part of the request budget.
Those are research directions suggested by the method and its limitations, rather than documented outcomes of later work. The paper’s demonstrated contribution remains specific and useful: previous computation can be valuable even when its final answer is unsuitable, provided the retained state is still adaptable and the system measures how much work it can safely inherit.
Cite
Cite as Shubham Agarwal, Subrata Mitra, Sarthak Chakraborty, Srikrishna Karanam, Koyel Mukherjee and Shiv Saini. 2023. Approximate Caching for Efficiently Serving Diffusion Models. arXiv:2312.04429.
@misc{agarwal2023approximate,
title = {{Approximate Caching for Efficiently Serving Diffusion Models}},
author = {Shubham Agarwal, Subrata Mitra, Sarthak Chakraborty, Srikrishna Karanam, Koyel Mukherjee and Shiv Saini},
year = {2023},
doi = {10.48550/arxiv.2312.04429},
eprint = {2312.04429},
archivePrefix = {arXiv},
url = {https://doi.org/10.48550/arxiv.2312.04429}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/agarwal-2023-approximate-caching-efficiently-serving-diffusion/