Video-to-Video
Diffusers
English
Chinese
video-editing
streaming
quantization
int8
text-stream-stripping
Instructions to use kylinfires/Joy-face_change_optimized with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use kylinfires/Joy-face_change_optimized with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("kylinfires/Joy-face_change_optimized", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
Sync main 7ac17e9: reference-KV reuse, FP8 head option, measured follow-ups
Browse files- README.md +12 -22
- deploy/xvideo/models/dit/__init__.py +1 -0
- deploy/xvideo/models/dit/dit.py +43 -1
- deploy/xvideo/models/models.py +7 -0
- deploy/xvideo/serving/joyomni_streaming.py +67 -7
README.md
CHANGED
|
@@ -1,19 +1,3 @@
|
|
| 1 |
-
---
|
| 2 |
-
license: apache-2.0
|
| 3 |
-
language:
|
| 4 |
-
- en
|
| 5 |
-
- zh
|
| 6 |
-
library_name: diffusers
|
| 7 |
-
pipeline_tag: video-to-video
|
| 8 |
-
base_model: jdopensource/JoyAI-Video-Edit
|
| 9 |
-
tags:
|
| 10 |
-
- video-editing
|
| 11 |
-
- streaming
|
| 12 |
-
- quantization
|
| 13 |
-
- int8
|
| 14 |
-
- text-stream-stripping
|
| 15 |
-
---
|
| 16 |
-
|
| 17 |
# Joy-face_change_optimized
|
| 18 |
|
| 19 |
[JoyAI-Video-Edit](https://github.com/jd-opensource/JoyAI-Video-Edit) 的优化分支(Apache-2.0)。
|
|
@@ -83,12 +67,18 @@ PyTorch 回退与 CUDA 版**逐张量验证一致**:99.997% 元素完全相同
|
|
| 83 |
- 可选 `JOYOMNI_KV_DTYPE=int8`:缓存的图像 K/V 存 int8(按 token/head 缩放),KV 1.44 → 0.74 GiB,稳态 15.3 → **14.7 GiB**;代价是与 bf16 缓存的输出差 **26.8 dB**(可复现测量),只在显存最紧时用。
|
| 84 |
- 会话可复现:`seed_everything(seed)` 之后,同 prompt/seed 的连续两个会话逐帧一致(138 dB);改动前因为参考图 VAE 采样走全局 RNG,两个会话相差约 25 dB。
|
| 85 |
|
| 86 |
-
### 2. 其他方向
|
| 87 |
-
|
| 88 |
-
- **
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
- **
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
## 快速开始
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# Joy-face_change_optimized
|
| 2 |
|
| 3 |
[JoyAI-Video-Edit](https://github.com/jd-opensource/JoyAI-Video-Edit) 的优化分支(Apache-2.0)。
|
|
|
|
| 67 |
- 可选 `JOYOMNI_KV_DTYPE=int8`:缓存的图像 K/V 存 int8(按 token/head 缩放),KV 1.44 → 0.74 GiB,稳态 15.3 → **14.7 GiB**;代价是与 bf16 缓存的输出差 **26.8 dB**(可复现测量),只在显存最紧时用。
|
| 68 |
- 会话可复现:`seed_everything(seed)` 之后,同 prompt/seed 的连续两个会话逐帧一致(138 dB);改动前因为参考图 VAE 采样走全局 RNG,两个会话相差约 25 dB。
|
| 69 |
|
| 70 |
+
### 2. 其他方向(本轮实测)
|
| 71 |
+
|
| 72 |
+
- **参考图 KV 复用** ✅ 已实现:参考图 prefill 跑的是 `skip_text_stream=True`,K/V 只依赖参考图 latent。
|
| 73 |
+
现在在主机侧留一个 LRU(2 条),同一参考图的新会话直接 memcpy 回显存,省一次 40 个 block 的前向(≈0.4 s/会话),
|
| 74 |
+
数值完全一致(复用 vs 重算逐帧 138.13 dB)。
|
| 75 |
+
- **VAE 分时驻留** ❌ 不适用:单卡部署里 encode / decode / pseudo-encode 三个角色共享同一份 VAE
|
| 76 |
+
(`_vae_for_role` 走 share 分支,`decode_vae = pipeline.vae`),全程只有 1.43 GiB 一份,没有"另一份"可释放。
|
| 77 |
+
原先说的省 0.7 GB 基于"两份 VAE"的假设,实测不成立;只有在 `--vae-decode-device` 指定第二张卡时才会出现第二份。
|
| 78 |
+
- **HEAD 输出量化** ⚠️ 已实现但**不建议开**:`JOYOMNI_FP8_HEAD=1` 把 `proj_out` + `condition_embedder`
|
| 79 |
+
(time_proj / time_embedder / text_embedder,152 M,291 MiB bf16)转成 FP8,省 145 MiB;
|
| 80 |
+
但与 bf16 输出差 **23.2 dB**(可复现测量),与整模型 8-bit 量化的 21.8 dB 同量级 —— 调制向量太敏感。
|
| 81 |
+
- **MLP 5-bit**:注意力 int8 + MLP 5-bit 约 13.3 GiB,误差预计 0.35%,相似度有望到 0.27–0.29(未做)
|
| 82 |
|
| 83 |
## 快速开始
|
| 84 |
|
deploy/xvideo/models/dit/__init__.py
CHANGED
|
@@ -6,6 +6,7 @@ from xvideo.models.dit.dit import (
|
|
| 6 |
end_text_kv_capture,
|
| 7 |
set_text_kv_active,
|
| 8 |
move_text_stream,
|
|
|
|
| 9 |
kv_entry_from_tensors,
|
| 10 |
kv_entry_tensors,
|
| 11 |
kv_cache_dtype,
|
|
|
|
| 6 |
end_text_kv_capture,
|
| 7 |
set_text_kv_active,
|
| 8 |
move_text_stream,
|
| 9 |
+
install_fp8_head,
|
| 10 |
kv_entry_from_tensors,
|
| 11 |
kv_entry_tensors,
|
| 12 |
kv_cache_dtype,
|
deploy/xvideo/models/dit/dit.py
CHANGED
|
@@ -303,6 +303,41 @@ def attention_backend() -> str:
|
|
| 303 |
return "SDPA (cuDNN/flash)"
|
| 304 |
|
| 305 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
_KV_DTYPE_ENV = "JOYOMNI_KV_DTYPE"
|
| 307 |
_KV_FP8_ENV = "JOYOMNI_KV_FP8"
|
| 308 |
_KV_FP8_MAX = 448.0
|
|
@@ -707,7 +742,14 @@ class WanTimeTextImageEmbedding(nn.Module):
|
|
| 707 |
timestep = timestep.flatten()
|
| 708 |
timestep = self.timesteps_proj(timestep)
|
| 709 |
|
| 710 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 711 |
if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
|
| 712 |
timestep = timestep.to(time_embedder_dtype)
|
| 713 |
temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
|
|
|
|
| 303 |
return "SDPA (cuDNN/flash)"
|
| 304 |
|
| 305 |
|
| 306 |
+
_FP8_HEAD_ENV = "JOYOMNI_FP8_HEAD"
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def install_fp8_head(transformer) -> int:
|
| 310 |
+
"""Quantise the head/embedding Linears to FP8 (JOYOMNI_FP8_HEAD=1).
|
| 311 |
+
|
| 312 |
+
Covers `proj_out` and all of `condition_embedder` (time_proj, time_embedder,
|
| 313 |
+
text_embedder: 152 M params). `img_in` keeps its 5-D weight and stays bf16.
|
| 314 |
+
"""
|
| 315 |
+
if os.environ.get(_FP8_HEAD_ENV, "").strip().lower() not in {"1", "true", "yes", "on"}:
|
| 316 |
+
return 0
|
| 317 |
+
if getattr(transformer, "_fp8_head_installed", False):
|
| 318 |
+
return 0
|
| 319 |
+
from xvideo.models.dit.fp8_linear import Fp8Linear
|
| 320 |
+
|
| 321 |
+
embedder = transformer.condition_embedder
|
| 322 |
+
targets = (
|
| 323 |
+
(transformer, "proj_out"),
|
| 324 |
+
(embedder, "time_proj"),
|
| 325 |
+
(embedder.time_embedder, "linear_1"),
|
| 326 |
+
(embedder.time_embedder, "linear_2"),
|
| 327 |
+
(embedder.text_embedder, "linear_1"),
|
| 328 |
+
(embedder.text_embedder, "linear_2"),
|
| 329 |
+
)
|
| 330 |
+
moved = 0
|
| 331 |
+
for module, name in targets:
|
| 332 |
+
linear = getattr(module, name, None)
|
| 333 |
+
if not isinstance(linear, nn.Linear):
|
| 334 |
+
continue
|
| 335 |
+
moved += sum(p.numel() * p.element_size() for p in linear.parameters())
|
| 336 |
+
setattr(module, name, Fp8Linear.from_linear(linear))
|
| 337 |
+
transformer._fp8_head_installed = True
|
| 338 |
+
return moved
|
| 339 |
+
|
| 340 |
+
|
| 341 |
_KV_DTYPE_ENV = "JOYOMNI_KV_DTYPE"
|
| 342 |
_KV_FP8_ENV = "JOYOMNI_KV_FP8"
|
| 343 |
_KV_FP8_MAX = 448.0
|
|
|
|
| 742 |
timestep = timestep.flatten()
|
| 743 |
timestep = self.timesteps_proj(timestep)
|
| 744 |
|
| 745 |
+
# FP8 Linears keep their weights in buffers, so `parameters()` can be
|
| 746 |
+
# empty and a float8 dtype is not a valid timestep dtype.
|
| 747 |
+
_time_embedder_dtype = next(iter(self.time_embedder.parameters()), None)
|
| 748 |
+
time_embedder_dtype = (
|
| 749 |
+
_time_embedder_dtype.dtype if _time_embedder_dtype is not None else torch.bfloat16
|
| 750 |
+
)
|
| 751 |
+
if time_embedder_dtype not in (torch.float32, torch.float16, torch.bfloat16):
|
| 752 |
+
time_embedder_dtype = torch.bfloat16
|
| 753 |
if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
|
| 754 |
timestep = timestep.to(time_embedder_dtype)
|
| 755 |
temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
|
deploy/xvideo/models/models.py
CHANGED
|
@@ -239,6 +239,13 @@ def load_dit(cfg, device: torch.device) -> torch.nn.Module:
|
|
| 239 |
if low_vram:
|
| 240 |
model = _move_dit_to_device_lowvram(model, device_obj)
|
| 241 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
return model.eval()
|
| 243 |
|
| 244 |
|
|
|
|
| 239 |
if low_vram:
|
| 240 |
model = _move_dit_to_device_lowvram(model, device_obj)
|
| 241 |
|
| 242 |
+
from xvideo.models.dit.dit import install_fp8_head
|
| 243 |
+
head_bytes = install_fp8_head(model)
|
| 244 |
+
if head_bytes:
|
| 245 |
+
logger.info(
|
| 246 |
+
f"FP8 head: {head_bytes / 2**20:.0f} MiB of head/embedding weights quantised"
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
return model.eval()
|
| 250 |
|
| 251 |
|
deploy/xvideo/serving/joyomni_streaming.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
| 3 |
import os
|
| 4 |
import queue
|
| 5 |
import threading
|
|
@@ -209,6 +210,11 @@ class JoyOmniRuntime:
|
|
| 209 |
self.pseudo_encode_vae = pseudo_encode_vae or self.decode_vae
|
| 210 |
self.postprocess_device = postprocess_device or _module_device(self.pseudo_encode_vae)
|
| 211 |
self.dit_lock = threading.Lock()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
self.output_quality = 60
|
| 213 |
self.lossless_output = False
|
| 214 |
self.graph_runners: dict[tuple, StreamingGraphRunner] = {}
|
|
@@ -684,13 +690,7 @@ class JoyOmniV2VStreamingSession:
|
|
| 684 |
self._clear_vae_feature_caches()
|
| 685 |
self.pipeline.transformer.reset_inference_kv_cache()
|
| 686 |
if self.ref_image_latent is not None:
|
| 687 |
-
self.
|
| 688 |
-
self.pipeline.transformer,
|
| 689 |
-
prompt_embeds=self.streaming_cond_embeds,
|
| 690 |
-
reference_image_latents=self.ref_image_latent,
|
| 691 |
-
transformer_dtype=self.target_dtype,
|
| 692 |
-
)
|
| 693 |
-
self.ref_image_kv_prefilled = True
|
| 694 |
|
| 695 |
if text_kv_env_enabled():
|
| 696 |
self._text_kv_by_step = self._capture_text_kv_by_step()
|
|
@@ -701,6 +701,66 @@ class JoyOmniV2VStreamingSession:
|
|
| 701 |
|
| 702 |
self.initialized = True
|
| 703 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 704 |
@torch.no_grad()
|
| 705 |
def _capture_text_kv_by_step(self) -> list[dict[int, tuple[torch.Tensor, torch.Tensor]]]:
|
| 706 |
"""Prefill the text stream once per denoise step.
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
import hashlib
|
| 4 |
import os
|
| 5 |
import queue
|
| 6 |
import threading
|
|
|
|
| 210 |
self.pseudo_encode_vae = pseudo_encode_vae or self.decode_vae
|
| 211 |
self.postprocess_device = postprocess_device or _module_device(self.pseudo_encode_vae)
|
| 212 |
self.dit_lock = threading.Lock()
|
| 213 |
+
# Host-side reference-image K/V cache: one entry per distinct reference,
|
| 214 |
+
# so a session that reuses the same reference skips the 40-block prefill.
|
| 215 |
+
self.ref_kv_cache: dict[str, dict] = {}
|
| 216 |
+
self.ref_kv_order: list[str] = []
|
| 217 |
+
self.ref_kv_cache_max = 2
|
| 218 |
self.output_quality = 60
|
| 219 |
self.lossless_output = False
|
| 220 |
self.graph_runners: dict[tuple, StreamingGraphRunner] = {}
|
|
|
|
| 690 |
self._clear_vae_feature_caches()
|
| 691 |
self.pipeline.transformer.reset_inference_kv_cache()
|
| 692 |
if self.ref_image_latent is not None:
|
| 693 |
+
self._prefill_or_reuse_reference_kv()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 694 |
|
| 695 |
if text_kv_env_enabled():
|
| 696 |
self._text_kv_by_step = self._capture_text_kv_by_step()
|
|
|
|
| 701 |
|
| 702 |
self.initialized = True
|
| 703 |
|
| 704 |
+
def _reference_kv_key(self) -> str:
|
| 705 |
+
latent = self.ref_image_latent.detach().to("cpu", torch.float32).contiguous()
|
| 706 |
+
return hashlib.sha1(latent.numpy().tobytes()).hexdigest()[:16]
|
| 707 |
+
|
| 708 |
+
@staticmethod
|
| 709 |
+
def _kv_entry_to(entry: dict, device) -> dict:
|
| 710 |
+
out = {"pre_rope": bool(entry.get("pre_rope", False))}
|
| 711 |
+
for name, tensor in entry.items():
|
| 712 |
+
if isinstance(tensor, torch.Tensor):
|
| 713 |
+
out[name] = tensor.to(device=device)
|
| 714 |
+
elif name != "pre_rope":
|
| 715 |
+
out[name] = tensor
|
| 716 |
+
return out
|
| 717 |
+
|
| 718 |
+
def _prefill_or_reuse_reference_kv(self) -> None:
|
| 719 |
+
"""Prefill the reference-image K/V once per reference image.
|
| 720 |
+
|
| 721 |
+
The prefill runs with `skip_text_stream=True`, so its K/V depends only on
|
| 722 |
+
the reference latent; a host-side copy can be installed on a later
|
| 723 |
+
session with the same reference image.
|
| 724 |
+
"""
|
| 725 |
+
key = self._reference_kv_key()
|
| 726 |
+
tf = self.pipeline.transformer
|
| 727 |
+
ref_id = self.pipeline._kv_cache_memory_id("ref_image")
|
| 728 |
+
cached = self.runtime.ref_kv_cache.get(key)
|
| 729 |
+
if cached is not None:
|
| 730 |
+
scope_store = tf._inference_kv_cache.setdefault("cond", {})
|
| 731 |
+
scope_store[ref_id] = {
|
| 732 |
+
layer_idx: self._kv_entry_to(entry, self.device)
|
| 733 |
+
for layer_idx, entry in cached.items()
|
| 734 |
+
}
|
| 735 |
+
tf._kv_cache_generation += 1
|
| 736 |
+
self.ref_image_kv_prefilled = True
|
| 737 |
+
print(f"#####[REF-KV] reused reference K/V from host cache ({key})", flush=True)
|
| 738 |
+
return
|
| 739 |
+
|
| 740 |
+
self.pipeline._prefill_static_reference_kv_cache(
|
| 741 |
+
self.pipeline.transformer,
|
| 742 |
+
prompt_embeds=self.streaming_cond_embeds,
|
| 743 |
+
reference_image_latents=self.ref_image_latent,
|
| 744 |
+
transformer_dtype=self.target_dtype,
|
| 745 |
+
)
|
| 746 |
+
self.ref_image_kv_prefilled = True
|
| 747 |
+
|
| 748 |
+
scope_store = tf._inference_kv_cache.get("cond", {})
|
| 749 |
+
store = scope_store.get(ref_id)
|
| 750 |
+
if store:
|
| 751 |
+
self.runtime.ref_kv_cache[key] = {
|
| 752 |
+
layer_idx: self._kv_entry_to(entry, "cpu")
|
| 753 |
+
for layer_idx, entry in store.items()
|
| 754 |
+
}
|
| 755 |
+
self.runtime.ref_kv_order.append(key)
|
| 756 |
+
while len(self.runtime.ref_kv_order) > self.runtime.ref_kv_cache_max:
|
| 757 |
+
self.runtime.ref_kv_cache.pop(self.runtime.ref_kv_order.pop(0), None)
|
| 758 |
+
print(
|
| 759 |
+
f"#####[REF-KV] cached reference K/V on host ({key}, "
|
| 760 |
+
f"{len(self.runtime.ref_kv_order)} reference(s))",
|
| 761 |
+
flush=True,
|
| 762 |
+
)
|
| 763 |
+
|
| 764 |
@torch.no_grad()
|
| 765 |
def _capture_text_kv_by_step(self) -> list[dict[int, tuple[torch.Tensor, torch.Tensor]]]:
|
| 766 |
"""Prefill the text stream once per denoise step.
|