Transformers 文档

Starcoder2

Starcoder2

概述

StarCoder2 是一个用于代码的开源大型语言模型家族,提供三种不同规模的模型,分别具有 3B、7B 和 15B 参数。旗舰模型 StarCoder2-15B 在超过 4 万亿个标记和 600 多种编程语言的数据集 The Stack v2 上进行了训练。所有模型都使用了分组查询注意力机制,上下文窗口为 16,384 个标记,滑动窗口注意力为 4,096 个标记,并使用填充中间目标进行训练。这些模型已与论文 StarCoder 2 和 The Stack v2: 下一代 一起发布,作者包括 Anton Lozhkov、Raymond Li、Loubna Ben Allal、Federico Cassano、Joel Lamy-Poirier、Nouamane Tazi、Ao Tang、Dmytro Pykhtar、Jiawei Liu、Yuxiang Wei、Tianyang Liu、Max Tian、Denis Kocetkov、Arthur Zucker、Younes Belkada、Zijian Wang、Qian Liu、Dmitry Abulkhanov、Indraneil Paul、Zhuang Li、Wen-Ding Li、Megan Risdal、Jia Li、Jian Zhu、Terry Yue Zhuo、Evgenii Zheltonozhskii、Nii Osae Osae Dade、Wenhao Yu、Lucas Krauß、Naman Jain、Yixuan Su、Xuanli He、Manan Dey、Edoardo Abati、Yekun Chai、Niklas Muennighoff、Xiangru Tang、Muhtasham Oblokulov、Christopher Akiki、Marc Marone、Chenghao Mou、Mayank Mishra、Alex Gu、Binyuan Hui、Tri Dao、Armel Zebaze、Olivier Dehaene、Nicolas Patry、Canwen Xu、Julian McAuley、Han Hu、Torsten Scholak、Sebastien Paquet、Jennifer Robinson、Carolyn Jane Anderson、Nicolas Chapados、Mostofa Patwary、Nima Tajbakhsh、Yacine Jernite、Carlos Muñoz Ferrandis、Lingming Zhang、Sean Hughes、Thomas Wolf、Arjun Guha、Leandro von Werra 和 Harm de Vries。

论文的摘要如下:

BigCode项目是一个开放科学合作项目,专注于负责任地开发用于代码的大型语言模型(Code LLMs),并推出了StarCoder2。我们与Software Heritage(SWH)合作,在其源代码档案的数字公共资源基础上构建了The Stack v2。除了涵盖619种编程语言的SWH仓库外,我们还精心挑选了其他高质量的数据源,如GitHub拉取请求、Kaggle笔记本和代码文档。这使得训练集比第一个StarCoder数据集大了4倍。我们在3.3到4.3万亿个token上训练了具有3B、7B和15B参数的StarCoder2模型,并在全面的Code LLM基准测试中进行了彻底评估。我们发现,我们的小模型StarCoder2-3B在大多数基准测试中优于其他类似大小的Code LLM,并且也优于StarCoderBase-15B。我们的大模型StarCoder2-15B显著优于其他类似大小的模型。此外,它与CodeLlama-34B(一个大小是其两倍多的模型)相当或优于它。尽管DeepSeekCoder-33B在高资源语言的代码补全方面表现最佳,但我们发现StarCoder2-15B在数学和代码推理基准测试以及几种低资源语言上优于它。我们在OpenRAIL许可证下提供了模型权重,并通过发布源代码数据的Software Heritage持久标识符(SWHIDs)确保了训练数据的完全透明性。

许可证

这些模型是根据BigCode OpenRAIL-M v1 许可协议授权的。

使用提示

StarCoder2 模型可以在 HuggingFace hub 中找到。你可以在 StarCoder2 的 GitHub repo 中找到一些推理和微调的示例。

这些现成的检查点可以通过HuggingFace Hub下载和使用:

>>> from transformers import AutoModelForCausalLM, AutoTokenizer

>>> model = AutoModelForCausalLM.from_pretrained("bigcode/starcoder2-7b", device_map="auto")
>>> tokenizer = AutoTokenizer.from_pretrained("bigcode/starcoder2-7b")

>>> prompt = "def print_hello_world():"

