U
    <c1                     @   s  d dl Z d dl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 d dlmZ G dd	 d	eZd
ddgZddgZedZedZedZedZdZedZedZdZedZedZedZedZedZedZ edZ!eed Z"dZ#ed Z$ed!Z%ee e&d"d#d$Z'ee e&d%d&d'Z(ee e&d(d)d*Z)ee e&d+d,d-Z*e+e&d.d/d0Z,ee&ef e&d1d2d3Z-eee&ef  ee&ef d4d5d6Z.e&eee&ef  dd7d8d9Z/eee&ef  eee&ef  d:d;d<Z0dd=d>d?Z1e2d@kre1  dS )A    N)Enum)Path)AnyDictList)generate_upgraders_bytecode)CodeTemplate)#MOBILE_UPGRADERS_HEADER_DESCRIPTIONc                   @   s    e Zd ZdZdZdZdZdZdS )ByteCode               N)__name__
__module____qualname__instructions	constantstypes	operatorsregister_size r   r   S/tmp/pip-unpacked-wheel-gikjz4vx/torchgen/operator_versions/gen_mobile_upgraders.pyr
      s
   r
   zaten::full.nameszaten::full.outz
aten::fullZfull_0_4Zfull_out_0_4z7
    Instruction{OpCode::${operator_name}, ${X}, ${N}},zSstd::vector<Instruction>({
        ${instruction_list}
    }), // instructions listz
    c10::IValue(${constant}),zMstd::vector<c10::IValue>({
        ${constant_list}
    }), // constants listz-std::vector<c10::IValue>(), // constants listzc10::parseType("${type_str}"),zFstd::vector<c10::TypePtr>({
        ${type_list}
    }), // types listz*std::vector<c10::TypePtr>(), // types listzN
    OperatorString({"${operator_name}", "${overload_name}", ${num_of_args}}),z\
    std::vector<OperatorString>({
        ${operator_string_list}
    }), // operators listz
    mobile::Function::registerFunc(
        "${upgrader_name}",
        ${instruction_list},
        ${constant_list},
        ${type_list},
        ${register_size}
    )zi
    ByteCodeFunctionWithOperator({
        ${bytecode_function},
        ${operator_string_list}
    }),zhUpgrader({${upgrader_min_version}, ${upgrader_max_version}, "${upgrader_name}", ${bytecode_func_index}})z
    {std::string("${operator_name}"),
        std::vector<Upgrader>({
            ${upgrader_list_in_version_map}
        })},a%  
const std::unordered_map<std::string, std::vector<Upgrader>>
getOperatorVersionMapForMobile() {
  static std::unordered_map<std::string, std::vector<Upgrader>>
        operatorVersionMapForMobile({
            ${operator_list_in_version_map}
      });
  return operatorVersionMapForMobile;
}
a(  
#include <caffe2/serialize/versions.h>
#include <torch/csrc/jit/mobile/upgrader_mobile.h>

namespace c10 {
TypePtr parseType(const std::string& pythonStr);
} // namespace c10

namespace torch {
namespace jit {

// clang-format off

// From operator_versions_map
${operator_version_map}

const std::vector<ByteCodeFunctionWithOperator>& getUpgraderBytecodeList() {
  auto generate_upgrader_bytecode_list = []() {
    std::vector<ByteCodeFunctionWithOperator> upgrader_function_list({
               ${upgrader_bytecode}
            });
    for (const auto& upgrader_function : upgrader_function_list) {
      for (const auto& op : upgrader_function.operators) {
        upgrader_function.function.append_operator(
            op.name,
            op.overload_name,
            op.num_specified_args);
      }
    }
    return upgrader_function_list;
  };
  static std::vector<ByteCodeFunctionWithOperator> upgraderBytecodeList =
      generate_upgrader_bytecode_list();
  return upgraderBytecodeList;
}

// clang-format on

} // namespace jit
} // namespace torch
zupgrader_mobile.cppzHUpgrader({${min_version}, ${max_version}, ${operator_name}, ${index}}),
zR{
  std::string(${operator_name}),
  std::vector<Upgrader>({${upgrader_list}});
}
)instruction_list_from_yamlreturnc                 C   sH   g }| D ]&}| tj|d |d |d d qtjd|ddS )Nr   r   r   )operator_nameXN 
)instruction_list)appendONE_INSTRUCTION
substituteINSTRUCTION_LISTjoinlstrip)r   Zinstruction_list_partZinstructionr   r   r   construct_instruction   s    r(   )constants_list_from_yamlr   c                 C   s   g }| D ]}d }t |tr(d| d}nTt |tr@|r:dnd}n<|d krNd}n.t |trbt|}ntd| dt| d|tj|d qt	|d	krt
S tjd|d
dS )N"truefalser   zThe type of z is zO. Please add change in construct_constants function in gen_mobile_upgraders.py.)Zconstantr   r    )constant_list)
isinstancestrboolint
ValueErrortyper"   ONE_CONSTANTr$   lenCONSTANTS_LIST_EMPTYCONSTANT_LISTr&   r'   )r)   Zconstants_list_partZconstant_from_yamlZconvert_constantr   r   r   construct_constants   s(    



