Skip to content

vllm.v1.kv_offload.tiering.spec

TieringOffloadingSpec: Spec for multi-tier KV cache offloading.

This spec creates a TieringOffloadingManager with a CPU primary tier and configurable secondary tiers (e.g., Storage, Network).

Configuration via kv_connector_extra_config
  • cpu_bytes_to_use: (required) Bytes to allocate for CPU primary tier
  • block_size: (optional) Tokens per offloaded chunk (default: GPU block size)
  • eviction_policy: (optional) Primary tier eviction policy: built-in "lru"/ "arc", or the name of a policy registered via CachePolicyFactory, or an out-of-tree CachePolicy class name paired with cache_policy_module_path (default: "lru")
  • cache_policy_module_path: (optional) Python import path to load eviction_policy from when it names an out-of-tree CachePolicy not registered via CachePolicyFactory
  • secondary_tiers: (optional) List of secondary tier configurations Each secondary tier config is a dict with:
    • type: (required) Type of secondary tier (e.g., "example", "fs", "p2p", "obj"), or the class name of an out-of-tree SecondaryTierManager paired with module_path.
    • module_path: (optional) Python import path to load 'type' from when it names an out-of-tree SecondaryTierManager not registered via SecondaryTierFactory.register_tier()
    • Additional tier-specific parameters are passed directly to the tier constructor. See each tier's documentation for supported parameters.
  • mirror_timeout_s: (optional) CPU region mirror transfer timeout when secondary tiers span several nodes (see docs/features/kv_offloading_usage.md)

