Transformers documentation

Moonshine 流式

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2024-10-21 在 HF papers 上发布,并于 2026-02-04 贡献至 Hugging Face Transformers。

FlashAttention SDPA

Moonshine 流式

Moonshine Streaming 是 Moonshine 语音识别模型的流式变体,专为低延迟的实时转录而优化。与原始 Moonshine 一样,它是一个编码器-解码器模型,使用 Rotary Position Embedding (RoPE) 来高效处理变长语音。其流式架构在编码器中采用了滑动窗口注意力机制,并包含一个上下文适配器,以支持对音频片段的增量处理。

Moonshine Streaming 提供三种规格:tiny、small 和 medium,在速度与精度之间提供权衡。它尤其适用于设备端流式转录和语音指令应用。

您可以在 Useful Sensors 组织下找到所有原始的 Moonshine Streaming 检查点。

Moonshine Streaming 直接处理原始音频波形,无需进行梅尔频谱图预处理,因此非常适合实时应用。

以下示例演示了如何使用 Pipeline 或 AutoModel 类将语音转录为文本。

Pipeline
AutoModel
from transformers import pipeline


pipe = pipeline(
    task="automatic-speech-recognition",
    model="UsefulSensors/moonshine-streaming-tiny",
    device=0
)
pipe("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")

MoonshineStreamingProcessor

class transformers.MoonshineStreamingProcessor

< >

( feature_extractortokenizer )

参数

  • feature_extractor (feature_extractor_class) — 特征提取器是必需的输入。
  • tokenizer (tokenizer_class) — 分词器是必需的输入。

构造一个 MoonshineStreamingProcessor,它将特征提取器和分词器封装为单个处理器。

MoonshineStreamingProcessor 提供了 feature_extractor_class 和 tokenizer_class 的所有功能。有关更多信息,请参阅 ~feature_extractor_class 和 ~tokenizer_class。

填充

< >

( *args**kwargs )

参数

  • input_features — 当第一个参数是包含一批张量的字典,或者存在 input_features 参数时,它会传递给 MoonshineStreamingFeatureExtractor.pad。
  • labels — 当存在 label 参数时,它会传递给 PreTrainedTokenizer.pad()。

此方法处理提取的特征批次和/或分词后的文本。它根据输入模态将所有参数转发给 MoonshineStreamingFeatureExtractor.pad 和/或 PreTrainedTokenizer.pad(),并返回它们的输出。如果同时传入两种模态,则会调用 MoonshineStreamingFeatureExtractor.pad 和 PreTrainedTokenizer.pad()。

MoonshineStreamingEncoderConfig

class transformers.MoonshineStreamingEncoderConfig

< >

( 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 = 320intermediate_size: int = 1280hidden_act: str = 'gelu'num_hidden_layers: int = 6num_attention_heads: int = 8num_key_value_heads: int = 8max_position_embeddings: int = 4096attention_dropout: float | int = 0.0attention_bias: bool = Falsesample_rate: int = 16000frame_ms: float = 5.0sliding_windows: tuple[tuple[int, int], ...] | list[list[int, int]] = ((16, 4), (16, 4), (16, 0), (16, 0), (16, 4), (16, 4))head_dim: int | None = None )