>>> model_inputs = tokenizer([prompt], return_tensors="pt").to("cuda")

>>> generated_ids = model.generate(**model_inputs, max_new_tokens=10, do_sample=False)
>>> tokenizer.batch_decode(generated_ids)[0]
'def print_hello_world():\n    print("Hello World!")\n\ndef print'

Starcoder2Config

transformers.Starcoder2Config

< >

( vocab_size = 49152 hidden_size = 3072 intermediate_size = 12288 num_hidden_layers = 30 num_attention_heads = 24 num_key_value_heads = 2 hidden_act = 'gelu_pytorch_tanh' max_position_embeddings = 4096 initializer_range = 0.018042 norm_epsilon = 1e-05 use_cache = True bos_token_id = 50256 eos_token_id = 50256 rope_theta = 10000.0 rope_scaling = None sliding_window = None attention_dropout = 0.0 residual_dropout = 0.0 embedding_dropout = 0.0 use_bias = True **kwargs )

参数

  • vocab_size (int, 可选, 默认为 49152) — Starcoder2 模型的词汇表大小。定义了可以通过调用 Starcoder2Model 时传递的 inputs_ids 表示的不同标记的数量
  • hidden_size (int, optional, defaults to 3072) — 隐藏表示的维度。
  • intermediate_size (int, optional, 默认为 12288) — MLP 表示的维度。
  • num_hidden_layers (int, optional, defaults to 30) — Transformer编码器中的隐藏层数量。
  • num_attention_heads (int, optional, 默认为 24) — Transformer 编码器中每个注意力层的注意力头数量。
  • num_key_value_heads (int, 可选, 默认为 2) — 这是用于实现分组查询注意力(Grouped Query Attention)的键值头数量。如果 num_key_value_heads=num_attention_heads,模型将使用多头注意力(MHA),如果 num_key_value_heads=1,模型将使用多查询注意力(MQA),否则将使用GQA。当 将多头检查点转换为GQA检查点时,每个组的键和值头应通过平均池化该组中的所有原始头来构建。 更多详情请查看这篇论文。如果未指定,将默认为8.
  • hidden_act (strfunction, 可选, 默认为 "gelu_pytorch_tanh") — 解码器中的非线性激活函数(函数或字符串)。
  • max_position_embeddings (int, 可选, 默认为 4096) — 该模型可能使用的最大序列长度。Starcoder2的滑动窗口注意力机制允许最多4096*32个标记的序列。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • norm_epsilon (float, optional, 默认为 1e-05) — 层归一化的 epsilon 值
  • use_cache (bool, 可选, 默认为 True) — 模型是否应返回最后的键/值注意力(并非所有模型都使用)。仅在 config.is_decoder=True 时相关。
  • bos_token_id (int, optional, 默认为 50256) — “序列开始”标记的ID。
  • eos_token_id (int, optional, defaults to 50256) — “序列结束”标记的ID。
  • rope_theta (float, optional, 默认为 10000.0) — RoPE 嵌入的基础周期。
  • rope_scaling (Dict, optional) — Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type and you expect the model to work on longer max_position_embeddings, we recommend you to update this value accordingly. Expected contents: rope_type (str): The sub-variant of RoPE to use. Can be one of [‘default’, ‘linear’, ‘dynamic’, ‘yarn’, ‘longrope’, ‘llama3’], with ‘default’ being the original RoPE implementation. factor (float, optional): Used with all rope types except ‘default’. The scaling factor to apply to the RoPE embeddings. In most scaling types, a factor of x will enable the model to handle sequences of length x original maximum pre-trained length. original_max_position_embeddings (int, optional): Used with ‘dynamic’, ‘longrope’ and ‘llama3’. The original max position embeddings used during pretraining. attention_factor (float, optional): Used with ‘yarn’ and ‘longrope’. The scaling factor to be applied on the attention computation. If unspecified, it defaults to value recommended by the implementation, using the factor field to infer the suggested value. beta_fast (float, optional): Only used with ‘yarn’. Parameter to set the boundary for extrapolation (only) in the linear ramp function. If unspecified, it defaults to 32. beta_slow (float, optional): Only used with ‘yarn’. Parameter to set the boundary for interpolation (only) in the linear ramp function. If unspecified, it defaults to 1. short_factor (List[float], optional): Only used with ‘longrope’. The scaling factor to be applied to short contexts (< original_max_position_embeddings). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 long_factor (List[float], optional): Only used with ‘longrope’. The scaling factor to be applied to long contexts (< original_max_position_embeddings). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 low_freq_factor (float, optional): Only used with ‘llama3’. Scaling factor applied to low frequency components of the RoPE high_freq_factor (float, optional*): Only used with ‘llama3’. Scaling factor applied to high frequency components of the RoPE
  • sliding_window (int, 可选) — 滑动窗口注意力窗口大小。如果未指定,将默认为 None(无滑动窗口)。
  • attention_dropout (float, optional, 默认为 0.0) — 注意力概率的丢弃比例。
  • residual_dropout (float, optional, defaults to 0.0) — 残差连接丢弃值。
  • embedding_dropout (float, optional, defaults to 0.0) — 嵌入层的dropout。
  • use_bias (bool, 可选, 默认为 True) — 是否在模型的线性层中使用偏置项。