Example configuration: { "cpu_bytes_to_use": 10737418240, # 10 GB "block_size": 16, "eviction_policy": "lru", "secondary_tiers": [ { "type": "example", "custom_param": 67 } ] }

Example out-of-tree tier configuration: { "cpu_bytes_to_use": 10737418240, "secondary_tiers": [ { "type": "MyCustomTier", "module_path": "my_package.my_module", "custom_param": "value" } ] }

Classes:

TieringOffloadingSpec

Bases: CPUOffloadingSpec

Spec for multi-tier KV cache offloading.

Creates a TieringOffloadingManager with: - Primary tier: CPU (LRU or ARC eviction policy) - Secondary tiers: Configurable via extra_config

The CPU primary tier has direct GPU access and serves as the gateway for all GPU↔offload operations. Secondary tiers cannot directly access GPU memory and must transfer data through the primary tier.

Methods:

Source code in vllm/v1/kv_offload/tiering/spec.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
class TieringOffloadingSpec(CPUOffloadingSpec):
    """Spec for multi-tier KV cache offloading.

    Creates a TieringOffloadingManager with:
    - Primary tier: CPU (LRU or ARC eviction policy)
    - Secondary tiers: Configurable via extra_config

    The CPU primary tier has direct GPU access and serves as the gateway for
    all GPU↔offload operations. Secondary tiers cannot directly access GPU
    memory and must transfer data through the primary tier.
    """

    BLOCK_SIZE_ALIGNMENT = SharedOffloadRegion.BLOCK_SIZE_ALIGNMENT

    @classmethod
    @override
    def build_metric_definitions(
        cls, extra_config: dict[str, Any]
    ) -> dict[str, OffloadingMetricMetadata]:
        metrics = super().build_metric_definitions(extra_config)
        metrics[TieringOffloadingMetrics.LOOKUP_SYNC_DELAY] = (
            OffloadingHistogramMetadata(
                documentation=(
                    "Histogram of blocking time spent in a per-chunk tier lookup "
                    "that resolved as a hit or miss, labeled by tier, in seconds."
                ),
                labelnames=(TIER_LABEL,),
                buckets=(
                    0.00001,
                    0.00005,
                    0.0001,
                    0.0005,
                    0.001,
                    0.005,
                    0.01,
                    0.05,
                    0.1,
                    0.5,
                    1,
                ),
            )
        )
        metrics[TieringOffloadingMetrics.LOOKUP_ASYNC_DELAY] = (
            OffloadingHistogramMetadata(
                documentation=(
                    "Histogram of wall-clock time from a per-chunk tier lookup "
                    "first returning retry until that same tier lookup resolves "
                    "as a hit or miss, labeled by tier, in seconds."
                ),
                labelnames=(TIER_LABEL,),
                buckets=(
                    0.0001,
                    0.0005,
                    0.001,
                    0.005,
                    0.01,
                    0.05,
                    0.1,
                    0.5,
                    1,
                    5,
                    10,
                ),
            )
        )
        metrics[TieringOffloadingMetrics.READ_BYTES] = OffloadingCounterMetadata(
            documentation=(
                "Total bytes read from secondary tiers into the primary tier, "
                "labeled by tier."
            ),
            labelnames=(TIER_LABEL,),
        )
        metrics[TieringOffloadingMetrics.READ_TIME] = OffloadingCounterMetadata(
            documentation=(
                "Total time spent reading from secondary tiers into the primary "
                "tier, in seconds, labeled by tier. Tiers that do not report "
                "per-job transfer time have no series here. Use "
                "vllm:kv_offload_tiering_promotion_latency_seconds for "
                "tier-independent promotion timing."
            ),
            labelnames=(TIER_LABEL,),
        )
        metrics[TieringOffloadingMetrics.WRITE_BYTES] = OffloadingCounterMetadata(
            documentation=(
                "Total bytes written from the primary tier to secondary tiers, "
                "labeled by tier."
            ),
            labelnames=(TIER_LABEL,),
        )
        metrics[TieringOffloadingMetrics.WRITE_TIME] = OffloadingCounterMetadata(
            documentation=(
                "Total time spent writing from the primary tier to secondary "
                "tiers, in seconds, labeled by tier. Tiers that do not report "
                "per-job transfer time have no series here."
            ),
            labelnames=(TIER_LABEL,),
        )
        metrics[TieringOffloadingMetrics.PROMOTION_JOB_FAILURES] = (
            OffloadingCounterMetadata(
                documentation=(
                    "Number of failed secondary-tier promotion jobs, labeled by tier."
                ),
                labelnames=(TIER_LABEL,),
            )
        )
        metrics[TieringOffloadingMetrics.CASCADE_JOB_FAILURES] = (
            OffloadingCounterMetadata(
                documentation=(
                    "Number of failed secondary-tier cascade jobs, labeled by tier."
                ),
                labelnames=(TIER_LABEL,),
            )
        )
        metrics[TieringOffloadingMetrics.CHUNK_QUERIES] = OffloadingCounterMetadata(
            documentation=(
                "Number of chunk lookup queries sent to a tier, labeled by tier."
            ),
            labelnames=(TIER_LABEL,),
        )
        metrics[TieringOffloadingMetrics.CHUNK_HITS] = OffloadingCounterMetadata(
            documentation="Number of chunk lookup hits in a tier, labeled by tier.",
            labelnames=(TIER_LABEL,),
        )
        metrics[TieringOffloadingMetrics.PROMOTION_ALLOCATION_FAILURES] = (
            OffloadingCounterMetadata(
                documentation=(
                    "Number of promotion attempts that failed because the "
                    "primary tier could not allocate space."
                ),
            )
        )
        metrics[TieringOffloadingMetrics.PRIMARY_WRITE_USAGE_PERC] = (
            OffloadingGaugeMetadata(
                documentation=(
                    "Current fraction of primary-tier space used by writes from "
                    "secondary tiers, labeled by tier."
                ),
                labelnames=(TIER_LABEL,),
            )
        )
        metrics[TieringOffloadingMetrics.PRIMARY_READ_USAGE_PERC] = (
            OffloadingGaugeMetadata(
                documentation=(
                    "Current fraction of primary-tier space used by reads to "
                    "secondary tiers, labeled by tier."
                ),
                labelnames=(TIER_LABEL,),
            )
        )
        metrics[TieringOffloadingMetrics.ACTIVE_PROMOTION_JOBS] = (
            OffloadingGaugeMetadata(
                documentation=(
                    "Number of active secondary-tier promotion jobs, labeled by tier."
                ),
                labelnames=(TIER_LABEL,),
            )
        )
        metrics[TieringOffloadingMetrics.ACTIVE_CASCADE_JOBS] = OffloadingGaugeMetadata(
            documentation=(
                "Number of active secondary-tier cascade jobs, labeled by tier."
            ),
            labelnames=(TIER_LABEL,),
        )
        metrics[TieringOffloadingMetrics.DEFERRED_RELEASE_CHUNKS] = (
            OffloadingGaugeMetadata(
                documentation=(
                    "Number of primary-tier chunks of failed promotions whose release "
                    "to the free pool is deferred until the tier confirms its I/O can "
                    "no longer write to them, labeled by tier."
                ),
                labelnames=(TIER_LABEL,),
            )
        )
        metrics[TieringOffloadingMetrics.DEFERRED_RELEASE_HOLD] = (
            OffloadingHistogramMetadata(
                documentation=(
                    "Histogram of how long a failed promotion's primary-tier "
                    "chunks were held before their deferred release completed, "
                    "observed at release, labeled by tier, in seconds."
                ),
                labelnames=(TIER_LABEL,),
                buckets=(0.01, 0.05, 0.1, 0.5, 1, 2.5, 5, 10, 20, 30, 60, 120),
            )
        )
        metrics[TieringOffloadingMetrics.PROMOTION_LATENCY] = (
            OffloadingHistogramMetadata(
                documentation=(
                    "Histogram of per-job latency for secondary-tier promotion "
                    "attempts, measured from job creation until the tiering "
                    "manager observes completion so that tier queueing is "
                    "included, labeled by tier and result, in seconds. Includes "
                    "failed attempts."
                ),
                labelnames=(TIER_LABEL, "result"),
                buckets=(
                    0.005,
                    0.01,
                    0.025,
                    0.05,
                    0.1,
                    0.25,
                    0.5,
                    1,
                    2.5,
                    5,
                    10,
                    30,
                    60,
                ),
            )
        )

        for tier_config, tier_cls in cls._get_secondary_tiers(extra_config):
            metrics.update(tier_cls.build_metric_definitions(tier_config))

        metrics[TieringOffloadingMetrics.BACKPRESSURE_STORE_LATENCY_EMA] = (
            OffloadingGaugeMetadata(
                documentation=(
                    "Exponential moving average of store latency "
                    "for back-pressure detection, in s/MiB."
                ),
                labelnames=(TIER_LABEL,),
            )
        )
        metrics[TieringOffloadingMetrics.BACKPRESSURE_STORES_DROPPED] = (
            OffloadingCounterMetadata(
                documentation=(
                    "Number of store operations dropped due to "
                    "back-pressure on a secondary tier."
                ),
                labelnames=(TIER_LABEL,),
            )
        )
        metrics[TieringOffloadingMetrics.BACKPRESSURE_BLOCKS_DROPPED] = (
            OffloadingCounterMetadata(
                documentation=(
                    "Number of blocks dropped due to back-pressure on a secondary tier."
                ),
                labelnames=(TIER_LABEL,),
            )
        )

        return metrics

    def __init__(self, config: OffloadingConfig):
        super().__init__(config)
        # Redeclare for mypy: parent sets this but `--follow-imports skip` hides it
        self._manager: OffloadingManager | None = None

        # Parse secondary tier configurations
        self.secondary_tier_configs = self.extra_config.get("secondary_tiers", [])
        if not isinstance(self.secondary_tier_configs, list):
            raise ValueError("secondary_tiers must be a list of tier configurations")

        # Pause between tier-poll rounds for tiers that need servicing
        # between engine steps. Zero or negative disables the thread, which
        # restores per-step servicing.
        self.tier_poll_interval_s = float(
            self.extra_config.get("tier_poll_interval_s", DEFAULT_TIER_POLL_INTERVAL_S)
        )

        # Backpressure config is merged field-by-field in priority order
        # (highest first):
        #   1. Per-tier ``backpressure`` dict in the tier config
        #   2. Top-level ``backpressure`` in kv_connector_extra_config
        # Merging per field (rather than per whole dict) means a partial
        # tier override still inherits missing fields from the top-level
        # default, so the resolved dict reaching the factory is complete.
        # Within each tier's resolved dict, tier-type-aware water marks
        # are filled in last so a bare ``"backpressure": {}`` picks up
        # sensible thresholds for the storage medium.
        bp_defaults = self.extra_config.get("backpressure")

        for tier_cfg in self.secondary_tier_configs:
            tier_override = tier_cfg.get("backpressure")
            # Overlay from lowest to highest precedence so higher-precedence
            # fields win while lower-precedence ones fill in the gaps.
            merged: dict[str, Any] = {}
            for source in (bp_defaults, tier_override):
                if source:
                    merged.update(source)
            # Only set a resolved dict when at least one source contributed
            # (or an explicit ``backpressure`` key was present, e.g. ``{}``),
            # so tiers without any backpressure config stay unconfigured.
            if merged or "backpressure" in tier_cfg:
                tier_cfg["backpressure"] = merged

        # Scheduler-side mmap (rank=None); kept for cleanup
        self._scheduler_mmap: SharedOffloadRegion | None = None

        # Set by create_worker when canonical_layout is enabled: True when
        # every layer's canonical bytes are parallelism-agnostic (portable),
        # False when some layers use the opaque fallback (exact-topology only)
        self.all_layers_portable: bool | None = None

        # engine_id is unique per DP replica (suffixed with _dp{rank} in both
        # the Ray and multiprocessing paths), so it names a per-replica offload
        # region.
        self._engine_id = config.engine_id

    @override
    def get_manager(self) -> OffloadingManager:
        """Get the TieringOffloadingManager.

        Creates a TieringOffloadingManager with:
        - Primary tier: CPU (LRU or ARC)
        - Secondary tiers: As configured in extra_config

        Returns:
            TieringOffloadingManager instance

        """
        if not self._manager:
            if int(self.extra_config.get("store_threshold", 0)) >= 2:
                raise ValueError(
                    "store_threshold is not supported for TieringOffloadingSpec"
                )

            scheduler_mmap: SharedOffloadRegion | None = None
            primary_tier: CPUPrimaryTierOffloadingManager | None = None
            secondary_tiers = []
            try:
                # Create scheduler-side SharedOffloadRegion (rank=None) so the
                # primary tier can eagerly create a memoryview over _base.
                scheduler_mmap = SharedOffloadRegion(
                    engine_id=self._engine_id,
                    num_chunks=self.num_chunks,
                    rank=None,
                    kv_bytes_per_chunk=self.kv_bytes_per_chunk,
                    cpu_page_size=self.cpu_page_size_per_worker,
                )
                self._scheduler_mmap = scheduler_mmap
                if (
                    self.secondary_tier_configs
                    and scheduler_mmap.created_file
                    and self.config.parallel.world_size > 1
                ):
                    # Secondary tiers read the region worker rank 0 created,
                    # into which the mirror also copies remote slots.
                    raise RuntimeError(
                        "The tiering scheduler created the shared CPU region "
                        "instead of joining its workers' region: the engine "
                        "core must share a node with worker rank 0."
                    )

                # Create primary tier (CPU-based)
                primary_tier = CPUPrimaryTierOffloadingManager(
                    num_chunks=self.num_chunks,
                    cache_policy=self.eviction_policy,
                    cache_policy_module_path=self.cache_policy_module_path,
                    enable_events=self.kv_events_config.enable_kv_cache_events,
                    mmap_region=scheduler_mmap,
                    info=self.cpu_info,
                )

                # Create secondary tiers
                primary_kv_view = primary_tier.get_kv_memoryview()
                for i, tier_config in enumerate(self.secondary_tier_configs):
                    tier = SecondaryTierFactory.create_secondary_tier(
                        tier_config, primary_kv_view, self
                    )
                    secondary_tiers.append(tier)
                    logger.info(
                        "Created secondary tier #%d (%s)",
                        i,
                        tier.tier_type,
                    )

                # Create TieringOffloadingManager. GPU↔CPU transfers use the inherited
                # get_worker(). Secondary tier transfers are handled by the
                # secondary tier managers and need no additional workers here.
                tiering_manager = TieringOffloadingManager(
                    primary_tier=primary_tier,
                    secondary_tiers=secondary_tiers,
                    tier_poll_interval_s=self.tier_poll_interval_s,
                )
                self._manager = tiering_manager
            except Exception:
                for tier in reversed(secondary_tiers):
                    try:
                        tier.shutdown()
                    except Exception:
                        logger.exception(
                            "Failed to shut down secondary tier during "
                            "initialization cleanup"
                        )
                if primary_tier is not None:
                    try:
                        primary_tier.shutdown()
                    except Exception:
                        logger.exception(
                            "Failed to shut down primary tier during "
                            "initialization cleanup"
                        )
                elif scheduler_mmap is not None:
                    try:
                        scheduler_mmap.cleanup()
                    except Exception:
                        logger.exception(
                            "Failed to clean up scheduler mmap during "
                            "initialization cleanup"
                        )
                self._scheduler_mmap = None
                raise

            logger.info(
                "Created TieringOffloadingManager with primary tier "
                "(%s, %s chunks) and %s secondary tier(s)",
                self.eviction_policy,
                self.num_chunks,
                len(secondary_tiers),
            )

        return self._manager

    @classmethod
    @override
    def config_info_keys(cls, extra_config: dict[str, Any]) -> tuple[str, ...]:
        """Return TIER_LABEL and the label names of all tiers, with no repeat."""
        # dict.fromkeys() keeps one copy of a name that two tier types share.
        keys = dict.fromkeys(super().config_info_keys(extra_config))
        keys[TIER_LABEL] = None
        for tier_config, tier_cls in cls._get_secondary_tiers(extra_config):
            tier_keys = tier_cls.config_info_keys(tier_config)
            assert TIER_LABEL not in tier_keys, (
                f"{tier_cls.__name__} must not declare the reserved label "
                f"{TIER_LABEL!r}"
            )
            keys.update(dict.fromkeys(tier_keys))
        return tuple(keys)

    @classmethod
    @override
    def registers_kv_cache_across_nodes(cls, extra_config: dict[str, Any]) -> bool:
        """With secondary tiers, workers off the head node register their GPU
        KV cache with NIXL to mirror their CPU region slots (create_worker)."""
        return bool(extra_config.get("secondary_tiers"))

    @classmethod
    def _get_secondary_tiers(
        cls, extra_config: dict[str, Any]
    ) -> list[tuple[dict[str, Any], type[SecondaryTierManager]]]:
        """Resolve every configured secondary tier to its manager class.

        Args:
            extra_config: kv_connector_extra_config of this instance.

        Returns:
            One (tier config, tier class) pair for each secondary tier, in
            configuration order. That order sets the tier index.

        Raises:
            ValueError: If secondary_tiers is not a list.

        """
        secondary_tier_configs = extra_config.get("secondary_tiers", [])
        if not isinstance(secondary_tier_configs, list):
            raise ValueError("secondary_tiers must be a list of tier configurations")

        tiers = []
        for tier_config in secondary_tier_configs:
            assert isinstance(tier_config, dict)
            tier_cls = SecondaryTierFactory.get_tier_class(tier_config)
            tiers.append((tier_config, tier_cls))
        return tiers

    @override
    def _uses_shared_region(self) -> bool:
        # Tiering always allocates on the shared region (every platform), so the
        # replicated-layout gate must not be narrowed by the CPU spec's
        # CUDA-alike check.
        return True

    @override
    def create_worker(self, kv_caches: CanonicalKVCaches) -> OffloadingWorker:
        topology = None
        if self.secondary_tier_configs and self.config.parallel.world_size > 1:
            topology = self._mirror_topology()
        worker_mmap: SharedOffloadRegion | None = None
        worker: CPUOffloadingWorker | None = None
        error: Exception | None = None
        # Off the head node the mirror moves GPU blocks straight to the head
        # region, so no CPU memory is allocated there.
        if topology is None or topology.on_head:
            try:
                worker_mmap = SharedOffloadRegion(
                    engine_id=self._engine_id,
                    num_chunks=self.num_chunks,
                    rank=0 if self.replicated_layout else self.config.parallel.rank,
                    kv_bytes_per_chunk=self.kv_bytes_per_chunk,
                    cpu_page_size=self.cpu_page_size_per_worker,
                )
                if self.config.canonical_layout:
                    self._validate_canonical_refs(kv_caches)
                worker = CPUOffloadingWorker(
                    kv_caches=kv_caches,
                    blocks_per_chunk=self.blocks_per_chunk,
                    num_cpu_chunks=self.num_chunks,
                    mmap_region=worker_mmap,
                    canonical_layout=self.config.canonical_layout,
                )
            except Exception as e:
                if worker_mmap is not None:
                    worker_mmap.cleanup()
                if topology is None:
                    raise
                error = e
        if topology is None:
            assert worker is not None
            return worker
        # Every rank reaches the collectives below, even after a failure.
        try:
            gather_construction_errors(topology, error)
            return attach_region_mirror(
                worker,
                worker_mmap,
                kv_caches,
                self.blocks_per_chunk,
                SlotLayout(
                    num_chunks=self.num_chunks,
                    row_stride=self.kv_bytes_per_chunk,
                    size=self.cpu_page_size_per_worker,
                ),
                topology,
                self._engine_id,
                timeout_s=self._mirror_timeout_s(),
                remaps_kv_cache=self.config.remaps_kv_cache,
            )
        except BaseException:
            if worker is not None:
                worker.shutdown()
            raise

    def _mirror_topology(self) -> MirrorTopology | None:
        """Locate this worker when its engine spans nodes, or return None.

        Collective over the engine's TP, PP and PCP groups, then over its
        workers if they span nodes. Raises for the setups the mirror cannot
        serve.
        """
        from vllm.distributed.parallel_state import get_world_group

        if not _workers_span_nodes():
            return None
        parallel = self.config.parallel
        if (
            parallel.data_parallel_size > 1
            or get_world_group().world_size != parallel.world_size
        ):
            # The mirror locates workers in the world group, which then holds
            # every replica, external ones (torchrun launchers) included.
            raise NotImplementedError(
                "TieringOffloadingSpec secondary tiers support engines whose "
                "workers span several nodes only without data parallelism and "
                "without other engines in the same world group (external_launcher)."
            )
        if self.config.canonical_layout:
            raise ValueError(
                "canonical_layout interleaves every rank's bytes in one row "
                "area and cannot be mirrored across nodes; remove "
                "canonical_layout from kv_connector_extra_config."
            )
        if any(
            _is_kvcr_tier(SecondaryTierFactory.get_tier_class(tier))
            for tier in self.secondary_tier_configs
        ):
            # KVCR keys carry no slot_layout namespace, so rows stored across
            # nodes before the mirror would still hit.
            raise ValueError(
                "The kvcr secondary tier does not support engines whose "
                "workers span several nodes."
            )
        if self.kv_bytes_per_chunk // self.cpu_page_size_per_worker < (
            parallel.world_size
        ):
            raise ValueError(
                "The head node's CPU region must hold every worker's slot to "
                "mirror it across nodes; remove replicated_layout from "
                "kv_connector_extra_config."
            )
        topology = mirror_topology()
        assert topology is not None
        return topology

    def _mirror_timeout_s(self) -> float:
        timeout_s = float(self.extra_config.get("mirror_timeout_s", 30))
        if not (math.isfinite(timeout_s) and timeout_s > 0):
            raise ValueError(
                f"mirror_timeout_s must be positive and finite, got {timeout_s}"
            )
        return timeout_s

    def _validate_canonical_refs(self, kv_caches: CanonicalKVCaches) -> None:
        """Require a mapping on every ref and record layer portability.

        Fails loudly rather than persist direct-layout bytes under a
        canonical format identity."""
        all_refs = [
            ref for group_refs in kv_caches.group_data_refs for ref in group_refs
        ]
        if any(ref.mapping is None for ref in all_refs):
            raise RuntimeError(
                "canonical_layout was requested but the KV cache layout "
                "could not be certified for canonical offload (offload "
                "workers must be exactly the TP group, and packed / "
                "cross-layer KV layouts are not supported). Remove "
                "canonical_layout from kv_connector_extra_config."
            )
        self.all_layers_portable = all(
            ref.mapping is not None and ref.mapping.parallelism_agnostic
            for ref in all_refs
        )
        if self.config.parallel.is_parallelism_agnostic and not (
            self.all_layers_portable
        ):
            # The scheduler-side storage namespace was already collapsed on
            # the static portability claim; opaque per-topology bytes must
            # not land in it.
            raise RuntimeError(
                "canonical_layout could not certify every layer as "
                "parallelism-agnostic, but the storage namespace is shared "
                "across topologies. Remove canonical_layout from "
                "kv_connector_extra_config or disable parallel-agnostic "
                "secondary tiers."
            )
        logger.info(
            "Canonical KV layout enabled (all_layers_portable=%s)",
            self.all_layers_portable,
        )

