
    Wh                       d Z ddlmZ ddlmZ ddlZddl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 dd
lmZ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 ddlmZ ddlmZmZm Z   ej!        d          Z"de"_#        d1dZ$e"j%        d             Z&e"j'        d             Z(d Z)d Z*d Z+e)ej,        e"<   e*ej-        e"<   e+ej.        e"<    ej/        e" ej0        e&d                     	 	 d2d3d*Z1	 	 d4d5d0Z2dS )6a  JAX primitives related to sparse operations.

This is experimental work to explore sparse support in JAX.

The primitives defined here are deliberately low-level: each primitive implements
a common sparse operation (sparse to dense, dense to sparse, sparse matrix/vector
product, sparse matrix/matrix product) for two common sparse representations
(CSR and COO).

These routines have reference implementations defined via XLA scatter/gather
operations that will work on any backend, although they are not particularly
performant. On GPU runtimes built against CUDA 11.0/ROCm 5.0 or newer, each operation is
computed efficiently via cusparse/hipsparse.

Further down are some examples of potential high-level wrappers for sparse objects.
(API should be considered unstable and subject to change).
    )annotations)partialN)	tree_util)	JAXSparse)BCOO)BCSR)COO)CSRCSC)_coo_extract)mlir)core)dtypes)ad)batching)Array	DTypeLikeShapetodenseFarrJAXSparse | Arrayreturnr   c                R    t          j        |           \  }}t          j        |d|iS )zIConvert input to a dense matrix. If input is already dense, pass through.tree)r   tree_flatten	todense_pbind)r   bufsr   s      a/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/jax/experimental/sparse/api.pyr   r   =   s+    %c***$		)D	)	))    c                    t          j        | |          }t          |t                    r|                                n|S N)r   tree_unflatten
isinstancer   r   r   r   r   s      r   _todense_implr&   B   s5     t,,#$S)44	=#=r    c                    t          j        | |          }t          |t          j                  r|S t          j        |j        |j        t          j        |j	                            S )N)	weak_type)
r   r#   r$   r   ShapedArrayshapedtyper   is_weakly_typeddatar%   s      r   _todense_abstract_evalr.   G   sY     t,,#T%&& J		#)SY&:PQTQY:Z:Z	[	[	[[r    c                   t          |d         t          j                  rJ t          d |dd          D                       sJ t	          j        | d|i}t	          j        |d         g| dd          R d|i}||fS )Nr   c              3  J   K   | ]}t          |t          j                  V  d S r"   )r$   r   Zero).0ts     r   	<genexpr>z_todense_jvp.<locals>.<genexpr>P   s.      ::Z27##::::::r       r   )r$   r   r1   allr   r   )primalstangentsr   primals_outtangents_outs        r   _todense_jvpr;   N   s    RW----	-	::Xabb\:::	:	:::	:3d33+EgabbkEEEEE,	l	""r    c               L   t          j        |d                   sJ t          d |dd          D                       rJ t                      }t	          j        ||gt          |          z            }ddlm}m	} ddl
m} ddlm} ||u r| fS t          ||          r|\  }	}
 ||
