before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
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 ...
No issues found.
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 ...
@@ -44,6 +44,9 @@ func IsRayClusterAvailable(cluster *rayclusterv1.RayCluster, minReadySeconds int headPodReadyCond := meta.FindStatusCondition(cluster.Status.Conditions, string(rayclusterv1.HeadPodReady)) provisionedCond := meta.FindStatusCondition(cluster.Status.Conditions, string(rayclusterv1.RayClusterProvisi...
pkg/utils/raycluster.go
0
Go
1
none
16
51
51
true
[Bug] fix: condition nil panic in FindStatusCondition func
1,078
vllm-project/aibrix
2,572
Go
googs1025
// and requeue the Deployment. if d.Status.CollisionCount == nil { d.Status.CollisionCount = new(int32) } preCollisionCount := *d.Status.CollisionCount *d.Status.CollisionCount++ // Update the collisionCount for the Deployment and let it requeue by returning the original // error. dErr := r.Status()....
No issues found.
// and requeue the Deployment. if d.Status.CollisionCount == nil { d.Status.CollisionCount = new(int32) } preCollisionCount := *d.Status.CollisionCount *d.Status.CollisionCount++ // Update the collisionCount for the Deployment and let it requeue by returning the original // error. dErr := r.Status()....
@@ -192,6 +192,13 @@ func (r *RayClusterFleetReconciler) getNewReplicaSet(ctx context.Context, d *orc // new ReplicaSet does not exist, create one. newRSTemplate := *d.Spec.Template.DeepCopy() + + // Add rayclusterfleet name to all pod label + newRSTemplate.Spec.HeadGroupSpec.Template.Labels = labelsutil.CloneAnd...
pkg/controller/rayclusterfleet/sync.go
0
Go
1
none
16
51
51
true
[Bug]fix: add scale subresource to rayclusterfleet
1,082
vllm-project/aibrix
2,572
Go
zhixian82
`) t.Run("Parse simple metric with model labels", func(t *testing.T) { value, err := ParseMetricFromBody(body, "vllm:num_requests_waiting") assert.NoError(t, err) assert.Equal(t, 2.0, value) }) } func TestExtractBucketBoundary(t *testing.T) { line := `vllm:time_per_output_token_seconds_bucket{le="0.1",model_...
No issues found.
`) t.Run("Parse simple metric with model labels", func(t *testing.T) { value, err := ParseMetricFromBody(body, "vllm:num_requests_waiting") assert.NoError(t, err) assert.Equal(t, 2.0, value) }) } func TestExtractBucketBoundary(t *testing.T) { line := `vllm:time_per_output_token_seconds_bucket{le="0.1",model_...
@@ -17,7 +17,13 @@ limitations under the License. package metrics import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" "testing" + "time" "github.com/stretchr/testify/assert" ) @@ -89,3 +95,88 @@ func TestBuildQueryWithModelLabel(t *testing.T) { assert.Contains(t, query, `model_name=...
pkg/metrics/utils_test.go
0
Go
1
none
16
51
51
true
feature: use worker pool management for periodic metrics update
1,096
vllm-project/aibrix
2,572
Go
googs1025
} ... ] } """ try: data = json.loads(json_str) temp_members: List[Member] = [] temp_slots = SortedList(key=lambda x: x[0]) for node in data["nodes"]: slots = node.pop("slots") ...
No issues found.
} ... ] } """ try: data = json.loads(json_str) temp_members: List[Member] = [] temp_slots = SortedList(key=lambda x: x[0]) for node in data["nodes"]: slots = node.pop("slots") ...
@@ -17,6 +17,7 @@ from dataclasses import dataclass from typing import Any, Dict, List, Sequence, Tuple, TypeVar +import torch from sortedcontainers import SortedList from ...common.absl_logging import getLogger @@ -27,7 +28,6 @@ Connector, ConnectorConfig, ConnectorFeature, - ConnectorRegiste...
python/aibrix_kvcache/aibrix_kvcache/l2/placement/placement.py
0
Python
1
none
16
51
51
true
[Feature] KVCache: Suppport InfiniStore GID and enhance cluster mode
1,106
vllm-project/aibrix
2,572
Go
DwyaneShi
}, Status: v1.PodStatus{ PodIP: fmt.Sprintf("10.0.0.%d", i+1), Conditions: []v1.PodCondition{ { Type: v1.PodReady, Status: v1.ConditionTrue, }, }, }, } switch readyMap[i] { case 1: pod.Status.PodIP = "" case 2: pod.Status.Conditions[0].Status = v1.ConditionFals...
No issues found.
}, Status: v1.PodStatus{ PodIP: fmt.Sprintf("10.0.0.%d", i+1), Conditions: []v1.PodCondition{ { Type: v1.PodReady, Status: v1.ConditionTrue, }, }, }, } switch readyMap[i] { case 1: pod.Status.PodIP = "" case 2: pod.Status.Conditions[0].Status = v1.ConditionFals...
@@ -18,10 +18,12 @@ package utils import ( "fmt" "math/rand" + "testing" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/stretchr/testify/assert" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -81,3 +83,59 @@ var _ = Describe("Pod", func() { Ex...
pkg/utils/pod_test.go
0
Go
1
none
16
51
51
true
Add support for custom inference engine port
1,140
vllm-project/aibrix
2,572
Go
varungup90
else: return JSONResponse({"message": "Deployment optimization already started"}) except Exception as e: return JSONResponse( {"error": f"Error starting deployment optimization: {e}"}, status_code=500 ) @app.route("/monitor/{namespace}/{deployment_name}", methods=["...
No issues found.
else: return JSONResponse({"message": "Deployment optimization already started"}) except Exception as e: return JSONResponse( {"error": f"Error starting deployment optimization: {e}"}, status_code=500 ) @app.route("/monitor/{namespace}/{deployment_name}", methods=["...
@@ -81,9 +81,12 @@ def new_deployment(deployment): min_replicas = int(label) return DeploymentStates( - deployment.metadata.name, - deployment.spec.replicas if deployment.spec.replicas is not None else 0, - min_replicas, + name=deployment.metadata.name, + namespace...
python/aibrix/aibrix/gpu_optimizer/app.py
0
Python
1
none
16
51
51
true
[Misc] [gpu_optimizer] add namespace info for log
1,149
vllm-project/aibrix
2,572
Go
googs1025
}, { message: "/v1/chat/completions json unmarhsal no messages", requestPath: "/v1/chat/completions", requestBody: []byte(`{"model": "llama2-7b"}`), statusCode: envoyTypePb.StatusCode_BadRequest, }, { message: "/v1/chat/completions json unmarhsal valid messages", requestPath: "/v1/cha...
No issues found.
}, { message: "/v1/chat/completions json unmarhsal no messages", requestPath: "/v1/chat/completions", requestBody: []byte(`{"model": "llama2-7b"}`), statusCode: envoyTypePb.StatusCode_BadRequest, }, { message: "/v1/chat/completions json unmarhsal valid messages", requestPath: "/v1/cha...
@@ -67,6 +67,20 @@ func Test_ValidateRequestBody(t *testing.T) { messages: "this is system say this is test", statusCode: envoyTypePb.StatusCode_OK, }, + { + message: "/v1/chat/completions json unmarhsal invalid messages with complex content", + requestPath: "/v1/chat/completions", + requestBo...
pkg/plugins/gateway/util_test.go
0
Go
1
none
16
51
51
true
[Bug] fix: error when parse complex content in completion body
1,160
vllm-project/aibrix
2,572
Go
firebook
//go:build !race /* 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 w...
No issues found.
//go:build !race /* 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 w...
@@ -1,3 +1,5 @@ +//go:build !race + /* Copyright 2024 The Aibrix Team.
pkg/types/types_test.go
0
Go
1
none
16
31
31
true
Add race condition check in unit-test CI and add test-coverage cmd in Makefile
1,169
vllm-project/aibrix
2,572
Go
varungup90
func (m *ModelRouter) addRouteFromRayClusterFleet(obj interface{}) { fleet := obj.(*orchestrationv1alpha1.RayClusterFleet) m.createHTTPRoute(fleet.Namespace, fleet.Labels) } func (m *ModelRouter) deleteRouteFromRayClusterFleet(obj interface{}) { fleet, ok := obj.(*orchestrationv1alpha1.RayClusterFleet) if !ok { ...
No issues found.
func (m *ModelRouter) addRouteFromRayClusterFleet(obj interface{}) { fleet := obj.(*orchestrationv1alpha1.RayClusterFleet) m.createHTTPRoute(fleet.Namespace, fleet.Labels) } func (m *ModelRouter) deleteRouteFromRayClusterFleet(obj interface{}) { fleet, ok := obj.(*orchestrationv1alpha1.RayClusterFleet) if !ok { ...
@@ -18,6 +18,7 @@ package modelrouter import ( "context" + "errors" "fmt" "strconv" @@ -105,6 +106,12 @@ func Add(mgr manager.Manager, runtimeConfig config.RuntimeConfig) error { DeleteFunc: modelRouter.deleteRouteFromRayClusterFleet, }) + klog.Info("Waiting for caches to sync") + if ok := cacher.Wait...
pkg/controller/modelrouter/modelrouter_controller.go
0
Go
1
none
16
51
51
true
[Misc]: ensure cache sync before starting controller reconcile
1,219
vllm-project/aibrix
2,572
Go
googs1025
# 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...
No issues found.
# 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...
@@ -12,6 +12,20 @@ # See the License for the specific language governing permissions and # limitations under the License. -from .rdma import AddrFamily, DeviceRequest, GIDType, RDMATransport -__all__ = ["AddrFamily", "DeviceRequest", "GIDType", "RDMATransport"] +# A global flag to indicate whether current platfor...
python/aibrix_kvcache/aibrix_kvcache/transport/__init__.py
0
Python
1
none
16
32
32
true
[Fix] KVCache: enhance rdma auto-detection
1,276
vllm-project/aibrix
2,572
Go
DwyaneShi
# 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...
No issues found.
# 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...
@@ -14,7 +14,6 @@ from .async_base import AsyncBase from .cached_pyobject import CachedPyObjectBase -from .nvtx import nvtx_range from .object_pool import ObjectPool -__all__ = ["AsyncBase", "nvtx_range", "ObjectPool", "CachedPyObjectBase"] +__all__ = ["AsyncBase", "ObjectPool", "CachedPyObjectBase"]
python/aibrix_kvcache/aibrix_kvcache/common/__init__.py
0
Python
1
none
16
20
20
true
[Feature] KVCache: enhance profiling
1,278
vllm-project/aibrix
2,572
Go
DwyaneShi
def test_allocating_heterogeneous(allocator): """Test allocating with heterogeneous sizes.""" if hasattr(allocator, "num_memory_regions"): assert allocator.num_memory_regions == 1024 sizes = [random.randint(8, 1024) for _ in range(31)] status = allocator.alloc(sizes) allocator.assert_consi...
No issues found.
def test_allocating_heterogeneous(allocator): """Test allocating with heterogeneous sizes.""" if hasattr(allocator, "num_memory_regions"): assert allocator.num_memory_regions == 1024 sizes = [random.randint(8, 1024) for _ in range(31)] status = allocator.alloc(sizes) allocator.assert_consi...
@@ -17,19 +17,21 @@ import pytest from aibrix_kvcache.memory import TensorPoolAllocator +from aibrix_kvcache.memory.allocator import CoalescingPoolAllocator @pytest.fixture def allocator(compact_layout_enabled): # use a small slab size for testing TensorPoolAllocator.SLAB_MAX_NBYTES = 1024 Tens...
python/aibrix_kvcache/tests/test_tensor_pool_allocator.py
0
Python
1
none
16
51
51
true
[Feature] KVCache: optimize allocator for compact layout
1,288
vllm-project/aibrix
2,572
Go
DwyaneShi
/* Copyright 2025 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, softwar...
No issues found.
/* Copyright 2025 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, softwar...
@@ -0,0 +1,48 @@ +/* +Copyright 2025 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 ag...
pkg/cache/utils.go
0
Go
1
none
16
49
49
true
[Feature] Adding raw metrics name conversion in metrics
1,293
vllm-project/aibrix
2,572
Go
happyandslow
require.NoError(t, orchestrationv1alpha1.AddToScheme(scheme)) tests := []struct { name string description string roleSet *orchestrationv1alpha1.RoleSet role *orchestrationv1alpha1.RoleSpec existingPods []*v1.Pod expectedError bool expectedCreate int expectedDelete int...
No issues found.
require.NoError(t, orchestrationv1alpha1.AddToScheme(scheme)) tests := []struct { name string description string roleSet *orchestrationv1alpha1.RoleSet role *orchestrationv1alpha1.RoleSpec existingPods []*v1.Pod expectedError bool expectedCreate int expectedDelete int...
@@ -0,0 +1,445 @@ +/* +Copyright 2025 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 a...
pkg/controller/roleset/rolesyncer_test.go
0
Go
1
none
16
51
51
true
[Misc] Add unit test code coverage of rolesyncer
1,296
vllm-project/aibrix
2,572
Go
vie-serendipity
from .hpkv import HPKVConnector return HPKVConnector.from_envs(conn_id, executor, **kwargs) elif backend_name == "PRIS": from .pris import PrisConnector return PrisConnector.from_envs(conn_id, executor, **kwargs) elif backend_name == "MOCK": ...
No issues found.
from .hpkv import HPKVConnector return HPKVConnector.from_envs(conn_id, executor, **kwargs) elif backend_name == "PRIS": from .pris import PrisConnector return PrisConnector.from_envs(conn_id, executor, **kwargs) elif backend_name == "MOCK": ...
@@ -92,6 +92,10 @@ def create( from .hpkv import HPKVConnector return HPKVConnector.from_envs(conn_id, executor, **kwargs) + elif backend_name == "PRIS": + from .pris import PrisConnector + + return PrisConnector.from_envs(conn_id, executor, **kwargs) el...
python/aibrix_kvcache/aibrix_kvcache/l2/connectors/connector.py
0
Python
1
none
16
51
51
true
[Feature] KVCache: add Pris connector
1,303
vllm-project/aibrix
2,572
Go
DwyaneShi
statusCode: envoyTypePb.StatusCode_OK, headers: []*configPb.HeaderValueOption{ { Header: &configPb.HeaderValue{ Key: HeaderRoutingStrategy, RawValue: []byte("invalid-router"), }, }, { Header: &configPb.HeaderValue{ Key: HeaderTargetPod, RawV...
No issues found.
statusCode: envoyTypePb.StatusCode_OK, headers: []*configPb.HeaderValueOption{ { Header: &configPb.HeaderValue{ Key: HeaderRoutingStrategy, RawValue: []byte("invalid-router"), }, }, { Header: &configPb.HeaderValue{ Key: HeaderTargetPod, RawV...
@@ -19,12 +19,11 @@ package gateway import ( "context" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" - "time" - configPb "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" extProcPb "github.com/envoyproxy/go-control-plane/envoy/service/ext_proc/v3...
pkg/plugins/gateway/gateway_req_body_test.go
0
Go
1
none
16
51
51
true
[feat] Add prefill-decode disaggregation support in aibrix router
1,309
vllm-project/aibrix
2,572
Go
varungup90
desiredUpdated: 1, }, { currentReplicas: 2, updatedReplicas: 2, desiredReplicas: 5, desiredCurrent: 3, desiredUpdated: 2, }, { currentReplicas: 5, updatedReplicas: 5, desiredReplicas: 3, desiredCurrent: 2, desiredUpdated: 1, }, { currentReplicas: 0, updatedReplica...
No issues found.
desiredUpdated: 1, }, { currentReplicas: 2, updatedReplicas: 2, desiredReplicas: 5, desiredCurrent: 3, desiredUpdated: 2, }, { currentReplicas: 5, updatedReplicas: 5, desiredReplicas: 3, desiredCurrent: 2, desiredUpdated: 1, }, { currentReplicas: 0, updatedReplica...
@@ -16,7 +16,21 @@ limitations under the License. package stormservice -import "testing" +import ( + "context" + "reflect" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runt...
pkg/controller/stormservice/sync_test.go
0
Go
1
none
16
51
51
true
[Misc] enhance headless service sync with update logic
1,311
vllm-project/aibrix
2,572
Go
omerap12
roleSet: &orchestrationv1alpha1.RoleSet{ Spec: orchestrationv1alpha1.RoleSetSpec{ Roles: []orchestrationv1alpha1.RoleSpec{ {Name: "role1", Replicas: int32Ptr(3)}, {Name: "role2", Replicas: int32Ptr(2)}, }, }, Status: orchestrationv1alpha1.RoleSetStatus{ Roles: []orchestrationv1...
No issues found.
roleSet: &orchestrationv1alpha1.RoleSet{ Spec: orchestrationv1alpha1.RoleSetSpec{ Roles: []orchestrationv1alpha1.RoleSpec{ {Name: "role1", Replicas: int32Ptr(3)}, {Name: "role2", Replicas: int32Ptr(2)}, }, }, Status: orchestrationv1alpha1.RoleSetStatus{ Roles: []orchestrationv1...
@@ -22,6 +22,7 @@ import ( "github.com/stretchr/testify/assert" orchestrationv1alpha1 "github.com/vllm-project/aibrix/api/orchestration/v1alpha1" "github.com/vllm-project/aibrix/pkg/controller/constants" + utils "github.com/vllm-project/aibrix/pkg/controller/util/orchestration" corev1 "k8s.io/api/core/v1" met...
pkg/controller/stormservice/utils_test.go
0
Go
1
none
16
51
51
true
Fix nil slice issue and add UT coverage for stormservice utils
1,314
vllm-project/aibrix
2,572
Go
Jeffwan
func (m *MockCache) GetMetricValueByPod(namespace string, podName string, metricName string) (metrics.MetricValue, error) { args := m.Called(namespace, podName, metricName) return args.Get(0).(metrics.MetricValue), args.Error(1) } func (m *MockCache) GetMetricValueByPodModel(namespace string, podName string, model ...
No issues found.
func (m *MockCache) GetMetricValueByPod(namespace string, podName string, metricName string) (metrics.MetricValue, error) { args := m.Called(namespace, podName, metricName) return args.Get(0).(metrics.MetricValue), args.Error(1) } func (m *MockCache) GetMetricValueByPodModel(namespace string, podName string, model ...
@@ -17,11 +17,22 @@ limitations under the License. package gateway import ( + "context" + "github.com/stretchr/testify/mock" "github.com/vllm-project/aibrix/pkg/cache" "github.com/vllm-project/aibrix/pkg/metrics" "github.com/vllm-project/aibrix/pkg/types" v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachin...
pkg/plugins/gateway/gateway_test_helpers.go
0
Go
1
none
16
51
51
true
Add check for missing httproute before request start
1,344
vllm-project/aibrix
2,572
Go
varungup90
"github.com/vllm-project/aibrix/pkg/types" "github.com/vllm-project/aibrix/pkg/utils" ) func (s *Server) HandleRequestBody(ctx context.Context, requestID string, req *extProcPb.ProcessingRequest, user utils.User) (*extProcPb.ProcessingResponse, string, *types.RoutingContext, bool, int64) { var term int64 // Identif...
No issues found.
"github.com/vllm-project/aibrix/pkg/types" "github.com/vllm-project/aibrix/pkg/utils" ) func (s *Server) HandleRequestBody(ctx context.Context, requestID string, req *extProcPb.ProcessingRequest, user utils.User) (*extProcPb.ProcessingResponse, string, *types.RoutingContext, bool, int64) { var term int64 // Identif...
@@ -19,6 +19,7 @@ package gateway import ( "context" "fmt" + "strconv" "k8s.io/klog/v2" @@ -81,7 +82,8 @@ func (s *Server) HandleRequestBody(ctx context.Context, requestID string, req *e } headers = buildEnvoyProxyHeaders(headers, HeaderRoutingStrategy, string(routingAlgorithm), - HeaderTargetPod...
pkg/plugins/gateway/gateway_req_body.go
0
Go
1
none
16
51
51
true
Bug fixes for PD disaggregation routing
1,354
vllm-project/aibrix
2,572
Go
varungup90
{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"role-name": "other"}}}, {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"role-name": "prefill", PodGroupIndex: "1"}}}, }, expectPrefill: 1, expectDecode: 1, }, } r := pdRouter{} for _, tt := range tests { t.Run(tt.name, func(t ...
No issues found.
{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"role-name": "other"}}}, {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"role-name": "prefill", PodGroupIndex: "1"}}}, }, expectPrefill: 1, expectDecode: 1, }, } r := pdRouter{} for _, tt := range tests { t.Run(tt.name, func(t ...
@@ -49,9 +49,9 @@ func TestPDRouter_Route(t *testing.T) { { name: "successful routing with both prefill and decode pods", readyPods: []*v1.Pod{ - {ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"role-name": "prefill"}, Name: "prefill-1"}, Status: v1.PodStatus{PodIP: "127.0.0.1", + {ObjectMeta:...
pkg/plugins/gateway/algorithms/pd_disaggregation_test.go
0
Go
1
none
16
51
51
true
Select PD workers in same roleset
1,409
vllm-project/aibrix
2,572
Go
varungup90
constants.StormServiceNameLabelKey: "test-service", }, }, Spec: orchestrationv1alpha1.RoleSetSpec{ SchedulingStrategy: orchestrationv1alpha1.SchedulingStrategy{ PodGroup: &schedv1alpha1.PodGroupSpec{ MinMember: 3, }, }, Roles: []orchestrationv1alpha1.RoleSpec{ { Name: "test-rol...
No issues found.
constants.StormServiceNameLabelKey: "test-service", }, }, Spec: orchestrationv1alpha1.RoleSetSpec{ SchedulingStrategy: orchestrationv1alpha1.SchedulingStrategy{ PodGroup: &schedv1alpha1.PodGroupSpec{ MinMember: 3, }, }, Roles: []orchestrationv1alpha1.RoleSpec{ { Name: "test-rol...
@@ -17,6 +17,7 @@ limitations under the License. package roleset import ( + "reflect" "testing" "github.com/stretchr/testify/assert" @@ -292,3 +293,107 @@ func makeNotReadyPod(name string) *corev1.Pod { pod.Status.Conditions[0].Status = corev1.ConditionFalse return pod } + +func TestSortRolesByUpgradeOrd...
pkg/controller/roleset/utils_test.go
0
Go
1
none
16
51
51
true
Feat: Support role upgrade sequences in stormservice
1,432
vllm-project/aibrix
2,572
Go
omerap12
testEnv *envtest.Environment // Test environment that spins up etcd and kube-apiserver ctx context.Context // Context to control the lifecycle of the controller manager cancel context.CancelFunc // Function to cancel the context and stop the manager stopCh chan struct{} // Channel to sig...
No issues found.
testEnv *envtest.Environment // Test environment that spins up etcd and kube-apiserver ctx context.Context // Context to control the lifecycle of the controller manager cancel context.CancelFunc // Function to cancel the context and stop the manager stopCh chan struct{} // Channel to sig...
@@ -0,0 +1,185 @@ +/* +Copyright 2025 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 a...
test/integration/controller/suit_test.go
0
Go
1
none
16
51
51
true
[Test]: add controller integration test framework
1,448
vllm-project/aibrix
2,572
Go
googs1025
}, ginkgo.Entry("normal RoleSet create and update replicas with sequential update strategy", &testValidatingCase{ makeRoleSet: func() *orchestrationapi.RoleSet { podTemplate := corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": "nginx", ...
No issues found.
}, ginkgo.Entry("normal RoleSet create and update replicas with sequential update strategy", &testValidatingCase{ makeRoleSet: func() *orchestrationapi.RoleSet { podTemplate := corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": "nginx", ...
@@ -0,0 +1,226 @@ +/* +Copyright 2025 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 a...
test/integration/controller/roleset_test.go
0
Go
1
none
16
51
51
true
add rolset integration test
1,491
vllm-project/aibrix
2,572
Go
googs1025
}), }, podMetrics: map[string]map[string]metrics.MetricValue{ "p1": {metrics.GPUBusyTimeRatio: &metrics.SimpleMetricValue{Value: 0.5}}, }, expectErr: false, expectMsgs: []string{"1.1.1.1:8000"}, }, { name: "all pods have no metrics - should use random fallback", readyPods: []*v1.Pod{ ...
No issues found.
}), }, podMetrics: map[string]map[string]metrics.MetricValue{ "p1": {metrics.GPUBusyTimeRatio: &metrics.SimpleMetricValue{Value: 0.5}}, }, expectErr: false, expectMsgs: []string{"1.1.1.1:8000"}, }, { name: "all pods have no metrics - should use random fallback", readyPods: []*v1.Pod{ ...
@@ -0,0 +1,241 @@ +/* +Copyright 2025 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 a...
pkg/plugins/gateway/algorithms/least_busy_time_test.go
0
Go
1
none
16
51
51
true
[Misc] Add unit tests for least_busy_time
1,495
vllm-project/aibrix
2,572
Go
omerap12
Value: roleSet.Annotations[constants.RoleSetIndexAnnotationKey], } envMap[constants.RoleNameEnvKey] = v1.EnvVar{ Name: constants.RoleNameEnvKey, Value: role.Name, } envMap[constants.RoleTemplateHashEnvKey] = v1.EnvVar{ Name: constants.RoleTemplateHashEnvKey, Value: templateHash, } if roleIndex != n...
No issues found.
Value: roleSet.Annotations[constants.RoleSetIndexAnnotationKey], } envMap[constants.RoleNameEnvKey] = v1.EnvVar{ Name: constants.RoleNameEnvKey, Value: role.Name, } envMap[constants.RoleTemplateHashEnvKey] = v1.EnvVar{ Name: constants.RoleTemplateHashEnvKey, Value: templateHash, } if roleIndex != n...
@@ -26,6 +26,7 @@ import ( "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/klog/v2" "sigs.k8s.io/controller-runtime/pkg/client" orchestrationv1alpha1 "github.com/vllm-project/aibrix/api/orchestration/v1alpha1" @@ -357,8 +358,13 @@ func creat...
pkg/controller/roleset/utils.go
0
Go
1
none
16
51
51
true
[Misc]: ignore AlreadyExists and NotFound in controller operations
1,507
vllm-project/aibrix
2,572
Go
googs1025
}, }, }, }, }, } }, }), ginkgo.Entry("apply StormService with sidecar injection annotation "+ "and sidecar runtime image annotation", &testDefaultingCase{ stormservice: func() *orchestrationapi.StormService { return makeStormServiceWithNoSidecarInjection("stormser...
No issues found.
}, }, }, }, }, } }, }), ginkgo.Entry("apply StormService with sidecar injection annotation "+ "and sidecar runtime image annotation", &testDefaultingCase{ stormservice: func() *orchestrationapi.StormService { return makeStormServiceWithNoSidecarInjection("stormser...
@@ -102,6 +102,9 @@ var _ = ginkgo.Describe("stormservice default webhook", func() { "app": "my-ai-app", }, }, + UpdateStrategy: orchestrationapi.StormServiceUpdateStrategy{ + Type: orchestrationapi.RollingUpdateStormServiceStrategyType, + }, Stateful: true, Templat...
test/integration/webhook/stormservice_webhook_test.go
0
Go
1
none
16
51
51
true
[Misc]: add sync-crds makefile cmd
1,513
vllm-project/aibrix
2,572
Go
googs1025
minExpectedLatency := math.MaxFloat64 sumPromptTokens := 0.0 sumGenerationTokens := 0.0 cntPromt := 0 cntGeneration := 0 for _, pod := range readyPodList.All() { avgPromptTokens, err := r.cache.GetMetricValueByPodModel(pod.Name, pod.Namespace, ctx.Model, metrics.AvgPromptToksPerReq) if err != nil { klog.E...
No issues found.
minExpectedLatency := math.MaxFloat64 sumPromptTokens := 0.0 sumGenerationTokens := 0.0 cntPromt := 0 cntGeneration := 0 for _, pod := range readyPodList.All() { avgPromptTokens, err := r.cache.GetMetricValueByPodModel(pod.Name, pod.Namespace, ctx.Model, metrics.AvgPromptToksPerReq) if err != nil { klog.E...
@@ -94,30 +94,40 @@ func (r leastExpectedLatencyRouter) Route(ctx *types.RoutingContext, readyPodLis } // expected prefill latency - avgPromptTokens, err := r.cache.GetMetricValueByPodModel(pod.Name, pod.Namespace, ctx.Model, metrics.AvgPromptToksPerReq) + avgPromptTokensMetric, err := r.cache.GetMetricValueB...
pkg/plugins/gateway/algorithms/least_latency.go
0
Go
1
none
16
51
51
true
[Bug] use fallback value to prevent divide zero error
1,517
vllm-project/aibrix
2,572
Go
zyfy29
createBudget-- } } if _, err = createPodSetsInBatch(ctx, p.cli, toCreate); err != nil { return err } if _, err = deletePodSetsInBatch(ctx, p.cli, toDelete); err != nil { return err } p.printLog(roleSet, role, toCreate, toDelete) return nil } func (p *PodSetRoleSyncer) AllReady(ctx context.Context, role...
No issues found.
createBudget-- } } if _, err = createPodSetsInBatch(ctx, p.cli, toCreate); err != nil { return err } if _, err = deletePodSetsInBatch(ctx, p.cli, toDelete); err != nil { return err } p.printLog(roleSet, role, toCreate, toDelete) return nil } func (p *PodSetRoleSyncer) AllReady(ctx context.Context, role...
@@ -442,7 +442,7 @@ func getRolePodSets(ctx context.Context, cli client.Client, namespace, roleSetNa func filterActivePodSets(allPodSets []*orchestrationv1alpha1.PodSet) ([]*orchestrationv1alpha1.PodSet, []*orchestrationv1alpha1.PodSet) { var active, inactive []*orchestrationv1alpha1.PodSet for _, podSet := range ...
pkg/controller/roleset/podset_rollsyncer.go
0
Go
1
none
16
51
51
true
[Bug] fix count ready podset condition
1,518
vllm-project/aibrix
2,572
Go
Epsilon314
// Remove from all maps for node := range nodeMap { delete(h.histogram, node) delete(h.nodeToCount, node) delete(h.hitTokens, node) delete(h.promptTokens, node) delete(h.decodingSize, node) delete(h.podAllocations, node) } } func (h *SlidingWindowHistogram) removeOldEntries(currentTime time.Time) { h.m...
No issues found.
// Remove from all maps for node := range nodeMap { delete(h.histogram, node) delete(h.nodeToCount, node) delete(h.hitTokens, node) delete(h.promptTokens, node) delete(h.decodingSize, node) delete(h.podAllocations, node) } } func (h *SlidingWindowHistogram) removeOldEntries(currentTime time.Time) { h.m...
@@ -542,7 +542,9 @@ func (p *prefixCacheAndLoadRouter) Route(ctx *types.RoutingContext, readyPodList targetPod = pod } } - klog.InfoS("Lowest cost pod: %s", "podName", targetPod.Name) + if targetPod != nil { + klog.InfoS("Lowest cost pod: %s", "podName", targetPod.Name) + } } if targetPod == nil ...
pkg/plugins/gateway/algorithms/prefix_cache_preble.go
0
Go
1
none
16
51
51
true
[Misc] (test): add unit test for prefix_cache_preble
1,519
vllm-project/aibrix
2,572
Go
zhengkezhou1
blocks. Each tuple in it represents (block id, address offset). on_mr_release: Callback function when memory region is released. Returns: KVCacheHandle. """ block_ntokens = block_spec.block_ntokens block_nbytes = block_spec.block_nbytes block_...
No issues found.
blocks. Each tuple in it represents (block id, address offset). on_mr_release: Callback function when memory region is released. Returns: KVCacheHandle. """ block_ntokens = block_spec.block_ntokens block_nbytes = block_spec.block_nbytes block_...
@@ -100,7 +100,7 @@ def __len__(self) -> int: def create( blocks: Sequence[torch.Tensor], block_spec: KVCacheBlockSpec, - slot_mapping: Sequence[int] | torch.Tensor, + select: Sequence[Tuple[int, int]], on_mr_release: Callable[[torch.Tensor, int, int], None] | None = None, ...
python/aibrix_kvcache/aibrix_kvcache/cache_handle.py
0
Python
1
none
16
51
51
true
[Refactor] KVCache: simplify external cache handle create API
1,542
vllm-project/aibrix
2,572
Go
DwyaneShi
template := orchestrationapi.RoleSetTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": "my-ai-app", }, }, Spec: &orchestrationapi.RoleSetSpec{ UpdateStrategy: orchestrationapi.InterleaveRoleSetStrategyType, Roles: []orchestrationapi.RoleSpec{}, }, } w.stor...
No issues found.
template := orchestrationapi.RoleSetTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": "my-ai-app", }, }, Spec: &orchestrationapi.RoleSetSpec{ UpdateStrategy: orchestrationapi.InterleaveRoleSetStrategyType, Roles: []orchestrationapi.RoleSpec{}, }, } w.stor...
@@ -17,9 +17,8 @@ limitations under the License. package wrapper import ( - "strconv" - "fmt" + "strconv" corev1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1" @@ -29,7 +28,7 @@ import ( "k8s.io/utils/ptr" orchestrationapi "github.com/vllm-project/aibrix/api/orchestration/v1alpha1" - webhook "github.com...
test/utils/wrapper/stormservice.go
0
Go
1
none
16
51
51
true
[Misc]: add stormservice integration test
1,544
vllm-project/aibrix
2,572
Go
googs1025
package v1alpha1 // RoleStatusApplyConfiguration represents a declarative configuration of the RoleStatus type for use // with apply. type RoleStatusApplyConfiguration struct { Name *string `json:"name,omitempty"` Replicas *int32 `json:"replicas,omitempty"` ReadyReplicas *int32 ...
No issues found.
package v1alpha1 // RoleStatusApplyConfiguration represents a declarative configuration of the RoleStatus type for use // with apply. type RoleStatusApplyConfiguration struct { Name *string `json:"name,omitempty"` Replicas *int32 `json:"replicas,omitempty"` ReadyReplicas *int32 ...
@@ -0,0 +1,83 @@ +/* +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 ag...
pkg/client/applyconfiguration/orchestration/v1alpha1/rolestatus.go
0
Go
1
none
16
51
51
true
[API]: add roleStatuses field in stormservice api
1,599
vllm-project/aibrix
2,572
Go
googs1025
for _, pod := range decodePods { if podRoleSet, exists := pod.Labels[PDRoleSetIdentifier]; exists && podRoleSet == prefillRoleSet { filteredDecodePods = append(filteredDecodePods, pod) } } if len(filteredDecodePods) == 0 { return nil } // prefer decode pod with least running requests decodePod := select...
No issues found.
for _, pod := range decodePods { if podRoleSet, exists := pod.Labels[PDRoleSetIdentifier]; exists && podRoleSet == prefillRoleSet { filteredDecodePods = append(filteredDecodePods, pod) } } if len(filteredDecodePods) == 0 { return nil } // prefer decode pod with least running requests decodePod := select...
@@ -145,11 +145,22 @@ func (r *pdRouter) evaluatePrefixCache(ctx *types.RoutingContext, prefillPods [] matchedPods, prefixHashes := r.prefixCacheIndexer.MatchPrefix(tokens, ctx.Model, readyPodsMap) var prefillPod *v1.Pod - if len(matchedPods) > 0 { + // check for load imbalance first + targetPod, isImbalanced := ...
pkg/plugins/gateway/algorithms/pd_disaggregation.go
0
Go
1
none
16
51
51
true
Improve pdRouter with load-aware routing
1,601
vllm-project/aibrix
2,572
Go
googs1025
return processingRes, complete } } } var requestEnd string if totalTokens != 0 { complete = true // Count token per user. if user.Name != "" { tpm, err := s.ratelimiter.Incr(ctx, fmt.Sprintf("%v_TPM_CURRENT", user.Name), totalTokens) if err != nil { return generateErrorResponse( envoy...
No issues found.
return processingRes, complete } } } var requestEnd string if totalTokens != 0 { complete = true // Count token per user. if user.Name != "" { tpm, err := s.ratelimiter.Incr(ctx, fmt.Sprintf("%v_TPM_CURRENT", user.Name), totalTokens) if err != nil { return generateErrorResponse( envoy...
@@ -23,6 +23,7 @@ import ( "fmt" "io" "net/http" + "strings" "github.com/openai/openai-go" "github.com/openai/openai-go/packages/ssestream" @@ -37,7 +38,7 @@ import ( type OpenAIResponse struct { Model string `json:"model"` - Usage struct { + Usage *struct { PromptTokens int64 `json:"prompt_toke...
pkg/plugins/gateway/gateway_rsp_body.go
0
Go
1
none
16
51
51
true
Add gateway-plugin support to generate image and video
1,603
vllm-project/aibrix
2,572
Go
varungup90
setCondition(&pa, string(condition.Type), metav1.ConditionStatus(condition.Status), condition.Reason, condition.Message) } if err = r.Status().Update(ctx, &pa); err != nil { klog.ErrorS(err, "Failed to update PodAutoscaler status") } // Return with no error and no requeue needed. return ctrl.Result{}, nil } /...
No issues found.
setCondition(&pa, string(condition.Type), metav1.ConditionStatus(condition.Status), condition.Reason, condition.Message) } if err = r.Status().Update(ctx, &pa); err != nil { klog.ErrorS(err, "Failed to update PodAutoscaler status") } // Return with no error and no requeue needed. return ctrl.Result{}, nil } /...
@@ -52,7 +52,6 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/discovery" memcache "k8s.io/client-go/discovery/cached/memory" "k8s.io/client-go/re...
pkg/controller/podautoscaler/podautoscaler_controller.go
0
Go
1
none
16
51
51
true
feat: add scaling history decision in the status spec
1,618
vllm-project/aibrix
2,572
Go
omerap12
# 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...
No issues found.
# 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...
@@ -15,5 +15,6 @@ from .async_base import AsyncBase from .cached_pyobject import CachedPyObjectBase from .object_pool import ObjectPool +from .threading import ConditionalLock -__all__ = ["AsyncBase", "ObjectPool", "CachedPyObjectBase"] +__all__ = ["AsyncBase", "ObjectPool", "CachedPyObjectBase", "ConditionalLock"...
python/aibrix_kvcache/aibrix_kvcache/common/__init__.py
0
Python
1
none
16
21
21
true
[Feature] KVCache: support multi-threading mode
1,628
vllm-project/aibrix
2,572
Go
DwyaneShi
} // ScalingStrategyType defines the type for scaling strategies. type ScalingStrategyType string const ( // HPA represents the Kubernetes native Horizontal Pod Autoscaler. HPA ScalingStrategyType = "HPA" // KPA represents the KNative Pod Autoscaling Algorithm KPA ScalingStrategyType = "KPA" // APA represents ...
No issues found.
} // ScalingStrategyType defines the type for scaling strategies. type ScalingStrategyType string const ( // HPA represents the Kubernetes native Horizontal Pod Autoscaler. HPA ScalingStrategyType = "HPA" // KPA represents the KNative Pod Autoscaling Algorithm KPA ScalingStrategyType = "KPA" // APA represents ...
@@ -132,14 +132,18 @@ type MetricSource struct { // Specifies how to fetch metrics: from individual pods, Kubernetes APIs, or external services // +kubebuilder:validation:Enum={pod,resource,custom,external,domain} MetricSourceType MetricSourceType `json:"metricSourceType"` - // Protocol for metric collection + //...
api/autoscaling/v1alpha1/podautoscaler_types.go
0
Go
1
none
16
51
51
true
[Bug]: Make optional fields in MetricSource
1,648
vllm-project/aibrix
2,572
Go
googs1025
for i := 0; i < count && len(remainingPods) > 0; i++ { pod, err := r.scheduler.SelectPod(ctx, instance.Name, remainingPods) if err != nil { return nil, err } selectedPods = append(selectedPods, *pod) // Remove selected pod from remaining pods to avoid selecting it again for j, p := range remainingPod...
No issues found.
for i := 0; i < count && len(remainingPods) > 0; i++ { pod, err := r.scheduler.SelectPod(ctx, instance.Name, remainingPods) if err != nil { return nil, err } selectedPods = append(selectedPods, *pod) // Remove selected pod from remaining pods to avoid selecting it again for j, p := range remainingPod...
@@ -360,13 +360,18 @@ func (r *ModelAdapterReconciler) DoReconcile(ctx context.Context, req ctrl.Reque oldInstance := instance.DeepCopy() + // Save old instances list before reconcileReplicas potentially modifies it + // This is needed to detect pod removal in reconcileLoading + oldInstances := make([]string, len...
pkg/controller/modeladapter/modeladapter_controller.go
0
Go
1
none
16
51
51
true
Refactor the model adapter replicas feature
1,670
vllm-project/aibrix
2,572
Go
Jeffwan
var anyValid bool for _, metricSource := range metricsSources { // Extract per-request configuration metricKey := types.MetricKey{ Namespace: pa.Namespace, Name: pa.Spec.ScaleTargetRef.Name, MetricName: metricSource.TargetMetric, PaNamespace: pa.Namespace, PaName: pa.Name, } re...
No issues found.
var anyValid bool for _, metricSource := range metricsSources { // Extract per-request configuration metricKey := types.MetricKey{ Namespace: pa.Namespace, Name: pa.Spec.ScaleTargetRef.Name, MetricName: metricSource.TargetMetric, PaNamespace: pa.Namespace, PaName: pa.Name, } re...
@@ -123,27 +123,114 @@ func (a *DefaultAutoScaler) getOrCreateAlgorithm(strategy autoscalingv1alpha1.Sc return algo } +// ComputeDesiredReplicas computes desired replicas based on all metrics in MetricsSources. +// It returns the maximum recommended replicas across all valid metrics. func (a *DefaultAutoScaler) C...
pkg/controller/podautoscaler/autoscaler.go
0
Go
1
none
16
51
51
true
[Feat]: support mulit metrics for podautoscaler
1,688
vllm-project/aibrix
2,572
Go
googs1025
constants.PodGroupIndexLabelKey: "0", }) cl := fake.NewClientBuilder().WithScheme(sch). WithObjects(p0, p1, pWrongApp). Build() pa := autoscalingv1alpha1.PodAutoscaler{} pa.Namespace = ns // Scale target is a Deployment (not StormService). scaleObj := buildScaleObject("apps/v1", "Deployment", ns, "foo-de...
No issues found.
constants.PodGroupIndexLabelKey: "0", }) cl := fake.NewClientBuilder().WithScheme(sch). WithObjects(p0, p1, pWrongApp). Build() pa := autoscalingv1alpha1.PodAutoscaler{} pa.Namespace = ns // Scale target is a Deployment (not StormService). scaleObj := buildScaleObject("apps/v1", "Deployment", ns, "foo-de...
@@ -0,0 +1,328 @@ +/* +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 a...
pkg/controller/podautoscaler/podautoscaler_controller_test.go
0
Go
1
none
16
51
51
true
fix: autoscaler for the podset only collect metrics from rank0
1,704
vllm-project/aibrix
2,572
Go
scarlet25151
name string routingCtx *types.RoutingContext responseStatus string // value of :status header respHeaders map[string]string expected testResponse } tests := []testCase{ { name: "successful response (200)", routingCtx: createRoutingCtx(true, map[string]string{"X-...
No issues found.
name string routingCtx *types.RoutingContext responseStatus string // value of :status header respHeaders map[string]string expected testResponse } tests := []testCase{ { name: "successful response (200)", routingCtx: createRoutingCtx(true, map[string]string{"X-...
@@ -0,0 +1,185 @@ +/* +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 a...
pkg/plugins/gateway/gateway_rsp_headers_test.go
0
Go
1
none
16
51
51
true
feature: add simple session affinity plugins in gateway plugin
1,751
vllm-project/aibrix
2,572
Go
googs1025
Subsystem: constants.AibrixSubsystemName, Name: "kvcache_zmq_errors_total", Help: "Total number of errors encountered", }, []string{LabelPodKey, LabelErrorType}, ), // State metrics zmqConnectionStatus: prometheus.NewGaugeVec( prometheus.GaugeOpts{ Subsystem: constants.AibrixSu...
No issues found.
Subsystem: constants.AibrixSubsystemName, Name: "kvcache_zmq_errors_total", Help: "Total number of errors encountered", }, []string{LabelPodKey, LabelErrorType}, ), // State metrics zmqConnectionStatus: prometheus.NewGaugeVec( prometheus.GaugeOpts{ Subsystem: constants.AibrixSu...
@@ -21,6 +21,8 @@ import ( "github.com/prometheus/client_golang/prometheus" "k8s.io/klog/v2" + + "github.com/vllm-project/aibrix/pkg/constants" ) // Metric labels @@ -97,101 +99,114 @@ func createKVCacheMetrics() *KVCacheMetrics { // Connection metrics zmqConnectionTotal: prometheus.NewCounterVec( p...
pkg/cache/kvcache/metrics.go
0
Go
1
none
16
51
51
true
refactor(metrics): use Subsystem for aibrix metrics instead of embedding in Name
1,756
vllm-project/aibrix
2,572
Go
googs1025
func buildRuntimeSidecarContainer(sidecarImage, engineType string) corev1.Container { return corev1.Container{ Name: SidecarName, Image: sidecarImage, Command: []string{ SidecarCommand, "--port", fmt.Sprintf("%d", SidecarPort), }, Env: []corev1.EnvVar{ { Name: "INFERENCE_ENGINE", Value: en...
No issues found.
func buildRuntimeSidecarContainer(sidecarImage, engineType string) corev1.Container { return corev1.Container{ Name: SidecarName, Image: sidecarImage, Command: []string{ SidecarCommand, "--port", fmt.Sprintf("%d", SidecarPort), }, Env: []corev1.EnvVar{ { Name: "INFERENCE_ENGINE", Value: en...
@@ -32,7 +32,7 @@ const ( // SidecarInjectionRuntimeImageAnnotation Annotation used to specify a custom image for the sidecar container SidecarInjectionRuntimeImageAnnotation = "model.aibrix.ai/sidecar-runtime-image" SidecarName = "aibrix-runtime" - SidecarImage ...
pkg/webhook/sidecar_injection.go
0
Go
1
none
16
51
51
true
[Misc] upgrade sidecar webhook image from v0.4.0 to v0.5.0
1,762
vllm-project/aibrix
2,572
Go
nurali-techie
Controller: boolPtr(true), BlockOwnerDeletion: boolPtr(true), } assert.NoError(t, ValidateControllerRef(ref)) table := []struct { name string ref *metav1.OwnerReference err string }{ {"nil ref", nil, "controllerRef is nil"}, {"empty version", &metav1.OwnerReference{Kind: "A", Controller: bo...
No issues found.
Controller: boolPtr(true), BlockOwnerDeletion: boolPtr(true), } assert.NoError(t, ValidateControllerRef(ref)) table := []struct { name string ref *metav1.OwnerReference err string }{ {"nil ref", nil, "controllerRef is nil"}, {"empty version", &metav1.OwnerReference{Kind: "A", Controller: bo...
@@ -132,4 +132,12 @@ func TestMinIntHelpers(t *testing.T) { assert.Equal(t, -5, MinInt(-5, 0)) } +func TestShorten(t *testing.T) { + assert.Equal(t, "abcdefghijklmnopqrstuvwxyz", Shorten("abcdefghijklmnopqrstuvwxyz", false, false)) + assert.Equal(t, "aijklmnopqrstuvwxyz-1234567890-1234567890-1234567890-1234567890"...
pkg/controller/util/orchestration/util_test.go
0
Go
1
none
16
51
51
true
fix(controller): shorten resource name
1,777
vllm-project/aibrix
2,572
Go
zhixian82
Obj() }, wantStormService: func() *orchestrationapi.StormService { return wrapper.MakeStormService("st-with-no-inject-sidecar"). Namespace(ns.Name). WithDefaultConfiguration(). Obj() }, }), ginkgo.Entry("apply StormService with sidecar injection annotation", &testDefaultingCase{ ...
No issues found.
Obj() }, wantStormService: func() *orchestrationapi.StormService { return wrapper.MakeStormService("st-with-no-inject-sidecar"). Namespace(ns.Name). WithDefaultConfiguration(). Obj() }, }), ginkgo.Entry("apply StormService with sidecar injection annotation", &testDefaultingCase{ ...
@@ -17,6 +17,8 @@ limitations under the License. package webhook import ( + "strings" + "github.com/google/go-cmp/cmp/cmpopts" "github.com/onsi/ginkgo/v2" "github.com/onsi/gomega" @@ -74,28 +76,28 @@ var _ = ginkgo.Describe("stormservice default webhook", func() { }, ginkgo.Entry("apply StormService wit...
test/integration/webhook/stormservice_webhook_test.go
0
Go
1
none
16
51
51
true
[Bug]: add validation in stormservice webhook
1,778
vllm-project/aibrix
2,572
Go
googs1025
}, originalBody: `{"messages":[{"role":"user","content":"test"}]}`, expectError: false, expectKV: true, }, { name: "no kv params in response", responseData: map[string]any{"other": "data"}, originalBody: `{"messages":[{"role":"user","content":"test"}]}`, expectError: false, ...
No issues found.
}, originalBody: `{"messages":[{"role":"user","content":"test"}]}`, expectError: false, expectKV: true, }, { name: "no kv params in response", responseData: map[string]any{"other": "data"}, originalBody: `{"messages":[{"role":"user","content":"test"}]}`, expectError: false, ...
@@ -1284,3 +1284,120 @@ func TestLoadImbalanceSelectDecodePod(t *testing.T) { }) } } + +func TestIsPodSuitableForPromptLength(t *testing.T) { + tests := []struct { + name string + podLabels map[string]string + promptLength int + expected bool + }{ + { + name: "no prompt length range configur...
pkg/plugins/gateway/algorithms/pd_disaggregation_test.go
0
Go
1
none
16
51
51
true
feat:router based on multi deployment configs
1,835
vllm-project/aibrix
2,572
Go
erictanjn
{ name: "array of strings exceeding total tokens", input: openai.EmbeddingNewParams{ Input: openai.EmbeddingNewParamsInputUnion{ OfArrayOfStrings: func() []string { // Create an array that would exceed MaxTotalTokens largeString := strings.Repeat("word ", MaxTotalTokens/2) return []st...
No issues found.
{ name: "array of strings exceeding total tokens", input: openai.EmbeddingNewParams{ Input: openai.EmbeddingNewParamsInputUnion{ OfArrayOfStrings: func() []string { // Create an array that would exceed MaxTotalTokens largeString := strings.Repeat("word ", MaxTotalTokens/2) return []st...
@@ -334,6 +334,79 @@ func Test_ValidateRequestBody_Embeddings(t *testing.T) { } } +func Test_ValidateRequestBody_Rerank(t *testing.T) { + testCases := []struct { + message string + requestPath string + requestBody []byte + model string + messages string + stream bool + user utils.Us...
pkg/plugins/gateway/util_test.go
0
Go
1
none
16
51
51
true
[feat]: support rerank models
1,837
vllm-project/aibrix
2,572
Go
sanmuny
assert.Equal(t, tt.routingAlgo, routingCtx.Algorithm) // Verify both routing headers are set foundRoutingStrategy := false foundTargetPod := false for _, header := range resp.GetRequestBody().GetResponse().GetHeaderMutation().GetSetHeaders() { if header.Header.Key == HeaderRoutingStrategy { ...
No issues found.
assert.Equal(t, tt.routingAlgo, routingCtx.Algorithm) // Verify both routing headers are set foundRoutingStrategy := false foundTargetPod := false for _, header := range resp.GetRequestBody().GetResponse().GetHeaderMutation().GetSetHeaders() { if header.Header.Key == HeaderRoutingStrategy { ...
@@ -28,12 +28,13 @@ import ( configPb "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" extProcPb "github.com/envoyproxy/go-control-plane/envoy/service/ext_proc/v3" envoyTypePb "github.com/envoyproxy/go-control-plane/envoy/type/v3" + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/...
pkg/plugins/gateway/gateway_req_body_test.go
0
Go
1
none
16
51
51
true
[bugfix] ReqBody receive stream=true when calling /v1/completion
1,850
vllm-project/aibrix
2,572
Go
DengHom
func (r *leastRequestRouter) SubscribedMetrics() []string { return []string{ metrics.RealtimeNumRequestsRunning, } } func selectTargetPodWithLeastRequestCount(cache cache.Cache, readyPods []*v1.Pod) *v1.Pod { var targetPod *v1.Pod targetPods := []string{} minCount := math.MaxInt32 podRequestCount := getReque...
No issues found.
func (r *leastRequestRouter) SubscribedMetrics() []string { return []string{ metrics.RealtimeNumRequestsRunning, } } func selectTargetPodWithLeastRequestCount(cache cache.Cache, readyPods []*v1.Pod) *v1.Pod { var targetPod *v1.Pod targetPods := []string{} minCount := math.MaxInt32 podRequestCount := getReque...
@@ -17,8 +17,11 @@ limitations under the License. package routingalgorithms import ( + "fmt" "math" "math/rand" + "strconv" + "strings" "github.com/vllm-project/aibrix/pkg/cache" "github.com/vllm-project/aibrix/pkg/metrics" @@ -45,14 +48,19 @@ func NewLeastRequestRouter() (types.Router, error) { return...
pkg/plugins/gateway/algorithms/least_request.go
0
Go
1
none
16
51
51
true
[feat] add distribute-dp api server least_request route
1,866
vllm-project/aibrix
2,572
Go
paranoidRick
contentTypeKey = "content-type" ) func (s *Server) HandleRequestHeaders(ctx context.Context, requestID string, req *extProcPb.ProcessingRequest) (*extProcPb.ProcessingResponse, utils.User, int64, *types.RoutingContext) { var username, requestPath string var user utils.User var rpm int64 var err error var errRe...
No issues found.
contentTypeKey = "content-type" ) func (s *Server) HandleRequestHeaders(ctx context.Context, requestID string, req *extProcPb.ProcessingRequest) (*extProcPb.ProcessingResponse, utils.User, int64, *types.RoutingContext) { var username, requestPath string var user utils.User var rpm int64 var err error var errRe...
@@ -106,14 +106,10 @@ func (s *Server) HandleRequestHeaders(ctx context.Context, requestID string, req }, }) - switch requestPath { - case "/v1/image/generations": - headers = buildEnvoyProxyHeaders(headers, ":path", "/generate") - case "/v1/video/generations": - headers = buildEnvoyProxyHeaders(headers, ":pat...
pkg/plugins/gateway/gateway_req_headers.go
0
Go
1
none
16
51
51
true
Support OpenAI compatible image generation endpoint
1,867
vllm-project/aibrix
2,572
Go
Jeffwan
Kind: "Deployment", }, ScalingStrategy: autoscalingv1alpha1.HPA, MetricsSources: []autoscalingv1alpha1.MetricSource{ { MetricSourceType: autoscalingv1alpha1.RESOURCE, TargetMetric: "cpu", TargetValue: "50", }, }, }, }, expectError: false, }...
No issues found.
Kind: "Deployment", }, ScalingStrategy: autoscalingv1alpha1.HPA, MetricsSources: []autoscalingv1alpha1.MetricSource{ { MetricSourceType: autoscalingv1alpha1.RESOURCE, TargetMetric: "cpu", TargetValue: "50", }, }, }, }, expectError: false, }...
@@ -0,0 +1,130 @@ +/* +Copyright 2026 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 a...
pkg/webhook/podautoscaler_webhook_test.go
0
Go
1
none
16
51
51
true
[Bug] Prevent div by zero in APA
1,879
vllm-project/aibrix
2,572
Go
alpe
err := recover() if err != nil { klog.Errorf("slowStartBatch panic: %v", err) } }() defer wg.Done() if err := fn(index); err != nil { errCh <- err } }(finished + i) } wg.Wait() curSuccesses := batchSize - len(errCh) successes += curSuccesses if len(errCh) > 0 { ...
No issues found.
err := recover() if err != nil { klog.Errorf("slowStartBatch panic: %v", err) } }() defer wg.Done() if err := fn(index); err != nil { errCh <- err } }(finished + i) } wg.Wait() curSuccesses := batchSize - len(errCh) successes += curSuccesses if len(errCh) > 0 { ...
@@ -268,7 +268,7 @@ func MinInt(a, b int) int { return b } -func EnsurePodGroupExist(ctx context.Context, dc dynamic.Interface, podGroup client.Object, name, namespace string) (created bool, err error) { +func EnsurePodGroup(ctx context.Context, dc dynamic.Interface, podGroup client.Object, name, namespace string)...
pkg/controller/util/orchestration/util.go
0
Go
1
none
16
51
51
true
[Feat]: update PodGroup when RoleSet.SchedulingStrategy changed
1,889
vllm-project/aibrix
2,572
Go
fungaren
) -> str: """ Download from GCS. Credentials dict should contain: - gcp_service_account_json: Service account JSON string """ try: from google.cloud import storage from google.oauth2 import service_account except ImportError: ...
No issues found.
) -> str: """ Download from GCS. Credentials dict should contain: - gcp_service_account_json: Service account JSON string """ try: from google.cloud import storage from google.oauth2 import service_account except ImportError: ...
@@ -14,6 +14,8 @@ """Artifact downloaders for different storage backends.""" +import asyncio +import functools import os from abc import ABC, abstractmethod from pathlib import Path @@ -58,6 +60,18 @@ class S3ArtifactDownloader(ArtifactDownloader): async def download( self, source_url: str, loca...
python/aibrix/aibrix/runtime/downloaders.py
0
Python
1
none
16
51
51
true
[Bug] Refactor downloader and artifact_service to be non-blocking
1,895
vllm-project/aibrix
2,572
Go
xieus
self.download_calls = [] fake_tos.last_client = self def list_objects_type2(self, bucket_name: str, **kwargs): prefix = kwargs.get("prefix", "") keys = [ prefix, f"{prefix}.git/", f"{prefix}sub/", f"...
No issues found.
self.download_calls = [] fake_tos.last_client = self def list_objects_type2(self, bucket_name: str, **kwargs): prefix = kwargs.get("prefix", "") keys = [ prefix, f"{prefix}.git/", f"{prefix}sub/", f"...
@@ -0,0 +1,131 @@ +# 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 ...
python/aibrix/tests/runtime/test_runtime_downloaders_tos.py
0
Python
1
none
16
51
51
true
Feat: delegate artifacts preparation to lora downloader
1,898
vllm-project/aibrix
2,572
Go
scarlet25151
t.Fatalf("computeMetricBasedReplicas returned error: %v", err) } if res == nil { t.Fatalf("expected non-nil result") } if as.lastRequest == nil { t.Fatalf("autoscaler did not receive request") } if as.lastRequest.CurrentReplicas != currentReplicas { t.Fatalf("CurrentReplicas mismatch: got=%d want=%d", as....
No issues found.
t.Fatalf("computeMetricBasedReplicas returned error: %v", err) } if res == nil { t.Fatalf("expected non-nil result") } if as.lastRequest == nil { t.Fatalf("autoscaler did not receive request") } if as.lastRequest.CurrentReplicas != currentReplicas { t.Fatalf("CurrentReplicas mismatch: got=%d want=%d", as....
@@ -29,6 +29,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/selection" "k8s.io/client-go/kubernetes/scheme" + "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client/fake" autoscalingv1alpha1 "github.com/vllm-project/aibrix/api/autoscaling/v1alpha1" @@ -111,6 +112,28 @@ func ...
pkg/controller/podautoscaler/podautoscaler_controller_test.go
0
Go
1
none
16
51
51
true
[Bugfix] add APA support to stormService without podGroupSize (#1913)
1,917
vllm-project/aibrix
2,572
Go
rayne-Li
} if len(prefixHashes) > 0 && targetPrefillPod != nil { r.enqueuePrefixUpdate(prefixHashes, routingCtx.Model, targetPrefillPod.Name) } r.countersMu.Lock() r.selectionCounts[targetPrefillPod.Name]++ r.selectionCounts[targetDecodePod.Name]++ r.countersMu.Unlock() metrics.EmitCounterMetric(routingCtx, targetPr...
No issues found.
} if len(prefixHashes) > 0 && targetPrefillPod != nil { r.enqueuePrefixUpdate(prefixHashes, routingCtx.Model, targetPrefillPod.Name) } r.countersMu.Lock() r.selectionCounts[targetPrefillPod.Name]++ r.selectionCounts[targetDecodePod.Name]++ r.countersMu.Unlock() metrics.EmitCounterMetric(routingCtx, targetPr...
@@ -127,7 +127,7 @@ func NewPDRouter() (types.Router, error) { pdRouter := pdRouter{ cache: c, tokenizer: tokenizerObj, - prefixCacheIndexer: prefixcacheindexer.NewPrefixHashTable(), + prefixCacheIndexer: prefixcacheindexer.GetSharedPrefixHashTable(), prefillRequestTracker...
pkg/plugins/gateway/algorithms/pd_disaggregation.go
0
Go
1
none
16
51
51
true
fix: use a shared prefix cache indexer across routing-strategies
1,939
vllm-project/aibrix
2,572
Go
varungup90
} } /* * Template arguments: * - TOnload: True if offload_kv_cache to kv_cache. * - TLayout: The layout of offload_kv_cache. * Args: * - offload_kv_cache: Supports LCND and NCLD layouts. * LCND: [num_blocks, num_layers, 2, block_size, dim] * NCLD: [num_blocks, block_siz...
No issues found.
} } /* * Template arguments: * - TOnload: True if offload_kv_cache to kv_cache. * - TLayout: The layout of offload_kv_cache. * Args: * - offload_kv_cache: Supports LCND and NCLD layouts. * LCND: [num_blocks, num_layers, 2, block_size, dim] * NCLD: [num_blocks, block_siz...
@@ -52,15 +52,23 @@ torch::Tensor get_device_ptrs(const std::vector<TTensor> &tensors) { return gpu_data_ptrs; } -__device__ __forceinline__ int64_t -get_kv_cache_offset(const int64_t kv_type, const int64_t num_blocks, - const int64_t block_size, const int64_t embed_dim, - co...
python/aibrix_kvcache/csrc/cache_kernels.cu
0
CUDA
1
none
16
51
51
true
[Feature] KVCache support block-first layout
1,947
vllm-project/aibrix
2,572
Go
DwyaneShi
"gateway_pod", }, labelNames) require.Equal(t, []string{ "ns1", "llm-pod-1", "m1", "vllm", "rs1", "role1", "0", "gw-pod-1", }, labelValues) } func TestEmitMetricToPrometheus_GaugeAndCounter(t *testing.T) { var gaugeCalls []struct { name string value float64 } originalGaugeFn := metrics.Se...
No issues found.
"gateway_pod", }, labelNames) require.Equal(t, []string{ "ns1", "llm-pod-1", "m1", "vllm", "rs1", "role1", "0", "gw-pod-1", }, labelValues) } func TestEmitMetricToPrometheus_GaugeAndCounter(t *testing.T) { var gaugeCalls []struct { name string value float64 } originalGaugeFn := metrics.Se...
@@ -15,6 +15,11 @@ limitations under the License. package cache import ( + "encoding/base64" + "fmt" + "net/http" + "net/http/httptest" + "sync" "testing" "time" @@ -23,6 +28,7 @@ import ( "github.com/vllm-project/aibrix/pkg/metrics" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ...
pkg/cache/cache_metrics_test.go
0
Go
1
none
16
51
51
true
Feat: load prom auth from secret
1,949
vllm-project/aibrix
2,572
Go
scarlet25151
# ruff: noqa import json import random import string from vllm import LLM from vllm.sampling_params import SamplingParams # This script is an offline demo for running Pixtral. # # If you want to run a server/client setup, please follow this code: # # - Server: # # ```bash # vllm serve mistralai/Mistral-7B-Instruct-v0...
Example file of how to use Mistral models with function calling
# ruff: noqa import json import random import string from vllm import LLM from vllm.sampling_params import SamplingParams # This script is an offline demo for function calling # # If you want to run a server/client setup, please follow this code: # # - Server: # # ```bash # vllm serve mistralai/Mistral-7B-Instruct-v0...
@@ -0,0 +1,138 @@ +# ruff: noqa
examples/offline_chat_with_tools.py
1
Python
0.357
suggestion
63
26
26
false
[Model] Add mistral function calling format to all models loaded with "mistral" format
8,515
vllm-project/vllm
71,895
Python
patrickvonplaten
patrickvonplaten
return {} def encode(self, prompt: str) -> List[int]: # `encode` should only be used for prompt completion # it should never be used for chat_completion. # For chat completion use `apply_chat_template` return self.tokenizer.encode(prompt, bos=True, eos=False) def apply_...
```suggestion return "".join( t for t in tokens if t not in self.tokenizer._all_special_tokens ) ``` `str.join` works on iterables so we can avoid iterating through it twice.
return {} def encode(self, prompt: str) -> List[int]: # `encode` should only be used for prompt completion # it should never be used for chat_completion. # For chat completion use `apply_chat_template` return self.tokenizer.encode(prompt, bos=True, eos=False) def apply_...
@@ -165,18 +165,20 @@ def apply_chat_template(self, messages: List["ChatCompletionMessageParam"], tools: Optional[Dict[str, Any]] = None, **kwargs) -> List[int]: - assert tools is None, "`tools` are not yet supported." - ...
vllm/transformers_utils/tokenizers/mistral.py
26
Python
1
suggestion
238
51
49
false
[Model] Add mistral function calling format to all models loaded with "mistral" format
8,515
vllm-project/vllm
71,895
Python
DarkLight1337
patrickvonplaten
) as mistral_format_model: mistral_format_outputs = mistral_format_model.generate_greedy_logprobs( example_prompts, max_tokens, num_logprobs) check_logprobs_close( outputs_0_lst=hf_format_outputs, outputs_1_lst=mistral_format_outputs, name_0="hf", name_1="mis...
> @DarkLight1337 seems like mistral-nemo is too large for the decoder-only tests: We can set `max_model_len` here to reduce the memory usage.
load_format="mistral", config_format="mistral", ) as mistral_format_model: mistral_format_outputs = mistral_format_model.generate_greedy_logprobs( example_prompts, max_tokens, num_logprobs) check_logprobs_close( outputs_0_lst=hf_format_outputs, output...
@@ -81,3 +127,22 @@ def test_mistral_format( name_0="hf", name_1="mistral", ) + + +@pytest.mark.parametrize("dtype", ["bfloat16"]) +@pytest.mark.parametrize("model", MODELS[1:]) # v1 can't do func calling +def test_mistral_function_calling( + vllm_runner, + model: str, + dtype: str, +) ...
tests/models/decoder_only/language/test_mistral.py
26
Python
0.786
suggestion
144
30
32
false
[Model] Add mistral function calling format to all models loaded with "mistral" format
8,515
vllm-project/vllm
71,895
Python
DarkLight1337
patrickvonplaten
# ruff: noqa import json import random import string from vllm import LLM from vllm.sampling_params import SamplingParams # This script is an offline demo for running Pixtral. # # If you want to run a server/client setup, please follow this code: # # - Server: # # ```bash # vllm serve mistralai/Mistral-7B-Instruct-v0...
Note that this is not a demo for Pixtral
# ruff: noqa import json import random import string from vllm import LLM from vllm.sampling_params import SamplingParams # This script is an offline demo for function calling # # If you want to run a server/client setup, please follow this code: # # - Server: # # ```bash # vllm serve mistralai/Mistral-7B-Instruct-v0...
@@ -0,0 +1,138 @@ +# ruff: noqa +import json +import random +import string + +from vllm import LLM +from vllm.sampling_params import SamplingParams + +# This script is an offline demo for running Pixtral.
examples/offline_chat_with_tools.py
9
Python
0.071
suggestion
40
34
34
false
[Model] Add mistral function calling format to all models loaded with "mistral" format
8,515
vllm-project/vllm
71,895
Python
mgoin
patrickvonplaten
assert (prepare_object_to_dump(CustomClass( 1, "b")) == "CustomClass(a=1, b='b')") def test_request_logger_log_outputs(): """Test the new log_outputs functionality.""" # Create a mock logger to capture log calls mock_logger = MagicMock() with patch("vllm.entrypoints.logger.logger", mock_...
Please remove the commented-out code
def test_request_logger_log_outputs(): """Test the new log_outputs functionality.""" # Create a mock logger to capture log calls mock_logger = MagicMock() with patch("vllm.entrypoints.logger.logger", mock_logger): request_logger = RequestLogger(max_log_len=None) # Test basic output log...
@@ -252,4 +259,253 @@ class CustomClass: b: str assert (prepare_object_to_dump(CustomClass( - 1, 'b')) == "CustomClass(a=1, b='b')") + 1, "b")) == "CustomClass(a=1, b='b')") + + +def test_request_logger_log_outputs(): + """Test the new log_outputs functionality.""" + # Create a mock ...
tests/test_logger.py
26
Python
0.286
suggestion
36
51
51
false
feat: Add --enable-log-outputs flag for logging model generations
20,707
vllm-project/vllm
71,895
Python
DarkLight1337
mizadri
help="The file path to the SSL cert file.", ) parser.add_argument( "--ssl-ca-certs", type=optional_type(str), default=None, help="The CA certificates file.", ) parser.add_argument( "--enable-ssl-refresh", action="store_true", default=False,...
Please revert the unnecessary formatting changes
# Special case: Middleware needs append action frontend_kwargs["middleware"]["action"] = "append" frontend_kwargs["middleware"]["type"] = str if "nargs" in frontend_kwargs["middleware"]: del frontend_kwargs["middleware"]["nargs"] frontend_kwargs["middleware"]["default...
@@ -92,102 +92,128 @@ def make_arg_parser(parser: FlexibleArgumentParser) -> FlexibleArgumentParser: "--uvicorn-log-level", type=str, default="info", - choices=['debug', 'info', 'warning', 'error', 'critical', 'trace'], - help="Log level for uvicorn.") - parser.add_argument("...
vllm/entrypoints/openai/cli_args.py
26
Python
0.286
style
48
51
51
false
feat: Add --enable-log-outputs flag for logging model generations
20,707
vllm-project/vllm
71,895
Python
DarkLight1337
mizadri
extract_reasoning_content_streaming( previous_text, current_text, delta_text, previous_token_ids, ...
When `Stream=True`, this line causes an error by repeatedly accumulating the previous content.
# when only reasoning elif self.reasoning_parser: delta_message = (reasoning_parser. extract_reasoning_content_streaming( previous_text, ...
@@ -808,6 +812,10 @@ async def chat_completion_stream_generator( assert all_previous_token_ids is not None previous_texts[i] = current_text all_previous_token_ids[i] = current_token_ids + else: + # Updat...
vllm/entrypoints/openai/serving_chat.py
26
Python
0.857
suggestion
96
51
51
false
feat: Add --enable-log-outputs flag for logging model generations
20,707
vllm-project/vllm
71,895
Python
chaunceyjiang
mizadri
lora_config: LoRAConfig, model_config: Optional[PretrainedConfig] = None, ) -> LogitsProcessorWithLoRA: ret = LogitsProcessorWithLoRA(layer, lm_head.embedding_dim, lm_head.weight.dtype, lm_head.weight.device, lm_head.get_sharded_to_full_map...
Could we move this warning into `vllm/lora/models.py`? If this helper function gets used in other places this warning might not be relevant
model_config: Optional[PretrainedConfig] = None, ) -> LogitsProcessorWithLoRA: ret = LogitsProcessorWithLoRA(layer, lm_head.embedding_dim, lm_head.weight.dtype, lm_head.weight.device, lm_head.get_sharded_to_full_mapping()) ret.create_lora_w...
@@ -97,6 +98,17 @@ def replace_submodule(model: nn.Module, module_name: str, return new_module +def is_moe_model(model: nn.Module) -> bool: + """Checks if the model contains FusedMoE layers and warns the user.""" + if any(isinstance(module, FusedMoE) for module in model.modules()): + logger.warnin...
vllm/lora/utils.py
26
Python
0.714
refactor
142
51
51
false
[Misc] Qwen MoE model supports LoRA
20,932
vllm-project/vllm
71,895
Python
hmellor
jeejeelee
q_i, k_i, v_i = ( rearrange(x, "b s h d -> b h s d") for x in [q_i, k_i, v_i] ) output_i = F.scaled_dot_product_attention(q_i, k_i, v_i, dropout_p=0.0) output_i = rearrange(output_i, "b h s d -> b s h d ") outputs.append...
qq: what happens to other dimensions? does dynamism on other dimensions trigger a recompile?
context_layer = einops.rearrange( context_layer, "b s h d -> s b (h d)" ).contiguous() elif self.attn_backend == _Backend.XFORMERS: context_layer = vit_xformers_attn_wrapper(q, k, v, seqlens) output, _ = self.proj(context_layer) return output ...
@@ -462,6 +465,10 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: return x +@set_model_tag("Qwen2_5_VisionPatchMerger") +@support_torch_compile(dynamic_arg_dims={ + "x": 0,
vllm/model_executor/models/qwen2_5_vl.py
26
Python
0.143
question
92
51
51
false
[Misc][qwen2_5_vl][torch.compile] Enable `supports_torch_compile` on generic nn.Module and demonstrate speedup on Qwen Vision model
23,207
vllm-project/vllm
71,895
Python
miladm
Lucaskabela
self.use_upstream_fa = use_upstream_fa self.attn_backend, self.flash_attn_varlen_func = ( maybe_get_vit_flash_attn_backend( self.attn_backend, self.use_upstream_fa, ) ) self.is_flash_attn_backend = self.attn_backend in { ...
NOTE: We push all the compile breaking things here (such as .item/.tolist). This way, we can specify this as a custom op and compile around it
output_size=embed_dim, quant_config=quant_config, prefix=f"{prefix}.proj", disable_tp=use_data_parallel, ) self.attn_backend = attn_backend self.use_upstream_fa = use_upstream_fa self.attn_backend, self.flash_attn_varlen_func = ( ...
@@ -356,62 +359,101 @@ def forward( q = apply_rotary_pos_emb_vision(q, rotary_pos_emb) k = apply_rotary_pos_emb_vision(k, rotary_pos_emb) - if self.is_flash_attn_backend: - if self.attn_backend == _Backend.ROCM_AITER_FA: - from aiter import flash_attn_varlen_...
vllm/model_executor/models/qwen2_5_vl.py
26
Python
0.286
suggestion
143
51
51
false
[Misc][qwen2_5_vl][torch.compile] Enable `supports_torch_compile` on generic nn.Module and demonstrate speedup on Qwen Vision model
23,207
vllm-project/vllm
71,895
Python
Lucaskabela
Lucaskabela
output, "(b s) h d -> s b (h d)", b=batch_size ).contiguous() elif self.attn_backend == _Backend.TORCH_SDPA: # Execute attention entry by entry for speed & less VRAM. from vllm.platforms import current_platform if current_platform.is_rocm(): ...
Other major change here; don't use optional primitives that are difficult to trace. Instead use tensor which works here
) elif self.attn_backend == _Backend.TORCH_SDPA: # Execute attention entry by entry for speed & less VRAM. outputs = [] for i in range(1, len(cu_seqlens)): start_idx = cu_seqlens[i - 1] end_idx = cu_seqlens[i] q_i = ...
@@ -450,8 +492,8 @@ def forward( x: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: torch.Tensor, - max_seqlen: Optional[int] = None, # Only used for Flash Attention
vllm/model_executor/models/qwen2_5_vl.py
26
Python
0.5
suggestion
120
51
51
false
[Misc][qwen2_5_vl][torch.compile] Enable `supports_torch_compile` on generic nn.Module and demonstrate speedup on Qwen Vision model
23,207
vllm-project/vllm
71,895
Python
Lucaskabela
Lucaskabela
seq_len, bs, _ = qkv.shape if self.tp_size > 1: qkv = all_gather_interleave(qkv, self.qkv.hidden_size, self.tp_size) # [s, b, 3 * head * head_dim] -> 3 * [s, b, head * head_dim] q, k, v = qkv.chunk(3, dim=2) # 3 * [s, b, head * head_dim] if self.tp_size > 1:...
Is there a reason why we're doing this at top level instead of per-attention backend? We have already changed the logic here so that there's no more repeative code on deciding attention backend - it'll be just populated from `Qwen2.5VLVisionTransformer` https://github.com/vllm-project/vllm/blob/2e4fe48c370e833350ea...
_Backend.FLASH_ATTN, _Backend.ROCM_AITER_FA, } def split_qkv(self, qkv: torch.Tensor) -> tuple[torch.Tensor, ...]: # [s, b, 3 * head * head_dim] seq_len, bs, _ = qkv.shape if self.tp_size > 1: qkv = all_gather_interleave(qkv, self.qkv.hidden_size,...
@@ -366,67 +369,104 @@ def forward( qk_rotated = apply_rotary_pos_emb_vision(qk_concat, rotary_pos_emb) q, k = torch.chunk(qk_rotated, 2, dim=0) - if self.is_flash_attn_backend: - if self.attn_backend == _Backend.ROCM_AITER_FA: - from aiter import flash_attn_...
vllm/model_executor/models/qwen2_5_vl.py
26
Python
0.857
question
579
51
51
false
[Misc][qwen2_5_vl][torch.compile] Enable `supports_torch_compile` on generic nn.Module and demonstrate speedup on Qwen Vision model
23,207
vllm-project/vllm
71,895
Python
ywang96
Lucaskabela
video_token_id = hf_config.video_token_id vision_start_token_id = hf_config.vision_start_token_id spatial_merge_size = hf_config.vision_config.spatial_merge_size tokens_per_second = getattr(hf_config.vision_config, "tokens_per_second", 1.0) input_tokens_tensor = torch.tensor(inp...
Do we not need to `set_forward_context` for the DP ViT case?
image_grid_thw: list[list[int]] | torch.Tensor, video_grid_thw: list[list[int]] | torch.Tensor, second_per_grid_ts: list[float], context_len: int = 0, seq_len: int | None = None, audio_feature_lengths: torch.Tensor | None = None, use_audio_in_video: bool = False, ...
@@ -1079,8 +1130,9 @@ def _process_image_input( grid_thw_list, rope_type="rope_3d") else: - image_embeds = self.visual(pixel_values, - ...
vllm/model_executor/models/qwen2_5_vl.py
26
Python
0.357
question
60
51
51
false
[Misc][qwen2_5_vl][torch.compile] Enable `supports_torch_compile` on generic nn.Module and demonstrate speedup on Qwen Vision model
23,207
vllm-project/vllm
71,895
Python
ywang96
Lucaskabela
outputs = [] for i in range(1, len(cu_seqlens)): start_idx = cu_seqlens[i - 1] end_idx = cu_seqlens[i] q_i = q[:, start_idx:end_idx] k_i = k[:, start_idx:end_idx] v_i = v[:, start_idx:end_idx] q_i, k_...
@Lucaskabela to check: previously we had an invariant that all dynamic dimensions were actually "the same". After this PR, that is no longer the case, right? (cc @laithsakka who wanted to make use of this information) This is not a problem, just a FYI
q_i, k_i, v_i = ( einops.rearrange(x, "b s h d -> b h s d") for x in [q_i, k_i, v_i] ) output_i = F.scaled_dot_product_attention(q_i, k_i, v_i, dropout_p=0.0) output_i = einops.rearrange(output_i, "b h s d -> b s h d ") ...
@@ -440,24 +440,21 @@ def forward( context_layer, "b s h d -> s b (h d)" ).contiguous() elif self.attn_backend == _Backend.XFORMERS: - from xformers import ops as xops - from xformers.ops.fmha.attn_bias import BlockDiagonalMask - - attn_bias = Bloc...
vllm/model_executor/models/qwen2_5_vl.py
26
Python
0.857
style
254
51
51
false
[Misc][qwen2_5_vl][torch.compile] Enable `supports_torch_compile` on generic nn.Module and demonstrate speedup on Qwen Vision model
23,207
vllm-project/vllm
71,895
Python
zou3519
Lucaskabela
elif self.attn_backend == _Backend.TORCH_SDPA: # Execute attention entry by entry for speed & less VRAM. from vllm.platforms import current_platform if current_platform.is_rocm(): q = q.contiguous() k = k.contiguous() v = v.con...
Does this turn on CUDAGraphs capture too? How does that interaction work?
# Execute attention entry by entry for speed & less VRAM. outputs = [] for i in range(1, len(cu_seqlens)): start_idx = cu_seqlens[i - 1] end_idx = cu_seqlens[i] q_i = q[:, start_idx:end_idx] k_i = k[:, start_idx:end_idx]...
@@ -440,24 +440,21 @@ def forward( context_layer, "b s h d -> s b (h d)" ).contiguous() elif self.attn_backend == _Backend.XFORMERS: - from xformers import ops as xops - from xformers.ops.fmha.attn_bias import BlockDiagonalMask - - attn_bias = Bloc...
vllm/model_executor/models/qwen2_5_vl.py
26
Python
0.143
question
73
51
51
false
[Misc][qwen2_5_vl][torch.compile] Enable `supports_torch_compile` on generic nn.Module and demonstrate speedup on Qwen Vision model
23,207
vllm-project/vllm
71,895
Python
zou3519
Lucaskabela
# support decorating multiple times return cls # take care of method resolution order # make sure super().__init__ is called on the base class # other than TorchCompileWrapperWithCustomDispatcher cls.__bases__ = cls.__bases__ + (TorchCompileWrapperWithCustomDispatcher,) old_init =...
this is kind of sketchy, do you have an example? I don't know where `old_init` came from
def _verify_source_unchanged(source_info, vllm_config) -> None: from .caching import _compute_code_hash, _compute_code_hash_with_content file_contents = {} for source in source_info.inlined_sources: module = sys.modules[source.module] file = inspect.getfile(module) vllm_config.com...
@@ -228,8 +233,18 @@ def _support_torch_compile( setattr(cls, IGNORE_COMPILE_KEY, False) - def __init__(self, *, vllm_config: VllmConfig, prefix: str = "", **kwargs): - old_init(self, vllm_config=vllm_config, prefix=prefix, **kwargs) + def __init__(self, **kwargs): + # NOTE: to support mult...
vllm/compilation/decorators.py
26
Python
0.357
suggestion
88
51
51
false
[Misc][qwen2_5_vl][torch.compile] Enable `supports_torch_compile` on generic nn.Module and demonstrate speedup on Qwen Vision model
23,207
vllm-project/vllm
71,895
Python
zou3519
Lucaskabela
@overload def support_torch_compile( *, enable_if: Callable[[VllmConfig], bool] | None = None, ) -> Callable[[_T], _T]: ... @overload def support_torch_compile( *, dynamic_arg_dims: dict[str, int | list[int]] | None, ) -> Callable[[_T], _T]: ... @overload def support_torch_compile(cls: _T) -> _T: ...
This arg is used with `dynamic_arg_dims` for `Qwen2_5_VisionBlock`. This overload does not provide a `dynamic_arg_dims` arg and my type checker complains about this. Should this be merged into overload above?
def _should_ignore_torch_compile(cls) -> bool: """ Check if the class should be ignored for torch.compile. """ return getattr(cls, IGNORE_COMPILE_KEY, False) @overload def support_torch_compile( *, enable_if: Callable[[VllmConfig], bool] | None = None, ) -> Callable[[_T], _T]: ... @overload ...
@@ -73,6 +78,13 @@ def support_torch_compile( ) -> Callable[[_T], _T]: ... +@overload +def support_torch_compile( + *, + mark_unbacked_dims: dict[str, int | list[int]] | None, +) -> Callable[[_T], _T]: ...
vllm/compilation/decorators.py
26
Python
1
question
208
51
51
false
[Misc][qwen2_5_vl][torch.compile] Enable `supports_torch_compile` on generic nn.Module and demonstrate speedup on Qwen Vision model
23,207
vllm-project/vllm
71,895
Python
yanyongyu
Lucaskabela
mode 3, i.e. the backend must be either eager or inductor. Furthermore, compilation is only piecewise if splitting ops is set accordingly and use_inductor_graph_partition is off. Note that the default options for splitting ops are sufficient for piecewise compilation. """ custom_ops: list[str] =...
This config has been placed between `splitting_ops` and its docstring. And the docstring for `compile_mm_encoder` has been placed above it.
(it sees a part of the graph). The backend can not be custom for compilation mode 3, i.e. the backend must be either eager or inductor. Furthermore, compilation is only piecewise if splitting ops is set accordingly and use_inductor_graph_partition is off. Note that the default options for splitting ...
@@ -250,6 +251,13 @@ class CompilationConfig: disabled when running with Inductor: mode>=VLLM_COMPILE and use_inductor=True. Inductor generates (fused) Triton kernels for disabled custom ops.""" splitting_ops: list[str] | None = None + + """ + Provide control over whether to compile the multimodal ...
vllm/config/compilation.py
26
Python
0.5
suggestion
142
51
51
false
[Multimodal][torch.compile] Add compilation config field for turning off ViT/MM compile
28,242
vllm-project/vllm
71,895
Python
hmellor
Lucaskabela
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright 2024 The vLLM 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 # #...
This is not where this should live. This file is for the Transformers backend.
return f"{prefix}{tip}" def can_enable_torch_compile(vllm_config: "VllmConfig") -> bool: """ Callable to be passed to `@support_torch_compile`'s `enable_if` argument. Defaults to `True` but is disabled in the following situations: - The model uses dynamic rope scaling. """ text_config = ...
@@ -205,3 +205,14 @@ def can_enable_torch_compile(vllm_config: "VllmConfig") -> bool: # Dynamic rope scaling is not compatible with torch.compile rope_scaling: dict = getattr(text_config, "rope_scaling", None) or {} return rope_scaling.get("rope_type") != "dynamic" + + +def should_torch_compile_mm_vit(vl...
vllm/model_executor/models/transformers/utils.py
26
Python
0.357
suggestion
78
208
27
false
[Multimodal][torch.compile] Add compilation config field for turning off ViT/MM compile
28,242
vllm-project/vllm
71,895
Python
hmellor
Lucaskabela
IS_AITER_FOUND and _______________| cls._AITER_ENABLED -----> Check by the logic in `is_enabled()` Example: from vllm._aiter_ops import rocm_aiter_ops # Check if aiter is enabled before using operations if rocm_aiter_ops.is_enabled(): ...
Please reuse `VLLM_ROCM_USE_AITER_MOE` for this feature and not introduce another FLAG `VLLM_ROCM_USE_CK_MXFP4_MOE` . It should be dispatched automatically based on the model config.
def _rocm_aiter_rmsnorm_with_add_fp8_group_quant_fake( x: torch.Tensor, residual: torch.Tensor, weight: torch.Tensor, variance_epsilon: float, group_size: int, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: M, N = x.shape scale_shape = (M, (N + group_size - 1) // group_size) retur...
@@ -708,6 +708,7 @@ class rocm_aiter_ops: _LINEAR_ENABLED = envs.VLLM_ROCM_USE_AITER_LINEAR _RMSNORM_ENABLED = envs.VLLM_ROCM_USE_AITER_RMSNORM _FMOE_ENABLED = envs.VLLM_ROCM_USE_AITER_MOE + _CK_MXFP4_MOE = envs.VLLM_ROCM_USE_CK_MXFP4_MOE
vllm/_aiter_ops.py
26
Python
0.714
suggestion
182
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
tjtanaa
maleksan85
# See also vllm/config/profiler.py and `--profiler-config` argument VLLM_TORCH_CUDA_PROFILE: str | None = None VLLM_TORCH_PROFILER_DIR: str | None = None VLLM_TORCH_PROFILER_RECORD_SHAPES: str | None = None VLLM_TORCH_PROFILER_WITH_PROFILE_MEMORY: str | None = None VLLM_TORCH_PROFILER_DISABLE_AS...
Let use the VLLM_ROCM_USE_AITER_MOE flag. The conditions whether to use the a16w4 should be determined based in the quantization config.
VLLM_FORCE_AOT_LOAD: bool = False VLLM_USE_MEGA_AOT_ARTIFACT: bool = False VLLM_USE_TRITON_AWQ: bool = False VLLM_ALLOW_RUNTIME_LORA_UPDATING: bool = False VLLM_SKIP_P2P_CHECK: bool = False VLLM_DISABLED_KERNELS: list[str] = [] VLLM_DISABLE_PYNCCL: bool = False VLLM_USE_OINK_OPS: bool = ...
@@ -115,6 +115,7 @@ VLLM_ROCM_USE_AITER_PAGED_ATTN: bool = False VLLM_ROCM_USE_AITER_LINEAR: bool = True VLLM_ROCM_USE_AITER_MOE: bool = True + VLLM_ROCM_USE_AITER_FUSED_MOE_A16W4: bool = True
vllm/envs.py
26
Python
0.5
suggestion
136
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
tjtanaa
maleksan85
from vllm.model_executor.layers.quantization.utils.marlin_utils_fp8 import ( prepare_fp8_moe_layer_for_marlin, ) from vllm.model_executor.layers.quantization.utils.mxfp4_utils import _swizzle_mxfp4 from vllm.model_executor.layers.quantization.utils.ocp_mx_utils import ( OCP_MX_BLOCK_SIZE, OCP_MX_Scheme, ) f...
No need to add these two. Both are supported under `QuarkOCP_MX_MoEMethod`. Both wmxfp4_amxfp4 and wmxfp4_afp8 are covered under `QuarkOCP_MX_MoEMethod`.
from vllm.model_executor.layers.quantization.utils.marlin_utils_fp8 import ( prepare_fp8_moe_layer_for_marlin, ) from vllm.model_executor.layers.quantization.utils.mxfp4_utils import _swizzle_mxfp4 from vllm.model_executor.layers.quantization.utils.ocp_mx_utils import ( OCP_MX_BLOCK_SIZE, OCP_MX_Scheme, ) f...
@@ -48,7 +50,13 @@ logger = init_logger(__name__) -__all__ = ["QuarkMoEMethod", "QuarkW8A8Fp8MoEMethod", "QuarkOCP_MX_MoEMethod"] +__all__ = [ + "QuarkMoEMethod", + "QuarkW8A8Fp8MoEMethod", + "QuarkW4MXFp4MoEMethod_OSS", + "QuarkW4MXFp4MoEMethod",
vllm/model_executor/layers/quantization/quark/quark_moe.py
26
Python
0.5
suggestion
154
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
BowenBao
maleksan85
else: return ocp_mx_moe_quant_config( quant_dtype=self.input_dtype, weight_dtype=self.weight_dtype, w1_scale=layer.w13_weight_scale, w2_scale=layer.w2_weight_scale, w1_bias=layer.w13_bias, w2_bias=layer.w...
For wmxfp4_afp8, just need to add the triton kernel dispatch at here. If there are some triton kernel specific setups needed like pre-shuffling, kwargs setting etc, please do it in process_weights_after_loading.
return mxfp4_w4a8_moe_quant_config( w1_scale=layer.w13_weight_scale, w2_scale=layer.w2_weight_scale, a1_scale=layer.w13_input_scale, a2_scale=layer.w2_input_scale, w1_bias=layer.w13_bias, w2_bias=layer.w2_bias, ...
vllm/model_executor/layers/quantization/quark/quark_moe.py
26
Python
0.357
suggestion
212
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
BowenBao
maleksan85
FnSpecs("swiglu", triton_kernels.swiglu.swiglu_fn, ("alpha", "limit")), (swiglu_alpha, swiglu_limit), 2, ) intermediate_cache1 = matmul_ogs( hidden_states, w1, quant_config.w1_bias, routing_data, gather_indx=...
why is it `use_mxfp4_w4a4` in config but `a8w4` kernel
# Shape check, only check non-mxfp4 assert hidden_states.shape[-1] == w1.shape[-2] assert w2.shape[-1] == w1.shape[1] E, _, N = w1.shape if global_num_experts == -1: global_num_experts = E gammas = routing_data.gate_scal if routing_data else None from aiter.ops.triton.moe_op_gemm...
@@ -299,6 +299,182 @@ def triton_kernel_fused_experts( return output_tensor +def triton_kernel_moe_oss_forward( + hidden_states: torch.Tensor, + w1, # Tensor or triton_kernels.Tensor + w2, # Tensor or triton_kernels.Tensor + gating_output: torch.Tensor, + topk: int, + renormalize: bool, + ...
vllm/model_executor/layers/fused_moe/gpt_oss_triton_kernels_moe.py
26
Python
0.571
suggestion
54
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
BowenBao
maleksan85
x, layer.w13_weight, layer.w2_weight, topk_weights=topk_weights, topk_ids=topk_ids, activation=layer.activation, quant_config=self.moe_quant_config, expert_map=layer.expert_map, ) ...
I think this can be merged with `QuarkOCP_MX_MoEMethod`. But probably it's okay to keep separate in this PR. There will be a larger refactor to abstract out kernel dependent logic for `process_weights_after_loading` and align with modular kernel refactors. That will do the merge anyways.
layer.w2_weight, topk_weights=topk_weights, topk_ids=topk_ids, activation=layer.activation, quant_config=self.moe_quant_config, expert_map=layer.expert_map, ) else: from vllm.model_executor.la...
@@ -1031,3 +1047,133 @@ def apply( expert_map=layer.expert_map, quant_config=self.moe_quant_config, ) + + +class QuarkOCP_MX_MoEMethod_OSS(QuarkOCP_MX_MoEMethod):
vllm/model_executor/layers/quantization/quark/quark_moe.py
26
Python
0.786
refactor
289
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
BowenBao
maleksan85
fused_activation=act, ) intermediate_cache3 = matmul_ogs( intermediate_cache1, w2, quant_config.w2_bias, routing_data, scatter_indx=scatter_indx, precision_config=quant_config.w2_precision, gammas=None if app...
ah i see how input scale is passed, through within w1_precision. I think by using `mxfp4_w4a8_moe_quant_config`, we can use `quant_config.a1_scale` here instead
assert quant_config.w2_precision is not None, ( "w2_precision in quant config can't be None" ) hidden_states = downcast_to_static_fp8( hidden_states, quant_config.w1_precision.flex_ctx.lhs_data.scale ) intermediate_cache1 = moe_gemm_a8w4( hidden_states, w1.storage.d...
@@ -304,6 +304,182 @@ def triton_kernel_fused_experts( return output_tensor +def triton_kernel_moe_oss_forward( + hidden_states: torch.Tensor, + w1, # Tensor or triton_kernels.Tensor + w2, # Tensor or triton_kernels.Tensor + gating_output: torch.Tensor, + topk: int, + renormalize: bool, + ...
vllm/model_executor/layers/fused_moe/gpt_oss_triton_kernels_moe.py
26
Python
0.714
suggestion
161
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
BowenBao
maleksan85
# Note: get_quant_method will look at the layer's local_num_experts # for heuristic purposes, so it must be initialized first. self.quant_method: FusedMoEMethodBase = _get_quant_method() if not self.moe_config.is_act_and_mul and not current_platform.is_cuda_alike(): raise No...
fyi: no action for this pr, i have a PR #34285 refactoring how hidden_size is padded. we can land this first and I'll pull in the update.
# Note: get_quant_method will look at the layer's local_num_experts # for heuristic purposes, so it must be initialized first. self.quant_method: FusedMoEMethodBase = _get_quant_method() if not self.moe_config.is_act_and_mul and not current_platform.is_cuda_alike(): raise N...
@@ -609,6 +611,7 @@ def _get_quant_method() -> FusedMoEMethodBase: moe_quant_params = { "num_experts": self.local_num_experts, "hidden_size": hidden_size, + "unpadded_hidden_size": unpadded_hidden_size,
vllm/model_executor/layers/fused_moe/layer.py
26
Python
0.5
refactor
137
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
BowenBao
maleksan85
elif ( self.quant_config.get_name() == "quark" and self.model_type == "gpt_oss" ): # When self._is_mxfp4 is true, model_dtype must be gpt_oss expert_data = param.data[expert_id] if "input_scale" in weight_name: a...
are these needed? I thought Xuebin's earlier PR that enables w4a8 emulation should support all the necessary scales loading?
quant_method_name = self.quant_method.__class__.__name__ global_expert_id = expert_id expert_id = self._map_global_expert_id_to_local_expert_id(global_expert_id) use_global_sf = ( getattr(self.quant_method, "use_global_sf", False) and "input_scale" in weight_nam...
@@ -1060,16 +1063,43 @@ def weight_loader( expert_id: int, return_success: bool = False, ) -> bool | None: - if self.quant_config and self.quant_config.get_name() == "mxfp4": - # (FIXME) for gpt-oss all experts are combined - if "bias" in weight_name: - ...
vllm/model_executor/layers/fused_moe/layer.py
26
Python
0.5
question
124
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
BowenBao
maleksan85
layer_quant_config = quant_config._find_matched_config(layer_name, module) if layer_quant_config.get("output_tensors") or layer_quant_config.get("bias"): raise NotImplementedError( "Currently, Quark models with " "output_tensors and bias " "qu...
best to avoid conditioning on model type, ideally something like `if self.ocp_mx_scheme == "w_mxfp4_a_fp8" and not emulate:`
if layer_quant_config.get("output_tensors") or layer_quant_config.get("bias"): raise NotImplementedError( "Currently, Quark models with " "output_tensors and bias " "quantized are not supported" ) weight_config = layer_quant_confi...
@@ -71,14 +77,31 @@ def get_moe_method( "output_tensors and bias " "quantized are not supported" ) + + emulate = not current_platform.supports_mx() or not ( + rocm_aiter_ops.is_fused_moe_enabled() + ) weight_config = layer_quant_config.get...
vllm/model_executor/layers/quantization/quark/quark_moe.py
26
Python
1
suggestion
124
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
BowenBao
maleksan85
layer.w2_input_scale = torch.nn.Parameter( layer.w2_input_scale.max().to(torch.float32), requires_grad=False ) from triton_kernels.numerics import InFlexData lhs_data13 = InFlexData(scale=layer.w13_input_scale) lhs_data2 = InFlexData(scale=la...
as commented elsewhere, suggest return `mxfp4_w4a8_moe_quant_config`
) from triton_kernels.numerics import InFlexData lhs_data13 = InFlexData(scale=layer.w13_input_scale) lhs_data2 = InFlexData(scale=layer.w2_input_scale) self.w13_precision_config = PrecisionConfig( weight_scale=w13_scale, fle...
@@ -1031,3 +1047,133 @@ def apply( expert_map=layer.expert_map, quant_config=self.moe_quant_config, ) + + +class QuarkOCP_MX_MoEMethod_OSS(QuarkOCP_MX_MoEMethod): + def __init__( + self, + weight_config: dict[str, Any], + input_config: dict[str, Any...
vllm/model_executor/layers/quantization/quark/quark_moe.py
26
Python
0.571
suggestion
68
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
BowenBao
maleksan85
hidden_states, w1, quant_config.w1_bias, routing_data, gather_indx=gather_indx, precision_config=quant_config.w1_precision, gammas=gammas if apply_router_weight_on_input else None, fused_activation=act, y=intermediate_cache, ) matmul_ogs( ...
can we unify this with [`triton_kernel_moe_forward`](https://github.com/ROCm/vllm/blob/0b21db603eae8077c9a25ce00cb2af922fae19a9/vllm/model_executor/layers/fused_moe/gpt_oss_triton_kernels_moe.py#L169)? Currently for this function, we always have `quant_config.use_mxfp4_w4a8 = True`; but the w4a16 section here would ac...
apply_router_weight_on_input: bool = False, global_num_experts: int = -1, expert_map: torch.Tensor | None = None, intermediate_cache: torch.Tensor | None = None, a1q_scale: torch.Tensor | None = None, ) -> torch.Tensor: """Triton implementation of fused expert computation using OAI kernels.""" ...
@@ -304,6 +304,182 @@ def triton_kernel_fused_experts( return output_tensor +def triton_kernel_moe_oss_forward(
vllm/model_executor/layers/fused_moe/gpt_oss_triton_kernels_moe.py
26
Python
0.857
bug
421
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
Rohan138
maleksan85
routing_data, gather_idx, scatter_idx = aiter_routing( gating_output, topk, sm_first=not renormalize ) return triton_kernel_fused_oss_experts( None, hidden_states, w1, w2, routing_data, gather_idx, scatter_idx, activation=a...
Same comment here, can we reuse [triton_kernel_fused_experts](https://github.com/ROCm/vllm/blob/0b21db603eae8077c9a25ce00cb2af922fae19a9/vllm/model_executor/layers/fused_moe/gpt_oss_triton_kernels_moe.py#L206) and add an `elif quant_config.use_mxfp4_w4a8 and rocm_aiter_ops.is_enabled()` for aiter triton with w4a8 moe?
else FusedActivation( FnSpecs("swiglu", triton_kernels.swiglu.swiglu_fn, ("alpha", "limit")), (swiglu_alpha, swiglu_limit), 2, ) ) gammas = routing_data.gate_scal if routing_data else None matmul_ogs( hidden_states, w1, quant_confi...
@@ -304,6 +304,182 @@ def triton_kernel_fused_experts( return output_tensor +def triton_kernel_moe_oss_forward( + hidden_states: torch.Tensor, + w1, # Tensor or triton_kernels.Tensor + w2, # Tensor or triton_kernels.Tensor + gating_output: torch.Tensor, + topk: int, + renormalize: bool, + ...
vllm/model_executor/layers/fused_moe/gpt_oss_triton_kernels_moe.py
26
Python
0.857
question
319
51
51
false
[ROCm][Quantization] GPT OSS Upstream MoE wmxfp4_afp8 with static scales
30,357
vllm-project/vllm
71,895
Python
Rohan138
maleksan85
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import subprocess import sys import regex as re # --------------------------------------------------------------------------- # # Regex: match `torch.cuda.xxx` but allow `torch.accelerator.xxx` # ---------------...
The hook doesn't need to work out which files it should run on, pre-commit already does that for us. Please look at `tools/pre_commit/check_pickle_imports.py` to see how this should be done
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import sys import regex as re # --------------------------------------------------------------------------- # # Regex: match `torch.cuda.xxx` but allow `torch.accelerator.xxx` # ---------------------------------...
tools/pre_commit/check_torch_cuda.py
1
Python
0.714
suggestion
190
26
26
false
[Hardware] Replace `torch.cuda.empty_cache` with `torch.accelerator.empty_cache`
30,681
vllm-project/vllm
71,895
Python
hmellor
jikunshang
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import sys import regex as re # --------------------------------------------------------------------------- # # Regex: match `torch.cuda.xxx` but allow `torch.accelerator.xxx` # ---------------------------------...
```suggestion with open(path, encoding="utf-8") as f: content = f.read() for match in re.finditer(_TORCH_CUDA_RE, content, re.MULTILINE): # Calculate line number from match position line_num = content[: match.start() + 1].count("\n") + 1 print( f"{path}:{line_num}: " ...
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import sys import regex as re # --------------------------------------------------------------------------- # # Regex: match `torch.cuda.xxx` but allow `torch.accelerator.xxx` # ---------------------------------...
@@ -0,0 +1,39 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +import sys + +import regex as re + +# --------------------------------------------------------------------------- # +# Regex: match `torch.cuda.xxx` but allow `torch.accelerator.xxx` +# -------...
tools/pre_commit/check_torch_cuda.py
25
Python
1
suggestion
440
40
44
false
[Hardware] Replace `torch.cuda.empty_cache` with `torch.accelerator.empty_cache`
30,681
vllm-project/vllm
71,895
Python
hmellor
jikunshang
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import sys import regex as re # --------------------------------------------------------------------------- # # Regex: match `torch.cuda.xxx` but allow `torch.accelerator.xxx` # ---------------------------------...
```suggestion _TORCH_CUDA_RE = r"\btorch\.cuda\.empty_cache\b" ```
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import sys import regex as re # --------------------------------------------------------------------------- # # Regex: match `torch.cuda.xxx` but allow `torch.accelerator.xxx` # ---------------------------------...
@@ -0,0 +1,39 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +import sys + +import regex as re + +# --------------------------------------------------------------------------- # +# Regex: match `torch.cuda.xxx` but allow `torch.accelerator.xxx` +# -------...
tools/pre_commit/check_torch_cuda.py
10
Python
0.857
performance
66
35
35
false
[Hardware] Replace `torch.cuda.empty_cache` with `torch.accelerator.empty_cache`
30,681
vllm-project/vllm
71,895
Python
hmellor
jikunshang
import regex as re # --------------------------------------------------------------------------- # # Regex: match `torch.cuda.xxx` but allow `torch.accelerator.xxx` # --------------------------------------------------------------------------- # _TORCH_CUDA_RE = r"\btorch\.cuda\.empty_cache\b" ALLOWED_FILES = {"vllm/...
```suggestion with open(path, encoding="utf-8") as f: content = f.read() return_code = 0 for match in re.finditer(_TORCH_CUDA_RE, content, re.MULTILINE): # Calculate line number from match position line_num = content[: match.start() + 1].count("\n") + 1 print( f"{...
import regex as re # --------------------------------------------------------------------------- # # Regex: match `torch.cuda.xxx` but allow `torch.accelerator.xxx` # --------------------------------------------------------------------------- # _TORCH_CUDA_PATTERNS = [ r"\btorch\.cuda\.empty_cache\b", ] ALLOWED_F...
@@ -0,0 +1,41 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +import sys + +import regex as re + +# --------------------------------------------------------------------------- # +# Regex: match `torch.cuda.xxx` but allow `torch.accelerator.xxx` +# -------...
tools/pre_commit/check_torch_cuda.py
26
Python
1
suggestion
490
38
40
false
[Hardware] Replace `torch.cuda.empty_cache` with `torch.accelerator.empty_cache`
30,681
vllm-project/vllm
71,895
Python
hmellor
jikunshang
if isinstance(pg, ProcessGroup): world_size = torch.distributed.get_world_size(group=pg) else: world_size = pg.world_size if world_size == 1: return 1 # Build node assignment map node_assignment = [0] * world_size # rank -> node_id next_node_id = 0 for current_ran...
This block was not confitional on `if not current_platform.is_cpu()` before? ```suggestion try: torch._C._host_emptyCache() except AttributeError: logger.warning("torch._C._host_emptyCache() only available in Pytorch >=2.5") ```
torch.distributed.destroy_process_group() def cleanup_dist_env_and_memory(shutdown_ray: bool = False): # Reset environment variable cache envs.disable_envs_cache() # Ensure all objects are not frozen before cleanup gc.unfreeze() destroy_model_parallel() destroy_distributed_environment...
@@ -1732,14 +1732,14 @@ def cleanup_dist_env_and_memory(shutdown_ray: bool = False): gc.collect() from vllm.platforms import current_platform - empty_cache = current_platform.empty_cache - if empty_cache is not None: - empty_cache() - try: - if not current_platform.is_cpu(): + if n...
vllm/distributed/parallel_state.py
26
Python
1
performance
253
28
51
false
[Hardware] Replace `torch.cuda.empty_cache` with `torch.accelerator.empty_cache`
30,681
vllm-project/vllm
71,895
Python
hmellor
jikunshang
Args: pg: The process group to analyze Returns: int: The total number of nodes """ if isinstance(pg, ProcessGroup): world_size = torch.distributed.get_world_size(group=pg) else: world_size = pg.world_size if world_size == 1: return 1 # Build node as...
If the call is no longer CUDA specific does it need to be guarded? ```suggestion torch.accelerator.empty_cache() ```
global _WORLD, _NODE_COUNT if _WORLD: _WORLD.destroy() _WORLD = None _NODE_COUNT = None if torch.distributed.is_initialized(): torch.distributed.destroy_process_group() def cleanup_dist_env_and_memory(shutdown_ray: bool = False): # Reset environment variable cache envs.disa...
@@ -1732,14 +1732,14 @@ def cleanup_dist_env_and_memory(shutdown_ray: bool = False): gc.collect() from vllm.platforms import current_platform - empty_cache = current_platform.empty_cache - if empty_cache is not None: - empty_cache() - try: - if not current_platform.is_cpu(): + if n...
vllm/distributed/parallel_state.py
26
Python
1
performance
121
34
51
false
[Hardware] Replace `torch.cuda.empty_cache` with `torch.accelerator.empty_cache`
30,681
vllm-project/vllm
71,895
Python
hmellor
jikunshang
if isinstance(pg, ProcessGroup): world_size = torch.distributed.get_world_size(group=pg) else: world_size = pg.world_size if world_size == 1: return 1 # Build node assignment map node_assignment = [0] * world_size # rank -> node_id next_node_id = 0 for current_ran...
@hmellor before code logic is: ``` call empty_cache for all platform (if possible, actually do nothing on cpu) then for non-cpu platform, call torch._C._host_emptyCache() ``` after: ``` for non-cpu platform, call empty_cache then call torch._C._host_emptyCache() (do nothing here for cpu platform) ``` I think...
torch.distributed.destroy_process_group() def cleanup_dist_env_and_memory(shutdown_ray: bool = False): # Reset environment variable cache envs.disable_envs_cache() # Ensure all objects are not frozen before cleanup gc.unfreeze() destroy_model_parallel() destroy_distributed_environment...
@@ -1732,14 +1732,14 @@ def cleanup_dist_env_and_memory(shutdown_ray: bool = False): gc.collect() from vllm.platforms import current_platform - empty_cache = current_platform.empty_cache - if empty_cache is not None: - empty_cache() - try: - if not current_platform.is_cpu(): + if n...
vllm/distributed/parallel_state.py
26
Python
0.929
performance
354
28
51
false
[Hardware] Replace `torch.cuda.empty_cache` with `torch.accelerator.empty_cache`
30,681
vllm-project/vllm
71,895
Python
jikunshang
jikunshang
self.quant_config = quant_config self.vocab_size = config.vocab_size if get_pp_group().is_first_rank or ( config.tie_word_embeddings and get_pp_group().is_last_rank ): self.embed_tokens = VocabParallelEmbedding( self.vocab_size, c...
This is needed to avoid a recompile (discovered via tlparse)
config = vllm_config.model_config.hf_config quant_config = vllm_config.quant_config self.config = config self.quant_config = quant_config self.vocab_size = config.vocab_size if get_pp_group().is_first_rank or ( config.tie_word_embeddings and get_pp_group()....
@@ -407,6 +407,9 @@ def __init__( ) def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: + # Need explicit mark here to avoid recompile from 0/1 spec + # since VocabEmbedding uses a different torch.compile decorator + torch._dynamo.decorators.mark_unbacked(input_ids, ...
vllm/model_executor/models/llama.py
26
Python
0.357
suggestion
60
51
51
false
[Misc][LLaMa4] Compile LLaMa Vision Encoder
30,709
vllm-project/vllm
71,895
Python
Lucaskabela
Lucaskabela
if modality.startswith("image"): return "<|image|>" raise ValueError("Only image modality is supported") def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super().__init__() config = vllm_config.model_config.hf_config quant_config = vllm_config.q...
I think we try to avoid lazy import, it can be moved at the top with others
"gate_up_proj": ["gate_proj", "up_proj"], } supports_encoder_tp_data = True @classmethod def get_placeholder_str(cls, modality: str, i: int) -> str | None: if modality.startswith("image"): return "<|image|>" raise ValueError("Only image modality is supported") ...
@@ -762,18 +769,28 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): multimodal_config = vllm_config.model_config.multimodal_config self.use_data_parallel = multimodal_config.mm_encoder_tp_mode == "data" + self.vllm_config = vllm_config self.config = config ...
vllm/model_executor/models/mllama4.py
26
Python
0.357
suggestion
75
51
51
false
[Misc][LLaMa4] Compile LLaMa Vision Encoder
30,709
vllm-project/vllm
71,895
Python
jeremyteboul
Lucaskabela