
    gy0              	       8   d dl mZ d dlmZmZ d dlmZ d dlmZ d dl	m
Z
mZmZmZ  e            rd dlZd dlmZmZ  e            rd dlZd ded	efd
Zd Zd!dedededefdZdededefdZd dZd dedededefdZd Zd Zd Ze dk    r e             dS dS )"    )
model_info)GatedRepoErrorRepositoryNotFoundError)init_empty_weights)CustomArgumentParser)calculate_maximum_sizesconvert_bytesis_timm_availableis_transformers_availableN)
AutoConfig	AutoModelrepotokenc                 n    	 t          | |          S # t          t          f$ r Y dS t          $ r Y dS w xY w)zAVerifies that the model is on the hub and returns the model info.)r   gatedr   )r   OSErrorr   r   )r   r   s     X/var/www/html/ai-engine/env/lib/python3.11/site-packages/accelerate/commands/estimate.pyverify_on_hubr   %   sZ    $e,,,,^$   ww"   vvs    4	44c                     t                      r&t          | t                    rd| j        d         v rdS t	                      r&t          | t
                    rd| j        d         v rdS dS )zG
    Checks what library spawned `error` when a model is not found
    zUnknown modelr   timmz$does not appear to have a file namedtransformersunknown)r
   
isinstanceRuntimeErrorargsr   r   )errors    r   check_has_modelr   /   sy      	z%>> 	?V[V`abVcCcCcv!##ug&& 3ejmCC~y    F
model_namelibrary_nametrust_remote_codeaccess_tokenc                 B   t          | |          }|dk    rt          d|  d          |dk    rt          d|  d          |&t          |dd          }|st	          d	|  d
          |dk    r#t                      st          d|  d          t          d|  d           |j        t          d|  d          |j        
                    dd          }t          j        | ||          }t                      5  t          }t          |t                     rId}|                                D ]}	|	                    d          r|	} n|t          t&          |          }|                    ||          }
ddd           n# 1 swxY w Y   n|dk    rqt+                      st          d|  d          t          d|  d           t                      5  t-          j        | d          }
ddd           n# 1 swxY w Y   nt	          d| d          |
S )a  
    Creates an empty model from its parent library on the `Hub` to calculate the overall memory consumption.

    Args:
        model_name (`str`):
            The model name on the Hub
        library_name (`str`):
            The library the model has an integration with, such as `transformers`. Will be used if `model_name` has no
            metadata on the Hub to determine the library.
        trust_remote_code (`bool`, `optional`, defaults to `False`):
            Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
            should only be set to `True` for repositories you trust and in which you have read the code, as it will
            execute code present on the Hub on your local machine.
        access_token (`str`, `optional`, defaults to `None`):
            The access token to use to access private or gated models on the Hub. (for use on the Gradio app)

    Returns:
        `torch.nn.Module`: The torch model that has been initialized on the `meta` device.

    r   zRepo for model `zW` is gated. You must be authenticated to access it. Please run `huggingface-cli login`.r   z` does not exist on the Hub. If you are trying to access a private repo, make sure you are authenticated via `huggingface-cli login` and have access.Nr    FzModel `z{` does not have any library metadata on the Hub, please manually pass in a `--library_name` to use (such as `transformers`)r   z
To check `zU`, `transformers` must be installed. Please install it via `pip install transformers`zLoading pretrained config for `z` from `transformers`...Tried to load `z8` with `transformers` but it does not have any metadata.auto_map)r!   r   AutoModelFor)r!   r   zE`, `timm` must be installed. Please install it via `pip install timm`z` from `timm`...)
pretrainedz	Library `zM` is not supported yet, please open an issue on GitHub for us to add support.)r   r   r   getattr
ValueErrorr   ImportErrorprintconfigr   getr   from_pretrainedr   r   r   dictkeys
startswithr   from_configr
   r   create_model)r   r    r!   r"   r   r%   r,   constructorvaluekeymodels              r   create_empty_modelr8   ?   s|   * z<88JW Cz  C  C  C
 
 	
 
