Spaces:
Running
on
Zero
Running
on
Zero
File size: 10,215 Bytes
426874e 32d3fde 426874e 32d3fde 426874e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
"""Module contains the audio and text processor for NatureLM-audio inference and evaluation"""
import json
import os
from dataclasses import dataclass, field
import numpy as np
import resampy
import librosa
import torch
@dataclass
class NatureLMAudioProcessor:
"""Preprocess samples to make them ready for NatureLM-audio inference.
Arguments
---------
naturelm_sample_rate : int
The sample rate of the NatureLM model
max_length_seconds : int
The maximum length of audio in seconds
audio_token_placeholder : str
The placeholder for the audio token in the instruction
prompt_template : str
The template for the prompt. The instruction or query from the user is inserted in the placeholder at {prompt}
Examples
--------
>>> processor = NatureLMAudioProcessor()
>>> audios = [np.random.rand(32000), np.random.rand(32000)]
>>> instructions = ["What is the weather today?", "What is the time now?"]
>>> input_sample_rates = [32000, 32000]
>>> audios, instructions = processor(audios, instructions, input_sample_rates)
>>> audios.shape == (2, 160000)
True
>>> "<Audio><AudioHere></Audio> " in instructions[0]
True
>>> "<|start_header_id|>user<|end_header_id|>" in instructions[0]
True
"""
sample_rate: int = 16000
max_length_seconds: int = 10
audio_token_placeholder: str = "<Audio><AudioHere></Audio> "
prompt_template: str = "<|start_header_id|>user<|end_header_id|>\n\n{prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
def prepare_audio(self, audio: list[float] | np.ndarray | os.PathLike, input_sr: int = None) -> torch.Tensor:
"""Prepare an audio array or file path for inference"""
if isinstance(audio, str | os.PathLike):
audio, sr = librosa.load(audio, sr=None, mono=False)
input_sr = sr
elif isinstance(audio, list):
audio = np.array(audio)
assert isinstance(audio, np.ndarray), "Audio not a numpy array"
# Convert stereo to mono
if len(audio.shape) == 2:
# find the smaller axis as channel dim to avg over (like (2, T) or (T, 2), 2 = channel dim
axis_to_average = int(np.argmin(audio.shape))
audio = audio.mean(axis=axis_to_average)
# Resample
if input_sr is not None and input_sr != self.sample_rate:
# audio = torchaudio.functional.resample(
# torch.from_numpy(audio), orig_freq=input_sr, new_freq=self.sample_rate
# )
audio = resampy.resample(audio, input_sr, self.sample_rate)
audio = torch.from_numpy(audio.squeeze())
else:
audio = torch.from_numpy(audio)
# Truncate audio to at most max_length_seconds
audio = audio[: self.sample_rate * self.max_length_seconds]
# Pad to max_length_seconds if short
if len(audio) < self.sample_rate * self.max_length_seconds:
pad_size = self.sample_rate * self.max_length_seconds - len(audio)
audio = torch.nn.functional.pad(audio, (0, pad_size))
# Clamp
audio = torch.clamp(audio, -1.0, 1.0)
return audio.squeeze()
def prepare_instruction(self, instruction: str) -> str:
"""Add the audio token placeholder to the instruction and format it
according to the llama tokenizer.
"""
if self.audio_token_placeholder not in instruction:
instruction = self.audio_token_placeholder + instruction
instruction = self.prompt_template.format(prompt=instruction.strip())
return instruction
def __call__(
self,
audios: list[list[float] | np.ndarray] | list[str | os.PathLike],
instructions: list[str],
input_sample_rates: list[int],
) -> tuple[torch.Tensor, list[str]]:
"""Prepare audios and instructions for inference
Arguments
---------
audios : list[list[float] | np.ndarray] | list[str | os.PathLike]
The audio samples or file paths
instructions : list[str]
The instructions or queries
input_sample_rates : list[int]
The sample rates of the input audio samples
Returns
-------
tuple[torch.Tensor, list[str]]
The prepared audios and instructions
"""
audios = torch.stack(
[self.prepare_audio(audio, input_sr) for audio, input_sr in zip(audios, input_sample_rates)]
)
instructions = [self.prepare_instruction(instruction) for instruction in instructions]
return audios, instructions
@dataclass
class NatureLMAudioEvalProcessor(NatureLMAudioProcessor):
"""Preprocess samples to make them ready for NatureLM-audio evaluation on BEANS-Zero dataset.
This requires a few additional parameters compared to the NatureLMAudioProcessor.
Arguments
---------
naturelm_sample_rate : int
The sample rate of the NatureLM model
max_length_seconds : int
The maximum length of audio in seconds
audio_token_placeholder : str
The placeholder for the audio token in the instruction
prompt_template : str
The template for the prompt. The instruction or query from the user is inserted in the placeholder at {prompt}
dataset_name : list[str]
The name of the dataset being processed
true_labels : list[str]
The true labels or expected outputs for the samples.
task: str
The task for the dataset. Can be 'detection', 'captioning', or 'classification'
threshold_too_many_detection_labels : int
The threshold for the number of labels in the dataset to switch to a detection prompt. Default is 8.
Examples
--------
>>> processor = NatureLMAudioEvalProcessor(task="detection", true_labels=["dog", "cat", "bird", "None", "mouse", "elephant", "lion", "tiger", "bear"])
>>> audios = [np.random.rand(32000), np.random.rand(32000)]
>>> instructions = ["What is the weather today?", "What is the time now?"]
>>> input_sample_rates = [32000, 32000]
>>> audios, instructions = processor(audios, instructions, input_sample_rates)
>>> audios.shape == (2, 160000)
True
>>> "<Audio><AudioHere></Audio> " in instructions[0]
True
>>> "<|start_header_id|>user<|end_header_id|>" in instructions[0]
True
>>> "What are the common names" in instructions[0]
True
"""
dataset_name: str = "beans-zero"
true_labels: list[str] = field(default_factory=lambda _: [])
task: str = "detection"
threshold_too_many_detection_labels: int = 8
def __post_init__(self):
self.detection_prompt: str = (
"<Audio><AudioHere></Audio> What are the common names for the species in the audio, if any?"
)
# find the unique labels in the dataset
self.dataset_labels = set(self.true_labels)
if self.task == "detection":
self.dataset_labels.add("None")
if self.task == "captioning":
self.dataset_labels = set()
def prepare_instruction(self, instruction: str) -> str:
"""Add the audio token placeholder to the instruction and format it"""
if self.task == "detection" and len(self.dataset_labels) > self.threshold_too_many_detection_labels:
instruction = self.detection_prompt
if self.audio_token_placeholder not in instruction:
instruction = self.audio_token_placeholder + instruction
instruction = self.prompt_template.format(prompt=instruction.strip())
return instruction
class NatureLMInferenceDataset(torch.utils.data.Dataset):
"""A pytorch dataset for batched inference with NatureLM-audio
TODO: currently, if the batch contains very different prompts the model doesnt work well.
Arguments
---------
ds : datasets.Dataset
The huggingface dataset containing the samples
Examples
--------
TODO: Add examples
"""
def __init__(self, ds, processor):
self.ds = ds
self.processor = processor
def __getitem__(self, idx):
sample = self.ds[idx]
input_sample_rate = json.loads(sample["metadata"])["sample_rate"]
audio_tensor = self.processor.prepare_audio(sample["audio"], input_sample_rate)
instruction = self.processor.prepare_instruction(sample["instruction"])
return {
"raw_wav": audio_tensor,
"text": "",
"task": sample["task"],
"audio_chunk_sizes": len(audio_tensor),
"index": idx,
"id": sample["id"],
"prompt": instruction,
"label": sample["output"],
}
def __len__(self):
return len(self.ds)
def collater(samples: list[dict]) -> dict:
"""Collate samples into a batch.
Samples is a list of dictionaries, each containing the following keys:
- raw_wav: a list of tensors containing the raw audio waveform
- text: a list of strings containing the text
- task: a list of strings containing the task
- id: a list of strings containing the id
- prompt: a list of strings containing the prompt
- index: a list of integers containing the index
- audio_chunk_sizes: a list of integers containing the size of each audio chunk
The indiviudal audio waveforms will be stacked along the batch dimension for easier
processing in the audio model. To keep which audio belongs to which sample, we add
the audio_chunk_sizes key to the batch dictionary.
"""
raw_wav = torch.stack([s["raw_wav"] for s in samples])
paddding_mask = torch.zeros_like(raw_wav).to(torch.bool)
text = [s["text"] for s in samples]
prompt = [s["prompt"] for s in samples]
task = [s["task"] for s in samples]
id = [s["id"] for s in samples]
index = [s["index"] for s in samples]
label = [s["label"] for s in samples]
return {
"raw_wav": raw_wav,
"padding_mask": paddding_mask,
"text": text,
"task": task,
"id": id,
"prompt": prompt,
"index": index,
"audio_chunk_sizes": 1,
"label": label,
}
|