#
# Лицензия Apache License, Version 2.0 («Лицензия»);
# вы можете использовать этот файл только в соответствии с Лицензией.
# Вы можете получить копию Лицензии по адресу
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Если это не требуется применимым законодательством или не оговорено письменно, программное
# распространяется по Лицензии на условиях «КАК ЕСТЬ»,
# БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ ИЛИ УСЛОВИЙ, прямо указанных или подразумеваемых.
# См. Лицензию для получения конкретных условий, регулирующих разрешения и
# ограничениями Лицензии. -->

  
    
      
    
  

# Helios

[Helios: Real Real-Time Long Video Generation Model](https://huggingface.co/papers/2603.04379) от Peking University & ByteDance & и др., авторы Shenghai Yuan, Yuanyang Yin, Zongjian Li, Xinwei Huang, Xiao Yang, Li Yuan.

*  Мы представляем Helios — первую модель генерации видео с 14 млрд параметров, работающую со скоростью 17 кадров в секунду на одном GPU NVIDIA H100 и поддерживающую генерацию видео длительностью в минуты при качестве, сопоставимом с сильным базовым уровнем. Мы добились прорыва по трем ключевым направлениям: (1) устойчивость к дрейфу в длинных видео без использования общепринятых эвристик против дрейфа, таких как self-forcing, error banks или выборка ключевых кадров; (2) генерация в реальном времени без стандартных методов ускорения, таких как KV-cache, каузальное маскирование или разреженное внимание; и (3) обучение без фреймворков параллелизма или шардирования, что позволяет использовать размеры батчей, сопоставимые с диффузионными моделями изображений, при размещении до четырех моделей на 14 млрд параметров в 80 ГБ памяти GPU. Конкретно, Helios — это авто-регрессивная диффузионная модель на 14 млрд параметров с унифицированным представлением входных данных, нативно поддерживающая задачи T2V, I2V и V2V. Для смягчения дрейфа при генерации длинных видео мы описываем его типичные режимы отказа и предлагаем простые, но эффективные стратегии обучения, которые явно имитируют дрейф в процессе обучения, одновременно устраняя повторяющееся движение на корню. Для повышения эффективности мы сильно сжимаем исторический и зашумленный контекст и сокращаем количество шагов выборки, что приводит к вычислительным затратам, сопоставимым с затратами моделей генерации видео на 1,3 млрд параметров или даже меньшим. Кроме того, мы вводим оптимизации на уровне инфраструктуры, ускоряющие как инференс, так и обучение, одновременно снижая потребление памяти. Обширные эксперименты показывают, что Helios стабильно превосходит предыдущие методы как в генерации коротких, так и длинных видео. Весь код и модели доступны по адресу [этот URL](https://pku-yuangroup.github.io/Helios-Page).

В Diffusers поддерживаются следующие модели Helios:

- [Helios-Base](https://huggingface.co/BestWishYsh/Helios-Base): лучшее качество, с v-prediction, стандартным CFG и собственным HeliosScheduler.
- [Helios-Mid](https://huggingface.co/BestWishYsh/Helios-Mid): промежуточный вес, с v-prediction, CFG-Zero* и собственным HeliosScheduler.
- [Helios-Distilled](https://huggingface.co/BestWishYsh/Helios-Distilled): лучшая эффективность, с x0-prediction и собственным HeliosDMDScheduler.

> [!TIP]
> Нажмите на модели Helios в правой боковой панели, чтобы увидеть больше примеров генерации видео.

### Оптимизация памяти и скорости вывода

Пример ниже демонстрирует, как сгенерировать видео из текста с оптимизацией под память или скорость инференса.

См. руководство [Сокращение использования памяти](../../optimization/memory) для получения подробной информации о различных техниках экономии памяти.

Модель Helios, приведённая ниже, требует ~6 ГБ видеопамяти.

```py
import torch
from diffusers import AutoModel, HeliosPipeline
from diffusers.hooks.group_offloading import apply_group_offloading
from diffusers.utils import export_to_video

vae = AutoModel.from_pretrained("BestWishYsh/Helios-Base", subfolder="vae", dtype=torch.float32)

# group-offloading
pipeline = HeliosPipeline.from_pretrained(
    "BestWishYsh/Helios-Base",
    vae=vae,
    dtype=torch.bfloat16
)
pipeline.enable_group_offload(
    onload_device=torch.device("cuda"),
    offload_device=torch.device("cpu"),
    offload_type="leaf_level",
    use_stream=True,
    record_stream=True,
)

prompt = """
A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue 
and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with 
a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, 
allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades 
of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and 
the vivid colors of its surroundings. A close-up shot with dynamic movement.
"""
negative_prompt = """
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
"""

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_frames=99,
    num_inference_steps=50,
    guidance_scale=5.0,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]
export_to_video(output, "helios_base_t2v_output.mp4", fps=24)
```

[Компиляция](../../optimization/fp16#torchcompile) выполняется медленно при первом запуске, но последующие вызовы пайплайна становятся быстрее. [Attention Backends](../../optimization/attention_backends), такие как FlashAttention и SageAttention, могут значительно повысить скорость за счёт оптимизации вычислений механизма внимания. [Context Parallelism](../../training/distributed_inference#context-parallelism) распределяет входную последовательность по нескольким устройствам, что позволяет обрабатывать длинные контексты параллельно, снижая нагрузку на память и задержки. [Caching](../../optimization/cache) также может ускорить инференс за счёт сохранения и повторного использования промежуточных результатов.

```py
import torch
from diffusers import AutoModel, HeliosPipeline
from diffusers.utils import export_to_video

vae = AutoModel.from_pretrained("BestWishYsh/Helios-Base", subfolder="vae", dtype=torch.float32)

pipeline = HeliosPipeline.from_pretrained(
    "BestWishYsh/Helios-Base",
    vae=vae,
    dtype=torch.bfloat16
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"

# attention backend
# pipeline.transformer.set_attention_backend("flash")
pipeline.transformer.set_attention_backend("_flash_3_hub") # For Hopper GPUs

# torch.compile
torch.backends.cudnn.benchmark = True
pipeline.text_encoder.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
pipeline.vae.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
pipeline.transformer.compile(mode="max-autotune-no-cudagraphs", dynamic=False)

prompt = """
A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue 
and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with 
a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, 
allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades 
of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and 
the vivid colors of its surroundings. A close-up shot with dynamic movement.
"""
negative_prompt = """
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
"""

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_frames=99,
    num_inference_steps=50,
    guidance_scale=5.0,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]
export_to_video(output, "helios_base_t2v_output.mp4", fps=24)
```

### Генерация с Helios-Base

Пример ниже демонстрирует, как использовать Helios-Base для генерации видео на основе текста, изображения или видео.

```python
import torch
from diffusers import AutoModel, HeliosPipeline
from diffusers.utils import export_to_video, load_video, load_image

vae = AutoModel.from_pretrained("BestWishYsh/Helios-Base", subfolder="vae", dtype=torch.float32)

pipeline = HeliosPipeline.from_pretrained(
    "BestWishYsh/Helios-Base",
    vae=vae,
    dtype=torch.bfloat16
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"

negative_prompt = """
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
"""

# For Text-to-Video
prompt = """
A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue 
and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with 
a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, 
allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades 
of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and 
the vivid colors of its surroundings. A close-up shot with dynamic movement.
"""

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_frames=99,
    num_inference_steps=50,
    guidance_scale=5.0,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]
export_to_video(output, "helios_base_t2v_output.mp4", fps=24)

# For Image-to-Video
prompt = """
A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, 
illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, 
casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes 
apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and 
relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and 
respect for nature’s might.
"""
image_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg"

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    image=load_image(image_path).resize((640, 384)),
    num_frames=99,
    num_inference_steps=50,
    guidance_scale=5.0,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]
export_to_video(output, "helios_base_i2v_output.mp4", fps=24)

# For Video-to-Video
prompt = """
A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees 
under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, 
emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to 
the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. 
A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery.
"""
video_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4"

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    video=load_video(video_path),
    num_frames=99,
    num_inference_steps=50,
    guidance_scale=5.0,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]
export_to_video(output, "helios_base_v2v_output.mp4", fps=24)
```

### Генерация с Helios-Mid

Пример ниже демонстрирует, как использовать Helios-Mid для генерации видео на основе текста, изображения или видео.

```python
import torch
from diffusers import AutoModel, HeliosPyramidPipeline
from diffusers.utils import export_to_video, load_video, load_image

vae = AutoModel.from_pretrained("BestWishYsh/Helios-Mid", subfolder="vae", dtype=torch.float32)

pipeline = HeliosPyramidPipeline.from_pretrained(
    "BestWishYsh/Helios-Mid",
    vae=vae,
    dtype=torch.bfloat16
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"

negative_prompt = """
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
"""

# For Text-to-Video
prompt = """
A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue 
and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with 
a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, 
allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades 
of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and 
the vivid colors of its surroundings. A close-up shot with dynamic movement.
"""

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_frames=99,
    pyramid_num_inference_steps_list=[20, 20, 20],
    guidance_scale=5.0,
    use_zero_init=True,
    zero_steps=1,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]
export_to_video(output, "helios_pyramid_t2v_output.mp4", fps=24)

# For Image-to-Video
prompt = """
A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, 
illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, 
casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes 
apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and 
relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and 
respect for nature’s might.
"""
image_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg"

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    image=load_image(image_path).resize((640, 384)),
    num_frames=99,
    pyramid_num_inference_steps_list=[20, 20, 20],
    guidance_scale=5.0,
    use_zero_init=True,
    zero_steps=1,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]
export_to_video(output, "helios_pyramid_i2v_output.mp4", fps=24)

# For Video-to-Video
prompt = """
A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees 
under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, 
emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to 
the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. 
A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery.
"""
video_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4"

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    video=load_video(video_path),
    num_frames=99,
    pyramid_num_inference_steps_list=[20, 20, 20],
    guidance_scale=5.0,
    use_zero_init=True,
    zero_steps=1,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]
export_to_video(output, "helios_pyramid_v2v_output.mp4", fps=24)
```

### Генерация с Helios-Distilled

Пример ниже демонстрирует, как использовать Helios-Distilled для генерации видео на основе текста, изображения или видео.

```python
import torch
from diffusers import AutoModel, HeliosPyramidPipeline
from diffusers.utils import export_to_video, load_video, load_image

vae = AutoModel.from_pretrained("BestWishYsh/Helios-Distilled", subfolder="vae", dtype=torch.float32)

pipeline = HeliosPyramidPipeline.from_pretrained(
    "BestWishYsh/Helios-Distilled",
    vae=vae,
    dtype=torch.bfloat16
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"

negative_prompt = """
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
"""

# For Text-to-Video
prompt = """
A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue 
and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with 
a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, 
allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades 
of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and 
the vivid colors of its surroundings. A close-up shot with dynamic movement.
"""

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_frames=240,
    pyramid_num_inference_steps_list=[2, 2, 2],
    guidance_scale=1.0,
    is_amplify_first_chunk=True,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]
export_to_video(output, "helios_distilled_t2v_output.mp4", fps=24)

# For Image-to-Video
prompt = """
A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, 
illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, 
casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes 
apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and 
relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and 
respect for nature’s might.
"""
image_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg"

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    image=load_image(image_path).resize((640, 384)),
    num_frames=240,
    pyramid_num_inference_steps_list=[2, 2, 2],
    guidance_scale=1.0,
    is_amplify_first_chunk=True,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]
export_to_video(output, "helios_distilled_i2v_output.mp4", fps=24)

# For Video-to-Video
prompt = """
A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees 
under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, 
emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to 
the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. 
A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery.
"""
video_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4"

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    video=load_video(video_path),
    num_frames=240,
    pyramid_num_inference_steps_list=[2, 2, 2],
    guidance_scale=1.0,
    is_amplify_first_chunk=True,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]
export_to_video(output, "helios_distilled_v2v_output.mp4", fps=24)
```

## Демонстрации генерации видео по тексту

  
    Видео, сгенерированное по промпту
  
  
    Викинг-воин, управляющий современным городским автобусом, полным пассажиров. У викинга длинные светлые волосы, собранные назад, борода, он одет в шлем с меховой отделкой и доспехи. На нём традиционная туника и штаны, но также пристёгнут ремень безопасности, пока он сосредоточенно маневрирует по оживлённым улицам. Интерьер автобуса типичный: ряды сидений заняты разнообразными пассажирами, ведущими свой обычный распорядок дня. Снимки снаружи показывают оживлённую городскую среду, включая высокие здания и транспортный поток. Средний план, сфокусированный на викинге за рулём, с периодическими крупными планами его решительного выражения лица.
    
    
      
        
      
    
  
  
    Снимок в документальном стиле, сделанный с движущейся влево машины-камеры, запечатлевший краба, быстро убегающего в свою норку. У краба твердая зеленовато-коричневая панцирь и длинные клешни; он движется по песчаной поверхности с решительной скоростью. Его тело слегка выгнуто, пока он зарывается в песок, оставляя за собой небольшой след. На заднем плане виден мелководный пляж с разбросанными камнями и ракушками, а на горизонте просматривается плавная изгиб береговой линии. Фотография обладает естественной и реалистичной текстурой, подчеркивающей естественное движение краба и фактуру песка. Крупный план, снятый с немного возвышенного ракурса.
    
    
      
        
      
    
  

## Демонстрации: изображение в видео

  
    Изображение Запрос Сгенерированное видео
  
  
    
    Стильный красный автомобиль Kia мчится по сельской дороге под облачным небом; его современный дизайн и динамичное движение подчёркиваются размытым фоном полей и деревьев, уходящих вдаль. Глянцевый кузов отражает пасмурное небо, выделяя аэродинамичную форму и спортивную посадку. На номерном знаке написано "KIA 626", а фары автомобиля включены, что усиливает ощущение движения и энергии. Дорога плавно изгибается, а автомобиль расположен немного не по центру, создавая ощущение стремительного движения вперёд. Динамичный вид спереди под углом в три четверти подчёркивает мощное присутствие автомобиля на фоне спокойного пейзажа с пологими холмами и разбросанными деревьями.
    
    
      
        
      
    
  
  
    
    Крупный план пушистого рыжего кота с выразительными зелёными глазами и белыми усами, пристально смотрящего в камеру. Шерсть кота мягкая и ухоженная, с сочетанием тёплых оранжевых и кремовых оттенков. Его большие выразительные глаза ярко-зелёные, отражающие любопытство и бдительность. Нос у кота маленький и розовый, рот слегка приоткрыт, и виден кончик розового языка. Фон мягко размыт, что создаёт ощущение уютного интерьера в нейтральных тонах. На снимке малая глубина резкости: лицо кота сфокусировано чётко, тогда как фон остаётся размытым. Крупный план, снятый с немного возвышенной точки.
    
    
      
        
      
    
  

## Демонстрации интерактивных видео

  
    Видео, сгенерированное по промпту
  
  
    Промпт можно найти здесь
    
      
        
      
    
  
  
    Промпт можно найти здесь
    
      
        
      
    
  

## Ресурсы

Узнайте больше о Helios с помощью следующих ресурсов.
- Посмотрите [video1](https://www.youtube.com/watch?v=vd_AgHtOUFQ) и [video2](https://www.youtube.com/watch?v=1GeIU2Dn7UY), чтобы увидеть демонстрацию ключевых возможностей Helios.
- Подробнее в научной статье [Helios: Real Real-Time Long Video Generation Model](https://huggingface.co/papers/2603.04379).

## HeliosPipeline[[diffusers.HeliosPipeline]]

#### diffusers.HeliosPipeline[[diffusers.HeliosPipeline]]

```python
diffusers.HeliosPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, vae: AutoencoderKLWan, scheduler: HeliosScheduler, transformer: HeliosTransformer3DModel)
```

[Источник](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/helios/pipeline_helios.py#L108)

**Параметры:**

tokenizer (`T5Tokenizer`) : Токенизатор из [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer), а именно вариант [google/umt5-xxl](https://huggingface.co/google/umt5-xxl).

text_encoder (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), а именно вариант [google/umt5-xxl](https://huggingface.co/google/umt5-xxl).

transformer ([HeliosTransformer3DModel](/docs/diffusers/main/ru/api/models/helios_transformer3d#diffusers.HeliosTransformer3DModel)) : Условный Transformer для удаления шума из входных латентов.

scheduler ([HeliosScheduler](/docs/diffusers/main/ru/api/schedulers/helios#diffusers.HeliosScheduler)) : планировщик, используемый в сочетании с `transformer` для удаления шума из закодированных латентов изображения.

vae ([AutoencoderKLWan](/docs/diffusers/main/ru/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan)) : Модель вариационного автоэнкодера (VAE) для кодирования и декодирования видео в латентные представления и обратно.

Pipeline для генерации видео из текста / из изображения / из видео с использованием Helios.

Эта модель наследуется от [DiffusionPipeline](/docs/diffusers/main/ru/api/pipelines/overview#diffusers.DiffusionPipeline). Общую документацию по методам, реализованным для всех пайплайнов (загрузка, сохранение, запуск на конкретном устройстве и т. д.), см. в документации родительского класса.

#### __call__[[diffusers.HeliosPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, negative_prompt: str | list[str] = None, height: int = 384, width: int = 640, num_frames: int = 132, num_inference_steps: int = 50, sigmas: list = None, guidance_scale: float = 5.0, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 512, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, image_latents: typing.Optional[torch.Tensor] = None, fake_image_latents: typing.Optional[torch.Tensor] = None, add_noise_to_image_latents: bool = True, image_noise_sigma_min: float = 0.111, image_noise_sigma_max: float = 0.135, video: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, video_latents: typing.Optional[torch.Tensor] = None, add_noise_to_video_latents: bool = True, video_noise_sigma_min: float = 0.111, video_noise_sigma_max: float = 0.135, history_sizes: list = [16, 2, 1], num_latent_frames_per_chunk: int = 9, keep_first_frame: bool = True, is_skip_first_chunk: bool = False)
```

[Источник](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/helios/pipeline_helios.py#L445)

**Параметры:**

prompt (`str` или `list[str]`, *необязательный*) : Промпт или промпты для управления генерацией изображения. Если не задан, передайте вместо него `prompt_embeds`.

negative_prompt (`str` или `list[str]`, *необязательный*) : Промпт или промпты, которые следует избегать при генерации изображения. Если не задан, передайте вместо него `negative_prompt_embeds`. Игнорируется, если не используется направляющая (`guidance_scale` < `1`).

height (`int`, по умолчанию `384`) : Высота генерируемого изображения в пикселях.

width (`int`, по умолчанию `640`) : Ширина генерируемого изображения в пикселях.

num_frames (`int`, по умолчанию `132`) : Количество кадров в сгенерированном видео.

num_inference_steps (`int`, по умолчанию `50`) : Количество шагов денойзинга. Как правило, большее число шагов денойзинга приводит к изображению более высокого качества, но за счёт более медленного вывода.

sigmas (`list[float]`, *optional*) : Пользовательские сигмы для процесса удаления шума. Если не заданы, используется расписание по умолчанию планировщика.

guidance_scale (`float`, по умолчанию `5.0`) : Масштаб руководства, определенный в [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` определяется как `w` из уравнения 2 в [Imagen Paper](https://huggingface.co/papers/2205.11487). Масштаб руководства активируется при установке `guidance_scale > 1`. Более высокий масштаб руководства способствует генерации изображений, тесно связанных с текстовым `prompt`, обычно за счет снижения качества изображения.

num_videos_per_prompt (`int`, *необязательный*, по умолчанию 1) : Количество изображений, генерируемых на один запрос.

generator (`torch.Generator` или `list[torch.Generator]`, *необязательно*) : [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) для обеспечения детерминированности генерации.

latents (`torch.Tensor`, *необязательный*) : Предварительно сгенерированные шумовые латенты, выбранные из гауссова распределения, которые используются в качестве входных данных для генерации изображений. Позволяет корректировать одну и ту же генерацию с помощью разных промптов. Если не задано, тензор латентов генерируется путём выборки с использованием переданного случайного `generator`.

prompt_embeds (`torch.Tensor`, *необязательный*) : Предварительно сгенерированные текстовые эмбеддинги. Можно использовать для простой настройки текстовых входных данных (взвешивание промпта). Если не предоставлены, текстовые эмбеддинги генерируются из входного аргумента `prompt`.

negative_prompt_embeds (`torch.Tensor`, *необязательный*) : Предварительно сгенерированные отрицательные текстовые эмбеддинги. Если не указаны, они генерируются из `negative_prompt`.

output_type (`str`, *необязательный*, по умолчанию `"np"`) : Формат вывода сгенерированного изображения. Выберите между `PIL.Image` и `np.array`.

return_dict (`bool`, *необязательный*, по умолчанию `True`) : Возвращать ли `HeliosPipelineOutput` вместо обычного кортежа.

attention_kwargs (`dict`, *необязательный*) : Словарь kwargs, который при указании передается в `AttentionProcessor`, определенный в `self.processor` в [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : функция или подкласс `PipelineCallback` или `MultiPipelineCallbacks`, вызываемая в конце каждого шага денойзинга во время инференса со следующими аргументами: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` будет содержать список всех тензоров, как указано в `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Список тензорных входных данных для функции `callback_on_step_end`. Тензоры, указанные в списке, будут переданы в качестве аргумента `callback_kwargs`. Вы сможете включать только переменные, перечисленные в атрибуте `._callback_tensor_inputs` вашего класса pipeline.

max_sequence_length (`int`, по умолчанию `512`) : Максимальная длина последовательности для текстового энкодера. Если промпт длиннее этого значения, он будет усечён. Если промпт короче, он будет дополнен до этой длины.

image (`PipelineImageInput`, *необязательный*) : Входное изображение, используемое для условного формирования видео по изображению.

image_latents (`torch.Tensor`, *необязательный*) : Предварительно закодированные латенты изображения для использования вместо `image`.

fake_image_latents (`torch.Tensor`, *необязательный*) : Необязательные фиктивные латентные изображения, используемые при условии.

add_noise_to_image_latents (`bool`, *необязательный*, по умолчанию `True`) : Добавлять ли шум к латентам изображения перед денойзингом.

image_noise_sigma_min (`float`, *optional*, по умолчанию `0.111`) : Минимальное значение сигмы для шума, добавляемого к латентам изображения.

image_noise_sigma_max (`float`, *optional*, по умолчанию `0.135`) : Максимальное значение сигмы для шума, добавляемого к латентам изображения.

video (`PipelineImageInput`, *необязательный*) : Входящее видео, используемое для видео-в-видео обусловливания.

video_latents (`torch.Tensor`, *необязательный*) : Предварительно закодированные латенты видео для использования вместо `video`.

add_noise_to_video_latents (`bool`, *необязательный*, по умолчанию `True`) : Добавлять ли шум к латентам видео перед денойзингом.

video_noise_sigma_min (`float`, *необязательный*, по умолчанию `0.111`) : Минимальное значение сигмы для шума, добавляемого к латентам видео.

video_noise_sigma_max (`float`, *необязательный*, по умолчанию `0.135`) : Максимальное значение сигмы для шума, добавляемого к латентам видео.

history_sizes (`list`, *необязательный*, по умолчанию `[16, 2, 1]`) : Размеры окон истории, используемые для авто-регрессивной генерации по чанкам.

num_latent_frames_per_chunk (`int`, *необязательный*, по умолчанию `9`) : Количество латентных кадров, генерируемых за один чанк при авторегрессионной генерации.

keep_first_frame (`bool`, *необязательный*, по умолчанию `True`) : Указывает, следует ли сохранять первый кадр между чанками.

is_skip_first_chunk (`bool`, *необязательный*, по умолчанию `False`) : Нужно ли пропустить генерацию первого фрагмента.

**Возвращает:** `~HeliosPipelineOutput` или `tuple`

Если `return_dict` равно `True`, возвращается `HeliosPipelineOutput`, иначе возвращается `tuple`, где первый элемент — это список сгенерированных изображений, а второй — список значений `bool`, указывающих, содержит ли соответствующее сгенерированное изображение контент, нежелательный для просмотра на рабочем месте (nsfw).

Функция вызова конвейера для генерации.

Примеры:
```python
>>> import torch
>>> from diffusers.utils import export_to_video
>>> from diffusers import AutoencoderKLWan, HeliosPipeline

>>> # Available models: BestWishYsh/Helios-Base, BestWishYsh/Helios-Mid, BestWishYsh/Helios-Distilled
>>> model_id = "BestWishYsh/Helios-Base"
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
>>> pipe = HeliosPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"

>>> output = pipe(
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     height=384,
...     width=640,
...     num_frames=132,
...     guidance_scale=5.0,
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=24)
```

#### encode_prompt[[diffusers.HeliosPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[Источник](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/helios/pipeline_helios.py#L196)

**Параметры:**

prompt (`str` или `list[str]`, *необязательный*) : промпт для кодирования

negative_prompt (`str` или `list[str]`, *необязательный*) : Промпт или промпты, которые не должны направлять генерацию изображения. Если не задан, необходимо передать `negative_prompt_embeds`. Игнорируется, если не используется направляющее влияние (то есть игнорируется, если `guidance_scale` меньше `1`).

do_classifier_free_guidance (`bool`, *необязательный*, по умолчанию `True`) : Использовать ли classifier free guidance.

num_videos_per_prompt (`int`, *optional*, по умолчанию 1) : Количество видео, которые должны быть сгенерированы для каждого промпта. Устройство torch, на котором должны размещаться результирующие эмбеддинги

prompt_embeds (`torch.Tensor`, *необязательный*) : Предварительно сгенерированные текстовые эмбеддинги. Можно использовать для простой настройки текстовых входных данных, *например* для взвешивания промпта. Если не предоставлены, текстовые эмбеддинги будут сгенерированы из входного аргумента `prompt`.

negative_prompt_embeds (`torch.Tensor`, *необязательный*) : Предварительно сгенерированные отрицательные текстовые эмбеддинги. Можно использовать для простой настройки текстовых входных данных, *например* для взвешивания промпта. Если не предоставлены, negative_prompt_embeds будут сгенерированы из входного аргумента `negative_prompt`.

device : (`torch.device`, *необязательный*): устройство torch

dtype : (`torch.dtype`, *необязательный*): torch dtype

Кодирует промпт в скрытые состояния текстового энкодера.

## HeliosPyramidPipeline[[diffusers.HeliosPyramidPipeline]]

#### diffusers.HeliosPyramidPipeline[[diffusers.HeliosPyramidPipeline]]

```python
diffusers.HeliosPyramidPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, vae: AutoencoderKLWan, scheduler: diffusers.schedulers.scheduling_helios.HeliosScheduler | diffusers.schedulers.scheduling_helios_dmd.HeliosDMDScheduler, transformer: HeliosTransformer3DModel, is_cfg_zero_star: bool = False, is_distilled: bool = False)
```

[Источник](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/helios/pipeline_helios_pyramid.py#L121)

**Параметры:**

tokenizer (`T5Tokenizer`) : Токенизатор из [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer), а именно вариант [google/umt5-xxl](https://huggingface.co/google/umt5-xxl).

text_encoder (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), а именно вариант [google/umt5-xxl](https://huggingface.co/google/umt5-xxl).

transformer ([HeliosTransformer3DModel](/docs/diffusers/main/ru/api/models/helios_transformer3d#diffusers.HeliosTransformer3DModel)) : Условный Transformer для удаления шума из входных латентов.

scheduler ([`HeliosScheduler`, `HeliosDMDScheduler`]) : планировщик, используемый в сочетании с `transformer` для удаления шума из закодированных латентов изображения.

vae ([AutoencoderKLWan](/docs/diffusers/main/ru/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan)) : Модель вариационного автоэнкодера (VAE) для кодирования и декодирования видео в латентные представления и обратно.

Pipeline для генерации видео из текста / из изображения / из видео с использованием Helios.

Эта модель наследуется от [DiffusionPipeline](/docs/diffusers/main/ru/api/pipelines/overview#diffusers.DiffusionPipeline). Общую документацию по методам, реализованным для всех пайплайнов (загрузка, сохранение, запуск на конкретном устройстве и т. д.), см. в документации родительского класса.

#### __call__[[diffusers.HeliosPyramidPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, negative_prompt: str | list[str] = None, height: int = 384, width: int = 640, num_frames: int = 132, sigmas: list = None, guidance_scale: float = 5.0, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 512, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, image_latents: typing.Optional[torch.Tensor] = None, fake_image_latents: typing.Optional[torch.Tensor] = None, add_noise_to_image_latents: bool = True, image_noise_sigma_min: float = 0.111, image_noise_sigma_max: float = 0.135, video: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, video_latents: typing.Optional[torch.Tensor] = None, add_noise_to_video_latents: bool = True, video_noise_sigma_min: float = 0.111, video_noise_sigma_max: float = 0.135, history_sizes: list = [16, 2, 1], num_latent_frames_per_chunk: int = 9, keep_first_frame: bool = True, is_skip_first_chunk: bool = False, pyramid_num_inference_steps_list: list = [10, 10, 10], use_zero_init: bool | None = True, zero_steps: int | None = 1, is_amplify_first_chunk: bool = False)
```

[Источник](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/helios/pipeline_helios_pyramid.py#L508)

**Параметры:**

prompt (`str` или `list[str]`, *необязательный*) : Промпт или промпты для управления генерацией изображения. Если не задан, передайте вместо него `prompt_embeds`.

negative_prompt (`str` или `list[str]`, *необязательный*) : Промпт или промпты, которые следует избегать при генерации изображения. Если не задан, передайте вместо него `negative_prompt_embeds`. Игнорируется, если не используется направляющая (`guidance_scale` < `1`).

height (`int`, по умолчанию `384`) : Высота генерируемого изображения в пикселях.

width (`int`, по умолчанию `640`) : Ширина генерируемого изображения в пикселях.

num_frames (`int`, по умолчанию `132`) : Количество кадров в сгенерированном видео.

sigmas (`list[float]`, *optional*) : Пользовательские сигмы для процесса удаления шума. Если не заданы, используется расписание по умолчанию планировщика.

guidance_scale (`float`, по умолчанию `5.0`) : Масштаб руководства, определенный в [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` определяется как `w` из уравнения 2 в [Imagen Paper](https://huggingface.co/papers/2205.11487). Масштаб руководства активируется при установке `guidance_scale > 1`. Более высокий масштаб руководства способствует генерации изображений, тесно связанных с текстовым `prompt`, обычно за счет снижения качества изображения.

num_videos_per_prompt (`int`, *необязательный*, по умолчанию 1) : Количество изображений, генерируемых на один запрос.

generator (`torch.Generator` или `list[torch.Generator]`, *необязательно*) : [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) для обеспечения детерминированности генерации.

latents (`torch.Tensor`, *необязательный*) : Предварительно сгенерированные шумовые латенты, выбранные из гауссова распределения, которые используются в качестве входных данных для генерации изображений. Позволяет корректировать одну и ту же генерацию с помощью разных промптов. Если не задано, тензор латентов генерируется путём выборки с использованием переданного случайного `generator`.

prompt_embeds (`torch.Tensor`, *необязательный*) : Предварительно сгенерированные текстовые эмбеддинги. Можно использовать для простой настройки текстовых входных данных (взвешивание промпта). Если не предоставлены, текстовые эмбеддинги генерируются из входного аргумента `prompt`.

negative_prompt_embeds (`torch.Tensor`, *необязательный*) : Предварительно сгенерированные отрицательные текстовые эмбеддинги. Если не указаны, они генерируются из `negative_prompt`.

output_type (`str`, *необязательный*, по умолчанию `"np"`) : Формат вывода сгенерированного изображения. Выберите между `PIL.Image` и `np.array`.

return_dict (`bool`, *необязательный*, по умолчанию `True`) : Возвращать ли `HeliosPipelineOutput` вместо обычного кортежа.

attention_kwargs (`dict`, *необязательный*) : Словарь kwargs, который при указании передается в `AttentionProcessor`, определенный в `self.processor` в [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : функция или подкласс `PipelineCallback` или `MultiPipelineCallbacks`, вызываемая в конце каждого шага денойзинга во время инференса со следующими аргументами: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` будет содержать список всех тензоров, как указано в `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Список тензорных входных данных для функции `callback_on_step_end`. Тензоры, указанные в списке, будут переданы в качестве аргумента `callback_kwargs`. Вы сможете включать только переменные, перечисленные в атрибуте `._callback_tensor_inputs` вашего класса pipeline.

max_sequence_length (`int`, по умолчанию `512`) : Максимальная длина последовательности для текстового энкодера. Если промпт длиннее этого значения, он будет усечён. Если промпт короче, он будет дополнен до этой длины.

image (`PipelineImageInput`, *необязательный*) : Входное изображение, используемое для условного формирования видео по изображению.

image_latents (`torch.Tensor`, *необязательный*) : Предварительно закодированные латенты изображения для использования вместо `image`.

fake_image_latents (`torch.Tensor`, *необязательный*) : Необязательные фиктивные латентные изображения, используемые при условии.

add_noise_to_image_latents (`bool`, *необязательный*, по умолчанию `True`) : Добавлять ли шум к латентам изображения перед денойзингом.

image_noise_sigma_min (`float`, *optional*, по умолчанию `0.111`) : Минимальное значение сигмы для шума, добавляемого к латентам изображения.

image_noise_sigma_max (`float`, *optional*, по умолчанию `0.135`) : Максимальное значение сигмы для шума, добавляемого к латентам изображения.

video (`PipelineImageInput`, *необязательный*) : Входящее видео, используемое для видео-в-видео обусловливания.

video_latents (`torch.Tensor`, *необязательный*) : Предварительно закодированные латенты видео для использования вместо `video`.

add_noise_to_video_latents (`bool`, *необязательный*, по умолчанию `True`) : Добавлять ли шум к латентам видео перед денойзингом.

video_noise_sigma_min (`float`, *необязательный*, по умолчанию `0.111`) : Минимальное значение сигмы для шума, добавляемого к латентам видео.

video_noise_sigma_max (`float`, *необязательный*, по умолчанию `0.135`) : Максимальное значение сигмы для шума, добавляемого к латентам видео.

history_sizes (`list`, *необязательный*, по умолчанию `[16, 2, 1]`) : Размеры окон истории, используемые для авто-регрессивной генерации по чанкам.

num_latent_frames_per_chunk (`int`, *необязательный*, по умолчанию `9`) : Количество латентных кадров, генерируемых за один чанк при авторегрессионной генерации.

keep_first_frame (`bool`, *необязательный*, по умолчанию `True`) : Указывает, следует ли сохранять первый кадр между чанками.

is_skip_first_chunk (`bool`, *необязательный*, по умолчанию `False`) : Нужно ли пропустить генерацию первого фрагмента.

pyramid_num_inference_steps_list (`list`, *необязательный*, по умолчанию `[10, 10, 10]`) : Количество шагов инференса для каждого этапа пирамиды при генерации на этапе 2.

use_zero_init (`bool`, *необязательный*, по умолчанию `True`) : Нужно ли применять CFG zero-init в начале процесса денойзинга.

zero_steps (`int`, *optional*, по умолчанию `1`) : Количество начальных шагов, использующих CFG zero-init.

is_amplify_first_chunk (`bool`, *необязательный*, по умолчанию `False`) : Усиливает ли направляющий сигнал на первом фрагменте (связано с DMD).

**Возвращает:** `~HeliosPipelineOutput` или `tuple`

Если `return_dict` равно `True`, возвращается `HeliosPipelineOutput`, иначе возвращается `tuple`, где первый элемент — это список сгенерированных изображений, а второй — список значений `bool`, указывающих, содержит ли соответствующее сгенерированное изображение контент, нежелательный для просмотра на рабочем месте (nsfw).

Функция вызова конвейера для генерации.

Примеры:
```python
>>> import torch
>>> from diffusers.utils import export_to_video
>>> from diffusers import AutoencoderKLWan, HeliosPyramidPipeline

>>> # Available models: BestWishYsh/Helios-Base, BestWishYsh/Helios-Mid, BestWishYsh/Helios-Distilled
>>> model_id = "BestWishYsh/Helios-Base"
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
>>> pipe = HeliosPyramidPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"

>>> output = pipe(
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     height=384,
...     width=640,
...     num_frames=132,
...     guidance_scale=5.0,
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=24)
```

#### encode_prompt[[diffusers.HeliosPyramidPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[Источник](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/helios/pipeline_helios_pyramid.py#L214)

**Параметры:**

prompt (`str` или `list[str]`, *необязательный*) : промпт для кодирования

negative_prompt (`str` или `list[str]`, *необязательный*) : Промпт или промпты, которые не должны направлять генерацию изображения. Если не задан, необходимо передать `negative_prompt_embeds`. Игнорируется, если не используется направляющее влияние (то есть игнорируется, если `guidance_scale` меньше `1`).

do_classifier_free_guidance (`bool`, *необязательный*, по умолчанию `True`) : Использовать ли classifier free guidance.

num_videos_per_prompt (`int`, *optional*, по умолчанию 1) : Количество видео, которые должны быть сгенерированы для каждого промпта. Устройство torch, на котором должны размещаться результирующие эмбеддинги

prompt_embeds (`torch.Tensor`, *необязательный*) : Предварительно сгенерированные текстовые эмбеддинги. Можно использовать для простой настройки текстовых входных данных, *например* для взвешивания промпта. Если не предоставлены, текстовые эмбеддинги будут сгенерированы из входного аргумента `prompt`.

negative_prompt_embeds (`torch.Tensor`, *необязательный*) : Предварительно сгенерированные отрицательные текстовые эмбеддинги. Можно использовать для простой настройки текстовых входных данных, *например* для взвешивания промпта. Если не предоставлены, negative_prompt_embeds будут сгенерированы из входного аргумента `negative_prompt`.

device : (`torch.device`, *необязательный*): устройство torch

dtype : (`torch.dtype`, *необязательный*): torch dtype

Кодирует промпт в скрытые состояния текстового энкодера.

## HeliosPipelineOutput[[diffusers.pipelines.helios.pipeline_output.HeliosPipelineOutput]]

#### diffusers.pipelines.helios.pipeline_output.HeliosPipelineOutput[[diffusers.pipelines.helios.pipeline_output.HeliosPipelineOutput]]

```python
diffusers.pipelines.helios.pipeline_output.HeliosPipelineOutput(frames: Tensor)
```

[Источник](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/helios/pipeline_output.py#L9)

**Параметры:**

frames (`torch.Tensor`, `np.ndarray` или List[List[PIL.Image.Image]]) : Список видеовыходов — может представлять собой вложенный список длины `batch_size,` где каждый подсписок содержит последовательности денойзированных изображений PIL длины `num_frames.` Также может быть массивом NumPy или тензором Torch формы `(batch_size, num_frames, channels, height, width)`.

Класс вывода для конвейеров Helios.

