Transformers 文档

DeepSeek-V3

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

此模型于 2024-12-27 发布,并于 2025-03-28 添加到 Hugging Face Transformers。

DeepSeek-V3

概述

DeepSeek-V3 模型由 DeepSeek-AI 团队在 DeepSeek-V3 Technical Report 中提出。

论文摘要如下:我们提出了 DeepSeek-V3,一个强大的专家混合(MoE)语言模型,总参数量为 671B,每个 token 激活 37B。为了实现高效的推理和成本效益高的训练,DeepSeek-V3 采用了在 DeepSeek-V2 中经过充分验证的多头潜在注意力(MLA)和 DeepSeekMoE 架构。此外,DeepSeek-V3 开创性地采用了无辅助损失的策略来实现负载均衡,并设置了多 token 预测训练目标以获得更强的性能。我们在 14.8 万亿个多样化的高质量 token 上预训练了 DeepSeek-V3,随后进行了监督微调和强化学习阶段,以充分发挥其能力。全面的评估表明,DeepSeek-V3 的性能优于其他开源模型,并达到了与领先的闭源模型相当的性能。尽管性能优异,DeepSeek-V3 的完整训练仅需要 2.788M H800 GPU 小时。此外,其训练过程异常稳定。在整个训练过程中,我们没有遇到任何不可恢复的损失尖峰,也没有进行任何回滚。模型检查点可在 https://github.com/deepseek-ai/DeepSeek-V3 获取。

限制与贡献呼吁!

我们非常乐意让这个代码变得社区驱动,并希望看到您如何能够最好地优化以下内容。

  • 当前实现使用了“朴素”的注意力计算(所以不是真正的 MLA)
  • 当前实现是通过循环遍历专家。这应该被替换。请参考使用 get_packed_weightsintegrations/tensor_parallel
  • 当前实现使用了 Eleuther 的 ROPE 公式,使用原始公式会更有效!(仍应遵循我们的 API)
  • 不支持静态缓存(这应该只是一个生成配置问题/配置形状问题)

使用技巧

该模型使用了多头潜在注意力(MLA)和 DeepSeekMoE 架构,以实现高效推理和成本效益高的训练。它采用了一种无辅助损失的策略来实现负载均衡,以及多 token 预测训练目标。该模型在 14.8 万亿 token 上进行了预训练,并经历了监督微调和强化学习阶段,可用于各种语言任务。

您可以使用 FP8 自动运行模型,使用 2 个 8 个 H100 节点应该绰绰有余!

# `run_deepseek_v1.py`
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
torch.manual_seed(30)

tokenizer = AutoTokenizer.from_pretrained("deepseek-r1")

chat = [
  {"role": "user", "content": "Hello, how are you?"},
  {"role": "assistant", "content": "I'm doing great. How can I help you today?"},
  {"role": "user", "content": "I'd like to show off how chat templating works!"},
]