_get_secondary_tiers(extra_config) classmethod

Resolve every configured secondary tier to its manager class.

Parameters:

  • extra_config

    (dict[str, Any]) –

    kv_connector_extra_config of this instance.

Returns:

Raises:

  • ValueError –

    If secondary_tiers is not a list.

Source code in vllm/v1/kv_offload/tiering/spec.py
@classmethod
def _get_secondary_tiers(
    cls, extra_config: dict[str, Any]
) -> list[tuple[dict[str, Any], type[SecondaryTierManager]]]:
    """Resolve every configured secondary tier to its manager class.

    Args:
        extra_config: kv_connector_extra_config of this instance.

    Returns:
        One (tier config, tier class) pair for each secondary tier, in
        configuration order. That order sets the tier index.

    Raises:
        ValueError: If secondary_tiers is not a list.

    """
    secondary_tier_configs = extra_config.get("secondary_tiers", [])
    if not isinstance(secondary_tier_configs, list):
        raise ValueError("secondary_tiers must be a list of tier configurations")

    tiers = []
    for tier_config in secondary_tier_configs:
        assert isinstance(tier_config, dict)
        tier_cls = SecondaryTierFactory.get_tier_class(tier_config)
        tiers.append((tier_config, tier_cls))
    return tiers

_mirror_topology()

