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/mem_cache/storage/aibrix_kvcache/unit_test.py
.py
import logging import os import torch import torch.distributed from aibrix_kvcache.common.absl_logging import log_every_n_seconds from aibrix_kvcache_storage import AibrixKVCacheStorage from sglang.srt.mem_cache.hicache_storage import HiCacheStorageConfig from sglang.srt.mem_cache.memory_pool import MHATokenToKVPool ...
98
3,417
sglang
python/sglang/srt/mem_cache/storage/aibrix_kvcache/aibrix_kvcache_storage.py
.py
import logging from typing import Any, List, Optional import torch from aibrix_kvcache import ( BaseKVCacheManager, BlockHashes, KVCacheBlockLayout, KVCacheBlockSpec, KVCacheConfig, KVCacheTensorSpec, ModelSpec, ) from aibrix_kvcache.common.absl_logging import log_every_n_seconds from sgla...
158
5,566
sglang
python/sglang/srt/mem_cache/storage/umbp/umbp_store.py
.py
"""UMBPStore — HiCache L3 storage backend using UMBP (local DRAM + SSD). Follows the same pattern as MooncakeStore: - Zero-copy v1 interface (batch_get_v1 / batch_set_v1) - Uses mem_pool_host.get_page_buffer_meta() for pointer/size extraction - Key suffix generation per TP rank / PP rank """ import logging import os ...
1,707
72,079
sglang
python/sglang/srt/mem_cache/storage/umbp/umbp_host_allocator.py
.py
import ctypes import logging import math import os from typing import Any, Dict import torch from sglang.srt.mem_cache.pool_host.common import HostTensorAllocator logger = logging.getLogger(__name__) def _bool_env(name: str, default: bool) -> bool: raw = os.getenv(name) if raw is None: return defau...
143
4,761
sglang
python/sglang/srt/mem_cache/storage/mmap/__init__.py
.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to SGLang project """Mmap allocator storage backend helpers for SGLang HiCache.""" from .mmap_allocator import alloc_mmap, alloc_shm __all__ = [ "alloc_mmap", "alloc_shm", ]
12
272
sglang
python/sglang/srt/mem_cache/storage/mmap/mmap_allocator.py
.py
import ctypes import ctypes.util import logging import math import mmap import os import uuid import weakref import torch from sglang.srt.environ import envs logger = logging.getLogger(__name__) # Load libc once at module level so munmap is callable safely at GC/shutdown time. # Resolve the SONAME via find_library ...
202
7,576
sglang
python/sglang/srt/mem_cache/cpp_radix_tree/radix_tree.py
.py
from __future__ import annotations import os from typing import TYPE_CHECKING, List, Optional, Tuple import torch from torch.utils.cpp_extension import load _abs_path = os.path.dirname(os.path.abspath(__file__)) radix_tree_cpp = load( name="radix_tree_cpp", sources=[ f"{_abs_path}/tree_v2_binding.cpp...
183
7,179
sglang
python/sglang/srt/mem_cache/allocator/mamba.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, software dis...
98
3,779
sglang
python/sglang/srt/mem_cache/allocator/hisparse.py
.py
import weakref import torch from sglang.srt.mem_cache.allocator.base import BaseTokenToKVPoolAllocator from sglang.srt.mem_cache.allocator.paged import PagedTokenToKVPoolAllocator from sglang.srt.mem_cache.deepseek_v4_memory_pool import ( DeepSeekV4TokenToKVPool, HiSparseC4DevicePool, ) from sglang.srt.mem_ca...
589
21,164
sglang
python/sglang/srt/mem_cache/allocator/swa.py
.py
import torch from sglang.srt.mem_cache.allocator.base import BaseTokenToKVPoolAllocator from sglang.srt.mem_cache.allocator.paged import PagedTokenToKVPoolAllocator from sglang.srt.mem_cache.allocator.token import TokenToKVPoolAllocator from sglang.srt.mem_cache.base_swa_memory_pool import BaseSWAKVPool from sglang.sr...
528
18,032
sglang
python/sglang/srt/mem_cache/allocator/paged.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, software dis...
348
11,705
sglang
python/sglang/srt/mem_cache/allocator/token.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, software dis...
85
2,800
sglang
python/sglang/srt/mem_cache/allocator/__init__.py
.py
"""Token-to-KV-slot allocators. One file per allocation strategy.""" from sglang.srt.mem_cache.allocator.base import BaseTokenToKVPoolAllocator from sglang.srt.mem_cache.allocator.paged import ( PagedTokenToKVPoolAllocator, alloc_extend_naive, ) from sglang.srt.mem_cache.allocator.token import TokenToKVPoolAll...
16
467
sglang
python/sglang/srt/mem_cache/allocator/base.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, software dis...
150
4,967
sglang
python/sglang/srt/mem_cache/pool_host/hisparse.py
.py
from __future__ import annotations import logging from typing import Optional import torch logger = logging.getLogger(__name__) class HiSparseHostPoolMixin: def _round_up_to_page_size(self, size: int) -> int: return (size + self.page_size - 1) // self.page_size * self.page_size def alloc_page(self...
72
2,494
sglang
python/sglang/srt/mem_cache/pool_host/mla.py
.py
from __future__ import annotations import logging from typing import Optional, Sequence import torch from sglang.kernels.ops.kvcache.hicache import ( can_use_hicache_jit_kernel, can_use_write_back_jit_kernel, ) from sglang.kernels.ops.kvcache.hicache import ( transfer_hicache_all_layer_mla as jit_transfe...
642
26,433
sglang
python/sglang/srt/mem_cache/pool_host/__init__.py
.py
from sglang.srt.mem_cache.pool_host.base import HostKVCache from sglang.srt.mem_cache.pool_host.common import HostTensorAllocator __all__ = [ "HostKVCache", "HostTensorAllocator", ]
8
191
sglang
python/sglang/srt/mem_cache/pool_host/common.py
.py
from __future__ import annotations import json import logging import os from collections import defaultdict import torch from sglang.srt.mem_cache.storage.mmap import alloc_mmap logger = logging.getLogger(__name__) class HostTensorAllocator: def __init__(self): """Initialize the HostTensorAllocator.""...
184
5,443
sglang
python/sglang/srt/mem_cache/pool_host/mha.py
.py
from __future__ import annotations import logging import threading from typing import Sequence import psutil import torch from sglang.kernels.ops.kvcache.hicache import ( can_use_hicache_jit_kernel, can_use_write_back_jit_kernel, ) from sglang.kernels.ops.kvcache.hicache import ( transfer_hicache_all_lay...
1,399
56,326
sglang
python/sglang/srt/mem_cache/pool_host/base.py
.py
from __future__ import annotations import abc import logging import threading from functools import wraps from typing import Optional import psutil import torch from sglang.srt.mem_cache.memory_pool import KVCache from sglang.srt.mem_cache.pool_host.common import ( _cuda_host_unregister, get_allocator_from_s...
395
14,121
sglang
python/sglang/srt/mem_cache/cpp_utils/native_hash.py
.py
import os import platform import sys from array import array from functools import lru_cache from typing import Any, Optional def _cpu_supports_avx2() -> bool: if platform.machine().lower() not in ("x86_64", "amd64"): return False try: with open("/proc/cpuinfo", "r", encoding="utf-8", errors="...
87
2,811
sglang
python/sglang/srt/mem_cache/unified_cache/unified_tree_core_interface.py
.py
"""Interface of the TreeCore: the radix tree mechanism that owns the tree structure, per-node values, the LRU(s), and bookkeeping. The Controller drives a TreeCore exclusively through this surface, so an alternative implementation (e.g. a Rust TreeCore) can satisfy it without subclassing the Python tree. """ from __fu...
524
16,906
sglang
python/sglang/srt/mem_cache/unified_cache/component_type.py
.py
"""The per-attention component identity; a leaf module importable from anywhere.""" from enum import Enum class ComponentType(int, Enum): """Integer enum so that per-node list/tuple storage can be indexed directly.""" FULL = 0 SWA = 1 MAMBA = 2 def __str__(self) -> str: # keep human-readable l...
30
667
sglang
python/sglang/srt/mem_cache/unified_cache/__init__.py
.py
"""Components of Unified Radix Cache. - **TreeCore** (``unified_tree_core.UnifiedTreeCore``): the pure tree mechanism. Owns the tree structure, per-node values, the LRU(s), bookkeeping, and KV-cache events -- the only object that touches that state; no scheduling policy or IO, and never touches the cache. Refere...
19
1,094
sglang
python/sglang/srt/mem_cache/unified_cache/session_ref_tracker.py
.py
"""Session ref tracking for UnifiedRadixCache (``--enable-session-radix-cache``): tag each request's KV by session_id for each tree component; ``release_radix_session`` (close) releases a session's tagged reference. """ from __future__ import annotations import logging from collections import OrderedDict from datacla...
119
4,447
sglang
python/sglang/srt/mem_cache/unified_cache/unified_tree_core.py
.py
"""The radix tree mechanism. ``UnifiedTreeCore`` owns the tree's member-var state -- the tree structure (root node), the per-component LRU lists, the per-component size counters, the evictable device/host leaf sets, and the empty match result -- plus ``reset()``. It also defines the tree's building blocks (``UnifiedTr...
2,499
102,228
sglang
python/sglang/srt/mem_cache/unified_cache/cache_action.py
.py
"""A TreeCore emits CacheActions through the TreeCoreInterface to guide Controller behavior. """ from __future__ import annotations from typing import TYPE_CHECKING import msgspec from sglang.srt.mem_cache.unified_cache.component_type import ComponentType if TYPE_CHECKING: import torch from sglang.srt.mem...
104
3,246
sglang
python/sglang/srt/mem_cache/unified_cache/tree_core_registry.py
.py
"""Registry for pluggable TreeCore implementations. The unified cache constructs its TreeCore through `create_tree_core`, selected by SGLANG_UNIFIED_RADIX_TREE_CORE_BACKEND (default "python"). To plug in a custom implementation, register it under a string name via `register_tree_core_backend(name, factory)`. """ from...
74
2,564
sglang
python/sglang/srt/mem_cache/unified_cache/components/full_component.py
.py
from __future__ import annotations import heapq from typing import TYPE_CHECKING, Callable, Optional, Sequence import torch from sglang.srt.mem_cache.base_prefix_cache import ( DecLockRefParams, IncLockRefResult, InsertResult, MatchPrefixParams, MatchResult, ) from sglang.srt.mem_cache.hicache_st...
445
16,340
sglang
python/sglang/srt/mem_cache/unified_cache/components/__init__.py
.py
from sglang.srt.mem_cache.unified_cache.components.full_component import FullComponent from sglang.srt.mem_cache.unified_cache.components.mamba_component import MambaComponent from sglang.srt.mem_cache.unified_cache.components.swa_component import SWAComponent from sglang.srt.mem_cache.unified_cache.components.tree_com...
36
1,006
sglang
python/sglang/srt/mem_cache/unified_cache/components/swa_component.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Callable, Optional, Sequence import torch from sglang.srt.mem_cache.base_prefix_cache import ( DecLockRefParams, IncLockRefResult, InsertParams, InsertResult, MatchPrefixParams, MatchResult, ) from sglang.srt.mem_cache.commo...
1,140
45,936
sglang
python/sglang/srt/mem_cache/unified_cache/components/mamba_component.py
.py
from __future__ import annotations from collections import defaultdict from typing import TYPE_CHECKING, Callable, Optional, Sequence import torch from sglang.srt.mem_cache.base_prefix_cache import ( DecLockRefParams, EvictParams, IncLockRefResult, InsertParams, InsertResult, MatchPrefixParam...
931
37,211
sglang
python/sglang/srt/mem_cache/unified_cache/components/tree_component.py
.py
from __future__ import annotations import dataclasses from abc import ABC, abstractmethod from collections import defaultdict from enum import Enum, IntFlag from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence import torch from numpy import float64 from sglang.srt.mem_cache.base_prefix_cache import ( ...
703
27,344
sglang
python/sglang/srt/mem_cache/sparsity/__init__.py
.py
from sglang.srt.mem_cache.sparsity.algorithms import ( BaseSparseAlgorithm, BaseSparseAlgorithmImpl, DeepSeekDSAAlgorithm, QuestAlgorithm, ) from sglang.srt.mem_cache.sparsity.backend import BackendAdaptor, FlashAttentionAdaptor from sglang.srt.mem_cache.sparsity.core import SparseConfig, SparseCoordina...
30
843
sglang
python/sglang/srt/mem_cache/sparsity/factory.py
.py
import json import logging from typing import Optional import torch from sglang.srt.mem_cache.sparsity.algorithms.base_algorithm import BaseSparseAlgorithm from sglang.srt.mem_cache.sparsity.algorithms.deepseek_dsa import DeepSeekDSAAlgorithm from sglang.srt.mem_cache.sparsity.algorithms.quest_algorithm import QuestA...
155
5,092
sglang
python/sglang/srt/mem_cache/sparsity/algorithms/quest_algorithm.py
.py
""" Quest sparse attention algorithm. This implementation follows the Quest paper's bounding-box estimation for query-aware page selection. For each KV page, it maintains per-dimension min/max of keys and uses them to upper-bound attention scores without materializing full dot products. """ import logging import tor...
167
5,889
sglang
python/sglang/srt/mem_cache/sparsity/algorithms/__init__.py
.py
from sglang.srt.mem_cache.sparsity.algorithms.base_algorithm import ( BaseSparseAlgorithm, BaseSparseAlgorithmImpl, ) from sglang.srt.mem_cache.sparsity.algorithms.deepseek_dsa import DeepSeekDSAAlgorithm from sglang.srt.mem_cache.sparsity.algorithms.quest_algorithm import QuestAlgorithm __all__ = [ "BaseS...
14
420
sglang
python/sglang/srt/mem_cache/sparsity/algorithms/base_algorithm.py
.py
from abc import ABC, abstractmethod from typing import TYPE_CHECKING import torch if TYPE_CHECKING: from sglang.srt.model_executor.forward_batch_info import ForwardBatch class BaseSparseAlgorithm(ABC): """ Abstract base class for sparse attention algorithms. This class provides a unified interface ...
384
14,611
sglang
python/sglang/srt/mem_cache/sparsity/algorithms/deepseek_dsa.py
.py
from typing import Any, Optional import torch from sglang.srt.mem_cache.sparsity.algorithms.base_algorithm import ( BaseSparseAlgorithmImpl, ) class DeepSeekDSAAlgorithm(BaseSparseAlgorithmImpl): """ Sparse attention algorithm for DeepSeek DSA. This algorithm uses DSA's native indexer for TopK retr...
81
1,962
sglang
python/sglang/srt/mem_cache/sparsity/core/sparse_coordinator.py
.py
import logging from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Optional import torch from sglang.srt.mem_cache.memory_pool import KVCache, ReqToTokenPool from sglang.srt.mem_cache.sparsity.algorithms.base_algorithm import BaseSparseAlgorithm from sglang.srt.mem_cache.sparsity.backend.b...
277
9,471
sglang
python/sglang/srt/mem_cache/sparsity/core/__init__.py
.py
from sglang.srt.mem_cache.sparsity.core.sparse_coordinator import ( RequestTrackers, SparseConfig, SparseCoordinator, ) __all__ = [ "RequestTrackers", "SparseConfig", "SparseCoordinator", ]
12
215
sglang
python/sglang/srt/mem_cache/sparsity/backend/__init__.py
.py
from sglang.srt.mem_cache.sparsity.backend.backend_adaptor import ( BackendAdaptor, DSABackendAdaptor, FlashAttentionAdaptor, ) __all__ = ["BackendAdaptor", "FlashAttentionAdaptor", "DSABackendAdaptor"]
8
216
sglang
python/sglang/srt/mem_cache/sparsity/backend/backend_adaptor.py
.py
import logging from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any, Optional import torch if TYPE_CHECKING: from sglang.srt.model_executor.forward_batch_info import ForwardBatch logger = logging.getLogger(__name__) class BackendAdaptor(ABC): """Base class for attention backend adaptor...
177
5,610
sglang
python/sglang/srt/mem_cache/hybrid_cache/hybrid_cache_controller.py
.py
from __future__ import annotations import json import logging import os import threading import time from queue import Empty, Queue from typing import TYPE_CHECKING, Any, Callable, List, Optional import torch from sglang.srt.managers.cache_controller import CacheOperation as BaseCacheOperation from sglang.srt.manage...
967
38,506
sglang
python/sglang/srt/mem_cache/hybrid_cache/hybrid_pool_assembler.py
.py
from __future__ import annotations import logging from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Callable, Optional from sglang.srt.mem_cache.hicache_storage import ( PoolHitPolicy, PoolName, SidecarPoolSpec, ) from sglang.srt.mem_cache.hybrid_cache.hybrid_cache_controller...
1,891
68,907
sglang
python/sglang/srt/mem_cache/layout/page_major.py
.py
"""Page-granularity envelope (page-major, layer-major within a page) cache views. A pool of this layout keeps all layers of all slots in one contiguous byte buffer. The buffer is split into pages of ``page_size`` slots; within a page, each layer's K and V (or each Mamba conv/temporal tensor) are grouped together: ...
298
11,677
sglang
python/sglang/srt/disaggregation/decode_kvcache_offload_manager.py
.py
from __future__ import annotations import json import logging import threading import time from typing import TYPE_CHECKING import torch from sglang.srt.disaggregation.kv_events import OffloadedState from sglang.srt.environ import envs from sglang.srt.managers.cache_controller import HiCacheController from sglang.sr...
361
14,576
sglang
python/sglang/srt/disaggregation/decode_schedule_batch_mixin.py
.py
from __future__ import annotations import logging from array import array from http import HTTPStatus from typing import TYPE_CHECKING, List import torch from sglang.srt.managers.overlap_utils import RelayPayload from sglang.srt.mem_cache.common import maybe_cache_unfinished_req from sglang.srt.model_executor.forwar...
160
6,908
sglang
python/sglang/srt/disaggregation/utils.py
.py
from __future__ import annotations import os import random from collections import deque from contextlib import nullcontext from enum import Enum from typing import ( TYPE_CHECKING, Iterable, List, Literal, Optional, Tuple, Type, overload, ) import numpy as np import torch import torch...
1,309
51,068
sglang
python/sglang/srt/disaggregation/encode_receiver.py
.py
import asyncio import itertools import logging import random import threading import time import uuid import weakref from abc import ABC, abstractmethod from array import array from collections import OrderedDict, defaultdict from contextlib import asynccontextmanager from enum import IntEnum from http import HTTPStatu...
2,621
104,931
sglang
python/sglang/srt/disaggregation/prefill.py
.py
""" Life cycle of a request in the prefill server 1. Bootstrap Queue a. Initialize a sender for each request b. Use the queue to store requests whose bootstrap (handshake and preallocation) has not finished c. Poll senders to check bootstrap state d. Once bootstrap is complete, move request to Waiting ...
1,363
56,837
sglang
python/sglang/srt/disaggregation/encode_server.py
.py
import asyncio import concurrent.futures import contextlib import ctypes import functools import logging import multiprocessing as mp import os import pickle import threading import time import traceback import uuid from collections import defaultdict from dataclasses import dataclass from http import HTTPStatus from t...
4,563
185,304
sglang
python/sglang/srt/disaggregation/kv_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, software dis...
489
16,535
sglang
python/sglang/srt/disaggregation/decode_hicache_mixin.py
.py
"""HiCache integration mixins for the decode side of PD disaggregation""" from __future__ import annotations import logging from dataclasses import dataclass from enum import Enum from typing import TYPE_CHECKING, Any, List, Optional import torch from sglang.srt.disaggregation.base import KVPoll from sglang.srt.man...
312
12,072
sglang
python/sglang/srt/disaggregation/decode.py
.py
""" Life cycle of a request in the decode server 1. PreallocQueue: a. Initialize a receiver for each request b. The request handshakes first, and pre-allocate kv once there is available kv. c. Move the request to TransferQueue. 2. TransferQueue: a. Poll the receiver to check the transfer state b. ...
2,381
101,654
sglang
python/sglang/srt/disaggregation/encode_grpc_server.py
.py
""" gRPC Encoder Server for SGLang EPD (Encode-Prefill-Decode) mode. This server provides gRPC-based encoding for multimodal inputs. Usage: python -m sglang.launch_server --model-path <model> --encoder-only --grpc-mode """ import asyncio import logging import multiprocessing as mp import traceback from concurren...
277
9,891
sglang
python/sglang/srt/disaggregation/base/conn.py
.py
from __future__ import annotations import dataclasses import enum from abc import ABC, abstractmethod from typing import TYPE_CHECKING, List, Optional import numpy as np import numpy.typing as npt from sglang.srt.server_args import ServerArgs if TYPE_CHECKING: from sglang.srt.disaggregation.utils import Disaggr...
246
6,600
sglang
python/sglang/srt/disaggregation/base/__init__.py
.py
from sglang.srt.disaggregation.base.conn import ( BaseKVBootstrapServer, BaseKVManager, BaseKVReceiver, BaseKVSender, KVArgs, KVPoll, )
9
160
sglang
python/sglang/srt/disaggregation/nixl/conn.py
.py
from __future__ import annotations import dataclasses import json import logging import struct import threading import time import uuid from collections import defaultdict from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple import numpy as np import numpy.typing as npt import zmq if TYPE_CHECKING...
3,068
127,372
sglang
python/sglang/srt/disaggregation/nixl/__init__.py
.py
from sglang.srt.disaggregation.nixl.conn import ( NixlKVBootstrapServer, NixlKVManager, NixlKVReceiver, NixlKVSender, )
7
136
sglang
python/sglang/srt/disaggregation/mooncake/conn.py
.py
from __future__ import annotations import concurrent.futures import dataclasses import logging import os import struct import threading import time from collections import defaultdict from typing import List, Optional, Set, Tuple, Union import numpy as np import numpy.typing as npt import zmq from prometheus_client i...
2,546
109,696
sglang
python/sglang/srt/disaggregation/mooncake/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...
113
4,049
sglang
python/sglang/srt/disaggregation/mooncake/__init__.py
.py
from sglang.srt.disaggregation.mooncake.conn import ( MooncakeKVBootstrapServer, MooncakeKVManager, MooncakeKVReceiver, MooncakeKVSender, )
7
156
sglang
python/sglang/srt/disaggregation/fake/conn.py
.py
import logging from typing import List, Optional import numpy as np import numpy.typing as npt from sglang.srt.disaggregation.base.conn import ( BaseKVManager, BaseKVReceiver, BaseKVSender, KVArgs, KVPoll, KVTransferMetric, ) from sglang.srt.disaggregation.utils import DisaggregationMode from ...
141
3,930
sglang
python/sglang/srt/disaggregation/fake/__init__.py
.py
from sglang.srt.disaggregation.fake.conn import ( FakeKVManager, FakeKVReceiver, FakeKVSender, )
6
109
sglang
python/sglang/srt/disaggregation/mori/conn.py
.py
from __future__ import annotations import dataclasses import logging import os import struct import threading import time import uuid from typing import Dict, List, Optional, Tuple import msgspec import numpy as np import numpy.typing as npt import zmq from mori.cpp import TransferStatus from mori.io import ( Bac...
1,812
68,918
sglang
python/sglang/srt/disaggregation/mori/__init__.py
.py
from sglang.srt.disaggregation.mori.conn import ( MoriKVBootstrapServer, MoriKVManager, MoriKVReceiver, MoriKVSender, )
7
136
sglang
python/sglang/srt/disaggregation/common/conn.py
.py
from __future__ import annotations import asyncio import concurrent.futures import dataclasses import logging import threading import time from collections import defaultdict from typing import Dict, List, Optional, Set, Tuple, Union import numpy as np import numpy.typing as npt import requests import torch.distribut...
1,822
79,084
sglang
python/sglang/srt/disaggregation/common/utils.py
.py
import ctypes import dataclasses import struct import threading from collections import deque from typing import List, Optional, Tuple, Union import numpy as np import numpy.typing as npt from sglang.srt.observability.trace import ( TraceNullContext, TraceReqContext, ) @dataclasses.dataclass class TransferK...
202
6,895
sglang
python/sglang/srt/disaggregation/common/staging_handler.py
.py
""" Staging handler for heterogeneous TP KV cache transfer. Isolates staging scatter lifecycle from decode.py and conn.py. Generic (backend-agnostic) code is at the top; mooncake-specific protocol code is at the bottom. """ from __future__ import annotations import dataclasses import logging import threading import ...
892
35,339
sglang
python/sglang/srt/disaggregation/common/__init__.py
.py
from sglang.srt.disaggregation.common.conn import ( CommonKVBootstrapServer, CommonKVManager, CommonKVReceiver, )
6
126
sglang
python/sglang/srt/disaggregation/common/staging_buffer.py
.py
""" GPU Staging Buffer for heterogeneous TP KV cache transfer. When prefill attn_tp_size != decode attn_tp_size, the per-token RDMA approach generates O(tokens * layers) small RDMA requests. This module provides a staging buffer mechanism that gathers scattered head slices into contiguous GPU memory, enabling bulk RDM...
800
26,135
sglang
python/sglang/srt/disaggregation/ascend/conn.py
.py
import concurrent.futures import enum import logging from typing import List, Optional, Tuple import numpy as np import numpy.typing as npt from sglang.srt.disaggregation.ascend.transfer_engine import AscendTransferEngine from sglang.srt.disaggregation.base.conn import StateType from sglang.srt.disaggregation.common....
240
9,172
sglang
python/sglang/srt/disaggregation/ascend/__init__.py
.py
from sglang.srt.disaggregation.ascend.conn import ( AscendKVBootstrapServer, AscendKVManager, AscendKVReceiver, AscendKVSender, )
7
146
sglang
python/sglang/srt/disaggregation/ascend/transfer_engine.py
.py
import logging import os from typing import List import torch from sglang.srt.disaggregation.utils import DisaggregationMode from sglang.srt.distributed.device_communicators.mooncake_transfer_engine import ( MooncakeTransferEngine, ) from sglang.srt.utils.network import NetworkAddress try: from memfabric_hyb...
106
3,874
sglang
python/sglang/srt/tokenizer/tiktoken_tokenizer.py
.py
import functools import json from typing import AbstractSet, Collection, List, Literal, Union class TiktokenProcessor: def __init__(self, name: str): self.tokenizer = TiktokenTokenizer(name) def image_processor(self, image): return {"pixel_values": [image]} RESERVED_TOKEN_TEXTS = [f"<|reser...
187
7,272
sglang
python/sglang/srt/layers/attn_residual.py
.py
# SPDX-License-Identifier: Apache-2.0 # Kimi-K3 Attention Residual: snapshot bank + aggregation. # # The public API is the AttnResidual class (constructed once per forward pass). # It owns the frozen snapshot bank [T, NB, H] and the valid-row counter, and # dispatches each aggregation point (score rows → softmax → weig...
604
19,681
sglang
python/sglang/srt/layers/parameter.py
.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/model_executor/parameter.py""" import logging from fractions import Fraction from typing import Callable, Optional, Union import torch ...
602
19,971
sglang
python/sglang/srt/layers/radix_attention.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...
615
22,475
sglang
python/sglang/srt/layers/logits_processor.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...
1,013
42,747
sglang
python/sglang/srt/layers/radix_linear_attention.py
.py
# Copyright 2025-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...
163
5,322
sglang
python/sglang/srt/layers/communicator_dsa_cp.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...
248
9,736
sglang
python/sglang/srt/layers/linear.py
.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/model_executor/layers/linear.py""" from __future__ import annotations import itertools import logging from typing import TYPE_CHECKING,...
1,775
72,182
sglang
python/sglang/srt/layers/logprob_processor.py
.py
from __future__ import annotations import dataclasses import logging from enum import Enum, auto from typing import TYPE_CHECKING, Callable, List, Optional, Tuple import torch from sglang.srt.environ import envs from sglang.srt.runtime_context import get_exec if TYPE_CHECKING: from sglang.srt.layers.logits_proc...
858
33,206
sglang
python/sglang/srt/layers/k3_gemm_ar.py
.py
"""K3 fused o_proj GEMM+AR dispatch (``SGLANG_K3_GEMM_AR``). Glue between the model and ``kernels.ops.kimi_k3.gemm_ar``: lazily allocates the P2P comm region on the TP group and swaps the o_proj RowParallelLinear forward for the single fused GEMM+all-reduce kernel at decode shapes (falling through to the regular GEMM ...
96
3,012
sglang
python/sglang/srt/layers/aux_hidden_states.py
.py
"""Aux hidden states captured for Eagle3/DFlash draft models.""" from typing import List, Optional, Union import torch # Two representations coexist: models migrated to AuxHiddenStatePacker pass one # packed [tokens, K * hidden] tensor, the rest still pass a list of K tensors. AuxHiddenStates = Union[torch.Tensor, L...
59
2,209
sglang
python/sglang/srt/layers/layernorm.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...
1,378
53,623
sglang
python/sglang/srt/layers/sparse_pooler.py
.py
from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F from transformers import PretrainedConfig from sglang.srt.model_executor.model_runner import ForwardBatch @dataclass class SparseEmbeddingOutput: embeddings: torch.Tensor # [batch_size, vocab_size] class Spar...
99
3,424
sglang
python/sglang/srt/layers/activation.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...
505
18,264
sglang
python/sglang/srt/layers/flashinfer_comm_fusion.py
.py
import inspect import logging from typing import Optional, Tuple import torch import torch.distributed as dist from torch.distributed import ProcessGroup from sglang.srt.distributed import ( get_attn_tp_group, get_moe_ep_group, get_moe_tp_group, get_tp_group, ) from sglang.srt.distributed.parallel_sta...
1,007
37,382
sglang
python/sglang/srt/layers/k3_sp_collective.py
.py
"""K3 SP-MoE MNNVL reduce-scatter/all-gather dispatch. The reduce-scatter folds the pending attention residual into its reduction epilogue. The matching all-gather reassembles the token shards after MoE. Both reuse CustomAllReduceV2's push workspace and fall back as a pair outside the checked-in GB300 tuning envelope...
470
14,876
sglang
python/sglang/srt/layers/clippable_linear.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...
284
11,516
sglang
python/sglang/srt/layers/conv.py
.py
""" Conv2d/Conv3d layers with unfold+linear optimization for patch embeddings. When kernel_size == stride, padding == 0, dilation == 1, groups == 1, the conv is equivalent to unfold + F.linear, which is significantly faster on CUDA and also avoids the PyTorch 2.9.1 + CuDNN < 9.15 Conv3d bug (https://github.com/pytorch...
320
11,154
sglang
python/sglang/srt/layers/rocm_linear_utils.py
.py
import torch from aiter.ops.triton.fused_kv_cache import fused_qk_rope_cat_and_cache_mla from aiter.ops.triton.fused_qk_concat import fused_qk_rope_cat from aiter.tuned_gemm import tgemm __all__ = ["fused_qk_rope_cat", "fused_qk_rope_cat_and_cache_mla"] def aiter_dsv3_router_gemm( hidden_states: torch.Tensor, ...
26
839
sglang
python/sglang/srt/layers/communicator.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...
1,473
57,957
sglang
python/sglang/srt/layers/modelopt_utils.py
.py
""" ModelOpt related constants """ QUANT_CFG_CHOICES = { "fp8": "FP8_DEFAULT_CFG", "int4_awq": "INT4_AWQ_CFG", # TODO: add support for int4_awq "w4a8_awq": "W4A8_AWQ_BETA_CFG", # TODO: add support for w4a8_awq "nvfp4": "NVFP4_DEFAULT_CFG", "nvfp4_awq": "NVFP4_AWQ_LITE_CFG", # TODO: add support f...
12
335
sglang
python/sglang/srt/layers/zero_copy_context.py
.py
import contextlib from typing import Iterator, Optional import msgspec import torch class ZeroCopyContext(msgspec.Struct, frozen=True): moe_output: Optional[torch.Tensor] = None ctx = ZeroCopyContext() @contextlib.contextmanager def set_moe_output(out: torch.Tensor) -> Iterator[None]: """Publish `out` as...
57
1,495
sglang
python/sglang/srt/layers/model_parallel.py
.py
""" Common utilities for torch model parallelism. """ import logging from typing import Optional, Sequence import torch import torch.nn as nn from torch.distributed.device_mesh import DeviceMesh logger = logging.getLogger(__name__) try: import torch.distributed.tensor as dt except ImportError: # torch 2.4 o...
170
6,401
sglang
python/sglang/srt/layers/int4fp8_utils.py
.py
""" Common utilities for quark. """ import logging from typing import Tuple import torch logger = logging.getLogger(__name__) def quantize_fp8_scale_tensorwise(w: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: FP8_MAX = 448.0 scale = w.abs().amax().float() / FP8_MAX scaled = (w / scale).clamp(-FP8...
74
2,559
sglang
python/sglang/srt/layers/n_gram_embedding.py
.py
import torch from torch import nn from torch.nn import Parameter from sglang.kernels.ops.speculative.ngram_embedding import compute_n_gram_ids from sglang.srt.layers.dp_attention import is_dp_attention_enabled from sglang.srt.layers.vocab_parallel_embedding import VocabParallelEmbedding from sglang.srt.model_executor....
184
7,748