3
I4W^o  ã               @   s\   d dl mZ d dl mZ d dl mZ d dl mZ d dlmZ d dlmZ G dd„ deƒZ	d	S )
é    )Úabsolute_import)Údivision)Úprint_function)Úunicode_literals)Ú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j|ƒƒ‚d|kd|koFd|kA sRtdƒ‚|| _d|krr|d }|d }n|d }|d }t|tj	ƒs tddj|ƒ ƒ‚t|tj	ƒs¾td	dj|ƒ ƒ‚d
|krð|d
 }	t|	tj	ƒsètdj|	ƒƒ‚|	| _
nd | _
|| _|| _|jƒ d j}
tj	|
|ff| jdƒƒ| _d S )Nz9Incorrect input type. Excpected Struct, but received: {0}Zall_embeddingsÚx_embeddingsÚy_embeddingsz<either (all_embeddings) xor (x_embeddings and y_embeddings) z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   ÚoutputzLeither (all_embeddings) xor (x_embeddings and y_embeddings) should be given.)Ú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__© úI/tmp/pip-build-e66j97b2/torch/caffe2/python/layers/pairwise_similarity.pyr      sB     
zPairwiseSimilarity.__init__c             C   sÜ   | j dkrP|j| jƒ dd�}|j| jƒ dd�}|j||g| j|d ƒgdd�}nH| j dkrˆ|j| jƒ | jƒ g| j| jƒ d ƒgdd�}ntdj| j ƒƒ‚| jrÈ|j	||d ƒ}|j
|| jƒ g| jƒ ƒ n|j	|| jƒ ƒ 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    0r   N)
Ú
__future__r   r   r   r   Zcaffe2.pythonr   Zcaffe2.python.layers.layersr   r   r   r   r   r   Ú<module>   s   