U
    d                     @   s,   d dl mZ d dlmZ G dd deZdS )    )schema)
ModelLayerc                       s&   e Zd Zd fdd	Zdd Z  ZS )PairwiseSimilaritydotpairwise_similarityc                    s.  t t| j|||f| t|tjs2td|d|kd|koFd|kA sRtd|| _d|krr|d }|d }n|d }|d }t|tj	stdd| t|tj	stdd| d	|kr|d	 }	t|	tj	std
|	|	| _
nd | _
|| _|| _| d j}
t	|
|ff| d| _d S )Nz8Incorrect input type. Expected Struct, but received: {0}Zall_embeddingsx_embeddingsy_embeddingszLeither (all_embeddings) xor (x_embeddings and y_embeddings) should be given.z-Incorrect input type for x. Expected Scalar, zbut received: {0}z-Incorrect input type for y. Expected Scalar, indices_to_gatherzGIncorrect type of indices_to_gather. Expected Scalar, but received: {0}r   output)superr   __init__
isinstancer   StructAssertionErrorformatpairwise_similarity_funcZScalarr	   r   r   Zfield_typesbaseget_next_blob_referenceoutput_schema)selfmodelZinput_recordZ
output_dimr   namekwargsr   r   r	   Zdtype	__class__ L/tmp/pip-unpacked-wheel-ua33x9lu/caffe2/python/layers/pairwise_similarity.pyr      sX    
zPairwiseSimilarity.__init__c                 C   s   | j dkrP|j|  dd}|j|  dd}|j||g| |d gdd}nH| j dkr|j|  |  g| |  d gdd}ntd| j | jr|	||d }|
||  g|   n|	||   d S )	NZcosine_similarity   )ZaxisZ_matmul)Ztrans_br   z(pairwise_similarity_func={} is not valid_flatten)r   Z	Normalizer   r   ZBatchMatMulr   NotImplementedErrorr   r	   ZFlattenZBatchGatherr   )r   netZx_embeddings_normZy_embeddings_normYZ	flattenedr   r   r   add_opsA   s:    

 
zPairwiseSimilarity.add_ops)r   r   )__name__
__module____qualname__r   r"   __classcell__r   r   r   r   r      s     1r   N)Zcaffe2.pythonr   Zcaffe2.python.layers.layersr   r   r   r   r   r   <module>   s   