U
    qh                     @  sH   d dl mZ d dlmZ d dlZd dlmZmZ ddddddd	ZdS )
    )annotations)AnyN)
ModelProtoValueInfoProtor   zdict[str, list[Any]])model
input_dimsoutput_dimsreturnc                   s   t   dddddd}| | jj | | jj | | jj ddd	d
dd fdd}| jjD ]2}|j}|| }t|D ]\}}	|||	|| q~qd| jjD ]2}
|
j}|| }t|D ]\}}	||
|	|| qqtj	|  | S )aM  This function updates the dimension sizes of the model's inputs and outputs to the values
    provided in input_dims and output_dims. if the dim value provided is negative, a unique dim_param
    will be set for that dimension.

    Example. if we have the following shape for inputs and outputs:

    * shape(input_1) = ('b', 3, 'w', 'h')
    * shape(input_2) = ('b', 4)
    * shape(output)  = ('b', 'd', 5)

    The parameters can be provided as:

    ::

        input_dims = {
            "input_1": ['b', 3, 'w', 'h'],
            "input_2": ['b', 4],
        }
        output_dims = {
            "output": ['b', -1, 5]
        }

    Putting it together:

    ::

        model = onnx.load('model.onnx')
        updated_model = update_inputs_outputs_dims(model, input_dims, output_dims)
        onnx.save(updated_model, 'model.onnx')
    zset[str]zlist[ValueInfoProto]None)dim_param_setvalue_infosr	   c                 S  s:   |D ]0}|j jj}|jD ]}|dr| |j qqd S )N	dim_param)typetensor_typeshapedimHasFieldaddr   )r   r   infor   r    r   @/tmp/pip-unpacked-wheel-xnis5xre/onnx/tools/update_model_dims.pyinit_dim_param_set1   s
    


z6update_inputs_outputs_dims.<locals>.init_dim_param_setr   r   intstr)tensorr   jnamer	   c              
     s   | j jjj| }t|tr|dkrb|drZ|j|krZtd| d| d| d|j d	||_q|d t	| }| krtd	| d| d
||_
n$t|t	r||_
ntdt | d S )Nr   	dim_valuez!Unable to set dimension value to z
 for axis z of z'. Contradicts existing dimension value ._z-Unable to generate unique dim_param for axis z,. Please manually provide a dim_param value.z@Only int or str is accepted as dimension value, incorrect type: )r   r   r   r   
isinstancer   r   r   
ValueErrorr   r   )r   r   r   r   Z	dim_protoZgenerated_dim_paramr   r   r   
update_dim>   s&    

z.update_inputs_outputs_dims.<locals>.update_dim)
setgraphinputoutputZ
value_infor   	enumerateonnxcheckerZcheck_model)r   r   r   r   r#   Zinput_Z
input_nameZinput_dim_arrr   r   r'   Zoutput_nameZoutput_dim_arrr   r"   r   update_inputs_outputs_dims   s$    #	r+   )	
__future__r   typingr   Zonnx.checkerr)   r   r   r+   r   r   r   r   <module>   s   