Skip to content

vllm.v1.worker.iteration_timing

Non-blocking GPU timing of engine iterations.

An iteration is timed between two CUDA events recorded on the output worker's stream: one before execute_model, one after sample_tokens returns. The interval covers the model forward pass, sampling and speculative drafting, including host submission gaps.

The end event is often still pending when the iteration's own output is built, so a finished timing leaves the worker as a record with the first reply built after its end event has completed: the iteration's own output, a later step's output or a dummy batch. No step waits for a timing, so the last iterations before the engine goes idle are reported once it steps again.

Classes:

  • IterationTimer –

    Times iterations on the calling thread's CUDA stream.

Functions:

IterationTimer

Times iterations on the calling thread's CUDA stream.

Only the worker's main thread uses it, and it never waits for the GPU.

Methods:

  • start –

    Begin an iteration, dropping any that never finished.

  • take_ready –

    Pop the oldest iterations whose GPU work has completed.

Source code in vllm/v1/worker/iteration_timing.py
class IterationTimer:
    """Times iterations on the calling thread's CUDA stream.

    Only the worker's main thread uses it, and it never waits for the GPU.
    """

    def __init__(self) -> None:
        self._indices = count()
        self._started: tuple[IterationDetails, bool, torch.Event | None] | None = None
        self._pending: deque[_TimedIteration] = deque()

    def start(self, details: IterationDetails | None, is_dummy: bool = False) -> None:
        """Begin an iteration, dropping any that never finished.

        Without a scheduling snapshot the iteration is not timed.
        """
        self._started = (
            None if details is None else (details, is_dummy, _record_event())
        )

    def finish(self) -> None:
        if self._started is None:
            return
        details, is_dummy, start = self._started
        self._started = None
        # An iteration whose timing failed keeps its index, so the gap shows.
        index, end = next(self._indices), _record_event()
        if start is not None and end is not None:
            self._pending.append(_TimedIteration(index, details, is_dummy, start, end))

    def take_ready(self) -> list[SchedulerIterationDetails]:
        """Pop the oldest iterations whose GPU work has completed."""
        records: list[SchedulerIterationDetails] = []
        while self._pending:
            with _drop_on_cuda_error():
                if not self._pending[0].end.query():
                    break
                records.append(self._pending[0].read())
            self._pending.popleft()
        return records

start(details, is_dummy=False)

Begin an iteration, dropping any that never finished.

Without a scheduling snapshot the iteration is not timed.

Source code in vllm/v1/worker/iteration_timing.py
def start(self, details: IterationDetails | None, is_dummy: bool = False) -> None:
    """Begin an iteration, dropping any that never finished.

    Without a scheduling snapshot the iteration is not timed.
    """
    self._started = (
        None if details is None else (details, is_dummy, _record_event())
    )

take_ready()

Pop the oldest iterations whose GPU work has completed.

Source code in vllm/v1/worker/iteration_timing.py
def take_ready(self) -> list[SchedulerIterationDetails]:
    """Pop the oldest iterations whose GPU work has completed."""
    records: list[SchedulerIterationDetails] = []
    while self._pending:
        with _drop_on_cuda_error():
            if not self._pending[0].end.query():
                break
            records.append(self._pending[0].read())
        self._pending.popleft()
    return records

_TimedIteration dataclass

Methods:

  • read –

    Read the elapsed time. Both events must have completed.

Source code in vllm/v1/worker/iteration_timing.py
@dataclass
class _TimedIteration:
    index: int
    details: IterationDetails
    is_dummy: bool
    start: torch.Event
    end: torch.Event

    def read(self) -> SchedulerIterationDetails:
        """Read the elapsed time. Both events must have completed."""
        details = self.details
        return SchedulerIterationDetails(
            iteration_index=self.index,
            num_ctx_requests=details.num_ctx_requests,
            num_ctx_tokens=details.num_ctx_tokens,
            num_generation_requests=details.num_generation_requests,
            num_generation_tokens=details.num_generation_tokens,
            elapsed_ms=self.start.elapsed_time(self.end),
            num_encoder_inputs=details.num_encoder_inputs,
            num_encoder_output_tokens=details.num_encoder_output_tokens,
            is_dummy=self.is_dummy,
        )

read()

Read the elapsed time. Both events must have completed.

