
    qi/                        d dl Z d dlmZ d dlZd dlZd dlZd dlZd dlmZm	Z	 d dl
Z
d dlmZ d dlmZ d dlmZ d dlZd dlmZ d dlZd dlmZ d dlZd dlZd dlmZ d dlmZ d dlmc mZ   ej!        d	          Z" e	d
ej#        ej$        z  ej%        z            Z& G d dej'                  Z(dZ)dZ*e j+        ej,         G d dee&                                           Z-e j.        e&df         Z/de)e*dde j0        dz  de-de1dee2         de3e4e4f         de-fdZ5 ej,        d           G d de j6                              Z7ej,         G d  d!ej8        e j6                              Z9ej#        ddd"d#ej:        e2z  d$e;ej%                 e;ej#                 z  d%ej<        dz  d&ej=        j>        dz  de j?        f
d'Z@dS )(    N)Sequence)GenericTypeVar)nnx)struct)traverse_util)pi0_pytorch)image_toolsopenpiArrayT)boundc                       e Zd ZdZdZdZdZdS )	ModelTypezSupported model types.pi0pi0_fastpi05N)__name__
__module____qualname____doc__PI0PI0_FASTPI05     4/home/robot-lab/Pi0.5_yam/src/openpi/models/model.pyr   r      s#          
CHDDDr   r   )
base_0_rgbleft_wrist_0_rgbright_wrist_0_rgb)   r    c                      e Zd ZU dZeeej        edf         f         e	d<   eeej
        edf         f         e	d<   ej        edf         e	d<   dZej        ed	f         dz  e	d
<   dZej
        ed	f         dz  e	d<   dZej        ed	f         dz  e	d<   dZej
        ed	f         dz  e	d<   edej        e         ddfd            Zdej        e         fdZdS )ObservationzHolds observations, i.e., inputs to the model.

    See `Observation.from_dict` to see the expected dictionary form. This is the format
    that should be produced by the data transforms.
    z*b h w cimagesz*bimage_masksz*b sstateNz*b ltokenized_prompttokenized_prompt_masktoken_ar_masktoken_loss_maskdatareturnzObservation[ArrayT]c                    d|v d|v k    rt          d          |d         D ]}|d         |         j        t          j        k    r>|d         |                             t          j                  dz  dz  dz
  |d         |<   at          |d         |         d          rt|d         |         j        t          j        k    rS|d         |                             t          j                  	                    d	d
dd          dz  dz  dz
  |d         |<    | |d         |d         |d         |
                    d          |
                    d          |
                    d          |
                    d                    S )zsThis method defines the mapping between unstructured data (i.e., nested dict) to the structured Observation format.r&   r'   zEtokenized_prompt and tokenized_prompt_mask must be provided together.imageg     o@       @      ?dtyper            
image_maskr%   r(   r)   r#   r$   r%   r&   r'   r(   r)   )
ValueErrorr0   npuint8astypefloat32hasattrtorchtopermuteget)clsr*   keys      r   	from_dictzObservation.from_dictm   s    $&,Ct,KLLdeee= 	r 	rCG}S!'2833%)']3%7%>%>rz%J%JU%RUX%X[^%^Wc""gs+W55 r$w-:L:RV[Va:a:a%)']3%7%:%:5=%I%I%Q%QRSUVXY[\%]%]`e%ehk%knq%qWc"s=\*w-!XX&899"&((+B"C"C((?33 HH%677
 
 
 	
r   c                     t          j        |           }|                    d          |d<   |                    d          |d<   |S )z)Convert the Observation to a nested dict.r#   r-   r$   r4   )dataclassesasdictpop)selfresults     r   to_dictzObservation.to_dict   sB    #D)) **X..w%zz-88|r   )r   r   r   r   dictstratFloatr   __annotations__Boolr&   Intr'   r(   r)   classmethodPyTreerB   rI   r   r   r   r"   r"   Q   sX          bhvz1223333c2764<0011118FFN#### 7;bfVV^,t3:::<@2766>2T9@@@
 48M26&&.)D07776:ORWVV^,t3:::
RYv. 
3H 
 
 
 [
*6*      r   r"   z*b ah adF)train
image_keysimage_resolutionrngobservationrS   rT   rU   r+   c          	         t          |                              |j                  s't          d| dt	          |j                             |j        j        dd         }i }|D ]d}|j        |         }|j        dd         |k    rBt                              d| d|j        dd          d	|            t          j
        |g|R  }|r|d
z  dz   }g }	d|vrr|j        dd         \  }
}|	t          j        t          |dz            t          |
dz                      t          j        ||
          t          j        d          gz  }	|	t          j        ddd          gz  }	t"          j                            | |j        d                   } t#          j        t          j        |	           ||          }|d
