
    Uh                     N   d dl mZmZmZmZmZ d dlZd dlmZ ddl	m
Z
 ddlmZmZmZ ddlmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlmZmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z% ddl&m'Z' ddl(m)Z)  e$       rd dl*m+Z+ ddl,m-Z-  e%j\                  e/      Z0 G d dejb                        Z2 G d dejb                        Z3dejh                  de5dejh                  fdZ6	 d4dejb                  dejh                  dejh                  dejh                  deejh                     d e7d!e7fd"Z8d# Z9d5d$Z: G d% d&ejb                        Z; G d' d(ejb                        Z< G d) d*e      Z=e" G d+ d,e             Z>e" G d- d.e>             Z? G d/ d0ee!      Z@e" G d1 d2e>e             ZAg d3ZBy)6    )CallableListOptionalTupleUnionN   )ACT2FN)CacheHybridCacheStaticCache)GenerationMixin)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tupleis_torch_flex_attn_availablelogging)deprecate_kwarg   )Cohere2Config)	BlockMask)make_flex_block_causal_maskc                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )Cohere2RotaryEmbeddingconfigc                    t         |           t        |d      rG|j                  ;|j                  j	                  d|j                  j	                  d            | _        nd| _        |j                  | _        |j                  | _        || _	        t        | j
                     | _        | j                  | j                  |      \  }| _        | j                  d|d       | j                  | _        y )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)super__init__hasattrr%   getr&   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr#   r   rope_init_fnattention_scalingregister_bufferr)   original_inv_freq)selfr#   devicer)   	__class__s       ~/var/www/catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/cohere2/modeling_cohere2.pyr,   zCohere2RotaryEmbedding.__init__3   s    6>*v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%    c                 .   | j                   d d d d f   j                         j                  |j                  d   dd      }|d d d d d f   j                         }t	        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        j                  |d      5  |j                         |j                         z  j                  dd      }t        j                  |dd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j                  |j                   
      	j                  |j                   
      fS # 1 sw Y   AxY w)Nr   r   mpscpuF)device_typeenabled   dimdtype)r)   floatexpandshape
isinstancer7   r'   strtorchautocast	transposerepeat_interleavecosr3   sintorE   )
r6   xposition_idsinv_freq_expandedposition_ids_expandedr?   freqsembrO   rP   s
             r9   forwardzCohere2RotaryEmbedding.forwardD   sD    !MM$4-8>>@GGHZHZ[\H]_acde ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfk^^UC 	5&,,.1F1L1L1NNYYZ[]^_E))%;C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFFN)
__name__
__module____qualname__r   r,   rK   no_gradr   rX   __classcell__r8   s   @r9   r"   r"   2   s3    /} /" U]]_<  <r:   r"   c                   &     e Zd Zd fd	Zd Z xZS )Cohere2LayerNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)zcThe hidden size can be a tuple or an int. The tuple is used for QKNorm to normalize across head_dimN)r+   r,   nn	ParameterrK   onesweightvariance_epsilon)r6   hidden_sizeepsbiasr8   s       r9   r,   zCohere2LayerNorm.__init__U   s/    ll5::k#:; #r:   c                    |j                   }|j                  t        j                        }|j	                  dd      }||z
  j                  d      j	                  dd      }||z
  t        j                  || j                  z         z  }| j                  j                  t        j                        |z  }|j                  |      S )Nr<   T)keepdimrA   )	rE   rQ   rK   float32meanpowrsqrtrg   rf   )r6   hidden_statesinput_dtypern   variances        r9   rX   zCohere2LayerNorm.forward[   s    #))%((7!!"d!3!D(--a055b$5G&-XH]H]=]1^^u}}5E,,r:   )Ngh㈵>FrZ   r[   r\   r,   rX   r^   r_   s   @r9   ra   ra   T   s    $-r:   ra   rq   n_repreturnc                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)rH   rG   reshape)rq   ru   batchnum_key_value_headsslenhead_dims         r9   	repeat_kvr}   e   so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr:   modulequerykeyvalueattention_maskscalingdropoutc                 T   t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
|#|d d d d d d d |j
                  d   f   }|