Source code in vllm/v1/worker/iteration_timing.py
def read(self) -> SchedulerIterationDetails:
    """Read the elapsed time. Both events must have completed."""
    details = self.details
    return SchedulerIterationDetails(
        iteration_index=self.index,
        num_ctx_requests=details.num_ctx_requests,
        num_ctx_tokens=details.num_ctx_tokens,
        num_generation_requests=details.num_generation_requests,
        num_generation_tokens=details.num_generation_tokens,
        elapsed_ms=self.start.elapsed_time(self.end),
        num_encoder_inputs=details.num_encoder_inputs,
        num_encoder_output_tokens=details.num_encoder_output_tokens,
        is_dummy=self.is_dummy,
    )

_WithIterationRecords

Bases: AsyncModelRunnerOutput

A step's output that also carries completed iteration records.

Source code in vllm/v1/worker/iteration_timing.py
class _WithIterationRecords(AsyncModelRunnerOutput):
    """A step's output that also carries completed iteration records."""

    def __init__(
        self,
        output: AsyncModelRunnerOutput,
        records: list[SchedulerIterationDetails],
    ) -> None:
        self._output = output
        self._records = records

    def get_output(self) -> ModelRunnerOutput:
        output = self._output.get_output()
        output.iteration_records = self._records
        return output

    def get_kv_connector_output(self) -> KVConnectorOutput | None:
        return self._output.get_kv_connector_output()

_drop_on_cuda_error()

Timing must never fail a step: a CUDA error drops the affected record.

Source code in vllm/v1/worker/iteration_timing.py
@contextmanager
def _drop_on_cuda_error() -> Iterator[None]:
    """Timing must never fail a step: a CUDA error drops the affected record."""
    try:
        yield
    except RuntimeError as error:
        # The timer lives on one worker per engine, whatever its local rank.
        logger.warning_once(
            "Dropping a GPU iteration timing: %s", str(error), scope="process"
        )

finish_iteration_timing(sample_tokens)

Decorates Worker.sample_tokens to record the iteration's end.

The returned output carries the iterations that have completed by then.

Source code in vllm/v1/worker/iteration_timing.py
def finish_iteration_timing(sample_tokens: Callable) -> Callable:
    """Decorates `Worker.sample_tokens` to record the iteration's end.

    The returned output carries the iterations that have completed by then.
    """

    @wraps(sample_tokens)
    def wrapper(self, *args, **kwargs):
        output = sample_tokens(self, *args, **kwargs)
        timer = self.iteration_timer
        # Only a deferred output ends a timed iteration: sample_tokens returns
        # None when its execute_model failed.
        if timer is None or not isinstance(output, AsyncModelRunnerOutput):
            return output
        timer.finish()
        records = timer.take_ready()
        return _WithIterationRecords(output, records) if records else output

    return wrapper

make_iteration_timer(vllm_config, rank)

Only the worker whose output the engine reads times iterations.

Source code in vllm/v1/worker/iteration_timing.py
def make_iteration_timer(vllm_config: VllmConfig, rank: int) -> IterationTimer | None:
    """Only the worker whose output the engine reads times iterations."""
    parallel_config = vllm_config.parallel_config
    output_rank = parallel_config.world_size - (
        parallel_config.tensor_parallel_size
        * parallel_config.prefill_context_parallel_size
    )
    if vllm_config.gpu_iteration_timing and rank == output_rank:
        return IterationTimer()
    return None

start_iteration_timing(execute_model)

Decorates Worker.execute_model to record the iteration's start.

Source code in vllm/v1/worker/iteration_timing.py
def start_iteration_timing(execute_model: Callable) -> Callable:
    """Decorates `Worker.execute_model` to record the iteration's start."""

    @wraps(execute_model)
    def wrapper(self, scheduler_output: SchedulerOutput, *args, **kwargs):
        if self.iteration_timer is not None:
            self.iteration_timer.start(scheduler_output.iteration_details)
        return execute_model(self, scheduler_output, *args, **kwargs)

    return wrapper

time_dummy_batch(execute_dummy_batch)

Decorates Worker.execute_dummy_batch to time the dummy iteration.

Returns the iterations that have completed by then.

Source code in vllm/v1/worker/iteration_timing.py
def time_dummy_batch(execute_dummy_batch: Callable) -> Callable:
    """Decorates `Worker.execute_dummy_batch` to time the dummy iteration.

    Returns the iterations that have completed by then.
    """

    @wraps(execute_dummy_batch)
    def wrapper(self) -> list[SchedulerIterationDetails] | None:
        timer = self.iteration_timer
        if timer is None:
            return execute_dummy_batch(self)
        timer.start(IterationDetails(), is_dummy=True)
        execute_dummy_batch(self)
        timer.finish()
        return timer.take_ready()

    return wrapper