Documentation
¶
Overview ¶
Copyright 2024 The Aibrix 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 distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright 2024 The Aibrix 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 distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright 2024 The Aibrix 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 distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Index ¶
- Constants
- Variables
- func ApplyLoadImbalanceGate(ctx *types.RoutingContext, c cache.Cache, readyPods []*v1.Pod) []*v1.Pod
- func GetPodModelMetricsSimplePrometheusValue(cache cache.Cache, podname, namespace, modelname, metricname string) float64
- func GetPodModelMetricsSimpleValue(cache cache.Cache, podname, namespace, modelname, metricname string) float64
- func HasEligibleRoleset(readyPods []*v1.Pod) bool
- func Init()
- func Lookup(algorithm types.RoutingAlgorithm) (types.Router, error)
- func NewExternalRouter() (types.Router, error)
- func NewExternalRouterWithCache(metricCache cache.Cache) (types.Router, error)
- func NewLeastBusyTimeRouter() (types.Router, error)
- func NewLeastExpectedLatencyRouter() (types.Router, error)
- func NewLeastGpuCacheRouter() (types.Router, error)
- func NewLeastKvCacheRouter() (types.Router, error)
- func NewLeastKvCacheRouterWithCache(c cache.Cache) (types.Router, error)
- func NewLeastLatencyRouterWithCache(c cache.Cache) (types.Router, error)
- func NewLeastLoadPullingRouter(provider cache.CappedLoadProvider) (types.Router, error)
- func NewLeastLoadRouter(provider cache.LoadProvider) (types.Router, error)
- func NewLeastRequestRouter() (types.Router, error)
- func NewLeastRequestRouterWithCache(c cache.Cache) (types.Router, error)
- func NewLeastRequestTopKRouter() (types.Router, error)
- func NewLeastUtilRouter() (types.Router, error)
- func NewLoadBalanceRouter() (types.Router, error)
- func NewLoadBalanceRouterWithCache(c cache.Cache) (types.Router, error)
- func NewPDRouter() (types.Router, error)
- func NewPDRouterWithCacheAndPrefixIndexer(c cache.Cache, sharedPrefixTable *prefixcacheindexer.PrefixHashTable) (types.Router, error)
- func NewPackLoadRouter(provider cache.CappedLoadProvider) (types.Router, error)
- func NewPowerOfTwoRouter() (types.Router, error)
- func NewPrefixCacheAndLoadRouter() (types.Router, error)
- func NewPrefixCacheRouter() (types.Router, error)
- func NewPrefixCacheRouterWithCache(c cache.Cache) (types.Router, error)
- func NewPrefixCacheRouterWithOptions(c cache.Cache, indexer *prefixcacheindexer.PrefixHashTable) (types.Router, error)
- func NewQueueRouter(backend types.Router, queue types.RouterQueue[*types.QueueEntry]) (types.QueueRouter, error)
- func NewRandomRouter() (types.Router, error)
- func NewSLORouter(modelName string) (types.QueueRouter, error)
- func NewSessionAffinityRouter() (types.Router, error)
- func NewThroughputRouter() (types.Router, error)
- func Register(algorithm types.RoutingAlgorithm, constructor types.RouterConstructor)
- func RegisterProvider(algorithm types.RoutingAlgorithm, provider types.RouterProviderFunc)
- func ResolveExclusiveStrategy(algStr string) (string, bool)
- func ResolveRoutingOverrides(routingCtx *types.RoutingContext)
- func RouteByScore(ctx *types.RoutingContext, readyPodList types.PodList, scorer types.PodScorer) (*v1.Pod, error)
- func Select(ctx *types.RoutingContext) (types.Router, error)
- func SelectByScore(pods []*v1.Pod, scores []float64, scored []bool, polarity types.Polarity) *v1.Pod
- func SelectRandomPodAsFallback(ctx *types.RoutingContext, pods []*v1.Pod, randomFunc func(int) int) (*v1.Pod, error)
- func SetFallback(router types.Router, fallback types.RoutingAlgorithm) error
- func Validate(algorithms string) (types.RoutingAlgorithm, bool)
- func ValidateAndGetLLMEngine(pods []*v1.Pod) (string, error)
- type FallbackRouter
- type LeastRequestTopKRouter
- func (r *LeastRequestTopKRouter) Polarity() types.Polarity
- func (r *LeastRequestTopKRouter) Route(ctx *types.RoutingContext, readyPodList types.PodList) (string, error)
- func (r *LeastRequestTopKRouter) ScoreAll(ctx *types.RoutingContext, readyPodList types.PodList) ([]float64, []bool, error)
- func (r *LeastRequestTopKRouter) SubscribedMetrics() []string
- type MultiRouterConfig
- type PDRolesetEligibility
- type PowerOfTwoRouter
- type PrefillTimeParams
- type PrefixCacheMetrics
- type RedisBackedRouter
- type RouterItem
- type RouterManager
- func DefaultRouterManager() *RouterManager
- func NewRouterManager() *RouterManager
- func NewRouterManagerWithCache(c cache.Cache) *RouterManager
- func NewRouterManagerWithCacheAndPrefixIndexer(c cache.Cache, indexer *prefixcacheindexer.PrefixHashTable) *RouterManager
- func NewRouterManagerWithDefaults() *RouterManager
- func (rm *RouterManager) Init()
- func (rm *RouterManager) InitializationError(algorithm types.RoutingAlgorithm) error
- func (rm *RouterManager) Lookup(algorithm types.RoutingAlgorithm) (types.Router, error)
- func (rm *RouterManager) Register(algorithm types.RoutingAlgorithm, constructor types.RouterConstructor)
- func (rm *RouterManager) RegisterProvider(algorithm types.RoutingAlgorithm, provider types.RouterProviderFunc)
- func (rm *RouterManager) Select(ctx *types.RoutingContext) (types.Router, error)
- func (rm *RouterManager) SetFallback(router types.Router, fallback types.RoutingAlgorithm) error
- func (rm *RouterManager) Validate(algorithms string) (types.RoutingAlgorithm, bool)
- type SLORouter
- type Scores
- type SlidingWindowHistogram
- type TokenizerPool
- type TokenizerPoolConfig
- type TokenizerPoolInterface
- type TokenizerPoolMetrics
Constants ¶
const ( RouterExternal = externalrouter.Algorithm EnvExternalRouterEndpoint = externalrouter.EnvExternalRouterEndpoint EnvExternalRouterPolicyMode = externalrouter.EnvExternalRouterPolicyMode EnvExternalRouterFailureMode = externalrouter.EnvExternalRouterFailureMode EnvExternalRouterFallback = externalrouter.EnvExternalRouterFallback EnvExternalRouterTimeout = externalrouter.EnvExternalRouterTimeout EnvExternalRouterMaxInflight = externalrouter.EnvExternalRouterMaxInflight EnvExternalRouterMaxRequestBytes = externalrouter.EnvExternalRouterMaxRequestBytes EnvExternalRouterMaxResponseBytes = externalrouter.EnvExternalRouterMaxResponseBytes EnvExternalRouterFailureThreshold = externalrouter.EnvExternalRouterFailureThreshold EnvExternalRouterOpenDuration = externalrouter.EnvExternalRouterOpenDuration EnvExternalRouterAuthTokenFile = externalrouter.EnvExternalRouterAuthTokenFile EnvExternalRouterCandidateAttributes = externalrouter.EnvExternalRouterCandidateAttributes EnvExternalRouterCandidateMetrics = externalrouter.EnvExternalRouterCandidateMetrics EnvExternalRouterPolicyAttributes = externalrouter.EnvExternalRouterPolicyAttributes )
const ( RouterPD types.RoutingAlgorithm = "pd" VLLMEngine string = "vllm" SGLangEngine string = "sglang" TensorRTLLM string = "trtllm" LLMEngineIdentifier string = constants.ModelLabelEngine PDRoleSetIdentifier string = "roleset-name" PDRoleIdentifier string = "role-name" PDRolePrefill string = "prefill" PDRoleDecode string = "decode" RoleReplicaIndex string = "stormservice.orchestration.aibrix.ai/role-replica-index" PodGroupIndex string = "stormservice.orchestration.aibrix.ai/pod-group-index" PromptLenBucketMinLength string = "prompt-len-bucket-min-length" PromptLenBucketMaxLength string = "prompt-len-bucket-max-length" )
const ( // KVConnectorTypeIdentifier specifies the KV transfer backend for a PD pod. Supported values include "shfs", "nixl", and "mooncake". KVConnectorTypeIdentifier = "model.aibrix.ai/kv-connector-type" // KV connector types for different backends KVConnectorTypeSHFS = "shfs" // Default - AIBrix SHFS/KVCacheManager (GPU) KVConnectorTypeNIXL = "nixl" // NIXL for Neuron (uses disagg_prefill_resp wrapper) KVConnectorTypeMooncake = "mooncake" // Mooncake KV transfer backend HeaderPrefillTargetPodIP = "prefill-target-pod-ip" HeaderPrefillTargetPod = "prefill-target-pod" )
const ( PREBLE_TARGET_GPU = "AIBRIX_ROUTER_PREBLE_TARGET_GPU" PREBLE_DECODING_LENGTH = "AIBRIX_ROUTER_PREBLE_DECODING_LENGTH" PREBLE_SLIDING_WINDOW_PERIOD = "AIBRIX_ROUTER_PREBLE_SLIDING_WINDOW_PERIOD" PREBLE_EVICTION_LOOP_INTERVAL = "AIBRIX_ROUTER_PREBLE_EVICTION_LOOP_INTERVAL" )
const ( // Default routing algorithm for slo-family algorithms, setting to RouterSLOLeastLoadPulling. RouterSLO types.RoutingAlgorithm = "slo" // SLO-aware routing algorithm that using SLOQueue and packLoadRouter as the backend. RouterSLOPackLoad types.RoutingAlgorithm = "slo-pack-load" // SLO-aware routing algorithm that using SLOQueue and leastLoadRouter (push mode) as the backend. RouterSLOLeastLoad types.RoutingAlgorithm = "slo-least-load" // SLO-aware routing algorithm that using SLOQueue and leastLoadRouter (pull mode) as the backend. RouterSLOLeastLoadPulling types.RoutingAlgorithm = "slo-least-load-pulling" )
const DefaultFallbackAlgorithm types.RoutingAlgorithm = RouterRandom
const RouterLeastBusyTime types.RoutingAlgorithm = "least-busy-time"
const RouterLeastGpuCache types.RoutingAlgorithm = "least-gpu-cache"
const RouterLeastKvCache types.RoutingAlgorithm = "least-kv-cache"
const RouterLeastLatency types.RoutingAlgorithm = "least-latency"
const RouterLeastRequest types.RoutingAlgorithm = "least-request"
const RouterLeastRequestTopK types.RoutingAlgorithm = "least-request-top-k"
const (
RouterNotSet = ""
)
const RouterPowerOfTwo types.RoutingAlgorithm = "power-of-two"
const RouterPrefixCachePreble types.RoutingAlgorithm = "prefix-cache-preble"
const RouterRandom types.RoutingAlgorithm = "random"
const RouterSessionAffinity types.RoutingAlgorithm = "session-affinity"
const RouterThroughput types.RoutingAlgorithm = "throughput"
const RouterUtil types.RoutingAlgorithm = "least-utilization"
Variables ¶
var ( ErrExternalPolicyDenied = externalrouter.ErrExternalPolicyDenied ErrExternalRouterDisabled = externalrouter.ErrExternalRouterDisabled )
var ( RandomRouter = &randomRouter{} RandomRouterProviderFunc = func(_ *types.RoutingContext) (types.Router, error) { return RandomRouter, nil } )
var ( ErrInitTimeout = errors.New("router initialization timeout") ErrFallbackNotSupported = errors.New("router not support fallback") ErrFallbackNotRegistered = errors.New("fallback router not registered") )
var DefaultFallbackRouter types.RouterProviderFunc = RandomRouterProviderFunc
var (
ErrorNoAvailablePod = fmt.Errorf("no pod available")
)
var ModelRouterFactory = NewSLORouter
var RouterLoadBalance types.RoutingAlgorithm = "load-balance"
var (
RouterPrefixCache types.RoutingAlgorithm = "prefix-cache"
)
Functions ¶
func ApplyLoadImbalanceGate ¶ added in v0.8.0
func ApplyLoadImbalanceGate(ctx *types.RoutingContext, c cache.Cache, readyPods []*v1.Pod) []*v1.Pod
ApplyLoadImbalanceGate narrows readyPods to the least-loaded subset when running-request load is severely skewed (see getTargetPodListOnLoadImbalance). Returns readyPods unchanged if not imbalanced.
It is exported so the gateway can apply this hotspot safeguard once, centrally, ahead of whichever routing strategy a request actually resolves to — including "load-balance" itself, whose own Route() relies on the caller having already applied this gate rather than calling it again. Callers should skip invoking this for exclusive strategies (pd, slo*), which manage their own pod subsets and would have their role split disrupted by a blanket running-request-count filter applied ahead of time.
func GetPodModelMetricsSimplePrometheusValue ¶ added in v0.6.0
func GetPodModelMetricsSimpleValue ¶ added in v0.6.0
func HasEligibleRoleset ¶ added in v0.8.0
HasEligibleRoleset reports whether at least one PD roleset has both a prefill and decode pod ready for disaggregated routing.
func NewExternalRouter ¶ added in v0.8.0
func NewExternalRouterWithCache ¶ added in v0.8.0
func NewLeastBusyTimeRouter ¶
func NewLeastGpuCacheRouter ¶ added in v0.4.0
func NewLeastKvCacheRouter ¶
func NewLeastKvCacheRouterWithCache ¶ added in v0.8.0
NewLeastKvCacheRouterWithCache constructs least-kv-cache with an explicit cache.
func NewLeastLatencyRouterWithCache ¶ added in v0.8.0
NewLeastLatencyRouterWithCache constructs least-latency with an explicit cache.
func NewLeastLoadPullingRouter ¶ added in v0.4.0
func NewLeastLoadPullingRouter(provider cache.CappedLoadProvider) (types.Router, error)
NewLeastLoadRouter creates leastLoadRouter instance in the pull mode.
func NewLeastLoadRouter ¶ added in v0.4.0
func NewLeastLoadRouter(provider cache.LoadProvider) (types.Router, error)
NewLeastLoadRouter creates leastLoadRouter instance in the push mode.
func NewLeastRequestRouter ¶
func NewLeastRequestRouterWithCache ¶ added in v0.8.0
NewLeastRequestRouterWithCache constructs least-request with an explicit cache.
func NewLeastRequestTopKRouter ¶ added in v0.8.0
NewLeastRequestTopKRouter creates a LeastRequestTopKRouter backed by the global cache.
func NewLeastUtilRouter ¶ added in v0.4.0
func NewLoadBalanceRouter ¶ added in v0.8.0
func NewLoadBalanceRouterWithCache ¶ added in v0.8.0
NewLoadBalanceRouterWithCache constructs load-balance with an explicit cache.
func NewPDRouter ¶ added in v0.4.0
func NewPDRouterWithCacheAndPrefixIndexer ¶ added in v0.8.0
func NewPDRouterWithCacheAndPrefixIndexer(c cache.Cache, sharedPrefixTable *prefixcacheindexer.PrefixHashTable) (types.Router, error)
NewPDRouterWithCacheAndPrefixIndexer builds a PD router on an explicit cache and prefix table instead of the process-global ones, so an isolated RouterManager (see NewRouterManagerWithCacheAndPrefixIndexer) can route "pd" without initialising the global cache. A nil sharedPrefixTable gets a fresh table.
func NewPackLoadRouter ¶ added in v0.4.0
func NewPackLoadRouter(provider cache.CappedLoadProvider) (types.Router, error)
NewPackLoadRouter creates packLoadRouter instance.
func NewPowerOfTwoRouter ¶ added in v0.8.0
NewPowerOfTwoRouter creates a Power of Two router backed by the global cache.
func NewPrefixCacheRouter ¶
func NewPrefixCacheRouterWithCache ¶ added in v0.8.0
NewPrefixCacheRouterWithCache constructs the prefix-cache router with an explicit cache while preserving tokenizer and indexer behavior.
func NewPrefixCacheRouterWithOptions ¶ added in v0.8.0
func NewPrefixCacheRouterWithOptions(c cache.Cache, indexer *prefixcacheindexer.PrefixHashTable) (types.Router, error)
NewPrefixCacheRouterWithOptions constructs a prefix-cache router with an explicit cache and optional per-instance prefix table. A nil indexer creates a new private table; the production constructor passes the shared table explicitly.
func NewQueueRouter ¶ added in v0.4.0
func NewQueueRouter(backend types.Router, queue types.RouterQueue[*types.QueueEntry]) (types.QueueRouter, error)
func NewRandomRouter ¶
func NewSLORouter ¶ added in v0.4.0
func NewSLORouter(modelName string) (types.QueueRouter, error)
func NewSessionAffinityRouter ¶ added in v0.6.0
func NewThroughputRouter ¶
func Register ¶
func Register(algorithm types.RoutingAlgorithm, constructor types.RouterConstructor)
func RegisterProvider ¶ added in v0.4.0
func RegisterProvider(algorithm types.RoutingAlgorithm, provider types.RouterProviderFunc)
func ResolveExclusiveStrategy ¶ added in v0.8.0
ResolveExclusiveStrategy parses algStr and, if it resolves to a single exclusive strategy (pd, slo*), returns its name and true. algStr may itself already be a multi-strategy string that collapses to one exclusive item (e.g. "pd:1,least-request:1" resolves to "pd") — this lets callers detect exclusivity from the caller's raw, unparsed algorithm string rather than comparing it against the exclusive name directly.
func ResolveRoutingOverrides ¶ added in v0.8.0
func ResolveRoutingOverrides(routingCtx *types.RoutingContext)
ResolveRoutingOverrides turns this request's model config profile into its resolved routing overrides and parks them on the routing context, so every strategy and gate on the routing path reads the same values with a single resolve per request. It is a no-op when the profile sets no applicable knob: the read sites then read the process defaults directly.
func RouteByScore ¶ added in v0.8.0
func RouteByScore(ctx *types.RoutingContext, readyPodList types.PodList, scorer types.PodScorer) (*v1.Pod, error)
RouteByScore is the shared "least-X"/"most-X" routing pattern used by single-metric strategies (least-request, least-kv-cache, least-busy-time, least-gpu-cache, ...): it scores all ready pods via scorer.ScoreAll, picks the best one per scorer.Polarity() breaking ties randomly, and falls back to a uniformly random ready pod when nothing could be scored.
func SelectByScore ¶ added in v0.8.0
func SelectByScore(pods []*v1.Pod, scores []float64, scored []bool, polarity types.Polarity) *v1.Pod
SelectByScore returns the pod with the best score according to polarity (lowest for PolarityLeast, highest for PolarityMost), breaking ties uniformly at random. Pods with scored[i] == false are ignored. Returns nil if no pod could be scored.
best is seeded with +Inf/-Inf rather than the first scored value so a NaN score (e.g. a metric that hasn't warmed up) can never become "best": every comparison against NaN is false, so a pod that started as best could never be dethroned or matched by a real value.
func SelectRandomPodAsFallback ¶
func SelectRandomPodAsFallback(ctx *types.RoutingContext, pods []*v1.Pod, randomFunc func(int) int) (*v1.Pod, error)
SelectRandomPodAsFallback selects a pod randomly as a fallback. This method should only be used when all other selection mechanisms have failed.
func SetFallback ¶ added in v0.4.0
func SetFallback(router types.Router, fallback types.RoutingAlgorithm) error
Types ¶
type FallbackRouter ¶ added in v0.4.0
type FallbackRouter struct {
// contains filtered or unexported fields
}
func (*FallbackRouter) Route ¶ added in v0.4.0
func (r *FallbackRouter) Route(ctx *types.RoutingContext, pods types.PodList) (string, error)
func (*FallbackRouter) SetFallback ¶ added in v0.4.0
func (r *FallbackRouter) SetFallback(fallback types.RoutingAlgorithm, provider types.RouterProviderFunc)
type LeastRequestTopKRouter ¶ added in v0.8.0
type LeastRequestTopKRouter struct {
// contains filtered or unexported fields
}
LeastRequestTopKRouter picks uniformly at random among the ready pods that are both among the K least-loaded and within leastRequestTopKEpsilon of the minimum, instead of always the minimum. Unlike power-of-two, every candidate comes from the least-loaded end of the fleet.
It is a types.Router (Route, as a standalone strategy) and a types.PodScorer (ScoreAll, for blending with other strategies).
func NewLeastRequestTopKRouterWithCache ¶ added in v0.8.0
func NewLeastRequestTopKRouterWithCache(c cache.Cache) *LeastRequestTopKRouter
NewLeastRequestTopKRouterWithCache creates a LeastRequestTopKRouter that reads load from the given cache.
func (*LeastRequestTopKRouter) Polarity ¶ added in v0.8.0
func (r *LeastRequestTopKRouter) Polarity() types.Polarity
Polarity implements types.PodScorer: fewer requests is better, as for least-request.
func (*LeastRequestTopKRouter) Route ¶ added in v0.8.0
func (r *LeastRequestTopKRouter) Route(ctx *types.RoutingContext, readyPodList types.PodList) (string, error)
Route implements types.Router: a uniform random pick among the eligible pods.
func (*LeastRequestTopKRouter) ScoreAll ¶ added in v0.8.0
func (r *LeastRequestTopKRouter) ScoreAll(ctx *types.RoutingContext, readyPodList types.PodList) ([]float64, []bool, error)
ScoreAll implements types.PodScorer so the strategy can be blended with others. The blend sums normalized scores deterministically and takes the argmax, so Route's random pick has no equivalent there: identical scores would let the other strategy's tie-break favor the same pod every time. Instead each eligible pod scores its count minus fresh random jitter in [0, epsilon), which can reorder the eligible cluster but never lift an ineligible pod above it. Ineligible pods keep their plain count.
func (*LeastRequestTopKRouter) SubscribedMetrics ¶ added in v0.8.0
func (r *LeastRequestTopKRouter) SubscribedMetrics() []string
SubscribedMetrics implements types.Router. It reads the live cross-gateway running-request count, not a scraped metric, so there is nothing to subscribe to.
type MultiRouterConfig ¶ added in v0.7.0
type MultiRouterConfig struct {
Items []RouterItem
}
MultiRouterConfig holds the parsed routing algorithms and their weight coefficients.
func ParseMultiRouterConfig ¶ added in v0.7.0
func ParseMultiRouterConfig(routerStr string) (*MultiRouterConfig, error)
ParseMultiRouterConfig parses a multi-router string into a MultiRouterConfig. Format example: "prefix-cache:2,least-latency:1,least-request" - Weight coefficients must be integers in range [0, 1000000]. - Default weight coefficient is 1 if omitted. - Weight coefficient 0 means the routing algorithm should be skipped.
type PDRolesetEligibility ¶ added in v0.8.0
type PDRolesetEligibility struct {
Roleset string
PrefillReplicas int
DecodeReplicas int
PrefillPods string
DecodePods string
Eligible bool
}
PDRolesetEligibility describes one roleset's readiness for PD routing.
func DescribePDRolesetEligibility ¶ added in v0.8.0
func DescribePDRolesetEligibility(readyPods []*v1.Pod) (fleetMaxPrefill, fleetMaxDecode int, statuses []PDRolesetEligibility, eligibleCount int)
DescribePDRolesetEligibility returns fleet-wide max replica counts (for diagnostics) and per-roleset eligibility (≥1 prefill and ≥1 decode).
type PowerOfTwoRouter ¶ added in v0.7.0
type PowerOfTwoRouter struct {
// contains filtered or unexported fields
}
PowerOfTwoRouter implements the power of two choices algorithm: it samples two distinct ready pods at random and routes to the one with fewer running requests.
The router keeps no counters of its own. The running-request count of a pod is the one the cache maintains for every routed request (see Cache.GetPodsRunningRequests): the gateway increments it when a request is dispatched and decrements it when the request completes, whichever router chose the pod. When Redis is configured the count is aggregated across gateway replicas; otherwise it is this gateway's own count.
func NewPowerOfTwoRouterWithCache ¶ added in v0.8.0
func NewPowerOfTwoRouterWithCache(c cache.Cache) *PowerOfTwoRouter
NewPowerOfTwoRouterWithCache creates a Power of Two router that reads load from the given cache.
func (*PowerOfTwoRouter) Route ¶ added in v0.7.0
func (p *PowerOfTwoRouter) Route(ctx *types.RoutingContext, readyPodList types.PodList) (string, error)
Route implements types.Router using power of two choices algorithm. It randomly selects two pods and routes to the one with fewer running requests.
A data-parallel pod serves several ports, and the port is then chosen the way least-request chooses it: the one with the lowest per-port realtime running-requests metric. The cache keeps no true per-port count -- that metric slot holds the pod's total running requests as of the last request that started or finished on the port -- so this is only approximately load-aware. The choice of pod above does not depend on it.
func (*PowerOfTwoRouter) SubscribedMetrics ¶ added in v0.7.0
func (p *PowerOfTwoRouter) SubscribedMetrics() []string
SubscribedMetrics implements types.Router.
type PrefillTimeParams ¶
type PrefixCacheMetrics ¶ added in v0.4.0
type PrefixCacheMetrics struct {
// contains filtered or unexported fields
}
PrefixCacheMetrics holds all prefix cache metrics
type RedisBackedRouter ¶ added in v0.8.0
RedisBackedRouter is implemented by routers that persist routing state to Redis and need a background sync loop started once both Redis and a process shutdown signal are available -- typically later than the router itself is constructed (see RouterManager.Init). The gateway server type- asserts to this interface after building its own shutdown channel.
type RouterItem ¶ added in v0.7.0
RouterItem represents a single routing algorithm and its weight coefficient for multi-router config.
type RouterManager ¶ added in v0.4.0
type RouterManager struct {
// contains filtered or unexported fields
}
func DefaultRouterManager ¶ added in v0.8.0
func DefaultRouterManager() *RouterManager
DefaultRouterManager returns the production process-wide router manager.
func NewRouterManager ¶ added in v0.4.0
func NewRouterManager() *RouterManager
func NewRouterManagerWithCache ¶ added in v0.8.0
func NewRouterManagerWithCache(c cache.Cache) *RouterManager
NewRouterManagerWithCache creates an isolated manager whose cache-backed constructors capture c instead of consulting the process-global cache.
func NewRouterManagerWithCacheAndPrefixIndexer ¶ added in v0.8.0
func NewRouterManagerWithCacheAndPrefixIndexer(c cache.Cache, indexer *prefixcacheindexer.PrefixHashTable) *RouterManager
NewRouterManagerWithCacheAndPrefixIndexer creates an isolated manager whose cache-backed constructors capture c and whose prefix-cache constructor uses indexer when it is non-nil. A nil indexer preserves the default per-manager prefix table behavior.
func NewRouterManagerWithDefaults ¶ added in v0.8.0
func NewRouterManagerWithDefaults() *RouterManager
NewRouterManagerWithDefaults creates an isolated manager with the standard Gateway routing constructors. Unlike Init, it does not mutate the process global manager.
func (*RouterManager) Init ¶ added in v0.4.0
func (rm *RouterManager) Init()
func (*RouterManager) InitializationError ¶ added in v0.8.0
func (rm *RouterManager) InitializationError(algorithm types.RoutingAlgorithm) error
InitializationError reports the most recent constructor failure for a strategy. Disabled optional routers may use a sentinel error that callers explicitly ignore; invalid enabled configuration remains fail-fast.
func (*RouterManager) Lookup ¶ added in v0.8.0
func (rm *RouterManager) Lookup(algorithm types.RoutingAlgorithm) (types.Router, error)
Lookup returns algorithm's constructed singleton router, as registered via Register/RegisterProvider and built by Init. It exists for callers (like the gateway server) that need the concrete instance directly -- for example to start a router's own background maintenance loop -- rather than going through Select's per-request algorithm resolution and blending. The probe context mirrors Validate's: providers built via Register ignore it entirely, since they already constructed their singleton at Init time, but it's supplied anyway so a ctx-dependent provider (e.g. SLO's) never sees a nil pointer.
func (*RouterManager) Register ¶ added in v0.4.0
func (rm *RouterManager) Register(algorithm types.RoutingAlgorithm, constructor types.RouterConstructor)
func (*RouterManager) RegisterProvider ¶ added in v0.4.0
func (rm *RouterManager) RegisterProvider(algorithm types.RoutingAlgorithm, provider types.RouterProviderFunc)
func (*RouterManager) Select ¶ added in v0.4.0
func (rm *RouterManager) Select(ctx *types.RoutingContext) (types.Router, error)
Select the user provided router provider supported by gateway, no error reported and fallback to random router Call Validate before this function to ensure expected behavior.
func (*RouterManager) SetFallback ¶ added in v0.4.0
func (rm *RouterManager) SetFallback(router types.Router, fallback types.RoutingAlgorithm) error
func (*RouterManager) Validate ¶ added in v0.4.0
func (rm *RouterManager) Validate(algorithms string) (types.RoutingAlgorithm, bool)
Validate validates if user provided routing routers is supported by gateway
type SLORouter ¶ added in v0.4.0
type SLORouter struct {
FallbackRouter
*queue.SLOQueue
}
SLORouter is a router that add FallbackRouter mechanism to the queue.
type SlidingWindowHistogram ¶
type SlidingWindowHistogram struct {
// contains filtered or unexported fields
}
type TokenizerPool ¶ added in v0.4.0
type TokenizerPool struct {
// contains filtered or unexported fields
}
TokenizerPool manages model-specific tokenizers with caching and health checking
func NewTokenizerPool ¶ added in v0.4.0
func NewTokenizerPool(config TokenizerPoolConfig, cache cache.Cache) *TokenizerPool
NewTokenizerPool creates a new TokenizerPool instance
func (*TokenizerPool) Close ¶ added in v0.4.0
func (p *TokenizerPool) Close() error
Close gracefully shuts down the TokenizerPool
func (*TokenizerPool) GetTokenizer ¶ added in v0.4.0
GetTokenizer returns a tokenizer for the specified model
type TokenizerPoolConfig ¶ added in v0.4.0
type TokenizerPoolConfig struct {
EnableVLLMRemote bool // Feature flag
EndpointTemplate string // "http://%s:8000"
HealthCheckPeriod time.Duration // Default: 30s
TokenizerTTL time.Duration // Default: 5m
MaxTokenizersPerPool int // Default: 100
DefaultTokenizer tokenizer.Tokenizer // Default when remote fails
ModelServiceMap map[string]string // Model -> Service endpoint mapping
Timeout time.Duration // Request timeout
}
TokenizerPoolConfig represents configuration for the TokenizerPool
type TokenizerPoolInterface ¶ added in v0.4.0
type TokenizerPoolInterface interface {
GetTokenizer(model string, pods []*v1.Pod) tokenizer.Tokenizer
Close() error
}
TokenizerPoolInterface defines the interface for tokenizer pools
type TokenizerPoolMetrics ¶ added in v0.4.0
type TokenizerPoolMetrics struct {
// contains filtered or unexported fields
}
TokenizerPoolMetrics contains Prometheus metrics for the pool
Source Files
¶
- external_adapter.go
- fallback.go
- least_busy_time.go
- least_gpu_cache.go
- least_kv_cache.go
- least_latency.go
- least_load.go
- least_request.go
- least_request_top_k.go
- least_util.go
- load_balance.go
- model_router_factory.go
- pack_load.go
- pd_disaggregation.go
- pd_prefill_request.go
- pd_roleset.go
- power_of_two.go
- prefix_cache.go
- prefix_cache_preble.go
- profile_knobs.go
- queue_router.go
- random.go
- router.go
- scorer.go
- simple_session_affinity.go
- slo.go
- throughput.go
- tokenizer_pool.go
- util.go
- vtc.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package external implements the optional HTTP-based replica-selection strategy.
|
Package external implements the optional HTTP-based replica-selection strategy. |
|
Package pd contains the scoring types used by the PD (prefill-decode) disaggregated-inference router.
|
Package pd contains the scoring types used by the PD (prefill-decode) disaggregated-inference router. |
|
selector
Package selector defines the PodSelector contract for PD-disaggregated routing.
|
Package selector defines the PodSelector contract for PD-disaggregated routing. |
|
Package vtc implements the Virtual Token Counter routing algorithms focused on fairness and utilization
|
Package vtc implements the Virtual Token Counter routing algorithms focused on fairness and utilization |