
    ʛ7i"                     ,   d dl Z d dlZd dlmZmZmZmZ d dlZd dl	Z	d dl
mZmZmZmZmZ 	 ddeee	j                   f   deeeef      defdZ	 ddeee	j                   f   deee j&                  f   deeeef      ddfd	Zdd
ededeee	j                   f   fdZ	 ddeee j&                  f   deee	j                   f   fdZ	 ddeeej.                  f   dedeee	j                   f   fdZdeee	j                   f   deeej2                  f   fdZe	j6                  de	j8                  de	j:                  de	j<                  de	j>                  de	j@                  de	jB                  de	jD                  de	jF                  de	jH                  de	jJ                  de	jL                  de	jN                  diZ(e	jH                  e	j8                  e	j>                  e	j<                  e	j6                  e	j:                  e	j@                  e	jD                  e	jB                  e	jF                  e	jJ                  e	jL                  dZ)e	j6                  ej6                  e	j8                  ej8                  e	j:                  ej:                  e	j<                  ej>                  e	j>                  ej>                  e	j@                  ej@                  e	jB                  ejB                  e	jD                  ejD                  e	jF                  e#e	jH                  ejH                  e	jJ                  ejB                  e	jL                  ejB                  iZ*dede	jV                  fdZ,deee	j                   f   fdZ-de	j                   dedefdZ.deee	j                   f   deeeeef   f   fdZ/y)     N)AnyDictOptionalUnion)numpydeserialize	safe_open	serializeserialize_filetensorsmetadatareturnc                 H    t        t        |       |      }t        |      }|S )a)  
    Saves a dictionary of tensors into raw bytes in safetensors format.

    Args:
        tensors (`Dict[str, paddle.Tensor]`):
            The incoming tensors. Tensors need to be contiguous and dense.
        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
            Optional text only metadata you might want to save in your header.
            For instance it can be useful to specify more about the underlying
            tensors. This is purely informative and does not affect tensor loading.

    Returns:
        `bytes`: The raw bytes representing the format

    Example:

    ```python
    from safetensors.paddle import save
    import paddle

    tensors = {"embedding": paddle.zeros((512, 1024)), "attention": paddle.zeros((256, 256))}
    byte_data = save(tensors)
    ```
    r   )r
   _flattenbytes)r   r   
serializedresults       O/home/rose/Desktop/poly/venv/lib/python3.12/site-packages/safetensors/paddle.pysaver      s$    6 8G,x@J:FM    filenamec                 2    t        t        |       ||       y)am  
    Saves a dictionary of tensors into raw bytes in safetensors format.

    Args:
        tensors (`Dict[str, paddle.Tensor]`):
            The incoming tensors. Tensors need to be contiguous and dense.
        filename (`str`, or `os.PathLike`)):
            The filename we're saving into.
        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
            Optional text only metadata you might want to save in your header.
            For instance it can be useful to specify more about the underlying
            tensors. This is purely informative and does not affect tensor loading.

    Returns:
        `None`

    Example:

    ```python
    from safetensors.paddle import save_file
    import paddle

    tensors = {"embedding": paddle.zeros((512, 1024)), "attention": paddle.zeros((256, 256))}
    save_file(tensors, "model.safetensors")
    ```
    r   N)r   r   )r   r   r   s      r   	save_filer   +   s    > 8G$hBr   datadevicec                     t         j                  dk\  rt        |       }t        ||      S t	        j
                  |       }t        ||      S )a  
    Loads a safetensors file into paddle format from pure bytes.

    Args:
        data (`bytes`):
            The content of a safetensors file

    Returns:
        `Dict[str, paddle.Tensor]`: dictionary that contains name as key, value as `paddle.Tensor` on cpu

    Example:

    ```python
    from safetensors.paddle import load

    file_path = "./my_folder/bert.safetensors"
    with open(file_path, "rb") as f:
        data = f.read()

    loaded = load(data)
    ```
    3.2.0)paddle__version__r   _view2paddler   load
_np2paddle)r   r   flats      r   r"   r"   M   sD    . W$4 D&))zz$$''r   c                    i }t         j                  dk\  rCt        | d|      5 }|j                         D ]  }|j	                  |      ||<    	 ddd       |S t        j                  |       }t        ||      }|S # 1 sw Y   |S xY w)a  
    Loads a safetensors file into paddle format.

    Args:
        filename (`str`, or `os.PathLike`)):
            The name of the file which contains the tensors
        device (`Union[Dict[str, any], str]`, *optional*, defaults to `cpu`):
            The device where the tensors need to be located after load.
            available options are all regular paddle device locations

    Returns:
        `Dict[str, paddle.Tensor]`: dictionary that contains name as key, value as `paddle.Tensor`

    Example:

    ```python
    from safetensors.paddle import load_file

    file_path = "./my_folder/bert.safetensors"
    loaded = load_file(file_path)
    ```
    r   r   )	frameworkr   N)r   r    r	   offset_keys