这是用于存储Starcoder2Model配置的配置类。它用于根据指定的参数实例化一个Starcoder2模型,定义模型架构。使用默认值实例化配置将产生与bigcode/starcoder2-7b模型类似的配置。

配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。

>>> from transformers import Starcoder2Model, Starcoder2Config

>>> # Initializing a Starcoder2 7B style configuration
>>> configuration = Starcoder2Config()

>>> # Initializing a model from the Starcoder2 7B style configuration
>>> model = Starcoder2Model(configuration)

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

Starcoder2Model

transformers.Starcoder2Model

< >

( config: Starcoder2Config )

参数

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

裸的Starcoder2模型输出原始的隐藏状态,没有任何特定的头部。 此模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

Transformer解码器由config.num_hidden_layers层组成。每一层都是一个Starcoder2DecoderLayer

前进

< >

( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None )

参数

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

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入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.

    什么是注意力掩码?

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    如果使用了past_key_values,则可以选择性地仅输入最后一个decoder_input_ids(参见past_key_values)。

    如果你想改变填充行为,你应该阅读modeling_opt._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

    • 1 indicates the head is not masked,
    • 0 indicates the head is 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 or tuple(tuple(torch.FloatTensor)), 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.

    允许两种格式:

    • a Cache instance, see our kv cache guide;
    • Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)). This is also known as the legacy cache format.

    模型将输出与输入相同的缓存格式。如果没有传递past_key_values,将返回旧的缓存格式。

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后input_ids(那些没有将其过去键值状态提供给此模型的input_ids),而不是形状为(batch_size, sequence_length)的所有input_ids

  • inputs_embeds (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。与position_ids相反, 这个张量不受填充的影响。它用于在正确的位置更新缓存并推断 完整的序列长度。

Starcoder2Model 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

Starcoder2ForCausalLM

transformers.Starcoder2ForCausalLM

< >

( config )

前进

< >

( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None num_logits_to_keep: int = 0 **loss_kwargs ) transformers.modeling_outputs.CausalLMOutputWithPasttuple(torch.FloatTensor)

参数

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

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入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.

    什么是注意力掩码?

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    如果使用了past_key_values,则可以选择性地仅输入最后一个decoder_input_ids(参见past_key_values)。

    如果你想改变填充行为,你应该阅读modeling_opt._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

    • 1 indicates the head is not masked,
    • 0 indicates the head is 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 or tuple(tuple(torch.FloatTensor)), 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.

    允许两种格式:

    • a Cache instance, see our kv cache guide;
    • Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)). This is also known as the legacy cache format.

    模型将输出与输入相同的缓存格式。如果没有传递past_key_values,将返回旧的缓存格式。

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后input_ids(那些没有将其过去键值状态提供给此模型的input_ids),而不是形状为(batch_size, sequence_length)的所有input_ids

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。与position_ids相反, 这个张量不受填充的影响。它用于在正确的位置更新缓存并推断 完整的序列长度。
  • Args — 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].

    num_logits_to_keep (int, 可选): 计算最后num_logits_to_keep个token的logits。如果为0,则计算所有input_ids的logits(特殊情况)。生成时只需要最后一个token的logits,仅计算该token的logits可以节省内存,这对于长序列或大词汇量来说非常重要。

