repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
sglang | python/sglang/srt/speculative/frozen_kv_mtp_worker_v2.py | .py | # Copyright 2026 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | 805 | 32,460 |
sglang | python/sglang/srt/speculative/frozen_kv_mtp_info.py | .py | # Copyright 2026 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | 63 | 2,192 |
sglang | python/sglang/srt/speculative/ngram_info.py | .py | from __future__ import annotations
from typing import List, Optional
import torch
from sglang.kernels.ops.attention.utils import create_flashinfer_kv_indices_triton
from sglang.srt.speculative.spec_info import SpecInput, SpecInputType
class NgramVerifyInput(SpecInput):
def __init__(
self,
draft... | 146 | 5,200 |
sglang | python/sglang/srt/speculative/multi_layer_eagle_utils.py | .py | # Copyright 2023-2024 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | 65 | 2,153 |
sglang | python/sglang/srt/speculative/adaptive_runtime_state.py | .py | from dataclasses import dataclass
from typing import TYPE_CHECKING, Protocol
from sglang.srt.speculative.adaptive_spec_params import AdaptiveSpeculativeParams
if TYPE_CHECKING:
from sglang.srt.layers.attention.base_attn_backend import AttentionBackend
from sglang.srt.model_executor.cpu_graph_runner import CPU... | 135 | 5,121 |
sglang | python/sglang/srt/speculative/ragged_verify.py | .py | from __future__ import annotations
import bisect
from enum import Enum
from typing import List, Optional, Sequence, Tuple
import msgspec
import torch
from sglang.srt.environ import envs
class RaggedVerifyMode(str, Enum):
STATIC = "static"
CAP_ACCEPT = "cap-accept"
COMPACT = "compact"
def read_ragged_... | 327 | 11,273 |
sglang | python/sglang/srt/speculative/eagle_utils.py | .py | from __future__ import annotations
import logging
import math
from enum import IntEnum
from typing import TYPE_CHECKING, List, Optional, Tuple
import torch
from sglang.kernels.ops.speculative.spec_tree import (
sgl_build_tree_kernel_efficient_triton,
verify_tree_greedy_kernel_triton,
)
from sglang.srt.hardwa... | 954 | 36,182 |
sglang | python/sglang/srt/speculative/eagle_disaggregation.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.srt.layers.attention.dsa.utils import (
should_remap_pd_dsa_seed_to_local_slots,
)
from sglang.srt.managers.overlap_utils import RelayPayload
from sglang.srt.model_executor.forward_batch_info import CaptureHiddenMode
fro... | 108 | 3,976 |
sglang | python/sglang/srt/speculative/eagle_worker_v2.py | .py | import contextlib
import logging
import time
from dataclasses import replace
from typing import List, Optional
import torch
from sglang.kernels.ops.speculative.topk1 import draft_topk1_postprocess
from sglang.srt.distributed.parallel_state_wrapper import ParallelState
from sglang.srt.environ import envs
from sglang.s... | 1,535 | 63,778 |
sglang | python/sglang/srt/speculative/external_corpus_manager.py | .py | """Manages external SAM corpora for ngram speculative decoding.
Handles add/remove/list operations and async background loading.
Used by the Scheduler — not a mixin, a standalone manager object.
"""
import logging
import threading
from typing import Callable, Optional, Tuple
from sglang.srt.managers.io_struct import... | 111 | 4,081 |
sglang | python/sglang/srt/speculative/dspark_disaggregation.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.srt.managers.overlap_utils import RelayPayload
from sglang.srt.speculative.dspark_components.dspark_draft import make_next_draft_input
if TYPE_CHECKING:
from sglang.srt.managers.overlap_utils import FutureMap
from s... | 35 | 1,134 |
sglang | python/sglang/srt/speculative/spec_registry.py | .py | """Internal storage backing ``SpeculativeAlgorithm.register``. Plugins
should use that classmethod API; do not import from this module directly.
"""
from __future__ import annotations
import logging
import warnings
from typing import TYPE_CHECKING, Callable, Dict, Optional, Type
import torch
if TYPE_CHECKING:
f... | 261 | 9,371 |
sglang | python/sglang/srt/speculative/eagle_draft_cuda_graph_runner.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable, Optional
import torch
from sglang.srt.compilation.torch_compile_decoration import set_torch_compile_config
from sglang.srt.environ import envs
from sglang.srt.layers.dp_attention import (
DpPaddingMod... | 681 | 28,483 |
sglang | python/sglang/srt/speculative/eagle_info.py | .py | import logging
from dataclasses import dataclass
from typing import List, Optional
import torch
from sglang.kernels.ops.attention.utils import create_flashinfer_kv_indices_triton
from sglang.srt.model_executor.forward_batch_info import CaptureHiddenMode
from sglang.srt.runtime_context import get_spec
from sglang.srt.... | 390 | 15,203 |
sglang | python/sglang/srt/speculative/frozen_kv_mtp_utils.py | .py | # Copyright 2026 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | 156 | 6,124 |
sglang | python/sglang/srt/speculative/decoupled_spec_io.py | .py | from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Optional
class DraftMeshMessageType(str, Enum):
CONTROL_BATCH = "control_batch"
TAIL_STREAM_OUTPUT_BATCH = "tail_stream_output_batch"
@dataclass(frozen=True)
class DraftReqKey:
... | 385 | 13,475 |
sglang | python/sglang/srt/speculative/base_spec_worker.py | .py | from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import TYPE_CHECKING, Optional
import torch
from sglang.srt.model_executor.graph_memory_usage import (
merge_graph_memory_usage,
merge_graph_time_usage,
)
from sglang.srt... | 336 | 12,451 |
sglang | python/sglang/srt/speculative/spec_utils.py | .py | from __future__ import annotations
import contextlib
import logging
import os
import time
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Callable, List, Literal, Optional, Tuple
import torch
from huggingface_hub import snapshot_download
from sglang.kernels.ops.speculative.cache_locs imp... | 1,056 | 40,460 |
sglang | python/sglang/srt/speculative/cpp_ngram/external_corpus.py | .py | import json
from collections.abc import Iterator
from pathlib import Path
# Must match SuffixAutomaton::kSeparatorToken in suffix_automaton.h.
SEPARATOR_TOKEN = -(2**31)
# Default chunk size for streaming tokenized documents into the SAM.
DEFAULT_CHUNK_SIZE = 4096
def iter_external_corpus_chunks(
path: str, tok... | 63 | 2,398 |
sglang | python/sglang/srt/speculative/cpp_ngram/ngram_corpus.py | .py | # -*- coding: utf-8 -*-
import logging
from collections.abc import Iterable, Sequence
from typing import Dict, List, Tuple
import numpy as np
from sglang.kernels.ops.speculative.ngram_corpus import get_ngram_corpus_cls
logger = logging.getLogger(__name__)
class NgramCorpus:
def __init__(
self,
... | 201 | 7,044 |
sglang | python/sglang/srt/speculative/dspark_components/dspark_observability.py | .py | from __future__ import annotations
import logging
import math
import statistics
import time
from collections import deque
from contextlib import contextmanager, nullcontext
from enum import Enum
from typing import Callable, ContextManager, Iterator, Optional, Union
import msgspec
import torch
from sglang.srt.environ... | 962 | 35,773 |
sglang | python/sglang/srt/speculative/dspark_components/dspark_block_accept_estimator.py | .py | from __future__ import annotations
import json
import logging
import math
from collections import deque
from pathlib import Path
from typing import Any, List, Optional, Tuple, Union
import msgspec
import torch
from sglang.srt.environ import envs
from sglang.srt.kv_canary.runner.future_tensor import DelayedDeviceHost... | 836 | 28,957 |
sglang | python/sglang/srt/speculative/dspark_components/dspark_planner.py | .py | from __future__ import annotations
import logging
from typing import Optional, Union
import msgspec
import torch
from sglang.kernels.ops.speculative.cache_locs import assign_extend_cache_locs_func
from sglang.kernels.ops.speculative.dspark.dspark_schedule import (
ScheduleVerifyLensTopk,
compute_sort_surviva... | 1,145 | 43,212 |
sglang | python/sglang/srt/speculative/dspark_components/dspark_config.py | .py | from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING, Any, List, Optional
import msgspec
from sglang.srt.speculative.dflash_utils import parse_dflash_draft_config
if TYPE_CHECKING:
from sglang.srt.server_args import ServerArgs
logger = logging.getLogger(__name__)
DEFA... | 296 | 10,205 |
sglang | python/sglang/srt/speculative/dspark_components/dspark_verify.py | .py | from __future__ import annotations
from typing import Optional
import msgspec
import torch
from sglang.kernels.ops.attention.dsv4.unified_kv_kernels.env_gate import (
is_unified_kv_triton,
)
from sglang.kernels.ops.speculative.dspark.dspark_accept import (
AcceptGreedy,
AcceptSampling,
FinalizeAccept... | 756 | 28,383 |
sglang | python/sglang/srt/speculative/dspark_components/dspark_worker_v2.py | .py | import logging
from contextlib import nullcontext
from dataclasses import replace
from typing import Optional
import torch
from sglang.kernels.ops.attention.dsv4.unified_kv_kernels.env_gate import (
is_unified_kv_triton,
)
from sglang.srt.configs.hybrid_arch import mambaish_config
from sglang.srt.distributed.para... | 829 | 33,934 |
sglang | python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py | .py | from typing import Optional
import torch
from sglang.kernels.ops.attention.dsv4.unified_kv_kernels.env_gate import (
is_unified_kv_triton,
)
from sglang.kernels.ops.speculative.cache_locs import assign_extend_cache_locs_func
from sglang.kernels.ops.speculative.dspark.dspark_verify_window import (
BuildCommitI... | 237 | 9,206 |
sglang | python/sglang/srt/speculative/dspark_components/dspark_sts.py | .py | from __future__ import annotations
from pathlib import Path
import msgspec
import torch
class DSparkStsCalibration(msgspec.Struct, frozen=True, omit_defaults=True):
temperatures: list[float]
dataset: str = ""
num_samples: int = 0
ece_before: list[float] = []
ece_after: list[float] = []
def ... | 77 | 2,634 |
sglang | python/sglang/srt/speculative/dspark_components/dspark_draft.py | .py | from __future__ import annotations
import logging
from contextlib import nullcontext
from typing import Optional
import msgspec
import torch
from sglang.kernels.ops.speculative.dspark.dspark_draft_model import (
SampleStepTokens,
)
from sglang.srt.environ import envs
from sglang.srt.managers.schedule_batch impor... | 420 | 15,872 |
sglang | python/sglang/srt/speculative/dspark_components/dspark_draft_sampler.py | .py | from __future__ import annotations
import logging
from typing import Optional
import torch
from sglang.kernels.ops.speculative.dspark.dspark_draft_model import (
SampleStepTokens,
)
from sglang.srt.environ import DsparkFoldedSampling, envs
from sglang.srt.utils import get_available_gpu_memory
logger = logging.g... | 206 | 7,257 |
sglang | python/sglang/srt/speculative/dspark_components/dspark_sps.py | .py | from __future__ import annotations
import bisect
from typing import Optional
import msgspec
def floor_probe_index(edges: list[int], batch_tokens: int) -> int:
idx = bisect.bisect_right(edges, batch_tokens) - 1
return max(0, min(idx, len(edges) - 1))
class SpsCostTable(msgspec.Struct, frozen=True):
sam... | 165 | 5,738 |
sglang | python/sglang/srt/mem_cache/embedding_store.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to SGLang project
import abc
import importlib
import logging
from typing import Any, Dict, List
import torch
logger = logging.getLogger(__name__)
class EmbeddingStore(abc.ABC):
"""Abstract base class for multimodal embedding... | 128 | 3,868 |
sglang | python/sglang/srt/mem_cache/mamba_slot_fused.py | .py | """Fused Triton kernels that clear / copy conv-state pool slots across all
conv-state tensors of a hybrid (mamba-style) pool in a single launch.
``MambaPool.clear_slots`` / ``copy_from`` otherwise loop over every conv-state
tensor (models with several short-conv streams have a handful, each a distinct
scattered-index ... | 172 | 6,192 |
sglang | python/sglang/srt/mem_cache/multi_ended_allocator.py | .py | # Copyright 2023-2026 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | 2,560 | 115,792 |
sglang | python/sglang/srt/mem_cache/allocation_sizing.py | .py | from __future__ import annotations
from typing import Optional
from sglang.srt.runtime_context import get_server_args
from sglang.srt.server_args import ServerArgs
def get_alloc_len_per_decode(
server_args: ServerArgs, *, max_draft_tokens: Optional[int] = None
) -> int:
"""``max_draft_tokens`` lets a caller... | 91 | 3,839 |
sglang | python/sglang/srt/mem_cache/base_swa_memory_pool.py | .py | import abc
from typing import List, Tuple
import torch
from sglang.srt.mem_cache.memory_pool import KVCache
class BaseSWAKVPool(KVCache):
"""ABC for SWA-like KV pools.
Subclasses expose a `swa_kv_pool` sub-pool plus a full -> swa index
mapping. Used by `SWATokenToKVPoolAllocator` and the disagg paths t... | 30 | 841 |
sglang | python/sglang/srt/mem_cache/embedding_cache_controller.py | .py | import asyncio
import logging
import math
import threading
import time
from collections import OrderedDict
from dataclasses import dataclass
from enum import Enum, auto
from queue import Empty, Queue
from typing import List, Optional, Tuple
import torch
try:
from sgl_kernel.kvcacheio import transfer_embedding_ran... | 1,088 | 38,008 |
sglang | python/sglang/srt/mem_cache/utils.py | .py | # Copyright 2025 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | 212 | 7,127 |
sglang | python/sglang/srt/mem_cache/deepseek_v4_compress_state.py | .py | from __future__ import annotations
import dataclasses
from contextlib import nullcontext
from math import gcd
import torch
from sglang.srt.constants import GPU_MEMORY_TYPE_KV_CACHE
from sglang.srt.mem_cache.utils import maybe_init_custom_mem_pool
from sglang.srt.utils import is_hip, is_npu
from sglang.srt.utils.torc... | 217 | 8,334 |
sglang | python/sglang/srt/mem_cache/evict_policy.py | .py | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Tuple, Union
if TYPE_CHECKING:
from sglang.srt.mem_cache.radix_cache import TreeNode
class EvictionStrategy(ABC):
@abstractmethod
def get_priority(self, node: TreeNode) -> Union[float, Tuple]:
... | 66 | 2,112 |
sglang | python/sglang/srt/mem_cache/radix_cache.py | .py | from __future__ import annotations
from sglang.srt.mem_cache.cache_init_params import CacheInitParams
"""
Copyright 2023-2024 SGLang Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http:/... | 863 | 32,019 |
sglang | python/sglang/srt/mem_cache/swa_memory_pool.py | .py | import logging
from typing import Dict, List, Optional, Tuple
import torch
from sglang.srt.layers.radix_attention import RadixAttention
from sglang.srt.mem_cache.base_swa_memory_pool import BaseSWAKVPool
from sglang.srt.mem_cache.memory_pool import (
KVCache,
MHATokenToKVPool,
unwrap_write_loc,
)
from sgl... | 304 | 11,963 |
sglang | python/sglang/srt/mem_cache/dsa_cache_layer_split.py | .py | # Copyright 2023-2026 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | 590 | 23,972 |
sglang | python/sglang/srt/mem_cache/deepseek_v4_memory_pool.py | .py | from __future__ import annotations
import logging
from contextlib import nullcontext
from typing import List, Literal, NamedTuple, Optional, Tuple
import torch
from sglang.kernels.ops.attention.dsa import index_buf_accessor
from sglang.kernels.ops.attention.dsv4 import (
clear_unaccepted_c128_draft_states,
f... | 1,258 | 46,714 |
sglang | python/sglang/srt/mem_cache/registry.py | .py | """Registry for pluggable RadixCache factories.
If `--radix-cache-backend` is unset (by default), the built-in selection
chain is used to pick a cache implementation.
To plug in a custom backend, register it under a string name via
`register_radix_cache_backend(name, factory)`, then select it with
`--radix-cache-back... | 245 | 8,524 |
sglang | python/sglang/srt/mem_cache/kv_cache_configurator.py | .py | from __future__ import annotations
import logging
import math
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Optional
import msgspec
import torch
from sglang.srt.configs.hybrid_arch import (
hybrid_gdn_config,
kimi_linear_config,
mambaish_config,
)
from sglang.srt.configs... | 2,197 | 98,885 |
sglang | python/sglang/srt/mem_cache/mamba_radix_cache.py | .py | from __future__ import annotations
"""
Copyright 2023-2024 SGLang Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable ... | 1,427 | 58,362 |
sglang | python/sglang/srt/mem_cache/cache_init_params.py | .py | from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING, Optional
import torch
if TYPE_CHECKING:
from sglang.srt.mem_cache.allocator import BaseTokenToKVPoolAllocator
from sglang.srt.mem_cache.memory_pool import ReqToTokenPool
from sglang.srt.mem_cache.unified_cache.compone... | 58 | 1,772 |
sglang | python/sglang/srt/mem_cache/chunk_cache.py | .py | from __future__ import annotations
"""Cache for chunked prefill, used when RadixCache is disabled."""
import logging
from typing import TYPE_CHECKING, Any, Optional
import torch
from sglang.srt.mem_cache.allocator.hisparse import (
DeepSeekV4HiSparseTokenToKVPoolAllocator,
)
from sglang.srt.mem_cache.allocator.... | 179 | 6,195 |
sglang | python/sglang/srt/mem_cache/memory_pool.py | .py | """
Copyright 2023-2024 SGLang Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwar... | 5,035 | 208,582 |
sglang | python/sglang/srt/mem_cache/hisparse_memory_pool.py | .py | # mapping on device memory, host memory and memory allocator
import logging
from typing import Optional
import torch
from sglang.srt.layers.radix_attention import RadixAttention
from sglang.srt.mem_cache.memory_pool import DSATokenToKVPool
from sglang.srt.utils import is_cuda, is_hip
logger = logging.getLogger(__na... | 123 | 4,167 |
sglang | python/sglang/srt/mem_cache/index_key_cache.py | .py | from __future__ import annotations
from contextlib import nullcontext
from typing import TYPE_CHECKING
import torch
from sglang.kernels.ops.attention.dsa import index_buf_accessor
if TYPE_CHECKING:
from sglang.srt.mem_cache.memory_pool import DSATokenToKVPool
class IndexKeyCache:
def __init__(self, pool: ... | 150 | 5,514 |
sglang | python/sglang/srt/mem_cache/hiradix_cache.py | .py | from __future__ import annotations
import atexit
import heapq
import json
import logging
import os
import threading
import time
from queue import Empty
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
import torch
from sglang.srt.disaggregation.kv_events import StorageMedium
from sglang.srt.distributed.... | 2,020 | 82,192 |
sglang | python/sglang/srt/mem_cache/kv_vmm_backing.py | .py | from __future__ import annotations
import ctypes
import logging
import os
import tempfile
from math import prod
from typing import TYPE_CHECKING, List, Optional, Sequence
import torch
import torch.utils.cpp_extension
from torch.cuda.memory import CUDAPluggableAllocator
from sglang.srt.cuda_vmm_utils import (
Vmm... | 365 | 15,235 |
sglang | python/sglang/srt/mem_cache/kv_cache_builder.py | .py | from __future__ import annotations
import logging
logger = logging.getLogger(__name__)
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True, slots=True, kw_only=True)
class KVCacheBuildResult:
is_hybrid_swa: bool
is_hybrid_ssm: bool
sliding_window_size: Optional[int]
... | 285 | 10,308 |
sglang | python/sglang/srt/mem_cache/mamba_checkpoint_pool.py | .py | """
Copyright 2023-2026 SGLang Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwar... | 374 | 14,781 |
sglang | python/sglang/srt/mem_cache/unified_radix_cache.py | .py | from __future__ import annotations
import logging
import threading
import time
from queue import Empty, Queue
from typing import TYPE_CHECKING, Iterator, NamedTuple, Optional, Sequence, TypeVar
import torch
from sglang.srt.distributed.communication_tags import P2PTag
from sglang.srt.environ import envs
from sglang.s... | 2,297 | 92,284 |
sglang | python/sglang/srt/mem_cache/base_prefix_cache.py | .py | from __future__ import annotations
import dataclasses
import time
from abc import ABC, abstractmethod
from typing import (
TYPE_CHECKING,
Any,
NamedTuple,
Optional,
Protocol,
Sequence,
Tuple,
runtime_checkable,
)
import torch
from sglang.srt.mem_cache.allocator import BaseTokenToKVPoo... | 430 | 14,041 |
sglang | python/sglang/srt/mem_cache/swa_radix_cache.py | .py | from __future__ import annotations
"""
Copyright 2023-2024 SGLang Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable ... | 1,440 | 60,319 |
sglang | python/sglang/srt/mem_cache/common.py | .py | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
import numpy as np
import torch
from sglang.kernels.ops.memory.common import (
_get_last_loc_safe_kernel as _get_last_loc_safe_kernel,
)
from sglang.kernels.ops.memory.common import get_last_loc_kernel as get_last_loc_kernel
from ... | 213 | 8,583 |
sglang | python/sglang/srt/mem_cache/allocation.py | .py | from __future__ import annotations
import logging
from collections import defaultdict
from typing import TYPE_CHECKING, Optional
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.memory.common import (
get_last_loc_triton,
get_last_loc_triton_safe,
write_req_to_token_pool_tr... | 727 | 25,257 |
sglang | python/sglang/srt/mem_cache/unified_memory_pool.py | .py | # Copyright 2023-2026 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | 1,692 | 66,500 |
sglang | python/sglang/srt/mem_cache/flush_cache.py | .py | """
Copyright 2023-2024 SGLang Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwar... | 34 | 979 |
sglang | python/sglang/srt/mem_cache/radix_cache_cpp.py | .py | from __future__ import annotations
import logging
import time
from typing import TYPE_CHECKING, List, Optional, Set
import torch
from sglang.srt.mem_cache.base_prefix_cache import (
BasePrefixCache,
DecLockRefParams,
DecLockRefResult,
EvictParams,
EvictResult,
IncLockRefResult,
MatchPrefi... | 273 | 10,691 |
sglang | python/sglang/srt/mem_cache/hicache_storage.py | .py | from __future__ import annotations
import logging
import os
import threading
import time
import uuid
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import TYPE_CHECKING, Any, List, Optional, Set
import torch
from sglang.srt.environ import envs
if TYPE_CHECKIN... | 726 | 25,362 |
sglang | python/sglang/srt/mem_cache/multimodal_cache.py | .py | import abc
from collections import OrderedDict
from dataclasses import dataclass
from typing import List, Optional
import torch
from sglang.srt.mem_cache.allocator import BaseTokenToKVPoolAllocator
class MultimodalCache(abc.ABC):
@abc.abstractmethod
def __init__(
self,
): ...
@staticmethod
... | 151 | 4,370 |
sglang | python/sglang/srt/mem_cache/kv_cache_dtype.py | .py | import logging
from typing import Optional
import torch
from torch import nn
from sglang.kernels.ops.quantization.fp8_kernel import fp8_dtype
from sglang.srt.utils import is_hip
logger = logging.getLogger(__name__)
_is_hip = is_hip()
TORCH_DTYPE_TO_KV_CACHE_STR = {
torch.float8_e4m3fn: "fp8_e4m3",
torch.fl... | 102 | 3,843 |
sglang | python/sglang/srt/mem_cache/memory_pool_host.py | .py | from __future__ import annotations
import logging
import threading
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable, Optional
if TYPE_CHECKING:
from sglang.srt.mem_cache.hicache_storage import PoolName
from sglang.srt.mem_cache.pool_host.mla import MLATokenToKVPoolHost
import... | 2,215 | 86,198 |
sglang | python/sglang/srt/mem_cache/pure_swa_radix_cache.py | .py | """Radix cache for all-SWA models (every layer is sliding-window attention)."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
import torch
from sglang.srt.mem_cache.base_prefix_cache import (
EvictParams,
EvictResult,
InsertParams,
)
from sglang.srt.mem_cache.cache_i... | 154 | 5,591 |
sglang | python/sglang/srt/mem_cache/events.py | .py | # Copyright 2025 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | 188 | 7,448 |
sglang | python/sglang/srt/mem_cache/storage/backend_factory.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to SGLang project
import importlib
import logging
from typing import TYPE_CHECKING, Any, Dict
from sglang.srt.mem_cache.hicache_storage import HiCacheStorage, HiCacheStorageConfig
if TYPE_CHECKING:
pass
logger = logging.getLo... | 248 | 8,540 |
sglang | python/sglang/srt/mem_cache/storage/__init__.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to SGLang project
"""Storage backend module for SGLang HiCache."""
from .backend_factory import StorageBackendFactory
__all__ = [
"StorageBackendFactory",
]
| 11 | 251 |
sglang | python/sglang/srt/mem_cache/storage/flexkv/flexkv_radix_cache.py | .py | """FlexKV-backed RadixCache for sglang.
This module exposes :class:`FlexKVRadixCache`, a subclass of
:class:`sglang.srt.mem_cache.radix_cache.RadixCache` that delegates
host-side prefix storage to a FlexKV ``KVManager``. The design mirrors
``LMCRadixCache`` (the LMCache integration) so the scheduler-side
contract is i... | 523 | 19,639 |
sglang | python/sglang/srt/mem_cache/storage/flexkv/__init__.py | .py | """FlexKV-backed RadixCache integration for sglang.
Two ways to select this backend at server launch:
1. ``--enable-flexkv`` (default chain in ``default_radix_cache_factory``)
2. ``--radix-cache-backend=flexkv`` (explicit registry path)
Importing this package registers the explicit name with the registry,
so the sec... | 88 | 2,992 |
sglang | python/sglang/srt/mem_cache/storage/flexkv/flexkv_comm.py | .py | """Communication helpers for the FlexKV connector.
FlexKV runs a single KVManager per DP group (typically the TP/CP/PP
sync leader's process). Every other rank in the same KV-cache-sharing
fan-out must be told the leader's decisions: which prefix matched in
FlexKV, which task id the leader allocated, which slot mappin... | 663 | 24,814 |
sglang | python/sglang/srt/mem_cache/storage/flexkv/verify_outputs.py | .py | """End-to-end correctness check for the FlexKV sglang connector.
Run twice with different server configurations:
# 1. Baseline: launch sglang WITHOUT --enable-flexkv first, then:
python verify_outputs.py --phase baseline
# 2. Restart sglang WITH --enable-flexkv, then:
python verify_outputs.py --phase... | 181 | 5,945 |
sglang | python/sglang/srt/mem_cache/storage/flexkv/flexkv_connector.py | .py | """Wrapper around FlexKV ``KVManager`` for sglang.
The public surface is small (see "Public API" below). The class owns:
* the FlexKV ``KVManager`` (server-client mode when ``dp_size > 1`` or
multi-instance; in-process otherwise — handled by FlexKV itself);
* the per-rank ``KVTPClient`` that registers this rank's G... | 926 | 37,600 |
sglang | python/sglang/srt/mem_cache/storage/nixl/hicache_nixl.py | .py | import logging
import os
import time
import uuid
from dataclasses import dataclass
from typing import Any, List, Optional
import torch
from sglang.srt.environ import envs
from sglang.srt.mem_cache.hicache_storage import (
STORAGE_BATCH_SIZE,
HiCacheStorage,
HiCacheStorageConfig,
HiCacheStorageExtraInf... | 1,014 | 39,384 |
sglang | python/sglang/srt/mem_cache/storage/nixl/nixl_routing.py | .py | """Deterministic path routing for NIXL FILE-backed HiCache storage."""
import hashlib
BUCKET_HEX_CHARS = 2
_BUCKET_MASK = (1 << (4 * BUCKET_HEX_CHARS)) - 1
def stable_key_hash(key: str) -> int:
"""Return a process-stable 64-bit hash for a NIXL storage key."""
return int.from_bytes(
hashlib.blake2b(k... | 30 | 899 |
sglang | python/sglang/srt/mem_cache/storage/nixl/nixl_cleaner.py | .py | """Background disk cleaner for the NIXL FILE HiCache backend."""
from __future__ import annotations
import concurrent.futures
import logging
import os
import re
import threading
import time
from dataclasses import dataclass, field
from typing import Iterable, Optional
from sglang.srt.mem_cache.storage.nixl.nixl_rout... | 271 | 9,240 |
sglang | python/sglang/srt/mem_cache/storage/nixl/nixl_registry.py | .py | """NIXL memory-registration helpers, exposed as context managers.
A ``NixlRegistry`` instance bundles the agent, the memory type, and
(optionally) the file manager. Its ``storage(...)`` method is a context
manager that performs the entire register-and-build-descs sequence for
the storage side of a transfer on entry, ... | 194 | 7,591 |
sglang | python/sglang/srt/mem_cache/storage/nixl/nixl_utils.py | .py | import logging
import os
from typing import Optional
from sglang.srt.environ import envs
from sglang.srt.mem_cache.storage.nixl.nixl_routing import (
_BUCKET_MASK,
BUCKET_HEX_CHARS,
route_key,
)
logger = logging.getLogger(__name__)
_SGLANG_NIXL_CONFIG_KEYS = {
"use_direct_io",
"l3_cleaner_enabled... | 316 | 12,632 |
sglang | python/sglang/srt/mem_cache/storage/mooncake_store/mooncake_embedding_store.py | .py | import logging
from typing import Any, List
from sglang.srt.mem_cache.embedding_store import EmbeddingStore
from sglang.srt.mem_cache.storage.mooncake_store.mooncake_store import (
DEFAULT_TENANT_ID,
MooncakeBaseStore,
)
logger = logging.getLogger(__name__)
class MooncakeEmbeddingStore(MooncakeBaseStore, Em... | 128 | 4,394 |
sglang | python/sglang/srt/mem_cache/storage/mooncake_store/test_mooncake_store.py | .py | import logging
import uuid
import torch
from sglang.srt.mem_cache.hicache_storage import HiCacheStorageConfig
from sglang.srt.mem_cache.storage.mooncake_store.mooncake_store import MooncakeStore
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogg... | 196 | 6,332 |
sglang | python/sglang/srt/mem_cache/storage/mooncake_store/mooncake_store.py | .py | import ctypes
import json
import logging
import os
import time
import uuid
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, List, Optional, Tuple
import requests
import torch
from sglang.srt.environ import envs
from sglang.srt.mem_cache.hicache_storage import (
HiCach... | 1,346 | 54,166 |
sglang | python/sglang/srt/mem_cache/storage/eic/test_unit.py | .py | import argparse
import os
import eic
import torch
import yaml
def pase_args():
parser = argparse.ArgumentParser(description="EIC Storage Unit Test")
parser.add_argument(
"--config",
"-c",
type=str,
default="/sgl-workspace/config/remote-eic.yaml",
help="EIC yaml config"... | 116 | 3,607 |
sglang | python/sglang/srt/mem_cache/storage/eic/eic_storage.py | .py | import json
import logging
import os
import time
from typing import Any, List, Optional, Tuple
import eic
import torch
import yaml
from sglang.srt.mem_cache.hicache_storage import (
HiCacheStorage,
HiCacheStorageConfig,
HiCacheStorageExtraInfo,
)
from sglang.srt.mem_cache.pool_host import HostKVCache
log... | 779 | 28,497 |
sglang | python/sglang/srt/mem_cache/storage/simm/hicache_simm.py | .py | import json
import logging
import os
import re
import time
import uuid
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Dict, List, Optional
import torch
from sglang.srt.mem_cache.hicache_storage import (
HiCacheStorage,
HiCacheStorage... | 545 | 20,710 |
sglang | python/sglang/srt/mem_cache/storage/simm/test_simm.py | .py | import logging
import uuid
import torch
from python.sglang.srt.mem_cache.storage.simm.hicache_simm import HiCacheSiMM
from sglang.srt.mem_cache.hicache_storage import HiCacheStorageConfig
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__na... | 182 | 5,722 |
sglang | python/sglang/srt/mem_cache/storage/shm/hicache_shm.py | .py | import logging
from typing import Any, List, Optional
import torch
from sglang.srt.mem_cache.hicache_storage import (
HiCacheStorage,
HiCacheStorageConfig,
HiCacheStorageExtraInfo,
PoolTransfer,
PoolTransferResult,
)
logger = logging.getLogger(__name__)
class HiCacheShm(HiCacheStorage):
"""... | 97 | 2,490 |
sglang | python/sglang/srt/mem_cache/storage/shm/__init__.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to SGLang project
"""Shared memory storage backend for SGLang HiCache."""
from .hicache_shm import HiCacheShm
__all__ = ["HiCacheShm"]
| 9 | 225 |
sglang | python/sglang/srt/mem_cache/storage/lmcache/unit_test.py | .py | try:
from lmcache.integration.sglang.sglang_adapter import (
LMCacheLayerwiseConnector,
LoadMetadata,
StoreMetadata,
)
except ImportError:
raise RuntimeError(
"LMCache is not installed. Please install it by running `pip install lmcache` in the root directory of LMCache"
)... | 119 | 3,524 |
sglang | python/sglang/srt/mem_cache/storage/lmcache/lmc_radix_cache.py | .py | from __future__ import annotations
import enum
import logging
import threading
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional, Tuple
import torch
from sglang.srt.mem_cache.base_prefix_cache import (
EvictParams,
EvictResult,
InitLoadBackParams,
MatchPrefixParams,
Mat... | 524 | 18,888 |
sglang | python/sglang/srt/mem_cache/storage/hf3fs/hf3fs_client.py | .py | import logging
import os
from abc import ABC, abstractmethod
from typing import List
import torch
class Hf3fsClient(ABC):
"""Abstract interface for HF3FS clients."""
@abstractmethod
def __init__(self, path: str, size: int, bytes_per_page: int, entries: int):
"""Initialize the HF3FS client.
... | 164 | 5,228 |
sglang | python/sglang/srt/mem_cache/storage/hf3fs/storage_hf3fs.py | .py | import atexit
import concurrent.futures
import json
import logging
import os
import signal
import threading
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass
from functools import wraps
from typing import Any, List, Optional, Tuple
import torch
from sglang.srt.mem_cache.hicache_storage... | 957 | 33,257 |
sglang | python/sglang/srt/mem_cache/storage/hf3fs/test_hf3fs_utils.py | .py | import multiprocessing.shared_memory
import sys
from pathlib import Path
import pytest
import torch
from torch.utils.cpp_extension import load
from tqdm import tqdm
root = Path(__file__).parent.resolve()
hf3fs_utils = load(
name="hf3fs_utils", sources=[f"{root}/hf3fs_utils.cpp"], verbose=True
)
def test_rw_shm(... | 45 | 1,110 |
sglang | python/sglang/srt/mem_cache/storage/hf3fs/mini_3fs_metadata_server.py | .py | import argparse
import atexit
import json
import logging
import threading
from collections import OrderedDict
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import orjson
import requests
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.responses import ORJSONResponse
... | 533 | 20,467 |
sglang | python/sglang/srt/mem_cache/storage/hf3fs/hf3fs_usrbio_client.py | .py | import datetime
import logging
import multiprocessing
import os
import threading
from functools import wraps
from pathlib import Path
from typing import List
import torch
from torch.utils.cpp_extension import load
from sglang.srt.mem_cache.storage.hf3fs.hf3fs_client import Hf3fsClient
root = Path(__file__).parent.re... | 221 | 6,506 |
sglang | python/sglang/srt/mem_cache/storage/file/lru_file_evictor.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to SGLang project
"""LRU/size-based file eviction for the HiCache file storage backend.
``HiCacheFile`` is a thin raw-bytes store: it suffixes keys, reads/writes
``.bin`` pages, and answers existence queries. Everything that bounds... | 394 | 16,395 |
sglang | python/sglang/srt/mem_cache/storage/file/__init__.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to SGLang project
"""File storage backend helpers for SGLang HiCache."""
from .lru_file_evictor import LRUFileEvictor
__all__ = [
"LRUFileEvictor",
]
| 11 | 244 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.