get_tensorr   	load_filer#   )r   r   r   fkr$   s         r   r)   r)   l   s    2 FW$x8FCq]]_LLOq	 % D M x(D&)M D Ms   *A<<B
numpy_dictc                 j    | j                         D ]  \  }}t        j                  ||      | |<   ! | S )Nplace)itemsr   	to_tensor)r,   r   r+   vs       r   r#   r#      s7       "1((&9
1 #r   paddle_dictc                     | j                         D ]4  \  }}|j                         j                         j                         | |<   6 | S N)r0   detachcpur   )r3   r+   r2   s      r   
_paddle2npr8      s>    !!#1)//1A $r               )F64F32F16BF16I64I32I16I8U8BOOLF8_E4M3F8_E5M2	dtype_strc                     t         |    S r5   )_TYPES)rI   s    r   	_getdtyperL      s    )r   c                    i }| D ]  \  }}t        |d         }t        |d         dk(  r2t        d |d   D              sJ t        j                  |d   |      }nUt        j
                  j                  j                  |d   |      j                  |d         }|dk7  r|j                  |      }t        j                  dk(  r5t        j                  |j                         j                  d	
      |      }|||<    |S )Ndtyper   r   c              3   &   K   | ]	  }|d k(    yw)r   N ).0xs     r   	<genexpr>z_view2paddle.<locals>.<genexpr>   s     2z!qAvzs   shape)rN   r7   bigFinplacer.   )rL   lenanyr   emptybasecore
frombufferreshapetosys	byteorderr1   r   byteswap)safeviewr   r   r+   r2   rN   arrs          r   r!   r!      s    F1!G*%qy>Q2qz2222,,qz7C++""--ai?GG'
SCffVn==E!""399;#7#7#7#FfUCq	  Mr   tensornamec                    | j                         st        d| d      | j                  j                         s| j	                         } dd l}dd l}t         |j                  | j                        j                               }t        | j                     }||z  }| j                         }|dk(  ry|j                  ||j                  |j                               }|j"                  j%                  ||f      }	t&        j(                  dk(  r4t*        | j                     }
|	j-                  |
      j/                  d      }	|	j1                         S )Nz1You are trying to save a non contiguous tensor: `a  ` which is not allowed. It either means you are trying to save tensors which are reference of each other in which case it's recommended to save only the full tensors, and reslice at load time, or simply call `.contiguous()` on your tensor to pack it before saving.r   r   rU   FrV   )is_contiguous
ValueErrorr/   is_cpu_placer7   ctypesr   intprodrT   item_SIZErN   data_ptrcastPOINTERc_ubyte	ctypeslibas_arrayr`   ra   NPDTYPESviewrb   tobytes)re   rf   rk   nplengthbytes_per_itemtotal_bytesptrnewptrr   npdtypes              r   _tobytesr      s   !?v F& &
 	
 <<$$& &++-.F6<<(N>)K
//
C
ax[[fnnV^^<=F<<  +8D
}}6<<(yy!**5*9<<>r   c                    t        | t              st        dt        |              | j	                         D ]9  \  }}t        |t
        j                        r!t        d| dt        |              | j	                         D ci c]E  \  }}|t        |j                        j                  d      d   |j                  t        ||      dG c}}S c c}}w )Nz5Expected a dict of [str, paddle.Tensor] but received zKey `z2` is invalid, expected paddle.Tensor but received .)rN   rT   r   )
isinstancedictri   typer0   r   TensorstrrN   splitrT   r   )r   r+   r2   s      r   r   r     s    gt$CDM?S
 	
 1!V]]+sLTRSWIV    MMO $DAq 	
\'',R0WWQN
 	

 $  s   A
Cr5   )r7   )0osr`   typingr   r   r   r   r   ry   r   safetensorsr   r	   r
   r   r   r   r   r   PathLiker   r"   r)   ndarrayr#   arrayr8   int64float32int32bfloat16float16int16uint8int8boolfloat64float8_e4m3fnfloat8_e5m2	complex64ro   rK   rv   rN   rL   r!   r   r   rP   r   r   <module>r      s   	 
 - -   P P MQ#v}}$%19$sCx.1I
F *.C#v}}$%CC$%C tCH~&C 
	CD(u (c (d33E.F (@ /4!C$%!	#v}}
!J 6;S"**_%/2	#v}}
Dfmm!34 c288m9L  LL!
NNA
LL!
OOQ
NNA
LL!
LL!
KK
KK
NNA
!

a	. >>>>>>OO<<<<<<
++
,,KK##!!
  LL"((
NNBJJ
LL"((
OORZZ
NNBJJ
LL"((
LL"((
KK
KK
NNBJJ
"((
$  d3+=&> & V]]  #  %  Fd3-. 4T#s(^8K3L r   