|z   }
t        j                  j                  |
dt        j                        j                  |j                        }
t        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )NrA   r   r<   )rC   rE   )ptrainingr   )r}   num_key_value_groupsrK   matmulrM   rH   rc   
functionalsoftmaxrm   rQ   rE   r   r   
contiguous)r~   r   r   r   r   r   r   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r9   eager_attention_forwardr   q   s    3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#k1==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r:   c                     | dd d df   }| ddd df   }t        j                  | |gd      j                  d      }|S )N.rA   r   r<   rB   r   )rK   stackflatten)rR   x1x2rot_xs       r9   rotate_halfr      sL    	
3!8B	
319BKK"b	r*2226ELr:   c                 6   | j                   }| j                         } |j                         }|j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }|j	                  |      |j	                  |      fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    rD   )rE   rF   	unsqueezer   rQ   )	qkrO   rP   rS   unsqueeze_dimrE   q_embedk_embeds	            r9   apply_rotary_pos_embr      s    ( GGE		A		A
--
&C
--
&C3w;q>C/0G3w;q>C/0G::E:"GJJUJ$;;;r:   c                   >    e Zd ZdZddedee   f fdZ	 	 ddej                  de
ej                  ej                  f   deej                     dee   d	eej                     d
ee   de
ej                  eej                     ee
ej                        f   fdZ xZS )Cohere2Attentionz=Multi-headed attention from 'Attention Is All You Need' paperr#   	layer_idxc                    t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        | j                  dz  | _
        |j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j                  | j                  z  |j
                  |j                        | _        | j                  dz   | j                  j(                  z  dk7  r|j*                  | _        y d | _        y )Nr|   g      Trj   r   r   )r+   r,   r#   r   getattrrh   num_attention_headsr|   rz   r   r   attention_dropout	is_causalrc   Linearattention_biasq_projk_projv_projo_projsliding_window_patternsliding_windowr6   r#   r   r8   s      r9   r,   zCohere2Attention.__init__   s   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
 '+nnq&8DKK<^<^%^bc%cF!! 	im 	r:   rq   position_embeddingsr   past_key_valuecache_positionr   rv   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }|\  }}| j                  t        |	|
||      \  }	}
|~||| j                  |d}|j                  |
|| j                  |      \  }
}|J| j                  j                  dk(  r1|j                   d   }|
d d d d d |d d f   |d d d d d |d d f   }}
t        }| j                  j                  dk7  r^| j                  j                  dk(  r(|j                  dd	      rt        j!                  d
       nt"        | j                  j                     } || |	|
||f| j$                  sdn| j&                  | j(                  | j                  d|\  }} |j*                  g |d j-                         }| j/                  |      }||fS )Nr<   r   rA   )rP   rO   r   r   flash_attention_2eagersdpaoutput_attentionsFz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.        )r   r   r   )rH   r|   r   viewrM   r   r   r   r   updater   r#   _attn_implementationr   r.   loggerwarning_oncer   r   r   r   rx   r   r   )r6   rq   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   rO   rP   cache_kwargsseq_lenattention_interfacer   r   s                      r9   rX   zCohere2Attention.forward   sb    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&S*';L*VY[^'_$L*%"&"5"5"0	L (6'<'<ZW[WeWegs't$J )dkk.N.NRe.e(..r2+5aHWHa6G+H,WXZ[]e^e]eghWhJiL
(?;;++w6{{//69fjjI\^c>d##L
 '>dkk>^>^&_#$7
%
  $}}C$2H2HLL..
%
 
%
!\ *k));;;;FFHkk+.L((r:   rY   )NN)rZ   r[   r\   __doc__r   r   intr,   rK   Tensorr   r
   
LongTensorr   r   rX   r^   r_   s   @r9   r   r      s    G
} 
# 
> +/59:)||:) #5<<#=>:) !.	:)
 !:) !!1!12:) -.:) 
