o
    wi%                     @   s   d dl 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 e rAd dlZd dlmZ dZdZdZdZdZ	dddZG dd dZdS )    N)Image   )_get_model_class)
AutoConfig)MODEL_FOR_PRETRAINING_MAPPINGMODEL_MAPPING)PROCESSOR_MAPPING_NAMESAutoProcessor)TOKENIZER_MAPPING_NAMESAutoTokenizer   )is_torch_availablez[92mz[93mz[0mu   ■u   ⬚<img>c              
      sp    jdkrdddddf jdkr%ddddddf ttdd D }d}g }tD ]6\ }	|	krL|sL }d  f< |dkrp|	ksZ d krp d krd d7  d| | f< d}q:ddurfd	d
tD dfddtD }
|dur|dk}t|	dd | 
 |	ddtd|d |}tj|dt t t dt t t d}|d|  d|d  dt|
d  }dur|d7 }|| g }tD ]3\}}||f dkr|dd
 tt|ttD  q|tt|tt qtttt| }|D ]}|durO|d d d| d d| nd q4tD ]Z\ }t||}|v rpt | t n|}d fddtD }d}durd fddtD }|| dt d d| d|  qXd|S )z
    Generates an attention matrix from a given attention mask.

    Optionally applies a sliding window mask (e.g., for Gemma2/3) and
    marks regions where image tokens occur based on the specified `img_token`.
       r   N   c                 s   s    | ]	}t t|V  qd S N)lenrepr).0word r   d/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/utils/attention_visualizer.py	<genexpr>7   s    z6generate_attention_matrix_from_mask.<locals>.<genexpr>r   r   c                    s$   g | ]  fd dt D qS )c                    s0   g | ]}d  |   krk rn ndnd qS )r   r   r   r   j)isliding_windowr   r   
<listcomp>H   s   0 zBgenerate_attention_matrix_from_mask.<locals>.<listcomp>.<listcomp>)range)r   )nr   )r   r   r   H   s   $ z7generate_attention_matrix_from_mask.<locals>.<listcomp> c                 3   sX    | ]'} d |f rt  t t nd |krt t t n	 d |f r&tntV  qdS r   NYELLOWBLACK_SQUARERESETGREENWHITE_SQUAREr   )maskr   r   r   J   s    


   )
boundariesz: i == j (diagonal)   z: token_type_idszAttention MatrixzSliding Window Maskc                 S   s   g | ]
}t  | t qS r   )r#   r%   )r   kr   r   r   r   h   s    z	    |     c                 3   sp    | ]3}| v r |f r  v rt  t t n |kr*t t t n	 |f r2tntV  qd S r   r"   r   )r   	img_tokenr(   wordsr   r   r   w   s    $

c                 3   s|    | ]9}| v r$  v r$d  f d |f kr$t  t t n |kr0t t t n	  | r8tntV  qdS r!   r"   r   )r   r.   sliding_window_masktoken_type_bucketsr/   r   r   r      s    


z: 
)intndimr   max	enumerater   jointorchwherecumsumboolarange	bucketizer&   r$   r%   r#   appendljustliststrrjustmapzipr   )r/   r(   r.   r   token_type_idsimage_seq_lengthmax_word_lengthfirst_img_idxoutputr,   	row_dummy
is_specialr+   legendf_stringvertical_headeridxr   row	word_reprcolored_wordrow_displaysliding_window_rowr   )r   r.   r(   r   r   r0   r1   r/   r   #generate_attention_matrix_from_mask'   s~   	

 
,"
$


.
rU   c                   @   s:   e Zd ZdefddZddefddZddefdd	Zd
S )AttentionMaskVisualizer
model_namec                 C   s   t |}d| _t| drt| dd | _zt|t}W n t	y-   t|t
}Y nw |d u r:td| d|| _G dd d|tj}|||| _| j|j || _|| _d S )Nr   r   zModel name z- is not supported for attention visualizationc                   @   s   e Zd Zdd ZdS )z7AttentionMaskVisualizer.__init__.<locals>._ModelWrapperc                 S   s$   t j|  t dd| _|| _d S )Nr   )nnModule__init__Lineardummy_moduleconfig)selfr]   rW   r   r   r   rZ      s   
z@AttentionMaskVisualizer.__init__.<locals>._ModelWrapper.__init__N)__name__
__module____qualname__rZ   r   r   r   r   _ModelWrapper   s    rb   )r   from_pretrainedimage_tokenhasattrget_text_configgetattrr   r   r   	Exceptionr   
ValueError
mapped_clsrX   rY   modeltotorch_dtyperepo_idr]   )r^   rW   r]   rj   rb   r   r   r   rZ      s"   

z AttentionMaskVisualizer.__init__r-   input_sentencec                 C   s   | j ||d d S )N)suffix)visualize_attention_mask)r^   ro   rp   r   r   r   __call__   s   z AttentionMaskVisualizer.__call__c              	   C   s  | j }i }d }| jjtv rkd}ttj|ddj}d}t	j
| j|d}t|dr-|j}n
|j|jgd }|r?|d|}||||d	d
}	|j|jgd | _|	d }
d|	v r`|	d |d< |j|	d d }n$| jjtv rt
| j}||}||d	dd }
n
td|jj dd|j_|  |jd|
|
| j jt|
jd d d|  }
dtd| jj d| j  d  }d}t!d|  t!dd| jj d| j d| j j" #t| d |  t!|  t$||
| jt%| jdd |dd |d}t!| t!|  d S ) Nzchttps://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg?download=trueT)streamr*   )rF   rd   r   r   pt)imagestextrp   return_tensorsattention_maskrE   	input_ids)rw   zModel type z) does not support attention visualizationeagerr   )rx   input_tensorcache_positionpast_key_valuesz##zAttention visualization for z | r   r2   z"  Attention visualization for [1m:z[0m z    r   )r.   r   rE   rF   r   )&rk   r]   
model_typer   r   openrequestsgetrawr	   rc   rn   re   rd   	tokenizerconvert_ids_to_tokensimage_token_idreplacer
   r   tokenizeri   _attn_implementationtrain_update_causal_maskrl   dtyper8   r<   shaper;   r   rj   printr_   centerrU   rg   )r^   ro   rp   rk   kwargsrF   img	processorrd   inputsrx   tokensr   top_bottom_borderside_borderrM   r   r   r   rq      s~   

 

z0AttentionMaskVisualizer.visualize_attention_maskN)r-   )r_   r`   ra   rA   rZ   rr   rq   r   r   r   r   rV      s    rV   )r   NNN)r   PILr   models.auto.auto_factoryr   models.auto.configuration_autor   models.auto.modeling_autor   r   models.auto.processing_autor   r	   models.auto.tokenization_autor
   r   import_utilsr   r8   torch.nnrX   r&   r#   r%   r$   r'   rU   rV   r   r   r   r   <module>   s&   
n