Locate this worker when its engine spans nodes, or return None.

Collective over the engine's TP, PP and PCP groups, then over its workers if they span nodes. Raises for the setups the mirror cannot serve.

Source code in vllm/v1/kv_offload/tiering/spec.py
def _mirror_topology(self) -> MirrorTopology | None:
    """Locate this worker when its engine spans nodes, or return None.

    Collective over the engine's TP, PP and PCP groups, then over its
    workers if they span nodes. Raises for the setups the mirror cannot
    serve.
    """
    from vllm.distributed.parallel_state import get_world_group

    if not _workers_span_nodes():
        return None
    parallel = self.config.parallel
    if (
        parallel.data_parallel_size > 1
        or get_world_group().world_size != parallel.world_size
    ):
        # The mirror locates workers in the world group, which then holds
        # every replica, external ones (torchrun launchers) included.
        raise NotImplementedError(
            "TieringOffloadingSpec secondary tiers support engines whose "
            "workers span several nodes only without data parallelism and "
            "without other engines in the same world group (external_launcher)."
        )
    if self.config.canonical_layout:
        raise ValueError(
            "canonical_layout interleaves every rank's bytes in one row "
            "area and cannot be mirrored across nodes; remove "
            "canonical_layout from kv_connector_extra_config."
        )
    if any(
        _is_kvcr_tier(SecondaryTierFactory.get_tier_class(tier))
        for tier in self.secondary_tier_configs
    ):
        # KVCR keys carry no slot_layout namespace, so rows stored across
        # nodes before the mirror would still hit.
        raise ValueError(
            "The kvcr secondary tier does not support engines whose "
            "workers span several nodes."
        )
    if self.kv_bytes_per_chunk // self.cpu_page_size_per_worker < (
        parallel.world_size
    ):
        raise ValueError(
            "The head node's CPU region must hold every worker's slot to "
            "mirror it across nodes; remove replicated_layout from "
            "kv_connector_extra_config."
        )
    topology = mirror_topology()
    assert topology is not None
    return topology