z  dz
  }|||<   fi }|D ]Q}||j        vr$t/          j        |t.          j                  ||<   /t/          j        |j        |                   ||<   Rt7          |||j        |j        |j        |j        |j                  S )zPreprocess the observations by performing image augmentations (if train=True), resizing (if necessary), and
    filling in a default image mask (if necessary).
    z#images dict missing keys: expected z, got Nr2   r1   zResizing image z from z to r.   g      ?wristgffffff?)   g333333?g?)
brightnesscontrast
saturationr   r/   )r0   r5   ) setissubsetr#   r6   listr%   shapeloggerinfor
   resize_with_padaugmax
RandomCropintResizeRotateColorJitterjaxrandomsplitvmapChainr$   jnponesboolasarrayr"   r&   r'   r(   r)   )rV   rW   rS   rT   rU   batch_shape
out_imagesrA   r-   
transformsheightwidthsub_rngs	out_maskss                 r   preprocess_observationr}      s    z??##K$677 mkzkkQUVaVhQiQikklll#)#2#.KJ    "3';qs///KK]#]]U[15E]]K[]]^^^/I8HIIIE 	&CK#%EJc!! %AaC 0%c%$,&7&7Vd]9K9KLLM%00M'** 

 "cCCPPP J z''U[^<<H7CHV\:677%HHE CK#%E
3 I G Gk--- XkBBBIcNN [)@)EFFIcNN$5)?!/#3   r   T)frozenc                   0   e Zd ZU dZeed<   eed<   eed<   eej        de	fd                        Z
ej        dej        ddfd	            Zd
ddej        deddfdZdefdZej        dddedeeef         fd            ZddedefdZddedefdZdS )BaseModelConfigzConfiguration shared by all models. Specific models should inherit from this class, and implement the `create`
    method to create the corresponding model.
    
action_dimaction_horizonmax_token_lenr+   c                     dS )zThe model type.Nr   )rG   s    r   
model_typezBaseModelConfig.model_type         r   rV   	BaseModelc                     dS )z,Create a new model, initializing parameters.Nr   )rG   rV   s     r   createzBaseModelConfig.create   r   r   T)remove_extra_paramsparamsr   c                   t          j        | j        t          j                            d                    }t          j        |          \  }}|r2t          j        	                    |
                                |          }t          j        |
                                |dd           |                    |           t          j        ||          S )z)Create a model with the given parameters.r   TF)expectedgotcheck_shapescheck_dtypes)r   
eval_shaper   rm   rn   rA   ro   ocptransform_utilsintersect_treesto_pure_dictrL   check_pytree_equalityreplace_by_pure_dictmerge)rG   r   r   modelgraphdefr%   s         r   loadzBaseModelConfig.load   s    t{CJNN1,=,=>>)E**% 	W(889K9K9M9MvVVF
 %*<*<*>*>FY]lqrrrr""6***y5)))r   weight_pathc                     t                               d|            t          j        |j                  }t
          j                            ||           |S )Nztrain_config: )config)rd   re   r	   
PI0Pytorchr   safetensorsr<   
load_model)rG   train_configr   r   s       r   load_pytorchzBaseModelConfig.load_pytorch   sQ    3\33444&l.@AAA$$UK888r   r2   
batch_sizer   c                    dS )zOReturns the input specification for the model. Values are jax.ShapeDtypeStruct.Nr   )rG   r   s     r   inputs_speczBaseModelConfig.inputs_spec   r   r   c                 v    |                      |          \  }}t          j                            d |          S )Nr   c                 @    t          j        | j        | j                  S Nrr   rs   rc   r0   xs    r   <lambda>z*BaseModelConfig.fake_obs.<locals>.<lambda>       chqw&@&@ r   r   rm   treemap)rG   r   observation_spec_s       r   fake_obszBaseModelConfig.fake_obs   s9    "..*.EE!x||@@BRSSSr   c                 v    |                      |          \  }}t          j                            d |          S )Nr   c                 @    t          j        | j        | j                  S r   r   r   s    r   r   z*BaseModelConfig.fake_act.<locals>.<lambda>  r   r   r   )rG   r   r   action_specs       r   fake_actzBaseModelConfig.fake_act  s6    ))Z)@@;x||@@+NNNr   N)r2   )r   r   r   r   ri   rN   propertyabcabstractmethodr   r   rL   KeyArrayLiker   Paramsrt   r   rK   r   tupler"   Actionsr   r   r   r   r   r   r   r      s         
 OOOI     X 	;"/ ;k ; ; ; ; FJ * * *29 *d *k * * * *c     	/0 ^ ^ ^ ^U;;O5P ^ ^ ^ ^T T3 T{ T T T TO O3 Ow O O O O O Or   r   c                       e Zd ZU dZeed<   eed<   eed<   ej        dddej	        de
