o
    پi"                     @   s   d dl Z d dlZd dlZd dlmZmZ d dlmZ d dlm	Z	m
Z
mZ d dlZd dlmZ d dlmZ eeZdde
e ded	efd
dZded	efddZeG dd dZeG dd dZG dd deZG dd deZdS )    N)ABCabstractmethod)	dataclass)AnyListOptional)envs)HostKVCache	token_ids
prior_hashreturnc              	   C   sp   t  }|r|t| | D ]#}t|tr(|D ]}||jdddd qq||jdddd q| S )N   littleF)	byteordersigned)	hashlibsha256updatebytesfromhex
isinstancetupleto_bytes	hexdigest)r
   r   hashertelem r   X/home/ubuntu/.local/lib/python3.10/site-packages/sglang/srt/mem_cache/hicache_storage.pyget_hash_str   s   
r   hash_strc                 C   s&   t | dd d}|dkr|d S |S )zConvert SHA256 hex string to signed 64-bit integer for events.

    Takes first 16 hex characters (64 bits) and converts to signed int64 range.
    N   l            l            )int)r    
uint64_valr   r   r   hash_str_to_int64"   s   r$   c                   @   sZ   e Zd ZU eed< eed< eed< eed< eed< eed< ee ed< dZee	 ed	< dS )
HiCacheStorageConfigtp_ranktp_sizepp_rankpp_sizeis_mla_modelis_page_first_layout
model_nameNextra_config)
__name__
__module____qualname__r"   __annotations__boolr   strr-   dictr   r   r   r   r%   /   s   
 r%   c                   @   s2   e Zd ZU dZeee  ed< dZee	 ed< dS )HiCacheStorageExtraInfoNprefix_keysN
extra_info)
r.   r/   r0   r7   r   r   r3   r1   r8   r4   r   r   r   r   r5   ;   s   
 r5   c                   @   s  e Zd ZdZdefddZ	d$dee dej	de
e d	ee fd
dZ	d$dee dej	de
e d	ee fddZe		d%dede
e de
e d	ej	dB fddZe		d%dee de
e de
e d	eej	dB  eB fddZe			d&dede
e de
e de
e d	ef
ddZe			d&dee de
e de
e de
e d	ef
ddZeded	efddZ	d$dee de
e d	efddZd'd d!Zd"d# ZdS )(HiCacheStoragez
    HiCacheStorage is a class that provides a generic key-value interface for storing and retrieving KV cache.
    It abstracts the underlying storage mechanism, allowing different implementations to be used.
    mem_pool_hostc                 C   s
   || _ d S r6   )r:   )selfr:   r   r   r   register_mem_pool_hostI      
z%HiCacheStorage.register_mem_pool_hostNkeyshost_indicesr8   r   c                 C      dS )zx
        Retrieve values for multiple keys.
        Returns a list of booleans indicating success for each key.
        Nr   r;   r>   r?   r8   r   r   r   batch_get_v1L      
zHiCacheStorage.batch_get_v1c                 C   r@   )zu
        Store multiple key-value pairs.
        Returns a list of booleans indicating success for each key.
        Nr   rA   r   r   r   batch_set_v1X   rC   zHiCacheStorage.batch_set_v1keytarget_locationtarget_sizesc                 C   r@   )zs
        Retrieve the value associated with the given key.
        Returns None if the key does not exist.
        Nr   )r;   rE   rF   rG   r   r   r   getd      zHiCacheStorage.gettarget_locationsc                 C   r@   )zl
        Retrieve values for multiple keys.
        Returns a list of tensors or None for each key.
        Nr   r;   r>   rJ   rG   r   r   r   	batch_getr   rI   zHiCacheStorage.batch_getvaluec                 C   r@   )z
        Store the value associated with the given key.
        Returns True if the operation was successful, False otherwise.
        Nr   )r;   rE   rM   rF   rG   r   r   r   set      zHiCacheStorage.setvaluesc                 C   r@   )zz
        Store multiple key-value pairs.
        Returns True if all operations were successful, False otherwise.
        Nr   )r;   r>   rP   rJ   rG   r   r   r   	batch_set   rO   zHiCacheStorage.batch_setc                 C   r@   )zr
        Check if the key exists in the storage.
        Returns True if the key exists, False otherwise.
        Nr   r;   rE   r   r   r   exists   s   zHiCacheStorage.existsc                 C   s0   t t|D ]}| || s|  S qt|S )z
        Check if the keys exist in the storage.
        return the number of consecutive existing keys from the start.
        Can be overridden by subclasses for more efficient implementation.
        )rangelenrS   )r;   r>   r8   ir   r   r   batch_exists   s
   zHiCacheStorage.batch_existsc                 C      d S r6   r   r;   r   r   r   clear      zHiCacheStorage.clearc                 C   rX   r6   r   rY   r   r   r   	get_stats   r[   zHiCacheStorage.get_statsr6   )NNNNN)r   N)r.   r/   r0   __doc__r	   r<   r   r3   torchTensorr   r5   r2   rB   rD   r   r   rH   r"   rL   rN   rQ   rS   rW   rZ   r\   r   r   r   r   r9   A   s    

	

