Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/diffusers/pipelines/audioldm2/pipeline_audioldm2.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,19 @@ def prepare_inputs_for_generation(
# only last token for inputs_embeds if past is defined in kwargs
inputs_embeds = inputs_embeds[:, -1:]

position_ids = kwargs.get("position_ids", None)
if attention_mask is not None and position_ids is None:
# create position_ids on the fly for batch generation
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
if past_key_values is not None:
position_ids = position_ids[:, -inputs_embeds.shape[1] :]

return {
"inputs_embeds": inputs_embeds,
"attention_mask": attention_mask,
"past_key_values": past_key_values,
"position_ids": position_ids,
"use_cache": kwargs.get("use_cache"),
}

Expand Down
68 changes: 68 additions & 0 deletions tests/pipelines/audioldm2/test_audioldm2.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
LMSDiscreteScheduler,
PNDMScheduler,
)
from diffusers.pipelines.audioldm2.pipeline_audioldm2 import prepare_inputs_for_generation
from diffusers.utils import is_transformers_version

from ...testing_utils import (
Expand Down Expand Up @@ -461,6 +462,73 @@ def test_to_dtype(self):
def test_encode_prompt_works_in_isolation(self):
pass

def test_prepare_inputs_for_generation_position_ids(self):
embeds = torch.zeros(2, 6, 8)
attention_mask = torch.tensor([[1, 1, 1, 0, 0, 1], [1, 1, 1, 1, 1, 1]])

model_inputs = prepare_inputs_for_generation(embeds, attention_mask=attention_mask, past_key_values=None)
assert torch.equal(model_inputs["inputs_embeds"], embeds)
assert torch.equal(
model_inputs["position_ids"],
torch.tensor([[0, 1, 2, 1, 1, 3], [0, 1, 2, 3, 4, 5]]),
)

extended_embeds = torch.zeros(2, 7, 8)
extended_mask = torch.cat([attention_mask, torch.ones(2, 1, dtype=torch.long)], dim=1)
cached_inputs = prepare_inputs_for_generation(
extended_embeds, attention_mask=extended_mask, past_key_values=(torch.zeros(1),)
)
assert cached_inputs["inputs_embeds"].shape == (2, 1, 8)
assert torch.equal(cached_inputs["position_ids"], torch.tensor([[4], [6]]))

no_mask_inputs = prepare_inputs_for_generation(embeds, attention_mask=None)
assert no_mask_inputs["position_ids"] is None

explicit_positions = torch.arange(6).unsqueeze(0).expand(2, -1)
explicit_inputs = prepare_inputs_for_generation(
embeds, attention_mask=attention_mask, position_ids=explicit_positions
)
assert torch.equal(explicit_inputs["position_ids"], explicit_positions)

def test_generate_language_model_batched_matches_single(self):
torch.manual_seed(0)
config = GPT2Config(
n_embd=32,
n_layer=2,
n_head=4,
n_positions=64,
vocab_size=10,
bos_token_id=0,
eos_token_id=0,
)
pipe = object.__new__(AudioLDM2Pipeline)
pipe.__dict__["language_model"] = GPT2LMHeadModel(config).to(torch_device).eval()

head = torch.randn(1, 4, 32, device=torch_device)
t5 = torch.randn(1, 3, 32, device=torch_device)
eos_1 = torch.randn(1, 1, 32, device=torch_device)

single = torch.cat([head, t5, eos_1], dim=1)
padded = torch.cat([head, t5, torch.zeros(1, 2, 32, device=torch_device), eos_1], dim=1)
batch = torch.cat([padded, torch.randn(1, 10, 32, device=torch_device)], dim=0)
batch_mask = torch.tensor([[1] * 7 + [0, 0] + [1], [1] * 10], dtype=torch.long, device=torch_device)
single_mask = torch.ones(1, 8, dtype=torch.long, device=torch_device)

with torch.no_grad():
ref = pipe.generate_language_model(single, attention_mask=single_mask, max_new_tokens=8)
batched = pipe.generate_language_model(batch, attention_mask=batch_mask, max_new_tokens=8)
unmasked = pipe.generate_language_model(single[:, :4], attention_mask=None, max_new_tokens=4)
ones_masked = pipe.generate_language_model(
single[:, :4],
attention_mask=torch.ones(1, 4, dtype=torch.long, device=torch_device),
max_new_tokens=4,
)

assert_tensors_close(
batched[:1], ref, atol=1e-5, msg="Batched prompt with middle padding diverged from single."
)
assert_tensors_close(unmasked, ones_masked, atol=1e-5, msg="attention_mask=None diverged from all-ones mask.")


class TestAudioLDM2PipelineMemory(AudioLDM2PipelineTesterConfig, MemoryTesterMixin):
"""Memory optimization tests (CPU offload, group offload, layerwise casting) for the AudioLDM2 pipeline."""
Expand Down