> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sglang.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Per-model execution choices

> How SGLang resolves, holds and selects the execution choices that belong to one model, such as a target and its speculative draft.

A target model and its speculative draft run in one process and can need different execution choices: different linear-attention kernels, a different shared-expert layout, or a different MoE runner and all-to-all backend. SGLang resolves these choices once per model, holds them per model role, and selects them for the code that builds or runs that model. This page is for contributors who add a speculative worker, a model, or a reader of these choices. It documents current internal interfaces, not a versioned plugin API.

## The per-model values

Each model role (`ModelRole.TARGET`, `ModelRole.DRAFT`) has one immutable `ModelExecutionConfig` (`sglang/srt/configs/model_execution.py`). Its fields are exposed as leaves of the `get_model()` namespace while that model is selected:

| Leaf | Holds | Read through |
| - | - | - |
| `get_model().linear_attn_backends` | decode, prefill and verify kernels for GDN, KDA and lightning layers | `bound_linear_attn_backends()` |
| `get_model().shared_experts` | the shared-expert layout (`SharedExpertsConfig`) | `current_shared_experts()`, `get_num_fused_shared_experts()` |
| `get_model().moe_backends` | MoE runner, all-to-all backend, FP4 allgather, draft-only construction choices (`MoeBackends`) | `get_moe_runner_backend()`, `get_moe_a2a_backend()`, `is_draft_moe_model()` |

Every runner of one model shares its role's entry; multi-layer EAGLE's step runners all use the draft entry.

## Lifecycle

1. **Resolve and install.** The scheduler calls `resolve_model_execution_configs` once per process, after platform and distributed initialization and before any worker exists, and installs the table with `install_model_execution_configs`. A draft role is resolved only when the speculative algorithm builds a draft model (`has_draft_model()`), and the draft's MoE choices follow `draft_builds_with_own_moe_backends()`.
2. **Build inside the model's scope.** `ModelRunner.model_context()` selects the runner's role entry. Model construction, weight loading, post-load preparation, attention-backend construction and CUDA graph setup run inside it.
3. **Built modules keep their choice.** A layer, quantization method, dispatcher or attention backend reads the value when it is built and keeps it. New code follows this rule: execution methods such as `forward`, a quantization method's `apply` or a runner's `run` use the kept value instead of calling `get_model()` or its accessors again. A few existing execution paths still read the current scope, so a model's forward, graph capture and weight updates must run inside its own scope (steps 2, 4 and 5); running a built module under another model's scope is not supported.
4. **Per-batch code reads the current scope.** Code that no built module owns, such as batch preparation, reads the leaf of the model whose scope is current. The scheduler keeps the target's scope entered for its lifetime; draft work outside the draft runner's forward enters `draft_model_scope()`.
5. **Weight updates run in the model's scope.** A runner's weight update, reload and post-processing run inside the same scope as its build, so reloaded weights are prepared for the backends the model was built with.

## Migrating from the earlier interfaces

| Earlier | Now |
| - | - |
| `speculative_moe_backend_context()`, `speculative_moe_a2a_backend_context()`, `draft_model_build_scope()` | `draft_model_scope()`, or `model_role_scope(role)`; a draft runner's own work is already inside `ModelRunner.model_context()` |
| `MoeFlags.speculative_runner_backend`, `speculative_a2a_backend`, `in_speculative_scope`, `speculative_context` | the draft role's `moe_backends` entry, read through the accessors above |
| `runner.linear_attn_backends` | `get_model().linear_attn_backends` |
| `model.shared_experts_config` | `get_model().shared_experts` |

In `get_flags().moe`, `runner_backend`, `runner_backend_explicit`, `a2a_backend` and `disable_fp4_allgather` are the served model's choices as configured: each model's `moe_backends` starts from them, and model code reads `get_model().moe_backends` instead. The other fields, such as `deepep_mode`, `deepep_config`, `tbo_enabled` and `sbo_enabled`, are process-wide settings and are still read from the flags.

## Examples

A speculative worker helper that runs draft modules outside the draft runner's forward enters the draft scope:

```python theme={null}
from sglang.srt.configs.model_execution import draft_model_scope, in_draft_model_scope


class MyDraftWorker:
    @in_draft_model_scope
    def project_hidden(self, hidden_states):
        return self.draft_model.project(hidden_states)

    def verify_epilogue(self, batch):
        # Target work stays in the target's scope; only the draft call switches.
        logits = self.target_logits(batch)
        with draft_model_scope():
            self.draft_model.write_context(batch)
        return logits
```

A unit test publishes a test config, overrides one leaf, and builds the module inside the override:

```python theme={null}
from sglang.srt.configs.shared_experts import SharedExpertsConfig
from sglang.srt.layers.moe.topk import TopK
from sglang.srt.runtime_context import get_context, get_model

# get_model() raises until a config is published.
with get_context().override_server_args():
    with get_model().override(
        shared_experts=SharedExpertsConfig(num_fused_shared_experts=1)
    ):
        topk = TopK(top_k=8, layer_id=0)
    # The module keeps the layout it was built with after the override ends.
```

## What the scope guarantees

* A scope selects an entry and restores the previous values on exit, including on exceptions. It cannot resize weights, buffers or captured graphs built under another entry.
* In a serving process that installed the table, reading a per-model value outside every scope raises. Tools and tests that install no table see the startup defaults for the MoE values and the shared-expert layout; a linear-attention backend always needs a bound kernel choice.
* Draft work that runs under the target's scope reads the target's values without any error. A missing `draft_model_scope()` is therefore not always detected; the unit test `test/registered/unit/spec/test_draft_model_calls_scoped.py` checks only calls made through the name `draft_model`.

## Speculative algorithm plugins

A `CustomSpecAlgo` declares two facts the resolver needs before its worker exists:

* `has_draft_model() -> bool`: whether its worker builds a draft model. The default is true when `--speculative-draft-model-path` is set or the algorithm answers true to a draft-building trait (`is_eagle`, `is_eagle3`, `is_frozen_kv_mtp`, `is_standalone`, `is_dflash`, `is_dspark`, `is_dflash_family`).
* `draft_builds_with_own_moe_backends() -> tuple[bool, bool]`: two independent answers, `(own_runner, own_a2a)`: whether its draft builds with its own MoE runner (`--speculative-moe-runner-backend`), and whether with its own all-to-all backend (`--speculative-moe-a2a-backend`). For example, `(True, False)` gives the draft its own runner and the target's all-to-all, as multi-layer EAGLE does. The default applies the built-in rule to the algorithm's `is_*()` answers; see [MoE backends for the draft model](https://docs.sglang.io/docs/advanced_features/speculative_decoding.md#moe-backends-for-the-draft-model).

Override either when the worker behaves differently, and build the draft inside `draft_model_scope()` so it builds with the resolved choices.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.