[Model] Support SenseNova-U1.5-8B-MoT and its distilled 8-step LoRA (#6516)
Signed-off-by: MrlixiangWE <mrdanaer@gmail.com> Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
1 parent
477083a103
commit
0288c3f56e
19 files changed
+2264
-66
No files matched your search
@@ -0,0 +1,368 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Paged KV cache for SenseNova-U1 autoregressive decode, and a CUDA graph over it.
|
||||
|
||||
Autoregressive decode dominates a think request -- 80% of the wall clock, at
|
||||
about 20 ms per token for 42 layers -- and almost all of the GPU idle in that
|
||||
window is Python/ATen dispatch rather than any CUDA call. A CUDA graph retires
|
||||
those dispatches, but capture needs static shapes, and the default cache grows
|
||||
K/V with ``torch.cat`` on every step.
|
||||
|
||||
Padding the cache to a bucket and masking the tail does give static shapes, but
|
||||
the mask is what costs: measured on an A800 at real decode shapes, a masked
|
||||
bucket attention runs 7.96-11.55 ms per step against 1.03 ms for an exact-length
|
||||
unmasked one, which is more than the graph saves.
|
||||
|
||||
The way out is a paged cache. ``flash_attn_varlen_func`` takes the used length
|
||||
as a *tensor* (``seqused_k``) alongside a ``block_table``, so the buffers stay
|
||||
bucket-sized and capturable while the kernel reads only the valid prefix. One
|
||||
captured graph then serves every length in the bucket.
|
||||
|
||||
Scope, and when to delete this. The cache is model-local on purpose:
|
||||
``DiffusionKVCacheManager`` reserves once per scheduler request, and
|
||||
``ARDiffusionModelRunner`` lives under ``vllm_omni/experimental``. SenseNova runs
|
||||
its whole autoregressive loop inside one pipeline ``forward``, so the decode
|
||||
steps never surface to the scheduler and it cannot admit, pool, evict, reuse a
|
||||
prefix for, or continuously batch them. What is here is therefore one set of
|
||||
buffers behind an identity block table, reused by whichever request fits them,
|
||||
not general paged-KV support: it holds while the pipeline serves one sequence
|
||||
per forward, and is released when sleep discards the memory it captured
|
||||
against. Once the decode loop is
|
||||
driven by a scheduler-visible runner, or the pipeline handles more than one
|
||||
sequence per forward, delete this file and use the manager instead.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
BLOCK_SIZE = 16
|
||||
# Growth schedule. Each new bucket costs one capture, so keep the list short and
|
||||
# let the last entry cover the tail rather than doubling forever.
|
||||
BUCKETS = (512, 1024, 2048, 4096, 8192)
|
||||
# Past the last bucket the schedule grows by this much at a time. A request
|
||||
# decodes at most `max_think_tokens` (1024) or `max_tokens` (512) steps, so a
|
||||
# step this size costs at most one reallocation per request. Doubling the last
|
||||
# bucket instead would also cost at most one, but a 9,100-token request would
|
||||
# then reserve 766 MiB it never uses, against 118 MiB here.
|
||||
TAIL_STEP = 2048
|
||||
|
||||
|
||||
# Every argument to the kernel is passed by keyword, so the probe covers all of
|
||||
# them. An older wheel can export `flash_attn_varlen_func` without the paged
|
||||
# ones, or under different names, and a version string would not say which;
|
||||
# probe the signature and fall back to SDPA when any is missing.
|
||||
_REQUIRED_KWARGS = (
|
||||
"max_seqlen_q",
|
||||
"cu_seqlens_q",
|
||||
"max_seqlen_k",
|
||||
"seqused_k",
|
||||
"block_table",
|
||||
"softmax_scale",
|
||||
"causal",
|
||||
)
|
||||
|
||||
|
||||
def _flash_varlen():
|
||||
"""Import lazily: the bundled kernel is CUDA-only and optional."""
|
||||
from vllm.vllm_flash_attn import flash_attn_varlen_func
|
||||
|
||||
return flash_attn_varlen_func
|
||||
|
||||
|
||||
def _accepts_paged_kwargs(fn) -> bool:
|
||||
try:
|
||||
params = inspect.signature(fn).parameters
|
||||
except (TypeError, ValueError): # pragma: no cover - no introspectable signature
|
||||
return False
|
||||
return all(name in params for name in _REQUIRED_KWARGS)
|
||||
|
||||
|
||||
def paged_decode_supported(device: torch.device, head_dim: int) -> bool:
|
||||
if device.type != "cuda":
|
||||
return False
|
||||
if head_dim % 8 or head_dim > 256:
|
||||
return False
|
||||
try:
|
||||
fn = _flash_varlen()
|
||||
except Exception as exc: # pragma: no cover - depends on the wheel
|
||||
logger.debug("Paged decode unavailable: %s", exc)
|
||||
return False
|
||||
if not _accepts_paged_kwargs(fn):
|
||||
logger.debug("Paged decode unavailable: flash_attn_varlen_func lacks %s", _REQUIRED_KWARGS)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def dynamic_lora_wrappers_present(module) -> bool:
|
||||
"""True once ``DiffusionLoRAManager`` has wrapped layers under ``module``.
|
||||
|
||||
The manager replaces linear layers with ``BaseLayerWithLoRA`` and then
|
||||
binds, rescales or resets slot 0 per request; the wrappers stay in the tree
|
||||
afterwards. Capture records the module tree and the branches that ran during
|
||||
it, so a graph taken before an adapter was bound would replay without the
|
||||
adapter's matmuls and one taken with it bound would survive its removal --
|
||||
both silently, and neither visible in the shape, dtype and bucket that decide
|
||||
reuse. Nothing captured may outlive a request once these exist.
|
||||
|
||||
The distilled LoRA is not affected: it is fused one-way into the weights and
|
||||
leaves no wrapper behind.
|
||||
"""
|
||||
try:
|
||||
from vllm.lora.layers import BaseLayerWithLoRA
|
||||
except ImportError: # pragma: no cover - depends on the wheel
|
||||
return False
|
||||
return any(isinstance(m, BaseLayerWithLoRA) for m in module.modules())
|
||||
|
||||
|
||||
def _bucket_for(length: int) -> int:
|
||||
for b in BUCKETS:
|
||||
if length <= b:
|
||||
return b
|
||||
# Past the schedule, grow in TAIL_STEP-sized steps. Rounding to a whole
|
||||
# number of blocks here would reallocate and re-capture every BLOCK_SIZE
|
||||
# tokens: a think edit with two 2048x2048 inputs runs to about 9,100 tokens
|
||||
# and paid 41 reallocations and 42 captures in one request.
|
||||
over = length - BUCKETS[-1]
|
||||
return BUCKETS[-1] + ((over + TAIL_STEP - 1) // TAIL_STEP) * TAIL_STEP
|
||||
|
||||
|
||||
class PagedDecodeCache:
|
||||
"""Per-layer paged K/V for single-token decode.
|
||||
|
||||
Layout follows what ``flash_attn_varlen_func`` accepts with a block table:
|
||||
``(num_blocks, BLOCK_SIZE, kv_heads, head_dim)``. ``seqused`` holds the
|
||||
number of valid tokens and is the only thing that changes between decode
|
||||
steps, which is what lets a captured graph be replayed unchanged.
|
||||
"""
|
||||
|
||||
def __init__(self, num_layers, kv_heads, head_dim, length, device, dtype):
|
||||
self.kv_heads = kv_heads
|
||||
self.head_dim = head_dim
|
||||
self.device = device
|
||||
self.dtype = dtype
|
||||
self.bucket = _bucket_for(length)
|
||||
nblocks = self.bucket // BLOCK_SIZE
|
||||
shape = (nblocks, BLOCK_SIZE, kv_heads, head_dim)
|
||||
self.k = [torch.zeros(shape, device=device, dtype=dtype) for _ in range(num_layers)]
|
||||
self.v = [torch.zeros(shape, device=device, dtype=dtype) for _ in range(num_layers)]
|
||||
self.block_table = torch.arange(nblocks, device=device, dtype=torch.int32).unsqueeze(0)
|
||||
self.cu_seqlens_q = torch.tensor([0, 1], device=device, dtype=torch.int32)
|
||||
self.seqused = torch.zeros(1, device=device, dtype=torch.int32)
|
||||
# The write slot has to live in a tensor, not a Python int. Under graph
|
||||
# capture a Python index is baked in at capture time, so every replay
|
||||
# would overwrite the same slot -- correct eagerly, silently wrong once
|
||||
# captured.
|
||||
self.pos = torch.zeros(1, device=device, dtype=torch.int64)
|
||||
self._length = 0
|
||||
# Bumped whenever the buffers are reallocated, so a graph runner can
|
||||
# tell that its capture no longer points at live memory.
|
||||
self.generation = 0
|
||||
|
||||
@property
|
||||
def length(self) -> int:
|
||||
return self._length
|
||||
|
||||
def set_length(self, n: int) -> None:
|
||||
self._length = n
|
||||
self.seqused.fill_(n)
|
||||
self.pos.fill_(n - 1)
|
||||
|
||||
def reusable_for(self, num_layers, kv_heads, head_dim, dtype, length) -> bool:
|
||||
"""Can this cache serve another request without reallocating?
|
||||
|
||||
Reusing the buffers is what lets captured graphs survive across
|
||||
requests: a capture binds the addresses it recorded, so a fresh cache
|
||||
forces a fresh capture.
|
||||
"""
|
||||
return (
|
||||
len(self.k) == num_layers
|
||||
and self.kv_heads == kv_heads
|
||||
and self.head_dim == head_dim
|
||||
and self.dtype == dtype
|
||||
and _bucket_for(length) <= self.bucket
|
||||
)
|
||||
|
||||
def load_prefix(self, cache) -> bool:
|
||||
"""Copy a prefill cache into the paged buffers.
|
||||
|
||||
Only the first ``seqused`` rows are ever read, so the tail is left as
|
||||
whatever the previous request wrote. Returns False for an empty cache.
|
||||
"""
|
||||
layer0 = cache.layers[0]
|
||||
if layer0.keys is None:
|
||||
return False
|
||||
prefix = layer0.keys.shape[2]
|
||||
for i in range(len(self.k)):
|
||||
keys, values = cache.layers[i].keys, cache.layers[i].values
|
||||
# [B, H, S, D] -> [S, H, D], then into the paged blocks
|
||||
self._write_prefix(i, keys[0].transpose(0, 1), values[0].transpose(0, 1))
|
||||
self.set_length(prefix)
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def from_dynamic_cache(cls, cache, num_layers, device, dtype, min_length=0):
|
||||
"""Allocate buffers for a prefill cache and copy it in."""
|
||||
layer0 = cache.layers[0]
|
||||
if layer0.keys is None:
|
||||
return None
|
||||
_, kv_heads, prefix, head_dim = layer0.keys.shape
|
||||
obj = cls(num_layers, kv_heads, head_dim, max(prefix + 1, min_length), device, dtype)
|
||||
obj.load_prefix(cache)
|
||||
return obj
|
||||
|
||||
def _write_prefix(self, layer_idx, keys_shd, values_shd):
|
||||
n = keys_shd.shape[0]
|
||||
flat_k = self.k[layer_idx].view(-1, self.kv_heads, self.head_dim)
|
||||
flat_v = self.v[layer_idx].view(-1, self.kv_heads, self.head_dim)
|
||||
flat_k[:n].copy_(keys_shd)
|
||||
flat_v[:n].copy_(values_shd)
|
||||
|
||||
def grow(self, length: int) -> bool:
|
||||
"""Move to the next bucket, keeping the tokens already stored.
|
||||
|
||||
Everything is built into locals first and published in one step. A
|
||||
resize that failed part way -- an allocation for a later layer, say --
|
||||
would otherwise leave new K beside old V under the ``generation`` a
|
||||
captured graph is keyed on, so the next request would keep selecting
|
||||
that graph and replay it over storage that had just been freed.
|
||||
"""
|
||||
new_bucket = _bucket_for(length)
|
||||
if new_bucket == self.bucket:
|
||||
return False
|
||||
nblocks = new_bucket // BLOCK_SIZE
|
||||
shape = (nblocks, BLOCK_SIZE, self.kv_heads, self.head_dim)
|
||||
old_len = self._length
|
||||
new_k, new_v = [], []
|
||||
for old_k, old_v in zip(self.k, self.v):
|
||||
k = torch.zeros(shape, device=self.device, dtype=self.dtype)
|
||||
v = torch.zeros(shape, device=self.device, dtype=self.dtype)
|
||||
k.view(-1, self.kv_heads, self.head_dim)[:old_len].copy_(
|
||||
old_k.view(-1, self.kv_heads, self.head_dim)[:old_len]
|
||||
)
|
||||
v.view(-1, self.kv_heads, self.head_dim)[:old_len].copy_(
|
||||
old_v.view(-1, self.kv_heads, self.head_dim)[:old_len]
|
||||
)
|
||||
new_k.append(k)
|
||||
new_v.append(v)
|
||||
block_table = torch.arange(nblocks, device=self.device, dtype=torch.int32).unsqueeze(0)
|
||||
|
||||
# Publish. New buffers mean any graph captured against the old ones is
|
||||
# stale, so the generation moves in the same step that hands them over.
|
||||
self.k, self.v, self.block_table, self.bucket = new_k, new_v, block_table, new_bucket
|
||||
self.generation += 1
|
||||
self.set_length(old_len)
|
||||
logger.debug("Paged decode grew to bucket %d at length %d (generation %d)", new_bucket, length, self.generation)
|
||||
return True
|
||||
|
||||
def attend(self, layer_idx, query_bhsd, key_bhsd, value_bhsd, softmax_scale):
|
||||
"""Append this step's K/V and attend over the whole valid prefix.
|
||||
|
||||
Writes at ``length - 1`` because the caller has already advanced the
|
||||
length for this step. Both the slot and the attended length come from
|
||||
device tensors, so a captured graph reads whatever they hold at replay
|
||||
rather than whatever they held at capture.
|
||||
"""
|
||||
flat_k = self.k[layer_idx].view(-1, self.kv_heads, self.head_dim)
|
||||
flat_v = self.v[layer_idx].view(-1, self.kv_heads, self.head_dim)
|
||||
flat_k.index_copy_(0, self.pos, key_bhsd[0, :, 0].unsqueeze(0))
|
||||
flat_v.index_copy_(0, self.pos, value_bhsd[0, :, 0].unsqueeze(0))
|
||||
heads, head_dim = query_bhsd.shape[1], query_bhsd.shape[3]
|
||||
q = query_bhsd[0].transpose(0, 1).reshape(1, heads, head_dim)
|
||||
out = _flash_varlen()(
|
||||
q,
|
||||
self.k[layer_idx],
|
||||
self.v[layer_idx],
|
||||
max_seqlen_q=1,
|
||||
cu_seqlens_q=self.cu_seqlens_q,
|
||||
max_seqlen_k=self.bucket,
|
||||
seqused_k=self.seqused,
|
||||
block_table=self.block_table,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=False,
|
||||
)
|
||||
return out.reshape(1, 1, heads, head_dim)
|
||||
|
||||
def to_dynamic_cache(self, cache) -> None:
|
||||
"""Write the decoded K/V back so the generation stage sees one cache.
|
||||
|
||||
Only decode is paged; the DiT stage that follows reads the ordinary
|
||||
cache, so the two are reconciled once at the hand-off rather than kept
|
||||
in sync on every step.
|
||||
"""
|
||||
n = self._length
|
||||
for i, layer in enumerate(cache.layers):
|
||||
keys = self.k[i].view(-1, self.kv_heads, self.head_dim)[:n]
|
||||
values = self.v[i].view(-1, self.kv_heads, self.head_dim)[:n]
|
||||
layer.keys = keys.transpose(0, 1).unsqueeze(0).contiguous()
|
||||
layer.values = values.transpose(0, 1).unsqueeze(0).contiguous()
|
||||
|
||||
|
||||
class DecodeGraphRunner:
|
||||
"""One captured decode step per KV bucket, replayed for every token.
|
||||
|
||||
The whole point of the paged cache is that everything the step reads which
|
||||
varies -- the token, its position, and how much of the cache is live -- sits
|
||||
in device tensors. So a single capture serves every step in a bucket: fill
|
||||
the tensors, replay, read the logits out of the static output.
|
||||
|
||||
A capture is invalidated when the cache reallocates (tracked by
|
||||
``PagedDecodeCache.generation``), which happens once per bucket boundary.
|
||||
"""
|
||||
|
||||
def __init__(self, language_model, cache, device):
|
||||
self.lm = language_model
|
||||
self.cache = cache
|
||||
self.device = device
|
||||
self.input_ids = torch.zeros(1, 1, dtype=torch.long, device=device)
|
||||
self.indexes = torch.zeros(3, 1, dtype=torch.long, device=device)
|
||||
self._graphs: dict[tuple[int, int], tuple[torch.cuda.CUDAGraph, torch.Tensor]] = {}
|
||||
self.captures = 0
|
||||
|
||||
def _forward(self):
|
||||
return self.lm(
|
||||
input_ids=self.input_ids,
|
||||
indexes=self.indexes,
|
||||
past_key_values=None,
|
||||
use_cache=False,
|
||||
paged_cache=self.cache,
|
||||
).logits
|
||||
|
||||
def _capture(self, key):
|
||||
# Warm up on a side stream first so cuBLAS workspaces and any lazy
|
||||
# allocation happen outside the capture. The warm-up recomputes this
|
||||
# same step, writing the same K/V to the same slot, so it is idempotent.
|
||||
side = torch.cuda.Stream()
|
||||
side.wait_stream(torch.cuda.current_stream())
|
||||
with torch.cuda.stream(side):
|
||||
for _ in range(3):
|
||||
self._forward()
|
||||
torch.cuda.current_stream().wait_stream(side)
|
||||
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
# A private pool would hand every runner its own arena and never give it
|
||||
# back, and a runner is rebuilt whenever the cache reallocates or a LoRA
|
||||
# wrapper appears: measured, that grew device memory by about 40 MiB per
|
||||
# request and never levelled off. The platform pool is shared, which is
|
||||
# what every other captured path in the tree uses.
|
||||
with torch.cuda.graph(graph, pool=current_platform.get_global_graph_pool()):
|
||||
logits = self._forward()
|
||||
self.captures += 1
|
||||
logger.debug("Captured decode graph for bucket=%d generation=%d", self.cache.bucket, self.cache.generation)
|
||||
self._graphs[key] = (graph, logits)
|
||||
return self._graphs[key]
|
||||
|
||||
def step(self, token, t_index):
|
||||
"""Run one decode step. Returns the static logits tensor."""
|
||||
self.input_ids[0, 0] = token
|
||||
self.indexes[0, 0] = t_index
|
||||
key = (self.cache.bucket, self.cache.generation)
|
||||
entry = self._graphs.get(key) or self._capture(key)
|
||||
entry[0].replay()
|
||||
return entry[1]
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""SenseNova-U1 Pipeline for vLLM-Omni.
|
||||
|
||||
SenseNova-U1 is a unified Qwen3-based model that uses Mixture-of-Tokenizers
|
||||
@@ -35,6 +35,13 @@ from vllm.logger import init_logger
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.lora.loader import (
|
||||
LoraLoaderMixin,
|
||||
_apply_diffusers_lora_alpha_scaling,
|
||||
_load_lora_state_dict,
|
||||
_prepare_lora_delta,
|
||||
_remap_state_dict_keys,
|
||||
)
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.interface import SupportsComponentDiscovery
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
@@ -44,7 +51,14 @@ from vllm_omni.transformers_utils.configs.sensenova_u1 import (
|
||||
SenseNovaU1Config,
|
||||
)
|
||||
|
||||
from .paged_decode import (
|
||||
DecodeGraphRunner,
|
||||
PagedDecodeCache,
|
||||
dynamic_lora_wrappers_present,
|
||||
paged_decode_supported,
|
||||
)
|
||||
from .sensenova_u1_transformer import (
|
||||
SenseNovaU1CausalLMOutput,
|
||||
SenseNovaU1ForCausalLM,
|
||||
clear_flash_kv_cache,
|
||||
create_block_causal_mask,
|
||||
@@ -446,7 +460,13 @@ class SenseNovaU1DenoisingAdapter(nn.Module):
|
||||
return self.language_model(*args, **kwargs)
|
||||
|
||||
|
||||
class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipelineProfilerMixin, CFGParallelMixin):
|
||||
class SenseNovaU1Pipeline(
|
||||
nn.Module,
|
||||
SupportsComponentDiscovery,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
CFGParallelMixin,
|
||||
LoraLoaderMixin,
|
||||
):
|
||||
"""SenseNova-U1 text-to-image and image-to-image pipeline for vllm-omni.
|
||||
|
||||
Builds the full model graph internally:
|
||||
@@ -709,8 +729,71 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
sigma = shift * sigma / (1 + (shift - 1) * sigma)
|
||||
return 1 - sigma
|
||||
|
||||
def _ar_step(self, next_token, t_idx, past_key_values):
|
||||
def _decode_context(self, past_key_values):
|
||||
"""Paged cache plus a captured graph for the AR loop, or ``None``.
|
||||
|
||||
Decode is where a think request spends most of its time, and every step
|
||||
issues the same work at the same shapes, so it is worth capturing. The
|
||||
cache has to be paged for that: it keeps the buffers a fixed size while
|
||||
the kernel reads only ``seqused_k`` of them, which is what lets one
|
||||
capture serve every step until the next bucket.
|
||||
|
||||
Both live on the pipeline and are reused across requests unless a LoRA
|
||||
adapter is being served dynamically. A capture binds the addresses it
|
||||
recorded, so a cache built per request forces a capture per request:
|
||||
measured, that left about 40 MiB of device memory behind on every
|
||||
request and re-captured every time. Reuse rests on the same thing the
|
||||
paged path already rests on -- one sequence in flight per pipeline
|
||||
forward.
|
||||
"""
|
||||
if os.environ.get("VLLM_OMNI_SENSENOVA_PAGED_DECODE", "1") != "1":
|
||||
return None
|
||||
head_dim = self.language_model.model.layers[0].self_attn.head_dim
|
||||
if not paged_decode_supported(torch.device(self.device), head_dim):
|
||||
return None
|
||||
if past_key_values is None or not past_key_values.layers:
|
||||
return None
|
||||
layer0 = past_key_values.layers[0]
|
||||
if layer0.keys is None:
|
||||
return None
|
||||
_, kv_heads, prefix, kv_head_dim = layer0.keys.shape
|
||||
device = torch.device(self.device)
|
||||
num_layers = len(self.language_model.model.layers)
|
||||
# Reuse is off once the LoRA manager holds the decode path: the test
|
||||
# below sees shape, dtype and bucket, none of which move when an adapter
|
||||
# is bound, rescaled or reset between requests.
|
||||
reuse = not dynamic_lora_wrappers_present(self.language_model)
|
||||
decode = getattr(self, "_paged_decode", None) if reuse else None
|
||||
if decode is None or not decode[0].reusable_for(
|
||||
num_layers, kv_heads, kv_head_dim, layer0.keys.dtype, prefix + 1
|
||||
):
|
||||
cache = PagedDecodeCache(num_layers, kv_heads, kv_head_dim, prefix + 1, device, layer0.keys.dtype)
|
||||
decode = (cache, DecodeGraphRunner(self.language_model, cache, device))
|
||||
self._paged_decode = decode if reuse else None
|
||||
if not decode[0].load_prefix(past_key_values):
|
||||
return None
|
||||
return decode
|
||||
|
||||
def release_captured_graphs(self) -> None:
|
||||
"""Drop the reused paged cache and the graphs captured against it.
|
||||
|
||||
Sleep level 2 discards the memory a capture recorded, so anything held
|
||||
across requests has to go with it. The next request rebuilds both.
|
||||
"""
|
||||
self._paged_decode = None
|
||||
|
||||
def _ar_step(self, next_token, t_idx, past_key_values, decode=None):
|
||||
"""One autoregressive token step. Constructs single-token `indexes` explicitly."""
|
||||
if decode is not None:
|
||||
cache, runner = decode
|
||||
if cache.length + 1 > cache.bucket:
|
||||
cache.grow(cache.length + 1)
|
||||
cache.set_length(cache.length + 1)
|
||||
logits = runner.step(int(next_token), t_idx + 1)
|
||||
# The caller reassigns its cache handle from this field; the paged
|
||||
# tokens are merged into it once, at the hand-off below.
|
||||
return SenseNovaU1CausalLMOutput(logits=logits, past_key_values=past_key_values)
|
||||
|
||||
indexes = torch.tensor([[t_idx + 1], [0], [0]], dtype=torch.long, device=self.device)
|
||||
outputs = self.language_model(
|
||||
input_ids=next_token.unsqueeze(0),
|
||||
@@ -725,24 +808,28 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
think_end_token_id = self.tokenizer.convert_tokens_to_ids("</think>")
|
||||
think_token_ids = []
|
||||
next_token = torch.argmax(prefix_outputs.logits[:, -1, :], dim=-1)
|
||||
decode = self._decode_context(past_key_values)
|
||||
|
||||
for _ in range(max_think_tokens):
|
||||
token_item = next_token.item()
|
||||
if token_item == eos_token_id:
|
||||
break
|
||||
if token_item == think_end_token_id:
|
||||
outputs = self._ar_step(next_token, t_idx, past_key_values)
|
||||
outputs = self._ar_step(next_token, t_idx, past_key_values, decode)
|
||||
past_key_values = outputs.past_key_values
|
||||
t_idx += 1
|
||||
think_token_ids.append(token_item)
|
||||
break
|
||||
|
||||
think_token_ids.append(token_item)
|
||||
outputs = self._ar_step(next_token, t_idx, past_key_values)
|
||||
outputs = self._ar_step(next_token, t_idx, past_key_values, decode)
|
||||
past_key_values = outputs.past_key_values
|
||||
t_idx += 1
|
||||
next_token = torch.argmax(outputs.logits[:, -1, :], dim=-1)
|
||||
|
||||
if decode is not None:
|
||||
decode[0].to_dynamic_cache(past_key_values)
|
||||
|
||||
# Append "\n\n<img>" tokens to cache
|
||||
append_ids = self.tokenizer(
|
||||
"\n\n<img>",
|
||||
@@ -797,6 +884,10 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
"""Autoregressive text decoding seeded from prefix logits."""
|
||||
eos_token_id = self.tokenizer.convert_tokens_to_ids("<|im_end|>")
|
||||
generated_ids: list[int] = []
|
||||
# Same paged decode as the think loop. No write-back at the end: the
|
||||
# caller returns the decoded string and never reads the cache again,
|
||||
# unlike the think path, which hands it to the generation stage.
|
||||
decode = self._decode_context(past_key_values)
|
||||
|
||||
logits = prefix_logits[:, -1, :]
|
||||
for _ in range(max_tokens):
|
||||
@@ -810,7 +901,7 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
if token_id == eos_token_id:
|
||||
break
|
||||
generated_ids.append(token_id)
|
||||
outputs = self._ar_step(next_token, t_idx, past_key_values)
|
||||
outputs = self._ar_step(next_token, t_idx, past_key_values, decode)
|
||||
past_key_values = outputs.past_key_values
|
||||
logits = outputs.logits[:, -1, :]
|
||||
t_idx += 1
|
||||
@@ -1174,8 +1265,37 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
layer.values = layer.values.expand(batch_size, *layer.values.shape[1:])
|
||||
prepare_flash_kv_cache(kv, current_len=token_hw, batch_size=batch_size)
|
||||
|
||||
@staticmethod
|
||||
def _is_warmup_request(req) -> bool:
|
||||
is_dummy_run = getattr(req, "is_dummy_run", None)
|
||||
if callable(is_dummy_run):
|
||||
return bool(is_dummy_run())
|
||||
return OmniDiffusionRequest.is_dummy_run_request_id(getattr(req, "request_id", None))
|
||||
|
||||
def _warm_ar_decode(self) -> None:
|
||||
"""Run one single-token decode at startup so its compiled region is built.
|
||||
|
||||
The engine's dummy request is a text-to-image run with think off. It
|
||||
exercises the prefill shape but never the decode one, so whatever the
|
||||
deploy config compiles for decode lands on the first real request
|
||||
instead of on readiness. Warmup is best effort and must not fail startup.
|
||||
"""
|
||||
try:
|
||||
lm = self.language_model
|
||||
device = torch.device(self.device)
|
||||
ids = torch.zeros(1, 2, dtype=torch.long, device=device)
|
||||
idx = torch.zeros(3, 2, dtype=torch.long, device=device)
|
||||
prefill = lm(input_ids=ids, indexes=idx, use_cache=True)
|
||||
nxt = torch.zeros(1, 1, dtype=torch.long, device=device)
|
||||
nidx = torch.tensor([[2], [0], [0]], dtype=torch.long, device=device)
|
||||
lm(input_ids=nxt, indexes=nidx, past_key_values=prefill.past_key_values, use_cache=True)
|
||||
except Exception as exc: # pragma: no cover - warmup is best effort
|
||||
logger.warning("Autoregressive decode warmup skipped: %s", exc)
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(self, req: DiffusionRequestBatch) -> DiffusionOutput:
|
||||
if self._is_warmup_request(req):
|
||||
self._warm_ar_decode()
|
||||
p = self._parse_request(req)
|
||||
|
||||
input_images = self._extract_input_images(p.first_prompt)
|
||||
@@ -1408,21 +1528,129 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
# Weight loading
|
||||
# -----------------------------------------------------------------------
|
||||
|
||||
# Shard name -> fused parameter, used by weight loading and LoRA loading.
|
||||
# More specific _mot_gen patterns FIRST to avoid substring ambiguity
|
||||
# (e.g. `.q_proj` is a substring of `.q_proj_mot_gen`).
|
||||
stacked_params_mapping: ClassVar[list[tuple[str, str, str | int]]] = [
|
||||
(".qkv_proj_mot_gen", ".q_proj_mot_gen", "q"),
|
||||
(".qkv_proj_mot_gen", ".k_proj_mot_gen", "k"),
|
||||
(".qkv_proj_mot_gen", ".v_proj_mot_gen", "v"),
|
||||
(".qkv_proj", ".q_proj", "q"),
|
||||
(".qkv_proj", ".k_proj", "k"),
|
||||
(".qkv_proj", ".v_proj", "v"),
|
||||
# MLP gate/up fused into MergedColumnParallelLinear
|
||||
(".gate_up_proj", ".gate_proj", 0),
|
||||
(".gate_up_proj", ".up_proj", 1),
|
||||
]
|
||||
|
||||
def load_lora_weights(
|
||||
self,
|
||||
pretrained_model_name_or_path: str | list[str],
|
||||
adapter_name: str | None = None,
|
||||
) -> None:
|
||||
"""Fuse a distilled few-step LoRA into the weights.
|
||||
|
||||
The checkpoints ship kohya `lora_down`/`lora_up`/`alpha` names, renamed
|
||||
here to the Diffusers names before `load_lora_into_module` routes each
|
||||
delta into its slice of the fused projections.
|
||||
"""
|
||||
if adapter_name in self.lora_loaded:
|
||||
return
|
||||
|
||||
paths = (
|
||||
[pretrained_model_name_or_path]
|
||||
if isinstance(pretrained_model_name_or_path, str)
|
||||
else list(pretrained_model_name_or_path)
|
||||
)
|
||||
if len(paths) != 1:
|
||||
raise ValueError(f"Expected exactly one distilled LoRA file, got {len(paths)}: {paths}")
|
||||
|
||||
state_dict = _load_lora_state_dict(paths[0])
|
||||
state_dict = _remap_state_dict_keys(
|
||||
state_dict,
|
||||
[(".lora_down.weight", ".lora_A.weight"), (".lora_up.weight", ".lora_B.weight")],
|
||||
)
|
||||
# Fold alpha and the low-rank product in fp32; scaling B in bf16 would
|
||||
# round once before the matmul and once after.
|
||||
state_dict = {k: v.to(torch.float32) for k, v in state_dict.items()}
|
||||
state_dict = _apply_diffusers_lora_alpha_scaling(state_dict)
|
||||
|
||||
applied = self._add_lora_deltas(state_dict)
|
||||
if not applied:
|
||||
raise ValueError(f"Distilled LoRA {paths[0]} matched no parameter of this pipeline.")
|
||||
logger.info("Fused distilled LoRA %s into %d parameters", paths[0], applied)
|
||||
# Fusion is one-way and there is no unload path, so keep only a sentinel;
|
||||
# the fp32 state dict is ~1.5 GiB and would stay resident for the process.
|
||||
self.lora_loaded[adapter_name] = paths[0]
|
||||
|
||||
def _fused_shards(self, base_key: str) -> list[tuple[str, str | int]] | None:
|
||||
"""Unfused source names and shard ids for a fused parameter, else None."""
|
||||
for param_name, weight_name, shard_id in self.stacked_params_mapping:
|
||||
if base_key.endswith(param_name):
|
||||
return [
|
||||
(base_key[: -len(param_name)] + w, sid)
|
||||
for p, w, sid in self.stacked_params_mapping
|
||||
if p == param_name
|
||||
]
|
||||
return None
|
||||
|
||||
def _add_lora_deltas(self, state_dict: dict[str, torch.Tensor]) -> int:
|
||||
"""Add every matching delta into its parameter, sharding through vLLM.
|
||||
|
||||
The delta read from the checkpoint spans the whole layer. A parameter of
|
||||
a parallel layer only holds this rank's slice of it, so the delta goes
|
||||
through the layer's own weight loader -- into a zeroed copy of the
|
||||
parameter, which is then added -- instead of being added directly.
|
||||
|
||||
Each parameter is fused in place as it is reached, so a failure part way
|
||||
through leaves the earlier ones fused and the pipeline has to be
|
||||
reloaded. Deferring the writes would mean holding every delta at once,
|
||||
and the deltas are full rank: 15.09 GiB for the 8B checkpoint, against
|
||||
the 192 MiB one parameter costs here. Fusion runs at load time, before
|
||||
the pipeline serves anything, so a partially fused model is never
|
||||
reachable from a request.
|
||||
"""
|
||||
applied = 0
|
||||
for name, param in self.named_parameters():
|
||||
if not name.endswith(".weight"):
|
||||
continue
|
||||
base_key = name[: -len(".weight")]
|
||||
shards = self._fused_shards(base_key)
|
||||
|
||||
deltas: list[tuple[torch.Tensor, str | int | None]] = []
|
||||
for src, shard_id in shards or [(base_key, None)]:
|
||||
delta, _ = _prepare_lora_delta(state_dict, src, None)
|
||||
if delta is None:
|
||||
deltas = []
|
||||
break
|
||||
deltas.append((delta, shard_id))
|
||||
if not deltas:
|
||||
continue
|
||||
|
||||
weight_loader = getattr(param, "weight_loader", None)
|
||||
buffer = torch.zeros_like(param.data)
|
||||
if weight_loader is None:
|
||||
# Not a parallel layer: the delta is already rank-local.
|
||||
buffer = torch.cat([d for d, _ in deltas]).to(device=param.device, dtype=param.dtype)
|
||||
else:
|
||||
saved = param.data
|
||||
try:
|
||||
param.data = buffer
|
||||
for delta, shard_id in deltas:
|
||||
delta = delta.to(device=param.device, dtype=param.dtype)
|
||||
if shard_id is None:
|
||||
weight_loader(param, delta)
|
||||
else:
|
||||
weight_loader(param, delta, shard_id)
|
||||
finally:
|
||||
param.data = saved
|
||||
with torch.no_grad():
|
||||
param.data.add_(buffer)
|
||||
applied += 1
|
||||
return applied
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
stacked_params_mapping = [
|
||||
# More specific _mot_gen patterns FIRST to avoid substring
|
||||
# ambiguity (e.g. `.q_proj` is a substring of `.q_proj_mot_gen`).
|
||||
(".qkv_proj_mot_gen", ".q_proj_mot_gen", "q"),
|
||||
(".qkv_proj_mot_gen", ".k_proj_mot_gen", "k"),
|
||||
(".qkv_proj_mot_gen", ".v_proj_mot_gen", "v"),
|
||||
(".qkv_proj", ".q_proj", "q"),
|
||||
(".qkv_proj", ".k_proj", "k"),
|
||||
(".qkv_proj", ".v_proj", "v"),
|
||||
# MLP gate/up fused into MergedColumnParallelLinear
|
||||
(".gate_up_proj", ".gate_proj", 0),
|
||||
(".gate_up_proj", ".up_proj", 1),
|
||||
]
|
||||
self.stacked_params_mapping = stacked_params_mapping
|
||||
stacked_params_mapping = self.stacked_params_mapping
|
||||
|
||||
params_dict = dict(self.named_parameters())
|
||||
loaded_params: set[str] = set()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Qwen3 LLM with Mixture-of-Tokenizers (MoT) for SenseNova-U1.
|
||||
|
||||
Ported from the sensenova_u1 package with vllm tensor-parallel support:
|
||||
@@ -16,6 +16,7 @@ from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from cache_dit import ForwardPattern
|
||||
from transformers.cache_utils import DynamicCache
|
||||
from vllm.logger import init_logger
|
||||
@@ -163,6 +164,18 @@ class Qwen3RotaryEmbedding(nn.Module):
|
||||
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
||||
|
||||
|
||||
def _build_3d_rope(config) -> tuple[Qwen3RotaryEmbedding, Qwen3RotaryEmbedding]:
|
||||
"""The t and h/w rotary modules: t uses half head_dim, h/w a quarter each."""
|
||||
t_config = copy.deepcopy(config)
|
||||
t_config.head_dim = config.head_dim // 2
|
||||
|
||||
hw_config = copy.deepcopy(config)
|
||||
hw_config.head_dim = config.head_dim // 4
|
||||
hw_config.rope_theta = config.rope_theta_hw
|
||||
hw_config.max_position_embeddings = config.max_position_embeddings_hw
|
||||
return Qwen3RotaryEmbedding(config=t_config), Qwen3RotaryEmbedding(config=hw_config)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Norms
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -175,11 +188,9 @@ class Qwen3RMSNorm(nn.Module):
|
||||
self.variance_epsilon = eps
|
||||
|
||||
def forward(self, hidden_states):
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.to(torch.float32)
|
||||
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
||||
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
return self.weight * hidden_states.to(input_dtype)
|
||||
# F.rms_norm keeps the fp32 accumulation internal and rounds once; the
|
||||
# cast chain it replaces rounded to bf16 before the weight multiply.
|
||||
return F.rms_norm(hidden_states, self.weight.shape, self.weight, self.variance_epsilon)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -303,23 +314,16 @@ class SenseNovaU1Attention(nn.Module):
|
||||
self.q_norm_hw_mot_gen = Qwen3RMSNorm(self.head_dim // 2, eps=config.rms_norm_eps)
|
||||
self.k_norm_hw_mot_gen = Qwen3RMSNorm(self.head_dim // 2, eps=config.rms_norm_eps)
|
||||
|
||||
# 3D RoPE: t uses half head_dim, h/w each use quarter head_dim
|
||||
t_config = copy.deepcopy(config)
|
||||
t_config.head_dim = config.head_dim // 2
|
||||
self.rotary_emb = Qwen3RotaryEmbedding(config=t_config)
|
||||
|
||||
hw_config = copy.deepcopy(config)
|
||||
hw_config.head_dim = config.head_dim // 4
|
||||
hw_config.rope_theta = config.rope_theta_hw
|
||||
hw_config.max_position_embeddings = config.max_position_embeddings_hw
|
||||
self.rotary_emb_hw = Qwen3RotaryEmbedding(config=hw_config)
|
||||
|
||||
self.attn = Attention(
|
||||
num_heads=self.num_heads,
|
||||
head_size=self.head_dim,
|
||||
causal=False,
|
||||
softmax_scale=self.scaling,
|
||||
num_kv_heads=self.num_heads,
|
||||
# Keep K/V at their real head count. The SDPA backend already picks
|
||||
# a fused GQA kernel when the runtime shape allows one and expands
|
||||
# K/V itself when it does not; expanding here hides the GQA shape
|
||||
# from that check, so it never fires.
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
prefix=f"{prefix}.attn",
|
||||
)
|
||||
self.attn.attention = self.attn.sdpa_fallback
|
||||
@@ -339,10 +343,6 @@ class SenseNovaU1Attention(nn.Module):
|
||||
attention_mask: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
"""Run unified attention with [B, H, S, D] inputs. Returns [B, S, H, D]."""
|
||||
if self.num_kv_groups > 1:
|
||||
n = self.num_kv_groups
|
||||
key_bhsd = key_bhsd.repeat_interleave(n, dim=1)
|
||||
value_bhsd = value_bhsd.repeat_interleave(n, dim=1)
|
||||
q = query_bhsd.transpose(1, 2).contiguous()
|
||||
k = key_bhsd.transpose(1, 2).contiguous()
|
||||
v = value_bhsd.transpose(1, 2).contiguous()
|
||||
@@ -358,16 +358,16 @@ class SenseNovaU1Attention(nn.Module):
|
||||
attention_mask: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
"""Run unified attention with [B, S, H, D] inputs. Returns [B, S, H, D]."""
|
||||
if self.num_kv_groups > 1:
|
||||
n = self.num_kv_groups
|
||||
key_bshd = key_bshd.repeat_interleave(n, dim=2)
|
||||
value_bshd = value_bshd.repeat_interleave(n, dim=2)
|
||||
attention_mask = self._align_mask_dtype(attention_mask, query_bshd)
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
|
||||
return self.attn(query_bshd, key_bshd, value_bshd, attn_metadata)
|
||||
|
||||
def _project_and_rope(self, hidden_states, indexes, qkv_proj, q_norm, k_norm, q_norm_hw, k_norm_hw):
|
||||
"""Project Q/K/V via the given QKVParallelLinear and apply 3D RoPE."""
|
||||
def _project_and_rope(self, hidden_states, position_embeddings, qkv_proj, q_norm, k_norm, q_norm_hw, k_norm_hw):
|
||||
"""Project Q/K/V via the given QKVParallelLinear and apply 3D RoPE.
|
||||
|
||||
The three tables come from the model, which builds them once per forward
|
||||
because every layer is handed the same `indexes`.
|
||||
"""
|
||||
input_shape = hidden_states.shape[:-1] # (B, S)
|
||||
qkv, _ = qkv_proj(hidden_states)
|
||||
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
|
||||
@@ -376,9 +376,7 @@ class SenseNovaU1Attention(nn.Module):
|
||||
k = k.view(*input_shape, self.num_kv_heads, self.head_dim)
|
||||
v = v.view(*input_shape, self.num_kv_heads, self.head_dim)
|
||||
|
||||
cos_t, sin_t = self.rotary_emb(hidden_states, indexes[0].unsqueeze(0))
|
||||
cos_h, sin_h = self.rotary_emb_hw(hidden_states, indexes[1].unsqueeze(0))
|
||||
cos_w, sin_w = self.rotary_emb_hw(hidden_states, indexes[2].unsqueeze(0))
|
||||
(cos_t, sin_t), (cos_h, sin_h), (cos_w, sin_w) = position_embeddings
|
||||
|
||||
value_states = v.transpose(1, 2) # [B, H, S, D]
|
||||
try:
|
||||
@@ -433,13 +431,23 @@ class SenseNovaU1Attention(nn.Module):
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
query_states, key_states, value_states = self._project_and_rope(
|
||||
hidden_states,
|
||||
indexes,
|
||||
kwargs["position_embeddings"],
|
||||
self.qkv_proj,
|
||||
self.q_norm,
|
||||
self.k_norm,
|
||||
self.q_norm_hw,
|
||||
self.k_norm_hw,
|
||||
)
|
||||
# Single-token decode with a paged cache: append this step's K/V and let
|
||||
# the kernel read the valid prefix via `seqused_k`. Shapes stay fixed,
|
||||
# which is what makes the step capturable as a CUDA graph.
|
||||
paged = kwargs.get("paged_cache")
|
||||
if paged is not None and attention_mask is None and query_states.shape[2] == 1:
|
||||
attn_output = paged.attend(self.layer_idx, query_states, key_states, value_states, self.scaling)
|
||||
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
||||
attn_output, _ = self.o_proj(attn_output)
|
||||
return attn_output
|
||||
|
||||
update_cache = kwargs.get("update_cache", True)
|
||||
if past_key_values is not None:
|
||||
if update_cache:
|
||||
@@ -460,7 +468,7 @@ class SenseNovaU1Attention(nn.Module):
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
query_states, key_states, value_states = self._project_and_rope(
|
||||
hidden_states,
|
||||
indexes,
|
||||
kwargs["position_embeddings"],
|
||||
self.qkv_proj_mot_gen,
|
||||
self.q_norm_mot_gen,
|
||||
self.k_norm_mot_gen,
|
||||
@@ -659,6 +667,10 @@ class SenseNovaU1Model(nn.Module):
|
||||
)
|
||||
self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.norm_mot_gen = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
# Every layer receives the same `indexes`, so the tables are the same for
|
||||
# all of them: build them once per forward here and thread them down,
|
||||
# rather than giving every layer its own pair.
|
||||
self.rotary_emb, self.rotary_emb_hw = _build_3d_rope(config)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -690,15 +702,25 @@ class SenseNovaU1Model(nn.Module):
|
||||
past_len = past_key_values.get_seq_length() if past_key_values else 0
|
||||
seq_len = inputs_embeds.shape[1]
|
||||
total_len = past_len + seq_len
|
||||
mask = torch.zeros(1, 1, seq_len, total_len, device=inputs_embeds.device)
|
||||
if seq_len > 1:
|
||||
mask = torch.zeros(1, 1, seq_len, total_len, device=inputs_embeds.device)
|
||||
causal = torch.tril(torch.ones(seq_len, seq_len, device=inputs_embeds.device))
|
||||
mask[:, :, :, past_len:] = torch.where(causal == 1, 0.0, float("-inf"))
|
||||
else:
|
||||
# A single query token attends to every cached key, so the mask
|
||||
# this branch used to build was all zeros. Passing it changed no
|
||||
# result, only which SDPA kernel was reachable.
|
||||
mask = None
|
||||
causal_mask_mapping = {"full_attention": mask}
|
||||
else:
|
||||
causal_mask_mapping = attention_mask
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = (
|
||||
self.rotary_emb(hidden_states, indexes[0].unsqueeze(0)),
|
||||
self.rotary_emb_hw(hidden_states, indexes[1].unsqueeze(0)),
|
||||
self.rotary_emb_hw(hidden_states, indexes[2].unsqueeze(0)),
|
||||
)
|
||||
for layer in self.layers:
|
||||
hidden_states = layer(
|
||||
hidden_states,
|
||||
@@ -706,6 +728,7 @@ class SenseNovaU1Model(nn.Module):
|
||||
exist_und=exist_und,
|
||||
exist_gen=exist_gen,
|
||||
indexes=indexes,
|
||||
position_embeddings=position_embeddings,
|
||||
attention_mask=causal_mask_mapping,
|
||||
past_key_values=past_key_values,
|
||||
use_cache=use_cache,
|
||||
|
||||
Reference in new issue
Block a user