r9   c                   @   s  e Zd Z	ddedefddZdedefdd	Z	
ddedejde	e
 dejd
B fddZ	
ddee deej de	e
 deejd
B  fddZ	
	
	
ddede	e
 de	e
 de	e
 def
ddZ	
	
	
ddee de	e
 de	e
 de	e
 def
ddZdedefddZdefddZd
S ) HiCacheFile/tmp/hicachestorage_config	file_pathc                 C   s   t j p|| _|j|j|j|jf\}}}}|r d|	dnd}|r+d| | _
nd| d| d| | _
tj| jsS|dkrUt| j td| j  d S d S d S )N-/ _r   z)Created HiCacheFile storage directory at )r   'SGLANG_HICACHE_FILE_BACKEND_STORAGE_DIRrH   rd   r&   r'   r,   r*   joinsplitconfig_suffixospathrS   makedirsloggerinfo)r;   rc   rd   r&   r'   r,   r*   r   r   r   __init__   s   zHiCacheFile.__init__rE   r   c                 C   s
   || j  S r6   )rl   rR   r   r   r   _get_suffixed_key   r=   zHiCacheFile._get_suffixed_keyNrF   rG   c                 C   s   |  |}tj| j| d}z>| |  }t|ddd$}t|	t
j  }|||kr;td| W d    |W S 1 sGw   Y  |W S  tya   td| d Y d S w )N.binrbr   )	bufferingzShort read for zFailed to fetch z from HiCacheFile storage.)rs   rm   rn   rj   rd   numelelement_sizeopen
memoryviewviewr_   uint8
contiguousnumpyreadintoIOErrorFileNotFoundErrorrp   warning)r;   rE   rF   rG   tensor_pathexpectedfbufr   r   r   rH      s"   

zHiCacheFile.getr>   rJ   c                    s&    fddt ||pd gt| D S )Nc                    s   g | ]
\}}  ||qS r   )rH   ).0rE   rF   rY   r   r   
<listcomp>   s    
z)HiCacheFile.batch_get.<locals>.<listcomp>)ziprU   rK   r   rY   r   rL      s
   
zHiCacheFile.batch_getrM   c              
   C   s   |  |rtd| d dS | |}tj| j| d}z| j	t
jd | W dS  tyO } ztd| d|  W Y d }~dS d }~ww )	NzKey z already exists. Skipped.Trt   )dtypezFailed to save tensor z: F)rS   rp   debugrs   rm   rn   rj   rd   r}   r{   r_   r|   r~   tofile	Exceptionerror)r;   rE   rM   rF   rG   r   er   r   r   rN      s   

zHiCacheFile.setrP   c                 C   s*   t ||D ]\}}| ||s dS qdS )NFT)r   rN   )r;   r>   rP   rJ   rG   rE   rM   r   r   r   rQ     s
   zHiCacheFile.batch_setc                 C   s,   |  |}tj| j| d}tj|S )Nrt   )rs   rm   rn   rj   rd   rS   )r;   rE   r   r   r   r   rS     s   
zHiCacheFile.existsc              
   C   s   z$t | jD ]}t j| j|}t j|rt | qtd W dS  t	y? } zt
d|  W Y d }~dS d }~ww )Nz+Cleared all entries in HiCacheFile storage.Tz%Failed to clear HiCacheFile storage: F)rm   listdirrd   rn   rj   isfileremoverp   rq   r   r   )r;   filenamerd   r   r   r   r   rZ     s   

zHiCacheFile.clear)rb   r6   r]   )r.   r/   r0   r%   r3   rr   rs   r_   r`   r   r   rH   r   rL   r2   rN   rQ   rS   rZ   r   r   r   r   ra      st    




ra   r6   )r   loggingrm   abcr   r   dataclassesr   typingr   r   r   r_   sglang.srt.environr   %sglang.srt.mem_cache.memory_pool_hostr	   	getLoggerr.   rp   r"   r3   r   r$   r%   r5   r9   ra   r   r   r   r   <module>   s$    
x