# Cohere 2

[Cohere Command R7B](https://cohere.com/blog/command-r7b) 是一个 7B 参数模型的开放权重研究版本。它是一个在 23 种语言上训练的多语言模型，拥有 128k 的上下文窗口。该模型包含三层滑动窗口注意力机制和 ROPE，用于高效的局部上下文建模和相对位置编码。第四层使用不带位置嵌入的全局注意力，从而允许整个序列中不受限制的 token 交互。

该模型针对速度、性价比和计算资源进行了优化。

您可以在 [Command Models](https://huggingface.co/collections/CohereForAI/command-models-67652b401665205e17b192ad) 集合中找到所有原始的 Command-R 检查点。

> [!TIP]
> 点击右侧边栏中的 Cohere 模型，以查看将 Cohere 应用于不同语言任务的更多示例。

以下示例演示了如何使用 [Pipeline](/docs/transformers/v5.24.0/zh/main_classes/pipelines#transformers.Pipeline) 或 [AutoModel](/docs/transformers/v5.24.0/zh/model_doc/auto#transformers.AutoModel) 类生成文本，以及如何通过命令行生成文本。

```python
from transformers import pipeline

pipeline = pipeline(
    task="text-generation",
    model="CohereLabs/c4ai-command-r7b-12-2024",
    device_map=0
)

messages = [
    {"role": "user", "content": "Hello, can you please help me book a hotel in Japan?"},
]
pipeline(messages)
```

```python
from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("CohereLabs/c4ai-command-r7b-12-2024")
model = AutoModelForCausalLM.from_pretrained(
    "CohereLabs/c4ai-command-r7b-12-2024",
    device_map="auto",
    attn_implementation="sdpa"
)

# format message with the Command-R chat template
messages = [{"role": "user", "content": "Hello, can you please help me book a hotel in Japan?"}]
input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
output = model.generate(
    input_ids,
    max_new_tokens=100,
    do_sample=True,
    temperature=0.3,
    cache_implementation="static",
)
print(tokenizer.decode(output[0], skip_special_tokens=True))
```

```bash
# pip install -U flash-attn --no-build-isolation
transformers chat CohereLabs/c4ai-command-r7b-12-2024 --dtype auto --attn_implementation flash_attention_2
```

量化通过以较低精度表示权重来降低大模型的内存负担。有关更多可用的量化后端，请参阅 [量化](../quantization/overview) 概述。

以下示例使用 [bitsandbytes](../quantization/bitsandbytes) 将权重量化为 4 位。

```python
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

bnb_config = BitsAndBytesConfig(load_in_4bit=True)
tokenizer = AutoTokenizer.from_pretrained("CohereLabs/c4ai-command-r7b-12-2024")
model = AutoModelForCausalLM.from_pretrained(
    "CohereLabs/c4ai-command-r7b-12-2024",
    device_map="auto",
    quantization_config=bnb_config,
    attn_implementation="sdpa"
)

# format message with the Command-R chat template
messages = [{"role": "user", "content": "Hello, can you please help me book a hotel in Japan?"}]
input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
output = model.generate(
    input_ids,
    max_new_tokens=100,
    do_sample=True,
    temperature=0.3,
    cache_implementation="static",
)
print(tokenizer.decode(output[0], skip_special_tokens=True))
```

## Cohere2Config[[transformers.Cohere2Config]]

#### transformers.Cohere2Config[[transformers.Cohere2Config]]

```python
transformers.Cohere2Config(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, vocab_size: int = 256000, hidden_size: int = 8192, intermediate_size: int = 22528, logit_scale: float = 0.0625, num_hidden_layers: int = 40, num_attention_heads: int = 64, num_key_value_heads: int | None = None, hidden_act: str = 'silu', max_position_embeddings: int = 8192, initializer_range: float = 0.02, layer_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = 0, bos_token_id: int | None = 5, eos_token_id: int | list[int] | None = 255001, tie_word_embeddings: bool = True, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, attention_bias: bool = False, attention_dropout: float | int = 0.0, sliding_window: int | None = 4096, layer_types: list[str] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/cohere2/configuration_cohere2.py#L30)

**参数：**

vocab_size (`int`，*可选*，默认值为 `256000`)：模型的词汇表大小。定义了 `input_ids` 可以表示的不同 token 数量。

hidden_size (`int`，*可选*，默认为 `8192`)：隐藏表示的维度。

intermediate_size (`int`，*可选*，默认为 `22528`)：MLP 表示的维度。

logit_scale (`float`, *可选*, 默认值为 0.0625) : 输出 logits 的缩放因子。

num_hidden_layers (`int`，*可选*，默认为 `40`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `64`)：Transformer 解码器中每个注意力层的注意力头数量。

num_key_value_heads (`int`, *可选*) : 这是用于实现分组查询注意力（Grouped Query Attention）的键值头数量。如果 `num_key_value_heads=num_attention_heads`，模型将使用多头注意力（MHA）；如果 `num_key_value_heads=1`，模型将使用多查询注意力（MQA）；否则将使用 GQA。在将多头检查点转换为 GQA 检查点时，每个组的键和值头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 [这篇论文](https://huggingface.co/papers/2305.13245)。如果未指定，则默认为 `num_attention_heads`。

hidden_act (`str`，*可选*，默认为 `silu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

max_position_embeddings (`int`，*可选*，默认为 `8192`)：该模型可能使用的最大序列长度。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

layer_norm_eps (`float`，*可选*，默认为 `1e-05`)：层归一化层所使用的 epsilon。

use_cache (`bool`，*可选*，默认为 `True`)：模型是否应返回最后的键/值注意力（并非所有模型都使用）。仅当 `config.is_decoder=True` 或模型为仅解码器生成模型时相关。

pad_token_id (`int`，*可选*，默认为 `0`)：词表中用于填充的 Token ID。

bos_token_id (`int`，*可选*，默认为 `5`)：词汇表中用于表示流开始的 Token id。

eos_token_id (`Union[int, list[int]]`，*可选*，默认为 `255001`)：词汇表中用于表示流结束（end-of-stream）的 Token ID。

tie_word_embeddings (`bool`，*可选*，默认为 `True`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *可选*) : 包含 RoPE 嵌入配置参数的字典。该字典应包含 `rope_theta` 的值，并且如果希望使用更长的 `max_position_embeddings` 配合 RoPE，则可选地包含用于缩放的参数。

attention_bias (`bool`，*可选*，默认为 `False`)：在自注意力机制中，是否在查询、键、值和输出投影层中使用偏置。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

sliding_window (`int`, *可选*，默认为 `4096`)：滑动窗口注意力的窗口大小。如果为 `None`，则不应用滑动窗口。

layer_types (`list[str]`，*可选*)：一个列表，用于显式地将每个层索引与其层类型进行映射。如果未提供，将根据配置值自动生成。

这是用于存储 Cohere2Model 配置的类。它根据指定的参数实例化 Cohere2 模型，并定义模型架构。使用默认值实例化配置，将得到与 [CohereForAI/c4ai-command-r-v01](https://huggingface.co/CohereForAI/c4ai-command-r-v01) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.24.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.24.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

```python
>>> from transformers import Cohere2Model, Cohere2Config

>>> # Initializing a Cohere Nextmodel configuration
>>> configuration = Cohere2Config()

>>> # Initializing a model from the Cohere2 configuration
>>> model = Cohere2Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```

## Cohere2Model[[transformers.Cohere2Model]]

#### transformers.Cohere2Model[[transformers.Cohere2Model]]

```python
transformers.Cohere2Model(config: Cohere2Config)
```

[来源](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/cohere2/modeling_cohere2.py#L335)

**参数：**

config ([Cohere2Config](/docs/transformers/v5.24.0/zh/model_doc/cohere2#transformers.Cohere2Config))：模型配置类，包含模型的所有参数。使用配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.24.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

未添加任何特定头部的裸 Cohere2 模型，直接输出原始隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.24.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Cohere2Model.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: 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/v5.24.0/src/transformers/models/cohere2/modeling_cohere2.py#L351)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.24.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.24.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.24.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.24.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/v5.24.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

use_cache (`bool`, *可选*) : 如果设置为 `True`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

**返回：** [BaseModelOutputWithPast](/docs/transformers/v5.24.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPast](/docs/transformers/v5.24.0/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[Cohere2Model](/docs/transformers/v5.24.0/zh/model_doc/cohere2#transformers.Cohere2Model) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。

  如果使用了`cache`，则仅输出形状为`(batch_size, 1, hidden_size)`的序列的最后一个隐藏状态。
- **cache**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [Cache](/docs/transformers/v5.24.0/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

## Cohere2ForCausalLM[[transformers.Cohere2ForCausalLM]]

#### transformers.Cohere2ForCausalLM[[transformers.Cohere2ForCausalLM]]

```python
transformers.Cohere2ForCausalLM(config: Cohere2Config)
```

[来源](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/cohere2/modeling_cohere2.py#L414)

**参数：**

config ([Cohere2Config](/docs/transformers/v5.24.0/zh/model_doc/cohere2#transformers.Cohere2Config))：模型配置类，包含模型的所有参数。使用配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.24.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

用于因果语言建模的 Cohere2 模型。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.24.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Cohere2ForCausalLM.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: 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/v5.24.0/src/transformers/models/cohere2/modeling_cohere2.py#L431)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.24.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/v5.24.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/v5.24.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/v5.24.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/v5.24.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*) : 用于计算因果语言建模损失的标签。索引应在 `[-100, 0, ..., config.vocab_size]` 范围内（参见 `input_ids` 的文档字符串）。索引设置为 `-100` 的 token 将被忽略（被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。 标签会在**内部进行移位**，因此使用 `labels[..., 1:]` 来预测 `logits[..., :-1, :]`。请传入与 `input_ids` 匹配的未移位标签（即 `labels = input_ids`）。在传入之前，请**不要**自行对标签进行移位。 如果标签已经移位（例如在使用序列并行时），请将其作为 `shift_labels` 关键字参数传入，系统将按原样使用它们。 为了计算损失，仍然必须传入 `labels`。

use_cache (`bool`, *可选*) : 如果设置为 `True`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

logits_to_keep (`Union[int, torch.Tensor]`，*可选*，默认为 `0`)：如果为 `int`，则计算最后 `logits_to_keep` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

**返回：** [CausalLMOutputWithPast](/docs/transformers/v5.24.0/zh/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithPast) 或 `tuple(torch.Tensor)`

一个 [CausalLMOutputWithPast](/docs/transformers/v5.24.0/zh/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithPast) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[Cohere2ForCausalLM](/docs/transformers/v5.24.0/zh/model_doc/cohere2#transformers.Cohere2ForCausalLM) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **cache**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [Cache](/docs/transformers/v5.24.0/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>> from transformers import AutoTokenizer, Cohere2ForCausalLM

>> model = Cohere2ForCausalLM.from_pretrained("Cohere2ForAI/c4ai-command-r-v01")
>> tokenizer = AutoTokenizer.from_pretrained("Cohere2ForAI/c4ai-command-r-v01")

>> prompt = "Hey, are you conscious? Can you talk to me?"
>> inputs = tokenizer(prompt, return_tensors="pt")

>> # Generate
>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
```

