
    ^j53                     <    d dl mZ d Z	 ddZd Z G d de      Zy)	   )PushToHubMixinc                     d}	 t        | j                               }|j                  j
                  }|dk(  r(ddlm}  |       rddl}t        |d      j                  y	|S # t        $ r t        d|       w xY w)
z
    Infers the device type from the model parameters.
    Args:
        model: The model instance.

    Returns:
        The device type.
    z
    {
        "RMSNorm": {
            "cuda":
                "kernels-community/layer_norm:LlamaRMSNorm",
            ...
        },
        ...
    }
    zPCannot determine model device, please provide a device to the mapping. Example: cudar   )is_torch_available    Nversionrocm)next
parametersStopIteration
ValueErrordevicetypeutilsr   torchgetattrhip)modelEXAMPLE_MAPPINGparamdev_typer   r   s         k/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/utils/kernel_config.pyinfer_devicer      s    	O
U%%'( ||  H6.ui(,,8O!  
^_n^op
 	

s   A" "A:Nc           	          ddl m} |dvrt        d|       |j                  d      d   }	|j                  d      d   }
|| ||
|	|||      ii|| <   y )Nr   LayerRepositoryr   r	   xpunpuneurontpuBOnly cuda, rocm, xpu, npu, neuron and tpu devices supported, got: :   )repo_id
layer_namer   revisiontrust_remote_code)kernelsr   r   split)r&   r   	repo_namemodecompatible_mappingr   r'   r(   r   repo_layer_namer%   s              r   add_to_mappingr/   :   sy     (DD]^d]efggooc*1-Oooc"1%G/*!"3

&z"    c                     ddl m} ddlm} |dvrt	        d|       |j                  d      d   }|j                  d      d   }|| | ||      |      ii|| <   y )	Nr   )Path)LocalLayerRepositoryr   r"   r#   r$   )	repo_pathr&   )pathlibr2   r)   r3   r   r*   )	r&   r   r+   r,   r-   r2   r3   r.   r4   s	            r   add_to_mapping_localr6   P   sv    ,DD]^d]efggooc*1-O$Q'I&y/*
&z"r0   c                   6    e Zd ZdZddZ	 d	dZd Zd Zd
dZy)KernelConfigze
    Kernel configuration class. This class is used to configure the kernel mapping for a model.
    Nc                 6    ||ni | _         i | _        || _        y )N)kernel_mappingregistered_layer_namesuse_local_kernel)selfr:   r<   s      r   __init__zKernelConfig.__init__h   s"    0>0JnPR&(# 0r0   c	           	      L    ddl m}	 || |	|||||      ii| j                  |<   y )Nr   r   )r%   r&   r'   r   r(   )r)   r   r:   )
r=   r%   registered_namer&   r   r,   r'   r   r(   r   s
             r   update_kernelzKernelConfig.update_kernelm   s<     	, o#)%#&7
