vllm.model_executor.models.moonvit
¶
Classes:
-
Learnable2DInterpPosEmb– -
MLP2–Args:
-
MoonVisionPatchEmbed– -
MoonVitEncoderLayer– -
MoonVitPretrainedModel– -
Rope2DPosEmb–2D rotary position embedding with multi-resolution support.
Functions:
-
apply_rope–Args: (The leading dimensions of all inputs should be the same)
-
patch_merger_packed–CUDA-graph-safe equivalent of
patch_merger.
Learnable2DInterpPosEmb
¶
Bases: Module
Methods:
-
get_pos_embeds–Build packed per-token positional embeddings for a list of grids.
get_pos_embeds(grid_hws_list)
¶
Build packed per-token positional embeddings for a list of grids.
Returns a tensor of shape (sum(h * w), dim) formed by interpolating
the learned (height, width, dim) weight to each (h, w) grid and
concatenating the flattened results in the same order as
grid_hws_list. Lives outside the captured CUDA graph so the
per-grid Python iteration is safe.
MLP2
¶
MoonVisionPatchEmbed
¶
Bases: Module
Methods:
-
forward–Args:
forward(x, grid_hw=None, *, pos_embeds=None)
¶
Parameters:
-
(x¶(L, Channels)) –input tensor
-
(grid_hw¶(N, 2), default:None) –grid height and width
-
(pos_embeds¶Tensor | None, default:None) –precomputed positional embeddings of shape
(L, Cout). When provided,grid_hwis unused and the CUDA-graph-incompatible interpolation inself.pos_embis skipped.
Returns:
-
Tensor–(L, Cout) tensor
MoonVitEncoderLayer
¶
Bases: Module
Methods:
-
attention_qkvpacked–Args:
-
forward–Args:
attention_qkvpacked(x, cu_seqlens, rope_freqs_cis=None, max_seqlen=None)
¶
Args:
x (torch.Tensor): (seqlen, hidden_dim)
cu_seqlens (torch.Tensor):
max_seqlen: Optional precomputed scalar tensor. When omitted it
is derived from cu_seqlens, which produces a GPU scalar
that breaks CUDA graph capture.
forward(hidden_states, cu_seqlens, rope_freqs_cis=None, max_seqlen=None)
¶
Parameters:
-
(hidden_states¶Tensor) –non-packed (B, N, D) or packed (L, D). if non-packed, seqlens should be None, if packed, seqlens should be set
-
(max_seqlen¶Tensor | None, default:None) –optional precomputed max-sequence-length scalar.
Returns:
-
output(Tensor) –same shape of input, non-packed (B, N, D) for non-packed input, (L, D) for packed input
MoonVitPretrainedModel
¶
Bases: PreTrainedModel
Methods:
-
forward–Args:
-
prepare_encoder_metadata–Precompute every grid-dependent input the encoder needs.
forward(pixel_values, grid_hw, *, encoder_metadata=None)
¶
Args:
pixel_values (torch.Tensor): The input pixel values.
grid_hw (torch.Tensor): The grid height and width.
encoder_metadata: Optional precomputed metadata produced by
prepare_encoder_metadata. When provided every
.tolist() call in the forward path is skipped, the
returned tensor is the packed
(sum(new_h*new_w), kh*kw, hidden_size) form (suitable
for CUDA graph capture/replay), and grid_hw is unused.
When None the legacy path runs and returns a list of
per-image tensors.
prepare_encoder_metadata(grid_hws_list, *, max_batch_size=None, max_seqlen_override=None, device=None)
¶
Precompute every grid-dependent input the encoder needs.
Used by the CUDA graph capture and replay paths to precompute
every grid-dependent input outside the captured graph, so per-grid
Python iteration and .tolist() round-trips are fine; the
values are then copied into fixed-shape buffers for replay.
Parameters:
-
(grid_hws_list¶list[list[int]] | list[tuple[int, int]]) –List of
(h, w)patch-grid sizes per image. -
(max_batch_size¶int | None, default:None) –When set,
cu_seqlensis right-padded with its last value so the buffer covers up to this many sequences. Required at CUDA graph capture/replay so the buffer shape matches what was recorded; padding entries are zero-length sequences and are ignored by varlen attention. -
(max_seqlen_override¶int | None, default:None) –Override the per-replay max sequence length scalar. At capture this must be a safe upper bound (worst case: a single image consuming the full token budget) because the value is baked into the captured graph.
-
(device¶device | None, default:None) –Device for the metadata tensors. Defaults to the model's parameter device.
Rope2DPosEmb
¶
Bases: Module
2D rotary position embedding with multi-resolution support.
This class is intended to be used in the following way:
1. Before training, create an instance of Rope2DPosEmb. This instance will hold the precomputed cis.
2. Before each forward pass, call get_freqs_cis_by_* to get the freqs_cis tensor for this iteration.
3. During the forward pass, pass the freqs_cis tensor to each attention layer, and call apply just before each attention operation.
The rope is shared across all attention layers and all heads.
Refs: - RoFormer: https://arxiv.org/abs/2104.09864 - VisionLLaMA: https://arxiv.org/abs/2403.00522 - https://github.com/Meituan-AutoML/VisionLLaMA/blob/main/dit/models.py
Parameters:
-
(dim¶int) –usually the multi-head attention dimension, should be divisible by 4 (TODO: relax this constraint if needed)
-
(max_height¶int) –the maximum height of the 2D grid
-
(max_width¶int) –the maximum width of the 2D grid
-
(theta_base¶float, default:10000) –the base of the theta
-
(device¶str, default:device_type) –the device to store the precomputed cis
Methods:
-
get_freqs_cis_by_seqlens–Args:
-
get_freqs_cis_by_seqlens_list–List-based variant of
get_freqs_cis_by_seqlens.
Attributes:
-
precomputed_freqs_cis(Tensor) –Calculate the cis(freqs) for each position in the 2D grid.
precomputed_freqs_cis
cached
property
¶
Calculate the cis(freqs) for each position in the 2D grid.
complex tensor of shape (max_height, max_width, dim//2) and value:
height axis: ret[h, w, 2i] = cis(h * theta_base(-4i/dim))
weight axis: ret[h, w, 2i+1] = cis(w * theta_base(-4i/dim)) with (i in [0, dim//4))
note: cis is a mathematical notation defined by cis x = cos x + i sin x,
get_freqs_cis_by_seqlens(grid_hws)
¶
get_freqs_cis_by_seqlens_list(grid_hws_list)
¶
List-based variant of get_freqs_cis_by_seqlens.
Accepts a Python list of (h, w) pairs so callers that already
operate outside the captured CUDA graph can avoid materializing a
tensor + .tolist() round-trip.
_build_merge_gather_idx(grid_hws_list, merge_kernel_size)
¶
Build the per-token gather indices used by patch_merger_packed.
For each item with grid (h, w) and merge kernel (kh, kw), the output block at position (nh, nw) gathers the khkw input tokens at rows (nhkh + ih, nw*kw + iw) of that item, in (ih, iw) row-major order.
apply_rope(xq, xk, freqs_cis)
¶
(The leading dimensions of all inputs should be the same)
-
(xq¶Tensor) –query, tensor of shape (..., num_heads, head_dim)
-
(xk¶Tensor) –key, tensor of shape (..., num_heads, head_dim)
-
(freqs_cis¶Tensor) –tensor of shape (..., head_dim/2), dtype=torch.complex64. It contains the precomputed cis(freqs) for each position in the 2D grid.
Returns:
patch_merger_packed(x, gather_idx, merge_kernel_size)
¶
CUDA-graph-safe equivalent of patch_merger.
Uses a precomputed index tensor to gather the per-token reshape +
permute that patch_merger does inside a Python loop. The output is
the concatenated 3D tensor (sum(new_h * new_w), kh * kw, d_model),
matching what torch.cat(patch_merger(...)) would produce.