|           |
fS t          ||          r|\  }	}
} ||
||           |
|fS t          |t                    r|\  }	}}t!          |||           ||fS t#          dt%          |                     )Nr   c              3  >   K   | ]}t          j        |          V  d S r"   )r   is_undefined_primal)r2   bufs     r   r4   z%_todense_transpose.<locals>.<genexpr>W   s-      AA',,AAAAAAr    r5   )r   r   )_bcoo_extract)bcsr_extractztodense_transpose for )r   r>   anyobjectr   r#   lenjax.experimental.sparser   r   jax.experimental.sparse.bcoor@   jax.experimental.sparse.bcsrrA   r$   r	   r   NotImplementedErrortype)ctr   r   standinobjr   r   r@   rA   _indicesindptrrowcols                 r   _todense_transposerR   U   s}   		Q	(	(((	(AAQRRAAAAAAA	AHH' y3t99'<==#00000000888888777777G^^5L#t 
DJAw="%%w..#t DAw<,,gv==#s DKAsCS"%%sC//
BtCyyBB
C
CCr    c               ^     t          j        t          t          |          |          |  dfS )N)r   r   )jaxvmapr   r&   )batched_args
batch_dimsr   s      r   _todense_batching_rulerX   l   s.    	@'-d333Z	@	@,	OQR	RRr    )multiple_resultsint32bcoor*   r   r+   DTypeLike | Noneindex_dtyper   sparse_formatstrr   c           	         t           t          t          t          t          d}||vr4t          d|dt          |                                                     ||         } |j        | f||d|S )a~  Create an empty sparse array.

  Args:
    shape: sequence of integers giving the array shape.
    dtype: (optional) dtype of the array.
    index_dtype: (optional) dtype of the index arrays.
    format: string specifying the matrix format (e.g. ['bcoo']).
    **kwds: additional keywords passed to the format-specific _empty constructor.
  Returns:
    mat: empty sparse matrix.
  )bcsrr[   coocsrcsczsparse_format=z  not recognized; must be one of )r+   r]   )	r   r   r	   r
   r   
ValueErrorlistkeys_empty)r*   r+   r]   r^   kwdsformatsclss          r   emptyrl   v   s     4CLL''!!
 >m > >'+GLLNN';';> > ? ? ?#	E	HK	H	H4	H	HHr    NintM
int | Nonekc           	     0   t           t          t          t          d}|| }t	          j        t          j        |           } t	          j        t          j        |          }t	          j        t          j        |          }||         } |j        d|| |||d|S )a  Create 2D sparse identity matrix.

  Args:
    N: int. Number of rows in the output.
    M: int, optional. Number of columns in the output. If None, defaults to `N`.
    k: int, optional. Index of the diagonal: 0 (the default) refers to the main
       diagonal, a positive value refers to an upper diagonal, and a negative value
       to a lower diagonal.
    dtype: data-type, optional. Data-type of the returned array.
    index_dtype: (optional) dtype of the index arrays.
    format: string specifying the matrix format (e.g. ['bcoo']).
    **kwds: additional keywords passed to the format-specific _empty constructor.

  Returns:
    I: two-dimensional sparse matrix with ones along the k-th diagonal.
  )r[   rb   rc   rd   N)ro   rm   rq   r+   r]    )	r   r	   r
   r   r   concrete_or_erroroperatorindex_eye)	rm   ro   rq   r+   r]   r^   ri   rj   rk   s	            r   eyerx      s    $ #c#>>'Y	A
X^Q//!
X^Q//!
X^Q//!#		NAau+	N	N	N	NNr    )r   r   r   r   )NrZ   r[   )
r*   r   r+   r\   r]   r   r^   r_   r   r   )Nr   NrZ   r[   )rm   rn   ro   rp   rq   rn   r+   r\   r]   r   r^   r_   r   r   )3__doc__
__future__r   	functoolsr   ru   rT   r   jax.experimental.sparse._baser   rF   r   rG   r   jax.experimental.sparse.coor	   jax.experimental.sparse.csrr
   r   jax.experimental.sparse.utilr   jax.interpretersr   jax._srcr   r   jax._src.interpretersr   r   jax._src.typingr   r   r   	Primitiver   rY   r   def_implr&   def_abstract_evalr.   r;   rR   rX   primitive_jvpsprimitive_transposesprimitive_batchersregister_lowering	lower_funrl   rx   rs   r    r   <module>r      s   $ # " " " " "        



       3 3 3 3 3 3 - - - - - - - - - - - - + + + + + + 0 0 0 0 0 0 0 0 5 5 5 5 5 5 ! ! ! ! ! !             $ $ $ $ $ $ * * * * * * 3 3 3 3 3 3 3 3 3 3 DN9%%	"	 * * * *
 > > > \ \ \# # #D D D.S S S  , ) %7 	 ")? I &  y.$.E#+ #+ #+ , , , PW%I I I I I* MQ?EO O O O O O Or    