_validate_canonical_refs(kv_caches)

Require a mapping on every ref and record layer portability.

Fails loudly rather than persist direct-layout bytes under a canonical format identity.

Source code in vllm/v1/kv_offload/tiering/spec.py
def _validate_canonical_refs(self, kv_caches: CanonicalKVCaches) -> None:
    """Require a mapping on every ref and record layer portability.

    Fails loudly rather than persist direct-layout bytes under a
    canonical format identity."""
    all_refs = [
        ref for group_refs in kv_caches.group_data_refs for ref in group_refs
    ]
    if any(ref.mapping is None for ref in all_refs):
        raise RuntimeError(
            "canonical_layout was requested but the KV cache layout "
            "could not be certified for canonical offload (offload "
            "workers must be exactly the TP group, and packed / "
            "cross-layer KV layouts are not supported). Remove "
            "canonical_layout from kv_connector_extra_config."
        )
    self.all_layers_portable = all(
        ref.mapping is not None and ref.mapping.parallelism_agnostic
        for ref in all_refs
    )
    if self.config.parallel.is_parallelism_agnostic and not (
        self.all_layers_portable
    ):
        # The scheduler-side storage namespace was already collapsed on
        # the static portability claim; opaque per-topology bytes must
        # not land in it.
        raise RuntimeError(
            "canonical_layout could not certify every layer as "
            "parallelism-agnostic, but the storage namespace is shared "
            "across topologies. Remove canonical_layout from "
            "kv_connector_extra_config or disable parallel-agnostic "
            "secondary tiers."
        )
    logger.info(
        "Canonical KV layout enabled (all_layers_portable=%s)",
        self.all_layers_portable,
    )

