o
    Xi                     @   s   d dl Z d dlmZ e eZdejddfddZdejddfddZdejddfd	d
Z	dejddfddZ
dejddfddZdS )    N)irvaluereturnc                 C   s(   | j tjjkr	d S tjj| _ t|  d S N)dtyper   DataTypeBFLOAT16FLOAT164_insert_cast_nodes_for_float16_to_bfloat16_to_inputsr    r   u/home/ubuntu/.local/lib/python3.10/site-packages/onnxscript/rewriter/onnxruntime/bfloat16_utils/bfloat16_converter.py(_convert_inputs_from_bfloat16_to_float16
   s   
r   c                 C   s   | j tjjkr	d S t|  d S r   )r   r   r   r   5_insert_cast_nodes_for_bfloat16_to_float16_to_outputsr   r   r   r   )_convert_outputs_from_bfloat16_to_float16   s   r   c                 C   s   t |  }tjdtjjd}tjdd| gd|gd}tjj|jd _| j	|jd _	t |  D ]\}}||u r9q0|
||jd  q0|d d jd usPJ d|d d jd | d S )	Ntonamer    Cast   domainop_typeinputsnum_outputs
attributesr   z!The node should belong to a graph)tupleusesr   	AttrInt64r   r   Nodeoutputsr   shapereplace_input_withgraphprepend)r   user_nodes_and_indicesattrcastnodeindexr   r   r   r
      s"   r
   c                 C   s  |   }|  }|d u s|d u rtd|  d S tjdtjjd}tjdd|j	| gd|gd}tjj|j	d _
|j	| j|j	d _|| |jd usPJ d	t|jj	D ]\}}||j	| krj|j	d |jj	|< qV|j	d j|j	| j|j	| _|j	d _d S )
Nz(Output value %s has no producer or indexr   r   r   r   r   r   r   zNode graph should not be None)producerr*   loggerwarningr   r   r   r	   r    r!   r   r"   appendr$   	enumerater   )r   r)   r*   r'   r(   idxgraph_or_function_outputr   r   r   r   0   s0   



r   modelc                 C   s0   | j jD ]}t| q| j jD ]}t| qdS )a  Adapt the model datatype if it's bfloat16.

    Because onnxruntime does not support bfloat16 as input/output datatype, we need to
    convert the bfloat16 datatype to float16. This function will convert the bfloat16
    datatype to float16 and insert Cast nodes to convert float16 to bfloat16.

    Model:
        inputs(float16) -> Cast(bfloat16) -> nodes(bfloat16) -> Cast(float16) -> outputs(float16)

    TODO: Delete this function after onnxruntime supports bfloat16.

    Args:
        model: The model to adapt.

    N)r$   r   r   r!   r   )r2   inputoutputr   r   r    dtype_adapter_for_bfloat16_modelP   s
   

r5   )logging
onnxscriptr   	getLogger__name__r,   Valuer   r   r
   r   Modelr5   r   r   r   r   <module>   s   
 