0
O,r0   c                     |j                         D ]+  \  }}t        |d      s|j                  | j                  |<   - y )Nkernel_layer_name)named_moduleshasattrrC   r;   )r=   r   namemodules       r   store_registered_layer_namesz)KernelConfig.store_registered_layer_names~   sA    !//1 	MLD&v234:4L4L++D1	Mr0   c           	         d}| j                  |       t        | j                  t              s$t	        d| dt        | j                               | j                  j                         D ]t  \  }}|| j                  j                         vrt	        d| d      d}t        |t        t        f      rd|i}d}t        |t              r|j                         D ]  \  }}|}|s|d	vrt	        d
|       t        |t              r|\  }}	t        |	t              st	        dt        |	      d|	 d      |	j                  dd      x}
t        |
t              st	        d|
       |	j                  dd      x}&|	j                  dd      x}	 t	        d|d|      t        |t              r	d|vsd|vst	        d| d|        ft	        d| d|        y)ar  
        Validates the kernel_mapping to ensure that:
        1. Each layer_name in the mapping is registered in the model (i.e., the model contains a module with a matching kernel_layer_name).
        2. Each kernel value is
            - either a string of the form 'org/repo:layer_name' or a tuple with the same as string and a dict of {"revision"/"version/trust_remote_code": ...},
            - or a dict mapping device types ("cuda", "rocm", "xpu", "npu") to such values as above.
        3. Each device key in a dict is one of "cuda", "rocm", "xpu", or "npu".
        5. Each trust remote code key must be a bool.
        6. Each revision or version key must exist mutually exclusive if it has been passed explicitly.
        7. Each repo_name is a valid repository and layer name in the format 'org/repo:layer_name' (i.e., a string containing both a slash and a colon).
        8. If a local path is detected, it should be in the format '/abs/path:layer_name', where the absolute path points to the kernel repository, like "/home/user/layer_norm".

        Args:
            model: The model instance whose modules are checked for registered kernel_layer_name attributes.

        Raises:
            ValueError: If a layer_name is not registered in the model, if a device is not supported,
                        or if a repo_name is not a valid 'org/repo:layer_name' string.
        a}  
        For single device form remote
        {
            "RMSNorm":
                "kernels-community/layer_norm:LlamaRMSNorm",
            ...
        },
        For multiple devices form remote
        {
            "RMSNorm": {
                "cuda":
                    "kernels-community/layer_norm:LlamaRMSNorm",
                "rocm":
                    "kernels-community/layer_norm:LlamaRMSNorm",
                ...
            },
            ...
        }
        You can also pass metadata along to inform about specific kernel information
        {
            "RMSNorm":
                ("kernels-community/layer_norm:LlamaRMSNorm", {"version": 1, "trust_remote_code": True}),
            ...
        },
        For single device form local
        {
            "RMSNorm":
                "/abs/path:LlamaRMSNorm",
            ...
        },
        For multiple devices form local
        {
            "RMSNorm": {
                "cuda":
                    "/abs/path:LlamaRMSNorm",
                "rocm":
                    "/abs/path:LlamaRMSNorm",
                ...
            },
            ...
        }
        z7Kernel mapping must be a dict of the following format: z, got: zLayer z[ is not registered in the model, please register it first using use_kernel_forward_from_hubFNTr   r"   z^The passed metadata as second entry in a tuple needs to be a dict but found: type(metadata) = z for .r(   z6Expected a bool value for `trust_remote_code` but got r'   r   zExpected valid combination for version/revision (mutually exclusive but one of them) to be passed when passed as tuple, but got revision= z and version= /r#   zKernel mapping for 'zl' must be a valid repo name with a layer name (e.g., 'org/repo:layer_name' or '/abs/path:layer_name'), got: z'Kernel mapping must follow the format: )rH   
isinstancer:   dictr   r   itemsr;   valuesstrtuplegetbool)r=   r   MAPPING_FORMATr&   kernelskip_device_checkr   repor+   metadatar(   r'   r   s                r   sanitize_kernel_mappingz$KernelConfig.sanitize_kernel_mapping   ss   ()T 	))%0$--t4I.IYY`aefjfyfyaz`{|  #'"5"5";";"= .	lJ!<!<!C!C!EE ZL  )D  E  !&&3,/$(!&$'$*LLN  LFD $I,?n1n(+mntmu)vww "$..2+	8)(D9",!5#'>"5U8*A!G# 
 2:>QSW1XX-e#-.?#F&0&\]n\o$p'" !" )1Z(FFHO'/||It'DDG!U" #-!YNV\Yh_f^i!k# 
 &i5I9MQT\eQe(2:,  ?k  lu  kv  w = D !#J>JZZabhai!jkk].	lr0   c                 \   ddl m} i }t        |      }| j                  j	                         D ]  \  }}|j
                  r|j                  n|j                  }|r||j                  z  }t        |t        t        f      r||i}|j	                         D ]  \  }	}
|	|k7  r| j                  rt        ||	|
||       (t        |
t              r<|
\  }}|j                  dd      }|j                  dd      }|j                  dd      }n|
}d}d}d}t        ||	||||||	         || _        y)
a  
        Transforms a simple kernel_mapping of the form:
            {
                "RMSNorm":
                    ("kernels-community/layer_norm:LlamaRMSNorm", {"version": 1, "trust_remote_code": True}),
                ...
            },

            or for local path:

            {
                "RMSNorm":
                    "/home/user/liger_kernels:LigerRMSNorm",
                ...
            },

        into a nested mapping:

            {
                "RMSNorm": {
                    "cuda": {
                        Mode.INFERENCE: LayerRepository(
                            repo_id="kernels-community/layer_norm",
                            layer_name="LlamaRMSNorm",
                            version=1,
                            trust_remote_code=True,
                        )
                    }
                }
            }

            or for local path:

            {
                "RMSNorm": {
                    "cuda": {
                        Mode.INFERENCE: LocalLayerRepository(
                            repo_path=Path("/home/user/liger_kernels"),
                            layer_name="LigerRMSNorm",
                        )
                    }
                }
            }

        that's compatible with the kernels library.

        The device is inferred from the model's parameters if not provided.
        The Mode is inferred from the model's training state.
        r   )Moder'   Nr   r(   Fr$   )r   r+   r,   r-   r   r'   r(   )r)   r[   r   r:   rN   trainingTRAINING	INFERENCETORCH_COMPILErL   rP   rQ   r<   r6   rR   r/   )r=   r   compiler[   r-   current_devicer&   rU   r,   r   rW   r+   rX   r'   r   r(   s                   r   create_compatible_mappingz&KernelConfig.create_compatible_mapping   sD   d 	!%e,"&"5"5";";"= &	J$)NN4==Dd000&3,/(&1 & ^+(((VT4I[\ dE**.'Ix'||J=H&ll9d;G(05H%(P% $I#HG(-%!''9#%&7	)&	P 1r0   )NF)Nr$   F)F)	__name__
__module____qualname____doc__r>   rA   rH   rY   rb    r0   r   r8   r8   c   s,    1 ot
"M
slj^1r0   r8   )r$   NF)r   r   r   r/   r6   r8   rg   r0   r   <module>rh      s/    #%R jo,&s1> s1r0   