config_info_keys(extra_config) classmethod

Return TIER_LABEL and the label names of all tiers, with no repeat.

Source code in vllm/v1/kv_offload/tiering/spec.py
@classmethod
@override
def config_info_keys(cls, extra_config: dict[str, Any]) -> tuple[str, ...]:
    """Return TIER_LABEL and the label names of all tiers, with no repeat."""
    # dict.fromkeys() keeps one copy of a name that two tier types share.
    keys = dict.fromkeys(super().config_info_keys(extra_config))
    keys[TIER_LABEL] = None
    for tier_config, tier_cls in cls._get_secondary_tiers(extra_config):
        tier_keys = tier_cls.config_info_keys(tier_config)
        assert TIER_LABEL not in tier_keys, (
            f"{tier_cls.__name__} must not declare the reserved label "
            f"{TIER_LABEL!r}"
        )
        keys.update(dict.fromkeys(tier_keys))
    return tuple(keys)

get_manager()

Get the TieringOffloadingManager.

Creates a TieringOffloadingManager with: - Primary tier: CPU (LRU or ARC) - Secondary tiers: As configured in extra_config

Returns:

Source code in vllm/v1/kv_offload/tiering/spec.py
@override
def get_manager(self) -> OffloadingManager:
    """Get the TieringOffloadingManager.

    Creates a TieringOffloadingManager with:
    - Primary tier: CPU (LRU or ARC)
    - Secondary tiers: As configured in extra_config

    Returns:
        TieringOffloadingManager instance

    """
    if not self._manager:
        if int(self.extra_config.get("store_threshold", 0)) >= 2:
            raise ValueError(
                "store_threshold is not supported for TieringOffloadingSpec"
            )

        scheduler_mmap: SharedOffloadRegion | None = None
        primary_tier: CPUPrimaryTierOffloadingManager | None = None
        secondary_tiers = []
        try:
            # Create scheduler-side SharedOffloadRegion (rank=None) so the
            # primary tier can eagerly create a memoryview over _base.
            scheduler_mmap = SharedOffloadRegion(
                engine_id=self._engine_id,
                num_chunks=self.num_chunks,
                rank=None,
                kv_bytes_per_chunk=self.kv_bytes_per_chunk,
                cpu_page_size=self.cpu_page_size_per_worker,
            )
            self._scheduler_mmap = scheduler_mmap
            if (
                self.secondary_tier_configs
                and scheduler_mmap.created_file
                and self.config.parallel.world_size > 1
            ):
                # Secondary tiers read the region worker rank 0 created,
                # into which the mirror also copies remote slots.
                raise RuntimeError(
                    "The tiering scheduler created the shared CPU region "
                    "instead of joining its workers' region: the engine "
                    "core must share a node with worker rank 0."
                )

            # Create primary tier (CPU-based)
            primary_tier = CPUPrimaryTierOffloadingManager(
                num_chunks=self.num_chunks,
                cache_policy=self.eviction_policy,
                cache_policy_module_path=self.cache_policy_module_path,
                enable_events=self.kv_events_config.enable_kv_cache_events,
                mmap_region=scheduler_mmap,
                info=self.cpu_info,
            )

            # Create secondary tiers
            primary_kv_view = primary_tier.get_kv_memoryview()
            for i, tier_config in enumerate(self.secondary_tier_configs):
                tier = SecondaryTierFactory.create_secondary_tier(
                    tier_config, primary_kv_view, self
                )
                secondary_tiers.append(tier)
                logger.info(
                    "Created secondary tier #%d (%s)",
                    i,
                    tier.tier_type,
                )

            # Create TieringOffloadingManager. GPU↔CPU transfers use the inherited
            # get_worker(). Secondary tier transfers are handled by the
            # secondary tier managers and need no additional workers here.
            tiering_manager = TieringOffloadingManager(
                primary_tier=primary_tier,
                secondary_tiers=secondary_tiers,
                tier_poll_interval_s=self.tier_poll_interval_s,
            )
            self._manager = tiering_manager
        except Exception:
            for tier in reversed(secondary_tiers):
                try:
                    tier.shutdown()
                except Exception:
                    logger.exception(
                        "Failed to shut down secondary tier during "
                        "initialization cleanup"
                    )
            if primary_tier is not None:
                try:
                    primary_tier.shutdown()
                except Exception:
                    logger.exception(
                        "Failed to shut down primary tier during "
                        "initialization cleanup"
                    )
            elif scheduler_mmap is not None:
                try:
                    scheduler_mmap.cleanup()
                except Exception:
                    logger.exception(
                        "Failed to clean up scheduler mmap during "
                        "initialization cleanup"
                    )
            self._scheduler_mmap = None
            raise

        logger.info(
            "Created TieringOffloadingManager with primary tier "
            "(%s, %s chunks) and %s secondary tier(s)",
            self.eviction_policy,
            self.num_chunks,
            len(secondary_tiers),
        )

    return self._manager

