# Stable Audio 3

Stable Audio 3 (SA3) là mô hình text-to-audio từ [Stability AI](https://stability.ai/), tạo ra âm thanh stereo chất lượng cao ở 44.1 kHz. Nó sử dụng rectified-flow DiT được điều kiện bởi hai tín hiệu:

* **Văn bản** — được mã hóa bởi bộ mã hóa T5Gemma đóng băng và được tiêm qua cơ chế chú ý chéo (cross-attention).
* **Thời lượng** — một số float (giây) được nhúng bởi [StableAudio3DurationEmbedder](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_audio_3#diffusers.StableAudio3DurationEmbedder) và được sử dụng làm vector điều kiện toàn cục cho chuẩn hóa lớp thích ứng.

Âm thanh được giải mã bởi autoencoder SAME (Semantically-Aligned Music Encoder), [AutoencoderSAME](/docs/diffusers/v0.43.0/vi/api/models/autoencoder_same#diffusers.AutoencoderSAME).

Cả hai checkpoint đều sử dụng [FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler) với lịch sigma log-SNR-uniform, chỉ khác nhau ở `stochastic_sampling` và số bước mặc định:

| Checkpoint | `diffusion_objective` | `stochastic_sampling` | `num_inference_steps` |
|---|---|---|---|
| `stable-audio-3-medium-base` | `rectified_flow` | `False` (Euler tất định) | **100** (không được chưng cất) |
| `stable-audio-3-medium` (đã chưng cất) | `rf_denoiser` | `True` (ping-pong re-noise) | **8** (được chưng cất trong 8 bước) |

Cấu hình scheduler chính xác được tích hợp sẵn trong mỗi checkpoint đã chuyển đổi, do đó `num_inference_steps` sẽ mặc định ở giá trị đúng khi bạn không đặt giá trị này. Chỉ truyền tham số này khi cần ghi đè.

Mã nguồn gốc: [Stability-AI/stable-audio-3](https://github.com/Stability-AI/stable-audio-3).

## Chuyển đổi các checkpoint gốc

Các checkpoint của Stability AI không được phát hành ở định dạng diffusers, vì vậy hãy chuyển đổi chúng cục bộ. Script sẽ tải xuống `model_config.json` của checkpoint và chọn scheduler từ `diffusion_objective` của nó:

```bash
python scripts/convert_stable_audio_3_to_diffusers.py \
  --checkpoint_path stabilityai/stable-audio-3-medium-base \
  --text_encoder_repo google/t5gemma-b-b-ul2 \
  --output_dir /tmp/sa3-diffusers-euler \
  --dtype float32
```

> [!TIP]
> `stable-audio-3-medium-base` là một repo **gated**. Hãy chạy `hf auth login` bằng một tài khoản có quyền truy cập trước khi chuyển đổi, nếu không quá trình tải xuống sẽ thất bại với mã 401.

## Ví dụ sử dụng

Tải checkpoint đã chuyển đổi từ thư mục đầu ra cục bộ (cài đặt [`soundfile`](https://pypi.org/project/soundfile/) bằng `pip install soundfile`):

```py
import torch
import soundfile as sf
from diffusers import StableAudio3Pipeline

pipe = StableAudio3Pipeline.from_pretrained("/tmp/sa3-diffusers-euler", torch_dtype=torch.float32)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

generator = torch.Generator("cuda").manual_seed(0)
audio = pipe(
    "A gentle piano melody with soft strings in a concert hall",
    duration=10.0,  # seconds; latent length is computed automatically
    generator=generator,
).audios

sf.write("sa3_output.wav", audio[0].T.cpu().float().numpy(), samplerate=44100)
```

Pipeline cũng được đăng ký với [AutoPipelineForText2Audio](/docs/diffusers/v0.43.0/vi/api/pipelines/auto_pipeline#diffusers.AutoPipelineForText2Audio), thành phần này sẽ tự động phân giải checkpoint thành `StableAudio3Pipeline`:

```py
from diffusers import AutoPipelineForText2Audio

pipe = AutoPipelineForText2Audio.from_pretrained("/tmp/sa3-diffusers-euler", torch_dtype=torch.float32)
```

> [!NOTE]
> Các ví dụ sử dụng đường dẫn cục bộ vì `stabilityai/stable-audio-3-medium` và `stable-audio-3-medium-base` chưa được phát hành ở định dạng diffusers (tải theo repo id sẽ trả về lỗi 404). Khi được phát hành, repo id sẽ hoạt động thay cho đường dẫn cục bộ.

## Mẹo

* Sử dụng `torch.float32` trên CPU hoặc MPS (Apple Silicon) — `torch.float16` trên MPS sẽ tạo ra nhiễu.
* Mô hình đã được chưng cất (`stable-audio-3-medium`) được **chưng cất đối kháng** — guidance được tích hợp sẵn vào trọng số. Giữ nguyên `guidance_scale=1.0` (mặc định) và không truyền `negative_prompt` cho checkpoint đó; cả hai chỉ có tác dụng hữu ích với checkpoint `stable-audio-3-medium-base` chưa được chưng cất.
* `silence_padding_duration` (mặc định `0.0`) thêm khoảng im lặng ở cuối chuỗi latent. Giữ nguyên ở `0.0` trừ khi mô hình được huấn luyện để che phần đệm đó — nếu không, các khung hình thừa sẽ làm giảm năng lượng đầu ra và kết quả sẽ nhỏ hơn.
* Đặt `num_waveforms_per_prompt > 1` để tạo nhiều clip cho mỗi prompt.

## StableAudio3Pipeline[[diffusers.StableAudio3Pipeline]]

#### diffusers.StableAudio3Pipeline[[diffusers.StableAudio3Pipeline]]

```python
diffusers.StableAudio3Pipeline(vae: AutoencoderSAME, text_encoder: T5GemmaEncoderModel, tokenizer: GemmaTokenizer, duration_embedder: StableAudio3DurationEmbedder, transformer: StableAudio3DiTModel, scheduler: FlowMatchEulerDiscreteScheduler)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3.py#L157)

**Tham số:**

vae ([*AutoencoderSAME*]) : autoencoder SAME được sử dụng để mã hóa và giải mã các ẩn âm thanh.

text_encoder ([*~transformers.T5GemmaEncoderModel*]) : Bộ mã hóa văn bản T5Gemma được đóng băng (`google/t5gemma-b-b-ul2`).

tokenizer ([*~transformers.GemmaTokenizerFast*]) : Tokenizer cho text encoder.

duration_embedder ([*StableAudio3DurationEmbedder*]) : Ánh xạ `duration` tính bằng giây thành một vector điều kiện toàn cục cho AdaLN trong mỗi khối DiT.

transformer ([*StableAudio3DiTModel*]) : DiT dự đoán vận tốc rectified-flow.

scheduler ([*FlowMatchEulerDiscreteScheduler*]) : Scheduler cho vòng lặp khử nhiễu lặp lại. Checkpoint SA3 Medium (distilled) dùng trong production sử dụng *stochastic_sampling=True* cho đúng 8 bước ping-pong; checkpoint base không distilled sử dụng *stochastic_sampling=False* cho ~100 bước Euler tất định.

Pipeline để tạo audio từ văn bản sử dụng Stable Audio 3.

SA3 sử dụng DiT rectified-flow đã được chưng cất với phương pháp lấy mẫu ping-pong. Hướng dẫn không có bộ phân loại (`guidance_scale` / `negative_prompt`) là không cần thiết cho checkpoint đã chưng cất (giữ nguyên `guidance_scale=1.0`, giá trị mặc định) nhưng có ý nghĩa đối với checkpoint `stable-audio-3-medium-base` chưa được chưng cất.

Mô hình này kế thừa từ [*DiffusionPipeline*]. Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline.

#### __call__[[diffusers.StableAudio3Pipeline.__call__]]

```python
__call__(prompt: typing.Union[str, typing.List[str], NoneType] = None, duration: float = 10.0, num_inference_steps: typing.Optional[int] = None, logsnr_min: float = -6.2, logsnr_max: float = 2.0, silence_padding_duration: float = 0.0, guidance_scale: float = 1.0, negative_prompt: typing.Union[str, typing.List[str], NoneType] = None, num_waveforms_per_prompt: int = 1, generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, encoder_attention_mask: typing.Optional[torch.LongTensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_encoder_attention_mask: typing.Optional[torch.LongTensor] = None, return_dict: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], dict]] = None, callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'], output_type: str = 'pt')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3.py#L398)

**Tham số:**

prompt (*str* hoặc *list[str]*, *tùy chọn*) : Prompt văn bản. Truyền `prompt_embeds` thay vào đó để bỏ qua tokenization và encoding.

duration (*float*, mặc định là 10.0) : Thời lượng đầu ra yêu cầu, tính bằng giây.

num_inference_steps (*int*, *optional*) : Số bước khử nhiễu. Khi `None` (mặc định), số bước được chọn từ cấu hình *stochastic_sampling* của trình lập lịch: **8** khi *True* (checkpoint kiểu ping-pong đã chưng cất) và **100** khi *False* (checkpoint cơ sở chưa chưng cất). Truyền một giá trị rõ ràng để ghi đè.

logsnr_min (*float*, mặc định là -6.2) : Giá trị log-SNR tối thiểu cho lịch trình nhiễu — tương ứng với điểm bắt đầu có nhiễu cao của lịch trình.

logsnr_max (*float*, mặc định là 2.0) : Giá trị log-SNR tối đa cho lịch trình nhiễu — tương ứng với đầu có mức nhiễu thấp của lịch trình.

silence_padding_duration (*float*, mặc định là 0.0) : Số giây ngữ cảnh tiềm ẩn (latent context) bổ sung được tạo ra ngoài nội dung mục tiêu, giúp mô hình có thêm không gian dự phòng tại ranh giới; đầu ra sẽ được cắt gọn lại về *duration*. Mặc định là 0.0 (tắt). Chỉ tăng giá trị này nếu mô hình được huấn luyện/chưng cất (distilled) để che (mask) phần đệm này — nếu không, các khung hình bổ sung sẽ làm hao hụt năng lượng đầu ra.

guidance_scale (*float*, mặc định là 1.0) : Thang độ hướng dẫn không điều kiện (classifier-free guidance). `1.0` tắt hướng dẫn (mặc định, và là giá trị hợp lý duy nhất cho checkpoint SA3 Medium đã được chưng cất, vì CFG của nó đã được tích hợp vào trọng số). Các giá trị `> 1.0` có ý nghĩa đối với checkpoint `stable-audio-3-medium-base` chưa được chưng cất; các giá trị cao hơn sẽ bám sát prompt hơn nhưng đánh đổi bằng sự đa dạng.

negative_prompt (*str* hoặc *list[str]*, *tùy chọn*) : Prompt mô tả những gì cần tránh khi `guidance_scale > 1.0`. Mặc định là chuỗi rỗng (không điều kiện) khi `guidance_scale > 1.0` và cả tham số này lẫn *negative_prompt_embeds* đều không được cung cấp. Bị bỏ qua khi `guidance_scale &amp;lt;= 1.0`.

num_waveforms_per_prompt (*int*, mặc định là 1) : Số lượng dạng sóng cần tạo cho mỗi prompt.

generator (*torch.Generator* hoặc *list[torch.Generator]*, *tùy chọn*) : Dùng cho việc tạo ra có tính xác định và tái nhiễu có thể tái lập trong vòng lặp ping-pong.

latents (*torch.Tensor*, *optional*) : Các latents khởi đầu đã được tạo trước. Nếu là `None`, một tensor Gaussian mới sẽ được lấy mẫu.

prompt_embeds (*torch.Tensor*, *optional*) : Các vector nhúng văn bản đã tính trước `(batch, seq_len, 768)`.

encoder_attention_mask (*torch.LongTensor*, *optional*) : Mặt nạ Boolean cho các embedding đã tính trước.

negative_prompt_embeds (*torch.Tensor*, *optional*) : Các embedding văn bản âm đã được tính trước, như một phương án thay thế cho *negative_prompt*.

negative_encoder_attention_mask (*torch.LongTensor*, *optional*) : Mặt nạ Boolean cho các embedding âm đã được tính trước.

return_dict (*bool*, mặc định là *True*) : Trả về một *AudioPipelineOutput* hoặc một tuple thông thường.

callback_on_step_end (*Callable*, *tuỳ chọn*) : Được gọi vào cuối mỗi bước khử nhiễu với *(self, step_idx, timestep, callback_kwargs)*, trong đó *callback_kwargs* chứa các tensor được liệt kê trong *callback_on_step_end_tensor_inputs*. Phải trả về một dict chứa các tensor (có thể đã được sửa đổi) để sử dụng cho phần còn lại của vòng lặp.

callback_on_step_end_tensor_inputs (*list[str]*, mặc định là *["latents"]*) : Các tensor được truyền vào *callback_on_step_end*. Phải là một tập con của *self._callback_tensor_inputs*.

output_type (*str*, mặc định là `"pt"`) : `"pt"` cho tensor PyTorch, `"np"` cho mảng NumPy, hoặc `"latent"` để bỏ qua giải mã và trả về các latent thô.

**Trả về:** [*~pipelines.AudioPipelineOutput*] hoặc *tuple*

`.audios` là một tensor / mảng có hình dạng `(batch * num_waveforms_per_prompt, audio_channels, samples)`.

Tạo âm thanh từ một câu lệnh văn bản.

Ví dụ:
```py
>>> import torch
>>> import soundfile as sf
>>> from diffusers import StableAudio3Pipeline

>>> pipe = StableAudio3Pipeline.from_pretrained("stabilityai/stable-audio-3-medium", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")

>>> generator = torch.Generator("cuda").manual_seed(0)
>>> audio = pipe(
...     "A gentle piano melody with soft strings in a concert hall",
...     duration=10.0,
...     generator=generator,
... ).audios

>>> sf.write("output.wav", audio[0].T.cpu().float().numpy(), samplerate=pipe.vae.config.sampling_rate)
```

#### encode_duration[[diffusers.StableAudio3Pipeline.encode_duration]]

```python
encode_duration(duration: float, device: device, num_waveforms_per_prompt: int, batch_size: int)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3.py#L289)

**Tham số:**

duration : Thời lượng tính bằng giây, được áp dụng cho mọi mẫu trong lô.

device : Thiết bị đích.

num_waveforms_per_prompt : Hệ số lát.

batch_size : Số lượng prompt.

**Trả về:**

tensor `(batch * num_waveforms_per_prompt, output_dim)`.

Nhúng giá trị thời lượng vào vector điều kiện toàn cục.

#### encode_prompt[[diffusers.StableAudio3Pipeline.encode_prompt]]

```python
encode_prompt(prompt: typing.Union[str, typing.List[str], NoneType], device: device, num_waveforms_per_prompt: int, prompt_embeds: typing.Optional[torch.Tensor] = None, encoder_attention_mask: typing.Optional[torch.LongTensor] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3.py#L223)

**Tham số:**

prompt : Text prompt hoặc danh sách các prompt. Bỏ qua khi `prompt_embeds` được cung cấp.

device : Thiết bị đích.

num_waveforms_per_prompt : Số lượng dạng sóng đầu ra cần tạo cho mỗi prompt; các tensor điều kiện sẽ được nhân bản (tile) tương ứng.

prompt_embeds : Nhúng văn bản đã tính trước `(batch, seq_len, hidden_size)`.

encoder_attention_mask : Mặt nạ Boolean `(batch, seq_len)` cho các embedding đã tính trước; `1` = token thực, `0` = pad.

**Trả về:**

`(prompt_embeds, encoder_attention_mask)` đều được nhân rộng (tiled) thành `batch * num_waveforms_per_prompt`.

Mã hóa các prompt văn bản thành các tensor điều kiện cho cross-attention.

#### prepare_cross_attention[[diffusers.StableAudio3Pipeline.prepare_cross_attention]]

```python
prepare_cross_attention(prompt_embeds: Tensor, encoder_attention_mask: Tensor, global_hidden_states: Tensor)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3.py#L313)

**Trả về:**

`(context, context_mask)` có hình dạng `(batch, T_text + 1, dim)` và `(batch, T_text + 1)`.

Xây dựng ngữ cảnh cross-attention bằng cách thêm embedding thời lượng vào như một token bổ sung.

SA3 định tuyến conditioner `seconds_total` đến *cả* đầu vào toàn cục (AdaLN) lẫn ngữ cảnh cross-attention (`cross_attention_cond_ids = ["prompt", "seconds_total"]`). Embedding thời lượng được nối sau các text token, và attention mask được mở rộng thêm một mục hợp lệ.

## StableAudio3InpaintPipeline[[diffusers.StableAudio3InpaintPipeline]]

#### diffusers.StableAudio3InpaintPipeline[[diffusers.StableAudio3InpaintPipeline]]

```python
diffusers.StableAudio3InpaintPipeline(vae: AutoencoderSAME, text_encoder: T5GemmaEncoderModel, tokenizer: GemmaTokenizer, duration_embedder: StableAudio3DurationEmbedder, transformer: StableAudio3DiTModel, scheduler: FlowMatchEulerDiscreteScheduler)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3_inpaint.py#L158)

**Tham số:**

vae ([*AutoencoderSAME*]) : autoencoder SAME được sử dụng để mã hóa và giải mã các ẩn âm thanh.

text_encoder ([*~transformers.T5GemmaEncoderModel*]) : Bộ mã hóa văn bản T5Gemma được đóng băng (`google/t5gemma-b-b-ul2`).

tokenizer ([*~transformers.GemmaTokenizerFast*]) : Tokenizer cho text encoder.

duration_embedder ([*StableAudio3DurationEmbedder*]) : Ánh xạ `duration` tính bằng giây thành một vector điều kiện toàn cục cho AdaLN trong mỗi khối DiT.

transformer ([*StableAudio3DiTModel*]) : DiT dự đoán vận tốc rectified-flow.

scheduler ([*FlowMatchEulerDiscreteScheduler*]) : Scheduler cho vòng lặp khử nhiễu lặp lại. Checkpoint SA3 Medium (distilled) dùng trong production sử dụng *stochastic_sampling=True* cho đúng 8 bước ping-pong; checkpoint base không distilled sử dụng *stochastic_sampling=False* cho ~100 bước Euler tất định.

Pipeline inpainting âm thanh cho Stable Audio 3.

Chia sẻ logic text-to-audio với [*StableAudio3Pipeline*] (được đồng bộ thông qua *# Copied from*). Khi `audio` và `mask` được cung cấp, mã hóa âm thanh tham chiếu bằng bộ mã hóa SAME đã đóng băng và tiêm `masked_latent ∥ mask` như điều kiện cộng cục bộ vào mỗi khối DiT thông qua đường dẫn `local_add_cond` của transformer (`to_local_embed`).

Mở rộng chữ ký gọi (xem `__call__`): audio (*torch.Tensor* có hình dạng `(batch, channels, samples)`): Dạng sóng âm thanh tham chiếu ở tần số lấy mẫu `vae.config.sampling_rate` Hz. mask (*torch.Tensor* có hình dạng `(batch, 1, latent_length)`): Mặt nạ nhị phân theo từng khung trong không gian ẩn. `1` = giữ nguyên âm thanh gốc; `0` = vùng cần được inpaint.

#### __call__[[diffusers.StableAudio3InpaintPipeline.__call__]]

```python
__call__(prompt: typing.Union[str, typing.List[str], NoneType] = None, duration: float = 10.0, audio: typing.Optional[torch.Tensor] = None, mask: typing.Optional[torch.Tensor] = None, mask_start_seconds: typing.Union[float, typing.List[float], NoneType] = None, mask_end_seconds: typing.Union[float, typing.List[float], NoneType] = None, num_inference_steps: typing.Optional[int] = None, logsnr_min: float = -6.2, logsnr_max: float = 2.0, silence_padding_duration: float = 0.0, num_waveforms_per_prompt: int = 1, generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, encoder_attention_mask: typing.Optional[torch.LongTensor] = None, return_dict: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], dict]] = None, callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'], output_type: str = 'pt')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3_inpaint.py#L455)

**Tham số:**

prompt (*str* hoặc *list[str]*, *tùy chọn*) : Prompt văn bản.

duration (*float*, mặc định là 10.0) : Thời lượng đầu ra tính bằng giây. Cần khớp với âm thanh tham chiếu.

audio (*torch.Tensor*, *optional*) : Dạng sóng tham chiếu `(batch, channels, samples)` ở tần số lấy mẫu `vae.config.sampling_rate` Hz. Bắt buộc cho inpainting.

mask (*torch.Tensor*, *optional*) : Mặt nạ không gian tiềm ẩn theo từng khung hình `(batch, 1, L)` với 0 = vùng inpaint, 1 = giữ nguyên. Phải cung cấp `mask` hoặc `mask_start_seconds` / `mask_end_seconds`.

mask_start_seconds (*float* hoặc *list[float]*, *tuỳ chọn*) : Thời gian bắt đầu (các) của vùng inpaint tính bằng giây.

mask_end_seconds (*float* hoặc *list[float]*, *tuỳ chọn*) : Thời điểm kết thúc của vùng inpaint (phải đi kèm với `mask_start_seconds`).

num_inference_steps (*int*, *optional*) : Số bước khử nhiễu. Khi `None` (mặc định), số bước được chọn từ cấu hình *stochastic_sampling* của trình lập lịch, khớp với [*StableAudio3Pipeline*].

logsnr_min (*float*, mặc định là -6.2) : Giá trị log-SNR tối thiểu cho lịch trình nhiễu — tương ứng với điểm bắt đầu có nhiễu cao của lịch trình.

logsnr_max (*float*, mặc định là 2.0) : Giá trị log-SNR tối đa cho lịch trình nhiễu — tương ứng với đầu có mức nhiễu thấp của lịch trình.

silence_padding_duration (*float*, mặc định là 0.0) : Khoảng trống tiềm ẩn bổ sung sau nội dung đích.

num_waveforms_per_prompt (*int*, mặc định là 1) : Số lượng waveform cho mỗi prompt.

generator : RNG để đảm bảo khả năng tái lập.

latents : Nhiễu khởi tạo đã tạo sẵn (`None` → lấy mẫu mới).

prompt_embeds : Nhúng văn bản đã tính trước.

encoder_attention_mask : Mặt nạ cho các embedding đã tính toán trước.

return_dict (*bool*, mặc định là *True*) : Trả về *AudioPipelineOutput* hoặc tuple.

callback_on_step_end (*Callable*, *tùy chọn*) : Được gọi vào cuối mỗi bước khử nhiễu với *(self, step_idx, timestep, callback_kwargs)*. Phải trả về một dict chứa các tensor (có thể đã được sửa đổi) để sử dụng cho phần còn lại của vòng lặp.

callback_on_step_end_tensor_inputs (*list[str]*, mặc định là *["latents"]*) : Các tensor được truyền vào *callback_on_step_end*. Phải là một tập con của *self._callback_tensor_inputs*.

output_type (*str*, mặc định là `"pt"`) : `"pt"` / `"np"` / `"latent"`.

**Trả về:**

[*~pipelines.AudioPipelineOutput*] với `.audios`.

Tạo âm thanh được khôi phục có điều kiện dựa trên một câu lệnh văn bản và một tham chiếu.

Ví dụ:
```py
>>> import torch
>>> import soundfile as sf
>>> import torchaudio
>>> from diffusers import StableAudio3InpaintPipeline

>>> pipe = StableAudio3InpaintPipeline.from_pretrained(
...     "stabilityai/stable-audio-3-medium", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> audio, sr = torchaudio.load("reference.wav")
>>> audio = torchaudio.functional.resample(audio, sr, pipe.vae.config.sampling_rate).unsqueeze(0).to("cuda")

>>> generator = torch.Generator("cuda").manual_seed(0)
>>> audio = pipe(
...     "A gentle piano melody with soft strings in a concert hall",
...     duration=10.0,
...     audio=audio,
...     mask_start_seconds=4.0,
...     mask_end_seconds=6.0,
...     generator=generator,
... ).audios

>>> sf.write("output.wav", audio[0].T.cpu().float().numpy(), samplerate=pipe.vae.config.sampling_rate)
```

#### encode_duration[[diffusers.StableAudio3InpaintPipeline.encode_duration]]

```python
encode_duration(duration: float, device: device, num_waveforms_per_prompt: int, batch_size: int)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3_inpaint.py#L290)

**Tham số:**

duration : Thời lượng tính bằng giây, được áp dụng cho mọi mẫu trong lô.

device : Thiết bị đích.

num_waveforms_per_prompt : Hệ số lát.

batch_size : Số lượng prompt.

**Trả về:**

tensor `(batch * num_waveforms_per_prompt, output_dim)`.

Nhúng giá trị thời lượng vào vector điều kiện toàn cục.

#### encode_prompt[[diffusers.StableAudio3InpaintPipeline.encode_prompt]]

```python
encode_prompt(prompt: typing.Union[str, typing.List[str], NoneType], device: device, num_waveforms_per_prompt: int, prompt_embeds: typing.Optional[torch.Tensor] = None, encoder_attention_mask: typing.Optional[torch.LongTensor] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3_inpaint.py#L223)

**Tham số:**

prompt : Text prompt hoặc danh sách các prompt. Bỏ qua khi `prompt_embeds` được cung cấp.

device : Thiết bị đích.

num_waveforms_per_prompt : Số lượng dạng sóng đầu ra cần tạo cho mỗi prompt; các tensor điều kiện sẽ được nhân bản (tile) tương ứng.

prompt_embeds : Nhúng văn bản đã tính trước `(batch, seq_len, hidden_size)`.

encoder_attention_mask : Mặt nạ Boolean `(batch, seq_len)` cho các embedding đã tính trước; `1` = token thực, `0` = pad.

**Trả về:**

`(prompt_embeds, encoder_attention_mask)` đều được nhân rộng (tiled) thành `batch * num_waveforms_per_prompt`.

Mã hóa các prompt văn bản thành các tensor điều kiện cho cross-attention.

#### prepare_cross_attention[[diffusers.StableAudio3InpaintPipeline.prepare_cross_attention]]

```python
prepare_cross_attention(prompt_embeds: Tensor, encoder_attention_mask: Tensor, global_hidden_states: Tensor)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3_inpaint.py#L315)

**Trả về:**

`(context, context_mask)` có hình dạng `(batch, T_text + 1, dim)` và `(batch, T_text + 1)`.

Xây dựng ngữ cảnh cross-attention bằng cách thêm embedding thời lượng vào như một token bổ sung.

SA3 định tuyến conditioner `seconds_total` đến *cả* đầu vào toàn cục (AdaLN) lẫn ngữ cảnh cross-attention (`cross_attention_cond_ids = ["prompt", "seconds_total"]`). Embedding thời lượng được nối sau các text token, và attention mask được mở rộng thêm một mục hợp lệ.

## StableAudio3AudioToAudioPipeline[[diffusers.StableAudio3AudioToAudioPipeline]]

Tạo ra một biến thể của đoạn âm thanh tham chiếu: toàn bộ đoạn tham chiếu được thêm nhiễu đến mức `init_noise_level` và sau đó được khử nhiễu từ đó, khác với điều kiện cộng cục bộ theo từng khung hình của [StableAudio3InpaintPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_audio_3#diffusers.StableAudio3InpaintPipeline) vốn giữ nguyên chính xác các khung hình cụ thể.

#### diffusers.StableAudio3AudioToAudioPipeline[[diffusers.StableAudio3AudioToAudioPipeline]]

```python
diffusers.StableAudio3AudioToAudioPipeline(vae: AutoencoderSAME, text_encoder: T5GemmaEncoderModel, tokenizer: GemmaTokenizer, duration_embedder: StableAudio3DurationEmbedder, transformer: StableAudio3DiTModel, scheduler: FlowMatchEulerDiscreteScheduler)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3_audio2audio.py#L154)

**Tham số:**

vae ([*AutoencoderSAME*]) : autoencoder SAME được sử dụng để mã hóa và giải mã các ẩn âm thanh.

text_encoder ([*~transformers.T5GemmaEncoderModel*]) : Bộ mã hóa văn bản T5Gemma được đóng băng (`google/t5gemma-b-b-ul2`).

tokenizer ([*~transformers.GemmaTokenizerFast*]) : Tokenizer cho text encoder.

duration_embedder ([*StableAudio3DurationEmbedder*]) : Ánh xạ `duration` tính bằng giây thành một vector điều kiện toàn cục cho AdaLN trong mỗi khối DiT.

transformer ([*StableAudio3DiTModel*]) : DiT dự đoán vận tốc rectified-flow.

scheduler ([*FlowMatchEulerDiscreteScheduler*]) : Scheduler cho vòng lặp khử nhiễu lặp lại. Checkpoint SA3 Medium (distilled) dùng trong production sử dụng *stochastic_sampling=True* cho đúng 8 bước ping-pong; checkpoint base không distilled sử dụng *stochastic_sampling=False* cho ~100 bước Euler tất định.

Pipeline biến thể audio-to-audio cho Stable Audio 3.

Chia sẻ logic text-to-audio với [*StableAudio3Pipeline*] (được đồng bộ thông qua *# Copied from*). Mã hóa âm thanh tham chiếu bằng bộ mã hóa SAME đã đóng băng, trộn nó với nhiễu mới theo `init_noise_level`, và khử nhiễu từ đó — toàn bộ tín hiệu được thêm nhiễu/khử nhiễu trên phạm vi toàn cục, khác với điều kiện cục bộ cộng theo từng khung hình của [*StableAudio3InpaintPipeline*].

Mở rộng chữ ký gọi (xem `__call__`): audio (*torch.Tensor* có hình dạng `(batch, channels, samples)`): Dạng sóng âm thanh tham chiếu ở tần số lấy mẫu `vae.config.sampling_rate` Hz. init_noise_level (*float*): Mức độ nhiễu trộn vào tham chiếu trước khi khử nhiễu. `1.0` = nhiễu hoàn toàn (tương đương với text-to-audio); các giá trị thấp hơn sẽ giữ lại nhiều hơn của tham chiếu.

#### __call__[[diffusers.StableAudio3AudioToAudioPipeline.__call__]]

```python
__call__(prompt: typing.Union[str, typing.List[str], NoneType] = None, duration: float = 10.0, audio: typing.Optional[torch.Tensor] = None, init_noise_level: float = 1.0, num_inference_steps: typing.Optional[int] = None, logsnr_min: float = -6.2, logsnr_max: float = 2.0, silence_padding_duration: float = 0.0, num_waveforms_per_prompt: int = 1, generator: typing.Union[torch.Generator, typing.List[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, encoder_attention_mask: typing.Optional[torch.LongTensor] = None, return_dict: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], dict]] = None, callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'], output_type: str = 'pt')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3_audio2audio.py#L424)

**Tham số:**

prompt (*str* hoặc *list[str]*, *tùy chọn*) : Prompt văn bản.

duration (*float*, mặc định là 10.0) : Thời lượng đầu ra tính bằng giây. Cần khớp với âm thanh tham chiếu.

audio (*torch.Tensor*, *optional*) : Dạng sóng tham chiếu `(batch, channels, samples)` ở tần số lấy mẫu `vae.config.sampling_rate` Hz. Bắt buộc.

init_noise_level (*float*, mặc định là 1.0) : Mức độ nhiễu (trong `(0, 1]`) được trộn vào tham chiếu trước khi khử nhiễu: `x_start = (1 - init_noise_level) * reference_latents + init_noise_level * noise`. `1.0` loại bỏ hoàn toàn tham chiếu (tương đương với [*StableAudio3Pipeline*]); các giá trị thấp hơn giữ lại ngày càng nhiều cấu trúc của tham chiếu trong khi vẫn thực hiện đầy đủ số bước.

num_inference_steps (*int*, *optional*) : Số bước khử nhiễu. Khi `None` (mặc định), số bước được chọn từ cấu hình *stochastic_sampling* của trình lập lịch, khớp với [*StableAudio3Pipeline*].

logsnr_min (*float*, mặc định là -6.2) : Giá trị log-SNR tối thiểu cho lịch trình nhiễu — tương ứng với điểm bắt đầu có nhiễu cao của lịch trình.

logsnr_max (*float*, mặc định là 2.0) : Giá trị log-SNR tối đa cho lịch trình nhiễu — tương ứng với đầu có mức nhiễu thấp của lịch trình.

silence_padding_duration (*float*, mặc định là 0.0) : Khoảng trống tiềm ẩn bổ sung sau nội dung đích.

num_waveforms_per_prompt (*int*, mặc định là 1) : Số lượng waveform cho mỗi prompt.

generator : RNG để đảm bảo khả năng tái lập.

latents : Nhiễu khởi tạo đã tạo sẵn (`None` → lấy mẫu mới).

prompt_embeds : Nhúng văn bản đã tính trước.

encoder_attention_mask : Mặt nạ cho các embedding đã tính toán trước.

return_dict (*bool*, mặc định là *True*) : Trả về *AudioPipelineOutput* hoặc tuple.

callback_on_step_end (*Callable*, *tùy chọn*) : Được gọi vào cuối mỗi bước khử nhiễu với *(self, step_idx, timestep, callback_kwargs)*. Phải trả về một dict chứa các tensor (có thể đã được sửa đổi) để sử dụng cho phần còn lại của vòng lặp.

callback_on_step_end_tensor_inputs (*list[str]*, mặc định là *["latents"]*) : Các tensor được truyền vào *callback_on_step_end*. Phải là một tập con của *self._callback_tensor_inputs*.

output_type (*str*, mặc định là `"pt"`) : `"pt"` / `"np"` / `"latent"`.

**Trả về:**

[*~pipelines.AudioPipelineOutput*] với `.audios`.

Tạo một biến thể âm thanh có điều kiện dựa trên một prompt văn bản và một dạng sóng tham chiếu.

Ví dụ:
```py
>>> import torch
>>> import soundfile as sf
>>> import torchaudio
>>> from diffusers import StableAudio3AudioToAudioPipeline

>>> pipe = StableAudio3AudioToAudioPipeline.from_pretrained(
...     "stabilityai/stable-audio-3-medium", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> audio, sr = torchaudio.load("reference.wav")
>>> audio = torchaudio.functional.resample(audio, sr, pipe.vae.config.sampling_rate).unsqueeze(0).to("cuda")

>>> generator = torch.Generator("cuda").manual_seed(0)
>>> audio = pipe(
...     "A gentle piano melody with soft strings in a concert hall",
...     duration=10.0,
...     audio=audio,
...     init_noise_level=0.6,
...     generator=generator,
... ).audios

>>> sf.write("output.wav", audio[0].T.cpu().float().numpy(), samplerate=pipe.vae.config.sampling_rate)
```

#### encode_duration[[diffusers.StableAudio3AudioToAudioPipeline.encode_duration]]

```python
encode_duration(duration: float, device: device, num_waveforms_per_prompt: int, batch_size: int)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3_audio2audio.py#L287)

**Tham số:**

duration : Thời lượng tính bằng giây, được áp dụng cho mọi mẫu trong lô.

device : Thiết bị đích.

num_waveforms_per_prompt : Hệ số lát.

batch_size : Số lượng prompt.

**Trả về:**

tensor `(batch * num_waveforms_per_prompt, output_dim)`.

Nhúng giá trị thời lượng vào vector điều kiện toàn cục.

#### encode_prompt[[diffusers.StableAudio3AudioToAudioPipeline.encode_prompt]]

```python
encode_prompt(prompt: typing.Union[str, typing.List[str], NoneType], device: device, num_waveforms_per_prompt: int, prompt_embeds: typing.Optional[torch.Tensor] = None, encoder_attention_mask: typing.Optional[torch.LongTensor] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3_audio2audio.py#L220)

**Tham số:**

prompt : Text prompt hoặc danh sách các prompt. Bỏ qua khi `prompt_embeds` được cung cấp.

device : Thiết bị đích.

num_waveforms_per_prompt : Số lượng dạng sóng đầu ra cần tạo cho mỗi prompt; các tensor điều kiện sẽ được nhân bản (tile) tương ứng.

prompt_embeds : Nhúng văn bản đã tính trước `(batch, seq_len, hidden_size)`.

encoder_attention_mask : Mặt nạ Boolean `(batch, seq_len)` cho các embedding đã tính trước; `1` = token thực, `0` = pad.

**Trả về:**

`(prompt_embeds, encoder_attention_mask)` đều được nhân rộng (tiled) thành `batch * num_waveforms_per_prompt`.

Mã hóa các prompt văn bản thành các tensor điều kiện cho cross-attention.

#### prepare_cross_attention[[diffusers.StableAudio3AudioToAudioPipeline.prepare_cross_attention]]

```python
prepare_cross_attention(prompt_embeds: Tensor, encoder_attention_mask: Tensor, global_hidden_states: Tensor)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_audio_3/pipeline_stable_audio_3_audio2audio.py#L312)

**Trả về:**

`(context, context_mask)` có hình dạng `(batch, T_text + 1, dim)` và `(batch, T_text + 1)`.

Xây dựng ngữ cảnh cross-attention bằng cách thêm embedding thời lượng vào như một token bổ sung.

SA3 định tuyến conditioner `seconds_total` đến *cả* đầu vào toàn cục (AdaLN) lẫn ngữ cảnh cross-attention (`cross_attention_cond_ids = ["prompt", "seconds_total"]`). Embedding thời lượng được nối sau các text token, và attention mask được mở rộng thêm một mục hợp lệ.

## StableAudio3DurationEmbedder[[diffusers.StableAudio3DurationEmbedder]]

#### diffusers.StableAudio3DurationEmbedder[[diffusers.StableAudio3DurationEmbedder]]

```python
diffusers.StableAudio3DurationEmbedder(output_dim: int = 768, fourier_dim: int = 256, min_val: float = 0.0, max_val: float = 384.0, min_freq: float = 0.5, max_freq: float = 10000.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/condition_embedders/condition_embedder_stable_audio_3.py#L43)

**Tham số:**

output_dim (*int*, mặc định là 768) : Kích thước của embedding đầu ra. Phải khớp với `global_cond_dim` của DiT.

fourier_dim (*int*, mặc định là 256) : Kích thước đặc trưng Fourier nội bộ (phải là số chẵn).

min_val (*float*, mặc định là 0.0) : Giá trị thời lượng tối thiểu cho việc kẹp chuẩn hóa.

max_val (*float*, mặc định là 384.0) : Giá trị thời lượng tối đa cho việc kẹp chuẩn hóa. Các giá trị lớn hơn giá trị này sẽ bị kẹp. 384 giây là giới hạn trên của SA3 Medium trong môi trường sản xuất cho bộ điều kiện `seconds_total`.

min_freq (*float*, mặc định là 0.5) : Tần số tối thiểu cho cơ sở Fourier mũ.

max_freq (*float*, mặc định là 10000.0) : Tần số tối đa cho cơ sở Fourier mũ.

Nhúng giá trị thời lượng (tính bằng giây) vào vector điều kiện toàn cục cho Stable Audio 3 DiT (được dùng làm đầu vào AdaLN của `global_hidden_states`).

Nhân bản `NumberConditioner(fourier_features_type="expo")` từ bản triển khai tham chiếu SA3.

#### forward[[diffusers.StableAudio3DurationEmbedder.forward]]

```python
forward(seconds: Tensor)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/condition_embedders/condition_embedder_stable_audio_3.py#L90)

**Tham số:**

seconds (`torch.Tensor` có hình dạng `(batch,)`) : Giá trị thời lượng tính bằng giây.

**Trả về:**

`torch.Tensor` có hình dạng `(batch, output_dim)` — các embedding thời lượng.