model = AutoModelForCausalLM.from_pretrained("deepseek-r1", device_map="auto", dtype=torch.bfloat16)
inputs = tokenizer.apply_chat_template(chat, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
import time
start = time.time()
outputs = model.generate(inputs, max_new_tokens=50)
print(tokenizer.batch_decode(outputs))
print(time.time()-start)

此生成

<|Assistant|><think>
Okay, the user wants to demonstrate how chat templating works. Let me break down what that means. Chat templating is about structuring the conversation data, especially for models that need specific input formats. Maybe they're referring to something like how messages are formatted with roles (user, assistant, system) in APIs like OpenAI.

First, I should explain what chat templating is. It's the process of formatting conversation data into a structured format that the model can understand. This usually includes roles and content. For example, user messages, assistant responses, and system messages each have their own role tags.

They might want an example. Let me think of a simple conversation. The user says "Hello, how are you?" and the assistant responds "I'm doing great. How can I help you today?" Then the user follows up with wanting to show off chat templating. So the example should include the history and the new message.

In some frameworks, like Hugging Face's Transformers, chat templates are applied using Jinja2 templates. The template might look something like combining system messages, then looping through user and assistant messages with appropriate tags. For instance, using {% for message in messages %} and assigning roles like <|user|>, <|assistant|>, etc.

I should structure the example with the messages array, showing each role and content. Then apply a hypothetical template to convert that into a formatted string the model uses. Also, mention that different models have different templating requirements, like using special tokens or varying role labels.

Wait, the user mentioned "chat templating" in the context of showing off. Maybe they want a practical example they can present. So providing a code snippet or a structured data example would be helpful. Let me outline a typical messages array and then the templated output.

Also, it's important to note that proper templating ensures the model knows the conversation flow, which is crucial for generating coherent responses. Maybe include a note about why it's important, like maintaining context and role-specific processing.

Let me check if there are any common mistakes or things to avoid. For example, not closing tags properly, or mismatching roles. But maybe that's too detailed unless the user asks. Focus on the positive example first.

Putting it all together, the response should have an example messages array, the applied template, and the final formatted string. Maybe use angle brackets or special tokens as placeholders. Also, mention that this helps in training or fine-tuning models with structured data.

I think that's a solid approach. Let me structure it step by step to make it clear.
</think>

Chat templating is a way to structure conversation data (e.g., user/assistant interactions) into a format that language models understand. This is especially important for models trained to handle multi-turn dialogues, where the input must explicitly separate roles (user, assistant, system, etc.) and messages. Let’s break this down with an example!

---

### **Step 1: Raw Conversation History**
Suppose we have this conversation:
- **User**: "Hello, how are you?"
- **Assistant**: "I'm doing great. How can I help you today?"
- **User**: "I'd like to show off how chat templating works!"

---

### **Step 2: Structured Messages**
In frameworks like Hugging Face Transformers or OpenAI, conversations are often formatted as a list of dictionaries with `role` and `content`:
```python
messages = [
    {"role": "user", "content": "Hello, how are you?"},
    {"role": "assistant", "content": "I'm doing great. How can I help you today?"},
    {"role": "user", "content": "I'd like to show off how chat templating works!"},
]
```

---

### **Step 3: Apply a Chat Template**
A **chat template** converts this structured data into a single string formatted for the model. For example, using a Jinja-style template (common in Hugging Face):

```jinja
{% for message in messages %}
    {% if message['role'] == 'user' %}
        <|user|>{{ message['content'] }}<|end|>
    {% elif message['role'] == 'assistant' %}
        <|assistant|>{{ message['content'] }}<|end|>
    {% endif %}
{% endfor %}
<|assistant|>
```

---

### **Step 4: Final Templated Output**
Applying the template to our `messages` list would produce:
```text
<|user|>Hello, how are you?<|end|>
<|assistant|>I'm doing great. How can I help you today?<|end|>
<|user|>I'd like to show off how chat templating works!<|end|>
<|assistant|>
```

This tells the model:  
1. The conversation history (user/assistant turns).  
2. The model's turn to generate a response (`<|assistant|>` at the end).  

---

### **Key Notes**:
- **Role Separation**: Tags like `<|user|>` and `<|assistant|>` help the model distinguish speakers.
- **Special Tokens**: Models often use unique tokens (e.g., `<|end|>`) to mark message boundaries.
- **Flexibility**: Templates vary by model (e.g., OpenAI uses `{"role": "user", "content": "..."}` instead of tags).

---

### **Why This Matters**:
- **Consistency**: Ensures the model understands dialogue structure.
- **Context Preservation**: Maintains the flow of multi-turn conversations.
- **Alignment**: Matches the format the model was trained on for better performance.

Want to dive deeper or see a specific framework’s implementation (e.g., OpenAI, Llama, Mistral)? Let me know! 😊<|end▁of▁sentence|>

使用以下命令运行它

torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0|1 --rdzv-id an_id --rdzv-backend c10d --rdzv-endpoint master_addr:master_port run_deepseek_r1.py

如果您遇到

[rank0]: ncclInternalError: Internal check failed.
[rank0]: Last error:
[rank0]: Bootstrap : no socket interface found

错误,则表示 NCCL 可能未加载。

DeepseekV3Config

class transformers.DeepseekV3Config

< >

( vocab_size: int | None = 129280 hidden_size: int | None = 7168 intermediate_size: int | None = 18432 moe_intermediate_size: int | None = 2048 num_hidden_layers: int | None = 61 num_attention_heads: int | None = 128 num_key_value_heads: int | None = 128 n_shared_experts: int | None = 1 n_routed_experts: int | None = 256 routed_scaling_factor: float | None = 2.5 kv_lora_rank: int | None = 512 q_lora_rank: int | None = 1536 qk_rope_head_dim: int | None = 64 v_head_dim: int | None = 128 qk_nope_head_dim: int | None = 128 n_group: int | None = 8 topk_group: int | None = 4 num_experts_per_tok: int | None = 8 first_k_dense_replace: int | None = 3 norm_topk_prob: bool | None = True hidden_act: str | None = 'silu' max_position_embeddings: int | None = 4096 initializer_range: float | None = 0.02 rms_norm_eps: int | None = 1e-06 use_cache: bool | None = True pad_token_id: int | None = None bos_token_id: int | None = 0 eos_token_id: int | None = 1 pretraining_tp: int | None = 1 tie_word_embeddings: bool | None = False rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict[str, transformers.modeling_rope_utils.RopeParameters] | None = None rope_interleave: bool | None = True attention_bias: bool | None = False attention_dropout: float | None = 0.0 **kwargs )

参数

  • vocab_size (int, optional, defaults to 129280) — The vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling DeepseekV3Model
  • hidden_size (int, optional, defaults to 7168) — Dimension of the hidden representations.
  • intermediate_size (int, optional, defaults to 18432) — Dimension of the MLP representations.
  • moe_intermediate_size (int, optional, defaults to 2048) — Dimension of the MoE representations.
  • num_hidden_layers (int, optional, defaults to 61) — Number of hidden layers in the Transformer decoder.
  • num_attention_heads (int, optional, defaults to 128) — Number of attention heads for each attention layer in the Transformer decoder.
  • num_key_value_heads (int, optional, defaults to 128) — This is the number of key_value heads that should be used to implement Grouped Query Attention. If num_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), if num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to num_attention_heads`.
  • n_shared_experts (int, optional, defaults to 1) — Number of shared experts.
  • n_routed_experts (int, optional, defaults to 256) — Number of routed experts.
  • routed_scaling_factor (float, optional, defaults to 2.5) — Scaling factor for routed experts.
  • kv_lora_rank (int, optional, defaults to 512) — Rank of the LoRA matrices for key and value projections.
  • q_lora_rank (int, optional, defaults to 1536) — Rank of the LoRA matrices for query projections.
  • qk_rope_head_dim (int, optional, defaults to 64) — Dimension of the query/key heads that use rotary position embeddings.
  • v_head_dim (int, optional, defaults to 128) — Dimension of the value heads.
  • qk_nope_head_dim (int, optional, defaults to 128) — Dimension of the query/key heads that don’t use rotary position embeddings.
  • n_group (int, optional, defaults to 8) — Number of groups for routed experts.
  • topk_group (int, optional, defaults to 4) — Number of selected groups for each token (for each token, ensuring the selected experts is only within topk_group groups).
  • num_experts_per_tok (int, optional, defaults to 8) — Number of selected experts, None means dense model.
  • first_k_dense_replace (int, optional, defaults to 3) — Number of dense layers in shallow layers (embed->dense->dense->…->dense->moe->moe…->lm_head). --k dense layers--/
  • norm_topk_prob (bool, optional, defaults to True) — Whether to normalize the weights of the routed experts.
  • hidden_act (str or function, optional, defaults to "silu") — The non-linear activation function (function or string) in the decoder.
  • max_position_embeddings (int, optional, defaults to 4096) — The maximum sequence length that this model might ever be used with.
  • initializer_range (float, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  • rms_norm_eps (float, optional, defaults to 1e-06) — The epsilon used by the rms normalization layers.
  • use_cache (bool, optional, defaults to True) — Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if config.is_decoder=True.
  • pad_token_id (int, optional) — Padding token id.
  • bos_token_id (int, optional, defaults to 0) — Beginning of stream token id.
  • eos_token_id (int, optional, defaults to 1) — End of stream token id.
  • pretraining_tp (int, optional, defaults to 1) — Experimental feature. Tensor parallelism rank used during pretraining. Please refer to this document to understand more about it. This value is necessary to ensure exact reproducibility of the pretraining results. Please refer to this issue.
  • tie_word_embeddings (bool, optional, defaults to False) — Whether to tie weight embeddings
  • rope_parameters (RopeParameters, optional) — Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value for rope_theta and optionally parameters used for scaling in case you want to use RoPE with longer max_position_embeddings.
  • rope_interleave (bool, optional, defaults to True) — Whether to interleave the rotary position embeddings.
  • attention_bias (bool, defaults to False, optional, defaults to False) — Whether to use a bias in the query, key, value and output projection layers during self-attention.
  • attention_dropout (float, optional, defaults to 0.0) — The dropout ratio for the attention probabilities.

这是用于存储 DeepseekV3Model 配置的类。它用于根据指定的参数实例化 DeepSeek 模型,定义模型架构。使用默认值实例化配置将生成一个与 DeepSeek-V3 类似的配置。例如 bzantium/tiny-deepseek-v3。配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PreTrainedConfig 的文档。

>>> from transformers import DeepseekV3Model, DeepseekV3Config

>>> # Initializing a Deepseek-V3 style configuration
>>> configuration = DeepseekV3Config()

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

DeepseekV3Model

class transformers.DeepseekV3Model

< >

( config: DeepseekV3Config )

参数

  • config (DeepseekV3Config) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

The bare Deepseek V3 Model outputting raw hidden-states without any specific head on top.

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None cache_position: torch.LongTensor | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.BaseModelOutputWithPast or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.

    Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

    What are input IDs?

  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    What are attention masks?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1].

    What are position IDs?

  • past_key_values (~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
  • use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

返回

transformers.modeling_outputs.BaseModelOutputWithPast or tuple(torch.FloatTensor)

A transformers.modeling_outputs.BaseModelOutputWithPast or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (DeepseekV3Config) and inputs.

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

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

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

    Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if config.is_encoder_decoder=True in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding.

  • hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

The DeepseekV3Model forward method, overrides the __call__ special method.

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

DeepseekV3ForCausalLM

class transformers.DeepseekV3ForCausalLM

< >

( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )

参数

  • config (DeepseekV3ForCausalLM) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

Deepseek V3 模型,用于因果语言建模。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None cache_position: torch.LongTensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.CausalLMOutputWithPasttuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length), 可选) — 词汇表中输入序列 token 的索引。默认情况下会忽略填充。

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

    输入 ID 是什么?

  • attention_mask (torch.Tensor,形状为 (batch_size, sequence_length), 可选) — 避免对填充 token 索引执行注意力的掩码。掩码值选择在 [0, 1]

    • 1 表示未被掩码的 token,
    • 0 表示被掩码的 token。

    注意力掩码是什么?

  • position_ids (torch.LongTensor,形状为 (batch_size, sequence_length), 可选) — 输入序列 token 在位置嵌入中的位置索引。选择范围为 [0, config.n_positions - 1]

    位置 ID 是什么?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速序列解码。这通常包括在 use_cache=Trueconfig.use_cache=True 时,模型在先前解码阶段返回的 past_key_values

    只允许输入 Cache 实例,请参阅我们的 kv cache 指南。如果未提供 past_key_values,则默认初始化 DynamicCache

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

    如果使用 past_key_values,用户需要只输入未处理的 input_ids(即没有其 past key value 状态提供给此模型的那些),形状为 (batch_size, unprocessed_length),而不是所有 input_ids,形状为 (batch_size, sequence_length)

  • inputs_embeds (torch.FloatTensor,形状为 (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 的 token 将被忽略(掩码),损失仅为标签在 [0, ..., config.vocab_size] 范围内的 token 计算。
  • use_cache (bool, 可选) — 如果设置为 True,则返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • cache_position (torch.LongTensor,形状为 (sequence_length), 可选) — 描述输入序列 token 在序列中位置的索引。与 position_ids 不同,此张量不受填充影响。它用于在正确的位置更新缓存并推断完整的序列长度。
  • logits_to_keep (Union[int, torch.Tensor], 可选, 默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。仅生成需要最后一个 token 的 logits,并且仅为该 token 计算 logits 可以节省内存,这对于长序列或大词汇量来说非常可观。如果为 torch.Tensor,则必须是 1D,对应于序列长度维度中要保留的索引。当使用打包张量格式(批处理和序列长度的单维度)时,这很有用。

返回

transformers.modeling_outputs.CausalLMOutputWithPast or tuple(torch.FloatTensor)

一个 transformers.modeling_outputs.CausalLMOutputWithPast 或一个 torch.FloatTensor 元组(如果传入了 return_dict=False 或当 config.return_dict=False 时),其中包含根据配置(DeepseekV3Config)和输入而变化的各种元素。

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

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

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

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

  • hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

transformers.DeepseekV3ForCausalLM 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> from transformers import AutoTokenizer, DeepseekV3ForCausalLM

>>> model = DeepseekV3ForCausalLM.from_pretrained("meta-deepseek_v3/DeepseekV3-2-7b-hf")
>>> tokenizer = AutoTokenizer.from_pretrained("meta-deepseek_v3/DeepseekV3-2-7b-hf")

>>> 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."

DeepseekV3ForSequenceClassification

class transformers.DeepseekV3ForSequenceClassification

< >

( config )

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.SequenceClassifierOutputWithPasttuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length), 可选) — 词汇表中输入序列 token 的索引。默认情况下会忽略填充。

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

    输入 ID 是什么?

  • attention_mask (torch.Tensor,形状为 (batch_size, sequence_length), 可选) — 避免对填充 token 索引执行注意力的掩码。掩码值选择在 [0, 1]

    • 1 表示未被掩码的 token,
    • 0 表示被掩码的 token。

    注意力掩码是什么?

  • position_ids (torch.LongTensor,形状为 (batch_size, sequence_length), 可选) — 输入序列 token 在位置嵌入中的位置索引。选择范围为 [0, config.n_positions - 1]

    位置 ID 是什么?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速序列解码。这通常包括在 use_cache=Trueconfig.use_cache=True 时,模型在先前解码阶段返回的 past_key_values

    只允许输入 Cache 实例,请参阅我们的 kv cache 指南。如果未提供 past_key_values,则默认初始化 DynamicCache

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

    如果使用 past_key_values,用户需要只输入未处理的 input_ids(即没有其 past key value 状态提供给此模型的那些),形状为 (batch_size, unprocessed_length),而不是所有 input_ids,形状为 (batch_size, sequence_length)

  • inputs_embeds (torch.FloatTensor,形状为 (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 的 token 将被忽略(掩码),损失仅为标签在 [0, ..., config.vocab_size] 范围内的 token 计算。
  • use_cache (bool, optional) — 如果设置为 True,将返回 past_key_values 键值状态,并可用于加速解码(请参阅 past_key_values)。

返回

transformers.modeling_outputs.SequenceClassifierOutputWithPasttuple(torch.FloatTensor)

A transformers.modeling_outputs.SequenceClassifierOutputWithPast or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (None) and inputs.

  • loss (形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。

  • logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(SoftMax 之前)。

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

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

  • hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

The GenericForSequenceClassification forward method, overrides the __call__ special method.

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

DeepseekV3ForTokenClassification

class transformers.DeepseekV3ForTokenClassification

< >

( config )

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.TokenClassifierOutput or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.

    Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

    什么是输入 ID?

  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — Labels for computing the masked language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].
  • use_cache (bool, optional) — 如果设置为 True,将返回 past_key_values 键值状态,并可用于加速解码(请参阅 past_key_values)。

返回

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

A transformers.modeling_outputs.TokenClassifierOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (None) and inputs.

  • loss (形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回) — 分类损失。

  • logits (形状为 (batch_size, sequence_length, config.num_labels)torch.FloatTensor) — 分类分数(SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

The GenericForTokenClassification forward method, overrides the __call__ special method.

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.