Diffusers documentation
Kandinsky S2V 1.0
Kandinsky S2V 1.0
Kandinsky S2V 1.0 генерирует видео аватара на основе опорного кадра и аудиодорожки с речью. Персонаж на кадре анимируется в соответствии с речью — анимируется всё тело, а не только голова. Речь выступает в роли условия, а не результата: модель не генерирует звук, а звуковым сопровождением итогового видео является переданная вами дорожка.
Обе ветви проходят через Qwen2.5-Omni-7B: его скрытые состояния кодируют промпт, а аудиобашня кодирует речь, которая поступает в трансформер через адаптеры кросс-внимания, выровненные по кадрам, так что каждый латентный кадр обращается только к той речи, которую он покрывает. Клип генерируется кусками по 5 с (125 кадров при 25 fps), каждый из которых несёт память FramePack от предыдущих, благодаря чему длинные дорожки остаются согласованными на границах кусков.
Kandinsky S2V 1.0 интегрирован только как модульный конвейер; стандартный класс DiffusionPipeline для него отсутствует.
Чекпоинты
| Чекпоинт | Transformer | Блоки | Планировщик | Шаги | Руководство |
|---|---|---|---|---|---|
| Lite | 2B | KandinskyS2VAutoBlocks | FlowMatchEulerDiscreteScheduler | 50 | 3.0 |
| Pro | 21B | KandinskyS2VAutoBlocks | FlowMatchEulerDiscreteScheduler | 50 | 3.0 |
| Лёгкая дистилляция | 2B | KandinskyS2VDistilledAutoBlocks | PiflowScheduler | 16 | off |
| Pro distilled | 21B | KandinskyS2VDistilledAutoBlocks | PiflowScheduler | 16 | off |
Дистиллированные контрольные точки настраивают PiflowScheduler с параметрами shift=10.0 и n_grid=5, а не с их значениями по умолчанию.
ModularPipeline.from_pretrained выбирает блоки из контрольной точки. Шаги по умолчанию принимают значения, указанные выше. Classifier-free guidance — это компонент guider, а не аргумент вызова: базовые контрольные точки поставляются с его значением 3.0. Дистиллированные контрольные точки не содержат ни guider, ни negative_prompt, поскольку guidance уже является частью student.
Использование
import librosa
import torch
from diffusers import ModularPipeline
from diffusers.utils import encode_video, load_image
pipe = ModularPipeline.from_pretrained("kandinskylab/Kandinsky-S2V-1.0-Lite-distill-Diffusers")
pipe.load_components(dtype=torch.bfloat16)
pipe.to("cuda")
image = load_image("reference.png")
audio, _ = librosa.load("speech.wav", sr=16000) # a mono waveform at 16 kHz, for the model
speech, sample_rate = librosa.load("speech.wav", sr=None) # the original track, added to the output video
video = pipe(image=image, audio=audio, output="videos")[0]
encode_video(
video,
fps=25,
output_path="avatar.mp4",
audio=torch.from_numpy(speech)[None],
audio_sample_rate=sample_rate,
)Чекпоинты Pro не помещаются на GPU с 80 ГБ памяти вместе с аудио- и текстовым энкодером 7B, если все компоненты находятся на устройстве. Используйте оффлоад через ComponentsManager:
import librosa
import torch
from diffusers import ComponentsManager, ModularPipeline
from diffusers.utils import encode_video, load_image
manager = ComponentsManager()
pipe = ModularPipeline.from_pretrained("kandinskylab/Kandinsky-S2V-1.0-Pro-Diffusers", components_manager=manager)
pipe.load_components(dtype=torch.bfloat16)
manager.enable_auto_cpu_offload(device="cuda", memory_reserve_margin="40GiB")
image = load_image("reference.png")
audio, _ = librosa.load("speech.wav", sr=16000)
speech, sample_rate = librosa.load("speech.wav", sr=None)
video = pipe(image=image, audio=audio, output="videos")[0]
encode_video(
video,
fps=25,
output_path="avatar.mp4",
audio=torch.from_numpy(speech)[None],
audio_sample_rate=sample_rate,
)Margin — это объём памяти, который остаётся свободным сверх весов при перемещении модели на GPU.
Он должен вмещать VAE-декодирование фрагмента, что составляет около 33 ГиБ при разрешении 512x768: при значении по умолчанию 3 ГБ
трансформер остаётся на GPU во время декодирования, после чего память исчерпывается. При
40 ГиБ пиковое потребление составляет около 50 ГиБ на GPU объёмом 80 ГБ. Включите offload после load_components,
чтобы он применялся ко всем компонентам.
Примечания
image— это изображение в формате PIL, аaudio— монофоническая волновая форма с плавающей точкой в диапазоне [-1, 1] при частоте дискретизации 16 кГц, представленная в виде тензора или массива с формой(samples,); конвейер не читает файлы.- Верхнеуровневые блоки (
text_encoder,vae_encoder,denoise,decode) также могут выполняться независимо; при их отдельном запуске передавайте каждому одни и те же значенияnum_latent_framesиfps. - Количество фрагментов определяется длиной аудиодорожки, если не передан параметр
num_chunks. В любом случае видео обрезается по длине дорожки, поэтому фрагменты, выходящие за её пределы, вычисляются и отбрасываются с выводом предупреждения. - При использовании guidance безусловный проход подставляет негативный промпт и заглушает речь, поэтому guidance является совместным для текста и речи.
KandinskyS2VModularPipeline
класс diffusers.KandinskyS2VModularPipeline
< source >( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )
Модульный ModularPipeline для генерации видео из речи в Kandinsky S2V 1.0.
KandinskyS2VAutoBlocks
Модульный конвейер для генерации видео из речи с использованием Kandinsky S2V 1.0: видео аватара из опорного кадра и аудиодорожки, генерируемое по частям.
Компоненты:
text_encoder (Qwen2_5OmniThinkerForConditionalGeneration) tokenizer (Qwen2_5OmniProcessor) text_encoder_2
(CLIPTextModel) tokenizer_2 (CLIPTokenizer) vae (AutoencoderKLHunyuanVideo) video_processor
(VideoProcessor) transformer (KandinskyS2VTransformer3DModel) scheduler
(FlowMatchEulerDiscreteScheduler) guider (ClassifierFreeGuidance)
Inputs:
prompt (str, optional, defaults to The video presents a stable medium close-up of a subject facing the
camera directly. The subject exhibits natural, lifelike body dynamics: the head and shoulders move fluidly
with the rhythm of speech. The lighting is even, maintaining a balanced natural exposure to clearly define
facial features without washout. Throughout the sequence, the subject engages in continuous speech marked by
precise, high-fidelity articulation. The lips move in a rhythmic, natural pattern: alternating between brief
firm closures and relaxed openings. During these openings, the tips of the upper teeth are momentarily and
realistically visible, exhibiting natural enamel texture. The upper lip lifts subtly over the teeth during
enunciation, while the jaw performs minimal vertical oscillations synchronized with the speech cadence.
Facial micro-expressions are active yet restrained; eyebrows rise and lower slightly with minute asymmetry.
The eyes maintain a steady, engaged gaze forward, punctuated by smooth, deliberate blinks. ):
The prompt to guide the generation.
negative_prompt (str, optional):
The prompt for the unconditional pass of the guidance. Defaults to DEFAULT_NEGATIVE_PROMPT when the
guidance needs one.
audio (Tensor | ndarray):
The speech track that drives the generation: a mono float waveform in [-1, 1] at 16000 Hz, shaped
(samples,).
num_latent_frames (int, optional, defaults to 32):
Latent frames per chunk; 32 gives 125 frames (5 s at 25 fps).
fps (int, optional, defaults to 25):
Frame rate the chunk length is computed at.
num_chunks (int, optional):
Number of chunks to generate. Defaults to however many cover the speech track; the video is trimmed to
the track either way.
image (Image):
The reference frame to animate.
height (int, optional):
The height in pixels of the generated video. Defaults to the 512 bucket closest to the reference frame.
width (int, optional):
The width in pixels of the generated video, chosen together with height.
generator (Generator, optional):
Torch generator for deterministic generation.
num_inference_steps (int, optional, defaults to 50):
The number of denoising steps.
scale_factor (tuple, optional, defaults to (1.0, 2.0, 2.0)):
Per-axis RoPE scale for the resolution bucket.
output_type (str, optional, defaults to pil):
Output format: ‘pil’, ‘np’, ‘pt’.
Вывод:
видео (list):
Сгенерированные видео.
KandinskyS2VDistilledModularPipeline
класс diffusers.KandinskyS2VDistilledModularPipeline
< source >( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )
ModularPipeline для дистиллированных контрольных точек Kandinsky S2V 1.0 от pi-Flow.
Guidance дистиллируется в ученическую модель, поэтому её блоки не содержат guider и не используют отрицательный промпт, а на каждый сегмент выполняется один прямой проход.
KandinskyS2VDistilledAutoBlocks
Модульный конвейер для генерации видео из речи с использованием дистиллированных чекпоинтов pi-Flow Kandinsky S2V 1.0: 16 сегментов на чанк и без гайдинга, что дистиллируется в ученическую модель.
Компоненты:
text_encoder (Qwen2_5OmniThinkerForConditionalGeneration) tokenizer (Qwen2_5OmniProcessor) text_encoder_2
(CLIPTextModel) tokenizer_2 (CLIPTokenizer) vae (AutoencoderKLHunyuanVideo) video_processor
(VideoProcessor) transformer (KandinskyS2VTransformer3DModel) scheduler (PiflowScheduler)
Inputs:
prompt (str, optional, defaults to The video presents a stable medium close-up of a subject facing the
camera directly. The subject exhibits natural, lifelike body dynamics: the head and shoulders move fluidly
with the rhythm of speech. The lighting is even, maintaining a balanced natural exposure to clearly define
facial features without washout. Throughout the sequence, the subject engages in continuous speech marked by
precise, high-fidelity articulation. The lips move in a rhythmic, natural pattern: alternating between brief
firm closures and relaxed openings. During these openings, the tips of the upper teeth are momentarily and
realistically visible, exhibiting natural enamel texture. The upper lip lifts subtly over the teeth during
enunciation, while the jaw performs minimal vertical oscillations synchronized with the speech cadence.
Facial micro-expressions are active yet restrained; eyebrows rise and lower slightly with minute asymmetry.
The eyes maintain a steady, engaged gaze forward, punctuated by smooth, deliberate blinks. ):
The prompt to guide the generation.
audio (Tensor | ndarray):
The speech track that drives the generation: a mono float waveform in [-1, 1] at 16000 Hz, shaped
(samples,).
num_latent_frames (int, optional, defaults to 32):
Latent frames per chunk; 32 gives 125 frames (5 s at 25 fps).
fps (int, optional, defaults to 25):
Frame rate the chunk length is computed at.
num_chunks (int, optional):
Number of chunks to generate. Defaults to however many cover the speech track; the video is trimmed to
the track either way.
image (Image):
The reference frame to animate.
height (int, optional):
The height in pixels of the generated video. Defaults to the 512 bucket closest to the reference frame.
width (int, optional):
The width in pixels of the generated video, chosen together with height.
generator (Generator, optional):
Torch generator for deterministic generation.
num_inference_steps (int, optional, defaults to 16):
The number of denoising steps.
scale_factor (tuple, optional, defaults to (1.0, 2.0, 2.0)):
Per-axis RoPE scale for the resolution bucket.
output_type (str, optional, defaults to pil):
Output format: ‘pil’, ‘np’, ‘pt’.
Вывод:
видео (list):
Сгенерированные видео.