u||Xell3XeELL>Q5RR	S:)r:   r   c                   $     e Zd Z fdZd Z xZS )
Cohere2MLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _	        t        |j                     | _        y NFr   )r+   r,   r#   rh   intermediate_sizerc   r   	gate_projup_proj	down_projr	   
hidden_actact_fnr6   r#   r8   s     r9   r,   zCohere2MLP.__init__  s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../r:   c                     | j                  | j                  | j                  |            | j                  |      z        }|S rY   )r   r   r   r   )r6   rR   r   s      r9   rX   zCohere2MLP.forward  s6    NN4;;t~~a/@#ADLLQRO#ST	r:   rt   r_   s   @r9   r   r     s    0r:   r   c                   b    e Zd Zdedef fdZ edd      	 	 	 	 	 ddej                  de	ej                  ej                  f   d	e
ej                     d
e
e   de
e   de
e   de
ej                     dee   de	ej                   e
e	ej                   ej                   f      f   fd       Z xZS )Cohere2DecoderLayerr#   r   c                 J   t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        || _
        |dz   | j                  j                  z  dk7  | _        |j                  | _        y )Nrh   ri   r   r   )r+   r,   rh   r   	self_attnr   mlpra   layer_norm_epsinput_layernormr#   r   
is_slidingr   r   s      r9   r,   zCohere2DecoderLayer.__init__  s    !--)&)<f%/V=O=OV\VkVkl$q=DKK,N,NNRSS$33r:   last_cache_positionz4.53.0)versionrq   r   r   r   r   	use_cacher   r   rv   c                 F   | j                   r?|<t        |j                  d   | j                        }	| j                  j
                  dk(  r|dd|	 df   }nt        j                  |j                        j                  }
t        j                  t        j                  |t        j                        | j                         }t        j                  ||
|      }|d   |	z
  dz   }t        j                  |d      }t        j                  t        |	|j                  d         |j                   	      }||z  }|dddddd|f   }|}| j#                  |      } | j$                  d|||||||d
|\  }}| j'                  |      }||z   |z   }|f}|r||fz  }|S )ax  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            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`).
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
        Nr   r   rD   diagonalr<   r   )minr7   )rq   r   r   r   r   r   r    )r   maxrH   r   r#   r   rK   finforE   r   tril	ones_likeboolwhereclamparanger7   r   r   r   )r6   rq   r   r   r   r   r   r   r   effective_seq_len	min_dtypesliding_window_maskoffsetmask_indexesresidualhidden_states_attentionself_attn_weightshidden_states_mlpoutputss                      r9   rX   zCohere2DecoderLayer.forward&  s   @ ??~9 #N$8$8$;T=P=P Q {{//3FF!/4E3E3F0F!G "KK(;(;<@@	&+jjOON%**EQUQdQdPd'# "'-@)^!\'+.??!CV3  %||)>+?+?+CD^MbMb  &!/1a0E!F ,,]; 6DT^^ 	6
' 3))/)	6
 	6
2!2 !HH]3 !#::=NN ")++Gr:   )NNFFN)rZ   r[   r\   r   r   r,   r   rK   r   r   r   r
   r   r   r   r   FloatTensorrX   r^   r_   s   @r9   r   r     s   4} 4 4 *H=
 26*.,1$)59U||U #5<<#=>U !.	U
 !U $D>U D>U !!1!12U -.U 
