routingalgorithms

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 18, 2026 License: Apache-2.0 Imports: 35 Imported by: 0

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

View Source
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"
	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"
)
View Source
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"
)
View Source
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"
)
View Source
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"
)
View Source
const DefaultFallbackAlgorithm types.RoutingAlgorithm = RouterRandom
View Source
const RouterLeastBusyTime types.RoutingAlgorithm = "least-busy-time"
View Source
const RouterLeastGpuCache types.RoutingAlgorithm = "least-gpu-cache"
View Source
const RouterLeastKvCache types.RoutingAlgorithm = "least-kv-cache"
View Source
const RouterLeastLatency types.RoutingAlgorithm = "least-latency"
View Source
const RouterLeastRequest types.RoutingAlgorithm = "least-request"
View Source
const (
	RouterNotSet = ""
)
View Source
const (
	RouterPowerOfTwo types.RoutingAlgorithm = "power-of-two"
)
View Source
const RouterPrefixCachePreble types.RoutingAlgorithm = "prefix-cache-preble"
View Source
const RouterRandom types.RoutingAlgorithm = "random"
View Source
const (
	RouterSessionAffinity types.RoutingAlgorithm = "session-affinity"
)
View Source
const RouterThroughput types.RoutingAlgorithm = "throughput"
View Source
const RouterUtil types.RoutingAlgorithm = "least-utilization"

Variables

View Source
var (
	RandomRouter             = &randomRouter{}
	RandomRouterProviderFunc = func(_ *types.RoutingContext) (types.Router, error) { return RandomRouter, nil }
)
View Source
var (
	ErrInitTimeout           = errors.New("router initialization timeout")
	ErrFallbackNotSupported  = errors.New("router not support fallback")
	ErrFallbackNotRegistered = errors.New("fallback router not registered")
)
View Source
var (
	ErrorNoAvailablePod = fmt.Errorf("no pod available")
)
View Source
var ModelRouterFactory = NewSLORouter
View Source
var (
	RouterPrefixCache types.RoutingAlgorithm = "prefix-cache"
)

Functions

func GetPodModelMetricsSimplePrometheusValue added in v0.6.0

func GetPodModelMetricsSimplePrometheusValue(cache cache.Cache, podname, namespace, modelname, metricname string) float64

func GetPodModelMetricsSimpleValue added in v0.6.0

func GetPodModelMetricsSimpleValue(cache cache.Cache, podname, namespace, modelname, metricname string) float64

func Init

func Init()

func NewLeastBusyTimeRouter

func NewLeastBusyTimeRouter() (types.Router, error)

func NewLeastExpectedLatencyRouter

func NewLeastExpectedLatencyRouter() (types.Router, error)

func NewLeastGpuCacheRouter added in v0.4.0

func NewLeastGpuCacheRouter() (types.Router, error)

func NewLeastKvCacheRouter

func NewLeastKvCacheRouter() (types.Router, error)

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 NewLeastRequestRouter() (types.Router, error)

func NewLeastUtilRouter added in v0.4.0

func NewLeastUtilRouter() (types.Router, error)

func NewPDRouter added in v0.4.0

func NewPDRouter() (types.Router, error)

func NewPackLoadRouter added in v0.4.0

func NewPackLoadRouter(provider cache.CappedLoadProvider) (types.Router, error)

NewPackLoadRouter creates packLoadRouter instance.

func NewPrefixCacheAndLoadRouter

func NewPrefixCacheAndLoadRouter() (types.Router, error)

func NewPrefixCacheRouter

func NewPrefixCacheRouter() (types.Router, error)

func NewQueueRouter added in v0.4.0

func NewQueueRouter(backend types.Router, queue types.RouterQueue[*types.RoutingContext]) (types.QueueRouter, error)

func NewRandomRouter

func NewRandomRouter() (types.Router, error)

func NewSLORouter added in v0.4.0

func NewSLORouter(modelName string) (types.QueueRouter, error)

func NewSessionAffinityRouter added in v0.6.0

func NewSessionAffinityRouter() (types.Router, error)

func NewThroughputRouter

func NewThroughputRouter() (types.Router, error)

func Register

func Register(algorithm types.RoutingAlgorithm, constructor types.RouterConstructor)

func RegisterPowerOfTwoRouter added in v0.7.0

func RegisterPowerOfTwoRouter(redisClient *redis.Client)

func RegisterProvider added in v0.4.0

func RegisterProvider(algorithm types.RoutingAlgorithm, provider types.RouterProviderFunc)

func Select

func Select(ctx *types.RoutingContext) (types.Router, error)

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

func Validate

func Validate(algorithms string) (types.RoutingAlgorithm, bool)

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 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 PowerOfTwoRouter added in v0.7.0

type PowerOfTwoRouter struct {
	// contains filtered or unexported fields
}

func NewPowerOfTwoRouterWithRedis added in v0.7.0

func NewPowerOfTwoRouterWithRedis(redisClient *redis.Client, keyRotationSec ...int64) (*PowerOfTwoRouter, error)

NewPowerOfTwoRouterWithRedis creates a new Power of Two router with the given Redis client. This is useful for testing or when you want to provide a custom Redis configuration. Returns error if cache registration fails, as the router cannot function correctly without it.

func (*PowerOfTwoRouter) AddRequestCount added in v0.7.0

func (p *PowerOfTwoRouter) AddRequestCount(ctx *types.RoutingContext, requestID string, modelName string) (traceTerm int64)

AddRequestCount implements cache.RequestTracker.

func (*PowerOfTwoRouter) DoneRequestCount added in v0.7.0

func (p *PowerOfTwoRouter) DoneRequestCount(ctx *types.RoutingContext, requestID string, modelName string, traceTerm int64)

DoneRequestCount implements cache.RequestTracker.

func (*PowerOfTwoRouter) DoneRequestTrace added in v0.7.0

func (p *PowerOfTwoRouter) DoneRequestTrace(ctx *types.RoutingContext, requestID string, modelName string, inputTokens int64, outputTokens int64, traceTerm int64)

DoneRequestTrace implements cache.RequestTracker.

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 candidates and routes to the one with fewer running requests.

func (*PowerOfTwoRouter) SubscribedMetrics added in v0.7.0

func (p *PowerOfTwoRouter) SubscribedMetrics() []string

SubscribedMetrics implements types.Router.

type PrefillTimeParams

type PrefillTimeParams struct {
	NumRequests      int
	NumBatchedTokens int
	TotalContext     int
	InputIDLens      []int
	NumUniqueKV      int
	SeqLens          []int
}

type PrefixCacheMetrics added in v0.4.0

type PrefixCacheMetrics struct {
	// contains filtered or unexported fields
}

PrefixCacheMetrics holds all prefix cache metrics

type RouterItem added in v0.7.0

type RouterItem struct {
	Name        string
	Coefficient int // Integer weight coefficient (0 to 1000000)
}

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 NewRouterManager added in v0.4.0

func NewRouterManager() *RouterManager

func (*RouterManager) Init added in v0.4.0

func (rm *RouterManager) Init()

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.

func (*SLORouter) Route added in v0.4.0

func (r *SLORouter) Route(ctx *types.RoutingContext, pods types.PodList) (string, error)

type Scores added in v0.5.0

type Scores struct {
	Pod   *v1.Pod
	Score float64
}

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

func (p *TokenizerPool) GetTokenizer(model string, pods []*v1.Pod) tokenizer.Tokenizer

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

Directories

Path Synopsis
pd
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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL