Transformers documentation
Parakeet
Mô hình này đã được đóng góp cho Hugging Face Transformers vào ngày 2025-09-25.
Parakeet
Tổng quan
Các mô hình Parakeet, được giới thiệu bởi NVIDIA NeMo, là các mô hình kết hợp bộ mã hóa Fast Conformer với bộ giải mã phân loại thời gian kết nối (CTC), transducer mạng nơ-ron hồi quy (RNNT) hoặc transducer token và thời lượng (TDT) cho nhận dạng giọng nói tự động.
Kiến trúc Mô hình
- Fast Conformer Encoder: Kiến trúc Conformer có khả năng mở rộng tuyến tính, xử lý các đặc trưng mel-spectrogram và giảm độ dài chuỗi thông qua hạ mẫu. Đây là phiên bản hiệu quả hơn của Conformer Encoder có trong FastSpeech2Conformer (xem ParakeetEncoder để biết chi tiết về cài đặt và thông tin của encoder).
- ParakeetForCTC: một Fast Conformer Encoder + một bộ giải mã CTC
- CTC Decoder: Bộ giải mã đơn giản nhưng hiệu quả, bao gồm:
- Chiếu tích chập 1 chiều từ kích thước ẩn của bộ mã hóa sang kích thước từ vựng (để tương thích tối ưu với NeMo).
- Tính toán tổn thất CTC cho huấn luyện.
- Giải mã CTC tham lam cho suy luận.
- CTC Decoder: Bộ giải mã đơn giản nhưng hiệu quả, bao gồm:
- ParakeetForRNNT: một Fast Conformer Encoder + một decoder RNN-T (RNN Transducer)
- RNN-T Decoder: Transducer thần kinh tiêu chuẩn:
- Mạng dự đoán LSTM duy trì ngữ cảnh ngôn ngữ xuyên suốt các dự đoán token.
- Mạng kết hợp (Joint network) kết hợp đầu ra của bộ mã hóa và bộ giải mã.
- Giải mã transducer tham lam cho suy luận: một phát xạ blank (trống) sẽ tiến bộ mã hóa (encoder) lên một khung, trong khi một phát xạ không-blank sẽ giữ nguyên ở cùng một khung.
- RNN-T Decoder: Transducer thần kinh tiêu chuẩn:
- ParakeetForTDT: một Fast Conformer Encoder + một TDT (Token Duration Transducer) decoder
- TDT Decoder: Dự đoán đồng thời các token và thời lượng của chúng, cho phép giải mã hiệu quả:
- Mạng dự đoán LSTM duy trì ngữ cảnh ngôn ngữ xuyên suốt các dự đoán token.
- Mạng kết hợp (Joint network) kết hợp đầu ra của bộ mã hóa và bộ giải mã.
- Duration head dự đoán số khung hình cần bỏ qua, cho phép suy luận nhanh.
- TDT Decoder: Dự đoán đồng thời các token và thời lượng của chúng, cho phép giải mã hiệu quả:
Bản triển khai gốc có thể được tìm thấy trong NVIDIA NeMo. Các checkpoint của mô hình có thể được tìm thấy dưới tổ chức NVIDIA.
Mô hình này được đóng góp bởi Nithin Rao Koluguri, Eustache Le Bihan, Eric Bezzam, Maksym Lypivskyi và Hainan Xu.
Cách sử dụng
Cách sử dụng ParakeetForCTC
from transformers import pipeline
pipe = pipeline("automatic-speech-recognition", model="nvidia/parakeet-ctc-1.1b")
out = pipe("https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3")
print(out)
# {'text': 'yesterday it was thirty five degrees in barcelona but today the temperature will go down to minus twenty degrees'}from datasets import Audio, load_dataset
from transformers import AutoModelForCTC, AutoProcessor
model_id = "nvidia/parakeet-ctc-1.1b"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForCTC.from_pretrained(model_id, device_map="auto")
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el['array'] for el in ds["audio"][:5]]
inputs = processor(speech_samples, sampling_rate=processor.feature_extractor.sampling_rate)
inputs.to(model.device, dtype=model.dtype)
outputs = model.generate(**inputs)
print(processor.decode(outputs))Cách sử dụng ParakeetForRNNT
Parakeet RNN-T chuyển văn bản thành chữ mà không phân biệt hoa thường hay dấu câu (giống CTC), và mô hình cũng có thể thực hiện gắn mốc thời gian cho từng token.
from transformers import pipeline
pipe = pipeline("automatic-speech-recognition", model="nvidia/parakeet-rnnt-0.6b", revision="refs/pr/4")
out = pipe("https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3")
print(out)
# {'text': 'yesterday it was thirty five degrees in barcelona but today the temperature will go down to minus twenty degrees'}from transformers import AutoModelForRNNT, AutoProcessor
from datasets import load_dataset, Audio
model_id = "nvidia/parakeet-rnnt-0.6b"
revision = "refs/pr/4"
processor = AutoProcessor.from_pretrained(model_id, revision=revision)
model = AutoModelForRNNT.from_pretrained(model_id, revision=revision, device_map="auto")
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el['array'] for el in ds["audio"][:5]]
inputs = processor(speech_samples, sampling_rate=processor.feature_extractor.sampling_rate)
inputs.to(model.device, dtype=model.dtype)
output = model.generate(**inputs, return_dict_in_generate=True)
print(processor.decode(output.sequences, skip_special_tokens=True))Khác với TDT (dự đoán thời lượng cho từng token), mỗi token RNN-T được phát ra tại một khung encoder duy nhất, do đó khoảng thời gian bắt đầu và kết thúc của nó chính xác bằng một khung.
from datasets import Audio, load_dataset
from transformers import AutoModelForRNNT, AutoProcessor
model_id = "nvidia/parakeet-rnnt-0.6b"
revision = "refs/pr/4"
processor = AutoProcessor.from_pretrained(model_id, revision=revision)
model = AutoModelForRNNT.from_pretrained(model_id, revision=revision, device_map="auto")
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el['array'] for el in ds["audio"][:1]]
inputs = processor(speech_samples, sampling_rate=processor.feature_extractor.sampling_rate)
inputs.to(model.device, dtype=model.dtype)
output = model.generate(**inputs, return_dict_in_generate=True)
decoded_output, decoded_timestamps = processor.decode(
output.sequences,
durations=output.durations,
skip_special_tokens=True,
)
print("Transcription:", decoded_output)
print("\nTimestamped tokens:", decoded_timestamps)
"""
Transcription: ['mister quilter is the apostle of the middle classes and we are glad to welcome his gospel']
Timestamped tokens: [[{'token': 'm', 'start': 0.4, 'end': 0.48}, {'token': 'is', 'start': 0.56, 'end': 0.64}, {'token': 'ter', 'start': 0.56, 'end': 0.64}, {'token': ' qu', 'start': 0.72, 'end': 0.8}, {'token': 'il', 'start': 0.96, 'end': 1.04}, {'token': 'ter', 'start': 1.12, 'end': 1.2}, {'token': ' is', 'start': 1.36, 'end': 1.44}, {'token': ' the', 'start': 1.52, 'end': 1.6}, {'token': ' ap', 'start': 1.68, 'end': 1.76}, {'token': 'o', 'start': 1.76, 'end': 1.84}, {'token': 'st', 'start': 1.84, 'end': 1.92}, {'token': 'le', 'start': 2.0, 'end': 2.08}, {'token': ' of', 'start': 2.16, 'end': 2.24}, {'token': ' the', 'start': 2.24, 'end': 2.32}, {'token': ' m', 'start': 2.4, 'end': 2.48}, {'token': 'id', 'start': 2.48, 'end': 2.56}, {'token': 'd', 'start': 2.56, 'end': 2.64}, {'token': 'le', 'start': 2.56, 'end': 2.64}, {'token': ' cl', 'start': 2.8, 'end': 2.88}, {'token': 'ass', 'start': 2.88, 'end': 2.96}, {'token': 'es', 'start': 3.12, 'end': 3.2}, {'token': ' and', 'start': 3.28, 'end': 3.36}, {'token': ' we', 'start': 3.44, 'end': 3.52}, {'token': ' are', 'start': 3.6, 'end': 3.68}, {'token': ' gl', 'start': 3.84, 'end': 3.92}, {'token': 'ad', 'start': 3.92, 'end': 4.0}, {'token': ' to', 'start': 4.08, 'end': 4.16}, {'token': ' we', 'start': 4.24, 'end': 4.32}, {'token': 'l', 'start': 4.32, 'end': 4.4}, {'token': 'c', 'start': 4.4, 'end': 4.48}, {'token': 'ome', 'start': 4.48, 'end': 4.56}, {'token': ' his', 'start': 4.72, 'end': 4.8}, {'token': ' go', 'start': 4.96, 'end': 5.04}, {'token': 's', 'start': 5.04, 'end': 5.12}, {'token': 'pe', 'start': 5.2, 'end': 5.28}, {'token': 'l', 'start': 5.36, 'end': 5.44}]]
"""Cách sử dụng ParakeetForTDT
Bản ghi Parakeet TDT bao gồm chữ hoa chữ thường, và mô hình cũng có thể thực hiện đánh dấu thời gian cho từng token.
from transformers import pipeline
pipe = pipeline("automatic-speech-recognition", model="nvidia/parakeet-tdt-0.6b-v3")
out = pipe("https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3")
print(out)
# {'text': 'Yesterday it was 35 degrees in Barcelona, but today the temperature will go down to minus 20 degrees.'}from transformers import AutoModelForTDT, AutoProcessor
from datasets import load_dataset, Audio
model_id = "nvidia/parakeet-tdt-0.6b-v3"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForTDT.from_pretrained(model_id, device_map="auto")
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el['array'] for el in ds["audio"][:5]]
inputs = processor(speech_samples, sampling_rate=processor.feature_extractor.sampling_rate)
inputs.to(model.device, dtype=model.dtype)
output = model.generate(**inputs, return_dict_in_generate=True)
print(processor.decode(output.sequences, skip_special_tokens=True))from datasets import Audio, load_dataset
from transformers import AutoModelForTDT, AutoProcessor
model_id = "nvidia/parakeet-tdt-0.6b-v3"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForTDT.from_pretrained(model_id, device_map="auto")
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el['array'] for el in ds["audio"][:1]]
inputs = processor(speech_samples, sampling_rate=processor.feature_extractor.sampling_rate)
inputs.to(model.device, dtype=model.dtype)
output = model.generate(**inputs, return_dict_in_generate=True)
decoded_output, decoded_timestamps = processor.decode(
output.sequences,
durations=output.durations,
skip_special_tokens=True,
)
print("Transcription:", decoded_output)
print("\nTimestamped tokens:", decoded_timestamps)
"""
Transcription: ['mister Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.']
Timestamped tokens: [[{'token': 'm', 'start': 0.24, 'end': 0.48}, {'token': 'ister', 'start': 0.48, 'end': 0.64}, {'token': 'Qu', 'start': 0.64, 'end': 0.88}, {'token': 'il', 'start': 0.88, 'end': 1.12}, {'token': 'ter', 'start': 1.12, 'end': 1.36}, {'token': 'is', 'start': 1.36, 'end': 1.44}, {'token': 'the', 'start': 1.44, 'end': 1.6}, {'token': 'ap', 'start': 1.6, 'end': 1.76}, {'token': 'ost', 'start': 1.76, 'end': 1.92}, {'token': 'le', 'start': 2.0, 'end': 2.16}, {'token': 'of', 'start': 2.16, 'end': 2.24}, {'token': 'the', 'start': 2.24, 'end': 2.4}, {'token': 'mid', 'start': 2.4, 'end': 2.48}, {'token': 'd', 'start': 2.48, 'end': 2.56}, {'token': 'le', 'start': 2.56, 'end': 2.64}, {'token': 'clas', 'start': 2.72, 'end': 2.88}, {'token': 's', 'start': 2.88, 'end': 3.04}, {'token': 'es', 'start': 3.04, 'end': 3.12}, {'token': ',', 'start': 3.12, 'end': 3.12}, {'token': 'and', 'start': 3.2800000000000002, 'end': 3.44}, {'token': 'we', 'start': 3.44, 'end': 3.6}, {'token': 'are', 'start': 3.6, 'end': 3.7600000000000002}, {'token': 'gl', 'start': 3.7600000000000002, 'end': 3.92}, {'token': 'ad', 'start': 3.92, 'end': 4.08}, {'token': 'to', 'start': 4.08, 'end': 4.24}, {'token': 'wel', 'start': 4.24, 'end': 4.4}, {'token': 'c', 'start': 4.4, 'end': 4.48}, {'token': 'ome', 'start': 4.48, 'end': 4.72}, {'token': 'his', 'start': 4.72, 'end': 4.96}, {'token': 'gos', 'start': 4.96, 'end': 5.12}, {'token': 'pel', 'start': 5.36, 'end': 5.6000000000000005}, {'token': '.', 'start': 5.6000000000000005, 'end': 5.6000000000000005}]]
"""Đẩy Mô Hình Chạy Nhanh Hơn
Parakeet hỗ trợ biên dịch toàn bộ đồ thị với cơ chế bắt đồ thị (CUDA graphs trên GPU NVIDIA, và cơ chế tương đương trên các bộ tăng tốc khác)! Tối ưu hóa này hiệu quả nhất khi bạn biết độ dài tối đa của âm thanh cần chuyển thành văn bản. Ý tưởng chính là sử dụng hình dạng đầu vào tĩnh để tránh biên dịch lại. Ví dụ, nếu bạn biết âm thanh của mình sẽ dưới 30 giây, bạn có thể dùng processor để đệm tất cả các đầu vào lên 30 giây, chuẩn bị các đặc trưng đầu vào và attention masks nhất quán. Xem ví dụ bên dưới!
import torch
from datasets import Audio, load_dataset
from transformers import AutoModelForCTC, AutoProcessor
processor = AutoProcessor.from_pretrained("nvidia/parakeet-ctc-1.1b")
model = AutoModelForCTC.from_pretrained("nvidia/parakeet-ctc-1.1b", device_map="auto")
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el['array'] for el in ds["audio"][:5]]
# Compile the generate method with fullgraph and graph capture
model.generate = torch.compile(model.generate, fullgraph=True, mode="reduce-overhead")
# let's define processor kwargs to pad to 30 seconds
processor_kwargs = {
"padding": "max_length",
"max_length": 30 * processor.feature_extractor.sampling_rate,
}
# Define a timing context using accelerator events
class TimerContext:
def __init__(self, name="Execution"):
self.name = name
self.start_event = None
self.end_event = None
def __enter__(self):
# Use accelerator events for more accurate device timing
self.start_event = torch.Event(enable_timing=True)
self.end_event = torch.Event(enable_timing=True)
self.start_event.record()
return self
def __exit__(self, *args):
self.end_event.record()
torch.accelerator.synchronize()
elapsed_time = self.start_event.elapsed_time(self.end_event) / 1000.0
print(f"{self.name} time: {elapsed_time:.4f} seconds")
inputs = processor(speech_samples[0], **processor_kwargs)
inputs.to(model.device, dtype=model.dtype)
print("\n" + "="*50)
print("First generation - compiling...")
# Generate with the compiled model
with TimerContext("First generation"):
outputs = model.generate(**inputs)
print(processor.decode(outputs))
inputs = processor(speech_samples[1], **processor_kwargs)
inputs.to(model.device, dtype=model.dtype)
print("\n" + "="*50)
print("Second generation - recording graphs...")
with TimerContext("Second generation"):
outputs = model.generate(**inputs)
print(processor.decode(outputs))
inputs = processor(speech_samples[2], **processor_kwargs)
inputs.to(model.device, dtype=model.dtype)
print("\n" + "="*50)
print("Third generation - fast !!!")
with TimerContext("Third generation"):
outputs = model.generate(**inputs)
print(processor.decode(outputs))
inputs = processor(speech_samples[3], **processor_kwargs)
inputs.to(model.device, dtype=model.dtype)
print("\n" + "="*50)
print("Fourth generation - still fast !!!")
with TimerContext("Fourth generation"):
outputs = model.generate(**inputs)
print(processor.decode(outputs))Huấn luyện CTC
from datasets import Audio, load_dataset
from transformers import AutoModelForCTC, AutoProcessor
model_id = "nvidia/parakeet-ctc-1.1b"
NUM_SAMPLES = 5
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForCTC.from_pretrained(model_id, device_map="auto")
model.train()
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el['array'] for el in ds["audio"][:NUM_SAMPLES]]
text_samples = ds["text"][:NUM_SAMPLES]
# passing `text` to the processor will prepare inputs' `labels` key
inputs = processor(audio=speech_samples, text=text_samples, sampling_rate=processor.feature_extractor.sampling_rate)
inputs.to(model.device, dtype=model.dtype)
outputs = model(**inputs)
print("Loss:", outputs.loss.item())
outputs.loss.backward()Huấn luyện RNN-T
Việc tính toán tổn thất RNN-T yêu cầu torchaudio (
pip install torchaudio).
from datasets import Audio, load_dataset
import torch
from transformers import AutoModelForRNNT, AutoProcessor
model_id = "nvidia/parakeet-rnnt-0.6b"
revision = "refs/pr/4"
NUM_SAMPLES = 4
processor = AutoProcessor.from_pretrained(model_id, revision=revision)
model = AutoModelForRNNT.from_pretrained(model_id, revision=revision, device_map="auto")
model.train()
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el['array'] for el in ds["audio"][:NUM_SAMPLES]]
text_samples = ds["text"][:NUM_SAMPLES]
# passing `text` to the processor will prepare inputs' `labels` key
inputs = processor(audio=speech_samples, text=text_samples, sampling_rate=processor.feature_extractor.sampling_rate)
inputs.to(model.device, dtype=model.dtype)
outputs = model(**inputs)
print("Loss:", outputs.loss.item())
outputs.loss.backward()Huấn luyện TDT
from datasets import Audio, load_dataset
import torch
from transformers import AutoModelForTDT, AutoProcessor
model_id = "nvidia/parakeet-tdt-0.6b-v3"
NUM_SAMPLES = 4
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForTDT.from_pretrained(model_id, device_map="auto")
model.train()
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el['array'] for el in ds["audio"][:NUM_SAMPLES]]
text_samples = ds["text"][:NUM_SAMPLES]
# passing `text` to the processor will prepare inputs' `labels` key
inputs = processor(audio=speech_samples, text=text_samples, sampling_rate=processor.feature_extractor.sampling_rate)
inputs.to(model.device, dtype=model.dtype)
outputs = model(**inputs)
print("Loss:", outputs.loss.item())
outputs.loss.backward()ParakeetTokenizer
Kế thừa tất cả các phương thức từ PreTrainedTokenizerFast. Người dùng nên tham khảo lớp cha này để biết thêm thông tin về các phương thức đó,
ngoại trừ _decode được ghi đè để điều chỉnh cho phù hợp với giải mã CTC:
- Nhóm các token liên tiếp
- Lọc bỏ token trống
ParakeetFeatureExtractor
lớp transformers.ParakeetFeatureExtractor
< source >( feature_size = 80sampling_rate = 16000hop_length = 160n_fft = 512win_length = 400preemphasis = 0.97padding_value = 0.0**kwargs )
Tham số
- feature_size (
int, tùy chọn, mặc định là 80) — Kích thước chiều của các đặc trưng đã trích xuất. - sampling_rate (
int, tùy chọn, mặc định là 16000) — Tần số lấy mẫu (tính bằng hertz (Hz)) mà các tệp âm thanh cần được số hóa. - hop_length (
int, tùy chọn, mặc định là 160) — Chiều dài của các cửa sổ chồng lấn cho STFT được sử dụng để lấy các hệ số Mel Frequency. - n_fft (
int, tùy chọn, mặc định là 512) — Kích thước của phép biến đổi Fourier. - win_length (
int, tùy chọn, mặc định là 400) — Chiều dài cửa sổ cho phép tính STFT. - preemphasis (
float, tùy chọn, mặc định là 0.97) — Hệ số của bộ lọc preemphasis. 0.0 có nghĩa là không có bộ lọc preemphasis. - padding_value (
float, tùy chọn, mặc định là 0.0) — Giá trị đệm được dùng để đệm âm thanh. Nên tương ứng với các khoảng im lặng.
Tạo một bộ trích xuất đặc trưng Parakeet.
Feature extractor này kế thừa từ SequenceFeatureExtractor, bao gồm hầu hết các phương thức chính. Người dùng nên tham khảo lớp cha này để biết thêm thông tin về các phương thức đó.
Lớp này trích xuất các đặc trưng mel-filter bank từ giọng nói thô bằng cách sử dụng một cài đặt numpy tùy chỉnh của Short Time Fourier Transform, vốn nên khớp với tương đương torch.stft của pytorch.
__call__
< source >( raw_speech: numpy.ndarray | list[float] | list[numpy.ndarray] | list[list[float]]truncation: bool = Falsepad_to_multiple_of: int | None = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = Nonereturn_attention_mask: bool | None = Nonepadding: str | None = 'longest'max_length: int | None = Nonesampling_rate: int | None = Nonedo_normalize: bool | None = Nonedevice: str | None = 'cpu'return_token_timestamps: bool | None = None**kwargs )
Tham số
- raw_speech (
np.ndarray,list[float],list[np.ndarray],list[list[float]]) — Chuỗi hoặc lô các chuỗi cần được đệm. Mỗi chuỗi có thể là một mảng numpy, một danh sách các giá trị float, một danh sách các mảng numpy hoặc một danh sách các danh sách giá trị float. Phải là âm thanh kênh đơn (mono), không phải stereo, tức là một giá trị float duy nhất cho mỗi bước thời gian. - truncation (
bool, tùy chọn, mặc định làTrue) — Bật tính năng cắt để giảm các chuỗi đầu vào dài hơn max_length xuống còn max_length. - pad_to_multiple_of (
int, tuỳ chọn, mặc định là None) — Nếu được đặt, sẽ đệm chuỗi đến bội số của giá trị được cung cấp.Điều này đặc biệt hữu ích để cho phép sử dụng Tensor Cores trên phần cứng NVIDIA có khả năng tính toán
>= 7.5(Volta), hoặc trên TPU, nơi mà việc có độ dài chuỗi là bội số của 128 sẽ mang lại lợi ích. - return_attention_mask (
bool, tuỳ chọn) — Có trả về attention mask hay không. Nếu để mặc định, sẽ trả về attention mask theo mặc định của feature_extractor cụ thể.Đối với các mô hình Parakeet,
attention_maskluôn phải được truyền vào khi suy luận theo lô (batched inference) để tránh các lỗi tinh vi. - return_tensors (
strhoặc TensorType, tùy chọn) — Nếu được đặt, sẽ trả về tensor thay vì danh sách các số nguyên Python. Các giá trị chấp nhận được là:'tf': Trả về các đối tượngtf.constantcủa TensorFlow.'pt': Trả về các đối tượngtorch.Tensorcủa PyTorch.'np': Trả về các đối tượng Numpynp.ndarray.
- sampling_rate (
int, tùy chọn) — Tần số lấy mẫu mà đầu vàoraw_speechđược lấy mẫu. Rất khuyến nghị truyềnsampling_ratetại cuộc gọi forward để ngăn các lỗi âm thầm và cho phép pipeline nhận dạng giọng nói tự động. - padding_value (
float, tùy chọn, mặc định là 0.0) — Giá trị được sử dụng để điền vào các giá trị / vector đệm. - do_normalize (
bool, tùy chọn, mặc định làFalse) — Có nên chuẩn hóa đầu vào theo phương pháp trung bình bằng không và phương sai đơn vị hay không. Việc chuẩn hóa có thể giúp cải thiện đáng kể hiệu suất của mô hình. - device (
str, tùy chọn, mặc định là'cpu') — Chỉ định thiết bị để tính toán phổ log-mel của tín hiệu âm thanh trong phương thức_torch_extract_fbank_features. (ví dụ: “cpu”, “cuda”) - return_token_timestamps (
bool, tuỳ chọn, mặc định làNone) — Đã ngừng hỗ trợ. Hãy dùngreturn_attention_maskthay thế, từ đó có thể suy ra số lượng khung hình.Có nên trả về số khung hình của raw_speech đầu vào hay không. Các num_frames này có thể được mô hình sử dụng để tính toán mốc thời gian ở cấp độ từ.
Phương thức chính để tạo đặc trưng và chuẩn bị một hoặc nhiều chuỗi cho mô hình. Việc triển khai sử dụng PyTorch cho phép tính toán STFT nếu khả dụng, nếu không sẽ dùng phương án dựa trên NumPy chậm hơn.
ParakeetProcessor
lớp transformers.ParakeetProcessor
< source >( feature_extractortokenizerblank_token = '<blank>'decoder_type = None )
Tham số
- feature_extractor (
feature_extractor_class) — Bộ trích xuất đặc trưng là một đầu vào bắt buộc. - tokenizer (
tokenizer_class) — Tokenizer là đầu vào bắt buộc. - blank_token (
str, tùy chọn, mặc định là"<blank>") — Token trống cho việc giải mã transducer. - decoder_type (
str, tuỳ chọn) — Chế độ giải mã/phát timestamp. Các giá trị có thể:"ctc": Các token giống nhau liên tiếp được gộp thành một lần phát."rnnt": Các token lặp lại được giữ lại; mỗi token có một khoảng thời gian timestamp 1 khung hình."tdt": Các token lặp lại được giữ lại; mỗi khoảng token dựa trên thời lượng dự đoán của nó. Dấu câu được gắn vào token phía trước.
Nếu là
None(các checkpoint cũ), loại decoder sẽ được suy luận tự động để đảm bảo tương thích ngược.
Tạo một ParakeetProcessor đóng gói một bộ trích xuất đặc trưng và một bộ phân từ thành một bộ xử lý duy nhất.
ParakeetProcessor cung cấp đầy đủ các chức năng của feature_extractor_class và tokenizer_class. Xem ~feature_extractor_class và ~tokenizer_class để biết thêm thông tin.
__call__
< source >( audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor']]text: str | list[str] | list[list[str]] | None = Nonesampling_rate: int | None = None**kwargs: *<class 'transformers.models.parakeet.processing_parakeet.ParakeetProcessorKwargs'> )
Tham số
- audio (
Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]]) — Âm thanh hoặc lô âm thanh cần được chuẩn bị. Mỗi âm thanh có thể là một mảng NumPy hoặc tensor PyTorch. Trong trường hợp là mảng NumPy/tensor PyTorch, mỗi âm thanh nên có hình dạng (C, T), trong đó C là số kênh và T là độ dài mẫu của âm thanh. - text (
Union[str, list[str], list[list[str]]], tùy chọn) — Chuỗi hoặc lô các chuỗi cần được mã hóa. Mỗi chuỗi có thể là một chuỗi ký tự hoặc một danh sách các chuỗi ký tự (chuỗi đã được tách token trước). Nếu bạn truyền vào dữ liệu đầu vào đã được tách token trước, hãy đặtis_split_into_words=Trueđể tránh nhầm lẫn với các đầu vào dạng lô. - sampling_rate (
int, tùy chọn) — Tần số lấy mẫu của âm thanh đầu vào, tính bằng Hz. Giá trị này phải khớp với tần số lấy mẫu mà bộ trích xuất đặc trưng kỳ vọng (mặc định là 16000 Hz). Nếu được cung cấp, nó sẽ được kiểm tra đối chiếu với tần số lấy mẫu kỳ vọng của bộ xử lý, và một lỗi sẽ được ném ra nếu chúng không khớp. Nếu không được cung cấp, một cảnh báo sẽ được phát ra và tần số lấy mẫu mặc định sẽ được giả định. - return_tensors (
strhoặc TensorType, tùy chọn) — Nếu được đặt, sẽ trả về tensor của một framework cụ thể. Các giá trị chấp nhận được là:'pt': Trả về các đối tượngtorch.Tensorcủa PyTorch.'np': Trả về các đối tượngnp.ndarraycủa NumPy.
- **kwargs (ProcessingKwargs, optional) — Các tùy chọn xử lý bổ sung cho từng modality (text, images, videos, audio). Các tham số cụ thể của model được liệt kê ở trên; xem lớp TypedDict để biết danh sách đầy đủ các đối số được hỗ trợ.
Truyền các đối số tới decode() và xử lý hậu kỳ các mốc thời gian (nếu được cung cấp cho TDT) như trong thư viện NeMo.
ParakeetEncoderConfig
lớp transformers.ParakeetEncoderConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1024num_hidden_layers: int = 24num_attention_heads: int = 8intermediate_size: int = 4096hidden_act: str = 'silu'attention_bias: bool = Trueconvolution_bias: bool = Trueconv_kernel_size: int = 9subsampling_factor: int = 8subsampling_conv_channels: int = 256num_mel_bins: int = 80subsampling_conv_kernel_size: int = 3subsampling_conv_stride: int = 2dropout: float | int = 0.1dropout_positions: float | int = 0.0layerdrop: float | int = 0.1activation_dropout: float | int = 0.1attention_dropout: float | int = 0.1max_position_embeddings: int = 5000scale_input: bool = Trueinitializer_range: float = 0.02 )
Tham số
- hidden_size (
int, tùy chọn, mặc định là1024) — Kích thước của các biểu diễn ẩn. - num_hidden_layers (
int, tùy chọn, mặc định là24) — Số lượng lớp ẩn trong bộ giải mã Transformer. - num_attention_heads (
int, tùy chọn, mặc định là8) — Số lượng đầu attention cho mỗi lớp attention trong bộ giải mã Transformer. - intermediate_size (
int, tùy chọn, mặc định là4096) — Kích thước của các biểu diễn MLP. - hidden_act (
str, tùy chọn, mặc định làsilu) — Hàm kích hoạt phi tuyến (hàm hoặc chuỗi) trong bộ giải mã. Ví dụ,"gelu","relu","silu", v.v. - attention_bias (
bool, tùy chọn, mặc định làTrue) — Có sử dụng bias trong các lớp chiếu query, key, value và output trong quá trình self-attention hay không. - convolution_bias (
bool, tùy chọn, mặc định làTrue) — Có sử dụng bias trong các phép convolution của module convolution trong conformer hay không. - conv_kernel_size (
int, tùy chọn, mặc định là 9) — Kích thước kernel của các lớp tích chập trong khối Conformer. - subsampling_factor (
int, tùy chọn, mặc định là 8) — Hệ số mà theo đó chuỗi đầu vào được lấy mẫu con. - subsampling_conv_channels (
int, tùy chọn, mặc định là 256) — Số lượng kênh trong các lớp tích chập hạ mẫu. - num_mel_bins (
int, tùy chọn, mặc định là 80) — Số lượng đặc trưng mel. - subsampling_conv_kernel_size (
int, tùy chọn, mặc định là 3) — Kích thước nhân của các lớp tích chập lấy mẫu con. - subsampling_conv_stride (
int, tuỳ chọn, mặc định là 2) — Bước nhảy (stride) của các lớp tích chập hạ mẫu (subsampling convolution). - dropout (
Union[float, int], tùy chọn, mặc định là0.1) — Tỷ lệ cho tất cả các lớp dropout. - dropout_positions (
float, tùy chọn, mặc định là 0.0) — Tỷ lệ dropout cho các vị trí trong chuỗi đầu vào. - layerdrop (
Union[float, int], tùy chọn, mặc định là0.1) — Xác suất LayerDrop. Xem [bài báo LayerDrop](xem https://huggingface.co/papers/1909.11556) để biết thêm chi tiết. - activation_dropout (
Union[float, int], tùy chọn, mặc định là0.1) — Tỷ lệ dropout cho các kích hoạt bên trong lớp liên kết đầy đủ. - attention_dropout (
Union[float, int], tùy chọn, mặc định là0.1) — Tỷ lệ dropout cho các xác suất chú ý. - max_position_embeddings (
int, tùy chọn, mặc định là5000) — Chiều dài chuỗi tối đa mà mô hình này có thể được sử dụng. - scale_input (
bool, tùy chọn, mặc định làTrue) — Có nên mở rộng các embedding đầu vào hay không. - initializer_range (
float, tùy chọn, mặc định là0.02) — Độ lệch chuẩn của truncated_normal_initializer để khởi tạo tất cả các ma trận trọng số.
Đây là lớp cấu hình để lưu trữ cấu hình của một ParakeetModel. Nó được sử dụng để khởi tạo một mô hình Parakeet theo các đối số được chỉ định, xác định kiến trúc của mô hình. Khởi tạo một cấu hình với các giá trị mặc định sẽ tạo ra một cấu hình tương tự như cấu hình của nvidia/parakeet-ctc-1.1b
Các đối tượng cấu hình kế thừa từ PreTrainedConfig và có thể được sử dụng để kiểm soát đầu ra của mô hình. Đọc tài liệu từ PreTrainedConfig để biết thêm thông tin.
Ví dụ:
>>> from transformers import ParakeetEncoderModel, ParakeetEncoderConfig
>>> # Initializing a `ParakeetEncoder` configuration
>>> configuration = ParakeetEncoderConfig()
>>> # Initializing a model from the configuration
>>> model = ParakeetEncoderModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configParakeetCTCConfig
lớp transformers.ParakeetCTCConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 1025ctc_loss_reduction: str = 'mean'ctc_zero_infinity: bool = Trueencoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonepad_token_id: int | None = 1024 )
Tham số
- vocab_size (
int, tùy chọn, mặc định là1025) — Kích thước từ vựng của mô hình. Xác định số lượng token khác nhau có thể được biểu diễn bởiinput_ids. - ctc_loss_reduction (
str, tùy chọn, mặc định là"mean") — Chỉ định phương pháp giảm (reduction) áp dụng cho đầu ra củatorch.nn.CTCLoss. Chỉ liên quan khi huấn luyện một thực thể của ParakeetForCTC. - ctc_zero_infinity (
bool, tùy chọn, mặc định làTrue) — Có nên đặt bằng không các tổn thất vô hạn và các gradient liên quan củatorch.nn.CTCLosshay không. Tổn thất vô hạn chủ yếu xảy ra khi các đầu vào quá ngắn để có thể căn chỉnh với các mục tiêu. Chỉ liên quan khi huấn luyện một instance của ParakeetForCTC. - encoder_config (
Union[dict, ParakeetEncoderConfig], tùy chọn) — Đối tượng cấu hình hoặc từ điển của bộ mã hóa. - pad_token_id (
int, tùy chọn, mặc định là1024) — Token id được sử dụng để đệm trong từ vựng.
Đây là lớp cấu hình để lưu trữ cấu hình của một ParakeetModel. Nó được sử dụng để khởi tạo một mô hình Parakeet theo các đối số được chỉ định, xác định kiến trúc của mô hình. Khởi tạo một cấu hình với các giá trị mặc định sẽ tạo ra một cấu hình tương tự như cấu hình của nvidia/parakeet-ctc-1.1b
Các đối tượng cấu hình kế thừa từ PreTrainedConfig và có thể được sử dụng để kiểm soát đầu ra của mô hình. Đọc tài liệu từ PreTrainedConfig để biết thêm thông tin.
Ví dụ:
>>> from transformers import ParakeetForCTC, ParakeetCTCConfig
>>> # Initializing a Parakeet configuration
>>> configuration = ParakeetCTCConfig()
>>> # Initializing a model from the configuration
>>> model = ParakeetForCTC(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configParakeetRNNTConfig
lớp transformers.ParakeetRNNTConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0id2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneis_encoder_decoder: bool = Truevocab_size: int = 8193decoder_hidden_size: int = 640num_decoder_layers: int = 2hidden_act: str = 'relu'max_symbols_per_step: int = 10encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonepad_token_id: int = 2blank_token_id: int = 8192 )
Tham số
- is_encoder_decoder (
bool, tùy chọn, mặc định làTrue) — Xác định xem mô hình có được sử dụng như một encoder/decoder hay không. - vocab_size (
int, tuỳ chọn, mặc định là8193) — Kích thước từ vựng của mô hình. Xác định số lượng token khác nhau có thể được biểu diễn bởiinput_ids. - decoder_hidden_size (
int, tùy chọn, mặc định là 640) — Kích thước ẩn của mạng dự đoán LSTM và mạng liên hợp. - num_decoder_layers (
int, tùy chọn, mặc định là 2) — Số lượng lớp LSTM trong mạng dự đoán. - hidden_act (
str, tùy chọn, mặc định làrelu) — Hàm kích hoạt phi tuyến (hàm hoặc chuỗi) trong bộ giải mã. Ví dụ,"gelu","relu","silu", v.v. - max_symbols_per_step (
int, tùy chọn, mặc định là 10) — Số lượng ký hiệu tối đa được phát ra cho mỗi bước thời gian của bộ mã hóa trong quá trình giải mã tham lam. - encoder_config (
Union[dict, ParakeetEncoderConfig], tùy chọn) — Đối tượng cấu hình hoặc từ điển của bộ mã hóa. - pad_token_id (
int, tùy chọn, mặc định là2) — Token id được sử dụng để đệm (padding) trong từ vựng. - blank_token_id (
int, tùy chọn, mặc định là 8192) — ID của token trống. Khác vớipad_token_idđối với RNN-T.
Đây là lớp cấu hình để lưu trữ cấu hình của một ParakeetModel. Nó được sử dụng để khởi tạo một mô hình Parakeet theo các đối số được chỉ định, xác định kiến trúc của mô hình. Khởi tạo một cấu hình với các giá trị mặc định sẽ tạo ra một cấu hình tương tự như cấu hình của nvidia/parakeet-rnnt-0.6b
Các đối tượng cấu hình kế thừa từ PreTrainedConfig và có thể được sử dụng để kiểm soát đầu ra của mô hình. Đọc tài liệu từ PreTrainedConfig để biết thêm thông tin.
Ví dụ:
>>> from transformers import ParakeetForRNNT, ParakeetRNNTConfig
>>> # Initializing a Parakeet RNN-T configuration
>>> configuration = ParakeetRNNTConfig()
>>> # Initializing a model from the configuration
>>> model = ParakeetForRNNT(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configParakeetTDTConfig
lớp transformers.ParakeetTDTConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0id2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneis_encoder_decoder: bool = Truevocab_size: int = 8193decoder_hidden_size: int = 640num_decoder_layers: int = 2hidden_act: str = 'relu'max_symbols_per_step: int = 10encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonepad_token_id: int = 2blank_token_id: int = 8192durations: list[int] | tuple[int, ...] = (0, 1, 2, 3, 4) )
Tham số
- is_encoder_decoder (
bool, tùy chọn, mặc định làTrue) — Xác định xem mô hình có được sử dụng như một encoder/decoder hay không. - vocab_size (
int, tuỳ chọn, mặc định là8193) — Kích thước từ vựng của mô hình. Xác định số lượng token khác nhau có thể được biểu diễn bởiinput_ids. - decoder_hidden_size (
int, tùy chọn, mặc định là 640) — Kích thước ẩn của mạng dự đoán LSTM và mạng liên hợp. - num_decoder_layers (
int, tùy chọn, mặc định là 2) — Số lượng lớp LSTM trong mạng dự đoán. - hidden_act (
str, tùy chọn, mặc định làrelu) — Hàm kích hoạt phi tuyến (hàm hoặc chuỗi) trong bộ giải mã. Ví dụ,"gelu","relu","silu", v.v. - max_symbols_per_step (
int, tùy chọn, mặc định là 10) — Số lượng ký hiệu tối đa được phát ra cho mỗi bước thời gian của bộ mã hóa trong quá trình giải mã tham lam. - encoder_config (
Union[dict, ParakeetEncoderConfig], tùy chọn) — Đối tượng cấu hình hoặc từ điển của bộ mã hóa. - pad_token_id (
int, tùy chọn, mặc định là2) — Token id được sử dụng để đệm (padding) trong từ vựng. - blank_token_id (
int, tùy chọn, mặc định là 8192) — ID của token trống. Khác vớipad_token_idđối với TDT. - durations (
list[int], tùy chọn, mặc định là[0, 1, 2, 3, 4]) — Các giá trị thời lượng token có thể dự đoán. Mỗi giá trị đại diện cho số khung hình mà một token hoặc một lần phát blank trải qua.
Đây là lớp cấu hình để lưu trữ cấu hình của một ParakeetModel. Nó được sử dụng để khởi tạo một mô hình Parakeet theo các đối số được chỉ định, xác định kiến trúc của mô hình. Khởi tạo một cấu hình với các giá trị mặc định sẽ tạo ra một cấu hình tương tự như cấu hình của nvidia/parakeet-tdt-0.6b-v3
Các đối tượng cấu hình kế thừa từ PreTrainedConfig và có thể được sử dụng để kiểm soát đầu ra của mô hình. Đọc tài liệu từ PreTrainedConfig để biết thêm thông tin.
Ví dụ:
>>> from transformers import ParakeetForTDT, ParakeetTDTConfig
>>> # Initializing a Parakeet TDT configuration
>>> configuration = ParakeetTDTConfig()
>>> # Initializing a model from the configuration
>>> model = ParakeetForTDT(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configParakeetEncoder
lớp transformers.ParakeetEncoder
< source >( config: ParakeetEncoderConfig )
Tham số
- config (ParakeetEncoderConfig) — Lớp cấu hình mô hình chứa tất cả các tham số của mô hình. Khởi tạo bằng tệp cấu hình sẽ không tải trọng số liên quan đến mô hình, chỉ tải cấu hình. Xem phương thức from_pretrained() để tải trọng số của mô hình.
Mô hình Parakeet Encoder, dựa trên kiến trúc Fast Conformer.
Mô hình này kế thừa từ PreTrainedModel. Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các mô hình của nó (chẳng hạn như tải xuống hoặc lưu trữ, thay đổi kích thước các nhúng đầu vào, cắt tỉa các đầu, v.v.)
Mô hình này cũng là một lớp con của torch.nn.Module trong PyTorch. Hãy sử dụng nó như một Module PyTorch thông thường và tham khảo tài liệu PyTorch cho mọi vấn đề liên quan đến cách sử dụng và hành vi chung.
forward
< source >( input_features: Tensorattention_mask: typing.Optional[torch.Tensor] = Noneoutput_attention_mask: bool = True**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutput or tuple(torch.Tensor)
Tham số
- input_features (
torch.Tensorcó hình dạng(batch_size, sequence_length, feature_dim)) — Các tensor tương ứng với các đặc trưng âm thanh đầu vào. Các đặc trưng âm thanh có thể được lấy bằng cách sử dụngfeature_extractor_class. Xemfeature_extractor_class.__call__để biết chi tiết (processor_classsử dụngfeature_extractor_classđể xử lý âm thanh). - attention_mask (
torch.Tensorcó hình dạng(batch_size, sequence_length), tùy chọn) — Mặt nạ để tránh thực hiện chú ý trên các chỉ số token đệm. Các giá trị mặt nạ được chọn trong[0, 1]:- 1 cho các token không bị che,
- 0 cho các token bị che.
- output_attention_mask (
bool, tùy chọn, mặc định làTrue) — Có trả về output attention mask hay không. Chỉ có hiệu lực khiattention_maskđược cung cấp.
Trả về
BaseModelOutput hoặc tuple(torch.Tensor)
Một BaseModelOutput hoặc một tuple của
torch.Tensor (nếu return_dict=False được truyền hoặc khi config.return_dict=False) bao gồm các
thành phần khác nhau tùy thuộc vào cấu hình (None) và đầu vào.
Phương thức forward của ParakeetEncoder ghi đè lên phương thức đặc biệt __call__.
Mặc dù công thức cho bước truyền tiến cần được định nghĩa bên trong hàm này, người dùng nên gọi instance của
Modulesau đó thay vì gọi hàm này, vì instanceModulesẽ đảm nhận việc thực hiện các bước tiền xử lý và hậu xử lý, trong khi hàm này sẽ lặng lẽ bỏ qua chúng.
last_hidden_state (
torch.Tensorcó hình dạng(batch_size, sequence_length, hidden_size)) — Chuỗi các hidden-state tại đầu ra của lớp cuối cùng của mô hình.hidden_states (
tuple(torch.Tensor), tuỳ chọn, được trả về khioutput_hidden_states=Trueđược truyền vào hoặc khiconfig.output_hidden_states=True) — Bộ tuple củatorch.Tensor(một cho đầu ra của embeddings, nếu mô hình có lớp embedding, + một cho đầu ra của mỗi lớp) có hình dạng(batch_size, sequence_length, hidden_size).Trạng thái ẩn của mô hình tại đầu ra của mỗi lớp cùng với các đầu ra embedding ban đầu tùy chọn.
attentions (
tuple(torch.Tensor), tuỳ chọn, được trả về khioutput_attentions=Trueđược truyền vào hoặc khiconfig.output_attentions=True) — Tuple củatorch.Tensor(một cho mỗi lớp) có hình dạng(batch_size, num_heads, sequence_length, sequence_length).Trọng số chú ý sau softmax của attention, được sử dụng để tính trung bình có trọng số trong các đầu self-attention.
Ví dụ:
>>> from transformers import AutoProcessor, ParakeetEncoder
>>> from datasets import load_dataset, Audio
>>> model_id = "nvidia/parakeet-ctc-1.1b"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> encoder = ParakeetEncoder.from_pretrained(model_id)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
>>> inputs = processor(ds[0]["audio"]["array"])
>>> encoder_outputs = encoder(**inputs)
>>> print(encoder_outputs.last_hidden_state.shape)ParakeetForCTC
lớp transformers.ParakeetForCTC
< source >( config: ParakeetCTCConfig )
Tham số
- config (ParakeetCTCConfig) — Lớp cấu hình mô hình chứa tất cả các tham số của mô hình. Khởi tạo bằng tệp cấu hình sẽ không tải trọng số liên quan đến mô hình, chỉ tải cấu hình. Xem phương thức from_pretrained() để tải trọng số của mô hình.
Bộ mã hóa Parakeet với đầu Connectionist Temporal Classification (CTC).
Mô hình này kế thừa từ PreTrainedModel. Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các mô hình của nó (chẳng hạn như tải xuống hoặc lưu trữ, thay đổi kích thước các nhúng đầu vào, cắt tỉa các đầu, v.v.)
Mô hình này cũng là một lớp con của torch.nn.Module trong PyTorch. Hãy sử dụng nó như một Module PyTorch thông thường và tham khảo tài liệu PyTorch cho mọi vấn đề liên quan đến cách sử dụng và hành vi chung.
forward
< source >( input_features: Tensorattention_mask: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → CausalLMOutput or tuple(torch.Tensor)
Tham số
- input_features (
torch.Tensorcó hình dạng(batch_size, sequence_length, feature_dim)) — Các tensor tương ứng với các đặc trưng âm thanh đầu vào. Các đặc trưng âm thanh có thể được lấy bằng cách sử dụngfeature_extractor_class. Xemfeature_extractor_class.__call__để biết chi tiết (processor_classsử dụngfeature_extractor_classđể xử lý âm thanh). - attention_mask (
torch.Tensorcó hình dạng(batch_size, sequence_length), tùy chọn) — Mặt nạ để tránh thực hiện chú ý trên các chỉ số token đệm. Các giá trị mặt nạ được chọn trong[0, 1]:- 1 cho các token không bị che,
- 0 cho các token bị che.
- labels (
torch.Tensorcó shape(batch_size, sequence_length), tùy chọn) — Nhãn để tính toán tổn thất mô hình hóa ngôn ngữ có che (masked language modeling loss). Chỉ số phải nằm trong[0, ..., config.vocab_size]hoặc -100 (xem docstring củainput_ids). Các token có chỉ số được đặt thành-100sẽ bị bỏ qua (che), tổn thất chỉ được tính cho các token có nhãn nằm trong[0, ..., config.vocab_size].
Trả về
CausalLMOutput hoặc tuple(torch.Tensor)
Một CausalLMOutput hoặc một tuple của
torch.Tensor (nếu return_dict=False được truyền hoặc khi config.return_dict=False) bao gồm các
thành phần khác nhau tùy thuộc vào cấu hình (None) và đầu vào.
Phương thức forward của ParakeetForCTC ghi đè lên phương thức đặc biệt __call__.
Mặc dù công thức cho bước truyền tiến cần được định nghĩa bên trong hàm này, người dùng nên gọi instance của
Modulesau đó thay vì gọi hàm này, vì instanceModulesẽ đảm nhận việc thực hiện các bước tiền xử lý và hậu xử lý, trong khi hàm này sẽ lặng lẽ bỏ qua chúng.
loss (
torch.Tensorcó shape(1,), tùy chọn, được trả về khilabelsđược cung cấp) — Loss của language modeling (cho next-token prediction).logits (
torch.Tensorcó hình dạng(batch_size, sequence_length, config.vocab_size)) — Điểm dự đoán của đầu mô hình hóa ngôn ngữ (điểm cho mỗi token trong từ vựng trước SoftMax).hidden_states (
tuple(torch.Tensor), tuỳ chọn, được trả về khioutput_hidden_states=Trueđược truyền vào hoặc khiconfig.output_hidden_states=True) — Bộ tuple củatorch.Tensor(một cho đầu ra của embeddings, nếu mô hình có lớp embedding, + một cho đầu ra của mỗi lớp) có hình dạng(batch_size, sequence_length, hidden_size).Trạng thái ẩn của mô hình tại đầu ra của mỗi lớp cùng với các đầu ra embedding ban đầu tùy chọn.
attentions (
tuple(torch.Tensor), tuỳ chọn, được trả về khioutput_attentions=Trueđược truyền vào hoặc khiconfig.output_attentions=True) — Tuple củatorch.Tensor(một cho mỗi lớp) có hình dạng(batch_size, num_heads, sequence_length, sequence_length).Trọng số chú ý sau softmax của attention, được sử dụng để tính trung bình có trọng số trong các đầu self-attention.
Ví dụ:
>>> from transformers import AutoProcessor, ParakeetForCTC
>>> from datasets import load_dataset, Audio
>>> model_id = "nvidia/parakeet-ctc-1.1b"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = ParakeetForCTC.from_pretrained(model_id)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
>>> outputs = model(**inputs)
>>> print(outputs.loss)generate
< source >( input_features: Tensorattention_mask: typing.Optional[torch.Tensor] = Nonereturn_dict_in_generate: bool = Falsecompile_config: transformers.generation.configuration_utils.CompileConfig | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )
compile_config (CompileConfig, tuỳ chọn):
Nếu được cung cấp, torch.compile sẽ được áp dụng cho các lời gọi forward trong vòng lặp giải mã.
Ví dụ:
>>> from transformers import AutoProcessor, ParakeetForCTC
>>> from datasets import load_dataset, Audio
>>> model_id = "nvidia/parakeet-ctc-1.1b"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = ParakeetForCTC.from_pretrained(model_id)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
>>> predicted_ids = model.generate(**inputs)
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
>>> print(transcription)ParakeetForRNNT
lớp transformers.ParakeetForRNNT
< source >( config: ParakeetRNNTConfig )
Tham số
- config (ParakeetRNNTConfig) — Lớp cấu hình mô hình chứa tất cả các tham số của mô hình. Khởi tạo bằng tệp cấu hình sẽ không tải trọng số liên quan đến mô hình, chỉ tải cấu hình. Xem phương thức from_pretrained() để tải trọng số của mô hình.
Parakeet Encoder với đầu RNN-T (RNN Transducer).
Mô hình này kế thừa từ PreTrainedModel. Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các mô hình của nó (chẳng hạn như tải xuống hoặc lưu trữ, thay đổi kích thước các nhúng đầu vào, cắt tỉa các đầu, v.v.)
Mô hình này cũng là một lớp con của torch.nn.Module trong PyTorch. Hãy sử dụng nó như một Module PyTorch thông thường và tham khảo tài liệu PyTorch cho mọi vấn đề liên quan đến cách sử dụng và hành vi chung.
forward
< source >( input_features: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_cache: transformers.models.parakeet.generation_parakeet.ParakeetRNNTDecoderCache | None = Noneuse_decoder_cache: bool | None = Noneencoder_outputs: transformers.models.parakeet.modeling_parakeet.ParakeetEncoderModelOutput | tuple[torch.Tensor] | None = Nonelabels: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ParakeetRNNTOutput or tuple(torch.Tensor)
Tham số
- input_features (
torch.Tensorcó hình dạng(batch_size, sequence_length, feature_dim), tùy chọn) — Các tensor tương ứng với các đặc trưng âm thanh đầu vào. Các đặc trưng âm thanh có thể được lấy bằng cách sử dụngfeature_extractor_class. Xemfeature_extractor_class.__call__để biết chi tiết (processor_classsử dụngfeature_extractor_classđể xử lý âm thanh). - attention_mask (
torch.Tensorcó hình dạng(batch_size, sequence_length), tùy chọn) — Mặt nạ để tránh thực hiện chú ý trên các chỉ số token đệm. Các giá trị mặt nạ được chọn trong[0, 1]:- 1 cho các token không bị che,
- 0 cho các token bị che.
- decoder_input_ids (
torch.LongTensorcó hình dạng(batch_size, 1), tùy chọn) — Các id token đầu vào của bộ giải mã cho suy luận một bước. - decoder_cache (
ParakeetRNNTDecoderCache, optional) — Bộ đệm LSTM của decoder. Khi được cung cấp và khởi tạo,decoder_outputđược lưu trong bộ đệm sẽ được tái sử dụng (ví dụ: trong quá trình bỏ qua các token blank) thay vì chạy decoder. Khiinput_idsđược cung cấp, decoder sẽ chạy và bộ đệm được cập nhật tại chỗ. - use_decoder_cache (
bool, tùy chọn) — Có sử dụng bộ nhớ đệm (cache) cho bộ giải mã (decoder) hay không. KhiTruevàdecoder_cachelàNone, một bộ nhớ đệm mới sẽ được tạo tự động trong quá trình truyền tiến (forward pass). - encoder_outputs (
tuple(torch.Tensor), tùy chọn) — Đầu ra của encoder đã được tính trước (last_hidden_state, pooler_output, hidden_states, attentions, attention_mask). Có thể là một tuple hoặcParakeetEncoderModelOutput. - labels (
torch.Tensorcó shape(batch_size, sequence_length), tùy chọn) — Nhãn để tính toán tổn thất mô hình hóa ngôn ngữ có che (masked language modeling loss). Chỉ số phải nằm trong[0, ..., config.vocab_size]hoặc -100 (xem docstring củainput_ids). Các token có chỉ số được đặt thành-100sẽ bị bỏ qua (che), tổn thất chỉ được tính cho các token có nhãn nằm trong[0, ..., config.vocab_size].
Trả về
ParakeetRNNTOutput hoặc tuple(torch.Tensor)
Một ParakeetRNNTOutput hoặc một tuple của
torch.Tensor (nếu return_dict=False được truyền hoặc khi config.return_dict=False) bao gồm các
thành phần khác nhau tùy thuộc vào cấu hình (None) và đầu vào.
Phương thức forward của ParakeetForRNNT ghi đè lên phương thức đặc biệt __call__.
Mặc dù công thức cho bước truyền tiến cần được định nghĩa bên trong hàm này, người dùng nên gọi instance của
Modulesau đó thay vì gọi hàm này, vì instanceModulesẽ đảm nhận việc thực hiện các bước tiền xử lý và hậu xử lý, trong khi hàm này sẽ lặng lẽ bỏ qua chúng.
- loss (
torch.Tensor, tùy chọn) — Lỗi RNN-T, được trả về khilabelsđược cung cấp. - logits (
torch.Tensor) — Logits của các token kết hợp. Hình dạng là(batch, T, U+1, vocab)cho quá trình huấn luyện hoặc(batch, 1, 1, vocab)cho suy luận một bước. - decoder_cache (
ParakeetRNNTDecoderCache, optional) — Bộ đệm LSTM của decoder chứa trạng thái ẩn, trạng thái ô và đầu ra cuối cùng.
Ví dụ:
>>> from transformers import AutoProcessor, ParakeetForRNNT
>>> from datasets import load_dataset, Audio
>>> model_id = "nvidia/parakeet-rnnt-0.6b"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = ParakeetForRNNT.from_pretrained(model_id)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
>>> inputs = processor(ds[0]["audio"]["array"])
>>> outputs = model(**inputs)ParakeetForTDT
lớp transformers.ParakeetForTDT
< source >( config: ParakeetTDTConfig )
Tham số
- config (ParakeetTDTConfig) — Lớp cấu hình mô hình chứa tất cả các tham số của mô hình. Khởi tạo bằng tệp cấu hình sẽ không tải trọng số liên quan đến mô hình, chỉ tải cấu hình. Xem phương thức from_pretrained() để tải trọng số của mô hình.
Parakeet Encoder với đầu TDT (Token Duration Transducer).
Mô hình này kế thừa từ PreTrainedModel. Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các mô hình của nó (chẳng hạn như tải xuống hoặc lưu trữ, thay đổi kích thước các nhúng đầu vào, cắt tỉa các đầu, v.v.)
Mô hình này cũng là một lớp con của torch.nn.Module trong PyTorch. Hãy sử dụng nó như một Module PyTorch thông thường và tham khảo tài liệu PyTorch cho mọi vấn đề liên quan đến cách sử dụng và hành vi chung.
forward
< source >( input_features: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_cache: transformers.models.parakeet.generation_parakeet.ParakeetRNNTDecoderCache | None = Noneuse_decoder_cache: bool | None = Noneencoder_outputs: transformers.models.parakeet.modeling_parakeet.ParakeetEncoderModelOutput | tuple[torch.Tensor] | None = Nonelabels: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ParakeetRNNTOutput or tuple(torch.Tensor)
Tham số
- input_features (
torch.Tensorcó hình dạng(batch_size, sequence_length, feature_dim), tùy chọn) — Các tensor tương ứng với các đặc trưng âm thanh đầu vào. Các đặc trưng âm thanh có thể được lấy bằng cách sử dụngfeature_extractor_class. Xemfeature_extractor_class.__call__để biết chi tiết (processor_classsử dụngfeature_extractor_classđể xử lý âm thanh). - attention_mask (
torch.Tensorcó hình dạng(batch_size, sequence_length), tùy chọn) — Mặt nạ để tránh thực hiện chú ý trên các chỉ số token đệm. Các giá trị mặt nạ được chọn trong[0, 1]:- 1 cho các token không bị che,
- 0 cho các token bị che.
- decoder_input_ids (
torch.LongTensorcó hình dạng(batch_size, 1), tùy chọn) — Các id token đầu vào của bộ giải mã cho suy luận một bước. - decoder_cache (
ParakeetRNNTDecoderCache, optional) — Bộ đệm LSTM của decoder. Khi được cung cấp và khởi tạo,decoder_outputđược lưu trong bộ đệm sẽ được tái sử dụng (ví dụ: trong quá trình bỏ qua các token blank) thay vì chạy decoder. Khiinput_idsđược cung cấp, decoder sẽ chạy và bộ đệm được cập nhật tại chỗ. - use_decoder_cache (
bool, tùy chọn) — Có sử dụng bộ nhớ đệm (cache) cho bộ giải mã (decoder) hay không. KhiTruevàdecoder_cachelàNone, một bộ nhớ đệm mới sẽ được tạo tự động trong quá trình truyền tiến (forward pass). - encoder_outputs (
tuple(torch.Tensor), tùy chọn) — Đầu ra của encoder đã được tính trước (last_hidden_state, pooler_output, hidden_states, attentions, attention_mask). Có thể là một tuple hoặcParakeetEncoderModelOutput. - labels (
torch.Tensorcó shape(batch_size, sequence_length), tùy chọn) — Nhãn để tính toán tổn thất mô hình hóa ngôn ngữ có che (masked language modeling loss). Chỉ số phải nằm trong[0, ..., config.vocab_size]hoặc -100 (xem docstring củainput_ids). Các token có chỉ số được đặt thành-100sẽ bị bỏ qua (che), tổn thất chỉ được tính cho các token có nhãn nằm trong[0, ..., config.vocab_size].
Trả về
ParakeetRNNTOutput hoặc tuple(torch.Tensor)
Một ParakeetRNNTOutput hoặc một tuple của
torch.Tensor (nếu return_dict=False được truyền hoặc khi config.return_dict=False) bao gồm các
thành phần khác nhau tùy thuộc vào cấu hình (None) và đầu vào.
Phương thức forward của ParakeetForTDT ghi đè lên phương thức đặc biệt __call__.
Mặc dù công thức cho bước truyền tiến cần được định nghĩa bên trong hàm này, người dùng nên gọi instance của
Modulesau đó thay vì gọi hàm này, vì instanceModulesẽ đảm nhận việc thực hiện các bước tiền xử lý và hậu xử lý, trong khi hàm này sẽ lặng lẽ bỏ qua chúng.
- loss (
torch.Tensor, tùy chọn) — Lỗi RNN-T, được trả về khilabelsđược cung cấp. - logits (
torch.Tensor) — Logits của các token kết hợp. Hình dạng là(batch, T, U+1, vocab)cho quá trình huấn luyện hoặc(batch, 1, 1, vocab)cho suy luận một bước. - decoder_cache (
ParakeetRNNTDecoderCache, optional) — Bộ đệm LSTM của decoder chứa trạng thái ẩn, trạng thái ô và đầu ra cuối cùng.
Ví dụ:
>>> from transformers import AutoProcessor, ParakeetForTDT
>>> from datasets import load_dataset, Audio
>>> model_id = "nvidia/parakeet-tdt-0.6b-v3"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = ParakeetForTDT.from_pretrained(model_id)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
>>> inputs = processor(ds[0]["audio"]["array"])
>>> outputs = model(**inputs)