返回

transformers.modeling_outputs.CausalLMOutputWithPasttuple(torch.FloatTensor)

一个 transformers.modeling_outputs.CausalLMOutputWithPast 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(Starcoder2Config)和输入。

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

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

  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(torch.FloatTensor) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量)

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

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

    模型在每层输出处的隐藏状态加上可选的初始嵌入输出。

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

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

Starcoder2ForCausalLM 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, Starcoder2ForCausalLM

>>> model = Starcoder2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)

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

Starcoder2ForSequenceClassification

transformers.Starcoder2ForSequenceClassification

< >

( config )

参数

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

Starcoder2 模型转换器,顶部带有序列分类头(线性层)。

Starcoder2ForSequenceClassification 使用最后一个标记进行分类,与其他因果模型(例如 GPT-2)相同。

由于它对最后一个标记进行分类,因此需要知道最后一个标记的位置。如果在配置中定义了pad_token_id,它会在每一行中找到不是填充标记的最后一个标记。如果没有定义pad_token_id,它只需取批次中每一行的最后一个值。由于在传递inputs_embeds而不是input_ids时无法猜测填充标记,它会执行相同的操作(取批次中每一行的最后一个值)。

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Union[transformers.cache_utils.Cache, typing.List[torch.FloatTensor], NoneType] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None )

参数

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

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入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.

    什么是注意力掩码?

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    如果使用了past_key_values,则可以选择性地仅输入最后一个decoder_input_ids(参见past_key_values)。

    如果你想改变填充行为,你应该阅读modeling_opt._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

    • 1 indicates the head is not masked,
    • 0 indicates the head is 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 or tuple(tuple(torch.FloatTensor)), 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.

    允许两种格式:

    • a Cache instance, see our kv cache guide;
    • Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)). This is also known as the legacy cache format.

    模型将输出与输入相同的缓存格式。如果没有传递past_key_values,将返回旧的缓存格式。

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后input_ids(那些没有将其过去键值状态提供给此模型的input_ids),而不是形状为(batch_size, sequence_length)的所有input_ids

  • inputs_embeds (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。与position_ids相反, 这个张量不受填充的影响。它用于在正确的位置更新缓存并推断 完整的序列长度。
  • labels (torch.LongTensor 形状为 (batch_size,), 可选) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。

Starcoder2ForSequenceClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

Starcoder2ForTokenClassification

transformers.Starcoder2ForTokenClassification

< >

( config )

参数

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

Starcoder2 模型转换器,顶部带有标记分类头(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

参数

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

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入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.

    什么是注意力掩码?

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    如果使用了past_key_values,则可以选择性地仅输入最后一个decoder_input_ids(参见past_key_values)。

    如果你想改变填充行为,你应该阅读modeling_opt._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

    • 1 indicates the head is not masked,
    • 0 indicates the head is 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 or tuple(tuple(torch.FloatTensor)), 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.

    允许两种格式:

    • a Cache instance, see our kv cache guide;
    • Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)). This is also known as the legacy cache format.

    模型将输出与输入相同的缓存格式。如果没有传递past_key_values,将返回旧的缓存格式。

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后input_ids(那些没有将其过去键值状态提供给此模型的input_ids),而不是形状为(batch_size, sequence_length)的所有input_ids

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。与position_ids不同, 这个张量不受填充的影响。它用于在正确的位置更新缓存并推断 完整的序列长度。
  • labels (torch.LongTensor 形状为 (batch_size,), 可选) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.TokenClassifierOutput 或一个包含 torch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(Starcoder2Config)和输入。

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

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

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

    模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。

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

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

Starcoder2ForTokenClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, Starcoder2ForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("bigcode/starcoder2-7b")
>>> model = Starcoder2ForTokenClassification.from_pretrained("bigcode/starcoder2-7b")

>>> inputs = tokenizer(
...     "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
... )

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_token_class_ids = logits.argmax(-1)

>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]

>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
< > Update on GitHub