# Csm

## 概要

Conversational Speech Model (CSM) は、[Sesame が公開した](https://www.sesame.com/research/crossing_the_uncanny_valley_of_voice)最初のオープンソースのコンテキスト付きテキスト読み上げモデルです。会話コンテキストの有無にかかわらず、自然な音声の生成を目的として設計されています。このコンテキストは、話者間のマルチターン対話で構成され、テキストのシーケンスとそれに対応する発話音声として表現されます。

**モデルアーキテクチャ:** CSMは、2つのLLaMAスタイルの自己回帰型Transformerデコーダーで構成されています。1つは最初のコードブックトークンを予測するバックボーンデコーダー、もう1つは残りのトークンを生成する深度デコーダーです。音声を離散コードブックトークンにエンコードし、それを音声にデコードするために、Kyutaiが発表した事前学習済みコーデックモデル[Mimi](./mimi)を使用しています。

元のcsm-1bチェックポイントは、Hugging Face上の[Sesame](https://huggingface.co/sesame/csm-1b)組織の下で利用できます。

    

> [!TIP]
> `use_kernels=True` を [from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) に設定すると、対応するレイヤーが Hub からの最適化されたカーネルに置き換えられます。詳細は [カーネルの読み込み](../kernel_doc/loading_kernels) を参照してください。

## 使用のコツ

### 会話コンテキストなし

CSMは、テキストプロンプトから簡単に音声生成を行うために使用できます。

```python
from transformers import AutoProcessor, CsmForConditionalGeneration

model_id = "sesame/csm-1b"

# load the model and the processor
processor = AutoProcessor.from_pretrained(model_id)
model = CsmForConditionalGeneration.from_pretrained(model_id, device_map="auto")

# prepare the inputs
text = "[0]The past is just a story we tell ourselves." # `[0]` for speaker id 0
inputs = processor(text, add_special_tokens=True).to(model.device)

# another equivalent way to prepare the inputs
conversation = [
    {"role": "0", "content": [{"type": "text", "text": "The past is just a story we tell ourselves."}]},
]
inputs = processor.apply_chat_template(
    conversation,
    tokenize=True,
    return_dict=True,
).to(model.device)

# infer the model
audio = model.generate(**inputs, output_audio=True)
processor.save_audio(audio, "example_without_context.wav")
```

### 会話コンテキスト付き

CSM は、会話に基づいて音声の生成に使用でき、声の一致を保ちながら、内容に応じた生成を行うことができます:

```python
from datasets import Audio, load_dataset

from transformers import AutoProcessor, CsmForConditionalGeneration

model_id = "sesame/csm-1b"

# load the model and the processor
processor = AutoProcessor.from_pretrained(model_id)
model = CsmForConditionalGeneration.from_pretrained(model_id, device_map="auto")

# prepare the inputs
ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
# ensure the audio is 24kHz
ds = ds.cast_column("audio", Audio(sampling_rate=24000))
conversation = []

# 1. context
for text, audio, speaker_id in zip(ds[:4]["text"], ds[:4]["audio"], ds[:4]["speaker_id"]):
    conversation.append(
        {
            "role": f"{speaker_id}",
            "content": [{"type": "text", "text": text}, {"type": "audio", "path": audio["array"]}],
        }
    )

# 2. text prompt
conversation.append({"role": f"{ds[4]['speaker_id']}", "content": [{"type": "text", "text": ds[4]["text"]}]})

inputs = processor.apply_chat_template(
    conversation,
    tokenize=True,
    return_dict=True,
).to(model.device)

# infer the model
audio = model.generate(**inputs, output_audio=True)
processor.save_audio(audio, "example_with_context.wav")
```

### バッチ推論

CSMはバッチ推論をサポートしています!

```python
from datasets import Audio, load_dataset

from transformers import AutoProcessor, CsmForConditionalGeneration

model_id = "sesame/csm-1b"

# load the model and the processor
processor = AutoProcessor.from_pretrained(model_id)
model = CsmForConditionalGeneration.from_pretrained(model_id, device_map="auto")

# prepare the inputs
ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
# ensure the audio is 24kHz
ds = ds.cast_column("audio", Audio(sampling_rate=24000))
# here a batch with two prompts
conversation = [
    [
        {
            "role": f"{ds[0]['speaker_id']}",
            "content": [
                {"type": "text", "text": ds[0]["text"]},
                {"type": "audio", "path": ds[0]["audio"]["array"]},
            ],
        },
        {
            "role": f"{ds[1]['speaker_id']}",
            "content": [
                {"type": "text", "text": ds[1]["text"]},
            ],
        },
    ],
    [
        {
            "role": f"{ds[0]['speaker_id']}",
            "content": [
                {"type": "text", "text": ds[0]["text"]},
            ],
        }
    ],
]
inputs = processor.apply_chat_template(
    conversation,
    tokenize=True,
    return_dict=True,
).to(model.device)

audio = model.generate(**inputs, output_audio=True)
processor.save_audio(audio, [f"speech_batch_idx_{i}.wav" for i in range(len(audio))])
```

### モデルを高速に動かす

CSMはCUDA graphsによるグラフ全体のコンパイルをサポートしています!

```python

import torch
from datasets import load_dataset

from transformers import AutoProcessor, CsmForConditionalGeneration

model_id = "sesame/csm-1b"

# set logs to ensure no recompilation and graph breaks
torch._logging.set_logs(graph_breaks=True, recompiles=True, cudagraphs=True)

# load the model and the processor
processor = AutoProcessor.from_pretrained(model_id)
model = CsmForConditionalGeneration.from_pretrained(model_id, device_map="auto")

# use static cache, enabling automatically torch compile with fullgraph and reduce-overhead
model.generation_config.max_length = 250 # big enough to avoid recompilation
model.generation_config.max_new_tokens = None # would take precedence over max_length
model.generation_config.cache_implementation = "static"
model.depth_decoder.generation_config.cache_implementation = "static"

# generation kwargs
gen_kwargs = {
    "do_sample": False,
    "depth_decoder_do_sample": False,
    "temperature": 1.0,
    "depth_decoder_temperature": 1.0,
}

# Define a timing decorator
class TimerContext:
    def __init__(self, name="Execution"):
        self.name = name
        self.start_event = None
        self.end_event = None

    def __enter__(self):
        # Use CUDA events for more accurate GPU timing
        self.start_event = torch.cuda.Event(enable_timing=True)
        self.end_event = torch.cuda.Event(enable_timing=True)
        self.start_event.record()
        return self

    def __exit__(self, *args):
        self.end_event.record()
        torch.cuda.synchronize()
        elapsed_time = self.start_event.elapsed_time(self.end_event) / 1000.0
        print(f"{self.name} time: {elapsed_time:.4f} seconds")

# prepare the inputs
ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")

conversation = [
    {
        "role": f"{ds[0]['speaker_id']}",
        "content": [
            {"type": "text", "text": ds[0]["text"]},
            {"type": "audio", "path": ds[0]["audio"]["array"]},
        ],
    },
    {
        "role": f"{ds[1]['speaker_id']}",
        "content": [
            {"type": "text", "text": ds[1]["text"]},
            {"type": "audio", "path": ds[1]["audio"]["array"]},
        ],
    },
    {
        "role": f"{ds[2]['speaker_id']}",
        "content": [
            {"type": "text", "text": ds[2]["text"]},
        ],
    },
]

padded_inputs_1 = processor.apply_chat_template(
    conversation,
    tokenize=True,
    return_dict=True,
).to(model.device)

print("\n" + "="*50)
print("First generation - compiling and recording CUDA graphs...")
with TimerContext("First generation"):
    _ = model.generate(**padded_inputs_1, **gen_kwargs)
print("="*50)

print("\n" + "="*50)
print("Second generation - fast !!!")
with TimerContext("Second generation"):
    _ = model.generate(**padded_inputs_1, **gen_kwargs)
print("="*50)

# now with different inputs
conversation = [
    {
        "role": f"{ds[0]['speaker_id']}",
        "content": [
            {"type": "text", "text": ds[2]["text"]},
            {"type": "audio", "path": ds[2]["audio"]["array"]},
        ],
    },
    {
        "role": f"{ds[1]['speaker_id']}",
        "content": [
            {"type": "text", "text": ds[3]["text"]},
            {"type": "audio", "path": ds[3]["audio"]["array"]},
        ],
    },
    {
        "role": f"{ds[2]['speaker_id']}",
        "content": [
            {"type": "text", "text": ds[4]["text"]},
        ],
    },
]
padded_inputs_2 = processor.apply_chat_template(
    conversation,
    tokenize=True,
    return_dict=True,
).to(model.device)

print("\n" + "="*50)
print("Generation with other inputs!")
with TimerContext("Generation with different inputs"):
    _ = model.generate(**padded_inputs_2, **gen_kwargs)
print("="*50)
```

### トレーニング

CSM Transformers統合はトレーニングをサポートしています！

```python
from datasets import Audio, load_dataset

from transformers import AutoProcessor, CsmForConditionalGeneration

model_id = "sesame/csm-1b"

# load the model and the processor
processor = AutoProcessor.from_pretrained(model_id)
model = CsmForConditionalGeneration.from_pretrained(model_id, device_map="auto")
model.train()
model.codec_model.eval()

ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
# ensure the audio is 24kHz
ds = ds.cast_column("audio", Audio(sampling_rate=24000))
conversation = []

# context
for text, audio, speaker_id in zip(ds[:4]["text"], ds[:4]["audio"], ds[:4]["speaker_id"]):
    conversation.append(
        {
            "role": f"{speaker_id}",
            "content": [{"type": "text", "text": text}, {"type": "audio", "path": audio["array"]}],
        }
    )

inputs = processor.apply_chat_template(
    conversation,
    tokenize=True,
    return_dict=True,
    output_labels=True,
).to(model.device)

out = model(**inputs)
out.loss.backward()
```

このモデルは[Eustache Le Bihan](https://huggingface.co/eustlb)によって提供されました。元のコードは[こちら](https://github.com/SesameAILabs/csm)で確認できます。

## CsmConfig[[transformers.CsmConfig]]

#### transformers.CsmConfig[[transformers.CsmConfig]]

```python
transformers.CsmConfig(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, num_codebooks: int | None = 32, vocab_size: int = 2051, text_vocab_size: int = 128256, hidden_size: int = 2048, intermediate_size: int = 8192, num_hidden_layers: int = 16, num_attention_heads: int = 32, num_key_value_heads: int | None = 8, hidden_act: str = 'silu', max_position_embeddings: int = 2048, initializer_range: float = 0.02, rms_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = 128002, codebook_pad_token_id: int | None = 2050, codebook_eos_token_id: int | list[int] | None = 0, bos_token_id: int | None = 128000, eos_token_id: int | list[int] | None = None, audio_token_id: int | None = 128002, audio_eos_token_id: int | list[int] | None = 128003, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, attention_bias: bool = False, attention_dropout: float | int | None = 0.0, mlp_bias: bool = False, head_dim: int | None = None, tie_codebooks_embeddings: bool | None = True, depth_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, codec_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/csm/configuration_csm.py#L90)

**パラメータ:**

num_codebooks (`int`、*任意*、デフォルトは`32`) : モデルが使用する並列コードブックの数。

vocab_size (`int`、*任意*、デフォルトは`2051`) : モデルの語彙サイズ。`input_ids`で表現できるトークンの種類数を定義します。

text_vocab_size (`int`、*任意*、デフォルトは`128256`) : モデルの語彙サイズ。`input_ids`で表現できるトークンの種類数を定義します。

hidden_size (`int`、*任意*、デフォルトは`2048`) : 隠れ表現の次元数。

intermediate_size (`int`、*任意*、デフォルトは`8192`) : MLP 表現の次元数。

num_hidden_layers (`int`、*任意*、デフォルトは`16`) : Transformer デコーダーの隠れ層の数。

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

num_key_value_heads (`int`, *optional*, デフォルトは `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 ヘッドは、そのグループ内の元のすべてのヘッドを平均プーリングして構築する必要があります。詳細については、[この論文](https://huggingface.co/papers/2305.13245)を参照してください。指定されない場合、デフォルトで `num_attention_heads` が使用されます。

hidden_act (`str`、*任意*、デフォルトは`silu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

max_position_embeddings (`int`、*任意*、デフォルトは`2048`)：このモデルが使用される可能性のある最大シーケンス長です。

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

rms_norm_eps (`float`、*任意*、デフォルトは`1e-05`) : rms 正規化レイヤーで使用する epsilon。

use_cache (`bool`、*任意*、デフォルトは `True`) : モデルが最後のキー/バリューアテンションを返すかどうか（すべてのモデルで利用されるわけではありません）。`config.is_decoder=True` の場合、またはモデルがデコーダー専用の生成モデルである場合にのみ関連します。

pad_token_id (`int`、*任意*、デフォルトは `128002`) : 語彙内でパディングに使用されるトークン ID。

codebook_pad_token_id (`int`、*任意*、デフォルトは 2050) : codebook トークンのためのパディングトークン ID。

codebook_eos_token_id (`int`、*任意*、デフォルトは 0) : コードブックトークンのストリーム終了トークン ID。

bos_token_id (`int`、*任意*、デフォルトは `128000`) : 語彙内でストリームの開始に使用されるトークン ID。

eos_token_id (`Union[int, list[int]]`、*任意*) : 語彙内でストリームの終了に使用されるトークン ID。

audio_token_id (`int`、*任意*、デフォルト値は 128002) : テキスト入力におけるオーディオトークンID。

audio_eos_token_id (`int`, *optional*, デフォルトは 128003) : テキスト入力における音声のストリーム終了トークン ID。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *optional*) : RoPE 埋め込みの設定パラメータを含む辞書です。この辞書には `rope_theta` の値が含まれていなければならず、より長い `max_position_embeddings` で RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。

attention_bias (`bool`、*任意*、デフォルトは`False`) : セルフアテンションにおけるクエリ、キー、バリュー、出力の投影層でバイアスを使用するかどうか。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

mlp_bias (`bool`, *任意*, デフォルトは `False`) : MLP 層の up_proj、down_proj、gate_proj 層でバイアスを使用するかどうか。

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

tie_codebooks_embeddings (`bool`, *任意*, デフォルトは `True`) : バックボーンモデルのコードブックトークン埋め込みを、深度デコーダーのコードブックトークン埋め込みと結合するかどうかを指定します。これにより `tie_word_embeddings` も設定されます。テキスト埋め込みと言語モデリングヘッドは結合されません。

depth_decoder_config (`CsmDepthDecoderConfig`、*任意*) : 深度デコーダーの設定。

codec_config (`PreTrainedConfig`、*任意*) : コーデックの設定です。

これは、[sesame/csm-1b](https://huggingface.co/sesame/csm-1b) と同様の設定をデフォルト値で生成する、CsmForConditionalGeneration の設定を保存するための設定クラスです。指定された引数に基づいて Csm モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。

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

```python
>>> from transformers import CsmForConditionalGeneration, CsmConfig

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

>>> # Initializing a model
>>> model = CsmForConditionalGeneration(configuration)

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

## CsmDepthDecoderConfig[[transformers.CsmDepthDecoderConfig]]

#### transformers.CsmDepthDecoderConfig[[transformers.CsmDepthDecoderConfig]]

```python
transformers.CsmDepthDecoderConfig(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, num_codebooks: int | None = 32, backbone_hidden_size: int = 2048, vocab_size: int = 2051, hidden_size: int = 1024, intermediate_size: int = 8192, num_hidden_layers: int = 4, num_attention_heads: int = 8, num_key_value_heads: int | None = 2, hidden_act: str = 'silu', max_position_embeddings: int = 33, initializer_range: float = 0.02, rms_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = None, bos_token_id: int | None = None, eos_token_id: int | list[int] | None = None, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, attention_bias: bool = False, attention_dropout: float | int | None = 0.0, mlp_bias: bool = False, head_dim: int | None = None)
```

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

**パラメータ:**

num_codebooks (`int`、*任意*、デフォルトは`32`) : モデルが使用する並列コードブックの数。

backbone_hidden_size (`int`、*optional*、デフォルトは 2048) : この depth decoder と一緒に使用される backbone モデルの隠れ表現の次元数。

vocab_size (`int`、*任意*、デフォルトは`2051`) : モデルの語彙サイズ。`input_ids`で表現できるトークンの種類数を定義します。

hidden_size (`int`、*任意*、デフォルトは`1024`) : 隠れ表現の次元数。

intermediate_size (`int`、*任意*、デフォルトは`8192`) : MLP 表現の次元数。

num_hidden_layers (`int`、*任意*、デフォルトは `4`) : Transformer デコーダーの隠れ層の数。

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

num_key_value_heads (`int`、*任意*、デフォルトは `2`) : 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 ヘッドは、そのグループ内の元のすべてのヘッドを平均プーリングして構築する必要があります。詳細については、[この論文](https://huggingface.co/papers/2305.13245)を参照してください。指定されない場合、デフォルトで `num_attention_heads` が使用されます。

hidden_act (`str`、*任意*、デフォルトは`silu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

max_position_embeddings (`int`、*任意*、デフォルトは`33`) : このモデルが使用される可能性のある最大シーケンス長です。

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

rms_norm_eps (`float`、*任意*、デフォルトは`1e-05`) : rms 正規化レイヤーで使用する epsilon。

use_cache (`bool`、*任意*、デフォルトは `True`) : モデルが最後のキー/バリューアテンションを返すかどうか（すべてのモデルで利用されるわけではありません）。`config.is_decoder=True` の場合、またはモデルがデコーダー専用の生成モデルである場合にのみ関連します。

pad_token_id (`int`, *任意*) : 語彙内でパディングに使用されるトークンID。

bos_token_id (`int`, *任意*) : 語彙内でストリームの開始に使用されるトークン ID。

eos_token_id (`Union[int, list[int]]`、*任意*) : 語彙内でストリームの終了に使用されるトークン ID。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *optional*) : RoPE 埋め込みの設定パラメータを含む辞書です。この辞書には `rope_theta` の値が含まれていなければならず、より長い `max_position_embeddings` で RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。

attention_bias (`bool`、*任意*、デフォルトは`False`) : セルフアテンションにおけるクエリ、キー、バリュー、出力の投影層でバイアスを使用するかどうか。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

mlp_bias (`bool`, *任意*, デフォルトは `False`) : MLP 層の up_proj、down_proj、gate_proj 層でバイアスを使用するかどうか。

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

これは、[sesame/csm-1b](https://huggingface.co/sesame/csm-1b) と同様の設定をデフォルト値で生成する、CsmForConditionalGeneration の設定を保存するための設定クラスです。指定された引数に基づいて Csm モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。

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

例:

```python
>>> from transformers import CsmDepthDecoder, CsmDepthDecoderConfig

>>> # Initializing a CsmDepthDecoder
>>> configuration = CsmDepthDecoderConfig()
>>> model = CsmDepthDecoderModel(configuration)

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

## CsmProcessor[[transformers.CsmProcessor]]

    

#### transformers.CsmProcessor[[transformers.CsmProcessor]]

```python
transformers.CsmProcessor(feature_extractor, tokenizer, chat_template = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/csm/processing_csm.py#L72)

**パラメータ:**

feature_extractor (`EncodecFeatureExtractor`) : 特徴量抽出器は必須の入力です。

tokenizer (`tokenizer_class`) : トークナイザーは必須の入力です。

chat_template (`str`) : チャット内のメッセージのリストをトークン化可能な文字列に変換するための Jinja テンプレート。

CsmProcessorを構築します。このクラスは、フィーチャーエクストラクターとトークナイザーを単一のプロセッサーにラップします。

[CsmProcessor](/docs/transformers/main/ja/model_doc/csm#transformers.CsmProcessor) は、[EncodecFeatureExtractor](/docs/transformers/main/ja/model_doc/encodec#transformers.EncodecFeatureExtractor) と `tokenizer_class` のすべての機能を提供します。詳細については、[~EncodecFeatureExtractor](/docs/transformers/main/ja/model_doc/encodec#transformers.EncodecFeatureExtractor) および `~tokenizer_class` を参照してください。

#### __call__[[transformers.CsmProcessor.__call__]]

```python
__call__(text: str | list[str] | list[list[str]] | None, audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None, output_labels: bool | None = False, depth_decoder_labels_ratio: float | None = 1.0, **kwargs: *<class 'transformers.models.csm.processing_csm.CsmProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/csm/processing_csm.py#L168)

**パラメータ:**

text (`Union[str, list[str], list[list[str]]]`、*任意*) : エンコード対象のシーケンスまたはシーケンスのバッチです。各シーケンスは文字列、または文字列のリスト（プレトークナイズ済み文字列）であることができます。プレトークナイズ済み入力を渡す場合は、バッチ入力との曖昧さを避けるために `is_split_into_words=True` を設定してください。

audio (`Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]]`, *任意*) : 準備対象のオーディオまたはオーディオのバッチです。各オーディオは NumPy 配列または PyTorch テンソルであることができます。NumPy 配列/PyTorch テンソルの場合、各オーディオの形状は (C, T) である必要があります。ここで C はチャネル数、T はオーディオのサンプル長を表します。

output_labels (`bool`, *optional*, default=False) : 学習用のラベルを返すかどうか。インデックスは `[config.audio_token_id, -100, -101]` の範囲になります。 - `config.audio_token_id` は音声フレームを示します（シーケンス長の要素をフレームとして扱います） - `-100` は損失計算時に無視されます - `-101` は、その音声フレームがバックボーンモデルでのみ使用されることを示します（ラベルとして最初のコードブックトークンを使用します）

depth_decoder_labels_ratio (`float`、*任意*、デフォルト=1.0) : 深度デコーダーのラベル用に保持するオーディオフレームの比率です。

encoded_length_kwargs (`dict[str, *kwargs*, Any]`, *任意*) : エンコードされた音声シーケンスの長さを計算するために使用されるキーワード引数の辞書です。音声エンコーディングで用いられる畳み込み層を定義する `kernel_sizes`、`strides`、`dilations`、`use_causal_conv` などのパラメータが含まれます。エンコードされた長さは、テキストシーケンス内の各音声入力に対して何個の音声トークンを生成するかを決定するために使用されます。

return_tensors (`str` または [TensorType](/docs/transformers/main/ja/internal/file_utils#transformers.TensorType)、*optional*) : 設定されている場合、特定のフレームワークのテンソルを返します。受け入れ可能な値は以下の通りです:  - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: NumPy の `np.ndarray` オブジェクトを返します。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/main/ja/main_classes/processors#transformers.ProcessingKwargs), *optional*) : 各モダリティ（テキスト、画像、動画、音声）の追加処理オプション。モデル固有のパラメータは上記にリストされています。サポートされている引数の完全なリストについては、TypedDict クラスを参照してください。

**戻り値:** [BatchFeature](/docs/transformers/main/ja/main_classes/feature_extractor#transformers.BatchFeature)

以下のフィールドを持つ[BatchFeature](/docs/transformers/main/ja/main_classes/feature_extractor#transformers.BatchFeature):

- **input_ids** -- モデルに与えるトークンIDのリスト。`text`が`None`でない場合に返されます。
- **input_values** -- モデルに与える音声値のリスト。`audio` が `None` でない場合に返されます。
- **attention_mask** -- モデルが注意すべきトークンを指定するインデックスのリスト（`return_attention_mask=True`の場合、または`self.model_input_names`に*"attention_mask"*が含まれており`text`が`None`でない場合）。
- **labels** -- 音声フレームのラベルのリスト。`output_labels=True` の場合に返されます。

## CsmForConditionalGeneration[[transformers.CsmForConditionalGeneration]]

#### transformers.CsmForConditionalGeneration[[transformers.CsmForConditionalGeneration]]

```python
transformers.CsmForConditionalGeneration(config: CsmConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/csm/modeling_csm.py#L741)

**パラメータ:**

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

Csmモデルは、llama風の自己回帰型transformerモデル2つで構成されています。1つは最初のcodebookトークンを予測するbackboneモデル、もう1つは残りのcodebookトークンを予測するdepth decoderです。

このモデルは [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.CsmForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, input_values: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, input_values_cutoffs: 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: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/csm/modeling_csm.py#L912)

**パラメータ:**

input_ids (`torch.LongTensor`、shape は `(batch_size, sequence_length, num_codebooks) or (batch_size, sequence_length)`) : 1. (batch_size, sequence_length): プロセッサでテキストプロンプトから準備された入力シーケンスに対応します。このような入力では、オーディオをコードブックトークンにエンコードしてからテキストトークンとマージできるように、`input_values` を提供する必要があります。 2. (batch_size, sequence_length, num_codebooks): 自己回帰デコーディング中に生成されるコードブックトークンです。このような入力はエンドユーザーが直接使用することを想定していません。 インデックスは [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_values (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : 入力生の音声波形の浮動小数点数値。値は、`.flac` または `.wav` 形式のオーディオファイルを `list[float]` 型、`numpy.ndarray` 型、または `torch.Tensor` 型の配列として読み込むことで取得できます。*例えば*、torchcodec ライブラリ（`pip install torchcodec`）や soundfile ライブラリ（`pip install soundfile`）を通じて行います。`input_values` として配列を準備するには、パディングと `torch.Tensor` 型への変換のために [AutoProcessor](/docs/transformers/main/ja/model_doc/auto#transformers.AutoProcessor) を使用してください。詳細は [CsmProcessor.__call__()](/docs/transformers/main/ja/model_doc/csm#transformers.CsmProcessor.__call__) を参照してください。

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

input_values_cutoffs (`torch.Tensor`、shape `(batch_size, max_num_audio)`、*optional*) : 連結されたオーディオ入力に対する、各バッチエントリ内のオーディオセグメントの終了位置を指定します。バッチエントリ内のセグメント数が最大数より少ない場合は、-1 でパディングされます。例えば、最初のシーケンスに長さ l1 の 2 つのオーディオセグメント、2 番目のシーケンスに長さ l2 の 1 つのオーディオセグメントを含む 2 シーケンスのバッチの場合、input_values_cutoffs は [[l1, 2 * l1], [l2, -1]] となります。

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`、shape `(batch_size, sequence_length)`、*任意*) : マスク言語モデリング損失を計算するためのラベル。インデックスは `[config.audio_token_id, -100, -101]` の範囲である必要があります。オーディオトークンは `codec_model` を使用して推論されるため、対象となる `input_values` を提供する必要があります。 - `config.audio_token_id` はオーディオフレームを示します（シーケンス長の要素をフレームとみなします） - `-100` は損失計算時に無視されます - `-101` は、そのオーディオフレームがバックボーンモデルでのみ使用されることを示します（ラベルとして最初のコードブックトークンを使用します）  このようなラベルは、[CsmProcessor](/docs/transformers/main/ja/model_doc/csm#transformers.CsmProcessor) を呼び出す際に `output_labels=True` を指定して準備できます。

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

logits_to_keep (`int` または `torch.Tensor`、*省略可*) : 互換性のために保持されています。サポートされる値は以下のいずれかです。1. `0`：すべての logits を保持するのと同じで、学習時に使用されます。2. `1`：最後の logit のみを保持するのと同じで、生成時に使用されます。

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

`CsmOutputWithPast`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。構成要素は、設定（[CsmConfig](/docs/transformers/main/ja/model_doc/csm#transformers.CsmConfig)）と入力によって異なります。

[CsmForConditionalGeneration](/docs/transformers/main/ja/model_doc/csm#transformers.CsmForConditionalGeneration)の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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **depth_decoder_loss** (`torch.Tensor`、形状 `(1,)`、*任意*、`labels` が指定された場合に返されます) -- 深度デコーダーモデルの言語モデリング損失(次のトークンの予測用)。
- **depth_decoder_logits** (`torch.Tensor`、shape `(batch_size, sequence_length, config.vocab_size)`) -- 深度デコーダーの予測スコア（SoftMax 適用前の各語彙トークンのスコア）。
- **depth_decoder_past_key_values** (`Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv キャッシュのガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。
- **depth_decoder_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、および任意の初期埋め込み出力。
- **depth_decoder_attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。
- **backbone_loss** (`torch.Tensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- バックボーンモデルの言語モデリング損失(次のトークンの予測用)。

例:

```python
>>> import torch
>>> from transformers import CsmForConditionalGeneration, AutoProcessor
>>> from datasets import load_dataset, Audio

>>> model_id = "sesame/csm-1b"
>>> torch_device = "cuda" if torch.cuda.is_available() else "cpu"

>>> processor = AutoProcessor.from_pretrained(model_id)

>>> ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
>>> # ensure the audio is 24kHz
>>> ds = ds.cast_column("audio", Audio(sampling_rate=24000))

>>> conversation = []
>>> # prepare a conversation with text and corresponding audio
>>> for text, audio, speaker_id in zip(ds[:4]["text"], ds[:4]["audio"], ds[:4]["speaker_id"]):
...     conversation.append(
...         {
...             "role": f"{speaker_id}",
...             "content": [{"type": "text", "text": text}, {"type": "audio", "path": audio["array"]}],
...         }
...     )

>>> inputs = processor.apply_chat_template(
...     conversation,
...     tokenize=True,
...     return_dict=True,
...     output_labels=True,
... ).to(torch_device)

>>> model = CsmForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
>>> output = model(**inputs)
>>> output.loss.backward()
```

#### generate[[transformers.CsmForConditionalGeneration.generate]]

```python
generate(input_ids: typing.Optional[torch.Tensor] = None, input_values: typing.Optional[torch.Tensor] = None, input_values_cutoffs: typing.Optional[torch.Tensor] = None, generation_config: transformers.generation.configuration_utils.GenerationConfig | None = None, logits_processor: transformers.generation.logits_process.LogitsProcessorList | None = None, stopping_criteria: transformers.generation.stopping_criteria.StoppingCriteriaList | None = None, synced_gpus: bool | None = None, streamer: typing.Optional[ForwardRef('BaseStreamer')] = None, output_audio: bool | None = False, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/csm/generation_csm.py#L334)

**パラメータ:**

inputs_ids (`torch.Tensor`、shape (batch_size, seq_length)、*optional*) : バックボーンモデルのプロンプトとして使用されるシーケンス。

input_values (`torch.Tensor`、shape (batch_size, channels, max_concatenated_audio_length)、*optional*) : バッチ化された音声入力値です。各バッチエントリには、そのエントリに属するすべての音声セグメントの連結が含まれます。これらの値は、codec モデルによって codebook トークンにエンコードされ、`input_ids` で提供されたテキスト入力 ID とマージされます。

input_values_cutoffs (`torch.Tensor`、shape (batch_size, max_num_audio)、*optional*) : 連結された音声入力に対する、各バッチエントリ内の音声セグメントの終了位置を指定します。バッチエントリのセグメント数が最大数より少ない場合は、-1 でパディングされます。例えば、最初のシーケンスに長さ l1 の音声セグメントが 2 つ、2 番目のシーケンスに長さ l2 の音声セグメントが 1 つ含まれる 2 シーケンスのバッチの場合、input_values_cutoffs は [[l1, 2 * l1], [l2, -1]] になります。

generation_config ([GenerationConfig](/docs/transformers/main/ja/main_classes/text_generation#transformers.GenerationConfig), *任意*) : 生成呼び出しのベースパラメータ化として使用される生成設定です。 `**kwargs` で `generation_config` の属性に一致するものが generate に渡された場合、それらは上書きされます。 `generation_config` が指定されない場合、デフォルトが使用されます。その読み込み優先順位は以下の通りです: 1) 存在する場合、`generation_config.json` モデルファイルから; 2) モデル設定から。未指定のパラメータは [GenerationConfig](/docs/transformers/main/ja/main_classes/text_generation#transformers.GenerationConfig) のデフォルト値を継承することに注意してください。生成をパラメータ化するには、そのドキュメントを確認する必要があります。

logits_processor (`LogitsProcessorList`, *任意*) : 引数や生成設定から構築されるデフォルトの logits プロセッサを補完する、カスタムの logits プロセッサです。引数や生成設定で既に作成済みの logits プロセッサが渡された場合、エラーが発生します。この機能は上級ユーザー向けです。

stopping_criteria (`StoppingCriteriaList`、*任意*) : 引数と生成設定から構築されるデフォルトの停止条件を補完する、カスタムの停止条件です。引数や生成設定からすでに作成された停止条件が渡された場合、エラーが発生します。停止条件が`scores`入力を依存している場合は、`generate`に`return_dict_in_generate=True, output_scores=True`を渡すことを確認してください。この機能は上級ユーザー向けです。

synced_gpus (`bool`, *optional*) : `FullyShardedDataParallel` または DeepSpeed ZeRO Stage 3 を複数 GPU で使用する場合、ある GPU が他の GPU より先に生成を完了した場合のデッドロックを回避するために、このフラグは `True` に設定されます（上書きされない限り）。それ以外の場合は、デフォルトで `False` になります。

streamer (`BaseStreamer`、*任意*) : 生成されたシーケンスのストリーミングに使用される Streamer オブジェクトです。生成されたトークンは `streamer.put(token_ids)` を介して渡され、その後の処理はすべて streamer が担当します。

output_audio (`bool`, *任意*) : 生成されたオーディオを返すかどうか。

kwargs (`dict[str, Any]`、*任意*) : `generation_config` のアドホックなパラメータ化、および/またはモデルの `forward` 関数に転送される追加のモデル固有の kwargs です。深度デコーダー固有の kwargs は、*depth_decoder_* をプレフィックスとして付ける必要があります。

**戻り値:** `CsmGenerateOutput` または `torch.LongTensor` または `list[torch.Tensor]`

`CsmGenerateOutput`（`return_dict_in_generate=True` の場合、または `config.return_dict_in_generate=True` の場合）、または `output_audio=False` の場合は `torch.LongTensor`、それ以外の場合は `list[torch.Tensor]`。

このメソッドは、Csm モデルの仕様に合わせて [generate()](/docs/transformers/main/ja/main_classes/text_generation#transformers.GenerationMixin.generate) をオーバーライドします。Csm モデルでは、カスタムの生成サンプリングステップが必要です。
1. バックボーンモデルを推論して、最初のコードブックトークンをサンプリングします
2. `input_ids` に最初のコードブックトークンを設定して深度デコーダーの generate を呼び出し、次のコードブックトークンをサンプリングします
3. これらの生成されたコードブックトークンを`input_ids`として使用し、バックボーンモデルで次の最初のコードブックトークンをサンプリングします
4. 停止条件が満たされるまで繰り返します

生成を制御するほとんどのパラメータは`generation_config`で設定されます。この引数が渡されない場合、モデルのデフォルトの生成設定が使用されます。`generation_config`の任意の値は、generate()に該当するパラメータを渡すことで上書きできます。例: `.generate(inputs, do_sample=True)`。

例:

```python
>>> from transformers import CsmProcessor, CsmForConditionalGeneration
>>> from datasets import load_dataset, Audio

>>> model_id = "sesame/csm-1b"
>>> torch_device = "cuda" if torch.cuda.is_available() else "cpu"

>>> processor = AutoProcessor.from_pretrained(model_id)

>>> ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
>>> # ensure the audio is 24kHz
>>> ds = ds.cast_column("audio", Audio(sampling_rate=24000))

>>> conversation = []
>>> # prepare a conversation with text and corresponding audio
>>> for text, audio, speaker_id in zip(ds[:4]["text"], ds[:4]["audio"], ds[:4]["speaker_id"]):
...     conversation.append(
...         {
...             "role": f"{speaker_id}",
...             "content": [{"type": "text", "text": text}, {"type": "audio", "path": audio["array"]}],
...         }
...     )

>>> # text prompt
>>> conversation.append({"role": f"{ds[4]['speaker_id']}", "content": [{"type": "text", "text": ds[4]["text"]}]})

>>> inputs = processor.apply_chat_template(
...     conversation,
...     tokenize=True,
...     return_dict=True,
... ).to(torch_device)

>>> model = CsmForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
>>> audio = model.generate(**inputs, output_audio=True)
>>> processor.save_audio(audio, "output.wav")
```

## CsmDepthDecoderForCausalLM[[transformers.CsmDepthDecoderForCausalLM]]

#### transformers.CsmDepthDecoderForCausalLM[[transformers.CsmDepthDecoderForCausalLM]]

```python
transformers.CsmDepthDecoderForCausalLM(config: CsmDepthDecoderConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/csm/modeling_csm.py#L530)

**パラメータ:**

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

The CsmDepthDecoder Model transformer, with a `CsmCodebooksHead` on top, which can be seen a position-specific language modeling head, allowing to use a different linear layer for each codebook (e.g. position 0 is the first codebook and uses the first codebook head, etc.)

このモデルは [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.CsmDepthDecoderForCausalLM.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, backbone_last_hidden_state: 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: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/csm/modeling_csm.py#L546)

**パラメータ:**

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)

backbone_last_hidden_state (`torch.Tensor`、形状 `(batch_size, backbone_hidden_size)`、*任意*) : バックボーンモデルの最後の隠れ状態。`input_ids` 引数に最初のコードブックトークン（バックボーンモデルによって生成されるもの）が提供される場合、この入力が必須です。

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 次元である必要があります。これは、パックされたテンソル形式（バッチとシーケンス長を単一の次元にまとめる形式）を使用する場合に有用です。

**戻り値:** [CausalLMOutputWithPast](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithPast) または `tuple(torch.Tensor)`

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

[CsmDepthDecoderForCausalLM](/docs/transformers/main/ja/model_doc/csm#transformers.CsmDepthDecoderForCausalLM)の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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

## CsmDepthDecoderModel[[transformers.CsmDepthDecoderModel]]

#### transformers.CsmDepthDecoderModel[[transformers.CsmDepthDecoderModel]]

```python
transformers.CsmDepthDecoderModel(config: CsmDepthDecoderConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/csm/modeling_csm.py#L400)

**パラメータ:**

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

特定のヘッドを付加せず、生のhidden-statesを出力する素のCsm Model。

このモデルは [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.CsmDepthDecoderModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, backbone_last_hidden_state: 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/csm/modeling_csm.py#L419)

**パラメータ:**

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)

backbone_last_hidden_state (`torch.Tensor`、形状 `(batch_size, backbone_hidden_size)`、*任意*) : バックボーンモデルの最後の隠れ状態。`input_ids` 引数に最初のコードブックトークン（バックボーンモデルによって生成されるもの）が提供される場合、この入力が必須です。

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`を参照）。

**戻り値:** [BaseModelOutputWithPast](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) または `tuple(torch.Tensor)`

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

[CsmDepthDecoderModel](/docs/transformers/main/ja/model_doc/csm#transformers.CsmDepthDecoderModel)の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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

## CsmBackboneModel[[transformers.CsmBackboneModel]]

#### transformers.CsmBackboneModel[[transformers.CsmBackboneModel]]

```python
transformers.CsmBackboneModel(config: CsmConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/csm/modeling_csm.py#L652)

**パラメータ:**

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

特定のヘッドを付加せず、生のhidden-statesを出力する素のCsm Model。

このモデルは [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.CsmBackboneModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = 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/csm/modeling_csm.py#L668)

**パラメータ:**

input_ids (`torch.LongTensor`、shape は `(batch_size, sequence_length, num_codebooks) or (batch_size, sequence_length)`) : 1. (batch_size, sequence_length): プロセッサでテキストプロンプトから準備された入力シーケンスに対応します。このような入力では、オーディオをコードブックトークンにエンコードしてからテキストトークンとマージできるように、`input_values` を提供する必要があります。 2. (batch_size, sequence_length, num_codebooks): 自己回帰デコーディング中に生成されるコードブックトークンです。このような入力はエンドユーザーが直接使用することを想定していません。 インデックスは [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)

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`を参照）。

**戻り値:** [BaseModelOutputWithPast](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) または `tuple(torch.Tensor)`

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

[CsmBackboneModel](/docs/transformers/main/ja/model_doc/csm#transformers.CsmBackboneModel)の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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

