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
kernel_size = config.patch_size if isinstance(kernel_size, int): kernel_size = (kernel_size, kernel_size) self.unfold = torch.nn.Unfold(kernel_size=kernel_size, stride=config.patch_size) self.linear = ColumnParallelLinear( input_size=config.num_channels * kernel_s...
interesting, are we saying we can not use image_flattened ?
use_data_parallel: bool = False, ): super().__init__() kernel_size = config.patch_size if isinstance(kernel_size, int): kernel_size = (kernel_size, kernel_size) self.unfold = torch.nn.Unfold(kernel_size=kernel_size, stride=config.patch_size) self.linear = ...
@@ -456,6 +459,9 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return hidden_states +@support_torch_compile( + dynamic_arg_dims={"images_flattened": 0}, enable_if=should_torch_compile_mm_vit
vllm/model_executor/models/mllama4.py
26
Python
0.357
question
60
51
51
false
[Misc][LLaMa4] Compile LLaMa Vision Encoder
30,709
vllm-project/vllm
71,895
Python
jeremyteboul
Lucaskabela
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.compilation.counter import compilation_counter from vllm.config import VllmConfig from vllm.config.compilation import CompilationMode from vllm.platforms import current_platform def test...
nit: the TODO you left below is quite clear already
"mode": CompilationMode.VLLM_COMPILE, "compile_mm_encoder": False, }, ) as _, ): pass # forked needed to workaround https://github.com/vllm-project/vllm/issues/21073 # Requires Cuda and 8 gpus as well @pytest.mark.forked @pytest.mark.skip(reason="Skippin...
@@ -71,3 +72,44 @@ def test_qwen2_5_vl_no_vit_compilation(vllm_runner, monkeypatch): ) as _, ): pass + + +# forked needed to workaround https://github.com/vllm-project/vllm/issues/21073 +@pytest.mark.forked +@pytest.mark.skipif(not current_platform.is_cuda(), reason="Skip if not cuda") +@pytest.m...
tests/compile/fullgraph/test_multimodal_compile.py
26
Python
0.143
nitpick
51
74
44
false
[Misc][LLaMa4] Compile LLaMa Vision Encoder
30,709
vllm-project/vllm
71,895
Python
NickLucche
Lucaskabela
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pytest from vllm.compilation.counter import compilation_counter from vllm.config import VllmConfig from vllm.config.compilation import CompilationMode from vllm.platforms import current_platform def test...
This test requires some notable resources for an optional feature, have you checked how this is interacting with CI @Lucaskabela ? I would probably separate this from the rest of the fullgraph tests that are run on CI, and either add a new job entry with `num_gpus: 8` in test-pipeline or skip this on CI altogether. ...
@pytest.mark.forked @pytest.mark.skip(reason="Skipping due to CI resource constraints") def test_mllama4_vit_compilation(vllm_runner, monkeypatch): """Test that Mllama4 vision submodules are compiled. This test verifies that the 2 vision submodules (Llama4VisionEncoder, Llama4VisionPixelShuffleMLP) are pro...
@@ -71,3 +72,44 @@ def test_qwen2_5_vl_no_vit_compilation(vllm_runner, monkeypatch): ) as _, ): pass + + +# forked needed to workaround https://github.com/vllm-project/vllm/issues/21073 +@pytest.mark.forked +@pytest.mark.skipif(not current_platform.is_cuda(), reason="Skip if not cuda") +@pytest.m...
tests/compile/fullgraph/test_multimodal_compile.py
26
Python
0.857
question
380
74
34
false
[Misc][LLaMa4] Compile LLaMa Vision Encoder
30,709
vllm-project/vllm
71,895
Python
NickLucche
Lucaskabela
q, k, v = (einops.rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v]) output = flash_attn_varlen_func( q, k, v, cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens, max_seqlen_q=max_seqlen, max_seqlen_k=max_seqlen, dropout_p=0.0, causal=F...
needs to match the other api (needs = None)
q, k, v = (einops.rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v]) output = flash_attn_varlen_func( q, k, v, cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens, max_seqlen_q=max_seqlen, max_seqlen_k=max_seqlen, dropout_p=0.0, causal=F...
@@ -72,9 +72,9 @@ def flash_attn_maxseqlen_wrapper_fake( batch_size: int, is_rocm_aiter: bool, fa_version: int | None, - scale: float | None, - cu_seqlens: torch.Tensor | None, - max_seqlen: torch.Tensor | None, + scale: float | None = None,
vllm/v1/attention/ops/vit_attn_wrappers.py
26
Python
0.071
suggestion
43
51
51
false
[Misc][LLaMa4] Compile LLaMa Vision Encoder
30,709
vllm-project/vllm
71,895
Python
Lucaskabela
Lucaskabela
# Fully Connected hidden_states, residual = self.post_attention_layernorm(hidden_states, residual) hidden_states = self.mlp(hidden_states) return hidden_states, residual def get_quant_config(self, vllm_config: VllmConfig) -> QuantizationConfig | None: """Get quantization co...
Wait so this applies to all llama models now? We're always marking `input_ids` as unbacked?
# Fully Connected hidden_states, residual = self.post_attention_layernorm(hidden_states, residual) hidden_states = self.mlp(hidden_states) return hidden_states, residual def get_quant_config(self, vllm_config: VllmConfig) -> QuantizationConfig | None: """Get quantization co...
@@ -369,7 +369,9 @@ def llama_model_invariants( torch._check(positions.size()[0] == input_ids.size()[0]) -@support_torch_compile(shape_invariants=llama_model_invariants) +@support_torch_compile( + mark_unbacked_dims={"input_ids": 0}, shape_invariants=llama_model_invariants +)
vllm/model_executor/models/llama.py
26
Python
0.357
question
91
51
51
false
[Misc][LLaMa4] Compile LLaMa Vision Encoder
30,709
vllm-project/vllm
71,895
Python
ProExpertProg
Lucaskabela
) with patch.object(GraphPickler, "reducer_override", _graph_reducer_override): state["graph_module"] = GraphPickler.dumps( state["graph_module"], Options(ops_filter=None) ) state["example_inputs"] = GraphPickler.dumps(state["example_inputs"]) ...
I'm trying to get a high-level overview of what is going on. @zhxchen17 @Lucaskabela. Are we saying that aot_compile now works on image encoders? And that we were missing serialization of part of the backend?
) with patch.object(GraphPickler, "reducer_override", _graph_reducer_override): state["graph_module"] = GraphPickler.dumps( state["graph_module"], Options(ops_filter=None) ) state["example_inputs"] = GraphPickler.dumps(state["example_inputs"]) ...
@@ -105,7 +108,10 @@ def deserialize_compile_artifacts(cls, data: bytes) -> "VllmSerializableFunction fake_mode = FakeTensorMode(shape_env=ShapeEnv()) state["graph_module"] = GraphPickler.loads(state["graph_module"], fake_mode) state["example_inputs"] = GraphPickler.loads(state["example_input...
vllm/compilation/caching.py
26
Python
0.571
question
209
51
51
false
[Bugfix][torch2.10] Fix test_qwen2_5_vl_compilation with 2.10 RC
30,822
vllm-project/vllm
71,895
Python
zou3519
Lucaskabela
if engine_idx not in self.per_engine_stat_loggers: logger.warning("Unexpected engine_idx: %d", engine_idx) return self.per_engine_stat_loggers[engine_idx].record( scheduler_stats, iteration_stats, mm_cache_stats=mm_cache_stats, engi...
Small nit. It would be better for consistency if the suffix of the class is `Prom` or `Prometheus` but not both. It seems to be `Prom` but line above is using `Prometheus` for `KVConnectorPrometheus`? Personally, I'd prefer `Prometheus` for clarity when reading the code.
if engine_idx not in self.per_engine_stat_loggers: logger.warning("Unexpected engine_idx: %d", engine_idx) return self.per_engine_stat_loggers[engine_idx].record( scheduler_stats, iteration_stats, mm_cache_stats=mm_cache_stats, engi...
@@ -390,6 +390,7 @@ class PrometheusStatLogger(AggregateStatLoggerBase): _histogram_cls = Histogram _spec_decoding_cls = SpecDecodingProm _kv_connector_cls = KVConnectorPrometheus + _perf_metrics_cls = PerfMetricsProm
vllm/v1/metrics/loggers.py
26
Python
0.786
suggestion
274
51
51
false
[Metrics] Add Prometheus counters for Model FLOPs Utilization (MFU)
30,950
vllm-project/vllm
71,895
Python
hickeyma
markmc
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Analytic flops/memory estimation module for transformer components, to help derive MFU (Model Flops Utilization) stats for a running model. """ import json import time from abc import ABC, abstractmethod fro...
This looks like its a duplicate of `make_per_engine()` in `vllm/v1/spec_decode/metrics.py`. If so, do you mind making it a utility function? Also, suggestions on naming to improve clarity as follows: - `make_per_engine` --> `create_counter_per_engine` - `per_engine_labelvalues` --> `per_engine_label_values`
) self.counter_write_bytes = make_per_engine( counter_write_bytes, per_engine_labelvalues ) def observe(self, perf_stats: PerfStats, engine_idx: int = 0): if not ( perf_stats.num_flops_per_gpu or perf_stats.num_read_bytes_per_gpu or pe...
@@ -1225,6 +1226,87 @@ def log(self, log_fn=logger.info, log_prefix: str = "") -> None: self.reset() +#### Prometheus Integration #### + + +class PerfMetricsProm: + """Record performance metrics in Prometheus. + + Average TFLOPS (tera floating-point operations per second) can be + calculated using...
vllm/v1/metrics/perf.py
26
Python
0.857
refactor
312
1,253
45
false
[Metrics] Add Prometheus counters for Model FLOPs Utilization (MFU)
30,950
vllm-project/vllm
71,895
Python
hickeyma
markmc
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import ast import logging from pathlib import Path from typing import Literal logger = logging.getLogger("mkdocs") ROOT_DIR = Path(__file__).parent.parent.parent.parent DOCS_DIR = ROOT_DIR / "docs" GENERATED_MET...
```suggestion {"path": "vllm/v1/metrics/perf.py", "output": "perf.inc.md"}, ```
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import ast import logging from pathlib import Path from typing import Literal logger = logging.getLogger("mkdocs") ROOT_DIR = Path(__file__).parent.parent.parent.parent DOCS_DIR = ROOT_DIR / "docs" GENERATED_MET...
@@ -22,6 +22,7 @@ "path": "vllm/distributed/kv_transfer/kv_connector/v1/nixl_connector.py", "output": "nixl_connector.inc.md", }, + {"path": "vllm/v1/metrics/perf.py", "output": "perf.md"},
docs/mkdocs/hooks/generate_metrics.py
25
Python
0.857
suggestion
83
50
50
false
[Metrics] Add Prometheus counters for Model FLOPs Utilization (MFU)
30,950
vllm-project/vllm
71,895
Python
hmellor
markmc
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import functools from collections.abc import Callable from typing import Any, ParamSpec, TypeVar from torch import fx as fx from vllm import envs from vllm._aiter_ops import rocm_aiter_ops from vllm.config impor...
Renamed to `RocmAiterRMSNormQuantFusionPass` for clarity
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import functools from collections.abc import Callable from typing import Any, ParamSpec, TypeVar from torch import fx as fx from vllm import envs from vllm._aiter_ops import rocm_aiter_ops from vllm.config impor...
@@ -18,8 +18,9 @@ if rocm_aiter_ops.is_enabled(): from vllm.compilation.rocm_aiter_fusion import ( - RocmAiterRMSNormFusionPass, + RocmAiterRMSNormQuantFusionPass,
vllm/compilation/pass_manager.py
21
Python
0.571
suggestion
56
46
46
false
Use aiter triton fused_add_rmsnorm_pad for gpt-oss
30,976
vllm-project/vllm
71,895
Python
Rohan138
Rohan138
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch import torch._inductor.pattern_matcher as pm from torch import fx from torch._inductor.pattern_matcher import PatternMatcherPass from torch._ops import OpOverload import vllm.model_executor.layers.q...
This is currently hardcoded for the gpt-oss pad i.e. pad(2880, 256) = 2880 + 192 = 3072. I can generalize this in a follow up, possibly in #32307 which will switch MI300 padding from 256 (back) to 128.
AiterSiluMulFp8GroupQuantPattern(quant_op).register(self.patterns) self.dump_patterns(config, self.patterns) @VllmInductorPass.time_and_log def __call__(self, graph: torch.fx.Graph) -> None: self.matched_count = self.patterns.apply(graph) logger.debug("Replaced %s patterns"...
@@ -399,3 +399,72 @@ def uuid(self) -> str: AiterSiluMulFp8GroupQuantPattern, ] return VllmInductorPass.hash_source(self, *fusion_patterns) + + +class AddAiterRMSNormPadPattern: + """ + This pattern replaces aiter_rmsnorm_with_add & a pad op with a aiter_triton_add_rmsnorm_pad op. +...
vllm/compilation/rocm_aiter_fusion.py
26
Python
0.357
suggestion
205
402
51
false
Use aiter triton fused_add_rmsnorm_pad for gpt-oss
30,976
vllm-project/vllm
71,895
Python
Rohan138
Rohan138
# Set the current vllm config to allow tracing CustomOp instances with set_current_vllm_config(config, check_compile=False): if self.pass_config.eliminate_noops: self.passes += [NoOpEliminationPass(config)] if self.pass_config.enable_sp: self.pass...
Let's add a flag here (can be enabled by default in optimization level 1+)
# Set the current vllm config to allow tracing CustomOp instances with set_current_vllm_config(config, check_compile=False): if self.pass_config.eliminate_noops: self.passes += [NoOpEliminationPass(config)] if self.pass_config.enable_sp: self.pas...
@@ -123,13 +124,16 @@ def configure(self, config: VllmConfig) -> None: self.passes += [RMSNormQuantFusionPass(config)] if rocm_aiter_ops.is_enabled(): self.passes += [ - RocmAiterRMSNormFusionPass(config), + RocmAiterRM...
vllm/compilation/pass_manager.py
26
Python
0.143
suggestion
74
51
51
false
Use aiter triton fused_add_rmsnorm_pad for gpt-oss
30,976
vllm-project/vllm
71,895
Python
ProExpertProg
Rohan138
self.experts_per_token = config.num_experts_per_tok self.world_size = dist.get_world_size() if dist.is_initialized() else 1 self.router = torch.nn.Linear(config.hidden_size, config.num_local_experts) assert config.intermediate_size % self.world_size == 0 self.experts = FusedMoE( ...
Instead of changing the model definition, the transformation should just transform `rms -> gemm -> pad` into `rms+pad -> gemm`. Also cc @tjtanaa could we unify this path in general so that we can call `self.router` on ROCm as well?
self.experts_per_token = config.num_experts_per_tok self.world_size = dist.get_world_size() if dist.is_initialized() else 1 self.router = torch.nn.Linear(config.hidden_size, config.num_local_experts) assert config.intermediate_size % self.world_size == 0 self.experts = FusedMoE( ...
@@ -182,12 +182,21 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: x = sequence_parallel_chunk(x) if current_platform.is_rocm(): + # Pad before router GEMM to fuse with preceding aiter_rmsnorm_with_add
vllm/model_executor/models/gpt_oss.py
26
Python
0.786
question
232
51
51
false
Use aiter triton fused_add_rmsnorm_pad for gpt-oss
30,976
vllm-project/vllm
71,895
Python
ProExpertProg
Rohan138
from vllm.config import ( CompilationConfig, CompilationMode, ModelConfig, PassConfig, VllmConfig, ) from vllm.model_executor.layers.layernorm import RMSNorm from vllm.model_executor.layers.utils import rocm_unquantized_gemm from .backend import TestBackend class TestModel(torch.nn.Module): d...
Let's replicate a few layers here to simulate residual reuse, as that can sometimes cause matching bugs.
CompilationConfig, CompilationMode, ModelConfig, PassConfig, VllmConfig, ) from vllm.model_executor.layers.layernorm import RMSNorm from vllm.model_executor.layers.utils import rocm_unquantized_gemm from .backend import TestBackend class TestModel(torch.nn.Module): def __init__( self,...
@@ -0,0 +1,112 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + + +import pytest +import torch + +import vllm.config +from vllm._aiter_ops import is_aiter_found_and_supported, rocm_aiter_ops +from vllm.compilation.noop_elimination import NoOpEliminationPa...
tests/compile/test_fuse_act_padding.py
26
Python
0.786
bug
104
51
51
false
Use aiter triton fused_add_rmsnorm_pad for gpt-oss
30,976
vllm-project/vllm
71,895
Python
ProExpertProg
Rohan138
# disables it # - No preference: auto-disable for unsupported features (e.g. kv connector) # - Explicit disable (--disable-kv-cache-manager): always respect it need_disable_hybrid_kv_cache_manager = False # logger should only print warning message for hybrid models. As we ...
Let's slightly improve the warning, something like this, feel free to edit: ```suggestion logger.warning_once( "KV connector %s requires PIECEWISE CUDA graph mode " "due to layerwise async operations that cannot be " "captured i...
# Check if KV connector requires PIECEWISE mode for CUDA graphs if ( self.kv_transfer_config is not None and self.kv_transfer_config.is_kv_transfer_instance and self.compilation_config.cudagraph_mode.has_full_cudagraphs() ): ...
@@ -717,6 +717,32 @@ def has_blocked_weights(): CUDAGraphMode.FULL_DECODE_ONLY ) + # Check if KV connector requires PIECEWISE mode for CUDA graphs + if ( + self.compilation_config.cudagraph_mode.has_full_cudagraphs() + a...
vllm/config/vllm.py
26
Python
1
performance
708
51
51
false
[KVConnector] Auto-downgrade to PIECEWISE cudagraph mode for layerwise async ops
31,057
vllm-project/vllm
71,895
Python
ProExpertProg
yashwantbezawada
# Check if KV connector requires PIECEWISE mode for CUDA graphs if ( self.compilation_config.cudagraph_mode.has_full_cudagraphs() and self.kv_transfer_config is not None and self.kv_transfer_config.is_kv_transfer_instance ): ...
I think this performance bit is a bit too "scary", suggesting that a connector that moves all the layers at once might actually be more performant than one that "streams" them.
# async tp is built on top of sequence parallelism # and requires it to be enabled. if self.compilation_config.pass_config.fuse_gemm_comms: self.compilation_config.pass_config.enable_sp = True if self.compilation_config.pass_config.enable_sp: if self.parallel_con...
@@ -849,6 +849,36 @@ def has_blocked_weights(): CUDAGraphMode.FULL_DECODE_ONLY ) + # Check if KV connector requires PIECEWISE mode for CUDA graphs + if ( + self.compilation_config.cudagraph_mode.has_full_cudagraphs() + a...
vllm/config/vllm.py
26
Python
0.786
performance
176
51
51
false
[KVConnector] Auto-downgrade to PIECEWISE cudagraph mode for layerwise async ops
31,057
vllm-project/vllm
71,895
Python
NickLucche
yashwantbezawada
block_size = 16 scheduler = _create_encoder_decoder_scheduler(block_size=block_size) # Simulate a mix of short and long audio inputs. test_data = [ ("short_audio", 50), ("medium_audio", 750), ("long_audio", 1500), ("tiny_audio", 16), ("odd_audio", 333), ] ...
this is actually misleading and had me go back to your change in scheduler. Whisper only takes in fixed-input len spectograms (1500). This test is suggesting that different audios will end up allocating different num blocks, if that was the case whisper would break.
shift_computed_tokens in the boundary calculation. Without the fix, the scheduler would fail to schedule encoder inputs at the boundary, causing "Encoder cache miss" errors. """ scheduler = create_scheduler( model="llava-hf/llava-1.5-7b-hf", max_num_batched_tokens=1024, disa...
@@ -3675,3 +3675,357 @@ def test_abort_request_finished_recving(): # verify request is deleted assert request.request_id not in scheduler.requests assert not scheduler.finished_recving_kv_req_ids + + +# ============================================================================== +# Variable-length enco...
tests/v1/core/test_scheduler.py
26
Python
0.571
suggestion
266
51
51
false
[Scheduler][ASR] Fix CrossAttn blocks per-request for Variable length encoder inputs
31,058
vllm-project/vllm
71,895
Python
NickLucche
ekagra-ranjan
slices: Sequence[slice] | Sequence[Sequence[slice]] dim: int = 0 def build_elems( self, modality: str, key: str, data: NestedTensors, ) -> Sequence[MultiModalFieldElem]: field_factory = self._field_factory(modality=modality, key=key) if not is_list_of(sel...
I think this solution isn't really proper because it fails to "flatten" the input (see L587, L588) which is how this field is defined. If another method of combining multiple inputs is required, you should use a different field type.
slices: Sequence[slice] | Sequence[Sequence[slice]] dim: int = 0 def build_elems( self, modality: str, key: str, data: NestedTensors, ) -> Sequence[MultiModalFieldElem]: field_factory = self._field_factory(modality=modality, key=key) if not is_list_of(sel...
@@ -578,6 +578,12 @@ def _shape_before_after(tensor: torch.Tensor): ) return torch.concat(batch, dim=self.dim, out=out) + # When shapes are incompatible on non-concat dimensions, + # return the batch as a list of tensors for the model to handle + # (e...
vllm/multimodal/inputs.py
26
Python
0.857
bug
233
51
51
false
[Bug Fix] Handle variable-length tensors in MultiModalFlatField batching
31,751
vllm-project/vllm
71,895
Python
DarkLight1337
AndriiPasternak31
batch = cast(list[torch.Tensor], batch) if len(batch) == 1: # An optimization when `batch` contains only one tensor: # - produce exactly same result as `torch.concat(batch)` # - will achieve zero-copy if the tensor is contiguous ret...
I think it would be more efficient to create the `out` tensor first, then slice-assign the batch items to it without needing to pad them.
batch = cast(list[torch.Tensor], batch) if len(batch) == 1: # An optimization when `batch` contains only one tensor: # - produce exactly same result as `torch.concat(batch)` # - will achieve zero-copy if the tensor is contiguous ret...
@@ -578,6 +578,34 @@ def _shape_before_after(tensor: torch.Tensor): ) return torch.concat(batch, dim=self.dim, out=out) + # Shapes don't match on non-concat dimensions (e.g., variable-length + # audio). Pad all tensors to max size before concatenating. + ...
vllm/multimodal/inputs.py
26
Python
0.5
performance
137
51
51
false
[Bug Fix] Handle variable-length tensors in MultiModalFlatField batching
31,751
vllm-project/vllm
71,895
Python
DarkLight1337
AndriiPasternak31
import torch.fx as fx from torch._higher_order_ops.auto_functionalize import auto_functionalized from torch._inductor.pattern_matcher import PatternMatcherPass from torch.distributed._symmetric_memory import enable_symm_mem_for_group from vllm.config import VllmConfig from vllm.config.utils import Range from vllm.dist...
cc @ProExpertProg refactored a bit here to move None to the top
import torch.fx as fx from torch._higher_order_ops.auto_functionalize import auto_functionalized from torch._inductor.pattern_matcher import PatternMatcherPass from torch.distributed._symmetric_memory import enable_symm_mem_for_group from vllm.config import VllmConfig from vllm.config.utils import Range from vllm.dist...
@@ -30,19 +30,20 @@ FP8_DTYPE = current_platform.fp8_dtype() +flashinfer_comm: ModuleType | None = None
vllm/compilation/collective_fusion.py
26
Python
0.357
refactor
64
51
51
false
[Misc][BE] Turn on strict type coverage for vllm/compilation
31,756
vllm-project/vllm
71,895
Python
Lucaskabela
Lucaskabela
not envs.VLLM_DISABLE_COMPILE_CACHE and not torch._inductor.config.force_disable_caches and not vllm_inductor_config_disable_cache ) class InductorStandaloneAdaptor(CompilerInterface): """ The adaptor for the Inductor compiler. Requires PyTorch 2.8+. This is not on by defau...
We should just use the utils for hashing here that we use for other compile_hash functions (I think sha256)
not envs.VLLM_DISABLE_COMPILE_CACHE and not torch._inductor.config.force_disable_caches and not vllm_inductor_config_disable_cache ) class InductorStandaloneAdaptor(CompilerInterface): """ The adaptor for the Inductor compiler. Requires PyTorch 2.8+. This is not on by defau...
@@ -198,9 +198,9 @@ def __init__(self, save_format: Literal["binary", "unpacked"]) -> None: def compute_hash(self, vllm_config: VllmConfig) -> str: factors = get_inductor_factors() - hash_str = safe_hash(str(factors).encode(), usedforsecurity=False).hexdigest()[ - :10 - ] + ...
vllm/compilation/compiler_interface.py
26
Python
0.5
suggestion
107
51
51
false
[Misc][BE] Turn on strict type coverage for vllm/compilation
31,756
vllm-project/vllm
71,895
Python
ProExpertProg
Lucaskabela
) from vllm.config.compilation import DynamicShapesType from vllm.forward_context import get_forward_context, is_forward_context_available from vllm.logger import init_logger from vllm.sequence import IntermediateTensors from vllm.utils.import_utils import resolve_obj_by_qualname from vllm.utils.torch_utils import is_t...
Gemini bot caught a good bug here - `_T` should be `type[_T]` since it is the cls type
) from vllm.config.compilation import DynamicShapesType from vllm.forward_context import get_forward_context, is_forward_context_available from vllm.logger import init_logger from vllm.sequence import IntermediateTensors from vllm.utils.import_utils import resolve_obj_by_qualname from vllm.utils.torch_utils import is_t...
@@ -44,10 +44,10 @@ IGNORE_COMPILE_KEY = "_ignore_compile_vllm" -_T = TypeVar("_T", bound=type[nn.Module]) +_T = TypeVar("_T", bound=nn.Module) -def ignore_torch_compile(cls: _T) -> _T: +def ignore_torch_compile(cls: type[_T]) -> type[_T]:
vllm/compilation/decorators.py
26
Python
0.857
bug
86
51
51
false
[Misc][BE] Turn on strict type coverage for vllm/compilation
31,756
vllm-project/vllm
71,895
Python
Lucaskabela
Lucaskabela
(outside torch.compile tracing), and - Thin wrappers around the torch.ops entrypoints for use in CUDA fast paths, without introducing graph breaks. Important: Do not call the availability helpers in a compiled region. They may call functions decorated with `torch._dynamo.disable` to safely check conditions t...
Do we need to check if the GPU is good for oink op?
- Thin wrappers around the torch.ops entrypoints for use in CUDA fast paths, without introducing graph breaks. Important: Do not call the availability helpers in a compiled region. They may call functions decorated with `torch._dynamo.disable` to safely check conditions that should not be traced. """ from __f...
@@ -0,0 +1,97 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Small helper wrappers for external Oink Blackwell custom ops. + +vLLM does not depend on the external Oink repository/package. When an external +plugin registers torch.library.custom_op entr...
vllm/_oink_ops.py
26
Python
0.143
question
51
51
51
false
[Perf] Add opt-in SM100 Oink RMSNorm custom-op path
31,828
vllm-project/vllm
71,895
Python
houseroad
Laurawly
# If set, allow loading or unloading lora adapters in runtime, "VLLM_ALLOW_RUNTIME_LORA_UPDATING": lambda: ( os.environ.get("VLLM_ALLOW_RUNTIME_LORA_UPDATING", "0").strip().lower() in ("1", "true") ), # We assume drivers can report p2p status correctly. # If the program hangs when us...
Can we make it more general, like VLLM_USE_OINK_OPS?
# Whether to use aiter paged attention. # By default is disabled. "VLLM_ROCM_USE_AITER_PAGED_ATTN": lambda: ( os.getenv("VLLM_ROCM_USE_AITER_PAGED_ATTN", "False").lower() in ("true", "1") ), # use aiter linear op if aiter ops are enabled # The following list of related ops # - scaled...
@@ -929,6 +930,11 @@ def get_vllm_port() -> int | None: "VLLM_DISABLE_PYNCCL": lambda: ( os.getenv("VLLM_DISABLE_PYNCCL", "False").lower() in ("true", "1") ), + # Optional fast path for RMSNorm on NVIDIA Blackwell GPUs using an + # external Oink kernel. Disabled by default. + "VLLM_USE_OINK_...
vllm/envs.py
26
Python
0.357
question
52
51
51
false
[Perf] Add opt-in SM100 Oink RMSNorm custom-op path
31,828
vllm-project/vllm
71,895
Python
houseroad
Laurawly
output_items: list[ResponseOutputItem] = [] recipient = message.recipient if recipient is not None: # Browser tool calls (browser.search, browser.open, browser.find) if recipient.startswith("browser."): output_items.append(_parse_browser_tool_call(message, recipient)) ...
non blocking: I think it would be easier to review if this logic was wrapped in a sub function like _parse_output_messages_no_recipient()
# final channel content are both intended to be shown to end-users. # See: https://cookbook.openai.com/articles/openai-harmony return [_parse_final_message(message)] raise ValueError(f"Unknown channel: {message.channel}") def parse_output_message(message: Message) -> list[ResponseOutputIt...
@@ -721,9 +713,10 @@ def parse_output_message(message: Message) -> list[ResponseOutputItem]: output_items.extend(_parse_reasoning(message)) elif message.channel == "commentary":
vllm/entrypoints/openai/parser/harmony_utils.py
26
Python
0.286
suggestion
137
51
51
false
[Bugfix] Fix Harmony preamble visibility in Responses API
32,114
vllm-project/vllm
71,895
Python
qandrew
thepushkarp
f"Backend {backend} is not supported for vit attention. " f"Supported backends are: {cls.get_supported_vit_attn_backends()}" ) logger.info_once(f"Using backend {backend} for vit attention") return backend cc = cls.get_device_capability() ...
can you help me to add this `AttentionBackendEnum.TRITON_ATTN,` to the `get_supported_vit_attn_backends` of `rocm.py`? I validated, it also works for rocm. But for now, I don't update the `get_vit_attn_backend`.
f"No valid attention backend found for {cls.device_name} " f"with {config_str}. Reasons: {reasons_str}." ) # We have found some valid backends. Select the one with the # highest priority. sorted_indices = sorted( range(len(valid_backends_p...
@@ -373,8 +373,9 @@ def get_attn_backend_cls( @classmethod def get_supported_vit_attn_backends(cls) -> list["AttentionBackendEnum"]: return [ - AttentionBackendEnum.TORCH_SDPA, AttentionBackendEnum.FLASH_ATTN, + AttentionBackendEnum.TRITON_ATTN,
vllm/platforms/cuda.py
26
Python
0.571
suggestion
212
51
51
false
[MM Encoder] Add Triton ViT attention backend
32,183
vllm-project/vllm
71,895
Python
tjtanaa
Isotr0py
num_pid_m = tl.cdiv(EM, BLOCK_SIZE_M) num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) num_pid_in_group = GROUP_SIZE_M * num_pid_n group_id = pid_m_n // num_pid_in_group first_pid_m = group_id * GROUP_SIZE_M group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M) pid_m = first_pid_m + ((pid_m_n % num...
nice that we have a parameter to control TMA on or off and could tune to test if its beneficial.
stride_cm, stride_cn, stride_tl, stride_el, slice_a_size, slice_c_size, # Meta-parameters num_slice_a: tl.constexpr, num_slice_c: tl.constexpr, # top_k_num or 1 depending on input token # is expanded by top_k or not token_mapping_factor: tl.constexpr, # whether use na...
@@ -91,6 +100,8 @@ def _fused_moe_lora_kernel( USE_GDC: tl.constexpr, launch_pdl: tl.constexpr, IS_PRIMARY: tl.constexpr, + USE_TMA: tl.constexpr,
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.357
suggestion
96
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
dcmaddix
gnovack
After this, it remains constant and subsequent usage is through LUT. Refer to: https://github.com/triton-lang/triton/blob/release/3.1.x/python/tutorials/08-grouped-gemm.py """ key = tuple(lora_weight.data_ptr() for lora_weight in lora_weights) if (ptr_tensor := _LORA_PTR_DICT.get(key)) is not N...
What is `sorted_c` used for? To check if the memory is contiguous? Could you add comment defining it thanks!
offs, offs_token, offs_cn, stride_cm, stride_cn, EM: tl.constexpr, BLOCK_SIZE_M: tl.constexpr, sort_c: tl.constexpr, ): # When sort_c is true, store the output in c_ptr using token order defined # in sorted_token_ids_ptr; otherwise, use the original token order from the prompt ...
@@ -91,6 +100,8 @@ def _fused_moe_lora_kernel( USE_GDC: tl.constexpr, launch_pdl: tl.constexpr, IS_PRIMARY: tl.constexpr, + USE_TMA: tl.constexpr, + sorted_c: tl.constexpr,
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
1
question
108
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
dcmaddix
gnovack
) if USE_GDC and IS_PRIMARY: # GDC launch dependents hints the runtime system to launch dependent kernels. tl.extra.cuda.gdc_launch_dependents() # accumulator accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) if USE_GDC and not IS_PRIMARY: tl.extra.cud...
Why is the GDC wait removed here?
# Get expert_id expert_id = _get_expert_id( expert_ids_ptr, lora_id, pid_m, stride_el, max_loras, naive_block_assignment, ) if expert_id == -1: return # Get token offsets offs_token = _get_token_offs( sorted_token_ids_ptr, ...
@@ -167,30 +203,50 @@ def _fused_moe_lora_kernel( tl.extra.cuda.gdc_wait() for k in range(0, grid_k): - k_remaining = K - k * (BLOCK_SIZE_K * SPLIT_K) - # GDC wait waits for ALL programs in the prior kernel to complete - # before continuing. + cur_k_offset = k * (BLOCK_SIZE_K...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.286
question
33
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
xyang16
gnovack
assert ( sorted_token_ids.shape[0] == expert_ids.shape[0] == num_tokens_post_padded.shape[0] ) assert output.shape[0] == topk_weights.shape[0] assert top_k_num == topk_weights.shape[1] device = qcurr_hidden_states.device num_slices = len(lora_a_stacked) w1_lora_b_stac...
Can we use `add_pre_run_hook`?
num_warps: int, num_stages: int, split_k: int, num_active_loras: int, mul_routed_weight: bool = False, offset: int = 0, use_gdc: bool = False, use_tma: bool = False, ) -> None: b_ptr = _get_ptr(lora_b_stacked, device) K = max_lora_rank N = w1_output_dim_size w1_lora_b_st...
@@ -487,8 +577,17 @@ def _fused_moe_lora( num_tokens = M * top_k_num w1_output_dim_size = w1_lora_b_stacked.shape[2] + # TMA is not currently compatiple with fully_sharded due to the non-determinism + # of token id sorting across ranks. + use_tma = supports_tma(device) and not fully_sharded + + ...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.5
question
30
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
jeejeelee
gnovack
else: a = tl.load( a_ptrs, mask=token_mask[:, None] & (offs_k[None, :] < k_remaining), other=0.0, ) a_ptrs += BLOCK_SIZE_K * SPLIT_K * stride_ak accumulator += tl.dot(a, b) if MUL_ROUTED_WEIGHT: moe_weight ...
In sort_c case, you have to add an extra lora_id dim for the c_buffer, otherwise different tokens might end up store in the same position in c_buffer.
+ offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn ) if USE_GDC and IS_PRIMARY: # GDC launch dependents hints the runtime system to launch dependent kernels. tl.extra.cuda.gdc_launch_dependents() accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dty...
@@ -280,36 +317,56 @@ def _fused_moe_lora_kernel( tl.extra.cuda.gdc_wait() for k in range(0, grid_k): - k_remaining = K - k * (BLOCK_SIZE_K * SPLIT_K) - # GDC wait waits for ALL programs in the prior kernel to complete - # before continuing. + cur_k_offset = k * (BLOCK_SIZE_K...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.286
style
150
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
RunkaiTao
gnovack
else: # 5D buffer: (num_slices, max_loras, M_padded, top_k, lora_rank) offs_am = ( slice_id * max_loras * per_lora_tokens + lora_id * per_lora_tokens + pid_m * pid_m_offset // token_mapping_factor ) offs_ak = pid_sk * BL...
feels like `a_desc is not None` should be a static assert ?
naive_block_assignment, ) if expert_id == -1: return # Get token offsets offs_token = _get_token_offs( sorted_token_ids_ptr, lora_id, pid_m, offs, stride_tl, max_loras, num_valid_tokens, naive_block_assignment, BLOC...
@@ -250,24 +261,60 @@ def _fused_moe_lora_kernel( cur_b_ptr = tl.load(b_ptr + slice_id).to(tl.pointer_type(c_ptr.dtype.element_ty)) cur_c_ptr = c_ptr + (slice_id % num_slice_c) * slice_c_size - # remove modulo wrap-around - offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(tl.int32) ...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.571
question
60
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
varun-sundar-rabindranath
gnovack
) assert output.shape[0] == topk_weights.shape[0] assert top_k_num == topk_weights.shape[1] device = qcurr_hidden_states.device num_slices = len(lora_a_stacked) w1_lora_b_stacked = lora_b_stacked[0] num_experts = lora_a_stacked[0].shape[1] N = max_lora_rank M = topk_weights.shape...
why isn't this no longer M ? I think it should still be M for the non-tma case so we don't allocate extra memory in that case.
expand_split_k: int, mul_routed_weight: bool = False, fully_sharded: bool = False, offset: int = 0, ) -> None: assert len(lora_a_stacked) == len(lora_b_stacked) > 0 assert topk_weights.dim() == qcurr_hidden_states.dim() == 2 if sorted_token_ids is None: assert expert_ids.dim() == 1 ...
@@ -616,8 +717,34 @@ def _fused_moe_lora( else num_tokens * shrink_block_size_m ) + # TMA is not currently compatiple with fully_sharded due to the non-determinism + # of token id sorting across ranks. + use_tma = supports_tma(device) and not fully_sharded + + intermediate_cache_shape = ( + ...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.786
question
126
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
varun-sundar-rabindranath
gnovack
def _adjust_kernel_inputs( num_active_loras: int, sorted_token_ids: torch.Tensor | None, expert_ids: torch.Tensor, ): """ helper function to adjust kernel inputs when sorted_token_ids is None """ if sorted_token_ids is None: stride_tl = 0 stride_el = 0 grid_lora_dim...
is this a global setting affecting other kernels ? if yes, I think we should set it to default after kernel invocation (would be better to do it with a context manager)
+ stride_cm * offs_token_id[:, None] + stride_cn * offs_cn[None, :] ) else: c_ptrs = ( cur_c_ptr + stride_cm * offs_token[:, None] + stride_cn * offs_cn[None, :] ) return c_ptrs _LORA_PTR_DICT: dict[tuple[int, ...], torch.tensor] = {} def _get_ptr(...
@@ -113,6 +113,13 @@ def _adjust_kernel_inputs( return grid_lora_dim, stride_tl, stride_el +def _set_triton_allocator(device: torch.device): + def alloc_fn(size: int, alignment: int, stream: int | None): + return torch.empty(size, device=device, dtype=torch.int8) + + triton.set_allocator(alloc_fn)
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.5
question
168
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
varun-sundar-rabindranath
gnovack
top_k_num, max_lora_rank, ) a_intermediate_cache1 = torch.zeros( intermediate_cache_shape, dtype=output.dtype, device=device, ) use_gdc = supports_pdl(device) and not fully_sharded _fused_moe_lora_shrink( a_intermediate_cache1...
Question about intermediate_cache_shape. Focusing on the `use_tma` and `sorted_tokens_ids != None` case IIUC, this is an intermediate tensor to store the outputs of the shrink operation, without permuting it (as being done in the non-tma case). The idea here is to simply store the outputs in the matching sorted_token_i...
# TMA is not currently compatiple with fully_sharded due to the non-determinism # of token id sorting across ranks. use_tma = supports_tma(device) and not fully_sharded intermediate_cache_shape = ( num_slices, M, top_k_num, max_lora_rank, ) if use_tma: i...
@@ -616,8 +717,34 @@ def _fused_moe_lora( else num_tokens * shrink_block_size_m ) + # TMA is not currently compatiple with fully_sharded due to the non-determinism + # of token id sorting across ranks. + use_tma = supports_tma(device) and not fully_sharded + + intermediate_cache_shape = ( + ...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.857
performance
988
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
varun-sundar-rabindranath
gnovack
) a_ptrs += BLOCK_SIZE_K * SPLIT_K * stride_ak accumulator += tl.dot(a, b) if MUL_ROUTED_WEIGHT: moe_weight = tl.load(topk_weights_ptr + offs_token, mask=token_mask, other=0.0) accumulator = accumulator * moe_weight[:, None] accumulator = accumulator.to(c_ptr.dt...
nit: would be nice to factor this out.
k_remaining = K - cur_k_offset # pre-fetch lora weight if b_desc is not None: b = ( b_desc.load([lora_id, expert_id, offs_bn, offs_bk + cur_k_offset]) .reshape(BLOCK_SIZE_N, BLOCK_SIZE_K) .T ) else: # add...
@@ -280,36 +327,57 @@ def _fused_moe_lora_kernel( tl.extra.cuda.gdc_wait() for k in range(0, grid_k): - k_remaining = K - k * (BLOCK_SIZE_K * SPLIT_K) - # GDC wait waits for ALL programs in the prior kernel to complete - # before continuing. + cur_k_offset = k * (BLOCK_SIZE_K...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.071
nitpick
39
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
varun-sundar-rabindranath
gnovack
) a_ptrs += BLOCK_SIZE_K * SPLIT_K * stride_ak accumulator += tl.dot(a, b) if MUL_ROUTED_WEIGHT: moe_weight = tl.load(topk_weights_ptr + offs_token, mask=token_mask, other=0.0) accumulator = accumulator * moe_weight[:, None] accumulator = accumulator.to(c_ptr.dt...
would be nice to factor this out to something like, ``` a_ptrs, a = load_a() b_ptrs, b = load_b() ```
k_remaining = K - cur_k_offset # pre-fetch lora weight if b_desc is not None: b = ( b_desc.load([lora_id, expert_id, offs_bn, offs_bk + cur_k_offset]) .reshape(BLOCK_SIZE_N, BLOCK_SIZE_K) .T ) else: # add...
@@ -280,36 +327,57 @@ def _fused_moe_lora_kernel( tl.extra.cuda.gdc_wait() for k in range(0, grid_k): - k_remaining = K - k * (BLOCK_SIZE_K * SPLIT_K) - # GDC wait waits for ALL programs in the prior kernel to complete - # before continuing. + cur_k_offset = k * (BLOCK_SIZE_K...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.786
suggestion
104
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
varun-sundar-rabindranath
gnovack
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) num_pid_in_group = GROUP_SIZE_M * num_pid_n group_id = pid_m_n // num_pid_in_group first_pid_m = group_id * GROUP_SIZE_M group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M) pid_m = first_pid_m + ((pid_m_n % num_pid_in_group) % group_size_m) pid_n =...
can you add a comment describing the various combinations possible with use_tma - IIUC, <google-sheets-html-origin><style type="text/css"><!--td {border: 1px solid #cccccc;}br {mso-data-placement:same-cell;}--></style> a_desc | b_desc | sort_c | comment -- | -- | -- | -- yes | yes | FALSE | expand kernel - num_slice...
# whether use naive block assignment naive_block_assignment: tl.constexpr, MUL_ROUTED_WEIGHT: tl.constexpr, ADD_INPUTS: tl.constexpr, USE_B_L2_CACHE: tl.constexpr, # new, enable .ca load for B BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, GROUP_...
@@ -177,6 +186,8 @@ def _fused_moe_lora_kernel( USE_GDC: tl.constexpr, launch_pdl: tl.constexpr, IS_PRIMARY: tl.constexpr, + USE_TMA: tl.constexpr, + sort_c: tl.constexpr, ):
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.929
style
475
51
51
false
Add TMA support to fused_moe_lora kernel
32,195
vllm-project/vllm
71,895
Python
varun-sundar-rabindranath
gnovack
with record_function_or_nullcontext( "gpu_model_runner: set_async_sampled_token_ids" ): # Save ref of sampled_token_ids CPU tensor if the batch contains # any requests with sampling params that require output ids. self.input_batch.set_async_sampled_token_i...
```suggestion torch.distributed.broadcast( sampled_token_ids, src=pp.rank, group=pp.device_group ```
"gpu_model_runner: set_async_sampled_token_ids" ): # Save ref of sampled_token_ids CPU tensor if the batch contains # any requests with sampling params that require output ids. self.input_batch.set_async_sampled_token_ids( async_output.sampled_toke...
@@ -3751,6 +3768,46 @@ def propose_draft_token_ids(sampled_token_ids): return async_output + def _pp_broadcast_prev_sampled_token_ids( + self, sampled_token_ids: torch.Tensor + ) -> None: + """Broadcast sampled token ids (GPU) from last PP stage""" + pp = get_pp_group() + ...
vllm/v1/worker/gpu_model_runner.py
26
Python
1
suggestion
123
51
51
false
[Feature] Fully support for async scheduling + PP, 30.8% E2E throughput improvement, 31.8% TPOT improvement
32,618
vllm-project/vllm
71,895
Python
njhill
yewentao256
model_runner_output=output, sampled_token_ids=sampler_output.sampled_token_ids, logprobs_tensors=sampler_output.logprobs_tensors, invalid_req_indices=invalid_req_indices, async_output_copy_stream=self.async_output_copy_stream, ...
Not sure we need the `is_initialized` asserts?
sampled_token_ids=sampler_output.sampled_token_ids, logprobs_tensors=sampler_output.logprobs_tensors, invalid_req_indices=invalid_req_indices, async_output_copy_stream=self.async_output_copy_stream, vocab_size=self.input_batch.vocab_size, ...
@@ -3751,6 +3768,46 @@ def propose_draft_token_ids(sampled_token_ids): return async_output + def _pp_broadcast_prev_sampled_token_ids( + self, sampled_token_ids: torch.Tensor + ) -> None: + """Broadcast sampled token ids (GPU) from last PP stage""" + pp = get_pp_group() + ...
vllm/v1/worker/gpu_model_runner.py
26
Python
0.286
question
46
51
51
false
[Feature] Fully support for async scheduling + PP, 30.8% E2E throughput improvement, 31.8% TPOT improvement
32,618
vllm-project/vllm
71,895
Python
njhill
yewentao256
def _pp_broadcast_prev_sampled_token_ids( self, sampled_token_ids: torch.Tensor ) -> None: """Broadcast sampled token ids (GPU) from last PP stage""" pp = get_pp_group() assert pp.is_last_rank assert torch.distributed.is_initialized() # `prev_sampled_token_ids` is...
```suggestion torch.distributed.broadcast(recv, src=pp.last_rank, group=pp.device_group) ```
self, sampled_token_ids: torch.Tensor ) -> None: """Broadcast sampled token ids (GPU) from last PP stage""" pp = get_pp_group() assert pp.is_last_rank # `prev_sampled_token_ids` is expected to have shape [num_reqs, 1]. assert sampled_token_ids.dim() == 2 and sampled_t...
@@ -3751,6 +3768,46 @@ def propose_draft_token_ids(sampled_token_ids): return async_output + def _pp_broadcast_prev_sampled_token_ids( + self, sampled_token_ids: torch.Tensor + ) -> None: + """Broadcast sampled token ids (GPU) from last PP stage""" + pp = get_pp_group() + ...
vllm/v1/worker/gpu_model_runner.py
26
Python
1
suggestion
102
51
51
false
[Feature] Fully support for async scheduling + PP, 30.8% E2E throughput improvement, 31.8% TPOT improvement
32,618
vllm-project/vllm
71,895
Python
njhill
yewentao256
# `prev_sampled_token_ids` is expected to have shape [num_reqs, 1]. assert sampled_token_ids.dim() == 2 and sampled_token_ids.shape[-1] == 1, ( "PP+async expects sampled_token_ids to have shape [num_reqs, 1]" ) src_global_rank = pp.ranks[pp.world_size - 1] torch.distr...
actually will also work without the `tolist` ```suggestion discard_req_indices = np.nonzero(self.discard_request_mask.np[:num_reqs])[0] ```
"PP+async expects sampled_token_ids to have shape [num_reqs, 1]" ) torch.distributed.broadcast( sampled_token_ids, src=pp.rank, group=pp.device_group ) def _pp_receive_prev_sampled_token_ids_to_input_batch(self) -> None: """Receive sampled token ids broadcast...
@@ -3751,6 +3768,46 @@ def propose_draft_token_ids(sampled_token_ids): return async_output + def _pp_broadcast_prev_sampled_token_ids( + self, sampled_token_ids: torch.Tensor + ) -> None: + """Broadcast sampled token ids (GPU) from last PP stage""" + pp = get_pp_group() + ...
vllm/v1/worker/gpu_model_runner.py
26
Python
1
suggestion
150
51
51
false
[Feature] Fully support for async scheduling + PP, 30.8% E2E throughput improvement, 31.8% TPOT improvement
32,618
vllm-project/vllm
71,895
Python
njhill
yewentao256
req_state.num_computed_tokens = num_computed_tokens if not is_last_rank: # When using PP, the scheduler sends the sampled tokens back, # because there's no direct communication between the first- # stage worker and the last-stage worker. ...
I think you could revert this, and instead: - wrap the contents of this if block in `if req_data.new_token_ids` - where we construct `prev_req_id_to_index` below, also look up each request in `self.requests` and append `-1` to it's `output_tokens` ... but skip those in `discard_req_indices_set`. - In the scheduler...
# Update the cached states. req_state.num_computed_tokens = num_computed_tokens if not is_last_rank: if not req_data.new_token_ids: # Async scheduled PP: Sampled tokens propagated via GPU broadcast. new_token_ids: list[int] = ...
@@ -1017,11 +1017,20 @@ def _update_states(self, scheduler_output: "SchedulerOutput") -> None: num_new_tokens = ( num_computed_tokens + len(new_token_ids) - req_state.num_tokens ) - if num_new_tokens == 1: - # Avoid slicing list in...
vllm/v1/worker/gpu_model_runner.py
26
Python
0.857
performance
626
51
51
false
[Feature] Fully support for async scheduling + PP, 30.8% E2E throughput improvement, 31.8% TPOT improvement
32,618
vllm-project/vllm
71,895
Python
njhill
yewentao256
# second step: num_computed_tokens = 100(prompt lenth), # spec_tokens = [a,b], prev_num_draft_len = 0. # third step: num_computed_tokens = 100 + 2, spec_tokens = [c,d], # prev_num_draft_len = 2. # num_computed_tokens in first step and secon...
I don't think this line is needed
# fist step: num_computed_tokens = 0, spec_tokens = [], # prev_num_draft_len = 0. # second step: num_computed_tokens = 100(prompt lenth), # spec_tokens = [a,b], prev_num_draft_len = 0. # third step: num_computed_tokens = 100 + 2, spec_token...
@@ -1011,17 +1011,21 @@ def _update_states(self, scheduler_output: "SchedulerOutput") -> None: # When using PP, the scheduler sends the sampled tokens back, # because there's no direct communication between the first- # stage worker and the last-stage worker. - ...
vllm/v1/worker/gpu_model_runner.py
26
Python
0.071
suggestion
33
51
51
false
[Feature] Fully support for async scheduling + PP, 30.8% E2E throughput improvement, 31.8% TPOT improvement
32,618
vllm-project/vllm
71,895
Python
njhill
yewentao256
# prev_num_draft_len = 0. # second step: num_computed_tokens = 100(prompt lenth), # spec_tokens = [a,b], prev_num_draft_len = 0. # third step: num_computed_tokens = 100 + 2, spec_tokens = [c,d], # prev_num_draft_len = 2. # n...
Also move this comment into the inner if, and change to "When using async PP, ..."?
# of the request. for example: # fist step: num_computed_tokens = 0, spec_tokens = [], # prev_num_draft_len = 0. # second step: num_computed_tokens = 100(prompt lenth), # spec_tokens = [a,b], prev_num_draft_len = 0. # third ...
@@ -1011,17 +1011,21 @@ def _update_states(self, scheduler_output: "SchedulerOutput") -> None: # When using PP, the scheduler sends the sampled tokens back, # because there's no direct communication between the first- # stage worker and the last-stage worker.
vllm/v1/worker/gpu_model_runner.py
26
Python
0.357
refactor
83
51
51
false
[Feature] Fully support for async scheduling + PP, 30.8% E2E throughput improvement, 31.8% TPOT improvement
32,618
vllm-project/vllm
71,895
Python
njhill
yewentao256
session.record_event(EngineCoreEventType.QUEUED) def _make_cached_request_data( self, running_reqs: list[Request], resumed_reqs: list[Request], num_scheduled_tokens: dict[str, int], spec_decode_tokens: dict[str, list[int]], req_to_new_blocks: dict[str, KV...
nit: redundant parens ```suggestion if self.use_pp and not self.scheduler_config.async_scheduling: ```
session.record_event(EngineCoreEventType.QUEUED) def _make_cached_request_data( self, running_reqs: list[Request], resumed_reqs: list[Request], num_scheduled_tokens: dict[str, int], spec_decode_tokens: dict[str, list[int]], req_to_new_blocks: dict[str, KV...
@@ -1003,7 +996,10 @@ def _make_cached_request_data( for idx, req in enumerate(itertools.chain(running_reqs, resumed_reqs)): req_id = req.request_id req_ids.append(req_id) - if self.use_pp: + # NOTE: In PP+async scheduling, we consume token ids via a direct GPU +...
vllm/v1/core/sched/scheduler.py
26
Python
1
suggestion
117
51
51
false
[Feature] Fully support for async scheduling + PP, 30.8% E2E throughput improvement, 31.8% TPOT improvement
32,618
vllm-project/vllm
71,895
Python
njhill
yewentao256
if spec_token_ids is None: return output_token_ids result = [] for out, spec in zip(output_token_ids, spec_token_ids): if len(spec) == 0: continue result.append(out) for i in range(len(spec) - 1): result.append([*re...
Creating a new tensor for each request inside the loop could be inefficient. Consider creating all stop token tensors once before the loop, or at least reusing tensors where stop token sets are identical across requests. However, this optimization may be acceptable given that stop token sets are typically small and the...
return logits @staticmethod def _combine_outputs_with_spec_tokens( output_token_ids: list[list[int]], spec_token_ids: list[list[int]] | None = None, ) -> list[list[int]]: if spec_token_ids is None: return output_token_ids result = [] for out, spe...
@@ -294,6 +294,65 @@ def apply_logits_processors( logits, bad_words_token_ids, output_token_ids, metadata.num_draft_tokens ) + logits = self._apply_min_tokens(logits, sampling_metadata, metadata) + + return logits + + def _apply_min_tokens( + self, + logits...
vllm/v1/sample/rejection_sampler.py
26
Python
0.643
performance
393
51
51
false
[Core] Support `min_tokens` with speculative decoding
32,642
vllm-project/vllm
71,895
Python
Copilot
qianlihuang
# Calculate indices of target logits. if sampling_metadata.allowed_token_ids_mask is not None or has_penalties: num_requests = len(sampling_metadata.output_token_ids) num_draft_tokens = torch.tensor(metadata.num_draft_tokens, device="cpu") original_indices = torch.ara...
Not sure why this import needs to be inline?
# Calculate indices of target logits. if sampling_metadata.allowed_token_ids_mask is not None or has_penalties: num_requests = len(sampling_metadata.output_token_ids) num_draft_tokens = torch.tensor(metadata.num_draft_tokens, device="cpu") original_indices = torch.ar...
@@ -292,6 +292,15 @@ def apply_logits_processors( logits, bad_words_token_ids, output_token_ids, metadata.num_draft_tokens ) + # Apply min_tokens constraint via MinTokensLogitsProcessor. + from vllm.v1.sample.logits_processor.builtin import MinTokensLogitsProcessor
vllm/v1/sample/rejection_sampler.py
26
Python
0.071
question
44
51
51
false
[Core] Support `min_tokens` with speculative decoding
32,642
vllm-project/vllm
71,895
Python
benchislett
qianlihuang
def build_logitsprocs( vllm_config: "VllmConfig", device: torch.device, is_pin_memory: bool, is_pooling_model: bool, custom_logitsprocs: Sequence[str | type[LogitsProcessor]] = (), ) -> LogitsProcessors: if is_pooling_model: if custom_logitsprocs: raise ValueError(STR_POOLIN...
What's the point of having an `iter` here?
def build_logitsprocs( vllm_config: "VllmConfig", device: torch.device, is_pin_memory: bool, is_pooling_model: bool, custom_logitsprocs: Sequence[str | type[LogitsProcessor]] = (), ) -> LogitsProcessors: if is_pooling_model: if custom_logitsprocs: raise ValueError(STR_POOLIN...
@@ -202,10 +202,11 @@ def build_logitsprocs( if custom_logitsprocs: raise ValueError(STR_SPEC_DEC_REJECTS_LOGITSPROCS) logger.warning( - "min_p, logit_bias, and min_tokens parameters won't currently work " - "with speculative decoding enabled." + "min_p an...
vllm/v1/sample/logits_processor/__init__.py
26
Python
0.286
question
42
51
51
false
[Core] Support `min_tokens` with speculative decoding
32,642
vllm-project/vllm
71,895
Python
benchislett
qianlihuang
# Update tensors if needed. if needs_update: reqs: list[int] = [] tok_ids: list[int] = [] for req, (_, _, stop_tok_ids) in self.min_toks.items(): reqs.extend([req] * len(stop_tok_ids)) tok_ids.extend(stop_tok_ids) self.log...
It's a bit hard to follow how this code works, please add a few short comments, for instance: - What is n_mask? - What do all_toks and all_rows represent? - What is logits_slice?
# Update tensors if needed. if needs_update: reqs: list[int] = [] tok_ids: list[int] = [] for req, (_, _, stop_tok_ids) in self.min_toks.items(): reqs.extend([req] * len(stop_tok_ids)) tok_ids.extend(stop_tok_ids) self.log...
@@ -236,6 +237,51 @@ def apply(self, logits: torch.Tensor) -> torch.Tensor: logits.index_put_(self.logits_slice, self.neg_inf_tensor) return logits + def apply_with_spec_decode(
vllm/v1/sample/logits_processor/builtin.py
26
Python
0.286
question
178
51
51
false
[Core] Support `min_tokens` with speculative decoding
32,642
vllm-project/vllm
71,895
Python
benchislett
qianlihuang
def _device_tensor(self, data: list, dtype: torch.dtype) -> torch.Tensor: return torch.tensor( data, device="cpu", dtype=dtype, pin_memory=self.pin_memory ).to(device=self.device, non_blocking=True) def apply(self, logits: torch.Tensor) -> torch.Tensor: if self.min_toks: ...
Is `req_idx < len(num_draft_tokens)` just a sanity check or are there cases where `req_idx` and be out-of-bounds here? If there are such cases, maybe it makes sense to assume no draft tokens but apply the min_toks anyways?
def _device_tensor(self, data: list, dtype: torch.dtype) -> torch.Tensor: return torch.tensor( data, device="cpu", dtype=dtype, pin_memory=self.pin_memory ).to(device=self.device, non_blocking=True) def apply(self, logits: torch.Tensor) -> torch.Tensor: if self.min_toks: ...
@@ -236,6 +237,51 @@ def apply(self, logits: torch.Tensor) -> torch.Tensor: logits.index_put_(self.logits_slice, self.neg_inf_tensor) return logits + def apply_with_spec_decode( + self, + logits: torch.Tensor, + num_draft_tokens: list[int], + ) -> torch.Tensor: + ...
vllm/v1/sample/logits_processor/builtin.py
26
Python
0.571
question
222
51
51
false
[Core] Support `min_tokens` with speculative decoding
32,642
vllm-project/vllm
71,895
Python
benchislett
qianlihuang
N: int, M: int, EM: int, K: int, num_tokens: int, num_experts: int, num_slices: int, max_lora_rank: int, w1_output_dim_size: int, block_size_m: int, block_size_n: int, block_size_k: int, group_size_m: int, num_warps: int, num_stages: int, split_k: int, ...
Why rename the `a_intermediate_cache1 `?
a_intermediate_cache1: torch.Tensor, # (num_slices, M, top_k_num, max_lora_rank) b_intermediate_cache1: torch.Tensor, # (num_slices, M, top_k_num, output_dim_size) lora_b_stacked: list[ torch.Tensor ], # [(max_loras, num_experts, max_lora_rank, K,),...] topk_weights: torch.Tensor, # (num...
@@ -331,32 +337,16 @@ def _fused_moe_lora_expand( b_ptr = _get_ptr(lora_b_stacked, device) K = max_lora_rank N = w1_output_dim_size - w1_lora_b_stacked = lora_b_stacked[0] - a_intermediate_cache1 = a_intermediate_cache1.view( - -1, a_intermediate_cache1.shape[3] - ) + a2d = a_inter...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.5
performance
40
51
51
false
[lora/moe] Improve fused MoE‑LoRA kernel indexing and memory access
32,770
vllm-project/vllm
71,895
Python
jeejeelee
cwazai
if USE_GDC and IS_PRIMARY: # GDC launch dependents hints the runtime system to launch dependent kernels. tl.extra.cuda.gdc_launch_dependents() # accumulator accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) if USE_GDC and not IS_PRIMARY: tl.extra.cuda.gdc_w...
Please don't rename these variables
+ lora_id * stride_bl + expert_id * stride_be + offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn ) if USE_GDC and IS_PRIMARY: # GDC launch dependents hints the runtime system to launch dependent kernels. tl.extra.cuda.gdc_launch_dependents() # accu...
@@ -120,84 +119,96 @@ def _fused_moe_lora_kernel( pid_m = first_pid_m + ((pid_m_n % num_pid_in_group) % group_size_m) pid_n = (pid_m_n % num_pid_in_group) // group_size_m - num_tokens_post_padded = tl.load(num_tokens_post_padded_ptr + lora_id) + num_tokens_post_padded = tl.load(num_tokens_post_padded_...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.286
suggestion
35
51
51
false
[lora/moe] Improve fused MoE‑LoRA kernel indexing and memory access
32,770
vllm-project/vllm
71,895
Python
jeejeelee
cwazai
stride_cm, stride_cn, stride_tl, stride_el, slice_a_size, slice_c_size, # Meta-parameters num_slice_a: tl.constexpr, num_slice_c: tl.constexpr, top_k: tl.constexpr, MUL_ROUTED_WEIGHT: tl.constexpr, BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE...
@jikunshang Will changing it to uint32 affect XPU?
stride_bn, stride_cm, stride_cn, stride_tl, stride_el, slice_a_size, slice_c_size, # Meta-parameters num_slice_a: tl.constexpr, num_slice_c: tl.constexpr, top_k: tl.constexpr, MUL_ROUTED_WEIGHT: tl.constexpr, USE_B_L2_CACHE: tl.constexpr, # new, enable .ca load for B...
@@ -95,19 +94,19 @@ def _fused_moe_lora_kernel( pid = tl.program_id(axis=0) slice_id = tl.program_id(axis=1) lora_idx = tl.program_id(axis=2) - lora_id = tl.load(lora_ids + lora_idx) - if lora_id == -1: - # Early exit for the no-lora case. + max_loras_u32 = tl.full((), MAX_LORAS_TOTAL, ...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.143
question
51
51
51
false
[lora/moe] Improve fused MoE‑LoRA kernel indexing and memory access
32,770
vllm-project/vllm
71,895
Python
jeejeelee
cwazai
do_not_specialize=[ "num_valid_tokens", "EM", "stride_tl", "stride_el", "slice_a_size", "slice_c_size", ] ) def _fused_moe_lora_kernel( a_ptr, b_ptr, c_ptr, topk_weights_ptr, sorted_token_ids_ptr, expert_ids_ptr, num_tokens_post_padded_...
why do we need this new variable? please define it. We have PR to update it to be the `num-active-lora` https://github.com/vllm-project/vllm/pull/32005. cc: @yugong333
do_not_specialize=[ "num_valid_tokens", "EM", "stride_tl", "stride_el", "slice_a_size", "slice_c_size", ] ) def _fused_moe_lora_kernel( a_ptr, b_ptr, c_ptr, topk_weights_ptr, sorted_token_ids_ptr, expert_ids_ptr, num_tokens_post_padded_...
@@ -62,6 +62,7 @@ def _fused_moe_lora_kernel( num_experts, lora_ids, adapter_enabled, + MAX_LORAS_TOTAL, # <<< PR2: new, used for masks when grid axis-2 != max_loras
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.5
question
168
51
51
false
[lora/moe] Improve fused MoE‑LoRA kernel indexing and memory access
32,770
vllm-project/vllm
71,895
Python
dcmaddix
cwazai
pid_m_n = pid // SPLIT_K num_pid_m = tl.cdiv(EM, BLOCK_SIZE_M) num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) num_pid_in_group = GROUP_SIZE_M * num_pid_n group_id = pid_m_n // num_pid_in_group first_pid_m = group_id * GROUP_SIZE_M group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M) pid_m = ...
nice! this is cleaner and can also be updated in `fused_moe` kernel in follow-up PR. Why do we not see gains from it though?
return grid_k = tl.cdiv(K, BLOCK_SIZE_K * SPLIT_K) # calculate pid_m,pid_n pid_sk = pid % SPLIT_K pid_m_n = pid // SPLIT_K num_pid_m = tl.cdiv(EM, BLOCK_SIZE_M) num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) num_pid_in_group = GROUP_SIZE_M * num_pid_n group_id = pid_m_n // num_pid_in_gro...
@@ -133,7 +136,8 @@ def _fused_moe_lora_kernel( cur_b_ptr = tl.load(b_ptr + slice_id).to(tl.pointer_type(c_ptr.dtype.element_ty)) cur_c_ptr = c_ptr + (slice_id % num_slice_c) * slice_c_size - offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(tl.int64)) % N + # remove modulo wrap-around +...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.714
question
124
51
51
false
[lora/moe] Improve fused MoE‑LoRA kernel indexing and memory access
32,770
vllm-project/vllm
71,895
Python
dcmaddix
cwazai
group_size_m: int, num_warps: int, num_stages: int, split_k: int, mul_routed_weight: bool = False, use_gdc: bool = False, ) -> None: w1_lora_a_stacked = lora_a_stacked[0] shrink_config = { "BLOCK_SIZE_M": block_size_m, "BLOCK_SIZE_N": block_size_n, "BLOCK_SIZE_K":...
should it be `+1`? please check https://github.com/vllm-project/vllm/pull/32277
## adding for kernel device: torch.device, N: int, M: int, EM: int, K: int, num_tokens: int, num_experts: int, num_slices: int, block_size_m: int, block_size_n: int, block_size_k: int, group_size_m: int, num_warps: int, num_stages: int, split_k: int, m...
@@ -247,13 +256,14 @@ def _fused_moe_lora_shrink( } b_ptr = _get_ptr(lora_a_stacked, device) + max_loras_total = sorted_token_ids.shape[0] # <<< PR2: new
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.571
suggestion
79
51
51
false
[lora/moe] Improve fused MoE‑LoRA kernel indexing and memory access
32,770
vllm-project/vllm
71,895
Python
dcmaddix
cwazai
* triton.cdiv(EM, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]), len(lora_a_stacked), ## max_loras + 1 to handle the no-lora case (lora_id == -1) lora_a_stacked[0].shape[0] + 1, ) _fused_moe_lora_kernel[grid]( qcurr_hidden_states, b_ptr, ...
do we need this and `max_loras`? the naming is confusing.
"GROUP_SIZE_M": group_size_m, "num_warps": num_warps, "num_stages": num_stages, "SPLIT_K": split_k, "USE_GDC": use_gdc, "launch_pdl": use_gdc, # triton kernel metadata } b_ptr = _get_ptr(lora_a_stacked, device) grid = lambda META: ( split_k ...
@@ -270,6 +280,7 @@ def _fused_moe_lora_shrink( num_experts, lora_ids, adapter_enabled, + max_loras_total, # new
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.357
question
57
51
51
false
[lora/moe] Improve fused MoE‑LoRA kernel indexing and memory access
32,770
vllm-project/vllm
71,895
Python
dcmaddix
cwazai
a_intermediate_cache1 = a_intermediate_cache1.view( -1, a_intermediate_cache1.shape[3] ) expand_config = { "BLOCK_SIZE_M": block_size_m, "BLOCK_SIZE_N": block_size_n, "BLOCK_SIZE_K": block_size_k, "GROUP_SIZE_M": group_size_m, "num_warps": num_warps, ...
what effect does this `split_k` change have and is it needed?
group_size_m: int, num_warps: int, num_stages: int, split_k: int, mul_routed_weight: bool = False, offset: int = 0, use_gdc: bool = False, ) -> None: b_ptr = _get_ptr(lora_b_stacked, device) K = max_lora_rank N = w1_output_dim_size w1_lora_b_stacked = lora_b_stacked[0] ...
@@ -350,10 +362,12 @@ def _fused_moe_lora_expand( "launch_pdl": use_gdc, # triton kernel metadata } + max_loras_total = sorted_token_ids.shape[0] # <<< PR2: new + grid = lambda META: ( - triton.cdiv(EM, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]), + split_k * tri...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.571
question
61
51
51
false
[lora/moe] Improve fused MoE‑LoRA kernel indexing and memory access
32,770
vllm-project/vllm
71,895
Python
dcmaddix
cwazai
MUL_ROUTED_WEIGHT: tl.constexpr, BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, GROUP_SIZE_M: tl.constexpr, SPLIT_K: tl.constexpr, USE_GDC: tl.constexpr, launch_pdl: tl.constexpr, IS_PRIMARY: tl.constexpr, ): pid = tl.program_id(axis=0) sl...
why not directly pass `MAX_LORAS`?
top_k: tl.constexpr, MUL_ROUTED_WEIGHT: tl.constexpr, USE_B_L2_CACHE: tl.constexpr, # new, enable .ca load for B BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, GROUP_SIZE_M: tl.constexpr, SPLIT_K: tl.constexpr, USE_GDC: tl.constexpr, launch_p...
@@ -104,7 +106,10 @@ def _fused_moe_lora_kernel( if moe_enabled == 0: # Early exit for the no moe lora case. return - max_loras = tl.num_programs(axis=2) + + max_loras = MAX_LORAS_TOTAL # <<< : was tl.num_programs(axis=2)
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.5
question
34
51
51
false
[lora/moe] Improve fused MoE‑LoRA kernel indexing and memory access
32,770
vllm-project/vllm
71,895
Python
dcmaddix
cwazai
expand_config = { "BLOCK_SIZE_M": block_size_m, "BLOCK_SIZE_N": block_size_n, "BLOCK_SIZE_K": block_size_k, "GROUP_SIZE_M": group_size_m, "num_warps": num_warps, "num_stages": num_stages, "SPLIT_K": split_k, # Set split_k = 1 for expand calls "USE_GDC...
Let's also please revert this change from this PR. I think this will break cudagraph. It is handled in this PR: https://github.com/vllm-project/vllm/pull/32005.
mul_routed_weight: bool = False, offset: int = 0, use_gdc: bool = False, ) -> None: b_ptr = _get_ptr(lora_b_stacked, device) K = max_lora_rank N = w1_output_dim_size w1_lora_b_stacked = lora_b_stacked[0] a_intermediate_cache1 = a_intermediate_cache1.view( -1, a_intermediate_cac...
@@ -350,10 +364,12 @@ def _fused_moe_lora_expand( "launch_pdl": use_gdc, # triton kernel metadata } + max_loras_total = sorted_token_ids.shape[0] # <<< PR2: new + grid = lambda META: ( - triton.cdiv(EM, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]), + split_k * tri...
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.786
bug
161
51
51
false
[lora/moe] Improve fused MoE‑LoRA kernel indexing and memory access
32,770
vllm-project/vllm
71,895
Python
dcmaddix
cwazai
GROUP_SIZE_M: tl.constexpr, SPLIT_K: tl.constexpr, USE_GDC: tl.constexpr, launch_pdl: tl.constexpr, IS_PRIMARY: tl.constexpr, ): pid = tl.program_id(axis=0) slice_id = tl.program_id(axis=1) lora_idx = tl.program_id(axis=2) lora_id = tl.load(lora_ids + lora_idx) if lora_id == -1:...
Add comment on why we need to add this case. Technically since you are passing it correctly it shouldn't go in here but ok to have this check.
BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, GROUP_SIZE_M: tl.constexpr, SPLIT_K: tl.constexpr, USE_GDC: tl.constexpr, launch_pdl: tl.constexpr, IS_PRIMARY: tl.constexpr, ): pid = tl.program_id(axis=0) slice_id = tl.program_id(axis=1) lora_idx = tl.program_id(axis=2) ...
@@ -104,7 +106,9 @@ def _fused_moe_lora_kernel( if moe_enabled == 0: # Early exit for the no moe lora case. return - max_loras = tl.num_programs(axis=2) + + if lora_id >= max_loras:
vllm/lora/ops/triton_ops/fused_moe_lora_op.py
26
Python
0.5
suggestion
142
51
51
false
[lora/moe] Improve fused MoE‑LoRA kernel indexing and memory access
32,770
vllm-project/vllm
71,895
Python
dcmaddix
cwazai
return self.uniform_decode_cudagraph_sizes.get(num_tokens) return self.cudagraph_sizes.get(num_tokens) def capture_graph( self, num_tokens: int, capture_cudagraph_mode: CUDAGraphMode, model: nn.Module, input_buffers: InputBuffers, mrope_positions:...
Better to use assert here since it's a program error
) -> int | None: if uniform_decode and self.uniform_decode_cudagraph_sizes: return self.uniform_decode_cudagraph_sizes.get(num_tokens) return self.cudagraph_sizes.get(num_tokens) def capture_graph( self, num_tokens: int, capture_cg_mode: CUDAGraphMode, ...
@@ -53,28 +67,44 @@ def needs_capture(self) -> bool: def get_cudagraph_size( self, - num_tokens_after_padding: int, - num_tokens_per_request: Iterable[int], + num_tokens: int, + uniform_decode: bool = False, ) -> int | None: - return get_cudagraph_size( - ...
vllm/v1/worker/gpu/cudagraph_utils.py
26
Python
0.643
suggestion
52
51
51
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
class CudaGraphManager: def __init__(self, vllm_config: VllmConfig, uses_mrope: bool, device: torch.device): self.vllm_config = vllm_config self.scheduler_config = vllm_config.scheduler_config self.uses_mrope = uses_mrope self.device = device self.max_model_len = vllm_confi...
I think we could eliminate this and just use non-emptiness of `self.uniform_decode_cudagraph_sizes`?
from vllm.v1.worker.gpu.input_batch import InputBuffers class CudaGraphManager: def __init__(self, vllm_config: VllmConfig, uses_mrope: bool, device: torch.device): self.vllm_config = vllm_config self.scheduler_config = vllm_config.scheduler_config self.uses_mrope = uses_mrope self...
@@ -34,14 +35,27 @@ def __init__(self, vllm_config: VllmConfig, uses_mrope: bool, device: torch.devi self.max_num_reqs = self.scheduler_config.max_num_seqs self.max_num_tokens = self.scheduler_config.max_num_batched_tokens self.dp_size = vllm_config.parallel_config.data_parallel_size + + ...
vllm/v1/worker/gpu/cudagraph_utils.py
26
Python
0.714
question
100
51
51
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.worker.gpu.attn_utils import ( build_attn_metadata, build_slot_mappings_by_layer, ) from vllm.v1.worker.gpu.block_table import BlockTables from vllm.v1.worker.gpu.dp_utils import make_num_tokens_across_dp from vllm.v1.worker.gpu.input_batch impor...
nit ```suggestion self.uniform_decode_query_len = 1 spec_config = vllm_config.speculative_config if spec_config is not None: self.uniform_decode_query_len += spec_config.num_speculative_tokens ```
from vllm.v1.attention.backend import AttentionMetadataBuilder from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.worker.gpu.attn_utils import ( build_attn_metadata, build_slot_mappings_by_layer, prepare_dcp_local_seq_lens, ) from vllm.v1.worker.gpu.block_table import BlockTables from vllm.v1...
@@ -34,14 +35,27 @@ def __init__(self, vllm_config: VllmConfig, uses_mrope: bool, device: torch.devi self.max_num_reqs = self.scheduler_config.max_num_seqs self.max_num_tokens = self.scheduler_config.max_num_batched_tokens self.dp_size = vllm_config.parallel_config.data_parallel_size + + ...
vllm/v1/worker/gpu/cudagraph_utils.py
26
Python
1
suggestion
232
51
51
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
def get_cudagraph_and_dp_padding( num_tokens: int, cudagraph_size: int | None, cudagraph_runtime_mode: int, dp_size: int, dp_rank: int, ) -> tuple[int, torch.Tensor | None, int]: if dp_size == 1: if cudagraph_size is not None: return cudagraph_size, None, cudagraph_runtime_...
```suggestion num_tokens_across_dp, cudagraph_size_across_dp, cudagraph_mode_across_dp = ( get_batch_metadata_across_dp( num_tokens, cudagraph_size, cudagraph_runtime_mode, dp_size, dp_rank ) ) ```
def get_cudagraph_and_dp_padding( num_tokens: int, cudagraph_size: int | None, cudagraph_runtime_mode: int, dp_size: int, dp_rank: int, ) -> tuple[int, torch.Tensor | None, int]: if dp_size == 1: if cudagraph_size is not None: return cudagraph_size, None, cudagraph_runtime_...
@@ -13,48 +13,67 @@ def make_num_tokens_across_dp(dp_size: int, num_tokens: int) -> torch.Tensor | N def get_batch_metadata_across_dp( - num_tokens: int, cudagraph_size: int, dp_size: int, dp_rank: int -) -> tuple[torch.Tensor, torch.Tensor]: + num_tokens: int, + cudagraph_size: int, + cudagraph_runtim...
vllm/v1/worker/gpu/dp_utils.py
26
Python
1
performance
233
50
48
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
# Prepare the inputs for the decode steps. prepare_eagle_decode( draft_tokens, hidden_states, last_token_indices, input_batch.seq_lens, num_rejected, self.input_buffers, self.hidden_states, self.max_model_len...
I don't think this assert is needed?
input_batch.seq_lens, num_rejected, self.input_buffers, self.hidden_states, self.max_model_len, self.max_num_reqs, ) query_start_loc = self.input_buffers.query_start_loc[: num_reqs + 1] slot_mappings = self.block_tables.comp...
@@ -283,12 +299,19 @@ def propose( ) cudagraph_size = self.cudagraph_manager.get_cudagraph_size(num_reqs) - if cudagraph_size is not None: - # Run CUDA graph. + cudagraph_mode = ( + self.cudagraph_manager.cudagraph_mode + if cudagraph_size is not None +...
vllm/v1/worker/gpu/spec_decode/eagle.py
26
Python
0.071
question
36
51
51
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
:, :num_tokens_after_padding ] if not skip_attn_for_dummy_run: self.prepare_dummy_attn_metadata(input_batch) # FIXME(woosuk): Fix warmup for LoRA. # Run model. if cudagraph_runtime_mode == CUDAGraphMode.FULL: # Use ...
these have defaults ```suggestion ```
num_tokens=scheduler_output.total_num_scheduled_tokens, max_query_len=max(scheduler_output.num_scheduled_tokens.values()), ) ) # DP sync: num_tokens + cudagraph_size + cudagraph_mode num_tokens_after_padding, num_tokens_across_dp, synced_cudagraph_mod...
@@ -853,27 +890,35 @@ def execute_model( # FIXME(woosuk): Fix warmup for LoRA. # Run model. - if use_cudagraph: - # Run CUDA graph. + if cudagraph_runtime_mode == CUDAGraphMode.FULL: + # Use explicit cudagraph replay for FULL mode. # NOTE(woosuk):...
vllm/v1/worker/gpu/model_runner.py
26
Python
0.786
suggestion
37
51
51
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
self.free_states(scheduler_output) self.add_requests(scheduler_output) self.update_requests(scheduler_output) self.block_tables.apply_staged_writes() if scheduler_output.total_num_scheduled_tokens == 0: # No need to run the model. ...
```suggestion num_tokens_after_padding, num_tokens_across_dp, synced_cudagraph_mode = ( get_cudagraph_and_dp_padding( scheduler_output.total_num_scheduled_tokens, local_cudagraph_size, local_cudagraph_mode.value, self.parallel_config.da...
# Update the number of computed tokens. post_update( input_batch.idx_mapping, self.req_states.num_computed_tokens.gpu, self.req_states.last_sampled_tokens, self.sampler.penalties_state.output_bin_counts, sampled_tokens, num_sampled,...
@@ -791,19 +823,24 @@ def execute_model( empty_output = self.kv_connector.no_forward(scheduler_output) return empty_output - # Get the CUDA graph size. None means no CUDA graph is used. - cudagraph_size = self.cudagraph_manager.get_cudagraph_size( + # Get local c...
vllm/v1/worker/gpu/model_runner.py
26
Python
1
suggestion
422
51
51
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
self.speculator.run_model( self.max_num_tokens, attn_metadata=None, slot_mappings=None, num_tokens_across_dp=num_tokens_across_dp, ) torch.cuda.synchronize() del hidden_states, sample_hidden_states gc.collect...
Could you move this method into `cudagraph_utils.py` / `CudaGraphManager`. Also I don't think it needs to take scheduler_output, we can pass some of these things directly, such as num_reqs. With a recent PR merged, we have `max_query_len` here too (same as max_num_scheduled_tokens)
self.execute_model( dummy_scheduler_output, intermediate_tensors=intermediate_tensors, dummy_run=True, skip_attn_for_dummy_run=skip_attn, ) self.kv_connector.set_disabled(False) # Non-last PP ranks don't produce output for sampling. ...
@@ -355,6 +356,36 @@ def _get_num_input_tokens(self, num_scheduled_tokens: int) -> int: # SP is not supported yet. return num_scheduled_tokens + def _get_cudagraph_runtime_mode( + self, + scheduler_output: SchedulerOutput, + ) -> tuple[CUDAGraphMode, int | None]:
vllm/v1/worker/gpu/model_runner.py
26
Python
0.786
refactor
283
51
51
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
k: v for k, v in cudagraph_sizes.items() if v <= max_num_tokens and v >= uniform_decode_query_len } return cudagraph_sizes, uniform_decode_cudagraph_sizes def capture_graphs( cudagraph_sizes: dict[int, int], device: torch.device, capture_fn: Callable, ca...
```suggestion size, capture_cudagraph_mode, **capture_kwargs ```
def capture_graphs( cudagraph_sizes: dict[int, int], device: torch.device, capture_fn: Callable, capture_cudagraph_mode: CUDAGraphMode, desc: str = "Capturing CUDA graphs", **capture_kwargs, ) -> None: # Capture larger graphs first. sizes_to_capture = sorted(set(cudagraph_sizes.values())...
@@ -168,68 +311,57 @@ def get_cudagraph_sizes( max_num_reqs: int, max_num_tokens: int, cudagraph_mode: CUDAGraphMode, -) -> dict[int, int]: - if not cudagraph_mode.has_full_cudagraphs(): - return {} + uniform_decode_query_len: int = 1, + uniform_decode_cudagraph: bool = False, +) -> tuple...
vllm/v1/worker/gpu/cudagraph_utils.py
26
Python
0.857
suggestion
80
51
51
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
if mixed_mode != CUDAGraphMode.NONE: capture_graphs( cudagraph_sizes=self.cudagraph_sizes, capture_cudagraph_mode=mixed_mode, desc=f"Capturing CUDA graphs (mixed, {mixed_mode.name})", uniform_decode=False, **common_kwarg...
```suggestion self, num_reqs: int, num_tokens: int, max_query_len: int ```
capture_graphs( cudagraph_sizes=self.cudagraph_sizes, capture_cudagraph_mode=mixed_mode, desc=f"Capturing CUDA graphs (mixed, {mixed_mode.name})", uniform_decode=False, **common_kwargs, ) # Phase 2: Capture ...
@@ -142,22 +239,68 @@ def capture( block_tables: BlockTables, attn_metadata_builders: list[AttentionMetadataBuilder], kv_cache_config: KVCacheConfig, + has_lora: bool = False, ) -> None: - capture_graphs( - self.cudagraph_sizes, - self.device, - ...
vllm/v1/worker/gpu/cudagraph_utils.py
26
Python
0.857
suggestion
82
51
51
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
# Phase 2: Capture FULL graphs for uniform decode batches if needed. # This is only needed if we use a separate routine for decode batches # and the decode_mode is FULL. if self.uniform_decode_cudagraph_sizes: capture_graphs( cudagraph_sizes=self.uniform_deco...
```suggestion num_tokens, uniform_decode=is_uniform_decode ```
# Phase 2: Capture FULL graphs for uniform decode batches if needed. # This is only needed if we use a separate routine for decode batches # and the decode_mode is FULL. if self.uniform_decode_cudagraph_sizes: capture_graphs( cudagraph_sizes=self.uniform_decod...
@@ -142,22 +239,68 @@ def capture( block_tables: BlockTables, attn_metadata_builders: list[AttentionMetadataBuilder], kv_cache_config: KVCacheConfig, + has_lora: bool = False, ) -> None: - capture_graphs( - self.cudagraph_sizes, - self.device, - ...
vllm/v1/worker/gpu/cudagraph_utils.py
26
Python
0.857
suggestion
74
51
51
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
hidden_states = model( input_ids=input_ids, positions=positions, inputs_embeds=inputs_embeds, ) assert self.hidden_states is not None self.hidden_states[:num_tokens] = hidden_states self.graphs[num_tokens] = graph ...
```suggestion num_tokens=num_tokens, has_lora=has_lora ```
torch.cuda.graph(graph, self.pool), ): hidden_states = model( input_ids=input_ids, positions=positions, inputs_embeds=inputs_embeds, ) assert self.hidden_states is not None self.hidden_states[:num_tokens]...
@@ -129,9 +188,47 @@ def capture_graph( positions=positions, inputs_embeds=inputs_embeds, ) + assert self.hidden_states is not None self.hidden_states[:num_tokens] = hidden_states self.graphs[num_tokens] = graph + def _capture_piecewis...
vllm/v1/worker/gpu/cudagraph_utils.py
26
Python
0.857
suggestion
70
51
51
false
[Model Runner V2] support piecewise & mixed cudagraph
32,771
vllm-project/vllm
71,895
Python
njhill
izhuhaoran
num_tokens_across_sp_cpu = num_tokens_across_sp_cpu.repeat_interleave(sp_size) return torch.cumsum(num_tokens_across_sp_cpu, dim=0) @dataclass class ForwardContext: # copy from vllm_config.compilation_config.static_forward_context no_compile_layers: dict[str, Any] attn_metadata: dict[str, ...
@ProExpertProg I could try to clean up how `no_compile_layers` works (it has both attention layers and MOE layers) by instead: - making it a list - popping from it instead of the new `remaining_moe_layers` list - deleting the "string" arguments to the moe_forward / moe_forward_shared operators (and maybe unified_attent...
num_tokens_across_sp_cpu = num_tokens_across_sp_cpu.repeat_interleave(sp_size) return torch.cumsum(num_tokens_across_sp_cpu, dim=0) @dataclass class ForwardContext: # copy from vllm_config.compilation_config.static_forward_context no_compile_layers: dict[str, Any] attn_metadata: dict[str, ...
@@ -188,6 +188,24 @@ def cu_tokens_across_sp(self, sp_size: int) -> torch.Tensor: class ForwardContext: # copy from vllm_config.compilation_config.static_forward_context no_compile_layers: dict[str, Any] + # For torch.compile cold start times, we need to avoid hard-coding + # any strings into the graph...
vllm/forward_context.py
26
Python
0.857
refactor
501
51
51
false
[torch.compile] Improve Cold Start for MoEs
32,805
vllm-project/vllm
71,895
Python
zou3519
zou3519
cudagraph_runtime_mode=cudagraph_runtime_mode, batch_descriptor=batch_descriptor, ubatch_slices=ubatch_slices, skip_compiled=skip_compiled, additional_kwargs=additional_kwargs or {}, ) @contextmanager def override_forward_context(forward_context: ForwardContext | None): ...
do we have profiling to show how long it takes? doing it in every forward can be time-consuming. maybe we can keep `all_moe_layers` and only increase a `current_index` inside forward context.
) return _forward_context def is_forward_context_available() -> bool: return _forward_context is not None def create_forward_context( attn_metadata: Any, vllm_config: VllmConfig, virtual_engine: int = 0, dp_metadata: DPMetadata | None = None, cudagraph_runtime_mode: CUDAGraphMode = C...
@@ -245,8 +269,17 @@ def create_forward_context( additional_kwargs: dict[str, Any] | None = None, skip_compiled: bool = False, ): + no_compile_layers = vllm_config.compilation_config.static_forward_context + from vllm.model_executor.layers.fused_moe.layer import FusedMoE + + remaining_moe_layers = [...
vllm/forward_context.py
26
Python
0.5
question
194
51
51
false
[torch.compile] Improve Cold Start for MoEs
32,805
vllm-project/vllm
71,895
Python
youkaichao
zou3519
#include <torch/all.h> #include <torch/cuda.h> #include <cuda_runtime.h> // This function assumes that `cpu_tensor` is a CPU tensor allocated with pinned // memory, and that UVA (Unified Virtual Addressing) is enabled. torch::Tensor get_cuda_view_from_cpu_tensor(torch::Tensor& cpu_tensor) { TORCH_CHECK(cpu_tensor.de...
it seems to mix two functionalities in one function. I'd prefer to separate them. keep the original `get_cuda_view_from_cpu_tensor` untouched, and have another `alloc_pinned_cpu_tensor_and_get_cuda_view(num_bytes)` function.
#include <torch/all.h> #include <torch/cuda.h> #include <cuda_runtime.h> // This function assumes that `cpu_tensor` is a CPU tensor, // and that UVA (Unified Virtual Addressing) is enabled. torch::Tensor get_cuda_view_from_cpu_tensor(torch::Tensor& cpu_tensor) { TORCH_CHECK(cpu_tensor.device().is_cpu(), "Input tenso...
@@ -1,34 +1,58 @@ #include <torch/all.h> #include <torch/cuda.h> #include <cuda_runtime.h> +#include <sys/mman.h> -// This function assumes that `cpu_tensor` is a CPU tensor allocated with pinned -// memory, and that UVA (Unified Virtual Addressing) is enabled. +// This function assumes that `cpu_tensor` is a CPU ...
csrc/cuda_view.cu
7
CUDA
0.786
suggestion
224
32
32
false
[Feature] Support CPU Offloading without Pytorch Pinned Memory that leads to doubled allocation
32,993
vllm-project/vllm
71,895
Python
youkaichao
wzhao18
#include <torch/all.h> #include <torch/cuda.h> #include <cuda_runtime.h> // This function assumes that `cpu_tensor` is a CPU tensor allocated with pinned // memory, and that UVA (Unified Virtual Addressing) is enabled. torch::Tensor get_cuda_view_from_cpu_tensor(torch::Tensor& cpu_tensor) { TORCH_CHECK(cpu_tensor.de...
is `cudaHostAlloc` enough? do we need to use system mmap and then use `cudaHostRegister`?
void* device_ptr = nullptr; cudaError_t err = cudaHostGetDevicePointer(&device_ptr, host_ptr, 0); TORCH_CHECK(err == cudaSuccess, "cudaHostGetDevicePointer failed: ", cudaGetErrorString(err)); return torch::from_blob( device_ptr, cpu_tensor.sizes(), cpu_tensor.strides(), ...
@@ -1,34 +1,58 @@ #include <torch/all.h> #include <torch/cuda.h> #include <cuda_runtime.h> +#include <sys/mman.h> -// This function assumes that `cpu_tensor` is a CPU tensor allocated with pinned -// memory, and that UVA (Unified Virtual Addressing) is enabled. +// This function assumes that `cpu_tensor` is a CPU ...
csrc/cuda_view.cu
26
CUDA
0.571
question
89
35
41
false
[Feature] Support CPU Offloading without Pytorch Pinned Memory that leads to doubled allocation
32,993
vllm-project/vllm
71,895
Python
youkaichao
wzhao18
# with quantization methods and attention backends. "VLLM_LOG_MODEL_INSPECTION": lambda: bool( int(os.getenv("VLLM_LOG_MODEL_INSPECTION", "0")) ), # Debug logging for --enable-mfu-metrics "VLLM_DEBUG_MFU_METRICS": lambda: bool( int(os.getenv("VLLM_DEBUG_MFU_METRICS", "0")) ), ...
nit: Since we also do kv offloading, it might be better to explicitly say weight offloading
# Allows viewing and setting breakpoints in Inductor's code output files. "VLLM_COMPILE_CACHE_SAVE_FORMAT": env_with_choices( "VLLM_COMPILE_CACHE_SAVE_FORMAT", "binary", ["binary", "unpacked"] ), # Flag to enable v2 model runner. "VLLM_USE_V2_MODEL_RUNNER": lambda: bool( int(os.g...
@@ -1532,6 +1534,14 @@ def _get_or_set_default() -> str: "VLLM_DEBUG_MFU_METRICS": lambda: bool( int(os.getenv("VLLM_DEBUG_MFU_METRICS", "0")) ), + # Disable using pytorch's pin memory for CPU offloading. + "VLLM_OFFLOADING_DISABLE_PIN_MEMORY": lambda: bool( + int(os.getenv("VLLM_OFFLOAD...
vllm/envs.py
26
Python
0.357
suggestion
91
51
51
false
[Feature] Support CPU Offloading without Pytorch Pinned Memory that leads to doubled allocation
32,993
vllm-project/vllm
71,895
Python
mgoin
wzhao18
Use tags=["scheduling"] to resume from level 0 sleep. """ self.llm_engine.wake_up(tags) def get_metrics(self) -> list["Metric"]: """Return a snapshot of aggregated metrics from Prometheus. Returns: A `MetricSnapshot` instance capturing the current state ...
what's the behavior of level 0? Will this cause any breakage if user use level 0 before?
return self.llm_engine.reset_prefix_cache( reset_running_requests, reset_connector ) def sleep(self, level: int = 1): """ Put the engine to sleep. The engine should not process any requests. The caller should guarantee that no requests are being processed ...
@@ -1604,19 +1665,22 @@ def sleep(self, level: int = 1): during the sleep period, before `wake_up` is called. Args: - level: The sleep level. Level 1 sleep will offload the model - weights and discard the kv cache. The content of kv cache - is forgotten. Leve...
vllm/entrypoints/llm.py
26
Python
0.357
question
89
51
51
false
[Core] Add sleep level 0 mode with enqueue/wait pattern
33,195
vllm-project/vllm
71,895
Python
houseroad
jaewonlee-fb
def enqueue( self, prompts: PromptType | Sequence[PromptType], sampling_params: SamplingParams | Sequence[SamplingParams] | None = None, lora_request: list[LoRARequest] | LoRARequest | None = None, priority: list[int] | None = None, use_tqdm: bool | Callable[..., tqdm...
where do we expect to call this function?
generated completions in the same order as the input prompts. """ model_config = self.model_config runner_type = model_config.runner_type if runner_type != "generate": raise ValueError( "LLM.generate() is only supported for generative models. " ...
@@ -420,10 +421,53 @@ def generate( "generative model." ) + # Use enqueue + wait_for_completion pattern + self.enqueue( + prompts=prompts, + sampling_params=sampling_params, + lora_request=lora_request, + priority=priority, + ...
vllm/entrypoints/llm.py
26
Python
0.071
question
41
51
51
false
[Core] Add sleep level 0 mode with enqueue/wait pattern
33,195
vllm-project/vllm
71,895
Python
houseroad
jaewonlee-fb
return output assert isinstance(output, IntermediateTensors) parallel_config = self.vllm_config.parallel_config assert ( parallel_config.distributed_executor_backend != "external_launcher" and not get_pp_group().is_last_rank ) get_pp_grou...
would be good to extract all of this into a util method rather than inline in the worker
and not get_pp_group().is_last_rank ) get_pp_group().send_tensor_dict( output.tensors, all_gather_group=get_tp_group(), all_gather_tensors=all_gather_tensors, ) return None def take_draft_token_ids(self) -> DraftTokenIds | None: ...
@@ -653,17 +647,73 @@ def execute_model( def take_draft_token_ids(self) -> DraftTokenIds | None: return self.model_runner.take_draft_token_ids() - def profile(self, is_start: bool = True): - if self.profiler is None: + def profile(self, is_start: bool = True, profile_prefix: str | None = No...
vllm/v1/worker/gpu_worker.py
26
Python
0.357
refactor
88
51
51
false
[Core] Profiler improvements and lazy initialization
33,198
vllm-project/vllm
71,895
Python
njhill
jaewonlee-fb
activities=["CPU", "CUDA"], ) logger.debug( "Starting torch profiler with trace name: %s", trace_name ) elif self.profiler_config.profiler == "cuda": self.profiler = CudaProfil...
shall we throw the exception here? Lazy create, then lazy throw?
# Generate the trace name by combining prefix with comprehensive rank suffix from vllm.distributed.utils import get_worker_rank_suffix rank_suffix = get_worker_rank_suffix(global_rank=self.rank) # Build the full trace name if profile_prefix: ...
@@ -659,17 +653,52 @@ def execute_model( def take_draft_token_ids(self) -> DraftTokenIds | None: return self.model_runner.take_draft_token_ids() - def profile(self, is_start: bool = True): - if self.profiler is None: + def profile(self, is_start: bool = True, profile_prefix: str | None = No...
vllm/v1/worker/gpu_worker.py
26
Python
0.429
question
65
51
51
false
[Core] Profiler improvements and lazy initialization
33,198
vllm-project/vllm
71,895
Python
houseroad
jaewonlee-fb
torch.set_float32_matmul_precision(precision) # Buffers saved before sleep self._sleep_saved_buffers: dict[str, torch.Tensor] = {} # Torch/CUDA profiler. Enabled and configured through profiler_config. # Profiler wrapper is created lazily in profile() when start is called, ...
I mean, not raise issue here, but raise when we lazily kick it off?
# configure float32 matmul precision according to vLLM env. precision = envs.VLLM_FLOAT32_MATMUL_PRECISION torch.set_float32_matmul_precision(precision) # Buffers saved before sleep self._sleep_saved_buffers: dict[str, torch.Tensor] = {} # Weight transfer engine (initi...
@@ -90,20 +90,14 @@ def __init__( self._sleep_saved_buffers: dict[str, torch.Tensor] = {} # Torch/CUDA profiler. Enabled and configured through profiler_config. + # Profiler wrapper is created lazily in profile() when start is called, + # so we have all the information needed for prope...
vllm/v1/worker/gpu_worker.py
26
Python
0.143
question
67
51
51
false
[Core] Profiler improvements and lazy initialization
33,198
vllm-project/vllm
71,895
Python
houseroad
jaewonlee-fb
fmaxf(s_max_vals[start], s_max_vals[j + warp_size]); } warpReduceMaxSpecialized(s_max_vals, start, thread_in_warp, min(warp_end - warp_start, warp_size)); } } __syncthreads(); if (thread_in_group == 0 && thread_offset < thread_end) { ...
Instead of this, could we just pass the outer scale stride as a parameter? We can read that directly from the torch tensor and don't need to template-specialize the kernels
fmaxf(s_max_vals[start], s_max_vals[j + warp_size]); } warpReduceMaxSpecialized(s_max_vals, start, thread_in_warp, min(warp_end - warp_start, warp_size)); } } __syncthreads(); if (thread_in_group == 0 && thread_offset < thread_end) { ...
@@ -133,7 +133,12 @@ __device__ void compute_dynamic_per_token_scales( scale = max(scale / qmax, min_scaling_factor<scalar_out_t>::val()); // Global output store if constexpr (is_scale_transposed) { - all_token_scales[(threadIdx.x / threads_per_group) * gridDim.x + + int64_t const sca...
csrc/quantization/fused_kernels/layernorm_utils.cuh
26
CUDA
0.5
suggestion
172
51
51
false
[Bugfix] Fix quant RMS norm fusion for quantization with TMA-aligned scales
33,255
vllm-project/vllm
71,895
Python
ProExpertProg
ElizaWszola
x, weight, EPS, quant_dtype, scale_ub, residual ) return out, scales, residual def ops_impl( weight: torch.Tensor, x: torch.Tensor, quant_dtype: torch.dtype, residual: torch.Tensor | None, scale_ub: torch.Tensor | None, group_size: list[int] | None, tma_alignment: i...
```suggestion @pytest.mark.parametrize("group_size, tma_alignment", [ (None, 0), *itertools.product(GROUP_SIZES, TMA_ALIGNMENTS) ) ```
else: out, scales = ops.rms_norm_dynamic_per_token_quant( x, weight, EPS, quant_dtype, scale_ub, residual ) return out, scales, residual def ops_impl( weight: torch.Tensor, x: torch.Tensor, quant_dtype: torch.dtype, residual: torch.Tensor | None, scale_ub: torch...
@@ -144,6 +155,7 @@ def ops_impl( @pytest.mark.parametrize("dtype", DTYPES) @pytest.mark.parametrize("quant_dtype", QUANT_DTYPES) @pytest.mark.parametrize("group_size", GROUP_SIZES) +@pytest.mark.parametrize("tma_alignment", TMA_ALIGNMENTS)
tests/kernels/core/test_fused_quant_layernorm.py
26
Python
1
suggestion
142
51
51
false
[Bugfix] Fix quant RMS norm fusion for quantization with TMA-aligned scales
33,255
vllm-project/vllm
71,895
Python
ProExpertProg
ElizaWszola
quant_key_group_shape = self.quant_key.scale.group_shape if quant_key_group_shape == GroupShape.PER_TOKEN: return self.QUANT_OP( # type: ignore[no-any-return] x=input, quant_dtype=self.quant_key.dtype, scale=scale, ) else: ...
Add a comment that scale must be passed for tma_aligned and it only supports the custom op matching?
quant_key_group_shape = self.quant_key.scale.group_shape if quant_key_group_shape == GroupShape.PER_TOKEN: return self.QUANT_OP( # type: ignore[no-any-return] x=input, quant_dtype=self.quant_key.dtype, scale=scale, ) else: ...
@@ -367,8 +370,9 @@ def forward_custom( ) if self.quant_key.scale.group_shape.is_per_group(): - assert scale is None - scale = self.make_scale(input, transposed=self.has_col_major_scales) + if not self.is_tma_aligned:
vllm/compilation/passes/fusion/matcher_utils.py
26
Python
0.286
question
100
51
51
false
[Bugfix] Fix quant RMS norm fusion for quantization with TMA-aligned scales
33,255
vllm-project/vllm
71,895
Python
ProExpertProg
ElizaWszola
Returns: A tuple of (function_calls, remaining_content) if tool calls were parsed, or None if no tool calls. """ function_calls: list[FunctionCall] = [] if request.tool_choice and isinstance(request.tool_choice, ToolChoiceFunction): # Forced Function...
I remember there should be an assertion here to check that `content` is not `None`. Please keep it.
Returns: A tuple of (function_calls, remaining_content) if tool calls were parsed """ function_calls: list[FunctionCall] = [] if request.tool_choice and isinstance(request.tool_choice, ToolChoiceFunction): # Forced Function Call (Responses API style) ...
@@ -260,6 +310,166 @@ def extract_reasoning( return None, model_output return self._reasoning_parser.extract_reasoning(model_output, request) + def extract_response_outputs( + self, + model_output: str, + request: ResponsesRequest, + enable_auto_tools: bool = False...
vllm/parser/abstract_parser.py
26
Python
0.857
suggestion
100
51
51
false
[2/N] move responses/serving _make_response_output_items logic to parser
33,281
vllm-project/vllm
71,895
Python
chaunceyjiang
qandrew
def _parse_tool_calls( self, request: ResponsesRequest, content: str | None, enable_auto_tools: bool, ) -> tuple[list[FunctionCall], str | None] | None: """ Parse tool calls from content based on request tool_choice settings. Returns: A tuple ...
I remember there should be an assertion here to check that content is not None. Please keep it.
content: str | None, enable_auto_tools: bool, ) -> tuple[list[FunctionCall], str | None]: """ TODO(qandrew): merge _parse_tool_calls_from_content for ChatCompletions into this function Parse tool calls from content based on request tool_choice settings. Retur...
@@ -260,6 +310,166 @@ def extract_reasoning( return None, model_output return self._reasoning_parser.extract_reasoning(model_output, request) + def extract_response_outputs( + self, + model_output: str, + request: ResponsesRequest, + enable_auto_tools: bool = False...
vllm/parser/abstract_parser.py
26
Python
0.643
suggestion
95
51
51
false
[2/N] move responses/serving _make_response_output_items logic to parser
33,281
vllm-project/vllm
71,895
Python
chaunceyjiang
qandrew
finished_recving.update(recving or ()) # Aggregate finished sending request ids - only include # once we've drained the "extra" count (for cases where # more than one connector is async-saving the same request). for req_id in sending or (): ext...
can you leave this todo in place, its being addressed in a separate PR
finished_recving.update(recving or ()) # Aggregate finished sending request ids - only include # once we've drained the "extra" count (for cases where # more than one connector is async-saving the same request). for req_id in sending or (): ext...
@@ -272,11 +274,32 @@ def get_block_ids_with_load_errors(self) -> set[int]: agg_block_ids |= c.get_block_ids_with_load_errors() return agg_block_ids - # TODO: Add a generic implementation of 'get_kv_connector_kv_cache_events' method - # for the MultiConnector. It should be able to get even...
vllm/distributed/kv_transfer/kv_connector/v1/multi_connector.py
26
Python
0.143
suggestion
70
51
51
false
[KV Connector] Add missing method overrides to MultiConnector
33,292
vllm-project/vllm
71,895
Python
NickLucche
eicherseiji
def set_host_xfer_buffer_ops(self, copy_operation: CopyBlocksOp): """Set xPU-specific copy ops for all sub-connectors.""" for c in self._connectors: c.set_host_xfer_buffer_ops(copy_operation) def handle_preemptions(self, preempted_req_ids: set[str]): """Handle preempted requ...
this is not grouping by connector. This is being implemented here https://github.com/vllm-project/vllm/pull/31811/
def set_host_xfer_buffer_ops(self, copy_operation: CopyBlocksOp): """Set xPU-specific copy ops for all sub-connectors.""" for c in self._connectors: c.set_host_xfer_buffer_ops(copy_operation) def handle_preemptions(self, preempted_req_ids: set[str]): """Handle preempted requ...
@@ -272,11 +274,32 @@ def get_block_ids_with_load_errors(self) -> set[int]: agg_block_ids |= c.get_block_ids_with_load_errors() return agg_block_ids - # TODO: Add a generic implementation of 'get_kv_connector_kv_cache_events' method - # for the MultiConnector. It should be able to get even...
vllm/distributed/kv_transfer/kv_connector/v1/multi_connector.py
26
Python
0.286
suggestion
114
51
51
false
[KV Connector] Add missing method overrides to MultiConnector
33,292
vllm-project/vllm
71,895
Python
NickLucche
eicherseiji
): chosen_connector = self._requests_to_connector.get(request.request_id, -1) empty_blocks = blocks.new_empty() for i, c in enumerate(self._connectors): if i == chosen_connector: # Forward call to the chosen connector (if any). c.update_state_after...
note for future work: we need to clarify these constraints when using multiconnector, making sure user understands order matters and/or adding a priority abstraction
c.update_state_after_alloc(request, blocks, num_external_tokens) else: # Call with empty blocks for other connectors. c.update_state_after_alloc(request, empty_blocks, 0) def build_connector_meta( self, scheduler_output: SchedulerOutput ) -> M...
@@ -332,6 +355,27 @@ def update_connector_output(self, connector_output: KVConnectorOutput): for c in self._connectors: c.update_connector_output(connector_output) + def get_handshake_metadata(self) -> KVConnectorHandshakeMetadata | None: + """ + Get the KVConnector handshake me...
vllm/distributed/kv_transfer/kv_connector/v1/multi_connector.py
26
Python
0.5
refactor
165
51
51
false
[KV Connector] Add missing method overrides to MultiConnector
33,292
vllm-project/vllm
71,895
Python
NickLucche
eicherseiji
array_like=True, # type: ignore[call-arg] omit_defaults=True, # type: ignore[call-arg] gc=False, # type: ignore[call-arg] tag=True, ): """Base class for all KV cache-related events""" MEDIUM_GPU = "GPU" class BlockStored(KVCacheEvent): block_hashes: list[ExternalBlockHash] parent_bloc...
Given that we are already adding the `extra_keys` field, this would be an ideal time to remove `array_like=True` from the `BlockStored event`, as suggested by @njhill here: https://github.com/vllm-project/vllm/pull/27577#pullrequestreview-3526591982 While forward compatibility is maintained (a legacy subscriber can of...
array_like=True, # type: ignore[call-arg] omit_defaults=True, # type: ignore[call-arg] gc=False, # type: ignore[call-arg] tag=True, ): """Base class for all KV cache-related events""" MEDIUM_GPU = "GPU" class BlockStored(KVCacheEvent): block_hashes: list[ExternalBlockHash] parent_bloc...
@@ -60,6 +60,13 @@ class BlockStored(KVCacheEvent): medium: str | None lora_name: str | None + extra_keys: list[tuple[Any, ...] | None] | None = None
vllm/distributed/kv_events.py
26
Python
0.857
bug
692
51
51
false
[feat] Add per-block extra_keys to KV events
33,304
vllm-project/vllm
71,895
Python
sagearc
zhongdaor-nv
if self.enable_kv_cache_events: if num_cached_blocks == 0: parent_block_hash: ExternalBlockHash | None = None else: parent_block_hash = maybe_convert_block_hash( block_hashes[num_cached_blocks - 1] ) # Calc...
@orozery +1 on your second point. Since custom embeddings are basically another modality, moving to hashes for `prompt_embeds` is a great call. It aligns with the mm-as-identifiers approach from #22880.
new_hashes.append(maybe_convert_block_hash(block_hash)) if self.enable_kv_cache_events: if num_cached_blocks == 0: parent_block_hash: ExternalBlockHash | None = None else: parent_block_hash = maybe_convert_block_hash( b...
@@ -279,13 +279,31 @@ def cache_full_blocks( block_hashes[num_cached_blocks - 1] ) + # Calculate token range for the blocks being cached + start_token_idx = num_cached_blocks * block_size + end_token_idx = num_full_blocks * block_size + + ...
vllm/v1/core/block_pool.py
26
Python
0.571
suggestion
202
51
51
false
[feat] Add per-block extra_keys to KV events
33,304
vllm-project/vllm
71,895
Python
sagearc
zhongdaor-nv
block_hash_with_group_id = make_block_hash_with_group_id( block_hash, kv_cache_group_id ) blk.block_hash = block_hash_with_group_id self.cached_block_hash_to_block.insert(block_hash_with_group_id, blk) if new_hashes is not None: ...
nit: this var can't be none as far as I can see
# Update and added the full block to the cache. block_hash_with_group_id = make_block_hash_with_group_id( block_hash, kv_cache_group_id ) blk.block_hash = block_hash_with_group_id self.cached_block_hash_to_block.insert(block_hash_with_group_id,...
@@ -279,13 +279,31 @@ def cache_full_blocks( block_hashes[num_cached_blocks - 1] ) + # Calculate token range for the blocks being cached + start_token_idx = num_cached_blocks * block_size + end_token_idx = num_full_blocks * block_size + + ...
vllm/v1/core/block_pool.py
26
Python
0.071
nitpick
47
51
51
false
[feat] Add per-block extra_keys to KV events
33,304
vllm-project/vllm
71,895
Python
NickLucche
zhongdaor-nv
`all_gather_group`'s world size. However, it should be disabled for tensors that are not fully replicated across the group (e.g., the residual tensor when sequence parallelism is enabled). This dictionary allows overriding the default behavior on a per-tensor ...
Let's define ```python def Handle(Protocol): def is_completed() -> bool: ... def wait() -> None: ... ``` so we can use it in typing
an optimization is enabled where each rank in the group sends a slice of a tensor and the receiver reconstructs it using an all-gather, which can improve performance. This is typically the tensor-parallel group. all_gather_tensors: A dictionary to specify which te...
@@ -808,6 +822,34 @@ def send_tensor_dict( # Bypass the function if we are using only 1 GPU. if not torch.distributed.is_initialized() or self.world_size == 1: return tensor_dict + handles = self.isend_tensor_dict( + tensor_dict, + dst=dst, + all_ga...
vllm/distributed/parallel_state.py
26
Python
1
suggestion
156
51
51
false
[Feature] Pipeline Parallel Async send/recv, 2.9% E2E throughput improvement
33,368
vllm-project/vllm
71,895
Python
njhill
yewentao256
NOTE: `src` is the local rank of the source rank. all_gather_group: The group for the all-gather operation. If provided, an optimization is enabled where each rank in the group sends a slice of a tensor and the receiver reconstructs it using an all-gather, which can ...
use handle instead of h (elsewhere too) ```suggestion for handle in handles: ```
def recv_tensor_dict( self, src: int | None = None, all_gather_group: "GroupCoordinator | None" = None, all_gather_tensors: dict[str, bool] | None = None, ) -> dict[str, torch.Tensor | Any] | None: """Recv the input tensor dictionary. NOTE: `src` is the local ran...
@@ -895,6 +916,36 @@ def recv_tensor_dict( # Bypass the function if we are using only 1 GPU. if not torch.distributed.is_initialized() or self.world_size == 1: return None + tensor_dict, handles, postprocess = self.irecv_tensor_dict( + src=src, + all_gather_gr...
vllm/distributed/parallel_state.py
26
Python
1
suggestion
88
51
51
false
[Feature] Pipeline Parallel Async send/recv, 2.9% E2E throughput improvement
33,368
vllm-project/vllm
71,895
Python
njhill
yewentao256
from vllm.tasks import SupportedTask from vllm.utils.mem_utils import MemorySnapshot, format_gib, memory_profiling from vllm.utils.torch_utils import set_random_seed from vllm.v1.core.sched.output import GrammarOutput, SchedulerOutput from vllm.v1.engine import ReconfigureDistributedRequest, ReconfigureRankType from vl...
I think it's better to avoid the `_` here ```suggestion class AsyncIntermediateTensors(IntermediateTensors): ```
from vllm.profiler.wrapper import CudaProfilerWrapper, TorchProfilerWrapper from vllm.sequence import IntermediateTensors from vllm.tasks import SupportedTask from vllm.tracing import instrument from vllm.utils.mem_utils import MemorySnapshot, format_gib, memory_profiling from vllm.utils.torch_utils import set_random_s...
@@ -66,6 +66,38 @@ from vllm.v1.worker.gpu_model_runner import GPUModelRunner +class _AsyncIntermediateTensors(IntermediateTensors):
vllm/v1/worker/gpu_worker.py
26
Python
1
suggestion
112
51
51
false
[Feature] Pipeline Parallel Async send/recv, 2.9% E2E throughput improvement
33,368
vllm-project/vllm
71,895
Python
njhill
yewentao256
group = self.device_group metadata_group = self.cpu_group if dst is None: dst = (self.rank_in_group + 1) % self.world_size assert dst < self.world_size, f"Invalid dst rank ({dst})" metadata_list, tensor_list = _split_tensor_dict(tensor_dict) self.send_objec...
I think this needs to go below the `isend` call
self.device_communicator.send_tensor_dict( # type: ignore tensor_dict, dst ) return [] all_gather_size = 1 if all_gather_group is None else all_gather_group.world_size all_gather_rank = ( 0 if all_gather_group is None else all_gather_grou...
@@ -820,53 +862,32 @@ def send_tensor_dict( dst = (self.rank_in_group + 1) % self.world_size assert dst < self.world_size, f"Invalid dst rank ({dst})" - if self.use_cpu_custom_send_recv: - if self.device_communicator is None: - raise ValueError("No device communi...
vllm/distributed/parallel_state.py
26
Python
0.286
suggestion
47
51
51
false
[Feature] Pipeline Parallel Async send/recv, 2.9% E2E throughput improvement
33,368
vllm-project/vllm
71,895
Python
njhill
yewentao256
for tensors that are not fully replicated across the group (e.g., the residual tensor when sequence parallelism is enabled). This dictionary allows overriding the default behavior on a per-tensor basis. """ # Bypass the function if we are using only 1 GPU....
`and not self.use_cpu_custom_send_recv` here and avoid the separate if?
on for any tensor whose size is divisible by the `all_gather_group`'s world size. However, it should be disabled for tensors that are not fully replicated across the group (e.g., the residual tensor when sequence parallelism is enabled). This dictionary allows...
@@ -808,6 +828,34 @@ def send_tensor_dict( # Bypass the function if we are using only 1 GPU. if not torch.distributed.is_initialized() or self.world_size == 1: return tensor_dict + handles = self.isend_tensor_dict( + tensor_dict, + dst=dst, + all_ga...
vllm/distributed/parallel_state.py
26
Python
0.571
question
71
51
51
false
[Feature] Pipeline Parallel Async send/recv, 2.9% E2E throughput improvement
33,368
vllm-project/vllm
71,895
Python
njhill
yewentao256