参数

  • hidden_size (int,可选,默认为 320) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 1280) — MLP 表示的维度。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • num_hidden_layers (int,可选,默认为 6) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 8) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_key_value_heads (int, 可选,默认为 8) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果 num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果 num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 num_attention_heads。
  • max_position_embeddings (int,可选,默认为 4096) — 该模型可能使用的最大序列长度。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • attention_bias (bool,可选,默认为 False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • sample_rate (int,可选,默认为 16000) — 音频输入的采样率,单位为 Hz。
  • frame_ms (float,可选,默认值为 5.0) — 用于音频处理的帧持续时间(以毫秒为单位)。
  • sliding_windows (list[tuple[int, int]],可选,默认为 [(16, 4), (16, 4), (16, 0), (16, 0), (16, 4), (16, 4)]) — 每个编码器层的滑动窗口配置列表。每个元组包含 (window_size, shift)。
  • head_dim (int,可选) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads

这是用于存储 MoonshineStreamingModel 配置的类。它根据指定的参数实例化 Moonshine Streaming 模型,并定义模型架构。使用默认值实例化配置将得到与 UsefulSensors/moonshine-streaming-tiny 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

>>> from transformers import MoonshineStreamingEncoder, MoonshineStreamingEncoderConfig

>>> # Initializing a Moonshine Streaming encoder configuration
>>> configuration = MoonshineStreamingEncoderConfig()

>>> # Initializing a model from the configuration
>>> model = MoonshineStreamingEncoder(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

MoonshineStreamingConfig

class transformers.MoonshineStreamingConfig

< >

( 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 = Trueencoder_config: dict | transformers.models.moonshine_streaming.configuration_moonshine_streaming.MoonshineStreamingEncoderConfig | None = Nonevocab_size: int = 32768hidden_size: int = 320intermediate_size: int = 1280num_hidden_layers: int = 6num_attention_heads: int = 8hidden_act: str = 'silu'max_position_embeddings: int = 4096use_cache: bool = Truepad_token_id: int | None = 0bos_token_id: int | None = 1eos_token_id: int | list[int] | None = 2rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falseattention_dropout: float | int = 0.0decoder_start_token_id: int | None = Nonehead_dim: int | None = Nonepad_head_dim_to_multiple_of: int | None = Nonetie_word_embeddings: bool = False )

参数

  • is_encoder_decoder (bool,可选,默认为 True) — 指示该模型是否用作编码器/解码器。
  • encoder_config (Union[dict, ~models.moonshine_streaming.configuration_moonshine_streaming.MoonshineStreamingEncoderConfig], 可选) — 编码器骨干网络的配置对象或字典。
  • vocab_size (int,可选,默认为 32768) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 320) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 1280) — MLP 表示的维度。
  • num_hidden_layers (int,可选,默认为 6) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 8) — Transformer 解码器中每个注意力层的注意力头数量。
  • hidden_act (str,可选,默认为 silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • max_position_embeddings (int,可选,默认为 4096) — 该模型可能使用的最大序列长度。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • pad_token_id (int, 可选,默认为 0) — 词表中用于填充的 token id。
  • bos_token_id (int,可选,默认为 1) — 词汇表中用于表示流起始的 token id。
  • eos_token_id (Union[int, list[int]],可选,默认为 2) — 词汇表中用于表示流结束(end-of-stream)的 token id。
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • attention_bias (bool,可选,默认为 False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • decoder_start_token_id (int, 可选) — 如果编码器-解码器模型使用不同于 bos 的 token 开始解码,则指定该 token 的 id。
  • head_dim (int,可选) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads
  • pad_head_dim_to_multiple_of (int, 可选) — 如果设置,则会将 head 维度填充为该值的整数倍。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 MoonshineStreamingModel 配置的类。它根据指定的参数实例化 Moonshine Streaming 模型,并定义模型架构。使用默认值实例化配置将得到与 UsefulSensors/moonshine-streaming-tiny 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

>>> from transformers import MoonshineStreamingModel, MoonshineStreamingConfig

>>> # Initializing a Moonshine Streaming configuration
>>> configuration = MoonshineStreamingConfig()

>>> # Initializing a model from the configuration
>>> model = MoonshineStreamingModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

MoonshineStreamingModel

class transformers.MoonshineStreamingModel

< >

( config: MoonshineStreamingConfig )

参数

  • config (MoonshineStreamingConfig) — 模型的配置类,包含模型的所有参数。通过配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

未添加任何特定头部的裸 Moonshine Streaming Model,直接输出原始隐藏状态。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_values: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.LongTensor] = Noneencoder_outputs: tuple[tuple[torch.Tensor]] | None = Nonepast_key_values: transformers.cache_utils.EncoderDecoderCache | None = Nonedecoder_inputs_embeds: tuple[torch.Tensor] | None = Nonedecoder_position_ids: tuple[torch.LongTensor] | None = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Seq2SeqModelOutput or tuple(torch.Tensor)

参数

  • input_values(形状为 (batch_size, audio_length) 的 torch.Tensor)— 原始语音波形的浮点值。可以通过将 .flac 或 .wav 音频文件加载为 list[float]、numpy.ndarray 或 torch.Tensor 类型的数组来获取原始语音波形,例如 使用 torchcodec 库(pip install torchcodec)或 soundfile 库(pip install soundfile)。要将该数组处理为 input_values,应使用 AutoFeatureExtractor 进行填充并将其转换为 torch.Tensor 类型的张量。
  • attention_mask (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充(padding)标记索引执行注意力机制的掩码。掩码值取自 [0, 1]:1 表示未屏蔽的标记,0 表示被屏蔽的标记。什么是注意力掩码? [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor 形状为 (batch_size, target_sequence_length), ,可选) — 解码器输入序列中各 token 在词汇表中的索引。可通过 AutoTokenizer 获取索引。详情请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是解码器输入 ID?

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是解码器输入 ID?

  • decoder_attention_mask(形状为 (batch_size, target_sequence_length) 的 torch.LongTensor,可选) — 用于避免对特定 token 索引执行注意力的掩码。默认情况下,会使用因果掩码,以确保模型只能查看之前的输入来预测未来。
  • encoder_outputs (tuple[tuple[torch.Tensor]],可选) — 元组由 (last_hidden_state,可选:hidden_states,可选:attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size),可选) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力。
  • past_key_values (~cache_utils.EncoderDecoderCache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • decoder_inputs_embeds (tuple[torch.Tensor] 形状为 (batch_size, target_sequence_length, hidden_size), 可选) — 可选地,除了传递 decoder_input_ids 之外,您还可以选择直接传递嵌入表示。如果使用了 past_key_values ,则只需输入最后一个 decoder_inputs_embeds (参见 past_key_values). 如果您希望对 decoder_input_ids 索引如何转换为对应的向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。

    如果 decoder_input_ids 和 decoder_inputs_embeds 均未设置,decoder_inputs_embeds 将取 inputs_embeds 的值。

  • decoder_position_ids (torch.LongTensor,形状为 (batch_size, target_sequence_length)) — 输入序列中每个 token 在位置嵌入中的位置索引。 用于计算直至 config.decoder_config.max_position_embeddings 的位置嵌入。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。

返回值

Seq2SeqModelOutput 或 tuple(torch.Tensor)

一个 Seq2SeqModelOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MoonshineStreamingConfig)和输入。

MoonshineStreamingModel 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型解码器最后一层输出的隐藏状态序列。

    如果使用了 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values(EncoderDecoderCache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 EncoderDecoderCache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • decoder_hidden_states (tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    解码器在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • decoder_attentions (tuple(torch.Tensor),可选,在传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    解码器在注意力 softmax 之后的注意力权重,用于在自注意力头中计算加权平均值。

  • cross_attentions (tuple(torch.Tensor),可选,在传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    解码器交叉注意力层在注意力 softmax 之后的注意力权重,用于在交叉注意力头中计算加权平均值。

  • encoder_last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选)— 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_states (tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    编码器每层输出处的隐藏状态,以及可选的初始嵌入输出。

  • encoder_attentions(tuple(torch.Tensor),可选,在传入 output_attentions=True 或 config.output_attentions=True 时返回)—— 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    编码器在注意力 softmax 之后的注意力权重,用于在自注意力头中计算加权平均值。

示例:

>>> import torch
>>> from transformers import AutoFeatureExtractor, MoonshineStreamingModel
>>> from datasets import load_dataset

>>> model = MoonshineStreamingModel.from_pretrained("UsefulSensors/moonshine_streaming-tiny")
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/moonshine_streaming-tiny")
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_values = inputs.input_values
>>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
>>> last_hidden_state = model(input_values, decoder_input_ids=decoder_input_ids).last_hidden_state
>>> list(last_hidden_state.shape)
[1, 2, 288]

MoonshineStreamingForConditionalGeneration

class transformers.MoonshineStreamingForConditionalGeneration

< >

( config: MoonshineStreamingConfig )

参数

  • config (MoonshineStreamingConfig) — 模型的配置类,包含模型的所有参数。通过配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

带有语言建模头的 MoonshineStreaming 模型。可用于自动语音识别。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_values: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.LongTensor] = Noneencoder_outputs: tuple[tuple[torch.Tensor]] | None = Nonepast_key_values: transformers.cache_utils.EncoderDecoderCache | None = Nonedecoder_inputs_embeds: tuple[torch.Tensor] | None = Nonedecoder_position_ids: tuple[torch.LongTensor] | None = Noneuse_cache: bool | None = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Seq2SeqLMOutput or tuple(torch.Tensor)

参数

  • input_values(形状为 (batch_size, audio_length) 的 torch.Tensor)— 原始语音波形的浮点值。可以通过将 .flac 或 .wav 音频文件加载为 list[float]、numpy.ndarray 或 torch.Tensor 类型的数组来获取原始语音波形,例如 使用 torchcodec 库(pip install torchcodec)或 soundfile 库(pip install soundfile)。要将该数组处理为 input_values,应使用 AutoFeatureExtractor 进行填充并将其转换为 torch.Tensor 类型的张量。
  • attention_mask (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充(padding)标记索引执行注意力机制的掩码。掩码值取自 [0, 1]:1 表示未屏蔽的标记,0 表示被屏蔽的标记。什么是注意力掩码? [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor 形状为 (batch_size, target_sequence_length), ,可选) — 解码器输入序列中各 token 在词汇表中的索引。可通过 AutoTokenizer 获取索引。详情请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是解码器输入 ID?

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是解码器输入 ID?

  • decoder_attention_mask(形状为 (batch_size, target_sequence_length) 的 torch.LongTensor,可选) — 用于避免对特定 token 索引执行注意力的掩码。默认情况下,会使用因果掩码,以确保模型只能查看之前的输入来预测未来。
  • encoder_outputs (tuple[tuple[torch.Tensor]],可选) — 元组由 (last_hidden_state,可选:hidden_states,可选:attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size),可选) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力。
  • past_key_values (~cache_utils.EncoderDecoderCache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 past_key_values,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • decoder_inputs_embeds (tuple[torch.Tensor] 形状为 (batch_size, target_sequence_length, hidden_size), 可选) — 可选地,除了传递 decoder_input_ids 之外,您还可以选择直接传递嵌入表示。如果使用了 past_key_values ,则只需输入最后一个 decoder_inputs_embeds (参见 past_key_values). 如果您希望对 decoder_input_ids 索引如何转换为对应的向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。

    如果 decoder_input_ids 和 decoder_inputs_embeds 均未设置,decoder_inputs_embeds 将取 inputs_embeds 的值。

  • decoder_position_ids (torch.LongTensor,形状为 (batch_size, target_sequence_length)) — 输入序列中每个 token 在位置嵌入中的位置索引。 用于计算直至 config.decoder_config.max_position_embeddings 的位置嵌入。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。

返回值

Seq2SeqLMOutput 或 tuple(torch.Tensor)

一个 Seq2SeqLMOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MoonshineStreamingConfig)和输入。

MoonshineStreamingForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • loss(形状为 (1,) 的 torch.Tensor,可选,在提供 labels 时返回)— 语言建模损失。

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。

  • past_key_values(EncoderDecoderCache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 EncoderDecoderCache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • decoder_hidden_states (tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    解码器在每一层输出处的隐藏状态,以及初始嵌入输出。

  • decoder_attentions (tuple(torch.Tensor),可选,在传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    解码器在注意力 softmax 之后的注意力权重,用于在自注意力头中计算加权平均值。

  • cross_attentions (tuple(torch.Tensor),可选,在传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    解码器交叉注意力层在注意力 softmax 之后的注意力权重,用于在交叉注意力头中计算加权平均值。

  • encoder_last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选)— 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_states (tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    编码器在每一层输出处的隐藏状态,以及初始嵌入输出。

  • encoder_attentions(tuple(torch.Tensor),可选,在传入 output_attentions=True 或 config.output_attentions=True 时返回)—— 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    编码器在注意力 softmax 之后的注意力权重,用于在自注意力头中计算加权平均值。

示例:

>>> import torch
>>> from transformers import AutoProcessor, MoonshineStreamingForConditionalGeneration
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("UsefulSensors/moonshine_streaming-tiny")
>>> model = MoonshineStreamingForConditionalGeneration.from_pretrained("UsefulSensors/moonshine_streaming-tiny")

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")

>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_values = inputs.input_values

>>> generated_ids = model.generate(input_values, max_new_tokens=100)

>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> transcription
'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'

generate

< >

( inputs: typing.Optional[torch.Tensor] = Nonegeneration_config: transformers.generation.configuration_utils.GenerationConfig | None = Nonelogits_processor: transformers.generation.logits_process.LogitsProcessorList | None = Nonestopping_criteria: transformers.generation.stopping_criteria.StoppingCriteriaList | None = Noneprefix_allowed_tokens_fn: collections.abc.Callable[[int, torch.Tensor], list[int]] | None = Nonesynced_gpus: bool | None = Noneassistant_model: typing.Optional[ForwardRef('PreTrainedModel')] = Nonestreamer: typing.Optional[ForwardRef('BaseStreamer')] = Nonenegative_prompt_ids: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonecustom_generate: str | collections.abc.Callable | None = None**kwargs ) → ModelOutput or torch.LongTensor

参数

  • inputs(形状因模态而异的 torch.Tensor,可选)— 用作生成提示的序列,或作为编码器的模型输入。如果为 None,该方法将使用 bos_token_id 和批大小 1 对其进行初始化。对于仅解码器模型,inputs 应采用 input_ids 的格式。对于编码器-解码器模型,inputs 可以是 input_ids、input_values、input_features 或 pixel_values 中的任意一种。
  • generation_config (GenerationConfig, 可选) — 用作生成调用基础参数化的生成配置。传递给 generate 且与 generation_config 属性匹配的 **kwargs 将覆盖这些属性。如果未提供 generation_config,则使用默认值,其加载优先级如下:1) 如果存在 generation_config.json 模型文件,则从中加载;2) 从模型配置中加载。请注意,未指定的参数将继承 GenerationConfig 的默认值,应查阅其文档以参数化生成。
  • logits_processor (LogitsProcessorList, 可选) — 自定义的 logits 处理器,用于补充由参数和生成配置构建的默认 logits 处理器。如果传入的 logit 处理器已经由参数或生成配置创建,则会抛出错误。此功能面向高级用户。
  • stopping_criteria (StoppingCriteriaList,可选) — 自定义停止条件,用于补充由参数和生成配置构建的默认停止条件。如果传入的停止条件已经由参数或生成配置创建,则会抛出错误。如果你的停止条件依赖于 scores 输入,请确保向 generate 传入 return_dict_in_generate=True, output_scores=True。此功能面向高级用户。
  • prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], list[int]], 可选) — 如果提供,此函数会在每一步将束搜索限制为仅使用允许的 token。如果未提供,则不施加任何约束。此函数接受 2 个参数:批次 ID batch_id 和 input_ids。它必须返回一个列表,其中包含根据批次 ID batch_id 和之前生成的 token inputs_ids 条件化后,用于下一步生成的允许 token。此参数对于基于前缀的约束生成非常有用,如 Autoregressive Entity Retrieval 中所述。
  • synced_gpus (bool, 可选) — 是否继续执行 while 循环直到达到 max_length。除非被覆盖,否则在使用 FullyShardedDataParallel 或 DeepSpeed ZeRO Stage 3 且涉及多 GPU 时,此标志将设置为 True,以避免某个 GPU 在其他 GPU 之前完成生成时发生死锁。否则,默认为 False。
  • assistant_model (PreTrainedModel, 可选) — 可用于加速生成的辅助模型。辅助模型必须使用完全相同的 tokenizer。当使用辅助模型预测候选 token 的速度远快于从你调用 generate 的模型运行生成时,即可实现加速。因此,辅助模型应小得多。
  • streamer (BaseStreamer,可选) — 用于流式传输生成序列的 Streamer 对象。生成的 token 会通过 streamer.put(token_ids) 传入,由 streamer 负责后续处理。
  • negative_prompt_ids(形状为 (batch_size, sequence_length) 的 torch.LongTensor,可选) — 某些处理器(例如 CFG)所需的负面提示。批处理大小必须与输入批处理大小相匹配。这是一个实验性功能,未来版本中可能会发生破坏性的 API 变更。
  • negative_prompt_attention_mask(形状为 (batch_size, sequence_length) 的 torch.LongTensor,可选)— negative_prompt_ids 的 attention_mask。
  • custom_generate (str 或 Callable, 可选) — 以下之一:
    • str(Hugging Face Hub 仓库名称):运行该仓库中 custom_generate/generate.py 定义的自定义 generate 函数,而不是标准的 generate 方法。该仓库会完全替换生成逻辑,且返回类型可能有所不同。
    • str(本地仓库路径):与上述相同,但来自本地路径。本地目录也需要 trust_remote_code=True,因为会执行本地的 custom_generate/generate.py。
    • Callable:generate 将执行常规的输入准备步骤,然后调用提供的可调用对象来运行解码循环。 有关更多信息,请参阅 文档。
  • kwargs (dict[str, Any], 可选) — generation_config 的临时参数设置,和/或将被转发给模型 forward 函数的额外模型特定 kwargs。如果模型是编码器-解码器模型,编码器特定的 kwargs 不应添加前缀,而解码器特定的 kwargs 应以 decoder_ 作为前缀。

返回值

ModelOutput 或 torch.LongTensor

ModelOutput(当 return_dict_in_generate=True 或 config.return_dict_in_generate=True 时)或 torch.LongTensor。

如果模型不是编码器-解码器模型(model.config.is_encoder_decoder=False),可能的 ModelOutput 类型为:

如果模型是编码器-解码器模型(model.config.is_encoder_decoder=True),则可能的 ModelOutput 类型为:

为具有语言建模头的模型生成 token id 序列。

大多数生成控制参数都在 generation_config 中设置,如果未传入该参数,则会使用模型的默认生成配置。你可以通过向 generate() 传入相应参数来覆盖 generation_config 中的任意设置,例如 .generate(inputs, num_beams=4, do_sample=True)。

有关生成策略和代码示例的概述,请参阅以下指南。

Update on GitHub