v		%\z \ \ \
 
 	
 z>5AA 	 b*  b  b  b   ~%%(** 	~Z~~~   	T
TTTUUU$uuuuvvv$((U;;+JJ[coppp!! 	Y 	Y#K(D)) ?#==??  C~~n55  # $"),">">K++FFW+XXE	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 
		 "" 	nZnnn   	L
LLLMMM!! 	D 	D%jUCCCE	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D ssss
 
 	
 Ls%    A=F		FFH  HHheadersrowstitlec                    d\  }g t          t          |                     D ]Hfd|D             |          gz   }t          d |D                       }                    |           Ifdt          t          |d                             D             }| |                    |           | }dfd} |ddd	          }	t          |          t                    k    r<t          t          |          t          |	          z
            d
xx         z  cc<    |ddd	          }	 |dd          | |                    t          |	          dz
             |  |ddd	          g}
d                    |
          dz   }d
xx         z  cc<   fdt          |           D             }||t          |          z   d|	 dz  }t          |          D ]8\  }fdt          |          D             }||t          |          z   dz  }9|dd                    fdD                        dz  }|S )zJCreates a pretty table from a list of rows, minimal version of `tabulate`.)u   │u   ─c                      g | ]
}|         S  r>   ).0rowis     r   
<listcomp>z&create_ascii_table.<locals>.<listcomp>   s    000CQ000r   c              3   4   K   | ]}t          |          V  d S N)len)r?   r5   s     r   	<genexpr>z%create_ascii_table.<locals>.<genexpr>   s(      EEes5zzEEEEEEr   c                 (    g | ]}d |          dS )%sr>   )r?   rA   column_widthss     r   rB   z&create_ascii_table.<locals>.<listcomp>   s*    DDD1&=#&&&DDDr   r   c                 \    |  |                     fdD                        z   | S )Nc                     g | ]}|z  S r>   r>   r?   n
in_betweens     r   rB   z8create_ascii_table.<locals>.make_row.<locals>.<listcomp>   s    .U.U.U!zA~.U.U.Ur   )join)	left_charmiddle_char
right_charrJ   diffrO   s      r   make_rowz$create_ascii_table.<locals>.make_row   sI    w[--.U.U.U.U}.U.U.UVVwXbeiXiwkuwwwr   u   ├u   ┼u   ┤u   ┌u   ┐   u   ┬
c                 L    g | ] \  }}|                     |                   !S r>   center)r?   rA   textrJ   s      r   rB   z&create_ascii_table.<locals>.<listcomp>   s.    UUUwq$T[[q!122UUUr   c                 L    g | ] \  }}|                     |                   !S r>   rZ   )r?   rA   trJ   s      r   rB   z&create_ascii_table.<locals>.<listcomp>   s.    PPP1-"233PPPr   u   └u   ┴c                     g | ]}|z  S r>   r>   rM   s     r   rB   z&create_ascii_table.<locals>.<listcomp>   s    EEE!zA~EEEr   u   ┘)
rangerE   maxappendrP   sumabsr[   	enumeratetuple)r9   r:   r;   sep_charcolumn_valuesmax_column_widthformatspatternrU   	separatorinitial_rowstablecentered_linelinerJ   rT   rA   rO   s                 @@@@r   create_ascii_tablerq      s   'HjM3w<<   / /00004000GAJ<?EE}EEEEE-....DDDDc$q'll0C0CDDDG=8==11=8==GDx x x x x x x u--I
5zzC&&&&3u::I.//bT! u--I
E**AU\\#i..1"455AxAAu%%L
 IIl##d*E"UUUU)GBTBTUUUM	%...??)????ET?? 7 74PPPP	$PPPGeM2226666	K5::EEEE}EEEFFKKKKELr   c           	         | |                      d          }nt          d          }|                    dt          d           |                    dt          dd	d
g           |                    dt          dg ddg d           |                    dddd           | |                    t
                     |S )Nzestimate-memoryz:Model size estimator for fitting a model onto CUDA memory.)descriptionr   z'The model name on the Hugging Face Hub.)typehelpz--library_namezThe library the model has an integration with, such as `transformers`, needed only if this information is not stored on the Hub.r   r   )rt   ru   choicesz--dtypes+)float32float16int8int4zbThe dtypes to use for the model, must be one (or many) of `float32`, `float16`, `int8`, and `int4`)rt   nargsdefaultru   rv   z--trust_remote_code
