Signed-off-by: linzhenpl07 <linzhenpl07@gmail.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
9159cedbd7
commit
8e2e9b6b53
6 files changed
+703
-93
No files matched your search
@@ -51,6 +51,7 @@ from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import DistributedAutoencoderKLWan
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
get_classifier_free_guidance_rank,
|
||||
get_classifier_free_guidance_world_size,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
@@ -71,6 +72,13 @@ from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPi
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.entrypoints.openai.video_api_utils import positive_float
|
||||
from vllm_omni.experimental.world_models.adapters.state_cosmos3_adapter import (
|
||||
Cosmos3StateAdapter,
|
||||
)
|
||||
from vllm_omni.experimental.world_models.session_state import (
|
||||
SessionStateManager,
|
||||
resolve_session_state_config,
|
||||
)
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
from .action import (
|
||||
@@ -910,6 +918,24 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
)
|
||||
self.is_edge_model = transformer_cls is Cosmos3EdgeVFMTransformer
|
||||
|
||||
# Opt-in: route the per-CFG-branch UND text K/V through the shared
|
||||
# SessionStateManager (RFC #4480) instead of the transformer-instance
|
||||
# cache. This establishes request-keyed state isolation; it does not by
|
||||
# itself make the mutable pipeline safe for concurrent execution.
|
||||
# Default off -> the bespoke transformer-instance path below is unchanged.
|
||||
self._use_session_state, mm_max_sessions = resolve_session_state_config(
|
||||
enable=od_config.enable_session_state_manager,
|
||||
)
|
||||
self._memory_manager: SessionStateManager | None = (
|
||||
SessionStateManager(max_sessions=mm_max_sessions) if self._use_session_state else None
|
||||
)
|
||||
# Forward declaration for the future BDE paged path (Stage C/D). Nothing
|
||||
# writes this field in Phase 0; a non-None value is rejected by the guards
|
||||
# below. None means the dense session adapter or the bespoke path.
|
||||
self._bde_kv_state = None
|
||||
if getattr(self, "_use_session_state", False):
|
||||
logger.info("Cosmos3: session state manager enabled (max_sessions=%d)", mm_max_sessions)
|
||||
|
||||
# --- Scheduler ---
|
||||
# Distilled model differs from regular one only by scheduler,
|
||||
# distilled one uses FlowMatchEulerDiscreteScheduler, while
|
||||
@@ -1463,6 +1489,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
sp: OmniDiffusionSamplingParams,
|
||||
inputs: RoboLabPolicyInputs,
|
||||
pipeline_start: float,
|
||||
session_id: str | None = None,
|
||||
) -> DiffusionOutput:
|
||||
if self.is_distilled_model:
|
||||
raise self._distilled_unsupported_error("RoboLab/action policy requests are unsupported.")
|
||||
@@ -1576,6 +1603,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
guidance_interval=None,
|
||||
raw_action_dim=raw_action_dim,
|
||||
scheduler=scheduler,
|
||||
session_id=session_id,
|
||||
generator=generator,
|
||||
)
|
||||
|
||||
@@ -2415,6 +2443,49 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
action_velocity_mask = 1.0 - condition_mask
|
||||
return action_latents, action_velocity_mask, clean_action, raw_action_dim
|
||||
|
||||
# -- Session-memory bypass for UND text K/V (RFC #4480) -----------------
|
||||
# Mirrors DreamZero's `_kv_*` pattern: route through the BDE pool when set
|
||||
# (Stage C/D), else the session adapter (Stage B), else the bespoke
|
||||
# transformer-instance cache. All gated so the default path is unchanged.
|
||||
|
||||
def _new_cosmos3_state(self, session_id: str | None) -> Cosmos3StateAdapter | None:
|
||||
if getattr(self, "_memory_manager", None) is None:
|
||||
return None
|
||||
return Cosmos3StateAdapter(session_id, self._memory_manager)
|
||||
|
||||
def _kv_load_und(self, state: Cosmos3StateAdapter | None, is_negative: bool) -> bool:
|
||||
"""Load this branch's UND K/V onto the transformer before forward.
|
||||
|
||||
Returns True if the session/BDE path handled the load (caller skips the
|
||||
bespoke ``cond_cache`` assignment), False for the bespoke path.
|
||||
"""
|
||||
if getattr(self, "_bde_kv_state", None) is not None:
|
||||
raise NotImplementedError("BDE pool path for Cosmos3 UND K/V is Stage C/D")
|
||||
if state is not None:
|
||||
state.load_into_transformer(self.transformer, is_negative)
|
||||
return True
|
||||
return False
|
||||
|
||||
def _kv_capture_und(self, state: Cosmos3StateAdapter | None, is_negative: bool) -> None:
|
||||
"""After forward, store the freshly computed UND K/V for this branch (encode-once)."""
|
||||
if getattr(self, "_bde_kv_state", None) is not None:
|
||||
raise NotImplementedError("BDE pool path for Cosmos3 UND K/V is Stage C/D")
|
||||
if state is not None:
|
||||
state.capture_from_transformer(self.transformer, is_negative)
|
||||
|
||||
def _kv_reset_und(self, state: Cosmos3StateAdapter | None) -> None:
|
||||
"""Reset UND K/V at the start of a generation (replaces ``transformer.reset_cache()``).
|
||||
|
||||
Always clears the transformer-instance cache so no stale UND K/V leaks into
|
||||
paths that read it directly (cfg-parallel / no-CFG / bespoke fallback); also
|
||||
clears the session objects when session state is active.
|
||||
"""
|
||||
if getattr(self, "_bde_kv_state", None) is not None:
|
||||
raise NotImplementedError("BDE pool path for Cosmos3 UND K/V is Stage C/D")
|
||||
self.transformer.reset_cache()
|
||||
if state is not None:
|
||||
state.reset()
|
||||
|
||||
# -- Denoising loop (shared by T2V and I2V) -----------------------------
|
||||
|
||||
def diffuse(
|
||||
@@ -2438,6 +2509,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
guidance_interval: tuple[float, float] | None = None,
|
||||
raw_action_dim: int | None = None,
|
||||
scheduler: Any | None = None,
|
||||
session_id: str | None = None,
|
||||
generator: torch.Generator | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, ...]:
|
||||
"""Denoising loop with 3-mode CFG support (parallel, sequential, none).
|
||||
@@ -2470,7 +2542,9 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
do_cfg = guidance_scale > 1.0
|
||||
cfg_parallel = self._cfg_parallel_active() and do_cfg
|
||||
step_scheduler = scheduler if scheduler is not None else self.scheduler
|
||||
self.transformer.reset_cache()
|
||||
# Session-keyed UND K/V (RFC #4480); None => bespoke transformer-instance cache.
|
||||
kv_state = self._new_cosmos3_state(session_id)
|
||||
self._kv_reset_und(kv_state)
|
||||
|
||||
def _cfg_active_at(t: torch.Tensor) -> bool:
|
||||
if guidance_interval is None:
|
||||
@@ -2606,18 +2680,57 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
if sound_latents is not None:
|
||||
sound_latents = step_out[idx]
|
||||
|
||||
if cfg_parallel:
|
||||
for t in self.progress_bar(timesteps):
|
||||
timestep = t.unsqueeze(0)
|
||||
# Out-of-interval steps run with effective scale 1.0 so the
|
||||
# combined output equals the cond branch (uncond is dropped).
|
||||
# All ranks still execute both branches; no CFG-Parallel
|
||||
# divergence.
|
||||
step_scale = guidance_scale if _cfg_active_at(t) else 1.0
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=True,
|
||||
true_cfg_scale=step_scale,
|
||||
positive_kwargs=dict(
|
||||
try:
|
||||
if cfg_parallel:
|
||||
# Each CFG-parallel rank runs exactly one branch (rank 0 -> cond,
|
||||
# else uncond), so session keying loads/stores only this rank's branch.
|
||||
cfg_rank_is_negative = get_classifier_free_guidance_rank() != 0
|
||||
for t in self.progress_bar(timesteps):
|
||||
timestep = t.unsqueeze(0)
|
||||
# Outside the interval, scale=1 makes the combined output equal
|
||||
# the cond branch. Every rank remains on the same iteration and
|
||||
# collective schedule.
|
||||
step_scale = guidance_scale if _cfg_active_at(t) else 1.0
|
||||
self._kv_load_und(kv_state, is_negative=cfg_rank_is_negative)
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=True,
|
||||
true_cfg_scale=step_scale,
|
||||
positive_kwargs=dict(
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=cond_ids,
|
||||
text_mask=cond_mask,
|
||||
action_latents=action_latents,
|
||||
sound_latents=sound_latents,
|
||||
**shared_kwargs,
|
||||
),
|
||||
negative_kwargs=dict(
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=uncond_ids,
|
||||
text_mask=uncond_mask,
|
||||
action_latents=action_latents,
|
||||
sound_latents=sound_latents,
|
||||
**shared_kwargs,
|
||||
),
|
||||
cfg_normalize=False,
|
||||
)
|
||||
if kv_state is not None:
|
||||
self._kv_capture_und(kv_state, is_negative=cfg_rank_is_negative)
|
||||
_assign_step_out(_step(noise_pred, t, latents, action_latents, sound_latents))
|
||||
|
||||
elif do_cfg:
|
||||
cond_cache: tuple = (None, None)
|
||||
uncond_cache: tuple = (None, None)
|
||||
keep_uncond_for_cache = self._cache_requires_paired_cfg()
|
||||
|
||||
for t in self.progress_bar(timesteps):
|
||||
timestep = t.unsqueeze(0)
|
||||
cfg_active = _cfg_active_at(t)
|
||||
|
||||
if not self._kv_load_und(kv_state, is_negative=False):
|
||||
self.transformer.cached_kv, self.transformer.cached_freqs_gen = cond_cache
|
||||
noise_cond = self.transformer(
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=cond_ids,
|
||||
@@ -2625,79 +2738,67 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
action_latents=action_latents,
|
||||
sound_latents=sound_latents,
|
||||
**shared_kwargs,
|
||||
),
|
||||
negative_kwargs=dict(
|
||||
)
|
||||
if kv_state is not None:
|
||||
self._kv_capture_und(kv_state, is_negative=False)
|
||||
elif cond_cache[0] is None:
|
||||
cond_cache = (self.transformer.cached_kv, self.transformer.cached_freqs_gen)
|
||||
|
||||
if cfg_active or keep_uncond_for_cache:
|
||||
if not self._kv_load_und(kv_state, is_negative=True):
|
||||
self.transformer.cached_kv, self.transformer.cached_freqs_gen = uncond_cache
|
||||
noise_uncond = self.transformer(
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=uncond_ids,
|
||||
text_mask=uncond_mask,
|
||||
action_latents=action_latents,
|
||||
sound_latents=sound_latents,
|
||||
**shared_kwargs,
|
||||
)
|
||||
if kv_state is not None:
|
||||
self._kv_capture_und(kv_state, is_negative=True)
|
||||
elif uncond_cache[0] is None:
|
||||
uncond_cache = (self.transformer.cached_kv, self.transformer.cached_freqs_gen)
|
||||
# Outside the interval, scale=1.0 makes the combined result
|
||||
# equal to noise_cond; the uncond pass is computed only to
|
||||
# preserve cache-dit's cond/uncond parity.
|
||||
step_scale = guidance_scale if cfg_active else 1.0
|
||||
noise_pred = self.combine_cfg_noise(
|
||||
noise_cond,
|
||||
noise_uncond,
|
||||
step_scale,
|
||||
cfg_normalize=False,
|
||||
)
|
||||
else:
|
||||
noise_pred = noise_cond
|
||||
|
||||
_assign_step_out(_step(noise_pred, t, latents, action_latents, sound_latents))
|
||||
|
||||
else:
|
||||
# No CFG: a single cond branch per step. Bespoke (state None) keeps
|
||||
# using the transformer-instance cache exactly as before.
|
||||
for t in self.progress_bar(timesteps):
|
||||
timestep = t.unsqueeze(0)
|
||||
self._kv_load_und(kv_state, is_negative=False)
|
||||
noise_pred = self.transformer(
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=uncond_ids,
|
||||
text_mask=uncond_mask,
|
||||
action_latents=action_latents,
|
||||
sound_latents=sound_latents,
|
||||
**shared_kwargs,
|
||||
),
|
||||
cfg_normalize=False,
|
||||
)
|
||||
_assign_step_out(_step(noise_pred, t, latents, action_latents, sound_latents))
|
||||
|
||||
elif do_cfg:
|
||||
cond_cache: tuple = (None, None)
|
||||
uncond_cache: tuple = (None, None)
|
||||
|
||||
keep_uncond_for_cache = self._cache_requires_paired_cfg()
|
||||
|
||||
for t in self.progress_bar(timesteps):
|
||||
timestep = t.unsqueeze(0)
|
||||
cfg_active = _cfg_active_at(t)
|
||||
|
||||
self.transformer.cached_kv, self.transformer.cached_freqs_gen = cond_cache
|
||||
noise_cond = self.transformer(
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=cond_ids,
|
||||
text_mask=cond_mask,
|
||||
action_latents=action_latents,
|
||||
sound_latents=sound_latents,
|
||||
**shared_kwargs,
|
||||
)
|
||||
if cond_cache[0] is None:
|
||||
cond_cache = (self.transformer.cached_kv, self.transformer.cached_freqs_gen)
|
||||
|
||||
if cfg_active or keep_uncond_for_cache:
|
||||
self.transformer.cached_kv, self.transformer.cached_freqs_gen = uncond_cache
|
||||
noise_uncond = self.transformer(
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=uncond_ids,
|
||||
text_mask=uncond_mask,
|
||||
text_ids=cond_ids,
|
||||
text_mask=cond_mask,
|
||||
action_latents=action_latents,
|
||||
sound_latents=sound_latents,
|
||||
**shared_kwargs,
|
||||
)
|
||||
if uncond_cache[0] is None:
|
||||
uncond_cache = (self.transformer.cached_kv, self.transformer.cached_freqs_gen)
|
||||
# Outside the interval, scale=1.0 makes the combined result
|
||||
# equal to noise_cond; the uncond pass is computed only to
|
||||
# preserve cache-dit's cond/uncond parity.
|
||||
step_scale = guidance_scale if cfg_active else 1.0
|
||||
noise_pred = self.combine_cfg_noise(noise_cond, noise_uncond, step_scale, cfg_normalize=False)
|
||||
else:
|
||||
noise_pred = noise_cond
|
||||
|
||||
_assign_step_out(_step(noise_pred, t, latents, action_latents, sound_latents))
|
||||
|
||||
else:
|
||||
for t in self.progress_bar(timesteps):
|
||||
timestep = t.unsqueeze(0)
|
||||
noise_pred = self.transformer(
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=cond_ids,
|
||||
text_mask=cond_mask,
|
||||
action_latents=action_latents,
|
||||
sound_latents=sound_latents,
|
||||
**shared_kwargs,
|
||||
)
|
||||
_assign_step_out(_step(noise_pred, t, latents, action_latents, sound_latents))
|
||||
if kv_state is not None:
|
||||
self._kv_capture_und(kv_state, is_negative=False)
|
||||
_assign_step_out(_step(noise_pred, t, latents, action_latents, sound_latents))
|
||||
finally:
|
||||
# Cosmos3 currently receives a unique request_id rather than a
|
||||
# reusable rollout session id. Retaining its state would only pin
|
||||
# K/V buffers on device after this generation finishes.
|
||||
if kv_state is not None:
|
||||
self._memory_manager.drop_session(session_id)
|
||||
|
||||
outputs = [latents]
|
||||
if action_latents is not None:
|
||||
@@ -2794,6 +2895,13 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
guidance_interval: tuple[float, float] | None = None,
|
||||
generator: torch.Generator | None = None,
|
||||
) -> torch.Tensor:
|
||||
if getattr(self, "_use_session_state", False):
|
||||
raise NotImplementedError(
|
||||
"Cosmos3 transfer does not yet support SessionStateManager: "
|
||||
"its control/text CFG branches require richer cache keys. "
|
||||
"Disable the session state manager for transfer requests."
|
||||
)
|
||||
|
||||
def _active_at(t: torch.Tensor, interval: tuple[float, float] | None) -> bool:
|
||||
if interval is None:
|
||||
return True
|
||||
@@ -3178,7 +3286,12 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
sp = req.sampling_params
|
||||
robolab_inputs = self._build_robolab_policy_inputs(sp, prompt_data, getattr(req, "request_id", None))
|
||||
if robolab_inputs is not None:
|
||||
return self._forward_robolab_policy(sp, robolab_inputs, pipeline_start)
|
||||
return self._forward_robolab_policy(
|
||||
sp,
|
||||
robolab_inputs,
|
||||
pipeline_start,
|
||||
session_id=getattr(req, "request_id", None),
|
||||
)
|
||||
|
||||
if isinstance(prompt_data, str):
|
||||
prompt = prompt_data
|
||||
@@ -3543,6 +3656,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
guidance_interval=guidance_interval,
|
||||
raw_action_dim=raw_action_dim,
|
||||
scheduler=scheduler,
|
||||
session_id=getattr(req, "request_id", None),
|
||||
generator=generator,
|
||||
)
|
||||
|
||||
|
||||
@@ -1674,8 +1674,11 @@ class Cosmos3VFMTransformer(nn.Module):
|
||||
sound_tokens = self.pack_sound(sound_latents)
|
||||
s_sound = sound_tokens.shape[1]
|
||||
|
||||
# Run UND pathway once and cache K/V (replicated across all ranks)
|
||||
if self.cached_kv is None:
|
||||
# Run UND pathway once and cache K/V (replicated across all ranks).
|
||||
# freqs_gen (M-RoPE cos/sin) is derived purely from shape/fps and is
|
||||
# cached alongside UND K/V by both the bespoke and session-state paths.
|
||||
need_kv = self.cached_kv is None
|
||||
if need_kv or self.cached_freqs_gen is None:
|
||||
freqs_und, freqs_gen = self._compute_rope_freqs(
|
||||
text_mask,
|
||||
t,
|
||||
@@ -1691,13 +1694,14 @@ class Cosmos3VFMTransformer(nn.Module):
|
||||
num_vision_items=len(control_latent_list) + 1,
|
||||
share_vision_temporal_positions=transfer_share_vision_temporal_positions,
|
||||
)
|
||||
with self._offload_context("reasoner"):
|
||||
cached_kv_full = self.language_model(text_ids, freqs_und)
|
||||
self.cached_freqs_gen = freqs_gen
|
||||
|
||||
# Trim to real text length (remove padding). K/V stay replicated;
|
||||
# the framework Attention layer head-slices them via joint_key/value.
|
||||
self.cached_kv = [(k[:, :max_real_len], v[:, :max_real_len]) for k, v in cached_kv_full]
|
||||
if need_kv:
|
||||
with self._offload_context("reasoner"):
|
||||
cached_kv_full = self.language_model(text_ids, freqs_und)
|
||||
# Trim to real text length (remove padding). K/V stay replicated;
|
||||
# the framework Attention layer head-slices them via joint_key/value.
|
||||
self.cached_kv = [(k[:, :max_real_len], v[:, :max_real_len]) for k, v in cached_kv_full]
|
||||
|
||||
with self._offload_context("generator"):
|
||||
# Patchify latents and project to hidden space after UND cache
|
||||
|
||||
Reference in new issue
Block a user