# Cohere

Cohere [Command-R](https://cohere.com/blog/command-r) 是一个拥有 350 亿参数的多语言大语言模型，专为长上下文任务设计，例如检索增强生成（RAG）以及调用外部 API 和工具。该模型专门针对基于事实的生成进行了训练，并支持单步和多步工具使用。它支持 128K 令牌的上下文长度。

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

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

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

```python
from transformers import pipeline

pipeline = pipeline(
    task="text-generation",
    model="CohereForAI/c4ai-command-r-v01",
    device=0
)
pipeline("Plants create energy through a process known as")
```

```python
from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
model = AutoModelForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01", device_map="auto", attn_implementation="sdpa")

# format message with the Command-R chat template
messages = [{"role": "user", "content": "How do plants make energy?"}]
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 CohereForAI/c4ai-command-r-v01 --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("CohereForAI/c4ai-command-r-v01")
model = AutoModelForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01", device_map="auto", quantization_config=bnb_config, attn_implementation="sdpa")

# format message with the Command-R chat template
messages = [{"role": "user", "content": "How do plants make energy?"}]
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))
```

使用 [AttentionMaskVisualizer](https://github.com/huggingface/transformers/blob/beb9b5b02246b9b7ee81ddf938f93f44cfeaad19/src/transformers/utils/attention_visualizer.py#L139) 可以更直观地了解模型能够和不能关注哪些 token。

```python
from transformers.utils.attention_visualizer import AttentionMaskVisualizer

visualizer = AttentionMaskVisualizer("CohereForAI/c4ai-command-r-v01")
visualizer("Plants create energy through a process known as")
```

    

## 备注

- 如果您正在使用 FlashAttention-2，请勿在 [from_pretrained()](/docs/transformers/main/zh/model_doc/auto#transformers.AutoModel.from_pretrained) 中使用 dtype 参数，因为它仅支持 fp16 或 bf16。您应该使用 [Automatic Mixed Precision](https://pytorch.org/tutorials/recipes/recipes/amp_recipe.html)，如果使用的是 [Trainer](/docs/transformers/main/zh/main_classes/trainer#transformers.Trainer)，请将 fp16 或 bf16 设置为 True，或者使用 [torch.autocast](https://pytorch.org/docs/stable/amp.html#torch.autocast)。

## CohereConfig[[transformers.CohereConfig]]

#### transformers.CohereConfig[[transformers.CohereConfig]]

```python
transformers.CohereConfig(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 | None = 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 | None = 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 | None = 0.0, use_qk_norm: bool | None = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/cohere/configuration_cohere.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 比率。

use_qk_norm (`bool`，*可选*，默认为 `False`)：是否在注意力机制中使用查询-键归一化。

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

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

```python
>>> from transformers import CohereModel, CohereConfig

>>> # Initializing a Cohere model configuration
>>> configuration = CohereConfig()

>>> # Initializing a model from the Cohere configuration
>>> model = CohereModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```

## CohereTokenizer[[transformers.CohereTokenizer]]

#### transformers.CohereTokenizer[[transformers.CohereTokenizer]]

```python
transformers.CohereTokenizer(vocab: str | dict[str, int] | None = None, merges: str | list[str] | None = None, errors: str = 'replace', unk_token: str = '<UNK>', bos_token: str = '<BOS_TOKEN>', eos_token: str = '<|END_OF_TURN_TOKEN|>', pad_token: str = '<PAD>', cls_token: str = '<CLS>', sep_token: str = '<SEP>', mask_token: str = '<MASK_TOKEN>', use_default_system_prompt: bool = False, add_prefix_space: bool = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/cohere/tokenization_cohere.py#L45)

**参数：**

vocab_file (`str`, *可选*) : 词汇表文件的路径。

merges_file (`str`, *可选*) : 合并文件的路径。

tokenizer_file (`str`, *可选*) : [tokenizers](https://github.com/huggingface/tokenizers) 文件（通常具有 .json 扩展名），其中包含加载分词器所需的所有内容。

clean_up_tokenization_spaces (`bool`, *可选*，默认为 `False`)：是否在解码后清理空格。清理操作包括移除多余空格等潜在伪影。

unk_token (`str` 或 `tokenizers.AddedToken`，*可选*，默认为 `"<UNK>"`)：未知标记。词汇表中不存在的标记无法转换为 ID，因此会被设置为该标记。

bos_token (`str` 或 `tokenizers.AddedToken`，*可选*，默认为 `"<BOS_TOKEN>"`)：预训练期间使用的序列起始标记。可用作序列分类标记。

eos_token (`str` 或 `tokenizers.AddedToken`，*可选*，默认为 `"<|END_OF_TURN_TOKEN|>"`)：序列结束标记。

add_bos_token (`bool`，*可选*，默认为 `True`)：是否在序列开头添加 `bos_token`。

add_eos_token (`bool`，*可选*，默认为 `False`)：是否在序列末尾添加 `eos_token`。

use_default_system_prompt (`bool`, *可选*, 默认为 `False`) : 是否使用 Cohere tokenizer 的默认系统提示。

add_prefix_space (`bool`, *可选*, 默认为 `False`) : 分词器是否应自动添加前导空格

vocab (`str`、`dict` 或 `list`，*可选*)：自定义词汇表。如果未提供，则从 vocab_file 加载词汇表。

merges (`str` 或 `list[str]`，*可选*)：自定义合并列表。如果未提供，则从 `merges_file` 加载合并。

构建一个 Cohere 分词器。基于字节级 Byte-Pair-Encoding。

此处显著使用了 ByteFallback 和 NFC 规范化。

```python
>>> from transformers import AutoTokenizer

>>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
>>> tokenizer.encode("Hello this is a test")
[5, 28339, 2075, 1801, 1671, 3282]
```

如果要更改 `bos_token` 或 `eos_token`，请确保在初始化模型时指定它们，或者调用 `tokenizer.update_post_processor()` 以确保后处理正确执行（否则编码序列中第一个 token 和最后一个 token 的值将不正确）。更多详细信息，请参阅 [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) 文档。

你可以通过在实例化该分词器时传入 `add_prefix_space=True` 来绕过该行为，但由于模型并非以这种方式进行预训练，这可能会导致性能下降。

与 `is_split_into_words=True` 一起使用时，此分词器需要以 `add_prefix_space=True` 进行实例化。

该分词器继承自 [TokenizersBackend](/docs/transformers/main/zh/main_classes/tokenizer#transformers.TokenizersBackend)，其中包含了大部分主要方法。用户应参考该父类以获取有关这些方法的更多信息。

#### apply_grounded_generation_template[[transformers.CohereTokenizer.apply_grounded_generation_template]]

```python
apply_grounded_generation_template(conversation: list[dict[str, str]], documents: list[dict], citation_mode: typing.Literal['fast', 'accurate'] = 'accurate', **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/cohere/tokenization_cohere.py#L297)

**参数：**

conversation (list[dict[str, str]]) : 一个字典列表，每个字典包含 "role" 和 "content" 键，表示迄今为止的聊天历史记录。

documents (list[dict[str, str]) : 一个字典列表，表示用于为生成提供依据的文档或工具输出。文档是一个半结构化字典，包含字符串到字符串的映射。常见字段包括 `url`、`title`、`snippet` 等，但键名应具有描述性。这些字段将被渲染到提示词中。

citation_mode : 可选值为 "accurate"（先提示模型生成答案，然后重写并加入引用片段）或 "fast"（提示模型直接生成包含引用的答案）。前者生成的引用质量更高，后者需要生成的 token 数量更少。

add_generation_prompt (bool, *optional*) : 是否以指示助手消息开始的标记结束提示。当您希望从模型生成响应时，这很有用。请注意，此参数将传递给聊天模板，因此模板必须支持该参数，此参数才能生效。

tokenize (`bool`，默认为 `True`)：是否对输出进行分词。如果为 `False`，输出将是一个字符串。

padding (`bool`，默认为 `False`)：是否将序列填充至最大长度。如果 tokenize 为 `False`，则此参数无效。

truncation (`bool`，默认为 `False`)：是否在最大长度处截断序列。如果 tokenize 为 `False`，则此参数无效。

max_length (`int`, *可选*) : 用于填充或截断的最大长度（以 token 计）。如果 tokenize 为 `False`，则此参数无效。如果未指定，将使用分词器的 `max_length` 属性作为默认值。

return_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。如果 tokenize 为 `False`，则无效。可接受的值为：- `'pt'`：返回 PyTorch `torch.Tensor` 对象。- `'np'`：返回 NumPy `np.ndarray` 对象。

return_dict (`bool`，*可选*，默认为 `False`)：是否返回包含命名输出的字典。如果 tokenize 为 `False`，则此参数无效。

- ****tokenizer_kwargs** : 传递给分词器的额外参数。

**返回：** `str`

渲染后的提示字符串。或者，如果 tokenize=True：`list[int]`：一个令牌 ID 列表，表示迄今为止已分词的聊天内容，包括控制令牌。此输出可直接传递给模型，或通过 `generate()` 等方法传递。

创建一个 Command-R 基于上下文的生成（也称为 RAG）提示词。

渲染完成后，该提示词会指示模型基于所提供的文档生成带有引用的回复。

从概念上讲，其工作方式与 `apply_chat_format` 相同，但额外接收 `documents` 和参数 `citation_mode`。

将包含 `"role"` 和 `"content"` 键的字典列表以及供模型作为响应依据的文档列表，转换为提示字符串或 token id 列表。此方法将使用在类级别指定的分词器 `grounded_generation_template` 模板。您可以使用 `grounded_generation_template` 关键字参数来覆盖默认模板，但这可能会导致结果质量下降。

示例：

```python
>> tokenizer = CohereTokenizer.from_pretrained('CohereForAI/c4ai-command-r-v01')

>> # define documents:
>> documents = [
    { "title": "Tall penguins", "text": "Emperor penguins are the tallest." },
    { "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica."}
]
>> # define a conversation:
>> conversation = [
    {"role": "user", "content": "What's the biggest penguin in the world?"}
]
>> # render the prompt, ready for user to inspect, or for input into the model:
>> grounded_generation_prompt = tokenizer.apply_grounded_generation_template(conversation, documents=documents, tokenize=False, add_generation_prompt=True)
>> print(grounded_generation_prompt)
>> inputs = tokenizer.encode(prompt, add_special_tokens=False, return_tensors='pt')
>> outputs = model.generate(inputs, max_new_tokens=128)
>> print(tokenizer.decode(outputs[0]))
```

#### apply_tool_use_template[[transformers.CohereTokenizer.apply_tool_use_template]]

```python
apply_tool_use_template(conversation: list[dict[str, str]], tools: list[dict], **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/cohere/tokenization_cohere.py#L186)

**参数：**

conversation (list[dict[str, str]]) : 一个字典列表，每个字典包含 "role" 和 "content" 键，表示迄今为止的聊天历史记录。

tools (list[Dict]) : 一个工具列表，用于渲染到提示词中供模型选择。文档字符串底部有一个示例。格式应如下：* name (str)：要调用的工具的名称。有效的名称仅包含 a-z、A-Z、0-9 和 _ 字符，且不能以数字开头。* description (str)：工具功能的描述，模型根据该描述来决定何时以及如何调用函数。* parameter_definitions (list[Dict])：工具的输入参数。接受一个字典，其中键是参数名称，值是参数规范。有效的参数名称仅包含 a-z、A-Z、0-9 和 _ 字符，且不能以数字开头。参数规范如下：* description (str)：参数的描述。* type (str)：参数的类型 - 对于 Python 内置数据类型（如 'str'、'bool'）最为有效。* required: boolean：表示参数是否始终存在（必需）。默认值为非必需。

add_generation_prompt (bool, *optional*) : 是否以指示助手消息开始的标记结束提示。当您希望从模型生成响应时，这很有用。请注意，此参数将传递给聊天模板，因此模板必须支持该参数，此参数才能生效。

tokenize (`bool`，默认为 `True`)：是否对输出进行分词。如果为 `False`，输出将是一个字符串。

padding (`bool`，默认为 `False`)：是否将序列填充至最大长度。如果 tokenize 为 `False`，则此参数无效。

truncation (`bool`，默认为 `False`)：是否在最大长度处截断序列。如果 tokenize 为 `False`，则此参数无效。

max_length (`int`, *可选*) : 用于填充或截断的最大长度（以 token 计）。如果 tokenize 为 `False`，则此参数无效。如果未指定，将使用分词器的 `max_length` 属性作为默认值。

return_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。如果 tokenize 为 `False`，则无效。可接受的值为：- `'pt'`：返回 PyTorch `torch.Tensor` 对象。- `'np'`：返回 NumPy `np.ndarray` 对象。

return_dict (`bool`，*可选*，默认为 `False`)：是否返回包含命名输出的字典。如果 tokenize 为 `False`，则此参数无效。

- ****tokenizer_kwargs** : 传递给分词器的额外参数。

**返回：** `str`

渲染后的提示字符串。或者，如果 tokenize=True：`list[int]`：一个令牌 ID 列表，表示迄今为止已分词的聊天内容，包括控制令牌。此输出可直接传递给模型，或通过 `generate()` 等方法传递。

创建一个 Command-R 工具使用提示。

渲染完成后，该提示词会指示模型生成一个操作列表，用于在用户提供的工具集上执行相应操作，以协助完成用户的请求。

从概念上讲，其工作方式与 `apply_chat_format` 相同，但额外接受一个 `tools` 参数。

将聊天（以包含 `"role"` 和 `"content"` 键的字典列表形式表示）以及模型可用的工具列表，转换为提示字符串或 token id 列表。此方法将使用在类级别指定的分词器 `default_tool_use_template` 模板。您可以使用 `tool_use_template` 关键字参数来覆盖默认模板，但这样做可能会导致结果质量下降。

示例：

```python
>> tokenizer = CohereTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
>> tools = [
    {
        "name": "internet_search",
        "description": "Returns a list of relevant document snippets for a textual query retrieved from the internet",
        "parameter_definitions": {
            "query": {
                "description": "Query to search the internet with",
                "type": "str",
                "required": True,
            }
        },
    },
    {
        "name": "directly_answer",
        "description": "Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history",
        "parameter_definitions": {},
    },
]
>> conversation = [
    {"role": "user", "content": "What's the biggest penguin in the world?"},
]
>> # Render the prompt, ready for user to inspect, or for input into the model
>> prompt = tokenizer.apply_tool_use_template(conversation, tools=tools, tokenize=False, add_generation_prompt=True)
>> print(prompt)
>> inputs = tokenizer.encode(grounded_generation_prompt, add_special_tokens=False, return_tensors='pt')
>> outputs = model.generate(inputs, max_new_tokens=128)
>> print(tokenizer.decode(outputs[0]))
[
    {
        "tool_name": "internet_search",
        "parameters": {
            "query": "biggest penguin in the world"
        }
    }
]
```

## CohereModel[[transformers.CohereModel]]

#### transformers.CohereModel[[transformers.CohereModel]]

```python
transformers.CohereModel(config: CohereConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/cohere/modeling_cohere.py#L361)

**参数：**

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

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

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.CohereModel.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/main/src/transformers/models/cohere/modeling_cohere.py#L378)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/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/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/main/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/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 或 `tuple(torch.Tensor)`

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

[CohereModel](/docs/transformers/main/zh/model_doc/cohere#transformers.CohereModel) 的 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/main/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 后的注意力权重，用于在自注意力头中计算加权平均值。

## CohereForCausalLM[[transformers.CohereForCausalLM]]

#### transformers.CohereForCausalLM[[transformers.CohereForCausalLM]]

```python
transformers.CohereForCausalLM(config: CohereConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/cohere/modeling_cohere.py#L436)

**参数：**

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

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

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.CohereForCausalLM.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/main/src/transformers/models/cohere/modeling_cohere.py#L453)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/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/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/main/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/main/zh/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithPast) 或 `tuple(torch.Tensor)`

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

[CohereForCausalLM](/docs/transformers/main/zh/model_doc/cohere#transformers.CohereForCausalLM) 的 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/main/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, CohereForCausalLM

>> model = CohereForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01")
>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/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."
```

