> This page is for version 2.1.6 (Latest) (default).
> For other versions, use one of these documentation indexes:
> - 2.1.6 (Latest) (default): https://docs.nvidia.com/nim/large-language-models/2.1.6/llms.txt
> - 2.1.5: https://docs.nvidia.com/nim/large-language-models/2.1.5/llms.txt
> - 2.1.4: https://docs.nvidia.com/nim/large-language-models/2.1.4/llms.txt
> - 2.0.13: https://docs.nvidia.com/nim/large-language-models/2.0.13/llms.txt
> - 2.0.12: https://docs.nvidia.com/nim/large-language-models/2.0.12/llms.txt
> - 2.0.11: https://docs.nvidia.com/nim/large-language-models/2.0.11/llms.txt
> - 2.0.10: https://docs.nvidia.com/nim/large-language-models/2.0.10/llms.txt
> - 2.0.9: https://docs.nvidia.com/nim/large-language-models/2.0.9/llms.txt
> - 2.0.8: https://docs.nvidia.com/nim/large-language-models/2.0.8/llms.txt
> - 2.0.4-pb6: https://docs.nvidia.com/nim/large-language-models/2.0.4-pb6/llms.txt
> - Archive: https://docs.nvidia.com/nim/large-language-models/archive/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.nvidia.com/nim/large-language-models/llms.txt.

# Custom Logits Processing

> Write a custom vLLM logits processor, mount it into the NIM LLM and VLM container, and enable it with a CLI flag to control next-token scoring.

NIM LLM and VLM supports custom logits processing on the vLLM backend through [vLLM's native logits processor API](https://docs.vllm.ai/en/latest/features/custom_logitsprocs/).
You can write your own processor, mount it into the container as a volume, and enable it with a single CLI flag.

> **Note**
>
> Custom logits processors are not supported on NIM's SGLang backend. The `--logits-processors` argument and the `vllm_xargs` request extension in this procedure apply to vLLM.

Custom processors operate at the *batch level*. vLLM batches multiple requests into a single tensor for GPU efficiency, so your processor receives the entire batch together. Each row in the tensor is one request.

You can still toggle behavior *per request*. Clients pass custom arguments in `vllm_xargs`. Your processor reads each row's `extra_args` and modifies only the rows that opt in.

Before you start, complete the following prerequisites:

1. Write a processor that extends `vllm.v1.sample.logits_processor.LogitsProcessor`, or use the example in this procedure.
2. Confirm that the processor module is importable from the `PYTHONPATH` you will set on the container.

To run a custom logits processor, complete the following steps:

1. Implement the five `LogitsProcessor` methods in your processor script.

   Custom processors extend `vllm.v1.sample.logits_processor.LogitsProcessor`.
   The following table describes each method:

   | Method                | Purpose                                                                                                                                                  |
   | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
   | `validate_params`     | Class method. Validates per-request parameters when a request arrives. Raise `ValueError` to reject the request.                                         |
   | `__init__`            | Runs during server startup. Initialize any state your processor needs.                                                                                   |
   | `apply`               | Called every engine step. Receives the full logits tensor `(num_requests, vocab_size)` and returns the modified tensor.                                  |
   | `is_argmax_invariant` | Return `True` if your processor never changes which token has the highest logit. Return `False` otherwise.                                               |
   | `update_state`        | Called every engine step with a `BatchUpdate` describing which requests were added, removed, or moved in the batch. Use this to track per-request state. |

   #### Example: BanTokenProcessor

   The following processor bans a single token per request. Requests opt in by sending `{"vllm_xargs": {"ban_token_id": <int>}}`. Requests that do not send this parameter are unaffected.

   ```python
   import torch
   from vllm.config import VllmConfig
   from vllm.sampling_params import SamplingParams
   from vllm.v1.sample.logits_processor import BatchUpdate, LogitsProcessor, MoveDirectionality

   class BanTokenProcessor(LogitsProcessor):

       @classmethod
       def validate_params(cls, params: SamplingParams):
           ban = params.extra_args and params.extra_args.get("ban_token_id")
           if ban is not None and not isinstance(ban, int):
               raise ValueError(f"ban_token_id must be int, got {type(ban).__name__}")

       def __init__(self, vllm_config: VllmConfig, device: torch.device, is_pin_memory: bool):
           self.banned: dict[int, int] = {}

       def is_argmax_invariant(self) -> bool:
           return False

       def update_state(self, batch_update: BatchUpdate | None) -> None:
           if not batch_update:
               return

           for index, params, _, _ in batch_update.added:
               ban = params.extra_args and params.extra_args.get("ban_token_id")
               if ban is not None:
                   self.banned[index] = ban
               else:
                   self.banned.pop(index, None)

           if not self.banned:
               return

           for index in batch_update.removed:
               self.banned.pop(index, None)

           for src, dst, direction in batch_update.moved:
               src_val = self.banned.pop(src, None)
               dst_val = self.banned.pop(dst, None)
               if src_val is not None:
                   self.banned[dst] = src_val
               if direction == MoveDirectionality.SWAP and dst_val is not None:
                   self.banned[src] = dst_val

       def apply(self, logits: torch.Tensor) -> torch.Tensor:
           if not self.banned:
               return logits

           for req_idx, token_id in self.banned.items():
               logits[req_idx, token_id] = float("-inf")

           return logits
   ```

2. Place your processor script in a local directory, for example `/home/user/my_processors/ban_token.py`.

3. Volume-mount that directory into the container.

4. Pass the processor's module path to NIM by using the `--logits-processors` CLI argument.

   ```bash
   docker run --gpus all \
   -v /home/user/my_processors:/opt/nim/my_processors \
   -e PYTHONPATH=/opt/nim \
   -e NIM_MODEL_PATH=hf://meta-llama/Llama-3.2-1B-Instruct \
   -p 8000:8000 \
   nim-llm:local \
   nim-serve --logits-processors my_processors.ban_token:BanTokenProcessor
   ```

   The `--logits-processors` value uses Python's `module.submodule:ClassName` format. The code must be importable from `PYTHONPATH`.

5. Optional: Enable the processor for a specific request by passing custom arguments in `vllm_xargs`.

   Custom logits processors operate at the batch level, but clients can enable specific logits processors per request by passing custom arguments using `vllm_xargs`.

   ```bash
   curl -X POST http://localhost:8000/v1/completions \
     -H "Content-Type: application/json" \
     -d '{
       "model": "meta-llama/Llama-3.2-1B-Instruct",
       "prompt": "Once upon a time...",
       "max_tokens": 64,
       "vllm_xargs": {"ban_token_id": 42}
     }'
   ```

   For more details on invoking custom logits processors per request, refer to the [vLLM documentation](https://docs.vllm.ai/en/latest/features/custom_logitsprocs/#invoking-a-custom-logits-processor-against-a-request).

## Next Steps

After the processor loads, continue with [Custom Parsers and Chat Templates](/nim/large-language-models/advanced-use-cases/custom-parsers-and-templates) if you also need a custom tool-call or reasoning parser.