r8   )operator_list_from_yamlr   c                 C   sH   g }| D ]&}| tj|d |d |d d qtjd|ddS )Nr   r   r   )r   Zoverload_nameZnum_of_argsr   r    )operator_string_list)r"   ONE_OPERATOTR_STRINGr$   OPERATOR_STRING_LISTr&   r'   )r9   Zoperator_list_partoperatorr   r   r   construct_operators   s    r>   )types_tr_list_from_yamlr   c                 C   sH   g }| D ]}| tj|d qt|dkr0tS tjd|ddS )N)Ztype_strr   r   r    )	type_list)r"   ONE_TYPEr$   r5   TYPE_LIST_EMPTY	TYPE_LISTr&   r'   )r?   Ztypes_tr_list_partZtypes_trr   r   r   construct_types   s    rD   )register_size_from_yamlr   c                 C   s"   t | tstd|  dt| S )NzInput register size is zJ andit's type is {type(register_size_from_yaml)}. An int type is expected.)r.   r1   r2   r/   )rE   r   r   r   construct_register_size   s
    

rF   )'upgrader_bytecode_function_to_index_mapr   c              
   C   s   t j }t| dd d}dd |D }g }|D ]}g }|tkrFq4t j|}|| }t|t|ksntt	|D ]:\}	}
|
j
}| | }|tj||	 j||	 j||d qv|tj|d|d q4tjd|d	d
S )Nc                 S   s   | d S )Nr   r   )itemr   r   r   <lambda>
      z(construct_version_maps.<locals>.<lambda>keyc                 S   s   i | ]\}}||qS r   r   ).0namelstr   r   r   
<dictcomp>  s      z*construct_version_maps.<locals>.<dictcomp>)Zupgrader_min_versionZupgrader_max_versionupgrader_nameZbytecode_func_indexr   )r   Zupgrader_list_in_version_mapr    )Zoperator_list_in_version_map)torchZ_CZ_get_operator_version_mapsorteditemsEXCLUDED_OP_SETZ_get_upgrader_rangesr5   AssertionError	enumeraterQ   r"   ONE_UPGRADER_IN_VERSION_MAPr$   min_versionZmax_versionONE_OPERATOR_IN_VERSION_MAPr&   OPERATOR_VERSION_MAPr'   )rG   Zversion_mapZsorted_version_map_Zsorted_version_mapZ!operator_list_in_version_map_partZop_nameZupgraders_in_version_map_partZupgrader_rangesZupgrader_entriesidxZupgrader_entryrQ   Zbytecode_function_indexr   r   r   construct_version_maps  sF    

r]   )upgrader_dictr   c                 C   sB   i }d}| D ]0}|  D ]"\}}|tkr*q|||< |d7 }qq|S )Nr   r   )rT   EXCLUE_UPGRADER_SET)r^   rG   indexupgrader_bytecoderQ   bytecoder   r   r   +get_upgrader_bytecode_function_to_index_map0  s    rc   )cpp_pathr^   r   c              	   C   s~  g }t |}t|}g }|D ]}| D ]\}}|tkr:q(d}	d}
d}d}d}| D ]v\}}t| }d}|tjkr~t|}	qV|tjkrt|}
qV|tj	krt
|}qV|tjkrt|}qV|tjkrVt|}qVtj||	|
||d}tj|d|dd}|| q(qtj|d|dd}|| td| d t  ttj| td }d|}||d	 W 5 Q R X d S )
Nr   )rQ   r!   r-   r@   r   r    )Zbytecode_functionr:   )Zoperator_version_mapra   zwriting file to : /wbzutf-8)rc   r]   rT   r_   r
   r   r(   r   r8   r   r>   r   rD   r   rF   ONE_UPGRADER_FUNCTIONr$   ONE_UPGRADER_SRCr'   r"   UPGRADER_CPP_SRCr&   printUPGRADER_MOBILE_FILE_NAMEopenospathwriteencode)rd   r^   Z
body_partsrG   Zversion_map_srcZall_upgrader_src_stringra   rQ   rb   Zinstruction_list_strZconstant_list_strZtype_list_strZregister_size_strZoperator_list_strZ
table_namecontentselementZbody_stringZone_upgrader_function_stringZone_upgrader_src_stringZupgrader_file_contentout_fileZfinal_outputr   r   r   	write_cpp>  s`    











rt   )upgrader_listr   c                 C   s   t | dd d}|S )Nc                 S   s   t t| S )N)nextiter)Zone_upgraderr   r   r   rI   w  rJ   zsort_upgrader.<locals>.<lambda>rK   )rS   )ru   sorted_upgrader_listr   r   r   sort_upgraderu  s
     ry   )r   c                  C   sb   t  } t| }|D ]}tdtt| qtt jd }|d d d d }t	t
|| d S )Nzafter sort upgrader : r   rR   ZcsrcZjitZmobile)r   ry   rj   rv   rw   r   __file__resolveparentsrt   r/   )ru   rx   ZupZpytorch_dirZupgrader_pathr   r   r   main|  s    r}   __main__)3rm   enumr   pathlibr   typingr   r   r   rR   Ztorch.jit.generate_bytecoder   Ztorchgen.code_templater   Z8torchgen.operator_versions.gen_mobile_upgraders_constantr	   r
   rU   r_   r#   r%   r4   r7   r6   rA   rC   rB   r;   r<   rg   rh   rX   rZ   r[   ri   rk   ZUPGRADER_ELEMENTZPER_OPERATOR_UPGRADER_LISTr/   r(   r8   r>   rD   r1   rF   r]   rc   rt   ry   r}   r   r   r   r   r   <module>   s   			-
	

+
7(