u  (51B1BEDUDU1U+V"WW	XU >Ur:   r   c                   F    e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdZdZd Zy)Cohere2PreTrainedModelmodelTr   past_key_valuesc                    | j                   j                  }t        |t        j                        rY|j
                  j                  j                  d|       |j                  %|j                  j                  j                          y y t        |t        j                        rf|j
                  j                  j                  d|       |j                  2|j
                  j                  |j                     j                          y y t        |t              r&|j
                  j                  j                  d       y y )Nr   )rn   stdg      ?)r#   initializer_rangerI   rc   r   rf   datanormal_rj   zero_	Embeddingpadding_idxra   fill_)r6   r~   r  s      r9   _init_weightsz$Cohere2PreTrainedModel._init_weights  s    kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . 01MM$$S) 2r:   N)rZ   r[   r\   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_flex_attn_supports_cache_class_supports_quantized_cache_supports_static_cache_supports_attention_backendr  r   r:   r9   r   r     sS     L&*#./#4"5!N  $!"&*r:   r   c                        e Zd Zdef fdZd Zd Zee	 	 	 	 	 	 	 	 	 dde	e
j                     de	e
j                     de	e
j                     de	e   d	e	e
j                     d
e	e   de	e   de	e   de	e
j                     dee   defd              Z e
j(                         	 ddee
j                  df   de
j                  de
j                  dedef
d       Zede
j                  dedede
j2                  de
j                  defd       Z xZS )Cohere2Modelr#   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nr   )r#   F)r+   r,   pad_token_idr
  
vocab_sizerc   r	  rh   embed_tokens
ModuleListrangenum_hidden_layersr   layersra   r   normr"   
rotary_embgradient_checkpointing	post_initr   s      r9   r,   zCohere2Model.__init__  s     !.. ++LL):):F<N<NPTP`P`ammEJ6KcKcEde	 3e
 %&2D2D6K`K`a	0?&+# 	 fs   Dc                     | j                   S rY   r  r6   s    r9   get_input_embeddingsz!Cohere2Model.get_input_embeddings  s       r:   c                     || _         y rY   r(  r6   r   s     r9   set_input_embeddingsz!Cohere2Model.set_input_embeddings  s
    !r:   	input_idsr   rS   r  inputs_embedsr   r   output_hidden_statesr   flash_attn_kwargsrv   c
                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|d u |d uz  rt	        d      | j
                  r%| j                  r|rt        j                  d       d}|| j                  |      }|rL|J| j                  s>|j                  \  }}}t        | j                   |||j                  | j                        }|	F||j                         nd}t        j                   |||j                  d   z   |j                        }	||	j#                  d      }| j%                  |||	||      }|}| j'                  ||      }|rdnd }|rdnd }| j(                  D ]+  }|r||fz  } ||f||||||	d	|
}|d   }|s#||d   fz  }- | j+                  |      }|r||fz  }t-        ||||
      S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.F)max_batch_sizemax_cache_lenrE   r7   r   r   r   r   )r   r   r   r   r   r   )last_hidden_stater  rq   
attentions)r#   r   r0  r   
ValueErrorr%  r   r   r   r  rH   r   rE   r7   get_seq_lengthrK   r   r   _update_causal_maskr$  r"  r#  r   )r6   r.  r   rS   r  r/  r   r   r0  r   r1  
batch_sizer   _past_seen_tokensr   rq   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                         r9   rX   zCohere2Model.forward  sT    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==Yj I  --i8M0%2%8%8"J))%#)){{O !CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L..M>?L]
 & #oom\J #7BD0d![[ 	6M#!m%55!)	$7*."3#-	 $	M *!,M =#3"55%	6( 		-0  -!11&+++%	
 	