d	ed
edej        ej        df         f
d            Zej        dej	        de
defd            ZdS )r   zBase class for all model implementations. Specific models should inherit from this class. They should call
    super().__init__() to initialize the shared attributes (action_dim, action_horizon, and max_token_len).
    r   r   r   F)rS   rV   rW   actionsrS   r+   z*b ahc                    d S r   r   )rG   rV   rW   r   rS   s        r   compute_losszBaseModel.compute_loss  s	     '*cr   c                     d S r   r   )rG   rV   rW   kwargss       r   sample_actionszBaseModel.sample_actions  s    cfcfr   N)r   r   r   r   ri   rN   r   r   rL   r   r"   r   rt   rM   Arrayr   r   r   r   r   r   r     s           OOO * * *_* !* 	* * 
"(G#	$* * * * 	f"/ffZafff fffr   r   )restore_typer0   shardingparams_pathr   r0   r   c                   t          |                               d          s&t          j        |                                           n| } t
          j        u romt
          j                            t          j	                    d          }t
          j        
                    |t
          j                                                  t          j                    5 }|                    |           }d|d         i}|                    | t          j                            |t
          j                            fd|                              d         }ddd           n# 1 swxY w Y   t)          j        |          }	t-          d |	D                       rd |	                                D             }	t)          j        |	          S )	a  Restores unstructured params PyTree from a checkpoint.

    This works with checkpoints saved with `save_state` during openpi training (see `training/checkpoints.py`) as
    well as pre-trained checkpoints released for openpi.

    Args:
        params_path: The local path to the checkpoint directory.
        restore_type: The type to restore the params as. Can be set to `np.ndarray` to load the params as a numpy array.
        dtype: The dtype to restore all params as. If not provided, will use the original dtype from the checkpoint.
        sharding: The sharding to use for the params. If not provided, the params will be replicated across all devices.

    Returns:
        The restored params.
    zgs://Nr   r   c                 2    t          j                  S )N)r   r   r0   )r   ArrayRestoreArgs)r   r0   r   r   s    r   r   z restore_params.<locals>.<lambda>B  s    c2HS_glmmm r   )itemrestore_argsc              3   .   K   | ]}|d          dk    V  dS )rY   valueNr   ).0kps     r   	<genexpr>z!restore_params.<locals>.<genexpr>J  s+      
3
32b6W
3
3
3
3
3
3r   c                 *    i | ]\  }}|d d         |S )NrY   r   )r   r   vs      r   
<dictcomp>z"restore_params.<locals>.<dictcomp>K  s&    CCCeb!r#2#wCCCr   )rK   
startswithpathlibPathresolverm   r   r   MeshdevicesNamedShardingPartitionSpecr   PyTreeCheckpointermetadatarestoreargsPyTreeRestorer   r   r   flatten_dictallitemsunflatten_dict)
r   r   r0   r   meshckptrr   r   r   flat_paramss
    ```      r   restore_paramsr     s   * >A=M=M=X=XY`=a=ar',{++33555grKsy  X%5|  77<--dCL4N4N4P4PQQ			!	! U>>+..(8,-H"" X\\mmmmmmos  #  
 
 	                 ,V44K

3
3{
3
3
333 DCC{/@/@/B/BCCC'444s   A>E((E,/E,)Ar   collections.abcr   rD   enumloggingr   typingr   r   rg   flaxr   r   r   rm   	jax.numpynumpyrr   r7   orbax.checkpoint
checkpointr   r   r<   openpi.models_pytorchr	   openpi.sharedr
   openpi.shared.array_typingsharedarray_typingrL   	getLoggerrd   r   Tensorndarrayr   Enumr   
IMAGE_KEYSIMAGE_RESOLUTION	typecheck	dataclassr"   rM   r   r   rt   rK   r   ri   r}   ABCr   Moduler   r   typer0   r   Shardingr   r   r   r   r   <module>r     s   



 $ $ $ $ $ $        # # # # # # # #                    



                      - - - - - - % % % % % % ' ' ' ' ' ' ' ' '		8	$	$ 
U\!9BJ!F	G	G	G    	   
  D 5 5 5 5 5'&/ 5 5  5t (6:%
&  *(8@ @ @	4	@@ 	@
 @ CHo@ @ @ @ @F d###/O /O /O /O /Ocg /O /O $#/Od g g g g g
CG g g g4 8;y"-1.5 .5 .5#.5 rz"T#)_4.5 9t	.5
 l#d*.5 Y.5 .5 .5 .5 .5 .5r   