Update modeling_minicpm.py
Browse files143 unmodified lines14414514614714814915015115215315415536 unmodified lines1921931941951961971989 unmodified lines208209210211212213214215216217218219220221222312 unmodified lines535536537538539540541364 unmodified lines906907908909910911912223 unmodified lines1136113711381139114011411142221 unmodified lines1364136513661367136813691370257 unmodified lines1628162916301631163216331634163516361637163833 unmodified lines1672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172122 unmodified lines1744174517461747174817491750220 unmodified lines19711972197319741975197619771978197919801981198219831984198519861987198819891990173 unmodified lines2164216521662167216821692170217121722173106 unmodified lines2280228122822283143 unmodified linesdef calc_chunks_with_stride(cu_seqlen, chunk_size, kernel_stride):"""Compute the chunks that require Sparse attention, with stride support.Args:cu_seqlen (torch.Tensor): Cumulative sequence lengths for each sample.chunk_size (int): Chunk size used for Sparse attention.kernel_stride (int): Stride size when sliding over the sequence.Returns:filtered_indices (torch.Tensor): Indices used to directly index into the key/value tensors.cu_seqlens_compressed (torch.Tensor): Cumulative sequence lengths after compression.36 unmodified linesdef __init__(self, head_num_k, head_dim, kernel_size, kernel_stride=16):"""Module for compressing key (K) representations.Args:head_num_k (int): Number of key attention heads.head_dim (int): Dimension of each attention head.9 unmodified linesdef forward(self, k: torch.Tensor, cu_seqlens):"""Forward pass for compressing the key (K) tensor.Args:k (torch.Tensor): Input key tensor of shape (total_seq_len, num_heads, head_dim).cu_seqlens (torch.Tensor): Cumulative sequence lengths for each sample in the batch, typically used for handling variable-length sequences.Returns:compress_k (torch.Tensor): Compressed key tensor.cu_seqlens_compressed (torch.Tensor): Updated cumulative sequence lengths after compression."""# Compute chunk-related metadata, with stride supportfiltered_k_indices, cu_seqlens_compressed = calc_chunks_with_stride(312 unmodified linesdef apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):"""Applies Rotary Position Embedding to the query and key tensors.Args:q (`torch.Tensor`): The query tensor.k (`torch.Tensor`): The key tensor.364 unmodified lines"""Calls the forward method of Flash Attention - if the input hidden states contain at least one padding tokenfirst unpad the input, then computes the attention scores and pad the final attention scores.Args:query_states (`torch.Tensor`):Input query states to be passed to Flash Attention API223 unmodified lines"""Calls the forward method of Flash Attention - if the input hidden states contain at least one padding tokenfirst unpad the input, then computes the attention scores and pad the final attention scores.Args:query_states (`torch.Tensor`):Input query states to be passed to Flash Attention API221 unmodified lines"""Calls the forward method of Flash Attention - if the input hidden states contain at least one padding tokenfirst unpad the input, then computes the attention scores and pad the final attention scores.Args:query_states (`torch.Tensor`):Input query states to be passed to Flash Attention API257 unmodified linesThis model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods thelibrary implements for all its model (such as downloading or saving, resizing the input embeddings, pruning headsetc.)This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usageand behavior.Parameters:config ([`MiniCPMConfig`]):Model configuration class with all the parameters of the model. Initializing with a config file does not33 unmodified linesinput_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 provideit.Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and[`PreTrainedTokenizer.__call__`] for details.[What are input IDs?](../glossary#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?](../glossary#attention-mask)Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and[`PreTrainedTokenizer.__call__`] for details.If `past_key_values` is used, optionally only the last `input_ids` have to be input (see`past_key_values`).If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for moreinformation on the default strategy.- 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]`.[What are position IDs?](../glossary#position-ids)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-attentionblocks) 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`.Two formats are allowed:- a [`~cache_utils.Cache`] instance;- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors ofshape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacycache format.The model will output the same cache format that is fed as input. If no `past_key_values` are passed, thelegacy cache format will be returned.If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don'thave their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`of shape `(batch_size, sequence_length)`.22 unmodified linesclass MiniCPMModel(MiniCPMPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]Args:config: MiniCPMConfig"""220 unmodified linesLabels 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]`.Returns:Example:```python>>> from transformers import AutoTokenizer, MiniCPMForCausalLM>>> model = MiniCPMForCausalLM.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]173 unmodified lines@add_start_docstrings("""The MiniCPM Model transformer with a sequence classification head on top (linear layer).[`MiniCPMForSequenceClassification`] uses the last token in order to do the classification, as other causal models(e.g. GPT-2) do.Since it does classification on the last token, it requires to know the position of the last token. If a`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. Ifno `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the106 unmodified linespast_key_values=transformer_outputs.past_key_values,hidden_states=transformer_outputs.hidden_states,attentions=transformer_outputs.attentions,)143 unmodified lines14414514614714814915015115215336 unmodified lines1901911921931941959 unmodified lines205206207208209210211212213214215216312 unmodified lines529530531532533534364 unmodified lines899900901902903904223 unmodified lines112811291130113111321133221 unmodified lines135513561357135813591360257 unmodified lines16181619162016211622162316241625162633 unmodified lines1660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169722 unmodified lines172017211722172317241725220 unmodified lines19461947194819491950195119521953195419551956195719581959173 unmodified lines21332134213521362137213821392140106 unmodified lines2247224822492250143 unmodified linesdef calc_chunks_with_stride(cu_seqlen, chunk_size, kernel_stride):"""Compute the chunks that require Sparse attention, with stride support.Args:cu_seqlen (torch.Tensor): Cumulative sequence lengths for each sample.chunk_size (int): Chunk size used for Sparse attention.kernel_stride (int): Stride size when sliding over the sequence.Returns:filtered_indices (torch.Tensor): Indices used to directly index into the key/value tensors.cu_seqlens_compressed (torch.Tensor): Cumulative sequence lengths after compression.36 unmodified linesdef __init__(self, head_num_k, head_dim, kernel_size, kernel_stride=16):"""Module for compressing key (K) representations.Args:head_num_k (int): Number of key attention heads.head_dim (int): Dimension of each attention head.9 unmodified linesdef forward(self, k: torch.Tensor, cu_seqlens):"""Forward pass for compressing the key (K) tensor.Args:k (torch.Tensor): Input key tensor of shape (total_seq_len, num_heads, head_dim).cu_seqlens (torch.Tensor): Cumulative sequence lengths for each sample in the batch, typically used for handling variable-length sequences.Returns:compress_k (torch.Tensor): Compressed key tensor.cu_seqlens_compressed (torch.Tensor): Updated cumulative sequence lengths after compression."""# Compute chunk-related metadata, with stride supportfiltered_k_indices, cu_seqlens_compressed = calc_chunks_with_stride(312 unmodified linesdef apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):"""Applies Rotary Position Embedding to the query and key tensors.Args:q (`torch.Tensor`): The query tensor.k (`torch.Tensor`): The key tensor.364 unmodified lines"""Calls the forward method of Flash Attention - if the input hidden states contain at least one padding tokenfirst unpad the input, then computes the attention scores and pad the final attention scores.Args:query_states (`torch.Tensor`):Input query states to be passed to Flash Attention API223 unmodified lines"""Calls the forward method of Flash Attention - if the input hidden states contain at least one padding tokenfirst unpad the input, then computes the attention scores and pad the final attention scores.Args:query_states (`torch.Tensor`):Input query states to be passed to Flash Attention API221 unmodified lines"""Calls the forward method of Flash Attention - if the input hidden states contain at least one padding tokenfirst unpad the input, then computes the attention scores and pad the final attention scores.Args:query_states (`torch.Tensor`):Input query states to be passed to Flash Attention API257 unmodified linesThis model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods thelibrary implements for all its model (such as downloading or saving, resizing the input embeddings, pruning headsetc.)This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usageand behavior.Parameters:config ([`MiniCPMConfig`]):Model configuration class with all the parameters of the model. Initializing with a config file does not33 unmodified linesinput_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 provideit.Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and[`PreTrainedTokenizer.__call__`] for details.[What are input IDs?](../glossary#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?](../glossary#attention-mask)Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and[`PreTrainedTokenizer.__call__`] for details.If `past_key_values` is used, optionally only the last `input_ids` have to be input (see`past_key_values`).If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for moreinformation on the default strategy.- 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]`.[What are position IDs?](../glossary#position-ids)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-attentionblocks) 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`.Two formats are allowed:- a [`~cache_utils.Cache`] instance;- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors ofshape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacycache format.The model will output the same cache format that is fed as input. If no `past_key_values` are passed, thelegacy cache format will be returned.If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don'thave their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`of shape `(batch_size, sequence_length)`.22 unmodified linesclass MiniCPMModel(MiniCPMPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]Args:config: MiniCPMConfig"""220 unmodified linesLabels 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]`.Returns:Example:```python>>> from transformers import AutoTokenizer, MiniCPMForCausalLM>>> model = MiniCPMForCausalLM.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]173 unmodified lines@add_start_docstrings("""The MiniCPM Model transformer with a sequence classification head on top (linear layer).[`MiniCPMForSequenceClassification`] uses the last token in order to do the classification, as other causal models(e.g. GPT-2) do.Since it does classification on the last token, it requires to know the position of the last token. If a`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. Ifno `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the106 unmodified linespast_key_values=transformer_outputs.past_key_values,hidden_states=transformer_outputs.hidden_states,attentions=transformer_outputs.attentions,)
modeling_minicpm.py+1-34