store_truea  Whether or not to allow for custom models defined on the Hub in their own modeling files. This flag
                should only be used for repositories you trust and in which you have read the code, as it will execute
                code present on the Hub on your local machine.F)actionru   r}   )func)
add_parserr   add_argumentstrset_defaultsestimate_command)
subparsersparsers     r   estimate_command_parserr      s   &&'899%2nooo
35^___
 P(	     666q666     B      !1222Mr   bytesmixed_precisionmsamp_configreturnc                     ddddd}| }| dz  }|dk    r||d<   ||d<   |dz  |d<   |dz  |d	<   n,|d
v s|dk    r"| ||d<   ||z   |d<   |dz  |d<   |d         |d	<   |S )a  
    Given an amount of `bytes` and `mixed_precision`, calculates how much training memory is needed for a batch size of
    1.

    Args:
        bytes (`int`):
            The size of the model being trained.
        mixed_precision (`str`):
            The mixed precision that would be ran.
        msamp_config (`str`):
            The msamp config to estimate the training memory for if `mixed_precision` is set to `"fp8"`.
    rV   )r7   	optimizer	gradientssteprW   rx   r7   r   r      r   )ry   bfloat16fp8r>   )r   r   r   memory_sizes	fp32_size	fp16_sizes         r   estimate_training_usager      s      br2NNLI
I)## )W$-[!$-M[!(1}V	3	3	358P8PUaUi !*W$-	$9[!$-M[!+K8Vr   c                    	 t          | j        | j        | j                  }nK# t          t
          f$ r7}t          |          }|dk    rt	          d| j         d| d          |d}~ww xY wt          |          \  }}g }| j        D ]g}|}|d         }	t          ||          }
|dk    r|d	z  }|	d	z  }	n!|d
k    r|dz  }|	dz  }	n|dk    r
|dz  }|	dz  }	|
                    ||	||
g           h|S )z9Creates an empty model and gathers the data for the sizes)r    r!   r   r$   z` with `z=` but a possible model to load was not found inside the repo.Nr   ry   rW   rz   r   r{      )r8   r   r    r!   r   r   r   r   dtypesr   rb   )r   r7   elibrary
total_sizelargest_layerdatadtypedtype_total_sizedtype_largest_layerdtype_training_sizes              r   gather_datar      s   
"O$*;tOe
 
 
 '"   !!$$i B$/  B  B7  B  B  B    !8 > >JD Y Y%+A.56FNNI!1$f__!1$f__!1$U/1ACVWXXXXKs   !$ A,2A''A,c                    t          |           }|D ]}t          |          D ]\  }}t          |t          t          f          rt          |          ||<   4t          |t                    r;t          |                                          }|dk    rt          |          nd||<   g d}d| j	         d}t          |||          }t          |           d S )NrV   zN/A)r   zLargest Layerz
Total SizezTraining using AdamzMemory Usage for loading ``)r   re   r   intfloatr	   r/   ra   valuesr   rq   r+   )	r   r   r@   rA   itemtraining_usager9   r;   rn   s	            r   r   r     s    tD Z Z ~~ 	Z 	ZGAt$e-- Z&t,,AD$'' Z!$T[[]]!3!3:HB:N:N~666TYA	Z NMMG;;;;Ewe44E	%LLLLLr   c                  h    t                      } |                                 }t          |           d S rD   )r   
parse_argsr   )r   r   s     r   mainr   .  s2    $&&FDTr   __main__rD   )FN)!huggingface_hubr   huggingface_hub.utilsr   r   
accelerater   accelerate.commands.utilsr   accelerate.utilsr   r	   r
   r   r   r   r   r   r   r   r   boolr8   listrq   r   r   r/   r   r   r   r   __name__r>   r   r   <module>r      s     ' & & & & & I I I I I I I I ) ) ) ) ) ) : : : : : :             322222222 KKK  C       I I3 Ic Id Ijm I I I IX& &D & & & & &R       F   3    C  [_        F     F  "   zDFFFFF r   