Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
aa868d3
[sglang][lora] Support DP attention in LoRA backends
erikwijmans Aug 5, 2026
5b11279
Merge branch 'main' into erik/lora-dp-attention
yushengsu-thu Aug 28, 2026
c20a9cf
[sglang][lora] Support DP attention in LoRA backends
erikwijmans Aug 5, 2026
5536aaa
Merge remote-tracking branch 'refs/remotes/erik/erik/lora-dp-attentio…
erikwijmans Aug 28, 2026
0a44163
[lora] Fix DP attention idle and graph buffer sizing
erikwijmans Aug 29, 2026
ab54db0
[lora] Right-size DP-attention MoE graph buffers
erikwijmans Aug 29, 2026
4207abc
[lora] Trim DP attention LoRA tests
erikwijmans Aug 31, 2026
4adcce4
[lora] Fix DP attention LM-head routing
erikwijmans Sep 2, 2026
e63e79c
[lora] Fix DP-attention LM-head routing
erikwijmans Sep 2, 2026
a7c2501
Fix DP-attention LoRA CUDA graph replay metadata
erikwijmans Sep 4, 2026
dc01347
Support LoRA LM-head routing from CUDA graph replay views
erikwijmans Sep 4, 2026
b900d5b
[lora] Align DP routing and require pinned adapters
erikwijmans Sep 7, 2026
d739b6c
Merge main into erik/lora-dp-attention
yushengsu-thu Sep 8, 2026
1a5b7ec
Fail fast when a LoRA backend omits DP-attention routing
yushengsu-thu Sep 8, 2026
e9bc7ca
Merge branch 'main' into erik/lora-dp-attention
yushengsu-thu Sep 9, 2026
e1962be
Fix Nemotron LoRA fixture for layout-aware batch metadata
yushengsu-thu Sep 9, 2026
fd01495
Fix LoRA unload identity after rejected duplicate loads
yushengsu-thu Sep 9, 2026
e6f49ab
Merge branch 'main' into erik/lora-dp-attention
yushengsu-thu Sep 13, 2026
806ec81
[lora] Fix DP-attention routing for embeddings, MHC layers and MoE de…
yushengsu-thu Sep 13, 2026
fe3250d
[lora] Reset the DP-attention LoRA layout at the start of every forward
yushengsu-thu Sep 13, 2026
fe555b9
[lora] Vote against the prefill CUDA graph when DP attention runs pre…
yushengsu-thu Sep 14, 2026
05ab613
[lora] Skip DP-attention LoRA layout publishing when LoRA is disabled
yushengsu-thu Sep 24, 2026
17ec447
[lora] Require dp_size == tp_size for LoRA with DP attention
yushengsu-thu Sep 24, 2026
ef70f3e
Merge branch 'main' into erik/lora-dp-attention
yushengsu-thu Sep 24, 2026
8c3c60d
[lora] Read the attention-DP rank and size from the parallel context
yushengsu-thu Sep 24, 2026
814cbe0
[lora] Default the communicator's LoRA layout flag for instances buil…
yushengsu-thu Sep 25, 2026
bb36e92
Merge branch 'main' into erik/lora-dp-attention
yushengsu-thu Sep 25, 2026
670ee87
[lora] Index per-DP-rank token counts with dp_slot_in
yushengsu-thu Sep 25, 2026
9664367
Merge branch 'main' into erik/lora-dp-attention
Fridge003 Sep 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion docs/docs/advanced_features/lora.mdx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: "LoRA Serving"
metatags:
description: "SGLang multi-LoRA serving: S-LoRA and Punica techniques, dynamic adapter loading, GPU pinning, overlap loading, Triton and CSGMV backends."
description: "SGLang multi-LoRA serving: S-LoRA and Punica techniques, DP attention, dynamic adapter loading, GPU pinning, overlap loading, Triton and CSGMV backends."
---
SGLang enables the use of [LoRA adapters](https://arxiv.org/abs/2106.09685) with a base model. By incorporating techniques from [S-LoRA](https://arxiv.org/pdf/2311.03285) and [Punica](https://arxiv.org/pdf/2310.18547), SGLang can efficiently support multiple LoRA adapters for different sequences within a single batch of inputs.

Expand Down Expand Up @@ -412,6 +412,32 @@ server_process, port = launch_server_cmd(
terminate_process(server_process)
```

## LoRA with DP attention

SGLang supports LoRA serving with [data parallel attention (DPA)](/docs/advanced_features/dp_dpa_smg_guide). The model architecture must support DPA, and you must currently select the Triton LoRA backend. Other built-in LoRA backends reject this configuration at startup.

The following NVIDIA CUDA example uses four attention-DP ranks:

```bash
python3 -m sglang.launch_server \
--model-path MODEL_PATH \
--tp 4 \
--dp-size 4 \
--enable-dp-attention \
--enable-lora \
--lora-backend triton \
--lora-paths '{"lora_name":"ADAPTER_NAME","lora_path":"ADAPTER_PATH","pinned":true}'
```

Keep these constraints in mind:

- `--dp-size` must equal `--tp-size`, so every attention DP rank owns its whole token batch. The server rejects other layouts at startup.
- All adapters must be GPU-pinned (`pinned: true`), including dynamically loaded adapters. You can pin at most `--max-loras-per-batch - 1` adapters; the remaining slot is reserved for the base model.
- Decode CUDA graphs are supported. LoRA prefill runs eagerly when DPA is enabled.
- `--max-loras-per-batch` limits the union of adapters active across all DP ranks in a synchronized forward, not the adapters on one rank alone.
- Dynamic load and unload requests are sent to every DP rank. An operation succeeds only if every rank reports success. After a partially successful load, retry unloading the same adapter name before loading it again.
- The built-in LoRA memory pool does not support `--enable-lora-overlap-loading` with DPA. The server rejects that combination rather than allowing DP ranks to assign different GPU slots.

## LoRA Overlap Loading


Expand Down
29 changes: 29 additions & 0 deletions python/sglang/srt/layers/communicator.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
)
from sglang.srt.model_executor.forward_batch_info import ForwardBatch, ForwardMode
from sglang.srt.runtime_context import (
LoRABatchLayout,
get_exec,
get_forward,
get_lora,
Expand Down Expand Up @@ -702,6 +703,9 @@ def _unfused_completion_matches_the_ffn(forward_batch: ForwardBatch) -> bool:


class LayerCommunicator:
# Communicators built without __init__ (e.g. test doubles) publish no LoRA layout.
_publish_lora_layout: bool = False

def __init__(
self,
layer_scatter_modes: LayerScatterModes,
Expand Down Expand Up @@ -740,6 +744,10 @@ def __init__(
self._speculative_algo = SpeculativeAlgorithm.from_string(
get_spec().speculative_algorithm
)
# LoRA kernels need the per-layer token layout only under DP attention.
self._publish_lora_layout = get_parallel().enable_dp_attention and bool(
get_lora().enable_lora
)

# Under LayerNorm SP the norm/residual run on the sequence shard with no
# collectives, so delegate to an all-SCATTERED sibling while the region is
Expand Down Expand Up @@ -846,6 +854,23 @@ def _post_attn_residual_is_read_only(self, residual: torch.Tensor) -> bool:
and apply_flashinfer_allreduce_fusion(residual.shape[0])
)

def publish_attn_lora_layout(self) -> None:
"""Attention consumes the DP-local token batch."""
if self._publish_lora_layout:
get_forward().set("lora_batch_layout", LoRABatchLayout.DP_LOCAL)

def publish_mlp_lora_layout(self) -> None:
"""The MLP consumes the TP-global batch only after a FULL DP gather."""
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
if self._publish_lora_layout:
get_forward().set(
"lora_batch_layout",
(
LoRABatchLayout.TP_GLOBAL
if self.layer_scatter_modes.mlp_mode is ScatterMode.FULL
else LoRABatchLayout.DP_LOCAL
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
),
)

def prepare_attn(
self,
hidden_states: Union[torch.Tensor, UnreducedOutput],
Expand All @@ -854,6 +879,8 @@ def prepare_attn(
quant_format: str = "",
post_residual_addition: Optional[torch.Tensor] = None,
):
self.publish_attn_lora_layout()

if isinstance(hidden_states, UnreducedOutput) and residual is None:
raise RuntimeError("an UnreducedOutput requires residual input")
if (
Expand All @@ -869,6 +896,7 @@ def prepare_attn(
pending = unreduced is not None
if pending:
hidden_states = unreduced.partial

# residual is None marks the first decoder layer, where the SP region
# opens: re-evaluated per forward so a crash mid-loop cannot leak into
# the next one.
Expand Down Expand Up @@ -988,6 +1016,7 @@ def prepare_mlp(
forward_batch: ForwardBatch,
cache=None,
):
self.publish_mlp_lora_layout()
if self._sp_variant is not None and get_forward().sp_active:
return self._sp_variant.prepare_mlp(
hidden_states, residual, forward_batch, cache
Expand Down
2 changes: 2 additions & 0 deletions python/sglang/srt/layers/communicator_mhc.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,7 @@ def prepare_attn(
residual: torch.Tensor,
forward_batch: ForwardBatch,
):
self.publish_attn_lora_layout()
if self.is_first_layer:
if get_attn_tp_context().input_scattered:
hidden_states, _ = tp_reduce_scatter(
Expand Down Expand Up @@ -525,6 +526,7 @@ def prepare_mlp(
forward_batch: ForwardBatch,
cache=None,
):
self.publish_mlp_lora_layout()
if cache is not None:
self._context.cache = cache

Expand Down
15 changes: 13 additions & 2 deletions python/sglang/srt/layers/logits_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,12 @@
ForwardBatch,
ForwardMode,
)
from sglang.srt.runtime_context import get_exec, get_parallel
from sglang.srt.runtime_context import (
LoRABatchLayout,
get_exec,
get_forward,
get_parallel,
)
from sglang.srt.utils.common import (
is_cpu,
is_npu,
Expand Down Expand Up @@ -874,7 +879,13 @@ def _get_logits(
_trace_e2e_logits("pre_lm_head_sync_returned")

_trace_e2e_logits("lm_head_enter", hidden_shape=tuple(hidden_states.shape))
logits = self._compute_lm_head(hidden_states, lm_head, embedding_bias)
lora_batch_layout = (
LoRABatchLayout.TP_GLOBAL
if self.do_tensor_parallel_all_gather_dp_attn
else LoRABatchLayout.DP_LOCAL
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
)
with get_forward().scoped(lora_batch_layout=lora_batch_layout):
logits = self._compute_lm_head(hidden_states, lm_head, embedding_bias)
_trace_e2e_logits("lm_head_returned", logits_shape=tuple(logits.shape))
if envs.SGLANG_TRACE_LOGITS_E2E_SYNC.get():
_trace_e2e_logits("post_lm_head_sync_enter")
Expand Down
45 changes: 45 additions & 0 deletions python/sglang/srt/lora/backend/base_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
get_batch_token_counts,
)
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
from sglang.srt.runtime_context import LoRABatchLayout
from sglang.srt.utils.common import empty_device_cache


class BaseLoRABackend(LoRABackendLmHeadMixing):
Expand All @@ -29,6 +31,8 @@ class BaseLoRABackend(LoRABackendLmHeadMixing):
# Supporting backends implement init_prefill_cuda_graph_batch_info() and
# honor use_prefill_cuda_graph in prepare_lora_batch().
supports_prefill_cuda_graph: bool = False
# Supporting backends must handle both eager execution and decode CUDA graphs.
supports_dp_attention: bool = False

def __init__(self, max_loras_per_batch: int, device: torch.device):
self.max_loras_per_batch = max_loras_per_batch
Expand All @@ -47,6 +51,8 @@ def __init__(self, max_loras_per_batch: int, device: torch.device):
self.prefill_cuda_graph_max_tokens: int | None = None
# Separate scratch sized for the largest prefill token bucket.
self.prefill_moe_cg_buffers: dict | None = None
self._moe_cg_buffer_init_args: tuple[int, torch.dtype, object] | None = None
self._moe_cg_buffer_max_bs: int | None = None

def reset_batch_state(self):
"""Idle-forward counterpart of prepare_lora_batch(): clears all
Expand All @@ -57,6 +63,22 @@ def reset_batch_state(self):
self.lm_head_pass_batch_infos = None
self._lm_head_pass_idx = None

def get_batch_info(
self, layout: LoRABatchLayout | None = None
) -> Optional[LoRABatchInfo]:
"""Return routing metadata for the requested token layout.

Backends that support multiple layouts override this method.
"""
return self.batch_info

def prepare_global_lora_batch(self, forward_batch: ForwardBatch) -> None:
Comment thread
yushengsu-thu marked this conversation as resolved.
Resolved
"""Prepare routing for TP-global sections of a DP-attention forward."""
raise NotImplementedError(
f"LoRA backend {type(self).__name__} must implement "
"prepare_global_lora_batch() to support DP attention."
)

def validate_lora_targets(
self,
base_model: torch.nn.Module,
Expand Down Expand Up @@ -201,6 +223,13 @@ def init_cuda_graph_batch_info(
"""
pass

def init_dp_attention_cuda_graph_batch_info(self, max_num_tokens: int) -> None:
"""Allocate backend-specific TP-global metadata for decode graphs."""
raise NotImplementedError(
f"LoRA backend {type(self).__name__} does not support DP attention "
"in the decode CUDA graph."
)

def init_prefill_cuda_graph_batch_info(
self, max_num_tokens: int, max_num_requests: Optional[int] = None
):
Expand Down Expand Up @@ -231,6 +260,10 @@ def init_cuda_graph_moe_buffers(

max_bs counts tokens. Layers reuse these buffers sequentially.
"""
if not prefill:
self._moe_cg_buffer_init_args = (max_loras, compute_dtype, moe_layer)
self._moe_cg_buffer_max_bs = max_bs

base = moe_layer.base_layer
top_k = base.top_k
device = moe_layer._quant_info.w13_weight.device
Expand Down Expand Up @@ -279,6 +312,18 @@ def init_cuda_graph_moe_buffers(
else:
self.moe_cg_buffers = buffers

def resize_cuda_graph_moe_buffers(self, max_bs: int) -> bool:
"""Shrink the provisional pre-profile buffers to the captured token cap."""
if self._moe_cg_buffer_max_bs is None or max_bs >= self._moe_cg_buffer_max_bs:
return False

assert self._moe_cg_buffer_init_args is not None
max_loras, compute_dtype, moe_layer = self._moe_cg_buffer_init_args
self.moe_cg_buffers.clear()
empty_device_cache()
self.init_cuda_graph_moe_buffers(max_bs, max_loras, compute_dtype, moe_layer)
return True

def _add_moe_lora_info(
self, forward_batch: ForwardBatch, batch_info: LoRABatchInfo
) -> LoRABatchInfo:
Expand Down
Loading
Loading