registers_kv_cache_across_nodes(extra_config) classmethod

With secondary tiers, workers off the head node register their GPU KV cache with NIXL to mirror their CPU region slots (create_worker).

Source code in vllm/v1/kv_offload/tiering/spec.py
@classmethod
@override
def registers_kv_cache_across_nodes(cls, extra_config: dict[str, Any]) -> bool:
    """With secondary tiers, workers off the head node register their GPU
    KV cache with NIXL to mirror their CPU region slots (create_worker)."""
    return bool(extra_config.get("secondary_tiers"))

_is_kvcr_tier(tier_cls)

Whether a tier class is, or derives from, the KVCR tier manager.

Compared by name: importing the KVCR manager needs the kvcr package.

Source code in vllm/v1/kv_offload/tiering/spec.py
def _is_kvcr_tier(tier_cls: type) -> bool:
    """Whether a tier class is, or derives from, the KVCR tier manager.

    Compared by name: importing the KVCR manager needs the kvcr package.
    """
    return any(
        cls.__module__ == "vllm.v1.kv_offload.tiering.kvcr.manager"
        and cls.__qualname__ == "KVCRSecondaryTierManager"
        for cls in tier_cls.__mro__
    )

_workers_span_nodes()

Whether the engine's workers span several nodes.

A rank sees only its own TP, PP and PCP groups: with TP=2, PP=2 and ranks 0-2 on one node, rank 0's groups share that node while rank 3's do not. The engine's workers form a grid of these groups, so a maximum over each group in turn gives every rank the same answer.

Source code in vllm/v1/kv_offload/tiering/spec.py
def _workers_span_nodes() -> bool:
    """Whether the engine's workers span several nodes.

    A rank sees only its own TP, PP and PCP groups: with TP=2, PP=2 and ranks
    0-2 on one node, rank 0's groups share that node while rank 3's do not.
    The engine's workers form a grid of these groups, so a maximum over each
    group in turn gives every rank the same answer.
    """
    from vllm.distributed.parallel_state import (
        get_pcp_group,
        get_pp_group,
        get_tp_group,
        in_the_same_node_as,
    )

    groups = [
        group
        for group in (get_tp_group(), get_pp_group(), get_pcp_group())
        if group.world_size > 1
    ]
    # Group sizes match on every rank, so all ranks run the same collectives.
    spans = [
        not all(in_the_same_node_as(group.cpu_group, source_rank=0)) for group in groups
    ]
    flag = torch.tensor([any(spans)], dtype=torch.int32)
    for group in groups:
        dist.all_reduce(flag, op=dist.ReduceOp.MAX, group=group.cpu_group)
    return bool(flag.item())