r:   r   input_tensorc           
         | j                   j                  dk(  r|S | j                   j                  dk(  r't        |t        j                        rt        |      }|S |j                  |j                  }}|j                  d   }t        |t        t        f      r|j                         }	n ||j                  d   n|j                  d   }	| j                  |||	||||j                  d         }
|
S )Nr   flex_attentionr   r<   r   sequence_lengthtarget_lengthrE   r7   r   r:  )r#   r   rI   rK   r   r    rE   r7   rH   r   r   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_position)r6   r   rA  r   r  r   rE   r7   rE  rF  r   s              r9   r9  z Cohere2Model._update_causal_mask  s     ;;++/BB!!;;++/??.%,,7!<^!L!!$**L,?,?v&,,Q/o['AB+??AM8F8RN004XdXjXjklXmM PP+')#))!, Q 
 r:   rE  rF  rE   r:  c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||j
                        |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }	|ddddddd|	f   | ddddddf   j                  |j
                        z   }
|
dk(  }
|ddddddd|	f   j                  |
|      |ddddddd|	f<   |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuerE   r7   r   r   r   r<   r   )rC   rK   r   r   fullr7   triur   rx   rG   clonerH   rQ   masked_fill)r   rE  rF  rE   r   r:  r   r   r   mask_lengthpadding_masks              r9   rH  zBCohere2Model._prepare_4d_causal_attention_mask_with_cache_position=  s   < %.*<*<*>!*C(K* ' E*..I** -0Ye\j\q\qK !##jjqA5<<n>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r:   )	NNNNNNNNN)F)rZ   r[   r\   r   r,   r*  r-  r   r   r   rK   r   r   r   r   r   r   r   r   rX   r]   r   r9  staticmethodr   rE   rH  r^   r_   s   @r9   r  r    s   }  !"  1515371559$(,0/359^
E,,-^
 !.^
 u//0	^

 "+.^
   1 12^
 D>^
 $D>^
 'tn^
 !!1!12^
 $$89^
 
!^
  ^
@ U]]_ #($ellK78$ ll$ 	$
 %$  $ $L 444 4 {{	4
 4 4 4r:   r  c                       e Zd Zy)KwargsForCausalLMN)rZ   r[   r\   r   r:   r9   rT  rT  u  s    r:   rT  c                       e Zd ZdgZddiZddgdgfiZdef fdZd Zd	 Z	d
 Z
d Zd Zd Zee	 	 	 	 	 	 	 	 	 	 	 ddeej$                     deej&                     deej$                     deeeeej.                     f      deej.                     deej$                     dee   dee   dee   deej$                     deeej&                  f   dee   defd              Z	 	 	 	 	 	 	 ddZ xZS )Cohere2ForCausalLMzlm_head.weightlm_headcolwise_reprq   logitsr#   c                 ,   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _
        | j                          y r   )r+   r,   r  r  r  rc   r   rh   rW  logit_scaletie_word_embeddingsr&  r   s     r9   r,   zCohere2ForCausalLM.__init__~  sq     !&)
 ++yy!3!3V5F5FUS!--#)#=#=  	r:   c                 .    | j                   j                  S rY   r  r  r)  s    r9   r*  z'Cohere2ForCausalLM.get_input_embeddings  s    zz&&&r:   c                 &    || j                   _        y rY   r^  r,  s     r9   r-  z'Cohere2ForCausalLM.set_input_embeddings  s    "'

