# Granite Speech Plus

## 概要

Granite Speech Plus は [Granite Speech](./granite_speech) のバリアントであり、そのプロジェクターは、エンコーダーの最終層の隠れ状態と、その中間層の隠れ状態の任意の部分集合を特徴量次元に沿って連結したものを消費します。選択される中間層は、[GraniteSpeechPlusEncoderConfig](/docs/transformers/main/ja/model_doc/granite_speech_plus#transformers.GraniteSpeechPlusEncoderConfig) の `cat_hidden_layers` 設定フィールドによって制御されます。`None` の場合、モデルは Granite Speech と完全に同じ挙動をします。設定されている場合、プロジェクターの `encoder_hidden_size` は `encoder_config.hidden_dim * (len(cat_hidden_layers) + 1)` と等しくなければなりません。

アーキテクチャの残りの部分、すなわち音声エンコーダー、クエリトランスフォーマープロジェクター、言語モデル、および任意のLoRAアダプターは、Granite Speechから変更なしに継承されています。使用例については、[Granite Speechのドキュメント](./granite_speech)を参照してください。ここでは、同じ[GraniteSpeechProcessor](/docs/transformers/main/ja/model_doc/granite_speech#transformers.GraniteSpeechProcessor)と[GraniteSpeechFeatureExtractor](/docs/transformers/main/ja/model_doc/granite_speech#transformers.GraniteSpeechFeatureExtractor)が使用されます。

## 使用方法

Granite Speech Plus は、テキストプロンプトへの応答を通じて、音声の文字起こし、話者アノテーション、単語レベルのタイムスタンプの提供を行うことができるマルチモーダルな音声認識モデルです。各機能の使用方法は以下の通りです。

**セットアップ** — モデルとテスト用の音声クリップを読み込みます:

```python
import re
import torch
from datasets import Audio, load_dataset
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor

SAMPLE_RATE = 16000
MODEL_NAME = "ibm-granite/granite-speech-4.1-2b-plus"
```

異なるタスクで使用されるプロンプトを定義します:

```python
SYSTEM_PROMPT = "Knowledge Cutoff Date: April 2024.\nToday's Date: December 19, 2024.\nYou are Granite, developed by IBM. You are a helpful AI assistant"
ASR_PROMPT = "<|audio|> can you transcribe the speech into a written format?"
SAA_PROMPT = "<|audio|> Speaker attribution: Transcribe and denote who is speaking by adding [Speaker 1]: and [Speaker 2]: tags before speaker turns."
TS_PROMPT = "<|audio|> Timestamps: Transcribe the speech. After each word, add a timestamp tag showing the end time in centiseconds, e.g. hello [T:45] world [T:82]"
```

モデルを読み込み、オーディオのデコードを行う汎用関数を定義します:

```python
processor = AutoProcessor.from_pretrained(MODEL_NAME)
model = AutoModelForSpeechSeq2Seq.from_pretrained(MODEL_NAME, device_map="auto")

@torch.inference_mode()
def transcribe(audio, prompt, max_new_tokens=2000, prefix_text=None):
    chat = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}]
    extra = {"prefix_text": prefix_text} if prefix_text is not None else {}
    prompt_text = processor.apply_chat_template(chat, tokenize=False, add_generation_prompt=True, **extra)
    inputs = processor(prompt_text, audio, device=device, return_tensors="pt").to(device)
    outputs = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False, num_beams=1)
    new_tokens = outputs[0, inputs["input_ids"].shape[-1]:]
    output_text = processor.decode(new_tokens, add_special_tokens=False, skip_special_tokens=True)
    return output_text
```

AMIデータセットからサンプル音声データを読み込みます

```python
ds = load_dataset("diarizers-community/ami", "ihm", split="test")
ds = ds.cast_column("audio", Audio(sampling_rate=SAMPLE_RATE, num_channels=1))

TEST_SAMPLE = 0
START_TIME, END_TIME = 5 * 60, 6 * 60
audio = ds["audio"][TEST_SAMPLE].get_samples_played_in_range(START_TIME, END_TIME)
```

**タスク 1: ASR** — 通常の音声からテキストへの書き起こし:

```python
asr_text = transcribe(audio.data, ASR_PROMPT)
print(asr_text)
```

**タスク 2: 話者属性付き ASR** — 話者ラベル付きの文字起こし:

```python
saa_text = transcribe(audio.data, SAA_PROMPT)
for segment in re.split(r"(\[Speaker \d+\]:)", saa_text):
    print(segment.strip())
```

**タスク 3: ワードレベルのタイムスタンプ** — ワードごとのタイミング付き転写:

タイムスタンプは1/100秒単位で与えられ、1000（=10秒）でモジュロ（剰余）がとられているため、10秒の整数倍を加算してアンラップ（展開）する必要があります。

```python
ts_text = transcribe(audio.data, TS_PROMPT, max_new_tokens=10000)
ts_words = re.split(r"\[T:(\d+)\]", ts_text)
last_word_end_time = 0
offset_time = 0
for word, ts in zip(ts_words[::2], ts_words[1::2]):
    word_end_time = float(ts) / 100
    while word_end_time + offset_time < last_word_end_time:
        offset_time += 10
    last_word_end_time = word_end_time + offset_time
    print(f"{word}\t{last_word_end_time:.2f}s")
```

**タスク 4: 増分デコーディング** — 音声コンテキストを蓄積しながらセグメントを文字起こしします:

```python
NUM_SEGMENTS = 3
previous_transcript = ""
all_audio = None

for k in range(NUM_SEGMENTS):
    t1 = START_TIME + (END_TIME - START_TIME) * k / NUM_SEGMENTS
    t2 = START_TIME + (END_TIME - START_TIME) * (k + 1) / NUM_SEGMENTS
    new_audio = ds["audio"][TEST_SAMPLE].get_samples_played_in_range(t1, t2)
    all_audio = new_audio.data if all_audio is None else torch.cat([all_audio, new_audio.data], dim=-1)
    saa_text = transcribe(all_audio, SAA_PROMPT, prefix_text=previous_transcript)
    print(f"{t1:06.2f}-{t2:06.2f}:\t{saa_text}")
    previous_transcript = (previous_transcript + " " + saa_text).strip()
```

## GraniteSpeechPlusConfig[[transformers.GraniteSpeechPlusConfig]]

#### transformers.GraniteSpeechPlusConfig[[transformers.GraniteSpeechPlusConfig]]

```python
transformers.GraniteSpeechPlusConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, projector_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, audio_token_index: int = 49155, initializer_range: float = 0.02, has_lora_adapter: bool = True, downsample_rate: int = 5, window_size: int = 15, tie_word_embeddings: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/granite_speech_plus/configuration_granite_speech_plus.py#L95)

**パラメータ:**

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *任意*) : テキストバックボーンの config オブジェクトまたは辞書。

encoder_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`、*optional*) : エンコーダーのバックボーンの設定オブジェクトまたは辞書。

projector_config (`Union[AutoConfig, dict]`、*任意*、デフォルトは`Blip2QFormerConfig`) : 音声プロジェクターの config オブジェクトまたは辞書。

audio_token_index (`int`、*任意*、デフォルトは`49155`) : 入力音声のプレースホルダーとして使用される音声トークンインデックス。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

has_lora_adapter (`bool`、*任意*、デフォルトは`True`) : モデルに、音声入力の処理時のみ有効化すべき LoRA アダプターが存在するかどうかを示します。

downsample_rate (`int`、*optional*、デフォルト値は 5) : 音声特徴抽出器のダウンサンプル率。

window_size (`int`、*optional*、デフォルトは 15) : 音声特徴量プロジェクターのウィンドウサイズ。

tie_word_embeddings (`bool`、*任意*、デフォルトは`True`) : モデルの`tied_weights_keys`マッピングに従って重み埋め込みを共有するかどうか。

これはGraniteSpeechPlusModelの設定を保存するための設定クラスです。指定された引数に基づいてGranite Speech Plusモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[ibm-granite/granite-speech-4.1-2b-plus](https://huggingface.co/ibm-granite/granite-speech-4.1-2b-plus)と類似した設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

```python
>>> from transformers import GraniteSpeechPlusConfig, GraniteSpeechPlusForConditionalGeneration

>>> # Initializing a GraniteSpeechPlusConfig
>>> configuration = GraniteSpeechPlusConfig()

>>> # Initializing a GraniteSpeechPlusForConditionalGeneration (with random weights)
>>> model = GraniteSpeechPlusForConditionalGeneration(configuration)

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

## GraniteSpeechPlusEncoderConfig[[transformers.GraniteSpeechPlusEncoderConfig]]

#### transformers.GraniteSpeechPlusEncoderConfig[[transformers.GraniteSpeechPlusEncoderConfig]]

```python
transformers.GraniteSpeechPlusEncoderConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, input_dim: int = 160, num_layers: int = 10, hidden_dim: int = 1024, feedforward_mult: int = 4, num_heads: int = 8, dim_head: int | None = None, output_dim: int = 42, context_size: int = 200, max_pos_emb: int = 512, dropout: float | int = 0.1, conv_kernel_size: int = 15, conv_expansion_factor: int = 2, cat_hidden_layers: list[int] | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/granite_speech_plus/configuration_granite_speech_plus.py#L29)

**パラメータ:**

input_dim (*int*、*optional*、デフォルトは *160*) : 入力音声特徴量の次元数（例：メルフィルタバンクのチャネル数）。

num_layers (*int*、*optional*、デフォルトは *10*) : Transformer デコーダーの隠れ層の数。

hidden_dim (*int*、*optional*、デフォルトは *1024*) : 隠れ表現の次元数。

feedforward_mult (*int*、*optional*、デフォルト値は 4) : エンコーダーのフィードフォワード層におけるアップ/ダウン投影の倍率です。投影の中間次元は *hidden_dim * feedforward_mult* になります。

num_heads (*int*、*optional*、デフォルトは *8*) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

dim_head (*int*, *optional*) : アテンションヘッドの次元です。None の場合、hidden_size // num_attention_heads がデフォルト値として使用されます。

output_dim (*int*、*optional*、デフォルト値は 42) : conformer に追加される、他のすべてのエンコーダーブロックの出力に足し込まれるフィードフォワード投影の中間次元。

context_size (*int*、*optional*、デフォルト値は 200) : conformer attention で使用されるコンテキストサイズ。

max_pos_emb (*int*, *optional*, デフォルト値は 512) : attention で使用する最大位置埋め込み数（shaw の相対位置エンコーディング）。

dropout (*Union[float, int]*、*optional*、デフォルトは *0.1*) : 全 dropout レイヤーの比率です。

conv_kernel_size (*int*、*optional*、デフォルトは *15*) : 畳み込みカーネルのサイズです。

conv_expansion_factor (*int*、*optional*、デフォルトは 2) : conformer の畳み込みで使用する中間次元。

cat_hidden_layers (*list[int]*, *optional*) : 最終エンコーダー出力に渡す前に、特徴量次元に沿って連結されるエンコーダー conformer レイヤーのインデックスです。設定した場合、projector の `encoder_hidden_size` は `encoder_config.hidden_dim * (len(cat_hidden_layers) + 1)` と等しくなければなりません。

これはGraniteSpeechPlusModelの設定を保存するための設定クラスです。指定された引数に基づいてGranite Speech Plusモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[ibm-granite/granite-speech-4.1-2b-plus](https://huggingface.co/ibm-granite/granite-speech-4.1-2b-plus)と類似した設定が得られます。

設定オブジェクトは [*PreTrainedConfig*] を継承し、モデルの出力を制御するために使用できます。詳細については、[*PreTrainedConfig*] のドキュメントを参照してください。

例:

```python
>>> from transformers import GraniteSpeechPlusEncoderConfig, GraniteSpeechPlusCTCEncoder

>>> # Initializing a GraniteSpeechPlusEncoderConfig
>>> configuration = GraniteSpeechPlusEncoderConfig()

>>> # Initializing a GraniteSpeechPlusCTCEncoder (with random weights)
>>> model = GraniteSpeechPlusCTCEncoder(configuration)

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

## GraniteSpeechPlusModel[[transformers.GraniteSpeechPlusModel]]

#### transformers.GraniteSpeechPlusModel[[transformers.GraniteSpeechPlusModel]]

```python
transformers.GraniteSpeechPlusModel(config: GraniteSpeechPlusConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/granite_speech_plus/modeling_granite_speech_plus.py#L131)

**パラメータ:**

config ([GraniteSpeechPlusConfig](/docs/transformers/main/ja/model_doc/granite_speech_plus#transformers.GraniteSpeechPlusConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを参照してください。

言語モデリングヘッドを含まない、オーディオエンコーダー、プロジェクター、言語モデルで構成される Granite Speech モデル。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.GraniteSpeechPlusModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, input_features: typing.Optional[torch.Tensor] = None, input_features_mask: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/granite_speech_plus/modeling_granite_speech_plus.py#L204)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

input_features (`torch.Tensor`、形状 `(batch_size, sequence_length, feature_dim)`、*任意*) : 入力音声特徴に対応するテンソルです。音声特徴は [GraniteSpeechFeatureExtractor](/docs/transformers/main/ja/model_doc/granite_speech#transformers.GraniteSpeechFeatureExtractor) を使用して取得できます。詳細は `GraniteSpeechFeatureExtractor.__call__()` を参照してください（[GraniteSpeechProcessor](/docs/transformers/main/ja/model_doc/granite_speech#transformers.GraniteSpeechProcessor) は音声の処理に [GraniteSpeechFeatureExtractor](/docs/transformers/main/ja/model_doc/granite_speech#transformers.GraniteSpeechFeatureExtractor) を使用します）。

input_features_mask (`torch.Tensor`, *任意*) : 言語埋め込みに散りばめる前に、音声特徴量に適用されるマスク。

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

position_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックスです。`[0, config.n_positions - 1]` の範囲から選択されます。 [位置 ID とは何か？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`, *任意*) : 逐次デコードを高速化するために使用できる、事前計算された hidden-states（self-attention ブロックおよび cross-attention ブロック内の key と value）です。通常、`use_cache=True` または `config.use_cache=True` の場合、モデルがデコードの以前の段階で返した `past_key_values` で構成されます。入力として許可されるのは [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/main/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

inputs_embeds (`torch.Tensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、`input_ids` のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。

use_cache (`bool`, *任意*) : `True`に設定すると、`past_key_values`のキーバリュー状態が返され、デコーディングの高速化に利用できます（`past_key_values`を参照）。

**戻り値:** `GraniteSpeechPlusModelOutputWithPast` または `tuple(torch.Tensor)`

`GraniteSpeechPlusModelOutputWithPast`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[GraniteSpeechPlusConfig](/docs/transformers/main/ja/model_doc/granite_speech_plus#transformers.GraniteSpeechPlusConfig)）や入力に応じて、さまざまな要素で構成されます。

[GraniteSpeechPlusModel](/docs/transformers/main/ja/model_doc/granite_speech_plus#transformers.GraniteSpeechPlusModel)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。

  `past_key_values`が使用されている場合、出力されるのは、形状`(batch_size, 1, hidden_size)`のシーケンスの最後の隠れ状態のみです。
- **past_key_values** (`Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。

  自己アテンションブロック（および `config.is_encoder_decoder=True` の場合、クロスカレンションブロック）の事前計算済みヒドゥンステート（キーとバリュー）を保持します。これらは逐次デコーディングを高速化するために使用できます（`past_key_values` 入力参照）。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **audio_hidden_states** (`torch.Tensor`、*任意*) -- 投影されたオーディオの隠れ状態。

## GraniteSpeechPlusForConditionalGeneration[[transformers.GraniteSpeechPlusForConditionalGeneration]]

#### transformers.GraniteSpeechPlusForConditionalGeneration[[transformers.GraniteSpeechPlusForConditionalGeneration]]

```python
transformers.GraniteSpeechPlusForConditionalGeneration(config: GraniteSpeechPlusConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/granite_speech_plus/modeling_granite_speech_plus.py#L517)

**パラメータ:**

config ([GraniteSpeechPlusConfig](/docs/transformers/main/ja/model_doc/granite_speech_plus#transformers.GraniteSpeechPlusConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを参照してください。

Granite Speech Plus モデルは、Granite Speech のバリアントであり、そのプロジェクターはエンコーダーの最終隠れ状態と、その中間隠れ状態の任意の部分集合の連結を消費します。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.GraniteSpeechPlusForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, input_features: typing.Optional[torch.Tensor] = None, input_features_mask: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/granite_speech_plus/modeling_granite_speech_plus.py#L539)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

input_features (`torch.Tensor`、形状 `(batch_size, sequence_length, feature_dim)`、*任意*) : 入力音声特徴に対応するテンソルです。音声特徴は [GraniteSpeechFeatureExtractor](/docs/transformers/main/ja/model_doc/granite_speech#transformers.GraniteSpeechFeatureExtractor) を使用して取得できます。詳細は `GraniteSpeechFeatureExtractor.__call__()` を参照してください（[GraniteSpeechProcessor](/docs/transformers/main/ja/model_doc/granite_speech#transformers.GraniteSpeechProcessor) は音声の処理に [GraniteSpeechFeatureExtractor](/docs/transformers/main/ja/model_doc/granite_speech#transformers.GraniteSpeechFeatureExtractor) を使用します）。

input_features_mask (`torch.Tensor`, *任意*) : 言語埋め込みに散りばめる前に、音声特徴量に適用されるマスク。

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

position_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックスです。`[0, config.n_positions - 1]` の範囲から選択されます。 [位置 ID とは何か？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`, *任意*) : 逐次デコードを高速化するために使用できる、事前計算された hidden-states（self-attention ブロックおよび cross-attention ブロック内の key と value）です。通常、`use_cache=True` または `config.use_cache=True` の場合、モデルがデコードの以前の段階で返した `past_key_values` で構成されます。入力として許可されるのは [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/main/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

inputs_embeds (`torch.Tensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、`input_ids` のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。

labels (`torch.LongTensor`、形状 `(batch_size, sequence_length)`、*任意*) : マスク言語モデリング損失を計算するためのラベル。インデックスは `[0, ..., config.vocab_size]` の範囲内であるか、-100 である必要があります（`input_ids` のドキュメント文字列を参照）。インデックスが `-100` に設定されたトークンは無視（マスク）され、損失は `[0, ..., config.vocab_size]` の範囲内のラベルを持つトークンに対してのみ計算されます。

use_cache (`bool`, *任意*) : `True`に設定すると、`past_key_values`のキーバリュー状態が返され、デコーディングの高速化に利用できます（`past_key_values`を参照）。

logits_to_keep (`Union[int, torch.Tensor]`、*任意*、デフォルトは `0`) : `int` の場合、最後の `logits_to_keep` トークンについて logits を計算します。`0` の場合、すべての `input_ids` について logits を計算します（特殊ケース）。生成には最後のトークンの logits だけで十分であり、そのトークンのみについて計算することでメモリを節約できます。これは、長いシーケンスや大規模な語彙サイズの場合に特に顕著な効果があります。`torch.Tensor` の場合、シーケンス長次元で保持するインデックスに対応する 1 次元である必要があります。これは、パックされたテンソル形式（バッチとシーケンス長を単一の次元にまとめる形式）を使用する場合に有用です。

**戻り値:** `GraniteSpeechPlusCausalLMOutputWithPast` または `tuple(torch.Tensor)`

`GraniteSpeechPlusCausalLMOutputWithPast` または、`return_dict=False` が渡された場合、または `config.return_dict=False` の場合、`torch.Tensor` のタプル。構成（[GraniteSpeechPlusConfig](/docs/transformers/main/ja/model_doc/granite_speech_plus#transformers.GraniteSpeechPlusConfig)）や入力に応じて、さまざまな要素で構成されます。

[GraniteSpeechPlusForConditionalGeneration](/docs/transformers/main/ja/model_doc/granite_speech_plus#transformers.GraniteSpeechPlusForConditionalGeneration)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **loss** (`torch.Tensor`、形状 `(1,)`、*任意*、`labels` が指定された場合に返されます) -- 言語モデリングの損失(次のトークンの予測用)。
- **logits** (`torch.Tensor`、形状 `(batch_size, sequence_length, config.vocab_size)`) -- 言語モデリングヘッドの予測スコア（SoftMax 適用前の各語彙トークンのスコア）。
- **past_key_values** (`Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。

  逐次デコーディングを高速化するために使用できる（`past_key_values` 入力参照）、事前計算済みの隠れ状態（自己注意ブロックのキーとバリュー）が含まれます。
- **hidden_states** (`tuple[torch.Tensor]`、*optional*、`output_hidden_states=True` が渡された場合、または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple[torch.Tensor]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **audio_hidden_states** (`torch.Tensor`、*任意*) -- 投影されたオーディオの隠れ状態。

例:

```python
>>> from transformers import AutoProcessor, GraniteSpeechPlusForConditionalGeneration
>>> from datasets import load_dataset
>>> import torch

>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")
>>> sampling_rate = dataset.features["audio"].sampling_rate

>>> processor = AutoProcessor.from_pretrained("ibm-granite/granite-speech-4.1-2b-plus")
>>> model = GraniteSpeechPlusForConditionalGeneration.from_pretrained("ibm-granite/granite-speech-4.1-2b-plus")

>>> # audio file is decoded on the fly
>>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
>>> with torch.no_grad():
...     logits = model(**inputs).logits
>>> predicted_ids = torch.argmax(logits, dim=-1)

>>> # transcribe speech
>>> transcription = processor.batch_decode(predicted_ids)
>>> transcription[0]
...

>>> inputs["labels"] = processor(text=dataset[0]["text"], return_tensors="pt").input_ids

>>> # compute loss
>>> loss = model(**inputs).loss
>>> round(loss.item(), 2)
...
```

#### get_audio_features[[transformers.GraniteSpeechPlusForConditionalGeneration.get_audio_features]]

```python
get_audio_features(*args, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/granite_speech_plus/modeling_granite_speech_plus.py#L536)

