---
myst:
  html_meta:
    description: "Structured outputs and tool calling"
    content_type: "conceptual-deep-dive"
    date-modified: "2026-11-08"
---

# Structured Outputs and Tool Calling

## Overview

Structured outputs and tool calling enable constrained generation on the vLLM Neuron backend using JSON schemas, regex patterns, choice enums, and BNF grammars. The model output is guaranteed to conform to the specified constraint by applying a grammar-derived bitmask to logits before sampling. Tool calling (function calling) builds directly on this same infrastructure vLLM internally converts tool schemas into structured output constraints, so no additional code changes were needed.

This feature is implemented across three layers:

- **Scheduler** (`scheduler.py`): Computes the grammar bitmask on CPU via vLLM's `StructuredOutputManager` and attaches it to `SchedulerOutput`
- **Model Runner** (`neuron_model_runner.py`): Unpacks the packed int32 bitmask into a boolean tensor, reorders it to match the batch layout, and passes it into the model forward call
- **vLLM Neuron Sampler** (on-device): Applies `logits.masked_fill(~logit_mask, -inf)` before argmax so only grammar-valid tokens can be selected

With async scheduling, Model Runner V2 works differently: the engine passes the bitmask to `sample_tokens`, and a separate sampler graph applies it after the forward graph. See [Structured Outputs with Async Scheduling](#structured-outputs-with-async-scheduling).

For scheduler background, see `neuron-scheduler`. For overall vLLM integration, see `vllm-integration-design-reference`.

## Problem Statement

With on-device sampling enabled, the model forward pass is compiled into a NEFF (Neuron Executable File Format). In this mode, logits are never returned to the CPU. Instead, the device runs the full pipeline from logits through argmax and returns only the sampled token IDs. (Without on-device sampling, logits are returned to CPU for sampling there.)

In standard vLLM (v1, GPU), the bitmask is NOT passed into the model forward call. The model executes inside a CUDA graph and returns logits; then, in a separate step outside the graph, a Triton kernel applies the grammar bitmask on-GPU (`logits.masked_fill → -inf`) before the sampler runs. The key distinction is that logits are accessible between the model forward and sampling steps.

With synchronous scheduling, structured outputs use the on-device sampling path. Since logits are never materialized outside the compiled NEFF, we cannot intercept them between the forward pass and sampling. The mask must be applied ON device before sampling, so we thread it through `model.forward()` to get it to the sampler:

``` text
Scheduler: attach bitmask to SchedulerOutput
                    ↓
Model Runner: extract bitmask, pass as logit_mask parameter
                    ↓
Model.forward(logit_mask=...) → On-device sampler applies mask
```

We added the `logit_mask` parameter because vLLM Neuron does on-device sampling and the mask must be applied ON device before sampling. We had to thread it through `model.forward()` to get it to the sampler.

## Solution

### Data Flow

The end-to-end flow spans the CPU host and the Neuron device, crossing the NEFF boundary once per decode step:

``` text
┌─────────────────────────────────────────────────────────────────┐
│  CPU (Host)                                                     │
├─────────────────────────────────────────────────────────────────┤
│  SCHEDULER (scheduler.py)                                       │
│  1. Request arrives with structured_output (JSON/regex/etc.)    │
│  2. grammar_init(request)  initialize FSM from schema          │
│  3. Each decode step: grammar_bitmask() → packed int32 tensor   │
│  4. Attach bitmask to scheduler_output._grammar_bitmask         │
├─────────────────────────────────────────────────────────────────┤
│  MODEL RUNNER (neuron_model_runner.py)                           │
│  5. _get_grammar_bitmask() extracts from scheduler_output       │
│  6. Unpack: [batch, packed_vocab] int32 → [batch, vocab] bool   │
│  7. Pass logit_mask to model forward                            │
└────────────────────────────┬────────────────────────────────────┘
                             │  Inputs transferred to device:
                             │  - input_ids, positions
                             │  - logit_mask [batch, vocab_size]
                             ▼
═══════════════════════════════════════════════════════════════════
CPU EXECUTION ↑  |  ↓ ON-DEVICE EXECUTION
═══════════════════════════════════════════════════════════════════
                             │
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│  Neuron Device (NEFF)                                           │
├─────────────────────────────────────────────────────────────────┤
│  MODEL (e.g. llama3/model.py)                                   │
│  8. Forward pass computes logits                                │
│  9. Pass logit_mask to sampler                                  │
├─────────────────────────────────────────────────────────────────┤
│  SAMPLER (nn/sampler.py)                                        │
│  10. logits.masked_fill(~logit_mask, -inf)                      │
│  11. argmax → only grammar-valid tokens can be selected         │
└────────────────────────────┬────────────────────────────────────┘
                             │  Output: token_ids [batch]
                             ▼
═══════════════════════════════════════════════════════════════════
ON-DEVICE EXECUTION ↑  |  ↓ CPU EXECUTION
═══════════════════════════════════════════════════════════════════
                             │
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│  CPU (Host)                                                     │
│  12. Update grammar FSM state with selected token               │
│  13. Next iteration: goto step 3 (new bitmask for new state)    │
└─────────────────────────────────────────────────────────────────┘
```

Per decode step the cycle is: forward pass → get bitmask → apply mask → sample → update FSM state → repeat.

### Bitmask Format

vLLM constructs a packed bitmask to minimize memory transfer between CPU and device.

- **Shape:** `[batch_size, packed_vocab_size]` where `packed_vocab_size = ceil(vocab_size / 32)`
- **Dtype:** `int32`
- Each `int32` element encodes 32 vocabulary tokens. Bit = 1 means token is ALLOWED, bit = 0 means DISALLOWED (little-endian bit order).

For Llama-3 with `vocab_size = 128,256`, this yields `packed_vocab_size = 4,008` int32 values per request roughly 16 KB per row.

### Scheduler Integration

With synchronous scheduling, `NeuronScheduler.schedule()` gets the grammar bitmask after the padding step (Step 6) and attaches it to the `SchedulerOutput`:

``` python
# Step 7: Attach grammar bitmask for structured outputs
if not self.scheduler_config.async_scheduling:
    grammar_output = self.get_grammar_bitmask(scheduler_output)
    if grammar_output is not None and grammar_output.grammar_bitmask is not None:
        scheduler_output._grammar_bitmask = grammar_output.grammar_bitmask
        scheduler_output._structured_output_request_ids = (
            grammar_output.structured_output_request_ids
        )
```

The engine core then calls `get_grammar_bitmask()` again before `sample_tokens`. `NeuronScheduler` caches the result for the same `SchedulerOutput` until the next `update_from_output()`, so `StructuredOutputManager` builds each bitmask once. The bitmask is a numpy array here, and the model runner converts it to a torch tensor. With async scheduling, `schedule()` does not build the bitmask. The engine core gets it before `sample_tokens`, and split sampling applies it (see [Bitmask Path](#bitmask-path)).

### Model Runner Integration

`_get_grammar_bitmask()` in `neuron_model_runner.py` performs three operations:

**1. Reordering** The compact bitmask from the scheduler only contains rows for requests with structured output constraints. The model runner expands this to match the full batch layout (including non-SO requests and speculative decode token offsets). Non-SO rows are filled with `-1` (all bits set = all tokens allowed).

``` python
# Build mapping: req_id -> logit_index (accounting for spec tokens)
for batch_index, req_id in enumerate(self.input_batch.req_ids):
    logit_index = batch_index + cumulative_offset
    cumulative_offset += len(spec_tokens.get(req_id, ()))
    if req_id in struct_out_req_ids_set:
        struct_out_req_batch_indices[req_id] = logit_index

# Full bitmask: -1 (all allowed) for non-SO rows
sorted_bitmask = torch.full(
    (num_logit_rows, packed_vocab_size), fill_value=-1, dtype=torch.int32
)
```

**2. Unpacking** The packed int32 bitmask is unpacked to a boolean tensor of shape `[num_logit_rows, vocab_size]`:

``` python
packed_uint = sorted_bitmask.view(num_logit_rows, packed_vocab_size, 1)
bit_positions = torch.arange(32, dtype=torch.int32)
unpacked = ((packed_uint >> bit_positions) & 1).view(num_logit_rows, -1)
unpacked = unpacked[:, :self.vocab_size]
bitmask = unpacked.bool()
```

**3. Device Transfer** The boolean mask is moved to the Neuron device and passed as `logit_mask` to the model forward call:

``` python
bitmask = bitmask.to(device=self.device)

# In execute_model():
model_kwargs["logit_mask"] = logit_mask
model_output = self.model(**model_kwargs)
```

Note: TP sharding of the mask is handled inside the vLLM Neuron sampler, matching the `lm_head` sharding strategy. The model runner passes the full-vocab mask.

### Model Runner V2

Model Runner V2 (`neuron_model_runner_v2.py`) applies the same bitmask. The differences are:

- `build_logit_mask()` in `neuron_input_build.py` places each bitmask row at the output row of its request. V2 output rows are in scheduler order: new requests first, then running requests. The other rows, which include padded rows, allow every token.
- The runner unpacks only the words that cover the local `lm_head` vocabulary shard, and sends a `[rows, shard width]` mask to each rank. It reads the shard start and width from the model's `lm_head` (`tp_rank` and `out_features_per_rank`), so the mask matches the group that the LM head is sharded over.
- With synchronous scheduling, the forward adapter passes `logit_mask` to the model in every target graph when `enable_structured_outputs` is true. A step without a bitmask passes a cached all-True mask, so one graph per bucket serves both cases. When `enable_structured_outputs` is false, the graphs have no mask input.
- With asynchronous scheduling, V2 serves structured outputs through split sampling (see [Structured Outputs with Async Scheduling](#structured-outputs-with-async-scheduling)). The forward graph then has no mask input. Structured outputs with speculative decoding use MRv1, and they need synchronous scheduling there. With synchronous scheduling, `lm_head_dp_size` greater than 1 also uses MRv1, except with the decode megakernel.
- Jump-forward decoding runs on MRv2 in a decode graph of its own (see [Jump-Forward Decoding](#jump-forward-decoding)). It needs synchronous scheduling.

## Benchmarking

Benchmarked with synchronous scheduling on Llama-3-8B with TP8, `max_model_len=256`, on-device greedy sampling (`all_greedy=true`), using the `xgrammar` backend. Results averaged over 10 runs.

### Per-Token Overhead

| Configuration    | Per-Token Latency | vs Baseline |
|------------------|-------------------|-------------|
| Simple JSON SO   | 759.7 ms/token    | +1.8%       |
| Complex JSON SO  | 739.0 ms/token    | −1.0%       |
| No SO (baseline) | 746.4 ms/token    |             |

The ~1-2% variation is within measurement noise. Structured output adds virtually no per-token overhead.

### Component Breakdown (Warm, Steady-State)

| Component                                  | Latency                 |
|--------------------------------------------|-------------------------|
| Scheduler: grammar bitmask computation     | ~0.12 ms                |
| Model runner: bitmask unpacking + transfer | ~0.24 ms                |
| Forward pass delta (with vs without mask)  | ~0 ms (within variance) |
| **Total per-token SO overhead**            | **~0.4 ms**             |

### Forward Pass Execution

| Phase              | With Mask | Without Mask | Delta   |
|--------------------|-----------|--------------|---------|
| 1st (NEFF compile) | 8,395 ms  | 8,117 ms     | +278 ms |
| 2nd (warmup)       | 5,372 ms  | 5,361 ms     | +11 ms  |
| 3rd+ (steady)      | ~750 ms   | ~762 ms      | −12 ms  |

The first structured output request triggers a NEFF recompilation (~8.4s one-time cost) because the model graph changes to accept the `logit_mask` input tensor. After warmup, the forward pass with mask is within noise of the baseline.

## Tool Calling

Tool calling (function calling) works on top of the structured outputs infrastructure. No additional code changes were needed vLLM internally converts tool schemas into structured output constraints.

### How It Works

Tool calling in vLLM has two distinct paths depending on `tool_choice` and the tools:

``` text
tool_choice
    |
+------------+------------+
|                         |
none, or auto            required / named, or auto
without strict tools     with strict tools
|                         |
No structured outputs     adjust_request() adds a
Model generates free text structural tag or a JSON
|                         schema to the request
Tool parser               |
extracts tool calls       xgrammar compiles grammar FSM
after generation          logit_mask constrains each token
|                                   |
|               vLLM Neuron sampler applies:
|               logits.masked_fill(~mask, -inf)
|                         |
+------------+------------+
    |
tool_calls returned
```

- **required/named**: Always structured outputs. If the tool parser has a structural-tag template (`structural_tag_model`, for example `llama` for `llama3_json`) and `VLLM_ENFORCE_STRICT_TOOL_CALLING` is on (the default), vLLM's `adjust_request()` sets a structural tag. Otherwise it sets `StructuredOutputsParams(json=tool_array_schema)`.
- **auto**: Structured outputs only with a tool parser that has a structural-tag template, and only when a tool sets `strict: true` or the server sets `--tool-strict-level function` or `parameter`. vLLM then sets a structural tag that still allows plain text. Otherwise the model generates free text, and the tool parser (for example `Llama3JsonToolParser`) extracts tool calls after generation.
- **none**: No structured outputs.

A tool call with structured outputs flows through the same grammar bitmask pipeline as any structured-output request, with no Neuron-specific change.

### Why On-Device Sampling Is Required for required/named

The vLLM Neuron model's `forward()` has two code paths:

``` python
# Path A: No on-device sampling → returns raw logits
if self.on_device_sampling_config is None:
    return logits  # logit_mask is IGNORED here

# Path B: On-device sampling → sampler applies mask
sampled_tokens = self.sampler(logits, sampling_params, logit_mask=logit_mask)
```

Without on-device sampling, the model returns raw logits before reaching the sampler. The `logit_mask` is passed into `forward()` but never applied unconstrained tokens violate the grammar FSM and cause `Failed to advance FSM` errors.

| Mode | CPU Sampling | On-Device Sampling | Why |
|----|----|----|----|
| `tool_choice="auto"` | ✅ | ✅ | No SO needed |
| `tool_choice="none"` | ✅ | ✅ | No SO needed |
| `tool_choice="required"` | ❌ | ✅ | Needs `logit_mask` applied in sampler |
| Named tool choice | ❌ | ✅ | Needs `logit_mask` applied in sampler |

### Avoiding Recompilation in SO-Enabled Mode

With synchronous scheduling and structured-output support, `logit_mask` is always passed as a tensor to the model forward call, never `None`. This ensures `torch.compile` traces a single code path during warmup, and no recompilation is needed when the first structured output request arrives at serving time.

When structured-output support is enabled, warmup passes an all-True mask (all tokens allowed):

``` python
# In warmup_prefill() and warmup_decode():
dummy_logit_mask = torch.ones(
    num_reqs, self.vocab_size, dtype=torch.bool, device=self.device
)
_ = self.model(..., logit_mask=dummy_logit_mask)
```

By default, vLLM Neuron optimizes for SO-off traffic and does not create a dummy logit mask. This avoids the no-op mask allocation / transfer / sampling overhead for deployments that do not serve structured-output requests.

For servers that need to accept structured-output requests, enable SO support explicitly:

``` json
{
  "neuron_config": {
    "enable_structured_outputs": true
  }
}
```

In that mode, if no structured output requests are active, an all-True mask is created as a no-op:

``` python
# In execute_model():
logit_mask = self._get_grammar_bitmask(scheduler_output)
if logit_mask is None:
    logit_mask = torch.ones(
        num_logit_rows, self.vocab_size, dtype=torch.bool, device=self.device
    )
```

An all-True mask is mathematically a no-op: `logits.masked_fill(~True, -inf)` fills nothing. This avoids any `if logit_mask is not None` branches that would cause `torch.compile` to trace a different graph.

In SO-enabled mixed-traffic mode, the vLLM Neuron sampler always receives a mask tensor, so `masked_fill` stays on the traced path:

``` python
# In Sampler.forward():
logits = logits.masked_fill(~logit_mask, float('-inf'))
```

This "always-pass, never-None" behavior keeps a mixed structured-output / non-structured-output server on one stable tensor path and avoids recompilation when the first structured-output request arrives.

For SO-off-only deployments, this no-op mask is skipped by default, or can be made explicit by setting:

``` json
{
  "neuron_config": {
    "enable_structured_outputs": false
  }
}
```

This is a performance mode for servers that will not accept structured-output requests. If a request does include `structured_outputs` while this mode is enabled, vLLM Neuron rejects it with an actionable error asking the user to restart the server with `enable_structured_outputs=true`. It does not silently ignore the schema request, because returning an unconstrained answer would violate the client's requested contract.

## Jump-Forward Decoding

Disabled by default. Enable via `max_jump_forward_tokens` (requires `enable_structured_outputs=true` and `{"backend": "xgrammar"}` in
`structured_outputs_config`). Jump-forward decoding needs synchronous scheduling:

``` json
{
  "additional_config": {
    "neuron_config": {
      "enable_structured_outputs": true,
      "max_jump_forward_tokens": 3
    }
  },
  "structured_outputs_config": {"backend": "xgrammar"},
  "async_scheduling": false
}
```

Currently, jump-forward decoding in vLLM Neuron is supported only with xgrammar.

### Motivation

Since many structured output requests can be advanced with deterministic strings (say, JSON keys or parentheses in generally), we can skip forward passes and just tokenize that deterministic string instead.

### How Jump-Forward Works

``` text
Scheduler (scheduler.py)
  1. After the normal grammar bitmask advancement, check if we can advance the request with a deterministic string.
  2. Tokenize it via _compute_jump_forward_tokens
  3. Advance the grammar FSM over those tokens via grammar.accept_tokens(),
     and attach them to scheduler_output._jf_decode_tokens.
                    ↓
Model Runner (neuron_model_runner_v2.py, or neuron_model_runner.py on MRv1)
  4. When _jf_decode_tokens is present for a decode step, use the JF NEFF to compute KV tensors
  and sample the next token.
```

Each request in a JF step owns `1 + max_jump_forward_tokens` token slots: the
previously sampled token, its JF tokens, and padding. The JF NEFF computes the
KV of the real tokens in one pass and samples one token after the last JF
token, under the grammar mask built after the JF tokens. A request without JF
tokens in the same step runs as a plain decode row. On MRv2 the graph also
commits the JF tokens and the sampled token to the device request state (see
`vllm_neuron/vllm/worker/v2/jump_forward.py`).

The decode attention places the token slots of a request at the end of its KV
window, after the cached prefix. The scheduler therefore skips JF tokens for a
step in which any request is within `max_jump_forward_tokens` tokens of
`max_model_len`.

### Grammar Rollback Patch

We apply a monkey-patch that wraps `StructuredOutputManager.grammar_init` so we don't double accept jump-forward tokens.
This patch lives in `vllm_neuron/vllm/patches/jf_grammar_patch.py` (`apply_jf_grammar_rollback_patch`), and is applied when `max_jump_forward_tokens > 0`.

### Mutual Exclusivity with Speculative Decoding

JF and speculative decoding are mutually exclusive. If both are enabled, we default to spec-decoding.

### Data Parallelism (DP > 1)

JF decoding runs with DP > 1 when the DP ranks are independent replicas. With expert parallelism, or with attention, embedding, MLP or LM-head data parallelism, the ranks share collectives, so every rank would have to run the JF NEFF when one rank has JF tokens. Each rank's scheduler accepts its JF tokens before the ranks agree on the graph, so a rank cannot skip them for a peer's request near `max_model_len`, which would lose part of its KV prefix. The server therefore refuses `max_jump_forward_tokens > 0` in those configurations at startup.

## Structured Outputs with Async Scheduling

Model Runner V2 (MRv2) serves structured outputs under async scheduling with split sampling. For the engine loop and the batch queue, see [Async Scheduling and Async Execution](async-scheduling-and-async-execution.md).

### Problem

With async scheduling, the engine launches decode step N before the host has the token of step N-1. The grammar bitmask of step N depends on that token. A forward graph that samples on the device gets its mask as an input at launch time, so that mask is one step old.

### Split Sampling

Split sampling moves the mask out of the forward graph:

- The forward graph `F(N)` ends at the logits. The logits stay on the device, and the graph commits nothing to the slot state.
- The engine defers `sample_tokens(N)` until it has the token of step N-1, and gives it the bitmask of step N. So the bitmask is current.
- The sampler graph `S(N)` (`NeuronSplitSamplerAdapter`) applies the mask to the logits and samples with the `split_sample` method of the model (see [Tensor Parallelism](#tensor-parallelism)). Then it commits the tokens to the slot state. The next forward graph reads them from the slot state.

Each step runs `F(N)`, then `S(N)`. The host fills the bitmask of step N while `F(N)` runs:

``` text
device:  ... | S(N-1) | F(N)       | S(N) | F(N+1) | ...
                   |                  ^
host:              token N-1 -> bitmask(N) -> sample_tokens(N)
```

When the engine skips `sample_tokens` for a step, the next `execute_model` runs the sampler graph of that step with a mask that allows every token. Every rank gets the same RPCs, so every rank runs it.

### Bitmask Path

1. The engine core gets the bitmask of step N with `get_grammar_bitmask()` and passes it to `sample_tokens(N)`. When a structured-output row still waits for the token of step N-1, the engine first processes the output of step N-1.
2. `build_token_bitmask()` cuts the rank's vocab shard (`split_sampling_vocab_shard`) out of each request's bitmask row and puts it at the request's output row. Other rows allow every token. The bits stay packed, so the host copies one bit per token to the device.
3. The model's `split_sample` passes the packed bitmask to its `split_sampler`. This `Sampler` applies it with `apply_token_bitmask()`, which unpacks the bits and sets blocked tokens to `-inf`. It splits each row into equal parts of whole bitmask bytes, so a small batch uses more of the 128 partitions of a NeuronCore. Then it samples with `sample()`.

### Tensor Parallelism

The lm_head layout decides which logits the sampler graph gets.

**Vocab shard.** Llama 3, Qwen3, and GPT-OSS MXFP4 use this layout with lm_head TP and no lm_head DP.

- Each rank keeps its vocab shard of the logits and gets the bitmask of that shard.
- The sampler graph samples with the `Sampler` of the forward graph: a local top-k (or argmax), an all-gather of the candidates, and a global top-k.
- This sampler graph has an all-gather over the lm_head TP group, so every rank of the group must run each sampler graph. Each sampler graph runs in `sample_tokens` or in `execute_model`, which every rank of a model replica gets in the same order.

**Full vocab.** This layout applies with lm_head DP or one lm_head rank.

- With lm_head DP, the forward graph all-gathers the full-vocab logits of each rank's own rows. The sampler graph then has no collective, so one DP rank can run it alone.
- The sampler graph samples with a `Sampler` without a process group. It runs the top-k and the argmax in vocab chunks (`chunked_local_topk`), because a full-vocab `torch.topk` or `torch.argmax` is slow on the device.
- All ranks start with the same device generator state. With lm_head DP, the forward graph without split sampling draws the random values of the rows of all lm_head DP ranks at once. The sampler graph does the same and keeps the values of its own rows, so the rows of two lm_head DP ranks get different values. An idle DP rank runs no sampler graph, so its generator falls behind. After that, the rows of two ranks can get the same values. The value of each row is still uniform, so the sample of each request is correct.

### Enabling a Model

A causal LM gets split sampling from `SplitSamplingMixin` (`vllm_neuron/nn/split_sampling.py`). The model sets the attributes that the mixin declares: `config`, `on_device_sampling_config`, `sampler`, `tp_group` and `_gather_logits`. A model with lm_head DP or another lm_head group also sets `lm_head_tp_group`, `lm_head_tp_rank`, `lm_head_dp_size` and `lm_head_dp_group`. Without them, the mixin uses a column-parallel lm_head on the TP group.

- Inherit the mixin. With split sampling on, the forward returns `_split_sampling_output(...)`: the logits of the local rows (the tokens of `split_sampling_vocab_shard`), and the full-vocab logits for logprobs.
- The lm_head must give equal contiguous vocab shards in the order of the lm_head TP ranks. Without lm_head DP, the lm_head TP group is the TP group of one replica. With lm_head DP, the lm_head TP rank is the lm_head DP rank times the TP size plus the TP rank.
- With split sampling, the forward gets `logit_mask=None` and `sampling_params=None`. Do not gather or use them before the lm_head.

When `enable_structured_outputs` is true and an MRv2 server runs with async scheduling, the runner uses split sampling. Split sampling needs all of these conditions. If a condition is false, the server refuses to start and names the cause.

- On-device sampling is on, and the server uses the native route.
- The batch queue depth is 2 (`VLLM_NEURON_BATCH_QUEUE_DEPTH` is unset or 2).
- Speculative decoding, jump-forward decoding, the decode megakernel and the debug logits directory are off.
- The model is not a pooling or synthetic model, and it supports split sampling.

### Logprobs

Logprobs come from the logits before the mask, as with synchronous scheduling, and the host builds them with the same code. vLLM on GPU masks first, so here a top logprob can be a token that the grammar blocks, and the sampled token can rank below first. With a vocab shard, the forward graph also returns the gathered full-vocab logits. With the full vocab, the sampler graph's input logits are already full-vocab.

With `max_logprobs` 0, the forward graph skips the full-vocab output, and the server rejects logprobs requests as it does without structured outputs.

## Limitations

1. **On-device sampling required** Structured outputs are only supported with on-device sampling enabled. Attempting to use them with CPU sampling raises `NotImplementedError`.
2. **Async scheduling needs split sampling** An MRv2 server with structured outputs and async scheduling refuses to start when split sampling cannot apply (see [Enabling a Model](#enabling-a-model)), for example with jump-forward decoding. An MRv1 server, for example one with speculative decoding, starts but rejects each structured-output request. Use `--no-async-scheduling` for both.
3. **Batch queue depth 2** The engine defers `sample_tokens` by one step. A third batch in flight would make the bitmask miss the newest token. So split sampling refuses `VLLM_NEURON_BATCH_QUEUE_DEPTH` above 2.
4. **Two graphs for each step** With structured outputs and async scheduling, every step runs the forward graph and the sampler graph, also when no request in the step uses a grammar. On GPT-OSS 120B (decode DP8 × TP8, Trn3), the two graph launches leave the device idle for about 0.11 ms in each step.

## FAQ

**Q: How does vLLM pass the bitmask? Is it through logit_mask?**

In standard vLLM, the bitmask is NOT passed into the model. It's applied after the model returns logits, during CPU sampling. The grammar/bitmask logic lives in the sampler layer, not the model layer. We added the `logit_mask` parameter because vLLM Neuron does on-device sampling and the mask must be applied ON device before sampling. We had to thread it through `model.forward()` to get it to the sampler.

**Q: Why is the scheduler attaching the bitmask?**

The scheduler has access to `StructuredOutputManager`, which stores the grammar and computes the bitmask. We attach `_grammar_bitmask` to `SchedulerOutput` because that's the data structure that flows from scheduler to model_runner. The model runner does not have access to `StructuredOutputManager`. With async scheduling, split sampling gets the bitmask from `sample_tokens` instead.

**Q: Why not use SamplingMetadata or create a NeuronSamplingMetadata instead?**

`SamplingMetadata` is created inside vLLM's `InputBatch`, which we don't subclass. To add `grammar_bitmask` there, we'd need to subclass `InputBatch` or patch it after creation. `SchedulerOutput` is simpler since we already override the scheduler and it's the known data channel to model_runner. Even if we defined `NeuronSamplingMetadata`, we'd still need all the places that read metadata to understand it (or at least to carry an extra field through). That's a core vLLM change, not just plugin code.

**Q: But runner and scheduler are the same process why serialize through SchedulerOutput?**

They are in the same process, but the scheduler and model runner are separate components with a well-defined interface (`SchedulerOutput`). Using this existing data channel keeps the design clean and avoids coupling the model runner to the `StructuredOutputManager` internals.

## See Also

- `neuron-scheduler` Scheduler design including holdback queue and padding
- `vllm-integration-design-reference` Overall vLLM integration architecture
- [PR \#754](https://github.com/aws-neuron/vllm-neuron/pull/754) Structured outputs implementation
- [PR \#786](https://github.com/aws-neuron/vllm-neuron/pull/786) Tool calling implementation (built on structured outputs)