r:   c                     | j                   S rY   rW  r)  s    r9   get_output_embeddingsz(Cohere2ForCausalLM.get_output_embeddings  s    ||r:   c                     || _         y rY   ra  )r6   new_embeddingss     r9   set_output_embeddingsz(Cohere2ForCausalLM.set_output_embeddings  s	    %r:   c                     || _         y rY   r  )r6   decoders     r9   set_decoderzCohere2ForCausalLM.set_decoder  s	    
r:   c                     | j                   S rY   rg  r)  s    r9   get_decoderzCohere2ForCausalLM.get_decoder  s    zzr:   r.  r   rS   r  r/  labelsr   r   r0  r   logits_to_keepr   rv   c                    ||n| j                   j                  }|	|	n| j                   j                  }	 | j                  d||||||||	|
d	|}|j                  }t        |t              rt        | d      n|}| j                  |dd|ddf         }|| j                  z  }d}|* | j                  d||| j                   j                  d|}t        |||j                  |j                  |j                        S )a~  
        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]`.

        Example:

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

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

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

        >> # Generate
        >> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```N)	r.  r   rS   r  r/  r   r   r0  r   )rY  rl  r  )lossrY  r  rq   r6  r   )r#   r   r0  r  r5  rI   r   slicerW  r[  loss_functionr  r   r  rq   r6  )r6   r.  r   rS   r  r/  rl  r   r   r0  r   rm  r   r   rq   slice_indicesrY  ro  s                     r9   rX   zCohere2ForCausalLM.forward  s+   N 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 ,64:: ,
)%+'/!5),
 ,
  118B>SV8W~ot4]kmA}a,?@A$***%4%%pVFt{{OeOepiopD%#33!//))
 	
r:   c	           	         |Y||d   |j                   d   k\  r|d d |j                   d    d f   }n(|j                   d   |j                   d   k7  r	|d d |f   }|t|r|j                         j                  d      dz
  }|j                  |dk(  d       |r9|d d |j                   d    d f   }|j	                  t
        j                        }||d   dk(  r|d d}
n#|j	                  t
        j                        d d}
t        |t              r|j                  dk(  r| j                  j                  dk(  s|
d	   #|
d	   j                   \  }}}|
d	   j                  }n!|
d
   j                   \  }}|
d
   j                  }| j                  j                  |||j                         | j                   j"                  j$                  |||      }|||
d<   |
j'                  |||||d       |
S )Nr<   r   r   )memory_format)r/  r.  )r.  r/  rA   r   r/  r.  rD  rm  )rS   r   r  r   r   )rH   longcumsummasked_fill_rN  rK   contiguous_formatrI   r   ndimr#   r   r7   r  rH  rG  rW  rf   rE   r   )r6   r.  r  r   r/  r   rS   r   rm  r   model_inputsr:  rE  r;  r7   s                  r9   prepare_inputs_for_generationz0Cohere2ForCausalLM.prepare_inputs_for_generation  s0   & &)!"%);;%a.*>*>q*A)A)C&CD	#~';';A'>>%a&78	%,*>)..077;a?L%%n&91=+A	0B/B/D,DE  ,11@W@W1X $):a)?-:NL *3uG^G^)_rvwL 4##q(KK448KKO,81=o1N1T1T.
OQ%o6==.:;.G.M.M+
O%k299!ZZ]] /-AACll))//-% ^ N %-;L)* ,"0#2&"0	
 r:   )NNNNNNNNNNr   )NNNNNTN) rZ   r[   r\   _tied_weights_keys_tp_plan_pp_planr   r,   r*  r-  rb  re  ri  rk  r   r   r   rK   r   r   r   r
   r   r   r   r   r   rT  r   rX   r{  r^   r_   s   @r9   rV  rV  x  s   *+=)H_-z:;H	} 	'(&  151537KO59-1$(,0/35934H
E,,-H
 !.H
 u//0	H

 "%tE4E4E/F(F"GHH
   1 12H
 ))*H
 D>H
 $D>H
 'tnH
 !!1!12H
 c5<</0H
 *+H
 
 H
  H
Z Qr:   rV  )rV  r  r   )r   )Nr   )Ctypingr   r   r   r   r   rK   torch.nnrc   activationsr	   cache_utilsr
   r   r   
generationr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   utils.deprecationr   configuration_cohere2r   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr    
get_loggerrZ   r   Moduler"   ra   r   r   r}   rF   r   r   r   r   r   r   r   r  rT  rV  __all__r   r:   r9   <module>r     s  , : 9   ! : : ) B 9 O K F & h h 0 0  !;J 
		H	%<RYY <D-ryy -"	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % %4<<W)ryy W)t  a4 aH *_ * *8 U) U Up ?,j > /  D Kr:   