
    ukin                   |   U d dl mZ d dlZd dlmZmZ d dlZd dlZd dlZd dlm	Z	 d dl
Z
d dlZd dlZd dlmZmZmZmZmZ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 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& 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/m0Z0m1Z1m2Z2m3Z3 d dl4m5Z5 d dl6m7Z7 d dl8m9Z9 d dl8m:Z: d dl8m;Z; d dl8m<Z= d d l8m>Z> d d!l?m@Z@ d d"l?mAZB d d#lCmDZDmEZE d d$lFmGZGmHZHmIZImJZJ d d%lKmLZL d d&lMmNZN d d'lMmOZO d d(lPmQZQ d d)lRmSZSmTZTmUZVmWZWmXZX d d*lYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z` d d+lambZbmcZcmdZdmeZemfZfmgZgmhZhmiZi ej                  Zkej                  Zmej                  Zo ed,      ZpedeqcZqZreeescZsZt e,j                  d-      Zvdd.Zwdd0Zxdd1Zydd2Zzdd3Z{edd4       Z|e	 	 dd5       Z|evd6        Z| eb       dd7       Z}d8 Z~d9 Zd: Zevdd;       Zevdd<       Zevdd=       Zevdd>       Zevdd?       Z G d@ dAej                        Zevej                  f	 	 	 ddB       ZevddC       Z G dD dE      Z G dF dGej                        ZevdddH       ZdddIZevdddJ       ZevdddK       ZevdddL       ZevdddM       ZevdddN       ZevdddO       ZevdddP       ZevddQ       ZevddR       ZevddS       ZevddT       ZevddU       ZevddV       ZevddW       Zevd dX       ZevdddY       ZevdddZ       Zevddd[       Zevdd\       Zevdd]       Zevdd^       Zevdd_       Zevdd`       Zevdda       Zevddb       Zevddc       Zevddd       Zevdde       Zevddf       Zevddg       Zjevddh       Zlevddi       Zevddj       Zevddk       Zevddl       Zevddm       Zevddn       Zevddo       Zevddp       Zevddq       Zev	 	 	 	 d!dr       Z	 	 	 	 d"	 	 	 	 	 	 	 	 	 d#dvZevd$dw       Zd%dzZeg	 	 	 	 	 	 	 	 d&d|       Z	 d'	 	 	 	 	 d(d}Z	 	 	 	 	 	 	 	 	 	 	 	 d)d~Zd Zd Zd Zd Z ej`                  d      Zej                  e       ej                  e       dte_        ee9j                  e<   ee9j                  e<    e;j                  ee       d*dZ	 d'	 	 	 d+dZi Zded<    G d dej                        Ze̐j                  ed<   e̐j                  ed<   e̐j                  ed<   e̐j                  ed<   e̐j                  ed<   e̐j                  ed<   e̐j                  ed<   e̐j                  ed<   e̐j                  ed<    G d de      Z G d dej                        Zedeeeeef   eeef   eef   Zedeeef   eef   Zeeee   ee   f   eee   ee   f   f   Z	 	 d,dd	 	 	 	 	 	 	 d-dZddddd	 	 	 	 	 	 	 d.dZ	 	 	 d/	 	 	 	 	 	 	 	 	 	 	 	 	 d0dZ ej                  dt       G d d             Z	 	 	 	 d1dZ edgdgfg g ffd gd g      Z	 	 	 d/	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d2dZdd	 d3dZdd	 	 	 d4dZd5dZ	 ddd	 	 	 	 	 d6dZ	 	 	 	 d7dZd8dZd9dZd:dZ	 	 	 	 d;dZ	 	 	 	 d<dZ	 	 	 	 d<dZ	 d	 	 	 	 	 	 	 	 	 d=dZn eb       	 	 d>d       Z eb       	 	 	 	 d?d       Z	 	 	 	 d@dZdAdZdAdZdAdZdAdZdAdZdAdZdd	 dBdZdBdZdBdZdBdZdBdZdBdZdBdZe	 	 dC	 	 	 	 	 dDd       Ze	 	 dC	 	 	 	 	 dEd       Z	 	 dC	 	 	 	 	 dFdÄZ	 	 dG	 	 	 dHdĄZddŜdIdƄZdJdǄZdddȜ	 	 	 dKdɄZdLdʄZ e ej                  e1<   dMd˄Zeej                  e*j                  <   dNd̄Zdd	 dOd̈́Zd'dPd΄ZdQdτZdPdЄZdRdфZ		 	 	 	 	 	 dSd҄Z
dTdӄZdTdԄZ	 	 d/	 	 	 	 	 	 	 	 	 dUdՄZ	 d	 	 	 dVdքZ	 d	 	 	 dWdׄZdd؄ZddلZevdddڄ       Zevddۄ       Zevdd܄       Zevdd݄       Zevddބ       Zevdd߄       Zevdd       Zevdd       Zevdd       Z ej6                  e      e1_         ej6                  e      e1_         ej6                  e      e1_        d Z ee      e1_        ddZd Z e
j@                  e!jB                  e.ejD                  ge#jF                        D ]  Z$eejJ                  e$<    d Z&d Z'd Z(	 dXdZ)d Z*dXdZ+ e	e+e      Z,d Z-dtdsddZ.d Z/d Z0d Z1	 	 dYdZ2 e	e2eG      Z3d Z4d Z5	 	 	 	 	 	 	 	 dZdZ6dd	 	 	 	 	 d[dZ7d Z8ejr                  hZ:ejv                  hZ<ejz                  ej|                  hZ?ej                  hZAej                  hZCej                  hZEeAe:z  e<z  ZFeAe:z  e<z  eCz  ZGeAeCz  ZHeAe:z  eCz  ZI e,eFd      ZJ e9j                  eJd         e;j                  eJ e	e7eOj                                e,eFd      ZM e9j                  eM       d ZO e;j                  eMeO        e3e:e:gd      ZP e;j                  eP e	e7eNj                                e,e:d      ZR e9j                  eR        e;j                  eR e	e7eOj                                e,e:d      ZS e9j                  eS        e;j                  eS e	e7eOj
                                e,e:d       ZT e9j                  eT       d ZU e;j                  eTeU        e+ e&ej                        e:d      ZV e9j                  eV        e;j                  eV e	e7eOj                                e,e:e<z  d      ZW e9j                  eWd         e;j                  eW e	e7eOj                               e8ej                  eW<    e,e:e<z  d      Z[ e9j                  e[d        d Z\ e;j                  e[e\       e8ej                  e[<    e,e:e<z  d      Z] e9j                  e]d	         e;j                  e] e	e7eOj"                               e8ej                  e]<    e,e:e<z  d
      Z_ e9j                  e_d         e;j                  e_ e	e7eOj                               e8ej                  e_<    e,e:e<z  d      Za e9j                  ead         e;j                  ea e	e7eOj                               e8ej                  ea<    e,e:e<z  d      Zc e9j                  ecd         e;j                  ec e	e7eOj&                               e8ej                  ec<    e,e:e<z  d      Zd e9j                  edd        d Ze e;j                  ed e;j                  eeds             e8ej                  ed<   d Zgd Zhd Zi e,e:e<z  d      Zj e9j                  ejd        eie9j                  ej<    e;j                  ejeh       e8ej                  ej<   d Zld Zm e,e:e<z  d      Zn e9j                  end         e;j                  enem       e8ej                  en<    e,e:e<z  d      Zo e9j                  eod         e;j                  eo e	e7eOj$                               e8ej                  eo<    e,e:e<z  d      Zp e9j                  epd          e;j                  ep e	e7eNj&                                e,e:e<z  d!      Zq e9j                  eqd"         e;j                  eq e	e7eNj(                               d# Zr e,e:e<z  d$      Zs e9j                  esd%         e;j                  es e	e7eNj*                                e3e:e<z  e:e<z  gd&      Zt e9j                  etd' d(         e;j                  et e	e7eOj.                                e,e:e<z  d)      Zu e9j                  eud*         e;j                  eu e	e7eNj,                                e,e:e<z  d+      Zv e9j                  evd,         e;j                  ev e	e7eNj.                                e,e:e<z  d-      Zw e9j                  ewd.         e;j                  ew e	e7eNj0                                e,e:e<z  d/      Zx e9j                  exd0         e;j                  ex e	e7eNj2                                e,e:e<z  d1      Zy e9j                  eyd2         e;j                  ey e	e7eNj4                                e+e'e<d3      Zz e9j                  ezd4         e;j                  ez e	e7eOj0                                e+e'e<d5      Z{ e9j                  e{d6         e;j                  e{ e	e7eOj2                               d7 Z|d8 Z} e2e}e?e?gd9      Z~ e9j                  e~e|        e;j                  e~ e	e7eOj4                                e+e}e?e<z  d:      Zd; Z e;j                  e e;j                  eds             d< Z e	e9j                  e      e9j                  e<   ee9j                  e<    e+e'eEe:z  e<z  d=ds>      Z e;j                  e e	e7eOj8                               d? Z e9j                  ee       d@ ZdA Z e,e:e<z  dB      Z e9j                  edC         e;j                  e e	e7eOj>                               e8ej                  e<    e,e:e<z  dD      Z e9j                  edE         e;j                  e e	e7eOj@                               e8ej                  e<    e,e:dF      Z e9j                  edG         e;j                  e e	e7eOjB                               e8ej                  e<    e,eAe:z  e<z  dH      ZdI Z e9j                  edJ         e;j                  ee       dK Z e2ee:e<z  eAe:z  e<z  gdLdsM      ZdN ZdO Z e9j                  eee       dP Z e;j                  ee       dQ ZdR Z eJ e-d      edS e-du       e-dT      U      Z e:j(                  e        e9j                  ee       dV ZdW Z e;j                  ee       dX Z e,eHdY      Z e9j                  e        e;j                  e e	e7eOj2                                e3eHeHgdZ      Z e9j                  e        e;j                  e e	e7eOj6                                e3eHeHgd[      Z e9j                  e        e;j                  e e	e7eOj:                                e3eHeHgd\      Z e9j                  e        e;j                  e e	e7eOj>                                e,eAd]      Z e;j                  e e	e7eOjB                                e,eAd^      Z e;j                  e e	e7eOjF                               d_ Zd` Zda Z e2eGeFeFgdbec      Zddeːde<   ee9j                  e<   ee9j                  e<    e;j                  e e	e7eOjP                               df Zdg Z e3eFeFgdh      Zee9j                  e<   ee9j                  e<    e;j                  e e	e7eOjV                               di Z e3eFeFgdjec      Z e9j                  edk dl         e9j\                  edm dn         e;j                  e e	e7eOj^                               do Z e3eFeFgdp      Z e9j                  edq dr        ee9j                  e<    e;j                  e e	e7eOjd                                e3eAe:z  eAe:z  gds      Z e9j                  edt du         e;j                  e e	e7eOjh                               dv Z e3eGeGgdy      Zdweːdx<    e9j                  edy dz         e;j                  e e	e7e;jn                                e3eGeGgdx      Zdweːd{<    e9j                  ed| d}         e;j                  e e	e7e;jr                                e3eAeAgd~      Z e9j                  e        e;j                  e e	e7eOjZ                                e3eAeAgd      Z e9j                  e        e;j                  e e	e7eOj\                                e3eAeAgd      Z e9j                  e        e;j                  e e	e7eOj^                               d Z e	edeOj|                  e      Z e	edeOj                  e      Zd\dZd]dZ e2 e&ej                        eGeGgddt      Z e9j                  eī        e;j                  e e	eÐdds              e2 e&ej                        eGeGgddt      Z e9j                  eū        e;j                  e e	eÐdds              e2 e&ej                        eIeIgd      Z e9j                  eƫ        e;j                  e e	eÐdds              e2 e&ej                        eIeIgd      Z e9j                  eǫ        e;j                  e e	eÐdds              e2 e&ej                        eIeIgd      Z e9j                  eȫ        e;j                  e e	eÐdds              e2 e&ej                        eIeIgd      Z e9j                  eɫ        e;j                  e e	eÐdds              e2 e&ej                        eGeGgd      Z e9j                  eʫ        e;j                  e e	eÐddt              e2 e&ej                        eIeIgd      Z e9j                  e˫        e;j                  e e	eÐddt              e2 e&ej                        eIeIgd      Z e9j                  e̫        e;j                  e e	eÐddt             d Z͐d Zΐd Zϐd ZАd Zѐd ZҐd ZӐd Ze#j                  ej                  he!jB                  e#jF                  Zאd Zؐd Zِd Z eJe͐eѐdeҐe e	ej                  d      eϐeА      Zܐd Zݐeܐj                  eݫ       eܐj                   e	e j                  eܫ              e9j                  eܐeԫ       ee9j                  e<   d Zee:j                  e<   d e:j                  e<   ee=j                  e<   ee=j                  e<   eej                  e<   d Zd Z e;j                  eܐe       d Z e0d      Zej                   e	e j                  e             ej                  e        e9j                  ed        d e9j                  e<    e:j(                  e        e;j                  ed        d Z e0d      Zej                   e	e j                  e             ej                  e        e9j                  ed        d e9j                  e<    e:j(                  e        e;j                  ed        d Zd Zd Z eJeede(e e	ej                  d            Z e9j                  e        e:j(                  e       d Z e;j                  ee       d Z	 	 d^dZd Zd Z	 	 d^dZd Zd Zd Zd Zdd	 	 	 d_dZd ZdÄ ZdsdĜ	 d^dńZ	 	 d^dƄZ	 	 d^dǄZdȄ Zd`dɄZ  eJeedʐe e	ej                  dʫ      ee˫      Zd̄ Zd̈́ Z e9j\                  eee        ej                  eeeeث      Zee:j                  e<   d΄ e:j                  e<   e ej                  e<   dadτZdbdЄZdbdфZ	 	 	 	 dcd҄Z	 d	 	 	 	 	 	 	 	 	 dddӄZ	dedԄZ
dՄ Zdd֜	 	 	 dfdׄZ e;j                  ee       dD ]'  Z e;j                  e e	ee֫      e֫       )  G dل dej                        Z	 	 	 	 	 	 dgdۄZ	 	 	 	 	 	 dhd܄Z	 	 	 	 	 	 did݄Zdބ Z	 	 d^d߄Z	 	 	 	 	 	 	 	 	 	 	 	 djdZd Z	 	 	 	 dkdZd Zd Zd Z	 	 d^dZ eJeed e	ej                  d            Zee9j                  e<   ee9j                  e<   ee:j                  e<   d e:j                  e<   	 	 	 d/	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d2dZddd	 	 	 	 	 dldZ e;j                  e e;j                  eds             dD ]'  Z e;j                  e e	ee֫      e֫       ) d Zd Zd Z d Z!d Z"d Z#d Z$d Z%d Z&	 	 dmdZ'd Z( ej`                  d      Z)e)j                  e(       e)j                   e	e j                  e)             e%e9j                  e)<   e!e9j                  e)<   e"e:j                  e)<   d e:j                  e)<   e#e=j                  e)<   e&e=jT                  e)<   e$e=jV                  e)<   e ejX                  e)<    e;j                  e)e'       d Z-d Z. e	e.eGeGeGeGgd      Z/d Z0 eJe-e/de. e	ej                  d      U      Z1 e9j                  e1d  d d        e0e:jd                  e1<    e;j                  e1 e	e7eOjr                               d Z3d Z4d Z5d Z6d Z7d Z8d	 Z9 eJe3e6d
e4 e	ej                  d
      e5      Z: e9j                  e:e7       e7e9j                  e:<   e8e:jd                  e:<   d Z; e;j                  e:e;       d Z<d Z=d Z>d Z?d Z@d ZAd ZBd ZC ej`                  d      ZDdteD_        eDj                   e	eIeDe<e=e>eBeC             eDj                   e	e j                  eD              e9j                  eDe?       e@e:jd                  eD<    e;j                  eDeA       d ZEd ZFd ZGd ZHd ZI eJeFeEdeG e	ej                  d      U      ZJ e9j                  eJeH       eIe:jd                  eJ<   d ZK e;j                  eJeK       d ZLd ZMd ZNd  ZOd! ZPd" ZQd# ZR eJeMeLd$eN e	ej                  d$      eO      ZS e9j                  eSeQ       eRe:jd                  eS<   d% ZT e;j                  eSeT       dnd&ZUd' ZVd( ZWd) ZXd* ZYd+ ZZd, Z[d- Z\d. Z]d/ Z^d0 Z_d1 Z`d2 Zad3 Zbd4 Zc eJeVe_d5eY e	ej                  d5      U      Zd e9j                  ede`       eae:j                  ed<   d6 e:j                  ed<    e;j                  edeb       e^ejX                  ed<   ece=jV                  ed<   d7 Zed8 Zfd9 Zg eJeeeGd:ef e	ej                  d:      U      Zh e9j                  ehd;        ege:jd                  eh<   d< Zi e;j                  ehei       d= Zjd> Zkd? Zld@ ZmdA ZndB Zo eJejeGdCek e	ej                  dC      elem˫      Zp e9j                  epdD        ene:jd                  ep<    e;j                  epeo       dE ZqdF ZrdG ZsdH ZtdI ZudJ ZvdK ZwdL ZxdM Zy eJeqesdNeter e	ej                  dN            Zzewe9j                  ez<   eue9j                  ez<   eve:j                  ez<   dO e:j                  ez<    e;j                  ezey       dP Z{dQ Z|dR Z}dS Z~dT ZdU ZdV ZdW Z ej`                  dX      Zdte_        ej                   e	e j                  e             ej                   e	eIee{e~ee|e}             ee:jd                  e<   ee9j                  e<   	 	 dodYZ e;j                  ee       dZ Zd[ Zd\ Zd] Zdd^d_Zd` Zda Zdb Z eJe e	edc      dce e	ej                  dc      ee˫      Z e9j                  ee        e:j                  ee       dd Zde Z eJe e	edf      dfe e	ej                  df      U      Zee9j                  e<    e:j                  ee       dg Z eJeeGdhe e	ej                  dh      U      Z e9j                  ee        e:j                  ee        eJeeGdie e	ej                  di      U      Z e9j                  ee        e:j                  ee       dj Zdk Zdl Z G dm dn      Zdo Z eJeedpe(e e	ej                  dp            Z e:j                  ee        e9j                  e        eJeedqe(e e	ej                  dq            Z e:j                  ee        e9j                  e        e;j                  e e;j                   e	eee      ds      dsr        e;j                  e e;j                   e	eee      ds      dsr       ds Zdt Zdu Z eJeeGdve(e e	ej                  dv            Z e:j                  ee       ee9j                  e<    eJeeGdwe(e e	ej                  dw            Z e:j                  ee        eJeeGdxe(e e	ej                  dx            Z e:j                  ee       dy Z e;j                  e e	eeOjF                  e              e;j                  e e	eeOjH                  e              e;j                  e e	eeOj                  e              e;j                  e e	eeOj|                  e              e;j                  e e	eeOjJ                  e              e;j                  e e	ee;jr                  e              e;j                  e e	ee;jn                  e             dz Zd{ Z eJe e	e)ee:d|      d|e e	ej                  d|      }      Z e9jR                  ed~         e:j(                  e       d Z e;j                  ee        ejV                  ejX                         ejV                  ejZ                         ejV                  ej\                        dZ ejV                  ej`                         ejV                  ejb                         ejV                  ejd                        dZd Zd ZdddZdddZdddZd Zd Z e0d      Zdte_        ej                   e	e j                  e             ej                  e       ee9j                  e<   ee:jd                  e<   d Z e;j                  ee       d Zd Zd Z e0d      Zdte_        ej                   e	e j                  e             ej                  e       d Z e;j                  ee       ee9j                  e<   ee:jd                  e<   d Zd ZÐee9j                  ej                  <   ee:jd                  ej                  <   ddZ e0d      ZƐeƐj                   e	e j                  eƫ             eƐj                  d        d Z e;j                  eƐeǫ       d ZȐd Z e0d      Zʐeʐj                   e	e j                  eʫ             eʐj                  eɫ       d Z e;j                  eʐe˫       d Z̐d Z e0d      Zΐeΐj                   e	e j                  eΫ             eΐj                  eͫ       d Z e;j                  eΐeϫ       d ZАd Zѐd ZҐd ZӐd Z G d dej                        ZՐd eՐ_        dpdZאd Z e0d      Zdte_        eِj                   e	e j                  e٫             eِj                   e	eIeِeАeӐeԐeѐeҫ              e;j                  eِeث       dqdZڐdrdZېd Zܐd Zݐd Z ej`                  d      Zߐeߐj                   e	eސe߫             eߐj                  d         e;j                  eߐd         e9jR                  eߐd         e:j(                  e߫       d Z G d de"j                        Z e       Ze"j                  j                  e       e"j                  j                  e        ej`                  d      Zej                  d        dte_        ej                  d         e;j                  ed         e9jR                  ed        d e:jd                  e<   ejZ                  eՐj                  fdddZd Z e0d      Zej                   e	e j                  e             ej                  e       d Zee=jV                  e<   d ZeejX                  e<   d Z e;j                  ee       ej                  Zd Zd Z G dÄ dej                        Zdń Zi d=dƓd!dǓd/dȓdbdbddɓd-dʓd$d˓d&d̓d1d͓dΐdΓdϐdϓdАdГdѐdѓdFdFddd
d
ddi d+d+dpdғddӓddd
d
dddԐdԓdՐdՓd֐d֓dאdדdddؐdؓdِdٓdڐdړdېdۓdddydܓi dxdݓdjdޓddߓdddddLdd d dd/d~dddddddddd)d)dBdBdhdddddiZdsdZdtdZd Z e	ed       Zd{eːd<   d Z e	ed      Zd{eːd<   d Zd Z e	ed      Zd{eːd<    e	edd      Z d{eːd<   e!jV                  Zd{ed<   e!jV                  Zd{eːd<   ddZdudZd Zd ZdvdZd Zd ZdddZ	 ej`                  d      Z
e
j                   e	e j                  e
             d Ze
j                  e       d Z e;j                  e
ed         e;j                  e
ed       d Z e;j                  e
e       d Zee:j                  e
<   d Z ej`                  d      Z e j"                  e       d Zej                  e       d Z e;j                  ee        ej`                  d      Zej                  d	        ej                  d
         e;j                  ed        d e9j                  e<   d e9j                  e<    e:j(                  e       d Zd Zd Z ej`                  d      Zdte_        ej                   e	e j                  e             ej                  e        e;j                  ee       d Zee:jd                  e<   d Zee9j                  e<   d Zee9j                  e<   y(w      )annotationsN)CallableSequence)partial)Any
NamedTupleTypeVarUnioncastoverload)ad_util)api)api_util)array)config)core)deprecations)dispatch)dtypes)effects)literals)linear_util)pjit)pretty_printer)source_info_util)state)	tree_util)util)array_types)	PrimitiveShapedArrayabstract_tokencanonicalize_shape)UnexpectedTracerError)HashableArray)ad)batching)mlir)partial_eval)pxla)slicing)utils)get_abstract_meshget_concrete_mesh)input_dtypedtype_to_string#standard_multi_result_abstract_evalstandard_primitive)ir)chlo)hlo)Sharding)PmapShardingNamedShardingPartitionSpeccanonicalize_shardingflatten_spec)Array	ArrayLikeDimSizeDuckTypedArrayDType	DTypeLikeShape)cachecanonicalize_axissafe_mapsafe_zip
split_listweakref_lru_cacheforeachtuple_insertTzjax.laxc                    | j                   dk\  sJ t        | g t        | j                   dz
        | j                   dz
  | j                   dz
        S )N      )ndim	transposerangexs    K/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/lax/lax.py_matrix_transposerU   W   sL    	
1	1Baffqj)B166A:BqvvzB	CC    wherec                    t        j                  |      }t        j                  | |      } t        j                  |j
                  t        j                  | |j                              S N)npiinfor   concrete_dim_or_errormax_dimminmin_dimmax)valdtyperW   infos       rT   _clip_int_to_valid_rangerd   [   sE    	%$""3.#	dhhS$(( ;	<<rV   c                ,    dd}| sJ t        ||        y )Nc                `    t        |       }t        d |D              sd| d}t        |      y )Nc              3  &   K   | ]	  }|d k\    ywr   N ).0idxs     rT   	<genexpr>z@_validate_shapes.<locals>._check_static_shape.<locals>.<genexpr>c   s     +Csax+   zUOnly non-negative indices are allowed when broadcasting static shapes, but got shape .)r#   all	TypeError)shapecheckedmsgs      rT   _check_static_shapez-_validate_shapes.<locals>._check_static_shapea   s<     'G+7++--2IQ8ccN ,rV   )rq   rB   )rI   )shapesrt   s     rT   _validate_shapesrv   `   s     
-	
v&rV   c                v   |st        |  d      |D ch c]  }t        |       }}t        |      dk7  rt        |  d|       g }t        | D ]  t        fddd D              r|j	                  d          /D cg c]  }t        j                  |d      r| c}s|j	                  d       jt        fddd D              r|j	                  d          t        |  dd	j                  t        t        t        t        |                   d
       t        |      S c c}w c c}w )zM
  Attempt to broadcast shapes, raising a TypeError if broadcasting fails.
  z!: At least one shape is required.rN   z6: arrays must have the same number of dimensions, got c              3  P   K   | ]  }t        j                  |d            ywrh   )r   same_referent)rj   ddss     rT   rl   z(_try_broadcast_shapes.<locals>.<genexpr>w   s"     
8A4aA'
8   #&Nr   c              3  P   K   | ]  }t        j                  d    |        ywrh   r   definitely_equal)rj   rz   non_1ss     rT   rl   z(_try_broadcast_shapes.<locals>.<genexpr>   s"     Gqt$$VAY2Gr|   z+ got incompatible shapes for broadcasting: , rn   )rp   lenzipro   appendr   r   joinmapstrtuple)nameru   rq   ranksresult_shaperz   r{   r   s         @@rT   _try_broadcast_shapesr   k   sH    

tf=>
??#)
*%3u:
*%
*Z1_
tf !7$ % %,L Gb

8AB
88"Q%  AaT%:%:1a%@AfAGF12JGGF1I&4& K99Sc%.@%ABC1F G 	GG 
|	' + Bs   D1D6"D6c                   t        | t              r| S t        | t        t        j                  t        j
                  f      rt        | d      S t        | t        j                        rt        | | j                        S t        | t        t        t        j                  f      r t        t        j                  |       d      S t!        d|  dt#        |        d      )z:Lightweight conversion of ArrayLike input to Array output.F	weak_typeTz!asarray: expected ArrayLike, got z	 of type rn   )
isinstancer<   boolrZ   ndarraygeneric_convert_element_typer   TypedNdArrayr   intfloatbuiltinscomplexr   coerce_to_arrayrp   typerR   s    rT   asarrayr      s    5H!dBJJ

34 e44!X**+ akk::!c5("2"234 !7!7!:dKK
7s)DG9AN
OOrV   c                      y rY   ri   ru   s    rT   broadcast_shapesr      s    CFrV   c                      y rY   ri   r   s    rT   r   r      s    9<rV   c                 2    	 t        |  S #  t        |  cY S xY w)a  Returns the shape that results from NumPy broadcasting of `shapes`.

  This follows the rules of `NumPy broadcasting`_.

  Args:
    shapes: one or more tuples of integers containing the shapes of arrays
      to be broadcast.

  Returns:
    A tuple of integers representing the broadcasted shape.

  Raises:
    ValueError: if shapes are not broadcast-compatible.

  See Also:
    - :func:`jax.numpy.broadcast_shapes`: similar API in the JAX NumPy namespace

  Examples:
    Some examples of broadcasting compatible shapes:

    >>> jnp.broadcast_shapes((1,), (4,))
    (4,)
    >>> jnp.broadcast_shapes((3, 1), (4,))
    (3, 4)
    >>> jnp.broadcast_shapes((3, 1), (1, 4), (5, 1, 1))
    (5, 3, 4)

    Error when attempting to broadcast incompatible shapes:

    >>> jnp.broadcast_shapes((3, 1), (4, 1))  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ValueError: Incompatible shapes for broadcasting: shapes=[(3, 1), (4, 1)]

  .. _NumPy broadcasting: https://numpy.org/doc/stable/user/basics.broadcasting.html
  )_broadcast_shapes_cached_broadcast_shapes_uncachedr   s    rT   r   r      s%    L/#V,,/%v..s   
 
c                     t        |  S rY   )r   r   s    rT   r   r      s    	#V	,,rV   c                 .   t        |        | ^}}|s|S t        | t              t              dk(  st        fd| D              rS t	        fd| D              }	 t        |ddiS # t        $ r}t        dt        |              |d }~ww xY w)Nkeyr   c              3  h   K   | ])  }t        j                  t        |      z
  d  |       + y wrY   )r   definitely_equal_shaper   )rj   srO   r   s     rT   rl   z-_broadcast_shapes_uncached.<locals>.<genexpr>   s/     cWXd11,tc!f}~2NPQRc   /2c              3  J   K   | ]  }g d t        |      z
  z  |  yw)rN   Nr   )rj   rq   rO   s     rT   rl   z-_broadcast_shapes_uncached.<locals>.<genexpr>   s*     [5F$$U*;"<FF[    #r   r   z-Incompatible shapes for broadcasting: shapes=)	rv   _maxr   ro   r   r   rp   
ValueErrorlist)ru   fstrstrank_promoted_shapeserrrO   r   s        @@rT   r   r      s    6)#	Sj f#&,	\	$	QY#c\bcc [TZ[[^ "6P=OPP	 ^
DT&\NS
TZ]]^s   #
A. .	B7BBc            	        | ^}}|s|j                   S t        | d       j                  dk(  st        fd| D              rj                   S g }| D ]  }t	        d|j                  z
  z  |j                   j
                  z    }d|j                  z
  z  |j                  z   }|j                  |j                  ||j                   j                  |                    t        d	g| S )
Nc                    | j                   S rY   rO   as    rT   <lambda>z%broadcast_shardings.<locals>.<lambda>   s
    qvv rV   r   r   c              3     K   | ]A  }j                   j                  |j                  z
  d  |j                   j                  k(   C y wrY   )shardingspecrO   )rj   r   rO   res_avals     rT   rl   z&broadcast_shardings.<locals>.<genexpr>   s@      PDEhTAFF]^,

?Ps   AA
rY   r   r   rq   r   broadcast_shardings)
r   r   rO   ro   Pr   rq   r   updatebroadcasting_sharding_rule)	avalsr   r   	aval_listr   new_spec	new_shaperO   r   s	          @@rT   r   r      s    )#	<< %-.(	$	QY# PINP P ) Ja'TAFF]+ajjoo=>Hqvv&0IQXXI'(zz'8'8h'8'G  I JJ
 
$$9	FI	FFrV   c                    | S rY   ri   )rS   _s     rT   	_identityr      s    axrV   c                ,    t         j                  |       S )a  Elementwise negation: :math:`-x`.

  This function lowers directly to the `stablehlo.negate`_ operation.

  Args:
    x: input array

  Returns:
    Array of same shape and dtype as ``x``, containing the element-wise negative.

  Notes:
    For unsigned integer inputs, this function returns ``2 ** nbits - x``, where
    ``nbits`` is the number of bits in the integer representation.

  .. _stablehlo.negate: https://openxla.org/stablehlo/spec#negate
  )neg_pbindrR   s    rT   negr          $ 
ArV   c                ,    t         j                  |       S )a<  Elementwise sign.

  This function lowers directly to the `stablehlo.sign`_ operation.

  Args:
    x: input array

  Returns:
    Array of same shape and dtype as ``x``, containing the sign
    of the value, as defined in Notes below.

  Notes:
    For floating-point inputs, returns

    .. math::

       \mathrm{sign}(x) = \begin{cases}
         -1 & x < 0\\
         -0 & x = -0\\
         \mathit{NaN} & x = \mathit{NaN}\\
         +0 & x = +0\\
         1 & x > 0
      \end{cases}

    For signed integer inputs, returns

    .. math::

       \mathrm{sign}(x) = \begin{cases}
         -1 & x < 0\\
         0 & x = 0\\
         1 & x > 0
       \end{cases}

    For complex inputs, returns the complex phase, i.e.
    :math:`\mathrm{sign}(x) = x / |x|`.

  .. _stablehlo.sign: https://openxla.org/stablehlo/spec#sign
  )sign_pr   rR   s    rT   signr   
  s    R 
QrV   c                `    t        j                  | |      \  } }t        j                  | |      S )a;  Returns the next representable value after ``x1`` in the direction of ``x2``.

  This function lowers directly to the ``chlo.next_after`` operation.

  Args:
    x1, x2: input arrays. Must have a matching floating-point dtypes. If neither is
      a scalar, must have the same number of dimensions and be broadcast-compatible.

  Returns:
    Array of the same dtype and broadcasted shape of the inputs, containing the
    next representable floating-point value after ``x1`` in the direction of
    ``x2``.

  Notes:
    In some environments flush-denormal-to-zero semantics is used.
    This means that, around zero, this function returns strictly non-zero
    values which appear as zero in any operations. Consider this example::

      >>> from jax import lax
      >>> lax.nextafter(0.0, 1.0)  # denormal numbers are representable
      Array(1.e-45, dtype=float32, weak_type=True)
      >>> lax.nextafter(0.0, 1.0) * 1  # but are flushed to zero
      Array(0., dtype=float32, weak_type=True)

    For the smallest usable (i.e. normal) float, use ``tiny`` of ``jnp.finfo``.
  )r   standard_insert_pvarynextafter_pr   x1x2s     rT   	nextafterr   5  s-    8 %%b"-&"b			"b	!!rV   c                ,    t         j                  |       S )a  Elementwise floor: :math:`\left\lfloor x \right\rfloor`.

  This function lowers directly to the `stablehlo.floor`_ operation.

  Args:
    x: input array. Must have floating-point type.

  Returns:
    Array of same shape and dtype as ``x``, containing values rounded
    to the next integer toward negative infinity.

  See also:
    - :func:`jax.lax.ceil`: round to the next integer toward positive infinity
    - :func:`jax.lax.round`: round to the nearest integer

  .. _stablehlo.floor: https://openxla.org/stablehlo/spec#floor
  )floor_pr   rR   s    rT   floorr   T  s    & 
arV   c                ,    t         j                  |       S )a  Elementwise ceiling: :math:`\left\lceil x \right\rceil`.

  This function lowers directly to the `stablehlo.ceil`_ operation.

  Args:
    x: input array. Must have floating-point type.

  Returns:
    Array of same shape and dtype as ``x``, containing values rounded
    to the next integer toward positive infinity.

  See also:
    - :func:`jax.lax.floor`: round to the next integer toward negative infinity
    - :func:`jax.lax.round`: round to the nearest integer

  .. _stablehlo.ceil: https://openxla.org/stablehlo/spec#ceil
  )ceil_pr   rR   s    rT   ceilr   i      & 
QrV   c                      e Zd ZdZdZ	 dZy)RoundingMethodzZRounding strategies for handling halfway values (e.g., 0.5) in
  :func:`jax.lax.round`.
  r   rN   N)__name__
__module____qualname____doc__AWAY_FROM_ZEROTO_NEAREST_EVENri   rV   rT   r   r   ~  s     .J/rV   r   c                F    t        |      }t        j                  | |      S )aY  Elementwise round.

  Rounds values to the nearest integer. This function lowers directly to the
  `stablehlo.round`_ operation.

  Args:
    x: an array or scalar value to round. Must have floating-point type.
    rounding_method: the method to use when rounding halfway values
      (e.g., ``0.5``). See :class:`jax.lax.RoundingMethod` for possible values.

  Returns:
    An array of the same shape and dtype as ``x``, containing the elementwise
    rounding of ``x``.

  See also:
    - :func:`jax.lax.floor`: round to the next integer toward negative infinity
    - :func:`jax.lax.ceil`: round to the next integer toward positive infinity

  Examples:
    >>> import jax.numpy as jnp
    >>> from jax import lax
    >>> x = jnp.array([-1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5])
    >>> jax.lax.round(x)  # defaults method is AWAY_FROM_ZERO
    Array([-2., -1., -1.,  0.,  1.,  1.,  2.], dtype=float32)
    >>> jax.lax.round(x, rounding_method=jax.lax.RoundingMethod.TO_NEAREST_EVEN)
    Array([-2., -1., -0.,  0.,  0.,  1.,  2.], dtype=float32)

  .. _stablehlo.round: https://openxla.org/stablehlo/spec#round
  )rounding_method)r   round_pr   )rS   r   s     rT   roundr     s"    B #?3/	a	99rV   c                ,    t         j                  |       S )a9  Elementwise :math:`\mathrm{isfinite}`.

  This function lowers directly to the  `stablehlo.is_finite`_ operation.

  Args:
    x: input array. Must have floating-point type.

  Returns:
    Array of boolean dtype with the same shape as ``x``, containing ``False`` where
    ``x`` is :math:`\pm\infty` or :math:`\mathit{NaN}`, and ``True`` otherwise.

  See also:
    - :func:`jax.numpy.isinf`: return True where array is infinite.
    - :func:`jax.numpy.isnan`: return True where array is NaN.

  .. _stablehlo.is_finite: https://openxla.org/stablehlo/spec#is_finite
  )is_finite_pr   rR   s    rT   	is_finiter     s    & 
		!	rV   c                      e Zd ZdZdddZy)	TolerancezSpecify the tolerances used for computing unary functions.

  Maximum two tolerances can be specified: (atol and rtol) or (atol and ulps).
  c                    |dk  s
|dk  s|dk  rt        d      |dk(  r|dk(  r|dk(  rt        d      || _        || _        || _        y )N        z Tolerances must be non-negative.r   z0At least one of atol, rtol, or ulps must be set.)r   atolrtolulps)selfr   r   r   s       rT   __init__zTolerance.__init__  sU    czTCZ4#:9::s{ts{tqyIJJDIDIDIrV   N)r   r   r   )r   r   r   r   r   r   )r   r   r   r   r   ri   rV   rT   r   r     s    
rV   r   c                      e Zd ZdZdZy)AccuracyModerN   rM   N)r   r   r   HIGHESTDEFAULTri   rV   rT   r   r     s    ''rV   r   c                0    t         j                  | |      S )a  Elementwise exponential: :math:`e^x`.

  This function lowers directly to the  `stablehlo.exponential`_ operation.

  Args:
    x: input array. Must have floating-point or complex type.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    exponential.

  See also:
    - :func:`jax.lax.exp2`: elementwise base-2 exponentional: :math:`2^x`.
    - :func:`jax.lax.log`: elementwise natural logarithm: :math:`\mathrm{log}(x)`.

  .. _stablehlo.exponential: https://openxla.org/stablehlo/spec#exponential
  accuracy)exp_pr   rS   r  s     rT   expr    s    2 
A	))rV   c                0    t         j                  | |      S )a  Elementwise base-2 exponential: :math:`2^x`.

  This function is implemented in terms of the `stablehlo.exponential`_
  and `stablehlo.multiply`_ operations.

  Args:
    x: input array. Must have floating-point or complex type.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    base-2 exponential.

  See also:
    - :func:`jax.lax.exp`: elementwise exponentional: :math:`e^x`.
    - :func:`jax.lax.log`: elementwise natural logarithm: :math:`\mathrm{log}(x)`.

  .. _stablehlo.exponential: https://openxla.org/stablehlo/spec#exponential
  .. _stablehlo.multiply: https://openxla.org/stablehlo/spec#multiply
  r  )exp2_pr   r  s     rT   exp2r        4 
Q	**rV   c                0    t         j                  | |      S )a  Elementwise :math:`e^{x} - 1`.

  This function lowers directly to the `stablehlo.exponential_minus_one`_
  operation. Compared to the naive expression ``lax.exp(x) - 1``, it is
  more accurate for ``x`` near zero.

  Args:
    x: input array. Must have floating-point or complex type.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    exponential minus 1.

  See also:
    - :func:`jax.lax.exp`: elementwise exponentional: :math:`e^x`.
    - :func:`jax.lax.log1p`: elementwise :math:`\mathrm{log}(1 + x)`.

  .. _stablehlo.exponential_minus_one: https://openxla.org/stablehlo/spec#exponential_minus_one
  r  )expm1_pr   r  s     rT   expm1r        6 
a(	++rV   c                0    t         j                  | |      S )aB  Elementwise natural logarithm: :math:`\mathrm{log}(x)`.

  This function lowers directly to the  `stablehlo.log`_ operation.

  Args:
    x: input array. Must have floating-point or complex type.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    natural logarithm.

  See also:
    - :func:`jax.lax.exp`: elementwise exponentional: :math:`e^x`.

  .. _stablehlo.log: https://openxla.org/stablehlo/spec#log
  r  )log_pr   r  s     rT   logr  .  s    0 
A	))rV   c                0    t         j                  | |      S )a  Elementwise :math:`\mathrm{log}(1 + x)`.

  This function lowers directly to the  `stablehlo.log_plus_one`_ operation.
  Compared to the naive expression ``lax.log(1 + x)``, it is more accurate
  for ``x`` near zero.

  Args:
    x: input array. Must have floating-point or complex type.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    natural logarithm of ``x + 1``.

  See also:
    - :func:`jax.lax.expm1`: elementwise :math:`e^x - 1`.
    - :func:`jax.lax.log`: elementwise natural logarithm :math:`\mathrm{log}(x)`.

  .. _stablehlo.log_plus_one: https://openxla.org/stablehlo/spec#log_plus_one
  r  )log1p_pr   r  s     rT   log1pr  H  r  rV   c                0    t         j                  | |      S )a  Elementwise hyperbolic tangent: :math:`\mathrm{tanh}(x)`.

  This function lowers directly to the `stablehlo.tanh`_ operation.

  Args:
    x: input array. Must have floating-point or complex type.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    hyperbolic tangent.

  See also:
    - :func:`jax.lax.atanh`: elementwise inverse hyperbolic tangent.
    - :func:`jax.lax.cosh`: elementwise hyperbolic cosine.
    - :func:`jax.lax.sinh`: elementwise hyperbolic sine.

  .. _stablehlo.tanh: https://openxla.org/stablehlo/spec#tanh
  r  )tanh_pr   r  s     rT   tanhr  e  r	  rV   c                0    t         j                  | |      S )a  Elementwise logistic (sigmoid) function: :math:`\frac{1}{1 + e^{-x}}`.

  There is no HLO logistic/sigmoid primitive, so this lowers to a sequence
  of HLO arithmetic operations.

  Args:
    x: input array. Must have floating point or complex dtype.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    logistic/sigmoid function.

  See also:
    - :func:`jax.nn.sigmoid`: an alternative API for this functionality.
  r  )
logistic_pr   r  s     rT   logisticr    s    $ 
X	..rV   c                0    t         j                  | |      S )a  Elementwise sine: :math:`\mathrm{sin}(x)`.

  For floating-point inputs, this function lowers directly to the
  `stablehlo.sine`_ operation. For complex inputs, it lowers to a
  sequence of HLO operations implementing the complex sine.

  Args:
    x: input array. Must have floating-point or complex type.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    sine.

  See also:
    - :func:`jax.lax.cos`: elementwise cosine.
    - :func:`jax.lax.tan`: elementwise tangent.
    - :func:`jax.lax.asin`: elementwise arc sine.

  .. _stablehlo.sine: https://openxla.org/stablehlo/spec#sine
  r  )sin_pr   r  s     rT   sinr        8 
A	))rV   c                0    t         j                  | |      S )a   Elementwise cosine: :math:`\mathrm{cos}(x)`.

  For floating-point inputs, this function lowers directly to the
  `stablehlo.cosine`_ operation. For complex inputs, it lowers to a
  sequence of HLO operations implementing the complex cosine.

  Args:
    x: input array. Must have floating-point or complex type.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    cosine.

  See also:
    - :func:`jax.lax.sin`: elementwise sine.
    - :func:`jax.lax.tan`: elementwise tangent.
    - :func:`jax.lax.acos`: elementwise arc cosine.

  .. _stablehlo.cosine: https://openxla.org/stablehlo/spec#cosine
  r  )cos_pr   r  s     rT   cosr     r  rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise two-term arc tangent: :math:`\mathrm{atan}({x \over y})`.

  This function lowers directly to the `stablehlo.atan2`_ operation.

  Args:
    x, y: input arrays. Must have a matching floating-point or complex dtypes. If
      neither is a scalar, the two arrays must have the same number of dimensions
      and be broadcast-compatible.

  Returns:
    Array of the same shape and dtype as ``x`` and ``y`` containing the element-wise
    arc tangent of :math:`x \over y`, respecting the quadrant indicated by the sign
    of each input.

  See also:
    - :func:`jax.lax.tan`: elementwise tangent.
    - :func:`jax.lax.atan`: elementwise one-term arc tangent.

  .. _stablehlo.atan2: https://openxla.org/stablehlo/spec#atan2
  )r   r   atan2_pr   rS   ys     rT   atan2r%    s+    , 
	#	#Aq	)$!Q	a	rV   c                ,    t         j                  |       S )am  Elementwise extract real part: :math:`\mathrm{Re}(x)`.

  This function lowers directly to the `stablehlo.real`_ operation.

  Args:
    x: input array. Must have complex dtype.

  Returns:
    Array of the same shape as ``x`` containing its real part. Will have dtype
    float32 if ``x.dtype == complex64``, or float64 if ``x.dtype == complex128``.

  See also:
    - :func:`jax.lax.complex`: elementwise construct complex number.
    - :func:`jax.lax.imag`: elementwise extract imaginary part.
    - :func:`jax.lax.conj`: elementwise complex conjugate.

  .. _stablehlo.real: https://openxla.org/stablehlo/spec#real
  )real_pr   rR   s    rT   realr(        ( 
QrV   c                ,    t         j                  |       S )ar  Elementwise extract imaginary part: :math:`\mathrm{Im}(x)`.

  This function lowers directly to the `stablehlo.imag`_ operation.

  Args:
    x: input array. Must have complex dtype.

  Returns:
    Array of the same shape as ``x`` containing its imaginary part. Will have dtype
    float32 if ``x.dtype == complex64``, or float64 if ``x.dtype == complex128``.

  See also:
    - :func:`jax.lax.complex`: elementwise construct complex number.
    - :func:`jax.lax.real`: elementwise extract real part.
    - :func:`jax.lax.conj`: elementwise complex conjugate.

  .. _stablehlo.imag: https://openxla.org/stablehlo/spec#imag
  )imag_pr   rR   s    rT   imagr,     r)  rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a#  Elementwise make complex number: :math:`x + jy`.

  This function lowers directly to the `stablehlo.complex`_ operation.

  Args:
    x, y: input arrays. Must have matching floating-point dtypes. If
      neither is a scalar, the two arrays must have the same number
      of dimensions and be broadcast-compatible.

  Returns:
    The complex array with the real part given by ``x``, and the imaginary
    part given by ``y``. For inputs of dtype float32 or float64, the result
    will have dtype complex64 or complex128 respectively.

  See also:
    - :func:`jax.lax.real`: elementwise extract real part.
    - :func:`jax.lax.imag`: elementwise extract imaginary part.
    - :func:`jax.lax.conj`: elementwise complex conjugate.

  .. _stablehlo.complex: https://openxla.org/stablehlo/spec#complex
  )r   r   	complex_pr   r#  s     rT   r   r     s+    . 
	#	#Aq	)$!Q	1	rV   c                B    t         j                  | t        |             S )a  Elementwise complex conjugate function: :math:`\overline{x}`.

  This function lowers to a combination of `stablehlo.real`_, `stablehlo.imag`_,
  and  `stablehlo.complex`_.

  Args:
    x: input array. Must have complex dtype.

  Returns:
    Array of the same shape and dtype as ``x`` containing its complex conjugate.

  See also:
    - :func:`jax.lax.complex`: elementwise construct complex number.
    - :func:`jax.lax.real`: elementwise extract real part.
    - :func:`jax.lax.imag`: elementwise extract imaginary part.
    - :func:`jax.lax.abs`: elementwise absolute value / complex magnitude.

  .. _stablehlo.real: https://openxla.org/stablehlo/spec#real
  .. _stablehlo.imag: https://openxla.org/stablehlo/spec#imag
  .. _stablehlo.complex: https://openxla.org/stablehlo/spec#complex
  )r/   )conj_pr   _dtyperR   s    rT   conjr2  0  s    0 
QF1I	..rV   c                ,    t         j                  |       S )a  Elementwise absolute value: :math:`|x|`.

  This function lowers directly to the `stablehlo.abs`_ operation.

  Args:
    x: Input array. Must have signed integer, floating, or complex dtype.

  Returns:
    An array of the same shape as ``x`` containing the elementwise absolute value.
    For complex valued input, :math:`a + ib`, ``abs(x)`` returns :math:`\sqrt{a^2+b^2}`.

  See also:
    - :func:`jax.numpy.abs`: a more flexible NumPy-style ``abs`` implementation.

  .. _stablehlo.abs: https://openxla.org/stablehlo/spec#abs
  )abs_pr   rR   s    rT   absr5  J  r   rV   c                `    t        j                  | |      \  } }t        j                  | |      S )al  Elementwise power: :math:`x^y`.

  This function lowers directly to the `stablehlo.pow`_ operation, along with
  a `stablehlo.convert`_ when the argument dtypes do not match.

  Args:
    x: Input array giving the base value. Must have floating or complex type.
    y: Input array giving the exponent value. Must have integer, floating, or
      complex type. Its dtype will be cast to that of ``x.dtype`` if necessary.
      If neither ``x`` nor ``y`` is a scalar, then ``x`` and ``y`` must have
      the same number of dimensions and be broadcast-compatible.

  Returns:
    An array of the same dtype as ``x`` containing the elementwise power.

  See also:
    :func:`jax.lax.integer_pow`: Elementwise power where ``y`` is a static integer.

  .. _stablehlo.convert: https://openxla.org/stablehlo/spec#convert
  .. _stablehlo.pow: https://openxla.org/stablehlo/spec#pow
  )r   r   pow_pr   r#  s     rT   powr8  ^  +    . 
	#	#Aq	)$!Q	Aq	rV   c                0    t         j                  | |      S )a   Elementwise power: :math:`x^y`, where :math:`y` is a static integer.

  This will lower to a sequence of :math:`O[\log_2(y)]` repetitions of
  `stablehlo.multiply`_.

  Args:
    x: Input array giving the base value. Must have numerical dtype.
    y: Static scalar integer giving the exponent.

  Returns:
    An array of the same shape and dtype as ``x`` containing the elementwise power.

  See also:
    :func:`jax.lax.pow`: Elementwise power where ``y`` is an array.

  .. _stablehlo.multiply: https://openxla.org/stablehlo/spec#multiply
  r$  )integer_pow_pr   r#  s     rT   integer_powr=  x  s    & 
		A		##rV   c                0    t         j                  | |      S )ax  Elementwise square root: :math:`\sqrt{x}`.

  This function lowers directly to the `stablehlo.sqrt`_ operation.

  Args:
    x: Input array. Must have floating or complex dtype.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    An array of the same shape and dtype as ``x`` containing the square root.

  See also:
    :func:`jax.lax.pow`: Elementwise power.
    :func:`jax.lax.cbrt`: Elementwise cube root.
    :func:`jax.lax.rsqrt`: Elementwise reciporical square root.

  .. _stablehlo.sqrt: https://openxla.org/stablehlo/spec#sqrt
  r  )sqrt_pr   r  s     rT   sqrtr@        2 
Q	**rV   c                0    t         j                  | |      S )a  Elementwise reciprocal square root:  :math:`1 \over \sqrt{x}`.

  This function lowers directly to the `stablehlo.rsqrt`_ operation.

  Args:
    x: Input array. Must have floating or complex dtype.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    An array of the same shape and dtype as ``x`` containing the
    reciporical square root.

  See also:
    :func:`jax.lax.pow`: Elementwise power.
    :func:`jax.lax.sqrt`: Elementwise square root.
    :func:`jax.lax.cbrt`: Elementwise cube root.

  .. _stablehlo.rsqrt: https://openxla.org/stablehlo/spec#rsqrt
  r  )rsqrt_pr   r  s     rT   rsqrtrD    s    4 
a(	++rV   c                0    t         j                  | |      S )ay  Elementwise cube root: :math:`\sqrt[3]{x}`.

  This function lowers directly to the `stablehlo.cbrt`_ operation.

  Args:
    x: Input array. Must have floating or complex dtype.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    An array of the same shape and dtype as ``x`` containing the cube root.

  See also:
    :func:`jax.lax.pow`: Elementwise power.
    :func:`jax.lax.sqrt`: Elementwise square root.
    :func:`jax.lax.rsqrt`: Elementwise reciporical square root.

  .. _stablehlo.cbrt: https://openxla.org/stablehlo/spec#cbrt
  r  )cbrt_pr   r  s     rT   cbrtrG    rA  rV   c                ,    t         j                  |       S )a  Elementwise NOT: :math:`\neg x`.

  This function lowers directly to the `stablehlo.not`_ operation.

  Args:
    x: Input array. Must have boolean or integer dtype.

  Returns:
    An array of the same shape and dtype as ``x`` containing the bitwise
    inversion of each entry.

  See also:
    - :func:`jax.numpy.invert`: NumPy wrapper for this API, also accessible
      via the ``~x`` operator on JAX arrays.
    - :func:`jax.lax.bitwise_and`: Elementwise AND.
    - :func:`jax.lax.bitwise_or`: Elementwise OR.
    - :func:`jax.lax.bitwise_xor`: Elementwise exclusive OR.

  .. _stablehlo.not: https://openxla.org/stablehlo/spec#not
  )not_pr   rR   s    rT   bitwise_notrJ    s    , 
ArV   c                `    t        j                  | |      \  } }t        j                  | |      S )a#  Elementwise AND: :math:`x \wedge y`.

  This function lowers directly to the `stablehlo.and`_ operation.

  Args:
    x, y: Input arrays. Must have matching boolean or integer dtypes.
      If neither is a scalar, ``x`` and ``y`` must have the same number
      of dimensions and be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the bitwise
    AND of each pair of broadcasted entries.

  See also:
    - :func:`jax.numpy.bitwise_and`: NumPy wrapper for this API, also accessible
      via the ``x & y`` operator on JAX arrays.
    - :func:`jax.lax.bitwise_not`: Elementwise NOT.
    - :func:`jax.lax.bitwise_or`: Elementwise OR.
    - :func:`jax.lax.bitwise_xor`: Elementwise exclusive OR.

  .. _stablehlo.and: https://openxla.org/stablehlo/spec#and
  )r   r   and_pr   r#  s     rT   bitwise_andrM    +    0 
	#	#Aq	)$!Q	Aq	rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise OR: :math:`x \vee y`.

  This function lowers directly to the `stablehlo.or`_ operation.

  Args:
    x, y: Input arrays. Must have matching boolean or integer dtypes.
      If neither is a scalar, ``x`` and ``y`` must have the same number
      of dimensions and be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the bitwise
    OR of each pair of broadcasted entries.

  See also:
    - :func:`jax.numpy.invert`: NumPy wrapper for this API, also accessible
      via the ``x | y`` operator on JAX arrays.
    - :func:`jax.lax.bitwise_not`: Elementwise NOT.
    - :func:`jax.lax.bitwise_and`: Elementwise AND.
    - :func:`jax.lax.bitwise_xor`: Elementwise exclusive OR.

  .. _stablehlo.or: https://openxla.org/stablehlo/spec#or
  )r   r   or_pr   r#  s     rT   
bitwise_orrQ    s*    0 
	#	#Aq	)$!Q	1arV   c                `    t        j                  | |      \  } }t        j                  | |      S )a#  Elementwise exclusive OR: :math:`x \oplus y`.

  This function lowers directly to the `stablehlo.xor`_ operation.

  Args:
    x, y: Input arrays. Must have matching boolean or integer dtypes.
      If neither is a scalar, ``x`` and ``y`` must have the same number
      of dimensions and be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the bitwise
    XOR of each pair of broadcasted entries.

  See also:
    - :func:`jax.numpy.bitwise_xor`: NumPy wrapper for this API, also accessible
      via the ``x ^ y`` operator on JAX arrays.
    - :func:`jax.lax.bitwise_not`: Elementwise NOT.
    - :func:`jax.lax.bitwise_and`: Elementwise AND.
    - :func:`jax.lax.bitwise_or`: Elementwise OR.

  .. _stablehlo.xor: https://openxla.org/stablehlo/spec#xor
  )r   r   xor_pr   r#  s     rT   bitwise_xorrT  .  rN  rV   c                ,    t         j                  |       S )a  Elementwise popcount, count the number of set bits in each element.

  This function lowers directly to the `stablehlo.popcnt`_ operation.

  Args:
    x: Input array. Must have integer dtype.

  Returns:
    An array of the same shape and dtype as ``x``, containing the number of
    set bits in the input.

  See also:
    - :func:`jax.lax.clz`: Elementwise count leading zeros.
    - :func:`jax.numpy.bitwise_count`: More flexible NumPy-style API for bit counts.

  .. _stablehlo.popcnt: https://openxla.org/stablehlo/spec#popcnt
  )population_count_pr   rR   s    rT   population_countrW  I  s    & 
	 	 	##rV   c                ,    t         j                  |       S )a  Elementwise count-leading-zeros.

  This function lowers directly to the `stablehlo.count_leading_zeros`_ operation.

  Args:
    x: Input array. Must have integer dtype.

  Returns:
    An array of the same shape and dtype as ``x``, containing the number of
    set bits in the input.

  See also:
    - :func:`jax.lax.population_count`: Count the number of set bits in each element.

  .. _stablehlo.count_leading_zeros: https://openxla.org/stablehlo/spec#count_leading_zeros
  )clz_pr   rR   s    rT   clzrZ  ^  r   rV   c                `    t        j                  | |      \  } }t        j                  | |      S )aU  Elementwise addition: :math:`x + y`.

  This function lowers directly to the `stablehlo.add`_ operation.

  Args:
    x, y: Input arrays. Must have matching numerical dtypes. If neither
      is a scalar, ``x`` and ``y`` must have the same number of dimensions
      and be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the sum
    of each pair of broadcasted entries.

  See also:
    - :func:`jax.numpy.add`: NumPy-style addition supporting inputs
      with mixed dtypes and ranks.

  .. _stablehlo.add: https://openxla.org/stablehlo/spec#add
  )r   r   add_pr   r#  s     rT   addr]  r  +    * 
	#	#Aq	)$!Q	Aq	rV   c                `    t        j                  | |      \  } }t        j                  | |      S )av  Elementwise subtraction: :math:`x - y`.

  This function lowers directly to the `stablehlo.subtract`_ operation.

  Args:
    x, y: Input arrays. Must have matching numerical dtypes. If neither
      is a scalar, ``x`` and ``y`` must have the same number of dimensions
      and be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the difference
    of each pair of broadcasted entries.

  See also:
    - :func:`jax.numpy.subtract`: NumPy-style subtraction supporting
      inputs with mixed dtypes and ranks.

  .. _stablehlo.subtract: https://openxla.org/stablehlo/spec#subtract
  )r   r   sub_pr   r#  s     rT   subra    r^  rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a~  Elementwise multiplication: :math:`x \times y`.

  This function lowers directly to the `stablehlo.multiply`_ operation.

  Args:
    x, y: Input arrays. Must have matching numerical dtypes. If neither
      is a scalar, ``x`` and ``y`` must have the same number of dimensions
      and be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the product
    of each pair of broadcasted entries.

  See also:
    - :func:`jax.numpy.multiply`: NumPy-style multiplication supporting
      inputs with mixed dtypes and ranks.

  .. _stablehlo.multiply: https://openxla.org/stablehlo/spec#multiply
  )r   r   mul_pr   r#  s     rT   mulrd    r^  rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise division: :math:`x \over y`.

  This function lowers directly to the `stablehlo.divide`_ operation.

  Integer division overflow (division by zero or signed division of
  INT_SMIN with -1) produces an implementation defined value.

  Args:
    x, y: Input arrays. Must have matching numerical dtypes. If neither
      is a scalar, ``x`` and ``y`` must have the same number of dimensions
      and be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the quotient
    of each pair of broadcasted entries. For integer inputs, any fractional
    part is discarded.

  See also:
    - :func:`jax.numpy.divide`: NumPy-style true division supporting
      inputs with mixed dtypes and ranks.
    - :func:`jax.numpy.floor_divide`: NumPy-style floor division supporting
      inputs with mixed dtypes and ranks.

  .. _stablehlo.divide: https://openxla.org/stablehlo/spec#divide
  )r   r   div_pr   r#  s     rT   divrg    s+    6 
	#	#Aq	)$!Q	Aq	rV   c                `    t        j                  | |      \  } }t        j                  | |      S )aP  Elementwise remainder: :math:`x \bmod y`.

  This function lowers directly to the `stablehlo.remainder`_ operation.
  The sign of the result is taken from the dividend, and the absolute value
  of the result is always less than the divisor's absolute value.

  Integer division overflow (remainder by zero or remainder of INT_SMIN with -1)
  produces an implementation defined value.

  Args:
    x, y: Input arrays. Must have matching int or float dtypes. If neither
      is a scalar, ``x`` and ``y`` must have the same number of dimensions
      and be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the remainder.

  See also:
    - :func:`jax.numpy.remainder`: NumPy-style remainder with different
      sign semantics.

  .. _stablehlo.remainder: https://openxla.org/stablehlo/spec#remainder
  )r   r   rem_pr   r#  s     rT   remrj    s+    2 
	#	#Aq	)$!Q	Aq	rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise maximum: :math:`\mathrm{max}(x, y)`.

  This function lowers directly to the `stablehlo.maximum`_ operation for
  non-complex inputs. For complex numbers, this uses a lexicographic
  comparison on the `(real, imaginary)` pairs.

  Args:
    x, y: Input arrays. Must have matching dtypes. If neither is a scalar,
      ``x`` and ``y`` must have the same rank and be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the elementwise
    maximum.

  See also:
    - :func:`jax.numpy.maximum`: more flexibly NumPy-style maximum.
    - :func:`jax.lax.reduce_max`: maximum along an axis of an array.
    - :func:`jax.lax.min`: elementwise minimum.

  .. _stablehlo.maximum: https://openxla.org/stablehlo/spec#maximum
  )r   r   max_pr   r#  s     rT   r`   r`     r9  rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise minimum: :math:`\mathrm{min}(x, y)`

  This function lowers directly to the `stablehlo.minimum`_ operation for
  non-complex inputs. For complex numbers, this uses a lexicographic
  comparison on the `(real, imaginary)` pairs.

  Args:
    x, y: Input arrays. Must have matching dtypes. If neither is a scalar,
      ``x`` and ``y`` must have the same rank and be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the elementwise
    minimum.

  See also:
    - :func:`jax.numpy.minimum`: more flexibly NumPy-style minimum.
    - :func:`jax.lax.reduce_min`: minimum along an axis of an array.
    - :func:`jax.lax.max`: elementwise maximum.

  .. _stablehlo.minimum: https://openxla.org/stablehlo/spec#minimum
  )r   r   min_pr   r#  s     rT   r^   r^     r9  rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a8  Elementwise left shift: :math:`x \ll y`.

  This function lowers directly to the `stablehlo.shift_left`_ operation.

  Args:
    x, y: Input arrays. Must have matching integer dtypes. If neither is a
      scalar, ``x`` and ``y`` must have the same number of dimensions and
      be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the element-wise
    left shift of each pair of broadcasted entries.

  See also:
    - :func:`jax.numpy.left_shift`: NumPy wrapper for this API, also accessible
      via the ``x << y`` operator on JAX arrays.
    - :func:`jax.lax.shift_right_arithmetic`: Elementwise arithmetic right shift.
    - :func:`jax.lax.shift_right_logical`: Elementwise logical right shift.

  .. _stablehlo.shift_left: https://openxla.org/stablehlo/spec#shift_left
  )r   r   shift_left_pr   r#  s     rT   
shift_leftrq  (  s-    . 
	#	#Aq	)$!Q			1a	  rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise arithmetic right shift: :math:`x \gg y`.

  This function lowers directly to the `stablehlo.shift_right_arithmetic`_ operation.

  Args:
    x, y: Input arrays. Must have matching integer dtypes. If neither is a
      scalar, ``x`` and ``y`` must have the same number of dimensions and
      be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the element-wise
    arithmetic right shift of each pair of broadcasted entries.

  See also:
    - :func:`jax.numpy.right_shift`: NumPy wrapper for this API when applied to
      signed integers, also accessible via the ``x >> y`` operator on JAX arrays
      with signed integer dtype.
    - :func:`jax.lax.shift_left`: Elementwise left shift.
    - :func:`jax.lax.shift_right_logical`: Elementwise logical right shift.

  .. _stablehlo.shift_right_arithmetic: https://openxla.org/stablehlo/spec#shift_right_arithmetic
  )r   r   shift_right_arithmetic_pr   r#  s     rT   shift_right_arithmeticrt  B  s-    0 
	#	#Aq	)$!Q	!	&	&q!	,,rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise logical right shift: :math:`x \gg y`.

  This function lowers directly to the `stablehlo.shift_right_logical`_ operation.

  Args:
    x, y: Input arrays. Must have matching integer dtypes. If neither is a
      scalar, ``x`` and ``y`` must have the same number of dimensions and
      be broadcast compatible.

  Returns:
    An array of the same dtype as ``x`` and ``y`` containing the element-wise
    logical right shift of each pair of broadcasted entries.

  See also:
    - :func:`jax.numpy.right_shift`: NumPy wrapper for this API when applied to
      unsigned integers, also accessible via the ``x >> y`` operator on JAX arrays
      with unsigned integer dtype.
    - :func:`jax.lax.shift_left`: Elementwise left shift.
    - :func:`jax.lax.shift_right_arithmetic`: Elementwise arithmetic right shift.

  .. _stablehlo.shift_right_logical: https://openxla.org/stablehlo/spec#shift_right_logical
  )r   r   shift_right_logical_pr   r#  s     rT   shift_right_logicalrw  ]  s-    0 
	#	#Aq	)$!Q		#	#Aq	))rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise equals: :math:`x = y`.

  This function lowers directly to the `stablehlo.compare`_ operation
  with ``comparison_direction=EQ`` and ``compare_type`` set according
  to the input dtype.

  Args:
    x, y: Input arrays. Must have matching dtypes. If neither is a
      scalar, ``x`` and ``y`` must have the same number of dimensions and
      be broadcast compatible.

  Returns:
    A boolean array of shape ``lax.broadcast_shapes(x.shape, y.shape)``
    containing the elementwise equal comparison.

  See also:
    - :func:`jax.numpy.equal`: NumPy wrapper for this API, also accessible
      via the ``x == y`` operator on JAX arrays.
    - :func:`jax.lax.ne`: elementwise not-equal
    - :func:`jax.lax.ge`: elementwise greater-than-or-equal
    - :func:`jax.lax.gt`: elementwise greater-than
    - :func:`jax.lax.le`: elementwise less-than-or-equal
    - :func:`jax.lax.lt`: elementwise less-than

  .. _stablehlo.compare: https://openxla.org/stablehlo/spec#compare
  )r   r   eq_pr   r#  s     rT   eqrz  x  *    8 
	#	#Aq	)$!Q	1arV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise not-equals: :math:`x \neq y`.

  This function lowers directly to the `stablehlo.compare`_ operation
  with ``comparison_direction=NE`` and ``compare_type`` set according
  to the input dtype.

  Args:
    x, y: Input arrays. Must have matching dtypes. If neither is a
      scalar, ``x`` and ``y`` must have the same number of dimensions and
      be broadcast compatible.

  Returns:
    A boolean array of shape ``lax.broadcast_shapes(x.shape, y.shape)``
    containing the elementwise not-equal comparison.

  See also:
    - :func:`jax.numpy.not_equal`: NumPy wrapper for this API, also accessible
      via the ``x != y`` operator on JAX arrays.
    - :func:`jax.lax.eq`: elementwise equal
    - :func:`jax.lax.ge`: elementwise greater-than-or-equal
    - :func:`jax.lax.gt`: elementwise greater-than
    - :func:`jax.lax.le`: elementwise less-than-or-equal
    - :func:`jax.lax.lt`: elementwise less-than

  .. _stablehlo.compare: https://openxla.org/stablehlo/spec#compare
  )r   r   ne_pr   r#  s     rT   ner~    r{  rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise greater-than-or-equals: :math:`x \geq y`.

  This function lowers directly to the `stablehlo.compare`_ operation
  with ``comparison_direction=GE`` and ``compare_type`` set according
  to the input dtype.

  Args:
    x, y: Input arrays. Must have matching non-complex dtypes. If neither is
      a scalar, ``x`` and ``y`` must have the same number of dimensions and
      be broadcast compatible.

  Returns:
    A boolean array of shape ``lax.broadcast_shapes(x.shape, y.shape)``
    containing the elementwise greater-than-or-equal comparison.

  See also:
    - :func:`jax.numpy.greater_equal`: NumPy wrapper for this API, also
      accessible via the ``x >= y`` operator on JAX arrays.
    - :func:`jax.lax.eq`: elementwise equal
    - :func:`jax.lax.ne`: elementwise not-equal
    - :func:`jax.lax.gt`: elementwise greater-than
    - :func:`jax.lax.le`: elementwise less-than-or-equal
    - :func:`jax.lax.lt`: elementwise less-than

  .. _stablehlo.compare: https://openxla.org/stablehlo/spec#compare
  )r   r   ge_pr   r#  s     rT   ger    r{  rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise greater-than: :math:`x > y`.

  This function lowers directly to the `stablehlo.compare`_ operation
  with ``comparison_direction=GT`` and ``compare_type`` set according
  to the input dtype.

  Args:
    x, y: Input arrays. Must have matching non-complex dtypes. If neither is
      a scalar, ``x`` and ``y`` must have the same number of dimensions and
      be broadcast compatible.

  Returns:
    A boolean array of shape ``lax.broadcast_shapes(x.shape, y.shape)``
    containing the elementwise greater-than comparison.

  See also:
    - :func:`jax.numpy.greater`: NumPy wrapper for this API, also accessible
      via the ``x > y`` operator on JAX arrays.
    - :func:`jax.lax.eq`: elementwise equal
    - :func:`jax.lax.ne`: elementwise not-equal
    - :func:`jax.lax.ge`: elementwise greater-than-or-equal
    - :func:`jax.lax.le`: elementwise less-than-or-equal
    - :func:`jax.lax.lt`: elementwise less-than

  .. _stablehlo.compare: https://openxla.org/stablehlo/spec#compare
  )r   r   gt_pr   r#  s     rT   gtr    r{  rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise less-than-or-equals: :math:`x \leq y`.

  This function lowers directly to the `stablehlo.compare`_ operation
  with ``comparison_direction=LE`` and ``compare_type`` set according
  to the input dtype.

  Args:
    x, y: Input arrays. Must have matching non-complex dtypes. If neither is
      a scalar, ``x`` and ``y`` must have the same number of dimensions and
      be broadcast compatible.

  Returns:
    A boolean array of shape ``lax.broadcast_shapes(x.shape, y.shape)``
    containing the elementwise less-than-or-equal comparison.

  See also:
    - :func:`jax.numpy.less_equal`: NumPy wrapper for this API, also
      accessible via the ``x <= y`` operator on JAX arrays.
    - :func:`jax.lax.eq`: elementwise equal
    - :func:`jax.lax.ne`: elementwise not-equal
    - :func:`jax.lax.ge`: elementwise greater-than-or-equal
    - :func:`jax.lax.gt`: elementwise greater-than
    - :func:`jax.lax.lt`: elementwise less-than

  .. _stablehlo.compare: https://openxla.org/stablehlo/spec#compare
  )r   r   le_pr   r#  s     rT   ler    r{  rV   c                `    t        j                  | |      \  } }t        j                  | |      S )a  Elementwise less-than: :math:`x < y`.

  This function lowers directly to the `stablehlo.compare`_ operation
  with ``comparison_direction=LT`` and ``compare_type`` set according
  to the input dtype.

  Args:
    x, y: Input arrays. Must have matching non-complex dtypes. If neither is
      a scalar, ``x`` and ``y`` must have the same number of dimensions and
      be broadcast compatible.

  Returns:
    A boolean array of shape ``lax.broadcast_shapes(x.shape, y.shape)``
    containing the elementwise less-than comparison.

  See also:
    - :func:`jax.numpy.less`: NumPy wrapper for this API, also accessible
      via the ``x < y`` operator on JAX arrays.
    - :func:`jax.lax.eq`: elementwise equal
    - :func:`jax.lax.ne`: elementwise not-equal
    - :func:`jax.lax.ge`: elementwise greater-than-or-equal
    - :func:`jax.lax.gt`: elementwise greater-than
    - :func:`jax.lax.le`: elementwise less-than-or-equal

  .. _stablehlo.compare: https://openxla.org/stablehlo/spec#compare
  )r   r   lt_pr   r#  s     rT   ltr    r{  rV   c                J    t        j                  |d      }t        | |d      S )a  Elementwise cast.

  This function lowers directly to the `stablehlo.convert`_ operation, which
  performs an elementwise conversion from one type to another, similar to a
  C++ ``static_cast``.

  Args:
    operand: an array or scalar value to be cast.
    new_dtype: a dtype-like object (e.g. a :class:`numpy.dtype`, a scalar type,
      or a valid dtype name) representing the target dtype.

  Returns:
    An array with the same shape as ``operand``, cast elementwise to ``new_dtype``.

  .. note::

     If ``new_dtype`` is a 64-bit type and `x64 mode`_ is not enabled,
     the appropriate 32-bit type will be used in its place.

     If the input is a JAX array and the input dtype and output dtype match, then
     the input array will be returned unmodified.

  See also:
    - :func:`jax.numpy.astype`: NumPy-style dtype casting API.
    - :meth:`jax.Array.astype`: dtype casting as an array method.
    - :func:`jax.lax.bitcast_convert_type`: cast bits directly to a new dtype.

  .. _stablehlo.convert: https://openxla.org/stablehlo/spec#convert
  .. _x64 mode: https://docs.jax.dev/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
  convert_element_typeFr   )r   !check_and_canonicalize_user_dtyper   operand	new_dtypes     rT   r  r  2  s*    B 66'))	w	U	CCrV   FTr   c                   t        | d      r| j                         } t        j                  |       }t	        |t        j
                        st	        |t        j
                        rh||k(  r9|| S t	        | t        j                        r| j                  j                  |k(  r| S ||rt        t	        |t        j
                        rt	        |t        j
                        rt        j                  |      j                  }t        j                  |      j                  }t        dt        |       dt        |       dt        |       dt        |       dt        |       dt        |             t	        |t        j
                        rt        j                  | |      S t         j                  | t#        j                  |            S t        j$                  |       }||}nt	        |t&              sJ |       |t	        |t(              st        d|d	      |rzt        j*                  |t"        j,                        rVt        j*                  |t"        j,                        s2d
}	t/        j0                  |	t"        j2                  j4                  d       t7        |       t8        u rK|t        j:                  k7  r8t=        j>                  t#        j@                  |       jC                  |      |      } ||f||fk(  r_t	        | tD              rOt	        | t        j                        rt        jF                  |       s ||jH                  rtK        | dd       |k(  r| S tL        j                  | |tO        |      |      S )N__jax_array__z6cannot directly convert between extended dtypes: from  to zB. Instead, convert to and from their representation dtypes, e.g.:
z -> edtyperb   z	sharding=z- must be an instance of jax.sharding.Shardingz:Casting complex values to real discards the imaginary partrM   
stacklevelr   r  r   r   )(hasattrr  r   rb   r   ExtendedDTyper   Traceravalr   NotImplementedErrorphysical_element_avalr   r0   to_edtype_pr   from_edtype_prZ   is_weakly_typedr@   r6   
issubdtypecomplexfloatingwarningswarn
exceptionsComplexWarningr   r   float0r   r   r   astyper<   is_concrete_is_concretegetattrconvert_element_type_pr   )
r  r  r   r   warn_on_complex_to_real_cast	old_dtypeold_rep_dtypenew_rep_dtypeold_weak_typers   s
             rT   r   r   W  s    Wo&##%Gll7#)F001F001I			GT[[	)gll.C.Cx.Oy9f2239f22300;AAm00;AAm
BY'(_Y-G,H INY'(_]-K,L M./tOI4N3O	QR R )V112gi88gRXXi-@AA((1-Ii'22'*Xx"@
	{"OP
QQ"	2#5#56


Ir'9'9
:
FCMM#r}}33B 
']ci6==8##BJJw$7$>$>y$I)24G - Y	$::% gt{{+0@0@0I'':t"D"PN!&&9Y '  rV   c                \    t        j                  |d      }t        j                  | |      S )aC  Elementwise bitcast.

  This function lowers directly to the `stablehlo.bitcast_convert`_ operation.

  The output shape depends on the size of the input and output dtypes with
  the following logic::

    if new_dtype.itemsize == operand.dtype.itemsize:
      output_shape = operand.shape
    if new_dtype.itemsize < operand.dtype.itemsize:
      output_shape = (*operand.shape, operand.dtype.itemsize // new_dtype.itemsize)
    if new_dtype.itemsize > operand.dtype.itemsize:
      assert operand.shape[-1] * operand.dtype.itemsize == new_dtype.itemsize
      output_shape = operand.shape[:-1]

  Args:
    operand: an array or scalar value to be cast
    new_dtype: the new type. Should be a NumPy type.

  Returns:
    An array of shape `output_shape` (see above) and type `new_dtype`,
    constructed from the same bits as operand.

  See also:
    - :func:`jax.lax.convert_element_type`: value-preserving dtype conversion.
    - :func:`jax.Array.view`: NumPy-style API for bitcast type conversion.

  .. _stablehlo.bitcast_convert: https://openxla.org/stablehlo/spec#bitcast_convert
  bitcast_convert_type)r  )r   r  bitcast_convert_type_pr   r  s     rT   r  r    s0    > 66'))		$	$W		$	BBrV   r^   r`   c                f    t        j                  | ||      \  } }}t        j                  | ||      S )zElementwise clamp.

  Returns :math:`\mathrm{clamp}(x) = \begin{cases}
  \mathit{min} & \text{if } x < \mathit{min},\\
  \mathit{max} & \text{if } x > \mathit{max},\\
  x & \text{otherwise}
  \end{cases}`.
  )r   r   clamp_pr   )r^   rS   r`   s      rT   clampr    s1     **337+#q#	c1c	""rV   r   c                .   t        j                  t        j                  | |      |      \  }}t	        j
                  ||      \  }}}	t        d |	D              rt        d| d      t	        j                  t	        j                  |            }
|
|	|fS )N
debug_infoc              3  P   K   | ]  }t        |t        j                           y wrY   r   r   r  rj   cs     rT   rl   z,_trace_composite_to_jaxpr.<locals>.<genexpr>       4At{{	#4   $&zLFound a JAX Tracer as a constant in the decomposition for the composite op 'z'. This means that the decomposition function closes over a value that is involved in a JAX transformation. Any values that aren't explicitly known at compile time must be explicitly passed as arguments to the composite.)
r   flatten_fun_nokwargslu	wrap_initpetrace_to_jaxpr_dynamicanyr$   close_jaxprconvert_constvars_jaxpr)funin_treein_avalsr   r  flat_funout_treejaxprr   constsclosed_jaxprs              rT   _trace_composite_to_jaxprr    s      44ll3:.9(H..xB%F4V44
	 ;	;< <  : :5 AB,	vx	''rV   c                J     t        j                          fd       }|S )aU
  Composite with semantics defined by the decomposition function.

  A composite is a higher-order JAX function that encapsulates an operation made
  up (composed) of other JAX functions. The semantics of the op are implemented
  by the ``decomposition`` function. In other words, the defined composite
  function can be replaced with its decomposed implementation without changing
  the semantics of the encapsulated operation.

  The compiler can recognize specific composite operations by their ``name``,
  ``version``, ``kwargs``, and dtypes to emit more efficient code, potentially
  leveraging hardware-specific instructions or optimizations. If the compiler
  doesn't recognize the composite, it falls back to compiling the
  ``decomposition`` function.

  Consider a "tangent" composite operation. Its ``decomposition`` function could
  be implemented as ``sin(x) / cos(x)``. A hardware-aware compiler could
  recognize the "tangent" composite and emit a single ``tangent`` instruction
  instead of three separate instructions (``sin``, ``divide``, and ``cos``).
  For hardware without dedicated tangent support, it would fall back to
  compiling the decomposition.

  This is useful for preserving high-level abstractions that would otherwise be
  lost while lowering, which allows for easier pattern-matching in low-level IR.

  Args:
    decomposition: function that implements the semantics of the composite op.
    name: name of the encapsulated operation.
    version: optional int to indicate semantic changes to the composite.

  Returns:
    Callable: Returns a composite function. Note that positional arguments to
    this function should be interpreted as inputs and keyword arguments should
    be interpreted as attributes of the op. Any keyword arguments that are
    passed with ``None`` as a value will be omitted from the
    ``composite_attributes``.

  Examples:
    Tangent kernel:

    >>> def my_tangent_composite(x):
    ...   return lax.composite(
    ...     lambda x: lax.sin(x) / lax.cos(x), name="my.tangent"
    ...   )(x)
    >>>
    >>> pi = jnp.pi
    >>> x = jnp.array([0.0, pi / 4, 3 * pi / 4, pi])
    >>> with jnp.printoptions(precision=3, suppress=True):
    ...   print(my_tangent_composite(x))
    ...   print(lax.tan(x))
    [ 0.  1. -1.  0.]
    [ 0.  1. -1.  0.]

    The recommended way to create composites is via a decorator. Use ``/`` and
    ``*`` in the function signature to be explicit about positional and keyword
    arguments, respectively:

    >>> @partial(lax.composite, name="my.softmax")
    ... def my_softmax_composite(x, /, *, axis):
    ...   return jax.nn.softmax(x, axis)
  c                 v   t        j                  d| i       }t        j                  |       \  }}t	        d |D              }t        d |j                         D              rt        d d      t        t        fi ||||      \  }}}g }	|j                         D ]C  \  }
}t        j                  |      \  }}t	        d |D              }|	j                  |
||f       E t        j                  g || }t        j                  |t	        |	      |d}t        j                    |       |      S )N	compositec              3  F   K   | ]  }t        j                  |        y wrY   )r   get_avalrj   rS   s     rT   rl   z0composite.<locals>._decorator.<locals>.<genexpr>'  s     9!T]]1%9   !c              3  P   K   | ]  }t        |t        j                           y wrY   r  rj   vs     rT   rl   z0composite.<locals>._decorator.<locals>.<genexpr>(  s     
?!:a%
?r  zNFound a JAX Tracer as an attribute in the decomposition for the composite op 'a*  '. This means that the decomposition function closes over a value that is involved in a JAX transformation. Any values that aren't explicitly known at compile time must be explicitly passed as arguments to the composite.

Note: If you are passing jax arrays as attributes, use numpy arrays instead.c              3  j   K   | ]+  }t        |t        j                        rt        |      n| - y wrY   )r   rZ   r   r%   r  s     rT   rl   z0composite.<locals>._decorator.<locals>.<genexpr>7  s,      CDjBJJ7-
Q
>s   13)r   
attributesversionr  )r   r  r   tree_flattenr   r  valuesr$   r  r   itemsr   r   r   composite_pr   tree_unflatten)argskwargsr  	flat_argsr  r  r  r  r  r  kr  leavestreedefflat_consts_and_argsout_flatdecompositionr   r  s                   rT   
_decoratorzcomposite.<locals>._decorator"  sV   $$[-%)2/J"//5Iw9y99H

?v}}
??!& !  &?(('8T:&"L&( J .1!..q1ofg HN f FG,-.  55JvJ	J	$H ##HJ99rV   )	functoolswraps)r  r   r  r  s   ``` rT   r  r    s*    B ??=! : " :D 
rV   c          
     \    t        j                  |j                        }t        j                  |      \  }}t         fd|D              }	g | j                  }
t        j                  || j                  t        |      |
 j                   j                        \  }}}i }|D ]2  \  }}}|j                  |      }|t        j                  |      ||<   4 |j                  j                   }t#        j$                  |j&                  j(                  t        j*                  |	|z         t,        j.                  j1                  |      t,        j2                  j1                  |      t,        j4                  j1                  |      t        j6                  |            }|j(                  S )a  Makes composite which calls the implementation function.

  Lowering a composite primitive to a ``stablehlo.composite`` op.

  Args:
    ctx: The MLIR context.
    *args: The arguments to the composite.
    name: The name of the composite.
    attributes: The attributes of the composite.
    version: The version of the composite.
    jaxpr: The jaxpr of the underlying composite.

  Returns:
    The results of the composite.
  c              3  h   K   | ])  \  }}t        j                  |j                  |        + yw))const_loweringr  N)r(   ir_constantr  )rj   r  r  ctxs      rT   rl   z&_composite_lowering.<locals>.<genexpr>a  s5      
!T q););$GGr   )r   r  composite_attributesr  )r   jaxpr_const_argsr  r   unzip2r   avals_inr(   lower_called_computationmodule_contextr   	avals_out	tokens_in	unflattenir_attributer   valuer5   CompositeOpr   resultsflatten_ir_valuesr3   
StringAttrgetFlatSymbolRefAttrDictAttri32_attr)r  r   r  r  r  r  const_args_and_avals
const_argsconst_avalsconst_arg_valuesr  func_opr   composite_attrsr  r  r  r  symbol_namer  s   `                   rT   _composite_loweringr  H  so   . ..u{{; KK(<=*k )  +{*S\\*(//
		*o	mm	mm-'1a /& 0a&!A},,Q/oa0 ""+ooll
-45==T"((,,[9;;???;mmG$) 
		rV   c                2     t        j                  |       | S rY   )r   jaxpr_as_funr  r  r   s      rT   _composite_implr    s    	!		5	!4	((rV   c                    ~| j                   S rY   )	out_avalsr  s      rT   _composite_abstract_evalr    s    
	rV   c                     ~ t        d      )NzJVP rule for composite not implemented. You can use `jax.custom_jvp` to add support. See https://docs.jax.dev/en/latest/_autosummary/jax.custom_jvp.htmlr   r  r   s     rT   composite_jvpr        
H	 rV   c                     ~ t        d      )NzTranspose rule for composite not implemented. You can use`jax.custom_jvp` or `jax.custom_vjp` to add support. See https://docs.jax.dev/en/latest/_autosummary/jax.custom_jvp.htmlr  r  s     rT   composite_transposer    r  rV   r  c                    t        |       dk(  rt        d      t        |       dk(  r| \  }t        |t              r|S t	        j
                  |  } t        j                  | d|iS )a  Concatenates a sequence of arrays along `dimension`.

  Wraps XLA's `Concatenate
  <https://www.openxla.org/xla/operation_semantics#concatenate>`_
  operator.

  Args:
    operands: a sequence of arrays to concatenate. The arrays must have equal
      shapes, except in the `dimension` axis.
    dimension: the dimension along which to concatenate the arrays.

  Returns:
    An array containing the concatenation.
  r   z4concatenate requires a non-empty sequences of arraysrN   	dimension)r   r   r   r<   r   r   concatenate_pr   )operandsr!  ops      rT   concatenater%    sd     	]a
K
LL]a
CB"ei''2(			X	;	;;rV   c                    t        |       } t        j                  | t        |      t	        || j
                              S )a  Splits an array along ``axis``.

  Args:
    operand: an array to split
    sizes: the sizes of the split arrays. The sum of the sizes must be equal
      to the size of the ``axis`` dimension of ``operand``.
    axis: the axis along which to split the array.

  Returns:
    A sequence of ``len(sizes)`` arrays. If ``sizes`` is
    ``[s1, s2, ...]``, this function returns chunks of sizes ``s1``, ``s2``,
    taken along ``axis``.
  sizesaxis)r   split_pr   r   rD   rO   r  r(  r)  s      rT   splitr,    s<     G'	gU5\,T7<<@ 
 
B BrV   zdict[Any, Precision]_precision_stringsc                  >    e Zd ZdZdZdZdZed	d       Zd
dZ	d
dZ
y)	Precisiona  Precision enum for lax matrix multiply related functions.

  The device-dependent `precision` argument to JAX functions generally
  controls the tradeoff between speed and accuracy for array computations on
  accelerator backends, (i.e. TPU and GPU). Has no impact on CPU backends.
  This only has an effect on float32 computations, and does not affect the
  input/output datatypes. Members are:

  DEFAULT:
    Fastest mode, but least accurate. On TPU: performs float32 computations in
    bfloat16. On GPU: uses tensorfloat32 if available (e.g. on A100 and H100
    GPUs), otherwise standard float32 (e.g. on V100 GPUs). Aliases:
    ``'default'``, ``'fastest'``.
  HIGH:
    Slower but more accurate. On TPU: performs float32 computations in 3
    bfloat16 passes. On GPU: uses tensorfloat32 where available, otherwise
    float32. Aliases: ``'high'``..
  HIGHEST:
    Slowest but most accurate. On TPU: performs float32 computations in 6
    bfloat16. Aliases: ``'highest'``. On GPU: uses float32.
  r   rN   rM   c                ,    t         j                  |      S rY   )r-  r  )clsr  s     rT   	_missing_zPrecision._missing_  s    !!%((rV   c                L    | j                   j                   d| j                   S Nrn   	__class__r   r   r   s    rT   __repr__zPrecision.__repr__  "    nn%%&a		{33rV   c                    | j                   S rY   r   r7  s    rT   __str__zPrecision.__str__      99rV   N)r  objectreturnzPrecision | Noner?  r   )r   r   r   r   r   HIGHr   classmethodr2  r8  r<  ri   rV   rT   r/  r/    s4    , '	
$') )4rV   r/  highestfloat32highbfloat16_3xtensorfloat32defaultbfloat16fastestc                  x    e Zd ZU dZded<   ded<   ded<   dZded<   dZded	<   dZded
<   dZded<   	 	 	 	 ddZ	y)DotAlgorithma  Specify the algorithm used for computing dot products.

  When used to specify the ``precision`` input to :func:`~jax.lax.dot`,
  :func:`~jax.lax.dot_general`, and other dot product functions, this data
  structure is used for controlling the properties of the algorithm used for
  computing the dot product. This API controls the precision used for the
  computation, and allows users to access hardware-specific accelerations.

  Support for these algorithms is platform dependent, and using an unsupported
  algorithm will raise a Python exception when the computation is compiled. The
  algorithms that are known to be supported on at least some platforms are
  listed in the :class:`~jax.lax.DotAlgorithmPreset` enum, and these are a
  good starting point for experimenting with this API.

  A "dot algorithm" is specified by the following parameters:

  * ``lhs_precision_type`` and ``rhs_precision_type``, the data types that the
    LHS and RHS of the operation are rounded to.
  * ``accumulation_type`` the data type used for accumulation.
  * ``lhs_component_count``, ``rhs_component_count``, and
    ``num_primitive_operations`` apply to algorithms that decompose the LHS
    and/or RHS into multiple components and execute multiple operations on
    those values, usually to emulate a higher precision. For algorithms with no
    decomposition, these values should be set to ``1``.
  * ``allow_imprecise_accumulation`` to specify if accumulation in lower
    precision is permitted for some steps (e.g.
    ``CUBLASLT_MATMUL_DESC_FAST_ACCUM``).

  The `StableHLO spec <https://openxla.org/stablehlo/spec#dot_general>`_ for
  the dot operation doesn't require that the precision types be the same as the
  storage types for the inputs or outputs, but some platforms may require that
  these types match. Furthermore, the return type of
  :func:`~jax.lax.dot_general` is always defined by the ``accumulation_type``
  parameter of the input algorithm, if specified.

  Examples:

    Accumulate two 16-bit floats using a 32-bit float accumulator:

    >>> algorithm = DotAlgorithm(
    ...     lhs_precision_type=np.float16,
    ...     rhs_precision_type=np.float16,
    ...     accumulation_type=np.float32,
    ... )
    >>> lhs = jnp.array([1.0, 2.0, 3.0, 4.0], dtype=np.float16)
    >>> rhs = jnp.array([1.0, 2.0, 3.0, 4.0], dtype=np.float16)
    >>> dot(lhs, rhs, precision=algorithm)  # doctest: +SKIP
    array([ 1.,  4.,  9., 16.], dtype=float16)

    Or, equivalently, using a preset:

    >>> algorithm = DotAlgorithmPreset.F16_F16_F32
    >>> dot(lhs, rhs, precision=algorithm)  # doctest: +SKIP
    array([ 1.,  4.,  9., 16.], dtype=float16)

    Presets can also be specified by name:

    >>> dot(lhs, rhs, precision="F16_F16_F32")  # doctest: +SKIP
    array([ 1.,  4.,  9., 16.], dtype=float16)

    The ``preferred_element_type`` parameter can be used to return the output
    without downcasting the accumulation type:

    >>> dot(lhs, rhs, precision="F16_F16_F32", preferred_element_type=np.float32)  # doctest: +SKIP
    array([ 1.,  4.,  9., 16.], dtype=float32)
  rA   lhs_precision_typerhs_precision_typeaccumulation_typerN   r   lhs_component_countrhs_component_countnum_primitive_operationsFr   allow_imprecise_accumulationc           	        ~~t         j                  j                  t        j                  t        j                  | j                              t        j                  t        j                  | j                              t        j                  t        j                  | j                              | j                  | j                  | j                  | j                        S rY   )r5   rL  r  r(   dtype_to_ir_typer   rb   rM  rN  rO  rP  rQ  rR  rS  )r   	lhs_dtype	rhs_dtypes      rT   _convert_to_hlo_attrz!DotAlgorithm._convert_to_hlo_attrQ  s    9fll4+B+BCDfll4+B+BCDfll4+A+ABC    %%)) rV   N)rV  rA   rW  rA   r?  zhlo.DotAlgorithm)
r   r   r   r   __annotations__rP  rQ  rR  rS  rX  ri   rV   rT   rL  rL    s^    AF  ss"#C#',,&/4DrV   rL  c                     e Zd ZdZ ej
                         Z	  ej
                         Z	  ej
                         Z	  ej
                         Z		  ej
                         Z
	  ej
                         Z ej
                         Z ej
                         Z ej
                         Z ej
                         Z	  ej
                         Z	  ej
                         Z	  ej
                         Z ej
                         Z	  ej
                         Z ej
                         Zd
dZd
dZedd       Zedd       Zedd       Z	 	 	 	 	 	 ddZ	 	 	 	 ddZy	)DotAlgorithmPreseta  An enum of known algorithms for computing dot products.

  This ``Enum`` provides a named set of :class:`~jax.lax.DotAlgorithm` objects
  that are known to be supported on at least platform. See the
  :class:`~jax.lax.DotAlgorithm` documentation for more details about the
  behavior of these algorithms.

  An algorithm can be selected from this list when calling :func:`~jax.lax.dot`,
  :func:`~jax.lax.dot_general`, or most other JAX dot product functions, by
  passing either a member of this ``Enum`` or it's name as a string using the
  ``precision`` argument.

  For example, users can specify the preset using this ``Enum`` directly:

  >>> lhs = jnp.array([1.0, 2.0, 3.0, 4.0], dtype=np.float16)
  >>> rhs = jnp.array([1.0, 2.0, 3.0, 4.0], dtype=np.float16)
  >>> algorithm = DotAlgorithmPreset.F16_F16_F32
  >>> dot(lhs, rhs, precision=algorithm)  # doctest: +SKIP
  array([ 1.,  4.,  9., 16.], dtype=float16)

  or, equivalently, they can be specified by name:

  >>> dot(lhs, rhs, precision="F16_F16_F32")  # doctest: +SKIP
  array([ 1.,  4.,  9., 16.], dtype=float16)

  The names of the presets are typically ``LHS_RHS_ACCUM`` where ``LHS`` and
  ``RHS`` are the element types of the ``lhs`` and ``rhs`` inputs
  respectively, and ``ACCUM`` is the element type of the accumulator. Some
  presets have an extra suffix, and the meaning of each of these is
  documented below. The supported presets are:
  c                L    | j                   j                   d| j                   S r4  r5  r7  s    rT   r8  zDotAlgorithmPreset.__repr__  r9  rV   c                    | j                   S rY   r;  r7  s    rT   r<  zDotAlgorithmPreset.__str__  r=  rV   c                l   | xxt         j                  k(  r  y xt         j                  k(  r	   y xt         j                  k(  r	   y xt         j                  k(  r	   y xt         j
                  k(  r	   y  xxt         j                  k(  rnxt         j                  k(  rn n  t        j                  fS xxt         j                  k(  rnxt         j                  k(  rn n"  t        j                  t        j                  fS t         j                  k(  rt        j                   fS 	 t        j                  fS rY   )r[  r   ANY_F8_ANY_F8_F32ANY_F8_ANY_F8_F32_FAST_ACCUMANY_F8_ANY_F8_ANYANY_F8_ANY_F8_ANY_FAST_ACCUMF16_F16_F16F16_F16_F32rZ   float16BF16_BF16_BF16BF16_BF16_F32r   rI  rD  F64_F64_F64float64r7  s    rT   supported_lhs_typesz&DotAlgorithmPreset.supported_lhs_types  s   
<
$

$
$ <  100< 	 <;;<  100<  <;;	< < K))),J,>,J,JJ

}+
+

+
+
*

*
*+ ,,))

}

}rV   c                    | j                   S rY   )rj  r7  s    rT   supported_rhs_typesz&DotAlgorithmPreset.supported_rhs_types  s    ###rV   c                   | xxt         j                  k(  r  y xt         j                  k(  r	   y xt         j                  k(  r	   y  xt         j                  k(  r t
        j                  S xt         j                  k(  r t        j                  S t         j                  k(  rt
        j                  S 	 t
        j                  S rY   )r[  r   ra  rb  rc  rZ   re  rf  r   rI  rh  ri  rD  r7  s    rT   rO  z$DotAlgorithmPreset.accumulation_type  s    
<
$

$
$ <  100<  <;;< 	<
 *))zz,,,))zzzzrV   c                &   | xxt         j                  k(  rnxt         j                  k(  rn n|  t        j                  t        j
                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  fS xt         j                  k(  rY t        j                  ||      t        j
                  k(  r t        j                  t        j
                  fS t        j                  fS t         j                  k(  rXt        j                  ||      t        j                  k(  r t        j                  t        j                  fS t        j                  fS 	 | j                   }|d S |fS rY   )r[  r_  r`  rZ   rD  re  r   rI  float8_e4m3fnfloat8_e5m2float8_e5m2fnuzfloat8_e4m3fnuzfloat8_e4m3b11fnuzrd  promote_typesrg  rO  )r   rV  rW  rO  s       rT   supported_output_typesz)DotAlgorithmPreset.supported_output_types  s!    <
.

.
.;;;< JJJJOO  """"%%	
 		
 *))	95C**bjj)
)**
++	95H**foo.
.**
 22(0tJ7H6JJrV   c           
     h
   t         j                  j                         }t         j                  j                         }t         j                  j                         }t         j
                  j                         }t         j                  j                         }| xxt        j                  k(  rn?xt        j                  k(  rn+xt        j                  k(  rnxt        j                  k(  rn n  t        j                  t        j                        t        j                  t        j                         t        j                  t        j"                        t        j                  t        j$                        t        j                  t        j&                        t        j                  t        j(                        t        j                  t        j*                        t        j                  t        j,                        g}||vs||vrt/        d|  d| d| d      t1        j2                  t        j                  |            }	t1        j2                  t        j                  |            }
t         j                  j                         }t4        j6                  j                  |	|
|ddd| t        j                  k(        S xt        j8                  k(  r& t4        j6                  j                  |||dddd      S xt        j:                  k(  r& t4        j6                  j                  |||dddd      S xt        j<                  k(  r& t4        j6                  j                  |||dddd      S xt        j>                  k(  r& t4        j6                  j                  |||dddd      S xt        j@                  k(  r& t4        j6                  j                  |||dddd      S xt        jB                  k(  r& t4        j6                  j                  |||dddd      S xt        jD                  k(  r& t4        j6                  j                  |||ddd	d      S xt        jF                  k(  r& t4        j6                  j                  |||dddd      S xt        jH                  k(  r& t4        j6                  j                  |||dddd      S xt        jJ                  k(  r& t4        j6                  j                  |||dddd      S t        jL                  k(  r%t4        j6                  j                  |||dddd      S 	 y )
NzThe dot algorithm 'z2' requires both inputs to have float8 dtypes. Got  and z	 instead.rN   F      	   )'r3   F16Typer  F32TypeF64TypeBF16TypeFloatTF32Typer[  r_  r`  ra  rb  rZ   rb   r   rs  ro  rr  rp  rq  float8_e3m4float8_e4m3float8_e8m0fnur   r(   rU  r5   rL  rc  rd  rf  rg  BF16_BF16_F32_X3BF16_BF16_F32_X6BF16_BF16_F32_X9TF32_TF32_F32TF32_TF32_F32_X3F32_F32_F32rh  )r   rV  rW  f16f32f64bf16tf32
fp8_dtypeslhsrhsaccs               rT   rX  z'DotAlgorithmPreset._convert_to_hlo_attr	  s   
**..
C
**..
C
**..
C;;??D!D
<
.

.
.;;;000;;;< HHV../HHV))*HHV++,HHV''(HHV++,HHV''(HHV''(HHV**+	

 J&):*E#D6 *&KuYKyB  ##FLL$;<##FLL$;<jjnn##&CCC
 	
 *))##Cc1aEBB)))##Cc1aEBB,,,##D$aAuEE+++##D$Q1eDD...##D$Q1eDD...##D$Q1eDD...##D$Q1eDD+++##D$Q1eDD...##D$Q1eDD)))##Cc1aEBB))##Cc1aEBBrV   Nr@  )r?  tuple[DTypeLike, ...] | None)r?  DTypeLike | None)rV  rA   rW  rA   r?  r  )rV  rA   rW  rA   r?  hlo.DotAlgorithm | None)r   r   r   r   enumautor   r_  r`  ra  rb  rc  rd  rf  rg  r  r  r  r  r  r  rh  r8  r<  propertyrj  rl  rO  ru  rX  ri   rV   rT   r[  r[  _  s   > DIIK'FdiikD!*  diik "+ 		+		+499;.$))+-TYY[ TYY[GTYY[G$))+-TYY[ 		+		+4  2 $ $  " K  K-6 K# KD@'0@5L@rV   r[  out_shardingc               $    t        | |||||      S )zAlias of :func:`jax.lax.dot`.

  Prefer use of :func:`jax.lax.dot` directly, but note that it requires
  all arguments after ``lhs`` and ``rhs`` to be specified by keyword
  rather than position.
  dimension_numbers	precisionpreferred_element_typer  )dot)r  r  r  r  r  r  s         rT   dot_generalr  ]	  s!     
S#):i$:
W WrV   r  c                  |rqt        j                  ddd       t        |      dk(  r|t        d      |\  }n9t        |      dk(  r |t        d      |t        d      |\  }}nt        d	      ~t	        j
                  |       }t        |      }t	        j
                  |      }	t        |	      }
|Td|cxk  rdk  r8n n5d|
cxk  rdk  r*n n't        j                  |d
   |	d         r|dz
  fdfdf}nt        d|d|	      t        |d      }|\  \  }}\  }}t        j                  |      t        j                  |      f}t        j                  |      t        j                  |      f}|dnt        j                  |d      }t        j                  | |      \  } }t        j!                  | |||ft#        |      ||      S )ay
  General dot product/contraction operator.

  This operation lowers directly to the `stablehlo.dot_general`_ operation.

  The semantics of ``dot_general`` are complicated, but most users should not have to
  use it directly. Instead, you can use higher-level functions like :func:`jax.numpy.dot`,
  :func:`jax.numpy.matmul`, :func:`jax.numpy.tensordot`, :func:`jax.numpy.einsum`,
  and others which will construct appropriate calls to ``dot_general`` under the hood.
  If you really want to understand ``dot_general`` itself, we recommend reading XLA's
  DotGeneral_ operator documentation.

  Args:
    lhs: an array
    rhs: an array
    dimension_numbers: an optional tuple of tuples of sequences of ints of the form
      ``((lhs_contracting_dims, rhs_contracting_dims), (lhs_batch_dims,
      rhs_batch_dims))``. This may be left unspecified in the common case of
      un-batched matrix-matrix, matrix-vector, or vector-vector dot products, as
      determined by the shape of ``lhs`` and ``rhs``.
    precision: Optional. This parameter controls the numerics of the
      computation, and it can be one of the following:

      - ``None``, which means the default precision for the current backend,
      - a :class:`~jax.lax.Precision` enum value or a tuple of two
        :class:`~jax.lax.Precision` enums indicating precision of ``lhs``` and
        ``rhs``, or
      - a :class:`~jax.lax.DotAlgorithm` or a
        :class:`~jax.lax.DotAlgorithmPreset` indicating the algorithm that
        must be used to accumulate the dot product.

    preferred_element_type: Optional. This parameter controls the data type
      output by the dot product. By default, the output element type of this
      operation will match the ``lhs`` and ``rhs`` input element types under
      the usual type promotion rules. Setting ``preferred_element_type`` to a
      specific ``dtype`` will mean that the operation returns that element type.
      When ``precision`` is not a :class:`~jax.lax.DotAlgorithm` or
      :class:`~jax.lax.DotAlgorithmPreset`, ``preferred_element_type`` provides
      a hint to the compiler to accumulate the dot product using this data type.
    out_sharding: an optional sharding specification for the output. If not specified,
      it will be determined automatically by the compiler.

  Returns:
    An array whose first dimensions are the (shared) batch dimensions, followed
    by the ``lhs`` non-contracting/non-batch dimensions, and finally the ``rhs``
    non-contracting/non-batch dimensions.

  .. _stablehlo.dot_general: https://openxla.org/stablehlo/spec#dot_general
  .. _DotGeneral: https://www.openxla.org/xla/operation_semantics#dotgeneral
  zjax-lax-dot-positional-argszqjax.lax.dot: passing precision or preferred_element_type by position is deprecated; pass them by keyword instead.rM   r  rN   Nz8jax.lax.dot got multiple values for argument 'precision'zEjax.lax.dot got multiple values for argument 'preferred_element_type'z4Too many positional arguments passed to jax.lax.dot.r   r   )ri   ri   zjax.lax.dot: dimension_numbers must be specified when not performing simple un-batched matrix-matrix, matrix-vector, or vector-vector products; got lhs_shape=z rhs_shape=r  r  r  )r   r  r   rp   rZ   rq   r   r   r   r:   r   _ensure_index_tupler   r  r   dot_general_pr   canonicalize_precision)r  r  r  r  r  r  r  	lhs_shapelhs_ndim	rhs_shaperhs_ndimlhs_contractrhs_contract	lhs_batch	rhs_batchcdimsbdimss                    rT   r  r  m	  s   n 
#	8  4yA~		RSSji	Ta		RSS		+_``*.'i'LMM
hhsm)^(hhsm)^(Ha80q0T5J5J9UW=ZcdeZf5g%\OT2H=	|<YL	*+ +
 '|]C,9J6< 6I''5''57%''	2''	24% %,d../EuM  ''S1(#s			C/4en&<Y&G3I)5	 
 
7 7rV   c           	     @    t        | ||t        t        |      ||      S )a  Ragged matrix multiplication.

  Args:
    lhs: (m, k) shaped array.
    rhs: (g, k, n) shaped array.
    group_sizes: (g,) shaped array with integer element type, where g denotes   number of groups. The ith element indicates the size of ith group.
    precision: Optional. Consistent with precision argument for :func:`jax.lax.dot`.
    preferred_element_type: Optional. Consistent with precision argument for :func:`jax.lax.dot`.
    group_offset: Optional. (1,) shaped array that indicates the group in group_sizes to start computing from. If not specified, defaults to [0].

  Results:
    (m, n) shaped array with preferred_element_type element type.
  ragged_dot_dimension_numbersr  r  group_offset)ragged_dot_general#_BASIC_RAGGED_DOT_DIMENSION_NUMBERSr  )r  r  group_sizesr  r  r  s         rT   
ragged_dotr  	  s+    * 
		#F&y13
 rV   )frozenc                  B     e Zd ZU dZded<   ded<   ded<    fdZ xZS )RaggedDotDimensionNumbersa  Describes ragged, group, and dot dimensions for ragged dot general.

  Args:
    dot_dimension_numbers: a tuple of tuples of sequences of ints of the form
      `((lhs_contracting_dims, rhs_contracting_dims), (lhs_batch_dims,
      rhs_batch_dims))`.
    lhs_ragged_dimensions: a sequence of ints indicating the 'lhs' ragged
      dimensions.
    rhs_group_dimensions: a sequence of ints indicating the 'rhs' group
      dimensions.
  DotDimensionNumbersdot_dimension_numbersSequence[int]lhs_ragged_dimensionsrhs_group_dimensionsc                    t         |   dt        d |D                     t         |   dt        |             t         |   dt        |             y )Nr  c              3  N   K   | ]  }t        t        t         |              y wrY   )r   r   rj   ts     rT   rl   z5RaggedDotDimensionNumbers.__init__.<locals>.<genexpr>
  s     BqeCqM"Bs   #%r  r  )super__setattr__r   )r   r  r  r  r6  s       rT   r   z"RaggedDotDimensionNumbers.__init__
  sR     
GB,ABB 
G/7L1MN	G.6J0KLrV   )r   r   r   r   rY  r   __classcell__)r6  s   @rT   r  r  	  s(    
 -,&&%%M MrV   r  c                >    t        | t              r| j                  S | S rY   )r   r  r  )r  s    rT   _from_maybe_raggedr  
  s*    
 
)+D	E 11 !rV   rN   r  r  r  c           	         t        j                  | ||      \  } }}t        j                  | |||t	        |      ||      S )ai  Ragged matrix multiplication.

  Ragged dot takes three arrays---``lhs``, ``rhs``, and ``group_sizes``---and
  a ``ragged_dot_dimension_numbers`` argument. Like `dot_general`, ``lhs`` and
  ``rhs`` are allowed arbitrary batch and contracting dimensions. Additionally,
  ``lhs`` is required to have one ragged dimension, and ``rhs`` may have at
  most one group dimension.

  Let `g` be the number of groups in the lhs ragged dimension. Ragged dot has
  three modes, depending on the kind of the lhs ragged dimension:

  1. ``[b...,m...,k...], [g,b...,k...,n...], [b...,x...,g] -> [b...,m...,n...]``.
     Here the ragged dimension is a non-contracting dimension (``m``) of ``lhs``,
     and ``x...`` are the lhs non-contracting dims outer to the ragged dim.
  2. ``[b...,m...,k...], [b...,k...,n...], [b...,x...,g] -> [g,b...,m...,n...]``.
     Here the ragged dimension is a contracting dimension (``k``) of ``lhs`` and
     ``rhs``, and `x...` are the lhs contracting dims outer to the ragged dim.
  3. ``[b...,m...,k...], [b...,k...,n...], [x...,g] -> [b...,m...,n...]``.
     Here the ragged dimension is a batch dimension (``b``) of ``lhs`` and
     ``rhs``, and ``x...`` are the lhs batch dims outer to the ragged dim.

  If ``group_sizes`` is passed-in with shape ``[g]``, it is broadcasted according
  to the rules above.

  Args:
    lhs: an array
    rhs: an array
    group_sizes: an array with integer element type
    ragged_dot_dimension_numbers: a ``RaggedDotDimensionNumbers`` object to
      specify the dot dimension numbers, lhs ragged dimension, and rhs group
      dimension.
    precision: Optional. Consistent with precision argument for
      :func:`jax.lax.dot`.
    preferred_element_type: Optional. Consistent with precision argument for
      :func:`jax.lax.dot`.
    group_offset: Optional. (1,) shaped array that indicates the group in
      group_sizes to start computing from. If not specified, defaults to [0].

  Results:
    An array whose shape is the same as that produced by `dot_general`, with an
    extra leading dimension of size `g` in the case where the lhs ragged
    dimension is a contracting dimension.
  r  )r   r   ragged_dot_general_pr   r  )r  r  r  r  r  r  r  s          rT   r  r  +
  sR    h 44S#{K#sK		"	"		#?&y13 
# 
 rV   c          	        t        |      dk(  r|t        |       S t        t        t        |      t        |      t	        j
                  |       z               }t        | t        |      t	        j                  |       z   ||      S )a]  Broadcasts an array, adding new leading dimensions

  Args:
    operand: an array
    sizes: a sequence of integers, giving the sizes of new leading dimensions
      to add to the front of the array.

  Returns:
    An array containing the result.

  See Also:
    jax.lax.broadcast_in_dim : add new dimensions at any location in the array shape.
  r   r  )r   r   r   rQ   rZ   rO   broadcast_in_dimrq   )r  r(  r  dimss       rT   	broadcastr  k
  sn     	Z1_-7	uSZUbggg.>!>?	@$	'5<"((72C#CT'3
5 5rV   rq   c                  t        |d      }t        j                  |       t        |      k(  rt        |      st	        | t
              r|| S t        j                  |       }|j                  |k(  rQt        |      t        t        |j                              k(  r'|%|j                  |k7  rt        j                  | |      S t        j                  | t!        |      t!        |      |      S )a  Wraps XLA's `BroadcastInDim
  <https://www.openxla.org/xla/operation_semantics#broadcastindim>`_
  operator.

  Args:
    operand: an array
    shape: the shape of the target array
    broadcast_dimensions: to which dimension in the target shape each dimension
      of the operand shape corresponds to. That is, dimension i of the operand
      becomes dimension broadcast_dimensions[i] of the result.

  Returns:
    An array containing the result.

  See Also:
    jax.lax.broadcast : simpler interface to add new leading dimensions.
  r  rq   broadcast_dimensionsr   )r:   rZ   rO   r   r   r<   r   typeofrq   r   rQ   r   r   reshardbroadcast_in_dim_pr   r   )r  rq   r  r  operand_avals        rT   r  r  
  s    ( '|5GH,ggg#e*$S1E-F% \%9NW%,E!
 D|/@/@)A$BB<#8#8L#H<<..		 	 U5\ !56 
! 
O OrV   c                p    t        j                  |       }||k(  rt        |       S t        | d||z
  z        S )z=Adds leading dimensions of ``1`` to give ``x`` rank ``rank``.r   )rZ   rO   r   r  )rS   rankrO   s      rT   broadcast_to_rankr  
  s6    	$	T\1:	1ddTk*	++rV   c               <   t        |      }t        |      }t        j                  t	        j
                  |       |      }|d}d}nHt        j                  |      }t        |      t        t        t	        j                  |                   k(  }t        |d      }|du xs" t        j                  |       j                  |k(  }t	        j
                  |       r|r|r|rt        | t              r| S t        j!                  | t        |      ||rd|      S ||      S )aa  Wraps XLA's `Reshape
  <https://www.openxla.org/xla/operation_semantics#reshape>`_
  operator.

  For inserting/removing dimensions of size 1, prefer using ``lax.squeeze`` /
  ``lax.expand_dims``. These preserve information about axis identity that may
  be useful for advanced transformation rules.

  Args:
    operand: array to be reshaped.
    new_sizes: sequence of integers specifying the resulting shape. The size
      of the final array must match the size of the input.
    dimensions: optional sequence of integers specifying the permutation order of
      the input shape. If specified, the length must match ``operand.shape``.

  Returns:
    out: reshaped array.

  Examples:
    Simple reshaping from one to two dimensions:

    >>> x = jnp.arange(6)
    >>> y = reshape(x, (2, 3))
    >>> y
    Array([[0, 1, 2],
                 [3, 4, 5]], dtype=int32)

    Reshaping back to one dimension:

    >>> reshape(y, (6,))
    Array([0, 1, 2, 3, 4, 5], dtype=int32)

    Reshaping to one dimension with permutation of dimensions:

    >>> reshape(y, (6,), (1, 0))
    Array([0, 3, 1, 4, 2, 5], dtype=int32)
  NTreshape	new_sizes
dimensionsr   )r#   r   r   r   rZ   rq   r   r  rQ   rO   r:   r  r   r   r<   	reshape_pr   )r  r  r  r  
same_shape	same_dimsr  same_shardings           rT   r  r  
  s   P !+)I)**288G+<iH*ID''
3DduU2777+;%<==I&|Y?,4' A;;w'00L@  	hhwJ9% N>>y)   8<   rV   c                v    t        j                  | |      \  } }t        j                  | |t	        |            S )as  Applies low, high, and/or interior padding to an array.

  Wraps XLA's `Pad
  <https://www.openxla.org/xla/operation_semantics#pad>`_
  operator.

  Args:
    operand: an array to be padded.
    padding_value: the value to be inserted as padding. Must have the same dtype
      as ``operand``.
    padding_config: a sequence of ``(low, high, interior)`` tuples of integers,
      giving the amount of low, high, and interior (dilation) padding to insert
      in each dimension. Negative values for ``low`` and ``high`` are allowed
      and remove elements from the edges of the array.

  Returns:
    The ``operand`` array with padding value ``padding_value`` inserted in each
    dimension according to the ``padding_config``.

  Examples:
    >>> from jax import lax
    >>> import jax.numpy as jnp

    Pad a 1-dimensional array with zeros, We'll specify two zeros in front and
    three at the end:

    >>> x = jnp.array([1, 2, 3, 4])
    >>> lax.pad(x, 0, [(2, 3, 0)])
    Array([0, 0, 1, 2, 3, 4, 0, 0, 0], dtype=int32)

    Pad a 1-dimensional array with *interior* zeros; i.e. insert a single zero
    between each value:

    >>> lax.pad(x, 0, [(0, 0, 1)])
    Array([1, 0, 2, 0, 3, 0, 4], dtype=int32)

    Pad a 2-dimensional array with the value ``-1`` at front and end, with a pad
    size of 2 in each dimension:

    >>> x = jnp.array([[1, 2, 3],
    ...                [4, 5, 6]])
    >>> lax.pad(x, -1, [(2, 2, 0), (2, 2, 0)])
    Array([[-1, -1, -1, -1, -1, -1, -1],
           [-1, -1, -1, -1, -1, -1, -1],
           [-1, -1,  1,  2,  3, -1, -1],
           [-1, -1,  4,  5,  6, -1, -1],
           [-1, -1, -1, -1, -1, -1, -1],
           [-1, -1, -1, -1, -1, -1, -1]], dtype=int32)

    Use negative padding to remove elements from the edges of an array:

    >>> x = jnp.array([1, 2, 3, 4, 5], dtype=jnp.int32)
    >>> lax.pad(x, 0, [(-1, -2, 0)])
    Array([2, 3], dtype=int32)
  padding_config)r   r   pad_pr   r   )r  padding_valuer  s      rT   padr  
  s6    r  55g}M'=	G]5;P	QQrV   c                B    t         j                  | t        |            S )zaWraps XLA's `Rev
  <https://www.openxla.org/xla/operation_semantics#rev_reverse>`_
  operator.
  r  )rev_pr   r   r  r  s     rT   revr  "  s    
 
Gj(9	::rV   c                f    t        j                  | ||      \  } }}t        j                  | ||      S )aE  Selects between two branches based on a boolean predicate.

  Wraps XLA's `Select
  <https://www.openxla.org/xla/operation_semantics#select>`_
  operator.

  In general :func:`~jax.lax.select` leads to evaluation of both branches, although
  the compiler may elide computations if possible. For a similar function that
  usually evaluates only a single branch, see :func:`~jax.lax.cond`.

  Args:
    pred: boolean array
    on_true: array containing entries to return where ``pred`` is True. Must have
      the same shape as ``pred``, and the same shape and dtype as ``on_false``.
    on_false: array containing entries to return where ``pred`` is False. Must have
      the same shape as ``pred``, and the same shape and dtype as ``on_true``.

  Returns:
    result: array with same shape and dtype as ``on_true`` and ``on_false``.
  )r   r   
select_n_pr   )predon_trueon_falses      rT   selectr  )  s5    . !66
Hg$'	x	11rV   c                    t        |      dk(  rt        d      t        j                  | g| ^} }t	        j
                  | g| S )ax  Selects array values from multiple cases.

  Generalizes XLA's `Select
  <https://www.openxla.org/xla/operation_semantics#select>`_
  operator. Unlike XLA's version, the operator is variadic and can select
  from many cases using an integer `pred`.

  Args:
    which: determines which case should be returned. Must be an array containing
      either a boolean or integer values. May either be a scalar or have
      shape matching ``cases``. For each array element, the value of ``which``
      determines which of ``cases`` is taken. ``which`` must be in the range
      ``[0 .. len(cases))``; for values outside that range the behavior is
      implementation-defined.
    *cases: a non-empty list of array cases. All must have equal dtypes and
      equal shapes.
  Returns:
    An array with shape and dtype equal to the cases, whose values are chosen
    according to ``which``.
  r   z&select_n() must have at least one case)r   r   r   r   r  r   whichcasess     rT   select_nr  D  sH    * 	Z1_
=
>>,,U;U;-%%		'	''rV   c                    t        d |D              }|t        t        t        j                  |                   k(  rt	        | t
              r| S t        j                  | |      S )zeWraps XLA's `Transpose
  <https://www.openxla.org/xla/operation_semantics#transpose>`_
  operator.
  c              3  F   K   | ]  }t        j                  |        y wrY   )operatorindexrj   rz   s     rT   rl   ztranspose.<locals>.<genexpr>e  s     =AhnnQ'=r  )permutation)r   rQ   rZ   rO   r   r<   transpose_pr   )r  r  s     rT   rP   rP   _  sS     ===+E% 0122z'57QNG==rV   c                `    t        j                  |d      }t        j                  | |f|      S )z9Computes the index of the minimum element along ``axis``.argminaxesindex_dtype)r   r  argmin_pr   r  r)  r  s      rT   r  r  k  -     88hO+	wdW+	FFrV   c                `    t        j                  |d      }t        j                  | |f|      S )z9Computes the index of the maximum element along ``axis``.argmaxr  )r   r  argmax_pr   r  s      rT   r
  r
  q  r  rV   c                (   t        j                  |       \  }}t        j                  d|||fi       }t        j                  |      \  }}	||	k7  rt	        d| d|	       t        |      t        |      k7  r#t	        dt        |       dt        |             t        ||      }
|
rXt        j                  | xr t        j                  | }||
t        urt        |d|ini } |
g ||i |}t        ||      S t        t        j                  |      }t        ||t!        |      |	      \  }}t        j"                  | }t        j"                  | }t%        j&                  g ||||t!        |      d}t        j(                  ||      S )a  Wraps XLA's `Reduce
  <https://www.openxla.org/xla/operation_semantics#reduce>`_
  operator.

  ``init_values`` and ``computation`` together must form a `monoid
  <https://en.wikipedia.org/wiki/Monoid>`_
  for correctness. That is ``init_values`` must be an identity of
  ``computation``, and ``computation`` must be associative. XLA may exploit both
  of these properties during code generation; if either is violated the result
  is undefined.
  zreduce compz;Operands must have the same tree structure as init_values: z vs. z9Must have same total number of operands as init_values:  r  r   )computationr  r  )r   r  r   r  r   r   _get_monoid_reducerr   r  
reduce_sumr  r   rE   r   r  _variadic_reduction_jaxprr   r   reduce_pr   r  )r#  init_valuesr  r  r  flat_operandsoperand_tree
comp_debugflat_init_valuesinit_value_treemonoid_reducerr   out_sharding_dictoutflat_init_avalsr  r  s                    rT   reducer  w  s     !* 6 6x @-""=+$/#=rC*&/&<&<[&I#O_$
 %eO+<> ? ?3/00
 ]+,E#6F2G1HJ K K&{4DE.''7 ;'')9: N*$D(4 ),7:< 

I-
I
I7H
IC 	::t}}.>?O6Z!7JL(..>M113CD
-- J J)9 J{*uZ7HJC##Hc22rV   c           	           fd}t        j                  |t        j                  d ||fi             }t	        j
                  |||f      \  }}}t        d |D              rt        d      |t        |      fS )Nc                     | |      }t        |t        j                        s/t        j                  |      st	        dt        |       d|       |fS )Nz-Invalid return type from reduction function: zE
Reduction functions should only return an array.
Full return value: )r   r   r  valid_jaxtyper   r   )rS   r$  resultr  s      rT   compz_reduction_jaxpr.<locals>.comp  s\    AFvt{{+t/A/A&/I9$v, H  &x)* * 9rV   reduction_jaxprr  c              3  P   K   | ]  }t        |t        j                           y wrY   r  r  s     rT   rl   z#_reduction_jaxpr.<locals>.<genexpr>  r  r  gReduction computations can't close over Tracers. Please open an issue at https://github.com/jax-ml/jax.)	r  r  r   r  r  r  r  r  r   )r  r  r!  comp_wrappedr  r   r  s   `      rT   _reduction_jaxprr&    s     
$$%6&*D\278, ..|dD\J%F4V44
	,- - 
f	rV   c                |   t        j                  ||      }t        j                  ||f      \  }}t        j                  | |      }t        j                  ||      \  }}	t        j                  |t        |            \  }
}}t        d |D              rt        d      t        j                  |
|       |	       fS )Nr  c              3  P   K   | ]  }t        |t        j                           y wrY   r  r  s     rT   rl   z,_variadic_reduction_jaxpr.<locals>.<genexpr>  r  r  r$  )r   r  r  r  r  r   r  r  r  r   r  r  r   ClosedJaxpr)r  r  
flat_avals	aval_treer   flat_in_avalsr  r!  	flat_compr  r  r   r  s                rT   r  r    s    
 
"
"9j
9%$115%.A-	kj	9$ 55dGD)X..y%:NO%F4V44
	,- - 
		%	((*	44rV   c                   t        |      dk7  ry |\  }t        j                  |      }t        |      }t        j                  |      r|j
                  dk(  rt        j                  |      }|t        j                  k(  xs$ t        j                  |t        j                        }| t        u rt        j                  |d      rt        S d S | t        u rt        j                  |d      rt         S d S | t"        u r)|r't        j                  |t%        |            rt&        S d S | t(        u r)|r't        j                  |t+        |            rt,        S d S | t.        u r)|r't        j                  |t%        |            rt0        S d S | t2        u r't        j                  |t5        |            rt6        S d S | t8        u r't        j                  |t;        |            rt<        S d S y )NrN   ri   r   )r   r   r  r1  r  rq   to_concrete_valuerZ   bool_r   r  integerr]  equalr  rd  reduce_prodrQ  _get_bitwise_or_identity	reduce_orrM  _get_bitwise_and_identity
reduce_andrT  
reduce_xorr`   _get_max_identity
reduce_maxr^   _get_min_identity
reduce_min)	monoid_opxsrS   r  rb   ra   _is_intlikes          rT   r  r    s   W\	"!	q	$
)%	aTZZ2-

 
 
#C288#Kv'8'8

'KKC88C+Z55	c	HHS!,[6$6	j	 [((3(@(GHYRdR	k	!k88C)B5)IJZTPTT	k	!k88C)A%)HIZStS	c	88C):5)ABZLL	c	88C):5)ABZLL	rV   rb   c                J    t        j                  d      j                  |       S Nr  )rZ   r   r  r  s    rT   r6  r6    s    	"		U	##rV   c                .    t        j                  d|       S Nr   rZ   r   r  s    rT   r4  r4        	!U	rV   c                .    t        j                  d|       S rC  rD  r  s    rT   _get_sum_identityrG    rE  rV   c                .    t        j                  d|       S NrN   rD  r  s    rT   _get_prod_identityrJ    rE  rV   c                d   t        j                  | t        j                        r`t        j                  t        j
                  |       rt        j                   |       S t        j                  |       j                  |       S t        j                  | t        j                        r3t        j                  t        j                  |       j                  |       S t        j                  | t        j                        r$t        j                  dt        j                        S t        d|        )Nr  FzUnsupported dtype for max: )r   r  rZ   inexactr   supports_infinffinfor^   r1  r[   r0  r   r  s    rT   r9  r9    s    ubjj)88v2259RVVG! !v||E?R?V?V! !

+88FLL'++U33)88E288$$
25':
;;rV   c                b   t        j                  | t        j                        r_t        j                  t        j
                  |       rt        j                  |       S t        j                  |       j                  |       S t        j                  | t        j                        r3t        j                  t        j                  |       j                  |       S t        j                  | t        j                        r$t        j                  dt        j                        S t        d|        )Nr  TzUnsupported dtype for min: )r   r  rZ   rL  r   rM  rN  rO  r`   r1  r[   r0  r   r  s    rT   r;  r;    s    ubjj)88f11%8BFF! !fll5>Q>U>U! !

+88FLL'++U33)88D"((##
25':
;;rV   c               \    t        |d      }t        j                  | t        |      |      S )a  Compute the sum of elements over one or more array axes.

  Args:
    operand: array over which to sum. Must have numerical dtype.
    axes: sequence of zero or more unique integers specifying the axes over
      which to sum. Each entry must satisfy ``0 <= axis < operand.ndim``.

  Returns:
    An array of the same dtype as ``operand``, with shape corresponding
    to the dimensions of ``operand.shape`` with ``axes`` removed.

  Notes:
    Unlike :func:`jax.numpy.sum`, :func:`jax.lax.reduce_sum` does not upcast
    narrow-width types for accumulation, so sums of 8-bit or 16-bit types
    may be subject to rounding errors.

  See also:
    - :func:`jax.numpy.sum`: more flexible NumPy-style summation API, built
      around :func:`jax.lax.reduce_sum`.
    - Other low-level :mod:`jax.lax` reduction operators:
      :func:`jax.lax.reduce_prod`, :func:`jax.lax.reduce_max`, :func:`jax.lax.reduce_min`,
      :func:`jax.lax.reduce_and`, :func:`jax.lax.reduce_or`, :func:`jax.lax.reduce_xor`.
  r  )r  r  )r:   reduce_sum_pr   r   )r  r  r  s      rT   r  r  	  s,    2 '|\B,			7t<		PPrV   c                B    t         j                  | t        |            S )a  Compute the product of elements over one or more array axes.

  Args:
    operand: array over which to sum. Must have numerical dtype.
    axes: sequence of zero or more unique integers specifying the axes over
      which to sum. Each entry must satisfy ``0 <= axis < operand.ndim``.

  Returns:
    An array of the same dtype as ``operand``, with shape corresponding
    to the dimensions of ``operand.shape`` with ``axes`` removed.

  Notes:
    Unlike :func:`jax.numpy.prod`, :func:`jax.lax.reduce_prod` does not upcast
    narrow-width types for accumulation, so products of 8-bit or 16-bit types
    may be subject to rounding errors.

  See also:
    - :func:`jax.numpy.prod`: more flexible NumPy-style product API, built
      around :func:`jax.lax.reduce_prod`.
    - Other low-level :mod:`jax.lax` reduction operators:
      :func:`jax.lax.reduce_sum`, :func:`jax.lax.reduce_max`, :func:`jax.lax.reduce_min`,
      :func:`jax.lax.reduce_and`, :func:`jax.lax.reduce_or`, :func:`jax.lax.reduce_xor`.
  r  )reduce_prod_pr   r   r  r  s     rT   r3  r3  %  s    0 
		G%+		66rV   c                B    t         j                  | t        |            S )a  Compute the maximum of elements over one or more array axes.

  Args:
    operand: array over which to compute maximum.
    axes: sequence of zero or more unique integers specifying the axes over
      which to reduce. Each entry must satisfy ``0 <= axis < operand.ndim``.

  Returns:
    An array of the same dtype as ``operand``, with shape corresponding
    to the dimensions of ``operand.shape`` with ``axes`` removed.

  See also:
    - :func:`jax.numpy.max`: more flexible NumPy-style max-reduction API, built
      around :func:`jax.lax.reduce_max`.
    - Other low-level :mod:`jax.lax` reduction operators:
      :func:`jax.lax.reduce_sum`, :func:`jax.lax.reduce_prod`, :func:`jax.lax.reduce_min`,
      :func:`jax.lax.reduce_and`, :func:`jax.lax.reduce_or`, :func:`jax.lax.reduce_xor`.
  rT  )reduce_max_pr   r   rV  s     rT   r:  r:  ?      & 
		7t		55rV   c                B    t         j                  | t        |            S )a  Compute the minimum of elements over one or more array axes.

  Args:
    operand: array over which to compute minimum.
    axes: sequence of zero or more unique integers specifying the axes over
      which to reduce. Each entry must satisfy ``0 <= axis < operand.ndim``.

  Returns:
    An array of the same dtype as ``operand``, with shape corresponding
    to the dimensions of ``operand.shape`` with ``axes`` removed.

  See also:
    - :func:`jax.numpy.min`: more flexible NumPy-style min-reduction API, built
      around :func:`jax.lax.reduce_min`.
    - Other low-level :mod:`jax.lax` reduction operators:
      :func:`jax.lax.reduce_sum`, :func:`jax.lax.reduce_prod`, :func:`jax.lax.reduce_max`,
      :func:`jax.lax.reduce_and`, :func:`jax.lax.reduce_or`, :func:`jax.lax.reduce_xor`.
  rT  )reduce_min_pr   r   rV  s     rT   r<  r<  T  rY  rV   c                B    t         j                  | t        |            S )ab  Compute the bitwise OR of elements over one or more array axes.

  Args:
    operand: array over which to compute the reduction. Must have boolean
      or integer dtype.
    axes: sequence of zero or more unique integers specifying the axes over
      which to reduce. Each entry must satisfy ``0 <= axis < operand.ndim``.

  Returns:
    An array of the same dtype as ``operand``, with shape corresponding
    to the dimensions of ``operand.shape`` with ``axes`` removed.

  See also:
    - :func:`jax.numpy.bitwise_or.reduce`: more flexible NumPy-style logical
      reduction API, built around :func:`jax.lax.reduce_or`.
    - Other low-level :mod:`jax.lax` reduction operators:
      :func:`jax.lax.reduce_sum`, :func:`jax.lax.reduce_prod`, :func:`jax.lax.reduce_max`,
      :func:`jax.lax.reduce_min`, :func:`jax.lax.reduce_and`, :func:`jax.lax.reduce_xor`.
  rT  )reduce_or_pr   r   rV  s     rT   r5  r5  i  s    ( 
		'd		44rV   c                B    t         j                  | t        |            S )ad  Compute the bitwise AND of elements over one or more array axes.

  Args:
    operand: array over which to compute the reduction. Must have boolean
      or integer dtype.
    axes: sequence of zero or more unique integers specifying the axes over
      which to reduce. Each entry must satisfy ``0 <= axis < operand.ndim``.

  Returns:
    An array of the same dtype as ``operand``, with shape corresponding
    to the dimensions of ``operand.shape`` with ``axes`` removed.

  See also:
    - :func:`jax.numpy.bitwise_and.reduce`: more flexible NumPy-style logical
      reduction API, built around :func:`jax.lax.reduce_and`.
    - Other low-level :mod:`jax.lax` reduction operators:
      :func:`jax.lax.reduce_sum`, :func:`jax.lax.reduce_prod`, :func:`jax.lax.reduce_max`,
      :func:`jax.lax.reduce_min`, :func:`jax.lax.reduce_or`, :func:`jax.lax.reduce_xor`.
  rT  )reduce_and_pr   r   rV  s     rT   r7  r7        ( 
		7t		55rV   c                B    t         j                  | t        |            S )ad  Compute the bitwise XOR of elements over one or more array axes.

  Args:
    operand: array over which to compute the reduction. Must have boolean
      or integer dtype.
    axes: sequence of zero or more unique integers specifying the axes over
      which to reduce. Each entry must satisfy ``0 <= axis < operand.ndim``.

  Returns:
    An array of the same dtype as ``operand``, with shape corresponding
    to the dimensions of ``operand.shape`` with ``axes`` removed.

  See also:
    - :func:`jax.numpy.bitwise_xor.reduce`: more flexible NumPy-style logical
      reduction API, built around :func:`jax.lax.reduce_xor`.
    - Other low-level :mod:`jax.lax` reduction operators:
      :func:`jax.lax.reduce_sum`, :func:`jax.lax.reduce_prod`, :func:`jax.lax.reduce_max`,
      :func:`jax.lax.reduce_min`, :func:`jax.lax.reduce_and`, :func:`jax.lax.reduce_or`.
  rT  )reduce_xor_pr   r   rV  s     rT   r8  r8    r`  rV   r  c                     y rY   ri   r  r!  	is_stablenum_keyss       rT   sortrg    s    >ArV   c                     y rY   ri   rd  s       rT   rg  rg    s    JMrV   c           	        t        | t              rt        |       dk(  rt        d      d|cxk  rt        |       k  sn t	        d|dt        |             t        |t        | d   j                              }t        j                  |  } t        t        j                  | |||d      S |dk7  rt	        d|d      t        |t        | j                              }t        j                  | ||d      d   S )av  Wraps XLA's `Sort
  <https://www.openxla.org/xla/operation_semantics#sort>`_ operator.

  For floating point inputs, -0.0 and 0.0 are treated as equivalent, and NaN values
  are sorted to the end of the array. For complex inputs, the sort order is
  lexicographic over the real and imaginary parts, with the real part primary.

  Args:
    operand : Array or sequence of arrays
    dimension : integer dimension along which to sort. Default: -1.
    is_stable : boolean specifying whether to use a stable sort. Default: True.
    num_keys : number of operands to treat as sort keys. Default: 1.
      For num_keys > 1, the sort order will be determined lexicographically using
      the first `num_keys` arrays, with the first key being primary.
      The remaining operands will be returned with the same permutation.

  Returns:
    operand : sorted version of the input or inputs.
  r   z"Sort requires at least one operandrN   z	num_keys=z$ must be between 1 and len(operand)=r!  re  rf  z# must equal 1 for a single operand.)r   r   r   rp   r   rD   rq   r   r   r   sort_pr   rd  s       rT   rg  rg    s    * "
7|q:;;)S\))($ICL?KLL!)S1A1A-BCI(('2Gg'0&.0 1 1 1})($GHII!)S-?@I;;w)yST;UVWXXrV   c                    t        |t        | j                              }t        j	                  | |||d      \  }}||fS )zRSorts ``keys`` along ``dimension`` and applies the same permutation to ``values``.rN   rj  )rD   r   rq   rk  r   )keysr  r!  re  r  r  s         rT   sort_key_valrn    s>      	3tzz?;)	T6Y)VW	X$!Q	
A+rV   r)  c                   t        j                  |      rt        |      }|dk  rt        d|       t	        |t        j                  |             }t        j                  | ||      S )ai  Returns top ``k`` values and their indices along the specified axis of ``operand``.

  Args:
    operand: N-dimensional array of non-complex type.
    k: integer specifying the number of top entries.
    axis: optional integer specifying the axis along which to compute the top
      ``k`` entries. Default is -1, indicating the last axis.

  Returns:
    A tuple ``(values, indices)`` where

    - ``values`` is an array containing the top k values along the last axis.
    - ``indices`` is an array containing the indices corresponding to values.

  ``values[..., i, ...]`` is the ``i``-th largest entry in ``operand`` along the
  specified axis, and its index is ``indices[..., i, ...]``.

  If two elements are equal, the lower-index element appears first.

  See also:
    - :func:`jax.lax.approx_max_k`
    - :func:`jax.lax.approx_min_k`

  Examples:
    Find the largest three values, and their indices, within an array:

    >>> x = jnp.array([9., 3., 6., 4., 10.])
    >>> values, indices = jax.lax.top_k(x, 3)
    >>> values
    Array([10.,  9.,  6.], dtype=float32)
    >>> indices
    Array([4, 0, 2], dtype=int32)
  r   -k argument to top_k must be nonnegative, got r  r)  )	r   is_constant_dimr   r   rD   rZ   rO   top_k_pr   )r  r  r)  s      rT   top_kru    s`    D 
!AAU
DQCH
II	4!1	2$	g	..rV   c                    |S )z,Deprecated. Ignores ``x`` and returns ``y``.ri   r#  s     rT   tie_inrw    s    	
(rV   r   c                  t        |       } t        j                  |      r/d}t        |j	                  t        j                  |                  |!t        j                  |      }t        |      }nYt        j                  |t
        j                        r|j                  j                  | ||      S d}t        j                  |d      }t        |||      }|t        |t              spt        |t         j"                        rV|j$                  rJ|j'                  |       }t)        ||      j+                  d      t!        j,                  | |fd|      S ||j$                  st)        || |      S t)        ||       S )a  Returns an array of `shape` filled with `fill_value`.

  Args:
    shape: sequence of integers, describing the shape of the output array.
    fill_value: the value to fill the new array with.
    dtype: the type of the output array, or `None`. If not `None`, `fill_value`
      will be cast to `dtype`.
    sharding: an optional sharding specification for the resulting array,
      note, sharding will currently be ignored in jitted mode, this might change
      in the future.
  zDfull must be called with scalar fill_value, got fill_value.shape {}.Ffullr   c                    S rY   ri   )r   shards    rT   r   zfull.<locals>.<lambda>,  s    5 rV   r  r  )r#   rZ   rq   rp   formatr   r  r1  r  extended_rulesrz  r  r   r   r7   r   	ArrayImplr  shard_shaper  addressable_datamake_array_from_callback)	rq   
fill_valuerb   r   rs   r   
fill_dtypebroadcast_shaper|  s	           @rT   rz  rz    sG    U
#%XXj
PC
CJJrxx
34
55
]&&z2I
#J0\\uj%88I99%HJ$ZYG*:h#EU__-(2G2G**51Oj/2E""1%E))x
< < ("7"7ZX>>Z''rV   c                8   t        | t              sJ t        j                  | j                  t        j
                        r0| j                  j                  j                  | j                        }n`| j                  t        j                  k(  r"t        j                  d| j                        }n!t        d| j                  | j                        }t        || j                  | j                        }t!        j"                  |t%        | j&                              S )Nri   r  r   r  )r   r!   r   r  rb   r~  r  zeror  rZ   zerosr   r   r  rq   r   r   pvaryr   vma)r  scalar_zeror  s      rT   zeros_like_shaped_arrayr  3  s    	D+	&&	&tzz6??3**##((4KzzV]]"((2TZZ0K'4::t~~FK+tzzF#	Ctxx	))rV   c                j    t        j                  | j                        }t        j                  |      S rY   )r   zeros_like_aval
inner_avalr   new_ref)r  ra   s     rT   zeros_like_abstract_refr  ?  s%    0#	c	rV   c                    t        | |fd      S )z[Wraps XLA's `Iota
  <https://www.openxla.org/xla/operation_semantics#iota>`_
  operator.
  r   )broadcasted_iota)rb   sizes     rT   iotar  H  s    
 
%$!	,,rV   c                   t        j                  | d      } t        |      }t        j                  t
        |d      }t        |d      }t        j                  | |||      S )z$Convenience wrapper around ``iota``.r  z*dimension argument of lax.broadcasted_iotarb   rq   r!  r   )	r   r  r#   r   concrete_or_errorr   r:   iota_pr   )rb   rq   r!  r  s       rT   r  r  O  sh     
2
25:L
M%
U
#%$$	9BD)&|5GH,	5(< 
 
A ArV   c           	     L   t        |t        j                  d      }t        j                  | d      } t        t        t        t        j                  |d      t        j                  |            t        t        j                  |d            }t        j                  || dd      S )z:Like numpy.eye, create a 2D array with ones on a diagonal.z"argument `offset` of jax.numpy.eyeeyer   rN   FNr  )
rd   rZ   int32r   r  rz  r]  r  r  r   )rb   rq   offsetbool_eyes       rT   _eyer  Z  s    #FBHH$HJ&

2
25%
@%$RXXua8"((6:JK 5!46(		$	$X%.2 
% 
4 4rV   c                   t        t        |      }t        j                  | d      } t	        t        j                  ||            }t        t        |            D cg c]  }t        t
        j                  ||       }}t        |dd |dd       D cg c]  \  }}t        ||       }}}t        j                  t        t         j"                  |      | dd      }	t%        |	||      S c c}w c c}}w )zAThis utility function exists for creating Kronecker delta arrays.deltaNr  rN   Fr  )r   r   r   r  r   rZ   takerQ   r   r  uint32r   rz  r  r   _reducer  and_r  )
rb   rq   r  
base_shapeiiotasi1i2eyesr   s
             rT   _deltar  d  s    	S$$

2
25'
B%RWWUD)**#j/*, BIIz15 ,% ,#&uSbz59#=	>R"R*	>$	>!&&hmmT"eu ' & 
&%	..,	>s   "C,C1c           	     "   t        t        j                  |            }t        j                  |j
                  t        j                        st        d|      t        j                  |d      }t        j                  |j
                        j                  t        j                  |      j                  k  sIt        j                  |j
                        j                  t        j                  |      j                  kD  r#t        j
                  t        j                        }t        j                  | d      } t!        t#        t%        ||d      |j'                  |            t%        ||d            }t(        j+                  || dd	      S )
z=Like numpy.tri, create a 2D array with ones below a diagonal.zoffset must be an integer, got Tsignedtrir   rN   FNr  )r   r   dimension_as_valuer   r  rb   rZ   r1  rp   	lax_utilsint_dtype_for_shaper[   r^   r`   int64r  r  r]  r  r  r  r   )rb   rq   r  shape_dtypebool_tris        rT   _trir  q  s$   4**623&			6<<	4
5fZ@
AA--eDA+hhv||  288K#8#<#<<	&,,		#	#bhh{&;&?&?	?((288$K

2
25%
@%$[%;MM+.0 eQ79( 
 	$	$X%.2 
% 
4 4rV   c                :    fdt        j                  |       S )a
  Stops gradient computation.

  Operationally ``stop_gradient`` is the identity function, that is, it returns
  argument `x` unchanged. However, ``stop_gradient`` prevents the flow of
  gradients during forward or reverse-mode automatic differentiation. If there
  are multiple nested gradient computations, ``stop_gradient`` stops gradients
  for all of them. For some discussion of where this is useful, refer to
  :ref:`stopping-gradients`.

  Args:
    x: array or pytree of arrays

  Returns:
    input value is returned unchanged, but within autodiff will be treated as
    a constant.

  Examples:
    Consider a simple function that returns the square of the input value:

    >>> def f1(x):
    ...   return x ** 2
    >>> x = jnp.float32(3.0)
    >>> f1(x)
    Array(9.0, dtype=float32)
    >>> jax.grad(f1)(x)
    Array(6.0, dtype=float32)

    The same function with ``stop_gradient`` around ``x`` will be equivalent
    under normal evaluation, but return a zero gradient because ``x`` is
    effectively treated as a constant:

    >>> def f2(x):
    ...   return jax.lax.stop_gradient(x) ** 2
    >>> f2(x)
    Array(9.0, dtype=float32)
    >>> jax.grad(f2)(x)
    Array(0.0, dtype=float32)

    This is used in a number of places within the JAX codebase; for example
    :func:`jax.nn.softmax` internally normalizes the input by its maximum
    value, and this maximum value is wrapped in ``stop_gradient`` for
    efficiency. Refer to :ref:`stopping-gradients` for more discussion of
    the applicability of ``stop_gradient``.
  c                    t        j                  t        j                  |       j                  t         j
                        r| S t        | t        j                        r | j                        S t        j                  j                  |       S rY   )r   r  r   r  rb   r~  r   r&   	JVPTracerprimalr   stop_gradient_pr   rS   stops    rT   r  zstop_gradient.<locals>.stop  s^    q)//Ah	Ar||	$!((^$$))!,,rV   )r   tree_mapr  s    @rT   stop_gradientr    s    Z- 
		D!	$$rV   c                    t        j                  t        j                  |d      }t        j                  t        j                  |d      }t        j                  | ||      S )zqWraps XLA's `ReducePrecision
  <https://www.openxla.org/xla/operation_semantics#reduceprecision>`_
  operator.
  z.exponent_bits argument of lax.reduce_precisionz.mantissa_bits argument of lax.reduce_precision)exponent_bitsmantissa_bits)r   r  r  r  reduce_precision_pr   r  r  r  s      rT   reduce_precisionr    s]     ((NNM#SU-((NNM#SU-		 	 /< 
! 
> >rV   c                    t        j                  |       t        t        fd|D                    }|st	        | t
              r| S t        j                  | |      S )z6Squeeze any number of size 1 dimensions from an array.c              3  6   K   | ]  }t        |        y wrY   )rD   )rj   r  rO   s     rT   rl   zsqueeze.<locals>.<genexpr>  s     K1-a6K   r  )rZ   rO   r   sortedr   r<   	squeeze_pr   )r   r  rO   s     @rT   squeezer    sI    	$VK
KKL*	
5%0L	*	55rV   c                ,   t        t        |            t        |      k7  rt        d|       t        j                  |       t        |      z   }|D cg c]  }t        ||       }}t        t        |            t        |      k7  rt        d|       t        |      }t        t        j                  |             }t        |      D ]  }|j                  |d        t        |      D cg c]	  }||vs| }}t        | ||      S c c}w c c}w )z5Insert any number of size 1 dimensions into an array.z"repeated axis in lax.expand_dims: rN   )r   setr   rZ   rO   rD   	frozensetr   rq   r  insertrQ   r  )r   r  ndim_outr  r  dims_setr   broadcast_dimss           rT   expand_dimsr    s    ZS_,
9*F
GGWWU^c*o-(2<	=Q
Ax
(	=$	=T^s4y 
9$@
AAt_(bhhuo&,( a1$XD!!82CAD.D	%~	>> 
> Es   D/	D9Dc                   |t        j                  |       n
t        |      }|du xr t        j                  |       }|t        |      n
t        |       }t        j                  |t        j                        r|j                  j                  |||      S |3|1t        | t        j                        r| j                  j                  }n|du xr t        | t        j                         xry t        | d      xrk | j                  duxr[ | j                  j                   xs t#               j$                   xr, t'        | dd      xr | xr |t        j                  |       k(  }|r| j                  }t        |t)        |||      |      }t*        j,                  j.                  r<t        j0                  |t3        t        j4                  |       j6                              }|S )a  Create a full array like np.full based on the example array `x`.

  Args:
    x: example array-like, used for shape and dtype information.
    fill_value: a scalar value to fill the entries of the output array.
    dtype: optional, a dtype parameter for the output ndarray.
    shape: optional, a shape parameter for the output ndarray.
    sharding: an optional sharding specification for the resulting array.
      If not specified, the output will have the same sharding as the input,
      with a few exceptions/limitations in particular:
      1. Sharding is not available during tracing, thus this will rely on jit.
      2. If x is weakly typed or uncommitted, will use default sharding.
      3. Shape is not None and is different from x.shape, default will be used.

  Returns:
    An ndarray with the same shape as `x` with its entries set equal to
    `fill_value`, similar to the output of np.full.
  Nr   
_committedTrx  )rZ   rq   r#   r   r  r1  r  r~  r  rz  r   r   r  r  r   r  r  r.   emptyr  r   r   
_check_vmar  r  r   r  r  )	rS   r  rb   rq   r   
fill_shaper   use_x_shardingra   s	            rT   	full_liker    s   * $mrxx{1CE1J*tm9 6 6q 9) ,&-&)%ufoo.<<ZU;;%-Jq$++,FvvH
 	D 
	& 1dkk**	
	&
 Az"
	& JJd"
	& ZZ$$E,=,?,E,E(E
	& A|T*
	& M
	& "((1+%  hZ.z5)L	 # **S%A 2 23
4C	*rV   c           	     P   t        ||      j                  t        | j                              \  }}}||k  rt	        d| j                   d| d| d      t        j                  | j                  ||       }| j                  d| |fz   | j                  |d z   }t        | |      S )a  Collapses dimensions of an array into a single dimension.

  For example, if ``operand`` is an array with shape ``[2, 3, 4]``,
  ``collapse(operand, 0, 2).shape == [6, 4]``. The elements of the collapsed
  dimension are laid out major-to-minor, i.e., with the lowest-numbered
  dimension as the slowest varying dimension.

  Args:
    operand: an input array.
    start_dimension: the start of the dimensions to collapse (inclusive).
    stop_dimension: the end of the dimensions to collapse (exclusive). Pass None
      to collapse all the dimensions after start.

  Returns:
    An array where dimensions ``[start_dimension, stop_dimension)`` have been
    collapsed (raveled) into a single dimension.
  z,Invalid dimension range passed to collapse: [:]N)sliceindicesr   rq   r   mathprodr  )r  start_dimensionstop_dimensionlohir   r  r   s           rT   collapser    s    & O^4<<S=OP)"b!"W
CGMM?)>*:!= > >	7==B'	($mmCR D7*W]]23-??)	)	$$rV   c                   t        | j                  |j                        dk  r/t        dj                  | j                  |j                              | j                  |j                  k7  r/t        dj                  | j                  |j                              | j                  dz
  f}|j                  dz
  f}t	        t        | j                  dz
              }t        | |||f||ff|      S )zBatch matrix multiplication.rM   z9Arguments to batch_matmul must be at least 2D, got {}, {}z9Arguments to batch_matmul must have same ndim, got {}, {}rN   r  )_minrO   r   r}  r   rQ   r  )r  r  r  r  r  batchs         rT   batch_matmulr  6  s     
#((CHH!
PfSXXsxx02 2XX
PfSXXsxx02 2((Q,,((Q,,
chhl#
$%	S#| <uenM(
* *rV   c                ,    t         j                  |       S )z Elementwise square: :math:`x^2`.)square_pr   rR   s    rT   squarer  I  s    	q	rV   c                    t        | d      S )z*Elementwise reciprocal: :math:`1 \over x`.r  )r=  rR   s    rT   
reciprocalr  M  s    	Q	rV   c                0    t         j                  | |      S )a  Elementwise tangent: :math:`\mathrm{tan}(x)`.

  This function lowers directly to the `stablehlo.tangent`_ operation.

  Args:
    x: input array. Must have floating-point or complex type.
    accuracy: Optional `lax.Tolerance` or `lax.AccuracyMode` object that
      selects the implementation of the op based on the requested accuracy. If
      the implementation cannot satisfy the requested tolerance, the
      compiler will return an error. If mode is specified and there are no
      multiple implementations available, the default implementation will be
      used.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    tangent.

  See also:
    - :func:`jax.lax.cos`: elementwise cosine.
    - :func:`jax.lax.sin`: elementwise sine.
    - :func:`jax.lax.atan`: elementwise arc tangent.
    - :func:`jax.lax.atan2`: elementwise 2-term arc tangent.

  .. _stablehlo.tangent: https://openxla.org/stablehlo/spec#tangent
  r  )tan_pr   r  s     rT   tanr  Q  s    6 
A	))rV   c                ,    t         j                  |       S )a  Elementwise arc sine: :math:`\mathrm{asin}(x)`.

  This function lowers directly to the ``chlo.asin`` operation.

  Args:
    x: input array. Must have floating-point or complex type.

  Returns:
    Array of the same shape and dtype as ``x`` containing the
    element-wise arc sine.

  See also:
    - :func:`jax.lax.sin`: elementwise sine.
    - :func:`jax.lax.acos`: elementwise arc cosine.
    - :func:`jax.lax.atan`: elementwise arc tangent.
  )asin_pr   rR   s    rT   asinr  n      $ 
QrV   c                ,    t         j                  |       S )a  Elementwise arc cosine: :math:`\mathrm{acos}(x)`.

  This function lowers directly to the ``chlo.acos`` operation.

  Args:
    x: input array. Must have floating-point or complex type.

  Returns:
    Array of the same shape and dtype as ``x`` containing the
    element-wise arc cosine.

  See also:
    - :func:`jax.lax.cos`: elementwise cosine.
    - :func:`jax.lax.asin`: elementwise arc sine.
    - :func:`jax.lax.atan`: elementwise arc tangent.
  )acos_pr   rR   s    rT   acosr    r  rV   c                ,    t         j                  |       S )a  Elementwise arc tangent: :math:`\mathrm{atan}(x)`.

  This function lowers directly to the ``chlo.atan`` operation.

  Args:
    x: input array. Must have floating-point or complex type.

  Returns:
    Array of the same shape and dtype as ``x`` containing the
    element-wise arc tangent.

  See also:
    - :func:`jax.lax.tan`: elementwise tangent.
    - :func:`jax.lax.acos`: elementwise arc cosine.
    - :func:`jax.lax.asin`: elementwise arc sine.
    - :func:`jax.lax.atan2`: elementwise 2-term arc tangent.
  )atan_pr   rR   s    rT   atanr     r   rV   c                ,    t         j                  |       S )a  Elementwise hyperbolic sine: :math:`\mathrm{sinh}(x)`.

  This function lowers directly to the ``chlo.sinh`` operation.

  Args:
    x: input array. Must have floating-point or complex type.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    hyperbolic sine.

  See also:
    - :func:`jax.lax.asinh`: elementwise inverse hyperbolic sine.
    - :func:`jax.lax.cosh`: elementwise hyperbolic cosine.
    - :func:`jax.lax.tanh`: elementwise hyperbolic tangent.
  )sinh_pr   rR   s    rT   sinhr    r  rV   c                ,    t         j                  |       S )a  Elementwise hyperbolic cosine: :math:`\mathrm{cosh}(x)`.

  This function lowers directly to the ``chlo.cosh`` operation.

  Args:
    x: input array. Must have floating-point or complex type.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    hyperbolic cosine.

  See also:
    - :func:`jax.lax.acosh`: elementwise inverse hyperbolic cosine.
    - :func:`jax.lax.sinh`: elementwise hyperbolic sine.
    - :func:`jax.lax.tanh`: elementwise hyperbolic tangent.
  )cosh_pr   rR   s    rT   coshr    r  rV   c                ,    t         j                  |       S )a  Elementwise inverse hyperbolic sine: :math:`\mathrm{asinh}(x)`.

  This function lowers directly to the ``chlo.asinh`` operation.

  Args:
    x: input array. Must have floating-point or complex type.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    inverse hyperbolic sine.

  See also:
    - :func:`jax.lax.acosh`: elementwise inverse hyperbolic cosine.
    - :func:`jax.lax.atanh`: elementwise inverse hyperbolic tangent.
    - :func:`jax.lax.sinh`: elementwise hyperbolic sine.
  )asinh_pr   rR   s    rT   asinhr	        $ 
arV   c                ,    t         j                  |       S )a  Elementwise inverse hyperbolic cosine: :math:`\mathrm{acosh}(x)`.

  This function lowers directly to the ``chlo.acosh`` operation.

  Args:
    x: input array. Must have floating-point or complex type.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    inverse hyperbolic cosine.

  See also:
    - :func:`jax.lax.asinh`: elementwise inverse hyperbolic sine.
    - :func:`jax.lax.atanh`: elementwise inverse hyperbolic tangent.
    - :func:`jax.lax.cosh`: elementwise hyperbolic cosine.
  )acosh_pr   rR   s    rT   acoshr    r
  rV   c                ,    t         j                  |       S )a  Elementwise inverse hyperbolic tangent: :math:`\mathrm{atanh}(x)`.

  This function lowers directly to the ``chlo.atanh`` operation.

  Args:
    x: input array. Must have floating-point or complex type.

  Returns:
    Array of the same shape and dtype as ``x`` containing the element-wise
    inverse hyperbolic tangent.

  See also:
    - :func:`jax.lax.acosh`: elementwise inverse hyperbolic cosine.
    - :func:`jax.lax.asinh`: elementwise inverse hyperbolic sine.
    - :func:`jax.lax.tanh`: elementwise hyperbolic tangent.
  )atanh_pr   rR   s    rT   atanhr    r
  rV   c                      j                   dk(  rt        d      t         j                  d         }t	        d  j                  D              r fdt        |      D        S  fdt        |      D        S )Nr   ziteration over a 0-d arrayc              3  P   K   | ]  }t        |t        j                           y wrY   r  r  s     rT   rl   z_iter.<locals>.<genexpr>  s     
<!:a%
<r  c              3  N   K   | ]  }t        j                  |d         ywF)keepdimsN)r+   dynamic_index_in_dimrj   r  tracers     rT   rl   z_iter.<locals>.<genexpr>  s+      ! **61uEE !   "%c              3  N   K   | ]  }t        j                  |d         ywr  )r+   index_in_dimr  s     rT   rl   z_iter.<locals>.<genexpr>  s#     P!g""61u==Pr  )rO   rp   r   rq   r  rQ   )r  ns   ` rT   _iterr    sg    [[A
0
11FLLOA

<v||
<<!Qx! ! QuQxPPrV   c                    t        | d      S rC  )r  rR   s    rT   zeros_like_arrayr  "  s    	1arV   c                
   t        t        j                  |       x}t              rSt	        j
                  |j                  t        j                        r%t        j                  j                  t        | |      S t        | |      S rY   )
r   r   r  r!   r   r  rb   r~  r  r]  )rS   r$  r   s      rT   _add_arraysr!  &  sW    dmmA&&41<<E1a((	QrV   c                      fdS )Nc                 .    t        j                        S rY   )rZ   rb   )r  r  rb   s     rT   r   z<lambda>.<locals>.<lambda>6  s    "((5/ rV   ri   r  s   `rT   r   r   6  s    9 rV   c                h    t        j                  t        j                  d|             j                  S Nri   )rZ   r5  r  rb   )rb   r  s     rT   r   r   7  s     BFF288B3F,G,M,M rV   c                      yNFri   r  s     rT   r   r   9      rV   c           	         j                   t        j                  k(  rt        d| d      t	        fd|D              sKd}t        j                         }d |D        }t        |j                  ||dj                  |                  |snj                   t        j                  t        j                  t        j                  t        j                  fv r$t        | dt        j                          d       | j                   fi |S )	NCalled a   with a float0 array. float0s do not support any operations by design, because they are not compatible with non-trivial vector spaces. No implicit dtype conversion is done. You can use np.zeros_like(arr, dtype=np.float) to cast a float0 array to a regular zeros array. 
If you didn't expect to get a float0 you might have accidentally taken a gradient with respect to an integer argument.c              3  ^   K   | ]$  }t        j                  j                  |       & y wrY   r   r  rb   rj   r  r  s     rT   rl   z"unop_dtype_rule.<locals>.<genexpr>G  s"     G!Vtzz1-G   *-z@{} does not accept dtype {}. Accepted dtypes are subtypes of {}.c              3  4   K   | ]  }|j                     y wrY   r   r  s     rT   rl   z"unop_dtype_rule.<locals>.<genexpr>J  s     >!**>   r   z does not accept dtype z. Support for narrow-width integers is platform-dependent and limited to a few specific operations, e.g. basic arithmetic and type casting.)rb   r   r  rp   r  r0   r}  r   uint2int2uint4int4)	result_dtypeaccepted_dtypesr   r  supports_narrow_intsr  rs   typenameaccepted_typenamess	      `     rT   unop_dtype_ruler;  <  s    	ZZ6== 

$ @ 	@A A 
GG	G
LCtzz*H>o>
CJJtXtyy9K/LM
NN
DJJ6<<fll\b\g\g2h$h
tf3ODJJ4O3P Q4 4 5 5 
djj	+F	++rV   c                    | j                  | j                  j                  |j                  j                  j                              S Nreducedr   r   r   r   r?  )out_sr  r  s      rT   unop_reduced_rulerB  S  s5    	5::,,T]]5G5G5O5O,P	QQrV   c           	         t        t        | |||      }t        t        d      ||t        d      t        d      t              }t        j                  |       |S )Nr8  rq   r   r  sharding_rulevma_rulereduced_rule)r   r;  r2   _attrgetterrB  r'   defvectorized)r6  r7  r   r8  
dtype_ruleprims         rT   unoprM  V  sU    ot,@B*	K0*d*5j*A%0%7):
<$ 	+rV   c                      fdS )Nc                    t        |       S rY   )r  )rS   r  r   s     rT   r   z<lambda>.<locals>.<lambda>b  s    wq$/? rV   ri   r;  s   `rT   r   r   b  s    ? rV   )require_sameallow_extended_dtypec          
        t        |      t        |      k(  s	J ||f       t        |      D ]  \  }|r%t        j                  t        j
                        r-||   }t        fd|D              rGj                  t        j                  k(  rt        d| d| d      d}	t        j                        }
dj                  d |D              }t        |	j                  ||
|||             |rt        |g|   | |i |S )Nc              3  ^   K   | ]$  }t        j                  j                  |       & y wrY   r,  r-  s     rT   rl   z$naryop_dtype_rule.<locals>.<genexpr>l  s"     ?Av  Q/?r.  r*  z with a float0 at position ap  . float0s do not support any operations by design, because they are not compatible with non-trivial vector spaces. No implicit dtype conversion is done. You can use np.zeros_like(arr, dtype=np.float) to cast a float0 array to a regular zeros array. 
If you didn't expect to get a float0 you might have accidentally taken a gradient with respect to an integer argument.z^{} does not accept dtype {} at position {}. Accepted dtypes at position {} are subtypes of {}.r   c              3  4   K   | ]  }|j                     y wrY   r0  r  s     rT   rl   z$naryop_dtype_rule.<locals>.<genexpr>z  s     8Qajj8r1  )r   	enumerater   rb   r   r  r  r  rp   r0   r   r}  check_same_dtypes)r6  r7  r   rP  rQ  r   r  r  typesrs   r9  	typenamesr  s               @rT   naryop_dtype_rulerY  e  s   	Us?+	+Ee_-EE	+5! Ega
4::v7K7K LAE???	v}}	$dV6qc :D DE 	ED"4::.II8%88	

41aCDD'E( $T2E2	u	'	''rV   c                t    |D cg c]  }|j                   s|j                    }}|syt        |d| iS c c}w )Nri   r   )rq   r   )r   r   r  ru   s       rT   broadcasting_shape_ruler[    s:    #(74DJJDJJ7&7			2T	22 8s   55c                   d }|D ]  }|j                   |j                   j                  j                  r1|H||j                   j                  k7  r/t        j                  d| d|j                   j                         |j                   j                  } |
t               n|}|D cg c]  }|j                  s|j                   }}|st        |t                     S t        |D ch c]  }t        |       c}      dk7  rHd}t        |j                  | dj                  t        t        t        t        |                              |D cg c]%  }|j                  s|j                   j                   ' }}d gt        |d         z  }	t#        t%        t%        | t%        |             D ]  \  }
\  }t'        fddd  D              r	d   |	|
<   )t%        |      D cg c]  \  }}t        j(                  |d      r||! c}}sd |	|
<   ht'        fddd  D              r	d   |	|
<   D ]f  }|	|
   |||	|
<   |	|
   ||	|
   |k7  s"t        j                  |  d	dj                  t        t        t        t        |                   d
        t        |t        |	       S c c}w c c}w c c}w c c}}w )Nz3Mesh for all inputs should be equal. Got one mesh: z and another mesh: rN   z7{}: arrays must have same number of dimensions, got {}.r   r   c              3  .   K   | ]  }d    |k(    ywrh   ri   )rj   r   sss     rT   rl   z-broadcasting_sharding_rule.<locals>.<genexpr>  s     
&!2a5A:
&   c              3  .   K   | ]  }d    |k(    ywrh   ri   )rj   r   non_trivial_ss     rT   rl   z-broadcasting_sharding_rule.<locals>.<genexpr>  s     @}Q1$@r_  z. got incompatible shardings for broadcasting: rn   )r   meshr  r   ShardingTypeErrorr-   rq   r8   r   r   rp   r}  r   r   r   r   r   rU  r   ro   r   )r   r   rb  r   r  ru   rq   rs   specsresult_specsr  r{   r   rz   ra  r^  s                 @@rT   r   r     s   	$ azzajjoo&;&;		dajjoo5$$A$ Hjjoo.01 	1 ZZ__d !%		$$#(74DJJDJJ7&7	qs##&	)#e*	)*a/
CC
CJJtTYYs3E68J/K%LM
NN$)
5qQWW1::??
5%
5#fQi.(,s3;V=> >ka"b

&r!"v
&& 1l1o%(R[ KTQ#44Q:qy  KmQ@mAB.?@@'*Q 	>A!_$LOQ+Q1$((&F99Sc%&789:!=> >	>>* 
tQ-	..? 8 
* 6Ks$   ,J;>J;-K K'K,$K
c                   |D cg c]  }|j                   s| }}|D cg c]  }|j                  j                   }}|D ch c]  }|j                  s|j                   }}t	        |      dkD  rt        j                  d|       |r|n
t               f\  }|r|D ]  }|j                  j                  }t        |      }	|j                  j                  |z  rt        j                  d| d|       t        |	      |z  sgt        j                  d| d|        | j                  | j                  j                  |            S c c}w c c}w c c}w )NrN   zCAll inputs should be reduced across the same mesh axes. Got specs: z_Inputs cannot be replicated on the same axes that another input is reduced on. Got input spec: z and reduced spec: zInputs cannot be sharded on the same axes that another input is reduced on. Reshard the input which is reduced to be sharded on the mesh axes it is reduced on via `jax.sharding.reshard(inp, jax.P(...))`. Got input spec: r>  r   )rq   r   r   r?  r   r   rc  r  r;   replicated_axesr   )
rA  r   paramsr   non_empty_avalsrd  r   reduced_spec	reduced_s	flat_specs
             rT   nary_reduced_rulerm    sh    %11Q1/1$3
4q1::??
4%
4%*8aii!))8,8

 
 	>	   ,|)+*) Q
**//aq/i	
	#	#i	/$$//0c1DYKQR 	R 
9			)$$. /0S0CI;PQ 	QQ 
5::,,Y,?	@@/ 2
48s   EEEEEc           
         t        t        | ||||      }t        t        |      }t        t        |      }	t	        ||||	t        t
        j                  |      |t              }
t        j                  |
       |
S )N)rQ  rP  rF  rG  unreduced_rulerH  )
r   rY  r[  r   r2   r   standard_vma_rulerm  r'   defbroadcasting)r6  r7  r   rQ  require_same_dtypesrp  rH  rK  
shape_rulerF  rL  s              rT   naryopru    sv    (,,@$79* .5*4d;-	*d-t--t4#2C
E$ 4 	+rV   c           
     J    t         t              st        d      t        j                  |      }t        j                   j                  |      r. j                  t        j                  |      j                  k(  r|S  j                  r#t        |      t         j                        k(  sJ  j                  s't        |t        t        t        |                        S t        t        | j                              D cg c]   \  }\  }}t        j                  ||      s|" }}}}t         j"                  j$                  rt'         fd|D              sJ |rt        ||      n|}t)        | j                   j+                         j                        S c c}}}w )Nz7transpose with implicit broadcasting of unshaped valuesc              3  B   K   | ]  }j                   |   d k(    ywrN   Nrq   )rj   r  r  s     rT   rl   z_unbroadcast.<locals>.<genexpr>  s     2A!#2s   r  )r   r!   rp   rZ   rq   r   r   r   r  r   r  r   rQ   rU  r   r   r   enable_checksr  ro   r  to_cotangent_aval)r  rS   x_shaper  r   br  s   `      rT   _unbroadcastr~    s>   	D+	&
M
NNHHQK'
!!$**g6
mmt{{1~...HZZ3w<3tzz?::	:	aeCL1233(Wdjj)AB 0 0)!Va((A.  0D 0!!2T2222#
1dA1djjt/E/E/G/P/PQQ0s   %Fc           	     h   t        j                  |      }t        j                  ||       r|S |st	        || d      S t        t        ||             D cg c]   \  }\  }}t        j                  ||      r|" }}}}|D cg c]  }||   	 }}t	        t        ||      | |      S c c}}}w c c}w r%  )	rZ   rq   r   r   r  rU  r   r   r  )target_shaperS   r|  r  r   r}  r  squeeze_shapes           rT   _maybe_broadcastr    s    HHQK'	  ,7HA|R00(Wl)CD , ,)!Va$$Q*  ,D ,)-.AWQZ.M.GA}5|TJJ,.s   %B(B/c                   g }t        ||      D ]r  \  }}|j                  | j                  k7  rAt        |j                        t        | j                        k  s	J || f       t        j                  t        t        t        | j                        t        |j                        z
  t        | j                                          }t        d | j                  D              rIt        j                  t        j                  |       |t        j                  | j                        |      }nDt        j                  t        j                  |j                  | j                              ||      }|j                  |       u |S )zLBroadcasts HLO values with broadcast-compatible shapes to the same shape.
  c              3  P   K   | ]  }t        |t        j                           y wrY   )r   r3   Valuer  s     rT   rl   z broadcast_hlo.<locals>.<genexpr>	  s     =Z288$=r  ry  )r   rq   r   r(   dense_int_arrayr   rQ   r  r5   dynamic_broadcast_in_dimaval_to_ir_typeshape_tensorr  r   r   )aval_outr   r  r  r  argr  s          rT   broadcast_hlor    s)   
 	#ud# idCzzX^^#_HNN 33EdH5EE3!!
uS(3tzz?:C<OP
QSd	=hnn=	=**  *Chnn-t5 ""  8>>!BCS JJsO 
*rV   r  c                   ~|j                   |j                  c}\  }t        j                  ||||j                  |j
                        } | | }|r | |dt        |      i}t        j                  |||      gS )z9Lowers an elementwise operator to its MLIR equivalent.
  result_accuracy)r  r  r(   multi_broadcast_in_dimrq   r   accuracy_attrlower_with_sharding_in_types)r$  r  r  r  rh  r  r  r  s           rT   _nary_lower_hlor    s|    
 ,,(KX		$	$S$(..%-%6%6
8$ 	D	#
d
<M($;
<C

+
+Ch
?	@@rV   c                    t        | j                        }d|v r|d   |d= t        j                  | j	                  |      ||      S )Nr  rh  dictrh  r   _pp_eqnreplaceeqncontextsettingsrh  s       rT   _unary_with_accuracy_pp_ruler  $  sH    

&6fZ08z	ckkk0'8	DDrV   r   c                    t        |       gS rY   )r   )r  r  s     rT   r   r   7  s    Q rV   r   c           
        | j                   \  }t        j                  |j                  t        j
                        rmt        j                  t        j                  |t        j                  | d|      dd      t        j                  | d|      t        j                  | d|            gS t        j                  |      gS )Nr   EQUNSIGNEDrN   )r  r   r  rb   rZ   unsignedintegerr5   r  r(   compare_hlofull_like_avalr   )r  rS   x_avals      rT   _sign_lower_hlor  =  s    LL'&v||R%7%78JJD//Q?#	%CF+CF+	- . .
 ((1+rV   r   r   r   r   c                   |t         j                  u rt        j                  |      gS |t         j                  u sJ t        j
                  |      gS rY   )r   r   r5   round_nearest_afzr   round_nearest_even)r  rS   r   s      rT   _round_lowerr  W  sL    555!!!$%%n<<<<<""1%&&rV   r   r  c                    t        | |      S rY   rd  gansrS   r  s       rT   r   r   d  s    c!Sk rV   r  c                T    t        t        t        |d            t        | |            S NrM   )rd  r  _constr  s       rT   r   r   j  s    Cq!,=s1c{(K rV   c                F   | j                   \  }t        j                  t        j                  t        j
                  d      |j                              }t        j                  | ||d      }t        j                  t        j                  ||      t        |            gS )NrM   ri   r  )r  )r  r(   r  rZ   r   r  rb   r  r5   exponentialmultiplyr  )r  rS   r  r  log2s        rT   _exp2_lowerr  m  su    LL'&			"((266!9fll;	<$			sD&r	J$	oo
,,tQ
x1H
 rV   r  c                    t        | |      S rY   rg  r  rS   r  s      rT   r   r   {  s    Aq	 rV   r  c           	         |t         j                  u rt        | t        ||            S t        | t	        |t        |                  S Nr  )r   r   rd  r  r]  _oner  r  rS   r  s       rT   r   r     sD    |+++ 	As1x()  CT#Y'( rV   r  c           	     @    t        | t        |t        |                  S rY   )rg  r]  r  r  s      rT   r   r     s    #aQQ*A rV   r  c                \   |t         j                  u rht        | t        t        |d      t        t	        t        t        |d      |      |      t	        t        t        |d      |      |                        S t        t        | t        | |            t        t        |      |            S )N   rM   r  )r   r   rd  r  r  r]  ra  r  r  s       rT   r   r     s     <''' !$AF1aLVAq\1-AVAr]A.BD	
!  
SC3K #d1gs"3	4 rV   r  c                    |t         j                  u r(t        | t        |t        t	        |                        S t        | t        |t        t        |      |                  S rY   )r   r   rd  r  r   ra  r  r  s       rT   r   r     sO    <''' !$As3Q0@'A B 	QCT#Y,-	. rV   c                l    ~t        | d      }t        |t        |t        t	        |                         S rI  )r  rg  r]  r  r   )rS   r  ones      rT   logistic_implr    s,    q!#	S#c3s1v;'	((rV   multiple_resultsc           	        t        |       t        |       }}t        |t        |d            }t        |d      }t	        |      t        |      }}t        |      t        t        |            }}t        t        ||      |      t        t        t        ||      |      |      }
}	t        ||
      t        ||	      }}t        |t        t        |d      |      t        ||            S Nr   rM   r(  r,  rz  r  r  r   r  r   rg  ra  r]  rd  r  r   rS   r   r}  	a_is_zerotwosncse1me2msnhcshreims                rT   _sin_complexr    s     
a$q'Q!F1aL!)q!#q63q6b"1XuSV}s#S#$c#c#smS*A3&Gs#r3<Rb"		76!Q<4gb"o	FFrV   c                    t        j                  | j                  d   j                  t        j
                        r$t        j                  t        d      } || |      S t        t        j                  | ||      S Nr   Fr  r  )r   r  r  rb   rZ   r  r(   	lower_funr  r  r5   sine)r  rS   r  r  s       rT   _sin_loweringr    sW    s||A,,b.@.@A>>,?DQ<	3H	==rV   c                T    | \  }t         j                  ||      |t        |      d fS )Nr  c                    t        ||       S rY   r  )cos_xr  s     rT   r   z_sin_lin.<locals>.<lambda>  s    3q%= rV   )r  r   r   )nzsrS   r  nzs       rT   _sin_linr    s.    #"
**Q*
*BA
(
* *rV   r  c                0    t        | t        ||            S r  )rd  r   r  rS   r  s      rT   r   r     s    As1x/H(I rV   c           
        t        |       t        |       }}t        |t        |d            }t        |d      }t	        |      t        |      }}t        |      t        t        |            }}t        t        ||      |      t        t        t        ||      |      |      }
}	t        ||
      t        t        |      |	      }}t        |t        |t        |d            t        ||            S r  r  r  s                rT   _cos_complexr    s     
a$q'Q!F1aL!)q!#q63q6b"1XuSV}s#S#$c#c#smS*A3&Gs#r3<SWc*b"		72va|4gb"o	FFrV   c                    t        j                  | j                  d   j                  t        j
                        r$t        j                  t        d      } || |      S t        t        j                  | ||      S r  )r   r  r  rb   rZ   r  r(   r  r  r  r5   cosine)r  rS   r  r  s       rT   _cos_loweringr    sW    s||A,,b.@.@A^^L5AF#q>	S!h	??rV   r   c           	     B    t        t        | t        ||                  S r  )r   rd  r  r  s      rT   r   r     s    #c!SX-F&G"H rV   r  c           	     T    t        | t        t        |d      t        |                  S rI  )rd  r]  r  r  r  s       rT   r   r     s    c!S1vc{5S.T rV   r  c                f    t        | t        t        t        |d      t	        |                        S rI  )rd  rD  ra  r  r  r  rS   s     rT   r   r     s#    s1eCq!fQi,H&IJ rV   r  c                x    t        | t        t        t        t	        |d      t        |                              S rI  )rd  r   rD  ra  r  r  r  s     rT   r   r     s(    s1c%F1aL&)0L*M&NO rV   c                .    t        | t        | d            S rI  )r%  r  rR   s    rT   	atan_implr    s    	q&A,	rV   r   c           	     T    t        | t        t        |d      t        |                  S rI  )rg  r]  r  r  r  s     rT   r   r     s    s1c&A,q	&BC rV   r%  c                f    t        | t        |t        t        |      t        |                        S rY   )rd  rg  r]  r  r  rS   r$  s      rT   r   r     s#    #aQF1Ivay(A!BC rV   c                x    t        | t        t        |      t        t	        |      t	        |                        S rY   )rd  rg  r   r]  r  r  s      rT   r   r     s'    #aSVSF1I-F!GH rV   r  c                ,    t        | t        |            S rY   )rd  r  r  s     rT   r   r   	      s1d1g rV   r  c                ,    t        | t        |            S rY   )rd  r  r  s     rT   r   r     r  rV   r	  c                d    t        | t        t        t        |      t	        |                        S rY   )rd  rD  r]  r  r  r  s     rT   r   r     s!    AuSDG-D'E F rV   r  c                d    t        | t        t        t        |      t	        |                        S rY   )rd  rD  ra  r  r  r  s     rT   r   r     s!    s1eCq	47$;<= rV   r  c                    t        t        t        t        |      |            t	        | t        t        |      |                  S rY   )rd  r  r]  r  rg  ra  r  s     rT   r   r     s-    s:c$q'1o6As47A8OP rV   r(  c           	     V    t        | t        j                  dt        |                   gS r%  )r   rZ   r  r1  r  r   s     rT   r   r   !  s    GArxxF1I/F$G#H rV   r,  c                h    t        t        j                  dt        |             t	        |             gS r%  )r   rZ   r  r1  r   r  s     rT   r   r   %  s#    GBHHR,CSV$L#M rV   c           	        t        j                  |      st        j                  |      sJ t        j                  |      rt        j                  |      rt        |       t        j                  u r>t        j                  |j
                        t        j                  |j
                        gS t        |j
                  t        |             t        |j
                  t        t        |                   gS t        j                  |      r]t        |       t        j                  u r!t        j                  |j
                        d gS t        |j
                  t        |             d gS t        |       t        j                  u r!d t        j                  |j
                        gS d t        |j
                  t        t        |                   gS rY   )
r&   is_undefined_primalr   r   Zeror  r~  r(  r,  r   )r  rS   r$  s      rT   _complex_transpose_ruler  )  s6   				"b&<&<Q&??	?A2#9#9!#<Aw',,ll166"GLL$89916647+\!&&$s1v,-OPP	a Aw',,ll166"D))16647+T22Aw',,GLL())Lc!f677rV   c                    t        j                  d|       t        j                  dt         j                        z   j                  S r%  )rZ   r  	complex64rb   )rb   r  r  s      rT   _complex_dtyper  ;  s-    
((2u
R\\ :
:	A	AArV   r   r2  c                    t        j                  | j                  t        j                        rt        t        |       t        |              S t        | t        |             S rY   )	r   r  rb   rZ   r  r   r(  r,  _zeros)rS   kws     rT   
_conj_implr	  D  sD    qww 2 2347T!WH%%1fQi  rV   c                  t        j                  |      sJ t        |       t        j                  u r t        j                  |j
                        gS t        j                  |t        j                        rt        |       gS t        |       gS rY   )r&   r   r   r   r  r  r   r  rZ   r  r2  r(  )r  rS   r/   s      rT   _conj_transpose_ruler  N  sj    				""	"	!WLL !!b&8&89G9G9rV   r5  rD  c                    t        |      rDt        t        | t        t	        |      t        t        |t        |                                    S t        t        |t        |            | t        |             S rY   )
_iscomplex_maybe_realrd  rg  _maybe_conj_replace_zeror  r1  r  r  _zeror   r  r  rS   s      rT   _abs_jvp_ruler  ^  sc    ]s1c+a.-c6!9=>@ A B B "Qa/1c!f--rV   c                2    t        |       rt        |       S | S rY   )r  r2  rR   s    rT   r   r   e      :a=Q a rV   c                2    t        |       rt        |       S | S rY   )r  r(  rR   s    rT   r   r   f  r  rV   r@  c           	     B    t        | t        t        |d      |            S )Ng      ?)rd  rg  r  r  s       rT   r   r   i  s    s1c&C.#6N/O rV   rD  c           
     V    t        | t        t        |d      t        ||                  S )Ng      )rd  r  rg  r  s       rT   r   r   p  s     As6!T?CQK'H I rV   rG  c           
     V    t        | t        t        |d      t        |d                  S )NgUUUUUU?r  )rd  r  r=  r  s       rT   r   r   x  s%    	3vaS"!56! rV   r  c                    t        j                  | j                  d   j                  t        j
                        rt        j                  ||      gS t        j                  |      gS rC  )
r   r  r  rb   rZ   r1  r5   r  r4   r  r  rS   s     rT   _square_lower_hlor    sI    s||A,,bjj9LLA
++a.	rV   c           	     B    t        | t        t        |d      |            S r  )rd  r  r  s      rT   r   r     s    s1c&A,.B'C rV   c                h   t        j                  | j                  t        j                        r:t        j                  |j                  t        j
                        r| j                  S | j                  |j                  k(  r| j                  S t        d| j                   d|j                   d      )Nzthe first argument to pow must have an inexact dtype (float or complex), and the second argument must have an inexact or integer dtype, and two inexact dtypes must match, but got rw  z respectively.)r   r  rb   rZ   rL  r1  rp   r#  s     rT   _pow_dtype_ruler    s    ,,77NWW77N P WWIU177)>; 	< <rV   r8  )rs  c                   t        j                  |      }t        j                  ||      }|t        k(  rd}t	        ||      }t	        ||      }t        j
                  |t        j                        r|j                  |j                  k7  r8t        |j                  |j                        }t        ||      }t        ||      }t        t        |t        |d            t        |      t        t!        |      t#        |t%        |t'        |                              }n)t        |t#        |t%        |t'        |                        }t        | |      S )Nr  r   )r   rb   result_typer   r  r  rZ   r1  rq   r   r  r  rz  r  r  rd  r  r8  ra  _ones)r  r  rS   r$  y_dtyper6  rq   jacs           rT   _pow_jvp_lhsr%    s   LLO'##Aq),TL1l+!1l+!w

+ww!''qww0e
5!
$a
5!
$a
Ava|$fQi]1%s1c!U1X.>'?@BC aQAuQx()
*C	QrV   c                    t        j                  |      }t        j                  |t        j                        sJ t        t        | t        t        t        |            |            |      S rY   )	r   rb   r  rZ   rL  r  rd  r  r  )r  r  rS   r$  r#  s        rT   _pow_jvp_rhsr'    sN    LLO'			7BJJ	//	/	c!S]1-=)>%DEw	OOrV   c                X   | j                   \  }}|j                  |j                  k7  rg| j                  \  }|j                  |j                        }t	        j
                  t        j                  |      |      }| j                  ||g      } t        t        j                  | ||      S )Nr  )r  )r  rb   r  r   r5   convertr(   r  r  r  power)r  rS   r$  r  y_avalout_avals         rT   
_pow_lowerr-    s    <<.&&\\V\\!IH]]]0FD((0!4A
++/+
0C	CA	..rV   c                   t        t        t        t        z  t        z  d|       }|dk  r6t        j                  |t        j                        rt        d|  d| d      |S )Nr=  r   z>Integers cannot be raised to negative powers, got integer_pow(r   ))
r;  r   _int_float_complexr   r  rZ   r1  rp   )rS   r$  rb   s      rT   _integer_pow_dtype_ruler3    s^    
)TF]X%=}a
P%Uv  

3
 ##$#Rs!- . .	,rV   c               |    |dk(  rt        |       S t        | t        t        ||      t        ||dz
                    S Nr   rN   )r  rd  r  r=  r  s      rT   _integer_pow_jvpr6    s6    1fR#aVAq\;q!a%;P)Q"RRrV   r=  r  )rF  rG  c                   |dk(  rt        | d      S |dk  }|r| }d }|dkD  r1|dz  r|| nt        ||       }|dz  }|dkD  rt        | |       } |dkD  r1|rt        t        |d      |      S |S r5  )r  rd  rg  )rS   r$  is_reciprocalr  s       rT   _integer_powr9    s    !VQ?a%-	
A#	A1uA#c1+c!GA1u
a)a 	
A )6YsA	$>3>rV   c                  |dk(  r|}n|dk(  rt        j                  ||      }n|dk(  r+t        j                  t        j                  ||      |      }nf|dk(  r9t        j                  t        j                  | d| j
                  d         |      }n(t        j                  t        d      } || ||      \  }| j                  \  }t        j                  | ||      gS )	NrN   rM   rx  r  r   Fr  r;  )
r5   r  divider(   r  r  r  r9  r  r  )r  rS   r$  r  loweringr  s         rT   _integer_pow_loweringr=    s     !V
CAv
,,q!
CAv
,,s||Aq)1
-CBw
**T((aaA1
EC~~lUCHCa DCmm)(

+
+Ch
?	@@rV   c           	     V    t        t        | t        | d            t        |       |       S rC  )r  rz  r  r"  rR   s    rT   r   r     s     &Ava|!4eAhB rV   notandorxorrW  rZ  c                   | \  }}|\  }}t        ||      }t        |      t        |      cxu rt        j                  u r$n n!|t        j                  j	                  |      fS t        |      t        j                  u r|t        |j                  |      fS t        |      t        j                  u r|t        |j                  |      fS |t        ||      fS rY   )r]  r   r   r  from_primal_valuer  rq   primalstangentsrS   r$  xdotydot
primal_outs          rT   _add_jvprK    s    	$!Q*$1ay*	$Z4:--w||55jAAA	$Z7<<'
(8(8$???DzW\\!'
(8(8$???s4&&rV   c                   t        j                  |      r|j                  nt        j                  |      }t        j                  |      r|j                  nt        j                  |      }t        |       t        j                  u r*t        j                  |      t        j                  |      gS t        ||       t        ||       gS rY   )	r&   r   r  r   r  r   r   r  r~  r  rS   r$  r  r+  s        rT   _add_transposerN    s    
 ++A.166DMM!4D&++A.166DMM!4D&	!WLL ',,v"677#\&!%<==rV   c                   |j                   j                  j                  |j                   j                  j                  }}|r%|r#||k7  rt        j                  d| d|       |}nA|s|r3|r|sd\  }}n|s|sJ d\  }}t        j                  | d| d| d      t               }| j                  | j                  j                  |      	      S )
NzIlhs and rhs to `add` must be unreduced along the same mesh axes. Got lhs=, rhs=)r  r  )r  r  z is unreduced while zi is not. `add` operation does not allow this because there will be implicit communication. Please reduce z$ via `reshard` before calling `add`.	unreducedr   )r   r   rR  r   rc  r  r   )r  rS   r$  x_ury_urres_unreducedlhs_strrhs_strs           rT   _add_unreduced_rulerX    s    zz((!**//*C*C$	dt|""F&() ) MtD%gw$%gw

 
 )'y 1)?	AB B
 KM			,"3"3":":]":"S		TTrV   r]  )rp  r    r\  c                   | \  }}|\  }}t        ||      }t        |      t        |      cxu rt        j                  u r$n n!|t        j                  j	                  |      fS t        |      t        j                  u r!|t        |j                  t        |            fS t        |      t        j                  u r|t        |j                  |      fS |t        ||      fS rY   )ra  r   r   r  rD  r  rq   r   rE  s          rT   _sub_jvprZ  :  s    	$!Q*$1ay*	$Z4:--w||55jAAA	$Z7<<'
(8(8#d)DDDDzW\\!'
(8(8$???s4&&rV   c                   t        j                  |      r|j                  nt        j                  |      }t        j                  |      r|j                  nt        j                  |      }t        |       t        j                  u r*t        j                  |      t        j                  |      gS t        ||       t        |t        |             gS rY   )
r&   r   r  r   r  r   r   r  r~  r   rM  s        rT   _sub_transposer\  G  s     ++A.166DMM!4D&++A.166DMM!4D&	!WLL ',,v"677#\&#a&%ABBrV   ra  c                   |j                   j                  j                  |j                   j                  j                  }}|r|rt        j                  d| d|       |rC|sA||j                   j                  j
                  k7  rt        j                  d| d|       |}nU|sC|rA|j                   j                  j
                  |k7  rt        j                  d| d|       |}n|s|rJ t               }|r&| j                  j
                  |k(  sJ t               }n| j                  j
                  }| j                  | j                  j                  ||            S )NzHlhs and rhs to `mul` cannot be unreduced since mul is bilinear. Got lhs=rP  zGRHS should be reduced along the same axes LHS is unreduced on. Got lhs=	 and rhs=zGLHS should be reduced along the same axes RHS is unreduced on. Got lhs=)rR  r?  r   )r   r   rR  r   rc  r?  r  r   )r  rS   r$  rS  rT  out_unreducedout_reduceds          rT   _mul_unreduced_rulera  W  sd   zz((!**//*C*C$	d

 
 F&() ) Dqzz&&&""IaS"# # MDzz$&""IaS"# # MD  KM$$555+K##++K			,"3"3":":{ #; #4	 
5 5rV   rd  c                    t        | |      S rY   r  )rH  rS   r$  s      rT   r   r   v  s    Sq\ rV   c                    t        ||       S rY   r  )rI  rS   r$  s      rT   r   r   w  s    SD\ rV   c                B    t        |j                  t        | |            S rY   r~  r  rd  ctrS   r$  s      rT   r   r   x  s    |AFFCAJ'G rV   c                B    t        |j                  t        ||             S rY   re  rf  s      rT   r   r   y  s    QVVSBZ @ rV   c                   t        j                  |      rt        j                  |      rJ t        |       t        j                  u r!t        j                  |j
                        d gS t        |j
                  t        | |            d gS rY   )r&   r   r   r   r  r  r~  rg  )	cotangentrS   r$  s      rT   _div_transpose_rulerk  |  sh    				"2+A+A!+DD	D	)_$LL $''Y!23T::rV   rg  c                    t        | |      S rY   r  r  s      rT   r   r     s    #a) rV   c                T    t        t        t        |       |      t        |d            S )Nr  )rd  r   r=  r  s      rT   r   r     s    #c#a&!nk!R.@A rV   rj  c                z    t        t        t        j                  |      t        j                  |            |       S rY   )r  r   rZ   rq   r  s      rT   r   r     s'    $%5bhhqk288A;%OQRS rV   c                    t        t        |       t        t        t        ||            t	        t        t        ||                              S rY   )rd  r   r   rg  r   r5  r  s      rT   r   r     s1    CADQOU3s1ay>5J KL rV   c          	     J   t        t        j                  |       t        j                  |            }t        ||       } t        ||      }t	        |       }t	        |      }t        t        ||       |t        |       t        |             |||            }t        || |      S rY   )r   rZ   rq   r  r(  r  rz  r,  )rS   r$  lax_cmp_pick_xr   rxrypick_xs          rT   _minmax_complex_loweringru    s    !"((1+rxx{;,|Q'!|Q'!Aw"Aw""R*nT!Wd1g> R(*&	1	rV   zcore.Primitiverl  c                0    t        | t        |||            S rY   rd  _balanced_eqr  r  rS   r$  s       rT   r   r         A|AsA'> ? rV   c                0    t        | t        |||            S rY   rw  ry  s       rT   r   r     rz  rV   rn  c                0    t        | t        |||            S rY   rw  ry  s       rT   r   r     rz  rV   c                0    t        | t        |||            S rY   rw  ry  s       rT   r   r     rz  rV   rq  rt  rw  c           	        |\  }}	t        j                  |      }
t        j                  |	      }t        j                  |
j                  |j                        }t        t        |j                  |j                              }t        j                  |t        t        | d      |||
|g|g      \  }t        j                  |t        t        |||      ||g|g      S )NFr  r  rT  )r   physical_avalr!   rq   rb   r   rQ   rO   r(   delegate_loweringr   _compare_lower_hlo_unary_reduce_lower)	directionreduction_opidentityr  r  r  rS   r$  aval_xaval_ybase_aval_xbase_aval_ybase_aval_outreduce_axesress                  rT   _opaque_comparison_hlor    s    .&&""6*+""6*+"";#4#4hnnE-eHMM=+=+=>?+				7%y%8k;/M?
L$# 
			7&h#%	]Oz
; ;rV   r  NEc                    t        fd|D              }| dk(  rt        ||||      S | dk(  rt        ||||      S t        d|  d|d   j                         )Nc              3  r   K   | ].  }t        j                  j                  |j                         0 y wrY   )r   r!   rq   rb   )rj   r  r  s     rT   rl   z,_compare_lower_hlo_opaque.<locals>.<genexpr>  s-      I7;dx~~tzz2Is   47r  r  zHLO comparison z for extended dtype r   )r   _opaque_eq_hlo_opaque_ne_hlor  rb   )r  r  r  r  rS   r$  broadcast_avals_ins      `   rT   _compare_lower_hlo_opaquer    s     I?GI I$#18QBBD#18QBB

)$8!9J9J8KLN NrV   c                   |j                   |j                  c}\  }|d   j                  }t        j                  |||f||j
                  |j                        \  }}t        j                  |t        j                        r|rJ t        | |||||      S t        j                  |t        j                        r|rdnd}n)t        j                  |t        j                        rd}nd}t        j                  ||| |      gS )Nr   
TOTALORDERFLOATSIGNEDr  )r  r  rb   r(   r  rq   r   r   r  r~  r  rZ   rL  signedintegerr  )	r  total_orderr  rS   r$  r  r  x_dtypecompare_types	            rT   r  r    s    ,,(KXQK'		$	$S1a&(HNN%-%6%6
8$!Qw0?$YXxANNw

+#.<GL""2"23LL


1aL
9	::rV   rz  )rQ  r~  r  GEr  GTr  LEr  LTeq_tole_tolt_toc                   | j                   S rY   ry  r  r  r   r   s       rT    _convert_element_type_shape_ruler  	  s    	rV   c                   || j                   S |j                  rNt        |t              r*t        |j                  j
                  |j                        S t        j                         S |S rY   )	r   r  r   r8   rb  abstract_meshr   r   get_cur_mesh_shardingr  s       rT   #_convert_element_type_sharding_ruler    sV    (M*8==66FF''))	/rV   c                   | j                  | j                  j                  |j                  j                  j                              S NrQ  r   r   r   r   rR  rA  r  r  r   r   s        rT   $_convert_element_type_unreduced_ruler    s@    	5::,,  %%// - 1 
2 2rV   c                   | j                  | j                  j                  |j                  j                  j                              S r=  r@  r  s        rT   "_convert_element_type_reduced_ruler    s@    	5::,,##++ - - 
. .rV   c                   |S rY   ri   r  s       rT    _convert_element_type_dtype_ruler  "      	rV   c                   |S rY   ri   r  s       rT   $_convert_element_type_weak_type_ruler  &  r  rV   c               B   t        j                  |      sJ |j                  j                  }t	        j
                  |      }t        |       t        j                  u r t        j                  |j                        gS t        j                  |      t        j                  k(  r?t        j                  |j                  j                  t        j                  d            gS t        j                  | |||j                  j                         j                         }|gS )NF)rb   r   r  )r&   r   r  rb   r   r  r   r   r  r   primal_dtype_to_tangent_dtyper  r   r  r   r{  r   )rg  r  r  r   r   r  r  r  s           rT   $_convert_element_type_transpose_ruler  *  s    				((	(ll  )((1-	"XLL&'')))4ELL,,6==E,RSTT
 
%
%
i=//1:: & <C 5LrV   c                   t        j                  |      }|t        j                  k(  rt        j
                  j                  |      S t        j                  | |||      S )Nr  )	r   r  r   r  r   r  rD  r  r   )tangentprimal_resultr  r  r   r   new_tangent_dtypes          rT   _convert_element_type_jvp_ruler  9  sX    88C&--'<<))-88!&&w:K1:X ' O OrV   c                   | \  }|\  }|d   }t        |      t        v rt        |t              rt	        j
                  |      st        j                  |t        j                        st	        j                  |      }t        j                  |j                  t        j                        r0t        j                  |t        j                        s|j                  }|j                  |      }t        j                  ||j                         gS y )Nr  r   )r   _foldable_typesr   r!   rZ   rq   r   r  r~  r   rb   r  r(  r  r   r   r   )r  rh  r  r  r,  r  r  s          rT   _convert_elt_type_folding_ruler  I  s     "!)([!)
1g Z+%Fhhqk	6??;
**Q-C#))R%7%78i););<HHc
**Y
C!!#1C1CDEE	rV   c                l   | j                   \  }|j                  }|j                  | j                  d   k(  rz|j                  | j                  d   k(  r^t        j                  |j                  t
        j                        s0| j                  d   | j                  d   |j                  k(  rdgd fS d g| fS )Nr  r   r   r   )	invarsr  rb   rh  r   r   r  r~  r   )r  r  r  s      rT   _convert_elt_type_fwd_ruler  `  s    
zz"!	
$
jjCJJ{++
nn

;//


DJJ
8
zz*%J)?4==)P3963;rV   c                    t        | j                        }|d   |d= t        j                  | j	                  |      ||      S )Nr   r  r  r  s       rT   _convert_elt_type_pp_ruler  k  sA    

&Jz	ckkk0'8	DDrV   r  )weak_type_rulerF  rG  rp  rH  c                    |d   }t         j                  j                  t        | ||      }|B|j                  r6t        j
                  |       5  t        j                  ||      }d d d        |S |S # 1 sw Y   |S xY w)Nr   )r   r    bind_with_tracer  r  set_current_tracer   with_sharding_constraint)tracer  rh  r   r  s        rT   %_convert_element_type_bind_with_tracer  {  sw    J(NN**+A5$PVW'h33				& A--gx@gA	..A	.s   A22A<c                   |t        j                  | |d      }t        |||      }t        j                  |i ||d   fS )Nr   r  )r'   get_sharding_for_vmapr  r  r   )	axis_databatched_args
batch_dimsr  r   r   
new_paramss          rT   #_convert_element_type_batching_ruler    sI    --i1EHi9xP*		$	$l	Aj	A:a=	PPrV   c                     yr%  ri   r   s    rT   r   r     r(  rV   c                @    t        j                  |       j                  S rY   )rZ   rO  rb   r  s    rT   _real_dtyper    s    rxx444rV   c                  | j                   \  }| j                  \  }t        j                  |j                  t
        j                        r^t        j                  |t
        j                        s:t        j                  |      }|j                  t        |j                              }t        j                  | |||      }t        j                  | ||      gS Nr  )r  r  r   r  rb   rZ   r  r5   r(  r   r  r(   convert_hlor  )r  r  r  r   r   aval_inr  r  s           rT   _convert_element_type_lowerr    s    \\('mm)(r'9'9:


Ir'9'9
:hhwGnn;w}}#=n>Ggw9#

+
+Ch
?	@@rV   c               \   t        |t        j                        r$t        | j                  t        j                        rJ t        | t              st        dt        |              t        |j                  dd       x}r || j                  |      }n|j                  j                  }|s-t        dt        | j                         dt        |             t        j                  |      }t        |j                  j                         d|j"                  z  k(  sJ | j                  |j                  k7  rDt        dt        | j                         dt        |       dt        |j                         d      | j"                  |j"                  k  rYt        d	t        |       d
|j$                   d|j"                   d| j$                   d| j"                   d|j"                   d      | j"                  |j"                  z
  }| j$                  d | | j$                  |d  }}||j$                  k7  rBt        d	t        |       d
|j$                   d| j$                   d| d|j$                   d      t        | t              r| j                  j                   d | | j                  j                   |d  }	}t        |	      dt'        |	      z  k7  r+t        d| j)                  d       d|j$                         | j+                  ||| j                  j+                  |            S J )Nz?can only convert to an extended dtype on an array type,but got 
convert_to!Cannot convert_element_type from r  rY   z\can only convert to extended dtype from its representation dtype, but tried to convert from - which doesn't match the representation type rn   zdcan only convert to extended dtype from an array of its representation type, but the extended dtype z has a representation shape z (rank z1) while the given representation array has shape z < z).z0 while the given representation array has shape z,, so the shape suffix does not match: given z but required zcan only convert to extended dtype from an array with trailing axes that are not explicitly sharded, but tried to convert from T)short_dtypesz) to an extended dtype with element shape r   )rq   rb   r   )r   r   r  rb   r!   rp   r   r  r  allow_conversionr   r0   r   r  r   r   r   rO   rq   r   	str_shortr   )
rS   r  r  r  rep_avalr  shape_prefixshape_suffixspec_prefixspec_suffixs
             rT   _to_edtype_abstract_evalr    s   
VV11
2&"6"679 8 
A{	#
 #Awi) * *6==,==Z=!!''62}}55	

+OAGG,D+E Ff%&	() ) ''/(	x  %%	&'HMM*A	AA	AWW
	%%4QWW%=$>d6"
##P8>>*
+1	./ /
 VVhmm
	77Fv7N6O
&x~~&6ghmm_ M::;'''66(#hmm_B		() ) ffx}}! wwr{AGGABK,X^^#
	77Fv7N6O
&x~~&6 7**+'' 3!!-nX^^<LA		OP P ; zzr2AJJOOAB4GK[Ws;'777M[[d[+, ->>"$% %
 88,fZZ..K.@  B B 5rV   	to_edtypec                @    t        | t        j                  |            S rY   r  r   r  )r  rS   r  s      rT   r   r     s    
q$"D"DV"L
M rV   c                Z    t         j                  | |j                  j                        gS r  )r  r   r  rb   )rg  rS   r  s      rT   r   r     s!    =--b-EF rV   c                    |gS rY   ri   r   rS   __s      rT   r   r     s    s rV   c          
        t        | j                  t        j                        rt        |t        j                        rJ t        | t              st        dt        |              t        | j                  j                  dd       x}r || j                  |      }n | j                  j                  j                  }|s-t        dt        | j                         dt        |             t        j                  | j                        }t        |j                  j                         d|j"                  z  k(  sJ |j                  |k7  rDt        dt        | j                         dt        |       dt        |j                         d      t        | t              r,| j%                  g | j&                  |j&                  |	      S J )
NzAcan only convert from an extended dtype on an array type,but got convert_fromr  r  rY   z\can only convert from extended dtype to its representation dtype, but tried to convert from r  rn   rq   rb   )r   rb   r   r  r!   rp   r   r  r  r  r   r0   r   r  r   r   r   rO   r   rq   )rS   rb   r  r  r  s        rT   _from_edtype_abstract_evalr    s   
QWWf22
3 4 457 6	A{	#
 #Awi) * *QWW^^^TBB\B#AGGU3ww~~66	

+OAGG,D+E Fe$%	'( ( ''0(	x  %%	&'HMM*A	AA	A^^u
	%%4QWW%=$>d5!
""O8>>*
+1	./ /
 ;885AGG5hnn5U8CC5rV   from_edtypec                @    t        | t        j                  |            S rY   r  )r  rS   rb   s      rT   r   r     s    
q$"D"DU"K
L rV   c                F    t         j                  | |j                        gS )Nr  )r  r   rb   )rg  rS   rb   s      rT   r   r     s    +**2agg*>? rV   c                    |gS rY   ri   r  s      rT   r   r   
  s    ! rV   c                  | j                   }t        j                  |      }t        j                  |      }||k(  r| j                  S ||kD  rg | j                  ||z  S | j                  r| j                  d   nd}||z  |k7  r-t	        d| j                   d| d| d| d| d| d| d	|       | j                  d d S )
Nr  rN   z%Attempting to convert array of shape z from z	 of size z	 bits to z, bits but z * z != )rb   r   itemsize_bitsrq   r   )r  r  r  	old_nbits	new_nbitsdim_sizes         rT    _bitcast_convert_type_shape_ruler     s    mm)""9-)""9-))==93W]]3I233$+MMw}}R qH)y(
/ ?{)I; /[	) -jI;d9+	78 8
 =="rV   c               j   | j                   }t        j                  |      }t        j                  |      }||k(  r| j                  S ||kD  r5| j                  j	                  g | j                  j
                  d       S | j                  j	                  | j                  j
                  d d       S )Nr   r  )rb   r   r  r   r   r   )r  r  r  r  r  s        rT   #_bitcast_convert_type_sharding_ruler  !  s    mm)""9-)""9-))9""(F'*:*:*?*?(F(F"GG""(8(8(=(=cr(B"CCrV   c               l   | j                   }t        j                  |t        j                        slt        j                  |t        j
                        sHt        j                  |t        j                        s$t        j                  |t        j
                        r||k7  rt        d| d|d      |S )Nzlax.bitcast_convert_type does not support bool or complex values unless the operand and destination types match. Got operand dtype=z, new_dtype=z/. Consider using the arr.view() method instead.)rb   r   r  rZ   r0  r  rp   )r  r  r  s      rT    _bitcast_convert_type_dtype_ruler  .  s    mm)	288,	2#5#56	288,	2#5#56I ++4+]	| DFF G G 
rV   r  )r  rF  rG  c                   | j                   \  }t        j                  t        j                  |      |      }t        j
                  | ||      gS rY   )r  r5   bitcast_convertr(   r  r  )r  r  r  r  r  s        rT   _bitcast_convert_type_lowerr  C  sB    mm)(D00:GD#

+
+Ch
?	@@rV   c                z    t        j                   t        j                        r%t        j                  t        j                        rnt        j                  t        j                  t        j
                  f}t         fd|D              rt        d      t        j                   t        j                        r/t        j                  t        j                        st        d      t        j                         j                  }t        j                        j                  }||k  rt        d      y )Nc              3  |   K   | ]3  }t        j                  |      xr t        j                  |        5 y wrY   r   r  )rj   r  r/   r  s     rT   rl   z3_validate_preferred_element_type.<locals>.<genexpr>S  sH      P<= [!, 83Q728 8 Ps   9<zInput type is incompatible with `preferred_element_type`. The compatible combinations of (input_type, preferred_element_type) are (integral, integral), (integral, floating), (floating, floating), (complex, complex.zL`preferred_element_type` must have the same signedness as the original type.zE`preferred_element_type` must not be narrower than the original type.)r   r  rZ   r1  floatingr  r  rp   r  rb   itemsize)r/   r  allowed_typesinput_bitwidthpreferred_bitwidths   ``   rT    _validate_preferred_element_typer  K  s   RZZ0.< 	ZZb.@.@AM
 PANP P A B B
 	+r'7'784b6F6FG . / /88K(11.xx 67@@.(
 % & & )rV   c               l    |t        |t              st        t        |      \  \  }}\  }}	t	         fd||fD              s d| d| d j
                   }
t        |
      t	        fd||	fD              s d|	 d| dj
                   }
t        |
      t        |      t        |	      k7  rd	}
t        |
j                  ||	            t        |      t        |      }}t        |      t        |	      }}t        |      t        |      k7  rd
| d}
t        |
      t        |      t        |	      k7  rd|	 d}
t        |
      t        |      t        |      k7  rd| d}
t        |
      t        |      t        |      k7  rd| d}
t        |
      ||z  rd}
t        |
j                  ||            ||z  rd}
t        |
j                  |	|            t         fd|D              }t        fd|	D              }t        j                  ||      sd}
t        |
j                  ||            t         fd|D              }t        fd|D              }t        j                  ||      sd}
t        |
j                  ||            t         j                  j                  |      S )Nc              3     K   | ]b  }t        j                  t        j                  |d             xr3 t        j                  t        j                  |j                               d ywrh   rZ   ro   greater_equallessrO   )rj   rz   r  s     rT   rl   z*_dot_general_shape_rule.<locals>.<genexpr>k  O      4 VVB$$Q*+Lrwwq#((7K0LL 4   A(A+zdot_general requires lhs dimension numbers to be nonnegative and less than the number of axes of the lhs value, got lhs_batch of z and lhs_contracting of z for lhs of rank c              3     K   | ]b  }t        j                  t        j                  |d             xr3 t        j                  t        j                  |j                               d ywrh   r  )rj   rz   r  s     rT   rl   z*_dot_general_shape_rule.<locals>.<genexpr>r  r  r  zdot_general requires rhs dimension numbers to be nonnegative and less than the number of axes of the rhs value, got rhs_batch of z and rhs_contracting of z for rhs of rank zldot_general requires equal numbers of lhs_batch and rhs_batch dimensions, got lhs_batch {} and rhs_batch {}.zHdot_general requires lhs batch dimensions to be distinct, got lhs_batch rn   zHdot_general requires rhs batch dimensions to be distinct, got rhs_batch zTdot_general requires lhs contracting dimensions to be distinct, got lhs_contracting zTdot_general requires rhs contracting dimensions to be distinct, got rhs_contracting z~dot_general requires lhs batch dimensions to be disjoint from contracting dimensions, got lhs_batch {} and lhs_contracting {}.z~dot_general requires rhs batch dimensions to be disjoint from contracting dimensions, got rhs_batch {} and rhs_contracting {}.c              3  <   K   | ]  }j                   |     y wrY   ry  rj   r  r  s     rT   rl   z*_dot_general_shape_rule.<locals>.<genexpr>       :1#))A,:   c              3  <   K   | ]  }j                   |     y wrY   ry  rj   r  r  s     rT   rl   z*_dot_general_shape_rule.<locals>.<genexpr>  r  r  zidot_general requires lhs batch dimensions and rhs batch dimensions to have the same shape, got {} and {}.c              3  <   K   | ]  }j                   |     y wrY   ry  r  s     rT   rl   z*_dot_general_shape_rule.<locals>.<genexpr>       F		!Fr  c              3  <   K   | ]  }j                   |     y wrY   ry  r  s     rT   rl   z*_dot_general_shape_rule.<locals>.<genexpr>  r   r  zRdot_general requires contracting dimensions to have the same shape, got {} and {}.)r   r8   r  r  ro   rO   rp   r   r}  r  r   r   r   _dot_general_shape_computationrq   )r  r  r  r  r  r  lhs_contractingrhs_contractingr  r  rs   lhs_contracting_setlhs_batch_setrhs_contracting_setrhs_batch_setlhs_batch_shaperhs_batch_shapelhs_contracting_shaperhs_contracting_shapes   ``                 rT   _dot_general_shape_ruler-  e  s    j}&M
?QRc?d<$?O&<y)	 4&	24 
4$+%=o=N O!hhZ)C C.	 4&	24 
4$+%=o=N O!hhZ)C C.^s9~%<C
CJJy)4
55'*?';S^}'*?';S^}3y>)!{!%C
C.3y>)!{!%C
C.	_!55""1!2!5C
C.	_!55""1!2!5C
C.=(NC
CJJy/:
;;=(NC
CJJy/:
;;:	::/:	::/		$	$_o	F4C
CJJ@
AAFoFFFoFF		$	$%:<Q	R#C
CJJ46KL
MM	'		399>O	PPrV   c                    t        |      \  \  }}\  }}t         fd|D              }t        t        t        |      t        |      z               }t         |      }	d}
t	        |t
              rt        |j                        }
t        t        t        |      t        |      z   |
z               }t        ||      }||	z   |z   S )Nc              3  (   K   | ]	  }|     y wrY   ri   )rj   r  r  s     rT   rl   z1_dot_general_shape_computation.<locals>.<genexpr>  s     6qil6   ri   )r  r   r  tuple_deleter   r  r  )r  r  r  r#  r$  r  r  batch_shapelhs_contract_or_batchlhs_tensored_shape	rhs_grouprhs_contract_or_batch_or_grouprhs_tensored_shapes   `            rT   r"  r"    s    ?QRc?d<$?O&<y)6I66+u_'=i@P'P QR#I/DE)!#<='<<=I#(U?#eI&66BC$  $I/MN	)	),>	>>rV   c                l    t        | |      D ]%  \  }}|	|||k7  st        j                  |       y rY   )r   r   rc  )lhs_specrhs_specrs   lrs        rT   _check_specs_matchr=    s<    (H% (da}16""3''(rV   c               N     j                   j                  j                  sj                   j                  j                  sp j                   j                  j                   j                  k7  rCt        j                  d j                   j                   dj                   j                         |t        |t              sJ |S |\  \  }}\  }}	t         fd|D              }
t        fd|D              }t         fd|D              }t        fd|	D              }d| d| d	}t        |||       d
|
 d| d	}t        |
||       t        |
|      D ]%  \  }}|	|t        j                  d|
d|        j                   j                  j                  r7j                   j                  j                  sj                   j                  }n j                   j                  }t         j                   j                  j                   j                  ||      S )Nz0Mesh of both lhs and rhs should match. Got lhs: z
 and rhs: c              3  P   K   | ]  }j                   j                  |     y wrY   r   r   r  s     rT   rl   z-_dot_general_sharding_rule.<locals>.<genexpr>        Ms||003Mr|   c              3  P   K   | ]  }j                   j                  |     y wrY   r@  r  s     rT   rl   z-_dot_general_sharding_rule.<locals>.<genexpr>  rA  r|   c              3  P   K   | ]  }j                   j                  |     y wrY   r@  r  s     rT   rl   z-_dot_general_sharding_rule.<locals>.<genexpr>        A!**1-Ar|   c              3  P   K   | ]  }j                   j                  |     y wrY   r@  r  s     rT   rl   z-_dot_general_sharding_rule.<locals>.<genexpr>  rD  r|   zhdot_general requires lhs batch dimensions and rhs batch dimensions to have the consistent sharding, got rw  rn   zMdot_general requires contracting dimensions to have consistent sharding, got zContracting dimensions are sharded and it is ambiguous how the output should be sharded. Please specify the output sharding via the `out_sharding` parameter. Got lhs_contracting_spec=z and rhs_contracting_spec=)r   rb  r  r   rc  r   r8   r   r=  r   !_dot_general_sharding_computationr   )r  r  r  r  r  r  r#  r$  r  r  lhs_contracting_specrhs_contracting_speclhs_batch_specrhs_batch_specrs   r;  r<  rb  s   ``                rT   _dot_general_sharding_rulerK    s    ,,


!
!#,,*;*;*A*A	ll3<<,,,

 
 	LLj):):(;	=> > lM222?P<$?O&<y)M_MMM_MMAyAA.AyAA.
00>/?u
!
# ^^S9
-.e4H3I
L#)+?E&(<= Gda}""( '((C.B-DFG GG 	\\S\\%6%6%<%<<<D<<D	*	ll**,=t
E ErV   c                F    |\  \  }}\  }}t         fd|D              }t        t        t        |      t        |      z               }	t         |	      }
t        t        t        |      t        |      z               }t        ||      }t        |t	        ||
z   |z          S )Nc              3  (   K   | ]	  }|     y wrY   ri   )rj   r  r9  s     rT   rl   z4_dot_general_sharding_computation.<locals>.<genexpr>  s     4QXa[4r0  )r   r  r1  r8   r   )r9  r:  r  rb  r#  r$  r  r  
batch_specr3  lhs_tensored_specrhs_contract_or_batchrhs_tensored_specs   `            rT   rF  rF    s    ?P<$?O&<y)4)44*u_'=i@P'P QR"8-BCu_'=i@P'P QR"8-BC	tQ.?!?BS!SU	VVrV   c               t   j                   j                  j                  s j                   j                  j                  rt        j                  dd      | j                  j                  r|\  \  }}}t        fd|D              }t        fd|D              }	||	k7  rt        j                  d| d|d|	      t        |      D 
cg c]  }
|
|
	 }}
| j                  j                  t        |      k7  r/t        j                  d| j                  j                   d	|       | S c c}
w )
Nz>lhs or rhs passed to dot_general cannot be unreduced. Got lhs=r^  c              3  P   K   | ]  }j                   j                  |     y wrY   r@  r  s     rT   rl   z._dot_general_unreduced_rule.<locals>.<genexpr>         O!!2!21!5 Or|   c              3  P   K   | ]  }j                   j                  |     y wrY   r@  r  s     rT   rl   z._dot_general_unreduced_rule.<locals>.<genexpr>  rT  r|   zlhs and rhs contracting dims should be sharded identically when out_sharding provided to dot_general mentions unreduced_axes. Got out_s=z, lhs_contracting_spec=z, rhs_contracting_spec=z[out_sharding's unreduced axes should be equal to the contracting specs. Got unreduced axes=z and contracting spec=)r   r   rR  r   rc  r   r;   r  )rA  r  r  r  r  r#  r$  r   rG  rH  r   rl  s    ``         rT   _dot_general_unreduced_rulerV    sL   \\  CLL$5$5$?$?

 
 
ISF K6	  ZZ,=)&_o  O OO  O OO33""102 3$"$&' '
 ))=>Pq!-PIPzzy33""((-

(<(<'= >3467 7 
, Qs   D5D5c                   | S rY   ri   )rA  r  r  r  r  s        rT   _dot_general_reduced_rulerX    s    	,rV   c                j     t        |      t         fdt        t                     D              S )Nc              3  2   K   | ]  }|vs|     y wrY   ri   )rj   r  idx_tups     rT   rl   ztuple_delete.<locals>.<genexpr>  s     @!!4-s1v@s   	
)r  r   rQ   r   )r\  rk   r[  s   ` @rT   r1  r1    s%    	S$	@uSX@	@@rV   zlax.dot_generalr;  c                  |t        |t              st        ~d } || j                         ||j                        }	}||	kD  r| j                  }
n^|	|kD  r|j                  }
nL| j                  |j                  k7  r't	        | d| j                   d|j                         | j                  }
t        |t
        t        f      }t        |
||       S )Nc                   t        j                  | t        j                        rt	        |       n| }t        j                  | t        j                        t        j                  |t        j
                        rt        j                  |      j                  ndt        j                  |t        j
                        rt        j                  |      j                  ndt        |      t        j                  |t        j                         fS rA  )r   r  rZ   r  r  r  rO  maxexpnmant
_bit_widthr  )dtr  s     rT   type_propertiesz0_dot_general_dtype_rule.<locals>.type_properties  s    !,,R1C1CDB"Ab""4"45&,&7&72;;&GFLLO""R&,&7&72;;&GFLLO!!RqM!!!R%7%788	: :rV   z argument type error: r   )check_bit_width)r   r8   r  rb   rp   rL  r[  _maybe_upcast)r  r  r  r  r  r  r   rc  lhs_proprhs_propr6  has_algorithms               rT   _dot_general_dtype_ruleri    s     j}&M
: 'syy1?3993MH(99L(99L
yyCII4SYYKr#))MNN99LY7I(JK-	|%;+8'8
: :rV   c                N   t        j                  | t        j                        rt        j                  |       j
                  S t        j                  | t        j                        rt        j                  |       j
                  S | t        j                  d      k(  ryJ |        )Nr   rN   )	r   r  rZ   rL  rO  bitsr1  r[   rb   )rz   s    rT   ra  ra  .  sl    q"**%fll1o.B.B'BBJJ'Q0D0D)DBHHVQaurV   c                    || |k(  r| S |rMt        j                  | t        j                        s)t	        |      t	        |       k  rt        d| d|  d      |S )Nzd`preferred_element_type` must not be narrower than the original type, got preferred_element_type of z for result type of rn   )r   r  rZ   r  ra  rp   )r6  r  rd  s      rT   re  re  4  sp    $,,f//bkkJ'(:l+CC
 D-..B#nA' ( ( 
 rV   )swap_ansc                  |\  \  }}	\  }
}|j                   j                  }t        t        |      ||
      }t        t        t	        j                  |            |	|      }|rt        |
||      \  }}}nt        |
||      \  }}}||f||ff}t        t	        j                  |t	        j                  |	                  }t        |
      |z   |z   }t	        j                  |      }|j                   j                         j                  t        fd|D              }j                  j                  j                  |            }t        | |||||      }t        |t        |            }|j                   |j                   j                   k7  r5t#        ||j                   j                   |j                   j$                        }|S )Nc              3  <   K   | ]  }j                   |     y wrY   r   )rj   or>  s     rT   rl   z-_dot_general_transpose_lhs.<locals>.<genexpr>Q  s     9arwwqz9r  
partitionsr   r  r  r  )r  rO   	remainingrQ   rZ   ranges_liker   r  argsortr{  r   r   r   r   r  rP   rb   r   r   )r  rS   r$  r  r  r  r  rm  
x_contract
y_contractx_batchy_batchx_ndimx_kepty_kept	ans_batchans_yr   r  x_contract_sorted_by_yunsorted_axesout_axesinverse_specr{   dot_general_outx_barr>  s                             @rT   _dot_general_transpose_lhsr  A  s    2C.:z.Wg66;;&U6]J8&U2771:&
G<&%gvv>Iua%gvv>Iq%&/Iw/	0$
BJJz4J KLw-&(+AA-ZZ&(vv!**"9=99,	yybggnnn=y>"1di7M-/1/ OU8_
5%
[[AFFLL !%qvv7G7GHE	,rV   c          
     N    |\  \  }}\  }	}
||f|
|	ff}t        | ||||||d      S )NT)r  r  r  r  rm  )r  )r  rS   r$  r  r  r  r  rw  rx  ry  rz  swapped_dimension_numberss               rT   _dot_general_transpose_rhsr  [  sO     2C.:z.Wg *J7'79KL	#q!8I1
 rV   c                   | |      \  }} ||      \  }}t        t        j                  |      t        j                  |      f||f|      \  }}t        j                  |      }t        j                  |      }t	        |||      }t        |t        |            }|t        j                  |||      } ||||||	|      }||fS )Nrs  )	_dot_general_batch_dim_numsrZ   rO   rq   r"  rD   r   r'   r  )unpack_argsunpack_dimsinvoke_primr  r  r  r  r  r  r  r   r  r  lbdrbdnew_dimension_numbersresult_stack_dimr  r  r   result_batch_dimbatched_outs                         rT   _dot_batch_ruler  f  s     &(#s$(#s,G	wws|RWWS\"S#J-)) hhsm)hhsm)/	9F[\,&'7\9JK11<!13L 		3+ 
&	&&rV   c           	        | \  }}|\  }}||J t        |      \  \  }}\  }	}
t        |t              }d }t        |      t        |      cxu rt        u r3n n0|f ||	|      z   }	|f ||
|      z   }
 |||      } |||      }d}nt        |      t        u ri|gt        |      D cg c]  }||	vr||vr| }}t        |	      t	        t        t        j                  ||                  z   } ||	|      }	 |||      }nt        |      t        u rz|xt        t        t        |      |
||r|j                  ng             }|t        |      z
  t	        t        t        j                  ||                  z   } ||
|      }
 |||      }nJ ||f|	|
ff}|r0t        | ||j                  |       ||j                  |            }||fS c c}w )Nc           	     h    t        t        j                  | t        j                  | |                  S rY   )r   rZ   r]  r  )r  r}  s     rT   	bump_dimsz._dot_general_batch_dim_nums.<locals>.bump_dims  s%    b..tQ7899rV   r   r  )r  r   r  r   r   rQ   r   sumrZ   r  r   rt  r  r  )ndimsr  r  r  r  r  r  r  r  r  r  is_ragged_dotr  r  rz   
lhs_tensor
rhs_tensorr  s                     rT   r  r    s"    (H (#s	CO+	+9KL]9^6< 6I.0IJ-: 
#Y$s)"s" 9c22I9c22I\3/L\3/LS	SS[ #8_ Ci'A\,A  CJ C9~C
C0H,I(JJ)S)I\3/LS	SS[ (O6C22		
J !3|#44C
C 89:;)S)I\3/L 5(,7)Y9OP53'33S
 '22C
 
 0	00GCs   *Gc                J   | j                   j                         D ci c]  \  }}|	|| }}}| j                   d   \  \  }}\  }}	t        |      t        |      ft        |      t        |	      ff|d<   t        j                  | j                  |      ||      S c c}}w )Nr  r  )rh  r  r   r   r  r  )
r  r  r  r  r  printed_paramslhs_contrhs_contr  r  s
             rT   _dot_general_pp_ruler    s     &)ZZ%5%5%7ITQ1=AqDI.I14<O1P.8X.IH~tH~&i$y/(J)L.$%	ckkk8'8	LL	 Js
   
BBr  ro  c                    | \  }}||fS rY   ri   )
batch_argsr  r  s      rT   _dot_general_batch_unpack_argsr        (#s
srV   c                    | \  }}||fS rY   ri   )r  r  r  s      rT   _dot_general_batch_unpack_dimsr    r  rV   c                     yr%  ri   r  s    rT   r   r     r(  rV   c                    | t        | t        t        f      r t        j                  t        j                  fS t        | t
              s| | fS | S rY   )r   rL  r[  r/  r   r   r  s    rT   _full_precisionr    sI    *Y?Q0RSy0011i'y!!rV   c           
         t         j                  j                  t        |       D cg c]*  }t        j
                  j                  t        |            , c}      S c c}w rY   )r3   	ArrayAttrr  r  r5   PrecisionAttrr   r  ps     rT   precision_attrr    sD    			.=i.HIsSV$I
 I   /Ac           
         t         j                  j                  t        |       D cg c]*  }t        j
                  j                  t        |            , c}      S c c}w rY   )r3   r  r  r  r4   r  r   r  s     rT   chlo_precision_attrr    sD    			/>y/IJ!tc!f%J
 Jr  c                T    t        | t        t        f      sy | j                  ||      S rY   )r   rL  r[  rX  )r  rV  rW  s      rT   dot_algorithm_attrr    s(    	I.@A	B		'	'	9	==rV   c                    t        | t              r#| j                  | j                  | j                  fS d } ||| j
                        } ||| j                        } ||| j                  ||            }|||fS )Nc                v    || S t        j                  |       t        t         j                  |      v r| S |d   S rC  )rZ   rb   r   )r/   target_dtypess     rT   maybe_convert_dtypez8get_algorithm_compute_types.<locals>.maybe_convert_dtype+  s;    	xxBHHm <<rV   )r   rL  rM  rN  rO  rj  rl  ru  )	algorithmrV  rW  	out_dtyper  out_types         rT   get_algorithm_compute_typesr    s     	<($$$$##  ")Y-J-JK)!)Y-J-JK) 11)YG( 
Ix	''rV   c                B   t        | t              r>t        j                  j	                  ddt        d      t        | j                              S t        | t              rAt        j                  j	                  | j                  | j                  | j                  d      S y )Nr   r   	TOLERANCE)r   r   r   mode)r   r   r5   ResultAccuracyAttrr  r   r   r   r   r   r   r   r  s    rT   r  r  :  s{    ,'!!%%c3AHMM8JKK(I&!!%%]]]]]]	 &   'rV   c           	          d } j                   ^}}}|j                  |j                  }
}	 j                  \  }|}i }t        |t        t
        f      r|dk(  r||t
        j                  t
        j                  t
        j                  t
        j                  t
        j                  t
        j                  t
        j                  hvrt        d| d       fd}t        ||	|
|j                        \  }	}
} ||||	      } ||||
      }| t        j                   |j"                  |      }|t
        j                  k7  r:dt%        ||	|
      i}n)|	|
k7  r#|dk(  rd } ||	      r	 ||
      s
t'        j(                   ||t        j                   |j"                  |j                              }t'        j(                   ||t        j                   |j"                  |j                              }n ||	|
      st'        j(                   ||t        j                   |j"                  |j                              }t'        j(                   ||t        j                   |j"                  |j                              }||||fS )	Nc                    t         j                  t         j                  t         j                  t         j                  t         j
                  t         j                  t         j                  f}| |v xr ||v S rY   )r   ro  rp  rq  rr  r  r  r  )_lhs_dtypes_rhs_dtypesr  s      rT   _is_fp8_mixed_precision_matmulz=_handle_dot_precision.<locals>._is_fp8_mixed_precision_matmulF  s\    &&(:(:((&*@*@$$f&8&8'')J *$B
)BBrV   cpuzThe precision 'z(' is not supported by dot_general on CPUc                    ||j                   |k(  r| S t        j                  |j                  |      }t	        j
                  | ||      S rY   )rb   r   r!   rq   r(   r  )r  r  target_dtyper  r  s       rT   r  z2_handle_dot_precision.<locals>.maybe_convert_dtyped  sJ    		!3!3|!Cl00,?dc7L$??rV   r  tpuc                    t        j                  | t        j                        xs$ t        j                  | t        j                        S rY   )r   r  rZ   r  r1  )rb  s    rT   r   z'_handle_dot_precision.<locals>.<lambda>}  s4    f//BKK@ @$//BJJ? rV   )r  rb   r  r   rL  r[  r   rc  r  rh  rg  r  r  r   r  r   r!   rq   r  r(   r  )r  r  r  r  platformr  lhs_avalrhs_avalr   rV  rW  r  accumulation_avalalgorithm_kwargr  accumulation_dtypehandleds   `                rT   _handle_dot_precisionr  E  sM   C <<(Hq!Y)mm)(/	L*<=> 5Y""$6$B$B&&(:(F(F((*<*M*M++	/  I;&N
OQ Q
@ 0K9i09,Iy,
c8Y
7C
c8Y
7C%**8>>;MN&...
))Y	Jo I	U	A	"wy'9  c8!%!1!1(..(..!QS#  c8!%!1!1(..(..!QS# .iC  c8!%!1!1(..(..!QS#  c8!%!1!1(..(..!QS#	c$o	55rV   )r  c                  ~t        | ||||      \  }}}}	|\  \  }
}\  }}t        j                  j                  t	        |      t	        |      t	        |
      t	        |            }t        j
                  t        j                  |      |||fdt        |      i|	}| j                  \  }t        j                  | ||      }|j                  |j                  k7  rt        j                  | |||      }|gS )N)lhs_batching_dimensionsrhs_batching_dimensionslhs_contracting_dimensionsrhs_contracting_dimensionsprecision_config)r  r5   r  r  r   r  r(   r  r  r  r  rb   r  )r  r  r  r  r  r  r  r  r  r  r#  r$  r  r  	dot_dnumsr   r  s                    rT   _dot_general_lowerr    s	    1F	3Y2.#s @Q<$?O&<y)%%))"9o"9o!%o!6!%o!6	 * 8)
 ??
,-			
 &i0 	& mm)(,,S&(C&.c6+<hGF
/rV   )r  r  c                      e Zd ZdZdZdZy)RaggedDotModerN   rM   rx  N)r   r   r   RAGGED_NONCONTRACTINGRAGGED_CONTRACTINGRAGGED_BATCHri   rV   rT   r  r    s    ,rV   r  c                j   t        |j                        dk(  sJ |j                  d   }|j                  \  \  }}\  }}t        t	        |       ||      }||v rt
        j                  }||fS ||v rt
        j                  }||fS ||v rt
        j                  }||fS t        d| d| d| d| d	      )NrN   r   zlhs_ragged_dim z! not found in lhs_noncontracting z, lhs_contracting z, or lhs_batch rn   )
r   r  r  rt  rQ   r  r  r  r  rp   )lhs_rankr  lhs_ragged_dimr#  r   r  lhs_noncontractingr  s           rT   _ragged_dot_mode_and_dimr    s     
)??	@A	EE	E/EEaH.)E)[)[&?AA x/9M))..D 
~	 (++D 
~	 "%%D 
~	 
.) *01 2*+ ,Kq	" rV   c                     t        | |      d   S rC  )r  r  r  s     rT   _ragged_dot_moder    s     
"(,H	I!	LLrV   c                <    t        | |      t        j                  k(  S rY   )r  r  r  r  s     rT   _is_ragged_contractingr    s"     x!=>		)	)*rV   c                T   t        t        ||f      \  }}t        t        |      ||      }| xt        j
                  k(  r ||d |j                  |       z   S xt        j                  k(  r ||d |j                  |       z   S t        j                  k(  r|d |j                  |       S y rY   )	r   r   rt  rQ   r  r  r  r  r  )r  r  
ragged_dimr  contractnoncontracts         rT   _ragged_dot_prefix_dimsr    s    uh/0/%%+x7+	,	,	,[!@;#4#4Z#@AAA	)	)	)X:z :;;;		#	#,U[[,-- 
$rV   c               f    d }t        |j                        dk7  rt        d      |j                  d   } || j                  dd       t	         j                  |      }	|j
                  \  \  }
}\  }}|j                  dk(  rt        d      |j                  dk7  r|t        |	 j                  |||
      }t         fd|D              }||j                  d	   fz  }t        j                  |j                  |      st        d
| d|j                   d      |j                  d	   }|j                  }|	xxt        j                  k(  rnxt        j                  k(  rn n  t        |      dk7  rt        d      t        j                  k(  rwt        |      dk7  rt        d      |d   } |||j                  dd       ||v s||v rt        d      |j                  |   |k7  rt        d| d|j                  |    d      t!         ||||d       }|	t        j                  k(  r|f|z   }|S )Nc                N    | dk  s| |k\  rt        d| d| d|  d| d| d      y )Nr   zragged_dot_general requires zC numbers to be nonnegative and less than the number of axes of the z value, got z for z	 of rank rn   )rp   )dimr  dim_namearg_names       rT   _check_in_rangez7_ragged_dot_general_shape_rule.<locals>._check_in_range  sO    
Qw#+(
 355=J ?U8*IdV16  rV   rN   z<ragged_dot_general expects exactly one lhs ragged dimension.r   zlhs ragged dimensionr  z'expected rank of group_sizes to be >=1.c              3  <   K   | ]  }j                   |     y wrY   ry  r  s     rT   rl   z1_ragged_dot_general_shape_rule.<locals>.<genexpr>  s     @qciil@r  r  z#expected group_sizes to have shape z, got rn   zoragged_dot_general requires zero group dimensions in the rhs when lhs ragged dimension is contracting or batch.zhragged_dot_general requires exactly one rhs group dimension when lhs ragged dimension is noncontracting.zrhs group dimensionr  zmragged_dot_general requires rhs group dimension numbers to be distinct from contracting and batch dimensions.z(expected rhs group dimension size to be r  )r   r  rp   rO   r  r  r  r   rq   r   r   r  r  r  r  r  r-  )r  r  r  r  r  r  r   r  r  r  r#  r$  r  r  prefix_dimsexpected_gs_shape
num_groupsrhs_group_dimsrhs_group_dim	out_shapes   `                   rT   _ragged_dot_general_shape_ruler    sy    		%	;	;<A
F  0EEaH..#((,BEJ	#(($@	A$ #88 =$?O&<y)
 
=
>>)chh	?K @K@@+++B/11&&{'8'8:KL
/vk&7&7%8;    $* 0DD.	F	)	)	),FM,F,F	F	^		!A
 	
 
	,	,	^		!;
 	
 %Q'mmSXX/DeL	)	#}'G>
 	
 
=	!Z	/6l&=!9 :!=
 	

 &		43) 
]---	)I	rV   c           	         t        j                  |j                  t        j                        st        d      t        | ||j                  ||d d      S )NzLragged_dot_general requires that group_sizes.dtype is subtype of np.integer.zlax.ragged_dot_general)r  r  r  r  r   )r   r  rb   rZ   r1  rp   ri  r  )r  r  r  r  r  r  r   s          rT   _ragged_dot_general_dtype_ruler   C  sZ     
		;,,bjj	9
	6 
 
!		4JJ3#
 rV   c                R   |t        d      | \  }}}|\  }	}
}t        ||||||      }t        |	      t        j                  urt        |	|||||      n
t        |      }t        |
      t        j                  urt        ||
||||      n
t        |      }t        ||      }||fS )N#Unimplemented group_offset support.r  r  r  )r  r  r   r   r  r  r]  )rF  rG  r  r  r  r  rS   r$  gsdxdyr   rJ  dx_outdy_outtangent_outs                   rT   _ragged_dot_general_jvp_ruler
  ]  s     
C
DD(!Q)"b! "#?3*& 
b	% 


'C!7 * 	* 
b	% 


'C!7 * 	 FF#+	[	  rV   c               J   t        d      j                  \  \  \  t        j                  |      r|j                  j
                  nt        j
                  |      }t        j                  |      r|j                  j
                  nt        j
                  |      }	t        t        |            j                  t        t        |	            t        |      \  d |dk(  xr |	dk(  xr	 t        k(  fd}
f
d}fd}t        j                  |      rd n! || rt        |      n||
|j                        }t        j                  |      rd n ||| ||j                        }||d fS )Nr  c                :    t        d|  d|j                   d      S )NzUnimplemented z  for ragged dot general in mode rn   )r  r   )fn_nameragged_dot_modes     rT   r   z4_ragged_dot_general_transpose_rule.<locals>.<lambda>  s)    3Fwi?			a!4 rV   rM   rx  c                    xt         j                  k(  r t              \  } }}r	n/t        |f| fft	              j                        z   g      }t        t        j                  t        j                                    }t              z   |z   }||fS xt         j                  k(  rnxt         j                  k(  rn fS   
d      )Nr  grad_x_dims)r  r  ru  r  r   r  r   rZ   r  rv  r  r  )r~  r   r  r  r  r  _is_basic_ragged_dotr  r  r  unimplementedry  rw  r|  rz  rx  y_groupr}  s         rT   r  z7_ragged_dot_general_transpose_rule.<locals>.grad_x_dims  s    
.=..)'66B	1e $ )*(-vG8L&ML6<<#??' &- 	 "&GGJ

: 67"
 W.1GG  ,=++.Hm.H.HH IM400rV   c                   
 xt         j                  k(  rz t        	      \  } }}t        |f	| ffgg       }t	        t        j                  t        j                  
                  }t	              t	              z   |z   z   }||fS xt         j                  k(  rnxt         j                  k(  rn fS   d      )Nr  grad_y_dims)
r  r  ru  r  r   rZ   r  rv  r  r  )r~  ans_xr   r  y_contract_sorted_by_xr  r  r  r  ry  rw  r|  rz  rx  r  r}  s         rT   r  z7_ragged_dot_general_transpose_rule.<locals>.grad_y_dims  s    
.=..)'66B	5!($*E?Wi4H"I#1"2!#

 "&GGJ

: 67"
 MDM),BBVK 	
  ,=++.Hm.H.HH IM400rV   c           	         |       \  }}t        | |	|
      }t        |t        t        j                  |                  }|j
                  |j
                  k7  r!t        ||j
                  |j                        }|S )N)r  r  r  )r  rP   r   rZ   rv  rb   r   r   )r  r  dims_fnr  r  r  ragged_dot_general_outr   r  r  r  r  s           rT   _ragged_dot_gradz<_ragged_dot_general_transpose_rule.<locals>._ragged_dot_grad  ss    !)D-/
sK!7#% -uRZZ5N/OPF||tzz!$VTZZHfMrV   )r  r  r&   r   r  rO   rZ   rt  rQ   r  r  r  rU   )rg  rS   r$  r  r  r  r  r  r{  y_ndimr  r  r  r  y_barr  r  r  r  ry  rw  r|  rz  rx  r  r}  s      `````       @@@@@@@@@@@rT   "_ragged_dot_general_transpose_ruler    s    
C
DD1M1c1c.:z.Wg003166;;&003166;;&U6]J8&(=='U6]JA&1*$- k N
A+N
&*M
M  . &	 
			" B4H-a0a'FF$  
			" Ar;7 
 
t	rV   c                    | \  }}}||fS rY   ri   )r  r  r  r   s       rT   _ragged_dot_batch_unpack_argsr     s    +#sA
srV   c                P    t        d | D              st        d      | \  }}}||fS )Nc              3  &   K   | ]	  }|d k(    ywrh   ri   )rj   r  s     rT   rl   z0_ragged_dot_batch_unpack_dims.<locals>.<genexpr>  s     ,#SAX,rm   z(ragged_dot vmap over any dim but 0 - NYI)ro   r  )r  r  r  r   s       rT   _ragged_dot_batch_unpack_dimsr#     s1    	,,	,
H
II+#sA
srV   c                &    ~t        ||| |||      S )Nr  )r  )r  r  r   new_ragged_dot_dimension_numbersr  r  r  s          rT   _ragged_dot_general_invoke_primr&    s&     			#C3
 rV   c                   t        t        |d         }t        t        t        || |||||d 
      \  }}	t        |d   j                  dz
  |      r|	dz  }	||	fS )NrM   r  r   rN   )r   r&  r  r   r#  r  rO   )
r  r  r  r  r  r  r   invoker  r  s
             rT   _ragged_dot_general_batch_ruler)    sx     2LOD&"1##43#+ LO00148:	&	&&rV   r  r  )rG  c                     yr%  ri   r  s    rT   r   r   A  r(  rV   c           
        |t        d      d
ddfdd fd}t        | j                  |      \  }}	|j                  \  \  }
}\  }}t	        || j                  |	||
      }t        t        ||      }|j                  dk(  r't        ||D cg c]  }| j                  |    c}      }|xt        j                  k(  rW |j                  }t        |      dk(  sJ  | || |	|g| | |
      dgz   t        |      |d   gz   f |      |ff	      S xt        j                  k(  rq ||
j                  |	         }t	        ||j                  |||      } | || |	|g|  ||||g|  |
       |      fdg |      z   dg |      z   ff	      S t        j                   k(  r || ||j                  	      S y c c}w )Nr  c                  ddl m} |j                  dk(  sJ |j                  | j                  z   }t	        | |t        t        dt        |                        } t        |j                  ||dz         }|j                  |      }t        t        |      d d |d d gd      }t	        ||d      }t	        ||d      }t        ||k  ||k        }t        || t        |             } | S )Nr   )control_flowrN   r  r!  r  )jax._src.laxr-  rO   rq   r  r   rQ   r   r  rb   cumsumr%  r  rM  r  )	rS   r  r  r-  rq   r  
group_endsgroup_startsmasks	            rT   ragged_to_densez1_ragged_dot_general_impl.<locals>.ragged_to_denseP  s    )77a<<HHqwwEE4aU(<#=>ABHHeSU3D$$R(J	BQCR)L "*eT:J#L%>L|t+TJ->?DtQq	"AHrV   c                    |st        |       S |^}fd}t        j                    ||       g|D cg c]
  } ||       c} df      S c c}w )N)r  c                    | k\  r| dz
  S | S rI  ri   )rz   x_axiss    rT   r   zK_ragged_dot_general_impl.<locals>.batched_ragged_to_dense.<locals>.<lambda>e  s    a6kQU q rV   r   )in_axes)r   r   vmap)r  	x_in_axesrestdecraxr7  batched_ragged_to_denser4  s        @rT   r>  z9_ragged_dot_general_impl.<locals>.batched_ragged_to_densea  s\    _#..MFT0D88S	F,E"T"X,EF ,Es   Ac                2    | D cg c]  }|dz   	 c}S c c}w rI  ri   )r  rz   s     rT   r   z*_ragged_dot_general_impl.<locals>.<lambda>k  s    d+q1u+ +s   c                      |g| | |      } |      dgz    t        t        | j                        |            z   }t        |t	        j
                  |            S rC  )rt  rQ   rO   rP   rZ   rv  )rS   r  r  r  expandedunsorted_dimsr>  incrs         rT   expandz(_ragged_dot_general_impl.<locals>.expandr  s[    2&s2T21b9HJ!$tIeAFFmT,J'KKMXrzz-899rV   )r  r  rN   r   )r  )rS   r<   r  r<   r  r   )r:  r   )r  r  rO   r  r  r   r  r  rq   r  r  r  r   r   r  r  r  )r  r  r  r  r  r  r  rD  r  r  
l_contract
r_contractl_batchr_batchl_prefix_dot_generalr  r  rhs_ragged_dimr_prefixr>  rC  r4  s                       @@@rT   _ragged_dot_general_implrM  D  s    
C
DD" 
,$:
 2	hh,$ #88 /:z.Wg %
CHHngz( 3, K)I1#))A,)IJK	,	,	,3HHn A%%%
nk
=H
=
J1#%tJ'7>!;L:M'MNG}g&  
*	)	)!*"2"2>"BCn(chhh 
nk
=H
=
nk
=H
=Jj!12sT']"QC$w-$78  
	#	#

8NN  
$7 *Js   G
)r  r  c          
     >   |t        d      t        j                  j                  sN t	        j
                  t        d      | |||||||      }	| j                  \  }
t	        j                  | |	|
      S ~t        | ||||      \  }}}}|j                  \  \  }}\  }}t        j                  j                  t        |      t        |      t        |      t        |      t        |j                        t        |j                               }t        j"                  t	        j$                  |      ||||t'        |            }	| j                  \  }
t	        j                  | |	|
      }	|j(                  |
j(                  k7  rt	        j*                  | |	||
      }	|	gS )Nr  Fr  r  )r  r  r  r  r  r  )r  )r  r   )jax_ragged_dot_use_ragged_dot_instructionr  r(   r  rM  r  r  r  r  r4   r  r  r   r  r  r  r  r  rb   r  )r  r  r  r  r  r  r  r  r  r   r  r  r   r#  r$  r  r  ragged_dot_dnumss                     rT   _ragged_dot_general_lowerrQ    s    
C
DD		9	9	?	?MT^^4uMS#{%A5!F --KX,,S&(CC#8	3Y$ #sq #88 =$?O&<y) 3377"9o"9o!%o!6!%o!6 
&
<
<  
&
;
; 8  ??
,-		*95& +8,,S&(C&.c6+<hGF
/rV   )r  gpuc          	     4    t        dd       t        dd       t        j                         }|t              k7  rd}t	        |j                  |            t              |k  r&d}t	        |j                  |t                          t              j                  t        t        t                                sd}t	        |j                  |            t         fdt        |      D              s8d}t	        |j                  t        d	  j                  D                          t              t        t                    k7  s t              t        t                    k7  rd
}t	        |j                              S )Nr  rq   r  z~broadcast_in_dim broadcast_dimensions must have length equal to operand ndim; got broadcast_dimensions {} for operand ndim {}.zbroadcast_in_dim target broadcast shape must have equal or higher rank to the operand shape; got operand ndim {} and target broadcast ndim {}.zubroadcast_in_dim broadcast_dimensions must be a subset of output dimensions, got {} for operand ndim {} and shape {}.c              3  t   K   | ]/  }t        j                  j                  |   d |      g       1 ywrx  )r   definitely_equal_one_of_dimrq   )rj   r  r  r  rq   s     rT   rl   z/_broadcast_in_dim_shape_rule.<locals>.<genexpr>  sC      + --gmmA.>/0%8LQ8O2P.QS +s   58zbroadcast_in_dim operand dimension sizes must either be 1, or be equal to their corresponding dimensions in the target broadcast shape; got operand of shape {}, target broadcast shape {}, broadcast_dimensions {} c              3  F   K   | ]  }t        j                  |        y wrY   )r    replace_tracer_for_error_messager  s     rT   rl   z/_broadcast_in_dim_shape_rule.<locals>.<genexpr>  s     N1d33A6Nr  z^broadcast_in_dim broadcast_dimensions must be strictly increasing; got broadcast_dimensions {})_check_shapelikerZ   rO   r   rp   r}  r  issubsetrQ   ro   r   rq   r  )r  rq   r  r   operand_ndimrs   s   ```   rT   _broadcast_in_dim_shape_ruler[    sx   %w6%'=')!,S-..LC
CJJ3\B
CCZ,UC
CJJ|SZ8
99	!	"	+	+Cc%j0A,B	CBC
CJJ3\5I
JJ	 +L)+ 
+	# 
 CJJNNN#% & & 

3s+?'@#AA !U62F+G%HH)C
CJJ34
55	,rV   c                  ||S t        |      }t        | j                  j                        }t	        t        |            D cg c]  }||v rt        |      nd  }}t        |d       J | j                  j                  j                  r
t               n| j                  j                  }| j                  j                  || j                  j                  j                  |            S c c}w )Nrq  )rb  r   )r  iterr   r   rQ   r   nextrb  r  r-   r   )	r  rq   r  r   bds	orig_specr  r   rb  s	            rT   _broadcast_in_dim_sharding_rulera    s    O !#7##(())=B3u:=NOcd9ot3O(O	i		&&	&!(!1!1!6!6!<!<






 				 	 g&&++22h2G 
! 
I I	 Ps   C.c                X    t         j                  |j                  |||      \  }}|g|fS Nr  )r  abstract_evalr  )r   r  rq   r  r   r,  r   s          rT    _broadcast_in_dim_typecheck_rulere  $  s:    (66ll%6J 7 (G W	rV   c           	        t        |       t        j                  u r t        j                  |j                        gS t	        |t
        j                        sd gS t        |j                  j                        D cg c]  \  }}t        j                  |d      r| }}}t        t        j                  ||            }t        t        j                  t        t        |            |            }	t!        t#        | |	      |      gS c c}}w rI  )r   r   r  r  r   r&   UndefinedPrimalrU  rq   r   r   r   rZ   deleterQ   r   r  r  )
rg  r  rq   r  r   r  r   	unit_dimsr  r  s
             rT    _broadcast_in_dim_transpose_rulerj  +  s    	"XLL&''	GR//	06M&w||'9'9: /TQ''1-  /) /
		.	:
;%	ryys5z*E2	3$
jT*I
6	77	/s   ;"Dc                
   |\  }|\  }|J t        j                  ||d      }dt        t        j                  d|            z   }	|j
                  |   f|z   }
|t        j                  | |d      }t        ||
|	|      }|dfS Nr   r  rN   r  )r'   moveaxisr   rZ   r]  rq   r  r  )r  r  r  rq   r  r   r  operand_bdimnew_operandnew_broadcast_dimensionsr   r   s               rT   _broadcast_in_dim_batch_rulerq  7  s    
 ('-,		!!	!!!'<;+!E"&&4H*I$JJ}}\*,u4)--i1EHK4L)13&	rV   c                
   | j                   \  }t        j                  | j                  d   |j                  j
                        r:| j                  d   &| j                  d   |j                  j                  k(  rdgd fS d g| fS )Nrq   r   r   )r  r   r   rh  r  rq   r   )r  r  s     rT   _broadcast_in_dim_fwd_rulers  J  sn    
zz"!
!!#**W"5qvv||D::j!)::j!QVV__43963;rV   c                R    t        |||      }| j                  t        |f||      S )Nr  source_info)r  default_process_primitiver  )r  rv  rS   rq   r  r   rh  s          rT   _broadcast_in_dim_staging_rulerx  S  s:    e2F!#&		(	();aT65@ 
) 
B BrV   c                   | \  }|^}}t         j                  ||||      }t        |      t        j                  u r#t        j                  j                  |      }	||	fS t         j                  ||||      }	||	fS rc  )r  r   r   r   r  rD  )
rF  rG  rq   r  r   r  operand_dotr   r$  y_dots
             rT   _broadcast_in_dim_jvp_ruler|  Z  s    ('/+gU3G'/  1! 
+',,&LL**1-E
 
E/ ##Ku9M-5 $ 7E 
E/rV   c           	     J    | j                  t        |ft        |||            S rc  )rw  r  r  )r  r  rq   r  r   s        rT   _broadcast_in_dim_partial_evalr~  i  s,    		(	(7*
-A
 rV   c                    | j                   \  }t        j                  | |||      }t        j                  | ||      gS )Nr  )r  r(   r  r  )r  rS   rq   r  r   r  r  s          rT   _broadcast_in_dim_lowerr  p  s?    mm)(c1h3G	I#

+
+Ch
?	@@rV   c                    t        | ||d       }t        | |||      }t        j                  d|       }t        j                  || j
                  | j                  ||| j                        S )Nr  r  )r   r  memory_space)r[  ra  r   rq  r!   rb   r   r  )rS   rq   r  r   new_shardingnew_vmas         rT   _broadcast_in_dim_abstract_evalr  w  so    
&u+?$P%0u+?, ""#5q9'			%!++%ANN
D DrV   r  c                     yr%  ri   r  s    rT   r   r     r(  rV   c                F   | j                   r?| j                   |j                   k7  r&t        d| j                    d|j                   d      |j                   r?|j                   |j                   k7  r&t        d|j                    d|j                   d      |j                   S )NzLclamp requires min.shape == operand.shape or min.shape == (), got min.shape=z, operand.shape=rn   zLclamp requires max.shape == operand.shape or max.shape == (), got max.shape=)rq   rp   r^   r  r`   s      rT   _clamp_shape_ruler    s    YY399-
 )),3Dgmm5EQH I IYY399-
 )),3Dgmm5EQH I I	rV   c                    |j                   S rY   rx  r  s      rT   _clamp_sharding_ruler        			rV   r  c                   | \  }}}|\  }}}t        d t        | |      D              }	||cxk(  r|k(  r.n n*t        j                  |      t        j                  |      cxk(  rt        j                  |      k(  rn nt        j                  |||      |fS t        j                  |      t        j                  |      cxk(  rdk(  rn nt        j                  |||      |fS t        j                  |      t        j                  |      cxk(  rdk(  rn nt        ||j                  |g      }t        ||j                  |g      }t        j                  |||      |fS t        j                  |      dk(  r3t        j                  |      dk(  r|t        j                  |||      |fS t        j                  |      rt        j                  |||	      n|}t        j                  |      rt        j                  |||	      n|}t        j                  |      rt        j                  |||	      n|}t        j                  |      dk(  r.t        j                  |      dkD  rt        ||j                        }t        j                  |      dk(  r.t        j                  |      dkD  rt        ||j                        }dt        j                  |      cxk  rt        j                  |      k  rMn nJt        j                  |      dk(  sJ t        j                  |             t        ||j                  dg      }dt        j                  |      cxk  rt        j                  |      k  rMn nJt        j                  |      dk(  sJ t        j                  |             t        ||j                  dg      }t        j                  |      t        j                  |      kD  rHt        j                  |      dk(  sJ t        j                  |             t        ||j                        }t        j                  |||      dfS )Nc              3  D   K   | ]  \  }}||j                   |     y wrY   ry  rj   rS   r  s      rT   rl   z$_clamp_batch_rule.<locals>.<genexpr>  (       TQ ggaj      r   rN   )r^  r   rZ   rq   r  r   rO   r  r'   bdim_at_frontr  )
r  r  rh  r^   rS   r`   min_bdimx_bdimmax_bdimr  s
             rT   _clamp_batch_ruler    s   +#q#)(FH	  Sz%B   
 $ #8#	xx}4rxx}4\\#q#&..		*	*\\#q#&..		*	*S!''H:6cS!''H:6c\\#q#&..	wws|qRWWS\Q.63E<<Q$f,,79xx}sHd3##79xx}sHd3##13!hQ-!!WWS\Q2771:>
C
!CWWS\Q2771:>
C
!C"
"773<1*bggcl*
3!
-C"
"773<1*bggcl*
3!
-CWWS\BGGAJ771:?&BGGAJ&?!SYYA	c1c	"A	%%rV   c           	     j    t        t        t        ||      t        ||            | t	        |            S rY   r  rM  r  r  r  r  r^   r  r`   s       rT   r   r     s.    
RW-r#s|<F7O% rV   c           	     j    t        t        t        ||      t        ||            | t	        |            S rY   r  r  s       rT   r   r     s/    
R-r'3/?@F7O% rV   c                B    t        t        ||      | t        |            S rY   )r  r  r  r  s       rT   r   r     s    
C!1fWo
6 rV   c                    	 |j                  d      	| sd}t        |      t        d | D              s7d}t        d | D              }t        |j	                  t        |                  t        | D ch c]  }|j                   c}      dk7  r2d}t        |j	                  dj                  d	 | D                          d
	cxk  r| d
   j                  k  sOn d}t        |j	                  	dj                  | D cg c]  }t        |j                         c}                  | D cg c]$  }|j                  d 	 |j                  	dz   d  z   & }}|d d |dd  k7  rSd}| D cg c]  }|j                   }}t        |j	                  	dj                  t        t        |                        t        	fd| D              }| d
   j                  }|d 	 |fz   |	dz   d  z   S c c}w c c}w c c}w c c}w )Nr!  z0concatenate expects at least one operand, got 0.c              3  <   K   | ]  }t        |t                y wrY   r   r!   )rj   r  s     rT   rl   z*_concatenate_shape_rule.<locals>.<genexpr>  s     F'Z-F   z2All objects to concatenate must be arrays, got {}.c              3  B   K   | ]  }t        |t              r|  y wrY   r  )rj   r$  s     rT   rl   z*_concatenate_shape_rule.<locals>.<genexpr>  s     GR:b++FbGs   rN   zGCannot concatenate arrays with different numbers of dimensions: got {}.r   c              3  F   K   | ]  }t        |j                          y wrY   r   rq   rj   rp  s     rT   rl   z*_concatenate_shape_rule.<locals>.<genexpr>  s     (H!QWW(Hr  r   z@concatenate dimension out of bounds: dimension {} for shapes {}.r  zCannot concatenate arrays with shapes that differ in dimensions other than the one being concatenated: concatenating along dimension {} for shapes {}.c              3  <   K   | ]  }|j                        y wrY   ry  )rj   rp  r!  s     rT   rl   z*_concatenate_shape_rule.<locals>.<genexpr>  s     91AGGI&9r  )poprp   ro   r^  r}  r   r   rO   r   r   rq   r   r  )
r#  r  rs   r$  r  rp  ru   concat_sizeex_shaper!  s
            @rT   _concatenate_shape_ruler    s   jj%)	
<C
C.	FXF	F
>C	G8G	GB
CJJtBx(
))h	/7',,	/0A5
SC
CJJtyy(Hx(HHI
JJ	
i	*(1+**	*
LC
CJJy$))84TaS\4T*UV
WW#% MM*9%ikl(CC %& %CR[F12J)C ,44gmm4F4
CJJy$))CV4D*EF
GG999+a[(	*9		.)A+,1G	GG# 
0
 5U% 5s   4G,?G1.)G6*G;c                 B   | D cg c]/  }|j                   j                  j                  r$|j                   1 c}st        j                         S t        fdD              s0dj                  d | D              }t        j                  d|       d   S c c}w )Nc              3  .   K   | ]  }|d    k(    ywrh   ri   rj   r   non_empty_ss     rT   rl   z-_concatenate_sharding_rule.<locals>.<genexpr>  s     6QQ+a. 6r_  r   c              3  F   K   | ]  }t        |j                          y wrY   )r   r   r  s     rT   rl   z-_concatenate_sharding_rule.<locals>.<genexpr>  s     5q3qzz?5r  z:All operands should have the same sharding. Got shardings r   )r   rb  r  r   r  ro   r   rc  )r#  r  rp  r^  r  s       @rT   _concatenate_sharding_ruler    s    %-KQZZ__5J5JK+	%%''	6+6	6	5H5	5B

 
 
DRDIK K	Q Ls
   %BBc                l   |D ch c]B  }|j                   j                  j                  r |j                   j                  j                  D }}t        |      dkD  rt	        j
                  d|       |r|n
t               f\  }| j                  | j                  j                  |            S c c}w )NrN   zKAll operands should be reduced along the same mesh axes. Got reduced specs r>  r   )r   r   r?  r   r   rc  r  r   )rA  r#  r  rp  reduced_specsrk  s         rT   _concatenate_reduced_ruler    s    $A

(?(? ::??** A- A!

 
 		"# # !.}IK>*)	5::,,Y,?	@@As   AB1c                 8    t        dg|   | d   j                  S )Nr%  r   )rV  rb   )r#  r  s     rT   _concatenate_dtype_ruler    s    M-H-	!		rV   c                  |D cg c]9  }t        j                  |      r|j                  j                  n|j                  ; }}t	        |       t
        j                  u rD|D cg c]8  }t        j                  |      rt        j                  |j                        nd : c}S t        | t        fd|D                    S c c}w c c}w )Nc              3  (   K   | ]	  }|     y wrY   ri   )rj   rq   r!  s     rT   rl   z._concatenate_transpose_rule.<locals>.<genexpr>  s     Gu%	*Gr0  ro  )	r&   r   r  rq   r   r   r  r,  r   )r  r!  r#  rp  operand_shapess    `   rT   _concatenate_transpose_ruler    s    %' %'$:$:1$=AFFLL177J '. '	!W %'$:$:1$=GLL 4G   EGGG! !'s   >C%=C
c                  t        d t        | |      D              }t        d t        | |      D              }t        | |      D cg c]  \  }}|t        j                  ||d      nft	        ||ft        j                  |      j                  j                  |gt        j                  |      j                  j                               }}}t        ||dz         dfS c c}}w )Nc              3  D   K   | ]  \  }}||j                   |     y wrY   ry  rj   r$  bdims      rT   rl   z*_concatenate_batch_rule.<locals>.<genexpr>  s)      #T! hhtn #r  c              3  ~   K   | ]5  \  }}|.t        j                  |      j                  j                  |    7 y wrY   )r   r  r   r   r  s      rT   rl   z*_concatenate_batch_rule.<locals>.<genexpr>  s=      Q"dt?O mmB((--d3 Qs   ;=r   r   r  rN   )r^  r   r'   rm  r  r   r  r   r   r   r%  )r  r  r!  r  r   r$  r  r#  s           rT   _concatenate_batch_ruler    s    	 #Sz-J # 
#$	 Q!,
;Q 
Q$ ",
;	= "d	 150@hD!,tgDMM",=,F,F,M,M>dmmB/88==> -N -@AA =( =
 
Xy1}	-q	00=s   B
C&c               R    t        fd| D              rt        |      gS t        )Nc              3  x   K   | ]1  }t        |j                     t        t        j                  f       3 y wrY   )r   rq   r   rZ   r1  )rj   r   r!  s     rT   rl   z(_concatenate_pad_rule.<locals>.<genexpr>  s2      	 
AGGI&bjj(9	: 	s   7:)ro   r%  r  )r  r  r!  r#  s     ` rT   _concatenate_pad_ruler    s.     		 ),--
rV   r%  rE  c                   | j                   \  }t        j                  |t        j                  |            }t        j
                  | ||      gS rY   )r  r5   r%  r(   i64_attrr  )r  r!  r>  r  r  s        rT   _concatenate_lowerr  .  s>    mm)(DMM)45#

+
+Ch
?	@@rV   c          
        g }t        | j                        }t        d |D              rt        dt        |             | j                  |   t	        j
                  |      k7  r:t        dt	        j
                  |       d| dt        | j                               |D ]!  }|||<   |j                  t        |             # |S )Nc              3  &   K   | ]	  }|d k    ywrh   ri   rj   r   s     rT   rl   z$_split_shape_rule.<locals>.<genexpr>8  s     1Qrm   z/Sizes passed to split must be nonnegative, got zSum of sizes z must be equal to dimension z of the operand shape )r   rq   r  r   rZ   r  r   r   )r  r(  r)  ru   rq   r  s         rT   _split_shape_ruler  5  s    &
w}}
%
7U}EG G]]4BFF5M)
bffUm_$@ GGMM*+-. .   dE$K
MM%,  
-rV   c               4    | j                   ft        |      z  S rY   )rb   r   r+  s      rT   _split_dtype_ruler  D  s    
--	CJ	&&rV   c               4    | j                   ft        |      z  S rY   )r   r   r+  s      rT   _split_weak_type_ruler  G  s    


	E
	**rV   c               .   t        j                  |      sJ t        d | D              r t        j                  |j
                        fS | D cg c]/  }t        |      t        j                  u r|j                         n|1 } }t        | |      fS c c}w )Nc              3  R   K   | ]  }t        |      t        j                  u  ! y wrY   r   r   r  r  s     rT   rl   z(_split_transpose_rule.<locals>.<genexpr>L  s     5QaGLL	 5   %'r.  )	r&   r   ro   r   r  r  r   instantiater%  )
cotangentsr  r(  r)  r  s        rT   _split_transpose_ruler  J  s    				((	(5*55<<%&&#% $(7gll#:A %* %	Z4	0	11%s   4Bc               h    | \  }|\  }|ft        |      z  }t        ||||k\  r|dz   n|      }||fS )NrN   r'  )r   r,  )r  r  r(  r)  r  r  	new_bdimsr  s           rT   _split_batch_ruler  R  sD    ('
%$gE
")gUTT\tL#	irV   c          	     r   | j                   \  }dg|j                  z  }t        |j                        }d|j                  z  }g }| j                  D ]c  }	||   |	j                  |   z   ||<   t        j                  | ||	|||      }
|j                  t        j                  | |
|	             ||   ||<   e |S )Nr   r   )start_indiceslimit_indicesstrides)	r  rO   r   rq   r  r(   slice_opr   r  )r  rS   r(  r)  r  r  r  r  outsr  r  s              rT   _split_lowerr  Y  s    LL'&##-v||$-6;;'	$-- .h'-t0DDM$
--Q&3WFCKK11#sHEF'-M$. 
+rV   c               r    t        | ||      }|D cg c]  }t        j                  || d       c}S c c}w )Nr'  r,  )r  r+   #_get_sharding_for_varying_out_shape)r  r(  r)  
out_shapesout_shs        rT   _split_sharding_ruler  g  sA     !DA*"
$ 
5
5fgw
O 
$ $ 
$s   4c               h    t        j                  d|       }t        | ||      }|gt        |      z  S )Nr,  r'  )r   rq  r  r   )r  r(  r)  out_vmar  s        rT   _split_vma_ruler  n  s3    ""7G4' DA*
S_	$$rV   r,  c                   | j                   |j                   k7  r1d}t        |j                  | j                   |j                               t        | |      S )Nz@pad operand and padding_value must be same dtype: got {} and {}.)rb   rp   r}  r/   )r  r  r  rs   s       rT   _pad_dtype_ruler  ~  sF    ]]m)))
LC
CJJw}}m.A.AB
CC	Wm	,,rV   c                  t        j                  |      dk7  r!t        dt        j                  |            t        j                  |       }t	        |      t        j                  |       k(  st        d| d|       t        d |D              st        d|       t        d t        ||      D              }t        d |D              sd	| d
| d| }t        |      |S )Nr   z<padding_value must be a scalar; got np.shape(padding_value)=zVlength of padding_config must equal the number of axes of operand, got padding_config  for operand shape c              3  .   K   | ]  \  }}}|d k\    ywrh   ri   )rj   r   r  s      rT   rl   z"_pad_shape_rule.<locals>.<genexpr>  s     21aQ!V2s   zKinterior padding in padding_config must be nonnegative, got padding_config c              3  h   K   | ]*  \  \  }}}}||z   t        j                  ||d z         z    , ywrx  )r   
dilate_dim)rj   r;  hr  rz   s        rT   rl   z"_pad_shape_rule.<locals>.<genexpr>  s<      D!YaA QAE22 Ds   02c              3  &   K   | ]	  }|d k\    ywrh   ri   r  s     rT   rl   z"_pad_shape_rule.<locals>.<genexpr>  s     $Q!V$rm   zADimension size after padding is not at least 0, got result shape z, for padding_config z and operand shape )rZ   rO   r   rq   r   ro   r   r   )r  r  r  op_shaper   rs   s         rT   _pad_shape_ruler    s	   WW]q 
TBHH]<S;UV
WWXXg(	^	 0	0
 77E6F G**25 6 6 
2>2	2
 ++9*:< = = D%(%BD D&	$V$	$%h&;N;K 
,C S/	-rV   c               L    t        | ||      }t        j                  || d      S )Nr  padding)r  r+   r  )r  r  r  r  s       rT   _pad_sharding_ruler    s/     g}-;=)		4	4)
% %rV   c                  	
 t               t        j                  u rpt        j                  |      rt        j                  |j
                        nd }t        j                  |      rt        j                  |j
                        nd }||gS t        j                  |      \  
	 fd}	
 fd}t        j                  |      r |       nd }t        j                  |      rt         |        ||            nd }||gS )Nc                T    t        | t        t        j                                    S rY   )r  r   rQ   rO   )rS   r  s    rT   r   z _pad_transpose.<locals>.<lambda>  s    jDqvv$78 rV   c            	     x   t        t        j                        t        j                        t        j                              } t	        t        j
                  dj                        |       }t        j                  |t        j                        |j                  t        j                  d            S )Nr   rN   )rF   rZ   negative
zeros_liker  r   rb   r+   r  rq   r]  )unpad_configunpaddedr  interiorr  r  s     rT   t_opz_pad_transpose.<locals>.t_op  s|    bkk"or{{2 mmH57lQQWW-|<h]]8R]]2%666(A.0 0rV   )	r   r   r  r&   r   r  r   unzip3ra  )r  r  r  r  	t_operandt_padvtotalr  r  r  r  s   `       @@@rT   _pad_transposer     s    	!W.0.D.DW.MW\\*SWI131G1G1VW\\-,,-\`F V	 {{>2BH8E0 009tI020F0F}0USq5+,[_F
V	rV   c                  | \  }}|\  }}|d}t        ||j                  |   f      }t        |      }|j                  |d       |t	        |||      |fS |dk(  sJ |       t	        |t        |      |      }t	        t        |dt        j                        d|      }t        ||j                  |f      }	t        |||	      |fS )Nr   r   r   r   TF)r  rq   r   r  r  r  r  rZ   r0  r  r  )
r  r  r  r  r  rn  padding_value_bdimrS   r3  broadcasted_paddings
             rT   _pad_batch_ruler    s    ''=%/","L-"5"56H"I!KLG'.i0w~6DD	q	 4"44	 	'5>>2!	Ywbhh/	G$(*6:	a,	-|	;;rV   r  c          	         | j                   \  }t        j                  |      \  }}}t        j                  | ||||||      }t        j
                  | ||      gS rY   )r  r   r  r(   r  r  )	r  rS   r  r  r  lowrE  r  r  s	            rT   
_pad_lowerr    sT    mm)(N3#tXh=#tXF#

+
+Ch
?	@@rV   c                   | j                   S rY   r  r  s     rT   _squeeze_dtype_ruler
        	rV   c               @    t        t        j                  |       |      S rY   )_compute_squeeze_shaperZ   rq   r  s     rT   _squeeze_shape_ruler    s    	 1:	>>rV   c                   t        |      t        fdt        | j                  j                        D              }| j                  j                  | j                  j                  j                  |            S )Nc              3  0   K   | ]  \  }}|vr|  y wrY   ri   rj   r  r   r  s      rT   rl   z)_squeeze_sharding_rule.<locals>.<genexpr>  s$      )Ax'  )   rq  r   )r  r   rU  r   r   r   )r  r  r   r  s      @rT   _squeeze_sharding_ruler    sn    _( )7+;+;+@+@!A ) )(				 	   ''8'< 
! 
> >rV   c                   | j                  | j                  j                  |j                  j                  j                              S r=  r@  )rA  r  r  s      rT   _squeeze_reduced_ruler    @    	5::,,##++ - - 
. .rV   c                .    t        |      t              t        |      k7  rt        d|       t         fdD              st        d|       t	         fd|D              rt        d d|      t        fdt               D              S )Nzdimensions are not unique: c              3  P   K   | ]  }d |cxk  xr t              k  nc   ywrh   r   rj   rz   rq   s     rT   rl   z)_compute_squeeze_shape.<locals>.<genexpr>  s"     3QQ! c%j  3r|   z$dimensions outside range [0, ndim): c              3  R   K   | ]  }t        j                  |   d           ywrx  r~   r  s     rT   rl   z)_compute_squeeze_shape.<locals>.<genexpr>  s%     DAT""58Q/	/D   $'zPcannot select an axis to squeeze out which has size not equal to one, got shape=z and dimensions=c              3  2   K   | ]  \  }}|vs|  y wrY   ri   r  s      rT   rl   z)_compute_squeeze_shape.<locals>.<genexpr>  s     CTQ(1BqC   )r  r   r   ro   r  r   rU  )rq   r  r  s   ` @rT   r  r    s    _(]c*o%
2:,?
@@	3(3	3
;J<H
IIDDD
	8,	/0 0 
CYu-C	CCrV   c               J    t        j                  |      sJ t        | |      gS rY   )r&   r   r  )r  r  r  s      rT   _squeeze_transpose_ruler    s&    				((	(
a
$	%%rV   c                   | \  }|\  }t        j                  ||d      }t        t        j                  d|            }t        |j                  |      }t        dt        |            }t        ||      |fS )Nr   rN   r  )
r'   rm  r   rZ   r]  r  rq   rD   r   r  )r  r  r  r  r  r   bdim_outs          rT   _squeeze_batch_ruler"    sl    ('
%$gtQ/'RVVAz*+*'zB,q#l"34(	Z	0(	::rV   r  c               ~    ~| j                   \  }t        j                  | ||      }t        j                  | ||      gS rY   )r  r(   r  r  )r  r  r  r  r  s        rT   _squeeze_lowerr$    s:    mm)(S'8,#

+
+Ch
?	@@rV   c           
     v   t        j                  | d      }t        |       dk(  r!t        dt	        j
                  d|            S t        j                  |       rt	        j                  | |      S | D cg c]+  }t        t        t        j                  |      |      d      - }}t        |d      S c c}w )z?Converts a shape that may contain Poly values into a JAX value.Tr  r   r  r  r.  )r  r  r   rz  rZ   r   r   is_constant_shaper   r  r  r  r%  )rq   rb   rz   r  s       rT   shape_as_valuer'    s    

'
'd
;%Z1_bhhq.//	E"::e5)) 
  &t'>'>q'A5I
$ 

 
TQ	''
s   70B6c                  t        d |D              sd}t        |j                  |            t        j                  t        j                  |             }t        j                  |      }|ct        |      t        t        t        j                  |                   k7  r0d}t        |j                  |t        j                  |                   t        |      S )Nc              3  &   K   | ]	  }|d k\    ywrh   ri   r  s     rT   rl   z&_reshape_shape_rule.<locals>.<genexpr>-  s     'Q!V'rm   z/reshape new_sizes must all be positive, got {}.z_reshape dimensions must be a permutation of operand dimensions, got dimensions {} for shape {}.)ro   rp   r}  r  r  rZ   rq   r  rQ   rO   r   )r  r  r  r   rs   operand_sizenew_sizes          rT   _reshape_shape_ruler,  ,  s    	'Y'	'
;C
CJJy)
**288G,-,YYy!(
:#eBGGG$4566/ccjjRXXg->?@@	y	rV   c                   t        |      t        |       k  rdg fS | |}}d}| d   dk(  r(|d   dk(  r |dz  }| d d } |d d }| d   dk(  r	|d   dk(  r dddg f\  }}}}	|t        |      k  r0| |   ||   k(  r|	j                  | |          n|dz  }|dkD  rt        j                  | d| d|      ||   g}
|dz   }t	        j
                  |
      | |   k7  s|t        |      k  r||   dk(  rt	        j
                  |
      | |   kD  rdg fS |dz  }|t        |      k\  rdg fS |
j                  ||          |dz  }t	        j
                  |
      | |   k7  rk|t        |      k  r	||   dk(  r|	j                  |
       |dz  }|dz  }|t        |      k  r0|	j                  dg|z         t        |      t        |	      k(  sJ d|	fS )NFr   r  rN   z on more than 1 axis is not supported. Please specify the sharding of the output via the `sharding` argument of jax.lax.reshape. Got operand.shape=z and orig_new_sizes=T)r   r   r   rc  r  r  extend)r  r  r   orig_op_shapeorig_new_sizesnum_1sr  jcountr  tempnext_js               rT   _split_on_one_axisr6  :  s)   ^s8}$"9"*I-&imq0
aKF}H#2I 	imq0
 1b[!Qs	C	N{il"	jj!qje	$$f 33@/ B  "# 	#
 l^d1ufYYt_+s9~%)F*;q*@99T?Xa[(
	QI
IaL!! YYt_+s9~%)F*;q*@ 
jjFAFA1 	
C	N2 **aS6\	]	s3x	''	'	srV   c                z    t        |      t        | j                        k\  rdg fS t        || j                  d      S )NFMerging)r   rq   r6  )r  r  s     rT   _merge_on_one_axisr9  e  s4    ^s7==))"9	Iw}}i	@@rV   c                  ||S t        d | j                  j                  D              r| j                  S | j                  D cg c]
  }|dk7  s	| }}|D cg c]
  }|dk7  s	| }}||k(  rt	        | |      S t        | j                  |d      \  }}|rt        | |||      S t        | |      \  }	}
|	rt        | |
||      S t        j                  d|  d|       c c}w c c}w )Nc              3  $   K   | ]  }|d u  
 y wrY   ri   r  s     rT   rl   z)_reshape_sharding_rule.<locals>.<genexpr>n  s     2qd2   rN   	SplittingThis reshape is not supported. Please specify the sharding of the output via the `out_sharding` argument of jax.lax.reshape. Got operand type: , new sizes: )ro   r   r   rq   (_split_merge_singleton_dim_sharding_ruler6  _split_an_axis_sharding_ruler9  _merge_an_axis_sharding_ruler   rc  )r  r  r  r   r   non_1s_op_shapenon_1s_new_shapeis_split	out_splitis_mergeoperand_merges              rT   _reshape_sharding_rulerI  k  s   O2G,,1122 '81aQ8/8!*5Aa1fa55((3GYGG*7==)[Q(I'I(24 4 /w	B(M'	(24 4 	yi[:	; ; 95s   
C C 
C%%C%c                V   t        | j                  | j                  j                        D cg c]  \  }}|dk7  r| }}}t	        |      }g }|D ]5  }|dk(  r|j                  d        t        |      }|j                  |       7 | j                  j                  |      S c c}}w )NrN   r   )r   rq   r   r   r]  r   r^  r   )r  r  shspfiltered_specfsr   r  s           rT   r@  r@    s    $'w7G7G7L7L$M &"bAg  - M"( aAvood8boob 
			 	 h	 	//s   B%c                j    t        | t              r| n| f}t        j                  fd|D              S )Nc              3  <   K   | ]  }j                   |     y wrY   ry  )rj   r  rb  s     rT   rl   z!_get_spec_size.<locals>.<genexpr>  s     1Q4::a=1r  )r   r   r  r  )rL  rb  tup_sps    ` rT   _get_spec_sizerR    s*    B&2RE&	1&1	11rV   c                .   g }| j                   j                  }t        || j                   j                        D ]  \  }}t	        |t
              ry||j                  d gt        |      z         7|;|d   t        ||      z  dk(  r&|j                  |gd gt        |      dz
  z  z          tt        j                  d|  d|       |j                  |        t        |      t        |      k(  s	J ||f       | j                   j                  |      S )Nr   rN   r>  r?  r   )r   rb  rF   r   r   r   r.  r   rR  r   rc  r   r   )r  rF  r  r  r   rb  r  rL  s           rT   rA  rA    s   (					$)W%5%5%:%:; gc2#t	S)*#a&>"d+C"Cq"HvSA667$$%YmI;@A 	A
 oob 
X#i.	(?8Y*??	(				 	 h	 	//rV   c                   g }| j                   j                  }t        | j                   j                        }t	        ||      D ]  \  }}t        |t              r|D 	cg c]  }	t        |       }
}	t        d |
D              r|j                  d        R|
d   Ct        d |
dd  D              r.|,|t        |
d   |      z  dk(  sJ |j                  |
d          t        j                  d|  d|       |j                  t        |              t        |d       J t        |      t        |      k(  s	J ||f       | j                   j                  |      S c c}	w )Nc              3  $   K   | ]  }|d u  
 y wrY   ri   r  s     rT   rl   z/_merge_an_axis_sharding_rule.<locals>.<genexpr>  s     #1Q$Y#r<  r   c              3  $   K   | ]  }|d u  
 y wrY   ri   r  s     rT   rl   z/_merge_an_axis_sharding_rule.<locals>.<genexpr>  s     %@Aa4i%@r<  rN   r>  r?  r   )r   rb  r]  r   r   r   r   r^  ro   r   rR  r   rc  r   r   )r  rH  r  r  r   rb  op_specr+  op_merger   rL  s              rT   rB  rB    sf   (					$!!&&''	=9 %h(D!#+,aDM,b,	##	#qE#%@AB%@"@.A55:::1$$%YmI;@A 	A
 ood7m$%  
gt		$$	$	X#i.	(?8Y*??	(				 	 h	 	//! -s   Ec                X    t         j                  |j                  |||      \  }}|g|fS )Nr  )r  rd  r  )r   r  r  r  r   r,  r   s          rT   _reshape_typecheck_rulerZ    s9    --lliJ . (G W	rV   c                   | j                   S rY   r  )r  r  r  r   s       rT   _reshape_dtype_ruler\    r  rV   c               "   t        j                  |      sJ |7t        | |j                  j                  |j                  j
                        gS |j                  j
                  j                  t        t        d t        j                  |j                  j
                  j                  |                        }t        t        | t        j                  |j                  j                  |      |      t        j                  |            gS )Nr  c                     | | S t        |       S rY   r   )r   s    rT   r   z)_reshape_transpose_rule.<locals>.<lambda>  s    A A rV   r   )r&   r   r  r  rq   r   r   r   r   rZ   r  r   rP   rv  )r  r  r  r  r   t_ss         rT   _reshape_transpose_rulera    s    				((	(Aw||))8M8MNOO
,,


&
&c6''',,//44jAC 	D ' EC ga););Z!H+.0jj,. / /rV   c                   |\  }|\  }t        j                  ||d      }|"dt        t        j                  d|            z   }|t        j
                  | |d      }t        ||j                  d d |z   ||      }|dfS rl  )r'   rm  r   rZ   r]  r  r  rq   )	r  r  r  r  r  r   r  r  r  s	            rT   _reshape_batch_rulerc    s    ('
%$gtQ/'bffQ
344J--i1EHr*Y6
%	'#	a-rV   c                    | j                   \  }|)t        j                  |t        j                  |            }t        j
                  | ||      }t        j                  | ||      gS rY   )r  r5   rP   r(   r  r  r  )r  rS   r  r  r   r  r  s          rT   _reshape_lowerre    sX    mm)(a--j9:AS!X&#

+
+Ch
?	@@rV   c                R    t        |||      }| j                  t        |f||      S )Nr  ru  )r  rw  r  )r  rv  rS   r  r  r   rh  s          rT   _reshape_staging_rulerg    s5    )
XN&		(	(QD&5@ 
) 
B BrV   r  c                     yr%  ri   r  s    rT   r   r     r(  rV   c               .   t        dd|       t        t        |            t        |      k7  rd}t        |j	                  |            |r?t        |      | j                  k  s'd}t        |j	                  || j                              | j                  S )Nr  r  z&rev dimensions must be unique, got {}.zYrev dimensions must all be less than operand ndim, got dimensions {} for operand ndim {}.)rX  r   r  rp   r}  r   rO   rq   )r  r  rs   s      rT   _rev_shape_rulerj    sz    5,
3ZS_,
2C
CJJz*
++Z(7<<7%C
CJJz7<<8
99	rV   c                   | j                   S rY   rx  r  s     rT   _rev_sharding_rulerl    s     
		rV   c               j    | \  }|\  }|D cg c]  }||k\  r|dz   n| }}t        ||      |fS c c}w rI  r  )r  r  r  r  r  r  new_dimensionss          rT   _rev_batch_rulerp    sJ    ('
%$7AB!Q$YAEA-B.B	Wn	%t	++ Cs   0r  c                    t        | |      gS rY   rn  )r  r   r  s      rT   r   r     s    s1j/A.B rV   c                   | j                   \  }t        j                  |t        j                  |            }t        j
                  | ||      gS rY   )r  r5   reverser(   r  r  )r  rS   r  r  r  s        rT   
_rev_lowerrt    s@    mm)(At++J78#

+
+Ch
?	@@rV   c               t    t        |t        t        t        j                  f      s%d}t        |j                  t        |                  t        t        |            t        t         j                              k7  r'd}t        |j                  | j                              t         fd|D              S )Nz;transpose permutation must be a tuple/list/ndarray, got {}.zitranspose permutation isn't a permutation of operand dimensions, got permutation {} for operand shape {}.c              3  <   K   | ]  }j                   |     y wrY   ry  )rj   old_idxr  s     rT   rl   z(_transpose_shape_rule.<locals>.<genexpr>,  s     A'w}}W%Ar  )r   r   r   rZ   r   rp   r}  r   r  rQ   rO   rq   )r  r  rs   s   `  rT   _transpose_shape_rulerx  $  s    	K%rzz!:	;
GC
CJJtK01
22
6+5w||)<#==6C
CJJ{GMM:
;;	A[A	AArV   c                   | j                   j                  }|D cg c]  }||   	 }}| j                   j                  |j                  |            S c c}w )Nrq  r   )r   r   r   )r  r  o_specrw  r   s        rT   _transpose_sharding_ruler{  .  sT      &-89'fWo9(9				 	 fmmxm&H	 	II :s   Ac                   | j                  | j                  j                  |j                  j                  j                              S r  r  rA  r  r  s      rT   _transpose_unreduced_ruler~  3  s@    	5::,,  %%// - 1 
2 2rV   c                   | j                  | j                  j                  |j                  j                  j                              S r=  r@  r}  s      rT   _transpose_reduced_ruler  7  r  rV   c               d    | \  }|\  ft        fd|D              z   }d}t        ||      |fS )Nc              3  6   K   | ]  }|k  r|n|d z     ywrx  ri   )rj   r  r  s     rT   rl   z(_transpose_batch_rule.<locals>.<genexpr>>  s      EAa$hAaC/Er  r   )r   rP   )r  r  r  r  permres_bdimr  s         @rT   _transpose_batch_ruler  ;  s?    ('
%$
5EEE	E$(	7D	!8	++rV   c                  | j                   \  }t        j                  |j                  t        j                        r]t        j                  |j                        j                  }t        t        |            D cg c]  }|j                  |z    }}g ||}t        j                  |t        j                  |            }t        j                  | ||      gS c c}w rY   )r  r   r  rb   r~  r   r  rq   rQ   r   rO   r5   rP   r(   r  r  )r  rS   r  r  	elt_shaper  trailing_dimsr  s           rT   _transpose_lowerr  B  s    mm)(x~~v7**8>>:@@I05c)n0EF1X]]Q&FMF0K0-0Ka--k:;#

+
+Ch
?	@@ Gs   <CrP   c                B    t        | t        j                  |            gS rY   )rP   rZ   rv  )r  r   r  s      rT   r   r   R  s    1bjj6M)N(O rV   c                   t              dk(  rt        d      t        fddd  D              rLd}t        |j                  dj	                  D cg c]  }t        |j                         c}                  | j                  rP| j                  d   j                  k7  r4d}t        |j                  | j                  d   j                              d   j                  S c c}w )Nr   z"select must have at least one casec              3  V   K   | ]   }|j                   d    j                   k7   " ywrh   ry  )rj   caser  s     rT   rl   z%_select_shape_rule.<locals>.<genexpr>Z  s"     <$uQx~~	%<   &)rN   z1select cases must have the same shapes, got [{}].r   zfselect `which` must be scalar or have the same shape as cases, got `which` shape {} but case shape {}.)r   rp   r  r}  r   r   rq   )r  r  rs   r  s    `  rT   _select_shape_ruler  W  s    Z1_
8
99<%)<<
=C
CJJtyy)F1#agg,)FGH
II
[[U[[E!HNN25C
CJJu{{E!HNN;
<<	q *Gs   C)c                   |D cg c]/  }|j                   j                  j                  r$|j                   1 c}st        j                         S t        fddd  D              rVd}t        j                  |j                  dj                  |D cg c]  }t        |j                          c}                  | j                  re| j                   j                  j                  sE| j                   d   k7  r3t        j                  d| j                    d|d   j                    d      d   S c c}w c c}w )	Nc              3  .   K   | ]  }|d    k7    ywrh   ri   r  s     rT   rl   z(_select_sharding_rule.<locals>.<genexpr>g       6k!n	6r_  rN   z4select cases must have the same shardings, got [{}].r   r   zWselect `which` must be scalar or have the same sharding as cases, got `which` sharding z but case sharding rn   )r   rb  r  r   r  r  rc  r}  r   r   rq   )r  r  r  rs   r  s       @rT   _select_sharding_ruler  c  s   %*H!**//2G2GH+	%%''6k!"o66
@C

 
 

499u=!c!**o=>?A Akk%..--33nnA&

 
 	"^^, -!Ha	!" " 
Q I >s   %D6D6D;c                   t        dg|  t        j                  | j                  t        j
                        sGt        j                  | j                  t        j                        st        d| j                   d      t        j                  | j                  t        j
                        rt        |      dkD  rt        d      |d   j                  S )Nr  z4select `which` must be boolean or integer type, got rn   rM   z2select with boolean `which` cannot have > 2 cases.r   )	rV  r   r  rb   rZ   r0  r1  rp   r   r  s     rT   _select_dtype_ruler  t  s    H%u%


EKK
2


EKK
4
J{{m1& ' 'u{{BHH-#e*q.
H
II	qrV   c                &    t        d |D              S )Nc              3  4   K   | ]  }|j                     y wrY   r   r  s     rT   rl   z)_select_weak_type_rule.<locals>.<genexpr>  s     (QQ[[(r1  )ro   r  s     rT   _select_weak_type_ruler  ~  s    	(%(	((rV   c                   t        j                  |      rJ t        |       t        j                  u rHd g|D cg c]8  }t        j                  |      rt        j                  |j
                        nd : c}z   S t        | d      }t        j                  |      t        j                  t        j                        k(  rSt        j                  |d         rt        |||       nd }t        j                  |d         rt        || |      nd }d ||fS d gt        |      D cg c]=  \  }}t        j                  |      r!t        t        |t        ||            | |      nd ? c}}z   S c c}w c c}}w r5  )r&   r   r   r   r  r  r  r   rb   rZ   r0  r  rU  rz  r  )	r  r  r  r  r  ct0ct1r  r  s	            rT   _select_transpose_ruler    sH   ##E**	*	!W6#% .0-C-CA-FW\\!&&)DP % % % aOE||Ebhhrxx00')'='=eAh'GF5%#Tc')'='=eAh'GF5!U#TcCVCLUCS8?4R##D) E6%+,a
7/34  %s   =E+#AE0c           
       
 |^}|^
t        d t        ||      D              }t        fd
D              rt        j                  |      t        j                  d         k(  rt        |g fS t        j                  |      dk(  sJ t        |d   j                  gt        j                  d         j                        }t        |g fS t        j                  |      dk(  rt        d 
D              rt        
fd
dd  D              rt        |g 
d   fS t        fdD              rP
d   }t        dd  
dd        D cg c]  \  }}t        j                  |||       }	}}t        |d   g|	 |fS t        j                  |      r"t        j                  ||| j                        n|}t        d	 D              s?t        
      D cg c]'  \  }}t        j                  |||| j                        ) c}}t        fd
dd  D              sJ dt        j                  |      cxk  rt        j                  d         k  rZn nWt        j                  |      dk(  sJ t        |d   j                  dgt        j                  d         j                        }t        j                  |      t        j                  d         kD  rAt        j                  d         dk(  sJ D cg c]  }t        ||j                         c}t        |g dfS c c}}w c c}}w c c}w )Nc              3  D   K   | ]  \  }}||j                   |     y wrY   ry  r  s      rT   rl   z%_select_batch_rule.<locals>.<genexpr>  r  r  c              3  (   K   | ]	  }|k(    y wrY   ri   )rj   r  
which_bdims     rT   rl   z%_select_batch_rule.<locals>.<genexpr>  s     3t	3r0  r   rN   r  c              3  $   K   | ]  }|d u 
 y wrY   ri   )rj   r  s     rT   rl   z%_select_batch_rule.<locals>.<genexpr>  s     "K4t#3"Kr<  c              3  .   K   | ]  }d    |k(    ywrh   ri   )rj   r  
case_bdimss     rT   rl   z%_select_batch_rule.<locals>.<genexpr>  s     
<T:a=D 
<r_  c              3  z   K   | ]2  }t        j                  d          t        j                  |      k(   4 ywrh   rZ   rq   rj   r  r  s     rT   rl   z%_select_batch_rule.<locals>.<genexpr>  s+     >1RXXeAh288A;.>   8;c              3  L   K   | ]  }d t        j                  |      k(    ywri   Nr  r  s     rT   rl   z%_select_batch_rule.<locals>.<genexpr>  s     .1R288A;.s   "$c              3  z   K   | ]2  }t        j                  d          t        j                  |      k(   4 ywrh   r  r  s     rT   rl   z%_select_batch_rule.<locals>.<genexpr>  s+     B1RXXeAh288A;.Br  )r^  r   ro   rZ   rq   r  rO   r  r   r  r   r'   rm  r  explicit_mesh_axisr  )r  r  r  unused_kwargsr  r  r  r  c_bdimother_casesr  r  r  s             @@@rT   _select_batch_ruler    s   -%%&*z	  Sz%B   
 $ 	3
33	xx"((58,,e$e$j00 WWU^q   ueAhnnzl,0KKa,A,J,JLee$e$j00	wwu~s"K
"KK

<Z^
<<e$e$jm33	>>	>]d&)%)Z^&DF"F &&q&$7 Fk FeU1X44d:: hhuo !!%T"+">">@#(  
..	.z24D ##AtT93O3OP 4E	Bab	B	BB	B+"''%(++775>QUE!HNNQC*.++eAh*?*H*HJEWWU^bggeAh''7758!!!0561Yq%++&6E	%	 %	 !	##'F4 7s   !M-,MMc                T   | ^}}|dd  }t        |g| }t        d |D              r&t        j                  |d   j                        }||fS t        t        d |D                    }|D cg c]!  }t        |      t        j                  u r|n|# }}t        |g| }||fS c c}w )NrN   c              3  R   K   | ]  }t        |      t        j                  u  ! y wrY   r  r  s     rT   rl   z_select_jvp.<locals>.<genexpr>  s     8QaGLL	 8r  r   c              3  X   K   | ]"  }t        |      t        j                  us| $ y wrY   r  r  s     rT   rl   z_select_jvp.<locals>.<genexpr>  s     L!Qw||0KALs    **)r  ro   r   r  r  r  r^  r   )	rF  rG  r  case_primalscase_tangentsr  out_dotzr  s	            rT   _select_jvpr    s     %,12,-&&#8-88ll=+001G
 
g 	tL}LLMABOPQ$q'W\\1Qq8PMPu-}-G	g Qs   -&B%c                <   | j                   }| j                  \  t        fd|dd  D              sJ t        fd|dd  D              sJ t        }t	        j
                        }|gt        |      dz
  z  }|d   }|j                  |j                        }|j                  d |j                   |j                  k(  sJ t        t        |j                              }	t        j                  | |||	      }
t        j                  | ||
g||g||gdd   S )Nc              3     K   | ]5  }|j                   |j                  fj                   j                  fk(   7 y wrY   r  rj   	aval_caser  s     rT   rl   z._select_hlo_lowering_opaque.<locals>.<genexpr>  s8      , ooy/HNNHNN3SS ,s   ;>rN   c              3     K   | ]I  }|j                   j                  j                  s'j                   j                  j                  s|k(   K y wrY   )r   rb  r  r  s     rT   rl   z._select_hlo_lowering_opaque.<locals>.<genexpr>  sI      Q )$$**83D3D3I3I3O3O 8Qs   AAr   r  r  r  )r  r  ro   _select_hlo_loweringr   r  r   r   rb   rq   rO   r   rQ   r(   r  r  )r  r  r  r  select_lowerphysical_aval_outphysical_avals_cases
aval_whichaval_which_bcast
bcast_dimswhich_bcastr  s              @rT   _select_hlo_lowering_opaquer    sQ   \\(mm)(	 ,&qrl, 
, , 
,	 Q-5ab\Q 
Q Q 
Q &,((2+,H0AB{*&--J4D4D-E			 0	1Z5E5E	EE	EE*//*+*%%	5"E+ 
			<
%',
% 8#78"#
% &'
( (rV   c                     j                   d    j                  \  }t        j                  |j                  t        j
                        r%t         g| }t        j                   ||      gS j                  t        j                  t        j                        k(  rUt        |      dk  sJ t        |      dk(  r|S t        j                  |d   |d         }t        j                   ||      gS t        j                  j                  t        j                        rdndd fd d|      }t        j                   ||      gS )Nr   rM   rN   r  r  r  c           
     "   t        |      dkD  sJ t        |      dk(  r|d   S t        |      dz  }t        j                  t        j                  | |z   	            }t	        j
                  | | |d |        | |z   ||d              S )Nr   rN   rM   )r   r(   r  r  r5   r  )
r  r  midr  _selectr  r  r  r  
which_avals
       rT   r  z%_select_hlo_lowering.<locals>._select  s    u:>>
5zQ1Xo
e*/CE //Vc\:N.D ::dGFE$3K8fslE#$K8: :rV   )r  r  r   r  rb   r~  r  r(   r  rZ   r0  r   r5   r  r  )	r  r  r  r  r$  r  r  r  r  s	   ``   @@@@rT   r  r    s#   ||A*mm)(x~~v7	$S%	8%	8B--c2x@AA"((++u:??
5zQu	E58U1X	.B--c2x@AAz'')9)9:LL"	: 	: q%"

+
+CX
>	??rV   r  c                     yr%  ri   r  s    rT   r   r     r(  rV   c           	     .   t        |t        |      dz  g      \  }}t        d |D              r'|D cg c]  }|j                   }}t	        d|       |D cg c]+  }t        t        j                  |j                  |            - c}S c c}w c c}w )NrM   c              3  :   K   | ]  }|j                   d k7    ywr  ry  )rj   r  s     rT   rl   z%_reduce_shape_rule.<locals>.<genexpr>  s     3Sb3s   z'reduce found non-scalar initial value: )rG   r   r  rq   r   r   rZ   rh  )	r  r  r  r   operand_avalsinit_val_avalsr   init_val_shapesr$  s	            rT   _reduce_shape_ruler    s    ",USZ1_4E"F-3N33(671qww7O7
>>OP
QQ;H	IR%		"((J/
0	II 8	Is   B0Bc           	         t        |t        |      dz  g      \  }}|D cg c]<  }|j                  j                  t	        |j                  j
                  |            > c}S c c}w )NrM   r   )rG   r   r   r   r1  r   )r  r  r  r   r  r   r$  s          rT   _reduce_sharding_ruler    sa    E
a'89-!
# ++

,r{{/?/?"L

M 
# # 
#s   AA%c                    t        |t        |      dz  g      \  }}t        j                  dg| }|gt        |      z  S )NrM   r  )rG   r   r   rq  )r  r  r  r   r  r   r  s          rT   _reduce_vma_ruler    sE    E
a'89-""8<m<'
S'	''rV   c                    t        |t        |      dz  g      \  }}|D cg c]  }|j                   }}|D cg c]  }|j                   }	}||	k7  rt        d| d|       |S c c}w c c}w )NrM   zTreduce operand dtypes should match corresponding initial value dtypes, got operands=z and initial_values=)rG   r   rb   rp   )
r  r  r  r   r  r  r$  operand_dtypesinitinit_val_dtypess
             rT   _reduce_dtype_ruler     s    ",USZ1_4E"F-'45BHH5.5,:;DTZZ;/;&
	%&:>:J	LM M 
 6;s
   A'A,c                    t        |t        |      dz  g      \  }}t        ||      D cg c]  \  }}|j                  xr |j                  ! c}}S c c}}w r  )rG   r   rF   r   )r  r  r  r   r  r  r$  init_vals           rT   _reduce_weak_type_ruler  *  s_    ",USZ1_4E"F-&}nE
Gb( ,,
-8--
- 
G G 
Gs   $Ac          	        t        |       dz  }t        | |g      \  }}t        ||g      \  }}	t        d |	D              rt        d t	        | |      D              }
t	        ||      D cg c]  \  }}t        j                  |||
       }}}|D cg c]  }|dz   	 }}dg|z  }t        j                  ||z   |t        |      |d|fS t        c c}}w c c}w )NrM   c              3  @   K   | ]  }|t         j                  u   y wrY   )r'   
not_mapped)rj   init_value_bdims     rT   rl   z%_reduce_batch_rule.<locals>.<genexpr>5  s#      	2 
H//	/ 	2s   c              3  D   K   | ]  \  }}||j                   |     y wrY   ry  )rj   rS   r=  s      rT   rl   z%_reduce_batch_rule.<locals>.<genexpr>7  s(      #2>  #r  rN   r   )r  r  r  )r   rG   ro   r^  r   r'   r  r  r   r   r  )r  r  r  r  r  num_operandsr#  r  operand_bdimsinit_value_bdimsr  r  r  rz   ro  new_operand_bdimss                   rT   _reduce_batch_ruler  /  s	    \"a',$\L>B(K$.zL>$J!-! 	2 0	2 2 #\:)F # #D "%X}!=?C &&sD$7 ?H ?%/0a!e0N0l*==8k1%0$).$9$& (99 9
 ?0s   ,!CCc                >   	
 t        j                  |d   j                  t              t        j                  t        |               }t        j                  t        j                  t                    |      
|t        
      z   |ft        
         z   	t        	fd|D              }t        	fd|D              }t        t        
      dz         D ]  }t        j                           dd
 fd
}t        j                  |||      S )Nr   r  c              3  8   K   | ]  }t        |        y wrY   r  )rj   rS   r   r  s     rT   rl   z_reduce_jvp.<locals>.<genexpr>M  s     F'!Y4F   c              3  8   K   | ]  }t        |        y wrY   r  )rj   r  r   r  s     rT   rl   z_reduce_jvp.<locals>.<genexpr>N  s     H!71i5Hr  rN   ro  c           	         |d   j                       dkD  r|d   j                       }|dz   dz  }||z
  }|D cg c]  }t        j                  |d|       }}|D cg c]  }t        j                  ||d       }}||k7  rJdgt        |d   j                         z  }d| <   t	        |      D 	
cg c]  \  }	}
t        |	|
|       }}	}
 ||z    }|d   j                       dkD  r|d   j                       dk(  rD 
cg c]  }
t           |
       c}
S t         fd|D              S c c}w c c}w c c}
}	w c c}
w )z9Reduce by repeatedly splitting the array and multiplying.r   rN   rM   Nr  )r   rN   r   c              3  8   K   | ]  }t        |f        y wrY   )r  )rj   rS   r)  s     rT   rl   z4_reduce_jvp.<locals>._reduce_tree.<locals>.<genexpr>a  s     1TG$1r  )rq   r+   slice_in_dimr   r   r  rz  r   )r)  r>  r  n1n2rS   xs1xs2paddingsr   r  r  input_shapenon_axesreducers   `          rT   _reduce_treez!_reduce_jvp.<locals>._reduce_treeR  sR   
Q%++d
a

Q%++d
aEa<br6b578W!!!Q+8c88:;1W!!!R.;c;	r;RU[[!11"14S+1FGAs2q(#GGS3Y b Q%++d
a
 
!u{{4A6ABd;x(!,BB1b111 9; H Cs   D2D74D<E)rZ   r   rq   r   r  r   rh  aranger   r   rQ   r   r9  jvp)r  r  rF  rG  r  r  rz   r  r  r   r  r  s   ``      @@@@rT   _reduce_jvpr  D  s    ))5+ggk$t*%&!YYryy[!12D9( uX&+dU;x011)FgFF'HxHH(X"#  ahhwG  2 2" 
w	11rV   c                   t        | t        |       dz  g      \  }}t        |t        |      dz  g      \  }}t        d |D              rt        d      t	        j
                  |      }	t        |	||||      S )NrM   c              3  R   K   | ]  }t        |      t        j                  u ! y wrY   r  r  s     rT   rl   z#_reduce_jvp_rule.<locals>.<genexpr>j  s     ;a	$;r  zeGradient of general lax.reduce with non-zero tangents for initial values to reduction not implemented)rG   r   r  r  r   r  r  )
rF  rG  r  r  r  	primal_xsr  
tangent_xstangent_initr  s
             rT   _reduce_jvp_ruler	  e  s    %gG0A/BC)['3x=A3E2FG*l 	;l;;
45 5 e$'	Wk9j*	MMrV   r  c          	        t        d | j                  D              sJ | j                         t        j                  |t	        |      dz  g      \  }}| j                  t	        |      dz  d  }t        j                  | j                  D cg c]  }t        j                  |       c}||t        j                  |            }	|D cg c]  }t        j                  |       }
} |	j                  d   j                  j                  |
|
z    }t        j                  |      5  t!        j"                         }|j$                  rt'        d      t        j(                  | j*                  |j,                  |t        j.                         |j0                  g|j2                  | j4                  | j6                  d\  }}t        j8                  t        j:                  |             d d d        t=        |	j>                  | j                        D cg c]  \  }}t        j@                  | ||       c}}S c c}w c c}w # 1 sw Y   [xY wc c}}w )Nc              3  P   K   | ]  }t        |t        j                           y wrY   r   r   r!   r  s     rT   rl   z _reduce_lower.<locals>.<genexpr>}       CZ4++,Cr  rM   r   z Cannot lower effectful `reduce`.)dim_var_valuesr  )!ro   r  r   rG   r   r5   ReduceOpr  r(   r  r  regionsblocksr   r3   InsertionPointr   new_name_stackr   r  jaxpr_subcompr  r  TokenSetr  	argumentsr	  r  return_r  rF   r  r  )r  r  r  r  r  r#  r  init_value_avalsr  r$  ir_typesr  
name_stack	out_nodesr   r<  s                   rT   _reduce_lowerr	  {  s   	CcllC	CQS\\Q	C//&3v;!3C2DE(K\\#f+"2"34
||CMMJDT))$/Jk4+?+?
+KM"5EFTd""4(F(F'BJJqM  ''(X*=?'	! 
3!002J}} BCC%%c&8&8%++&0$--/&+llI (/'8'8I 695G5G585G5GILIq KK&&y12
3 ""**cmm<
>a 
+
+CD
9 
> > KF
3 
3
>s   H8	H=%CI!IIc                    t        j                  |j                  t        j                        s.t        dj                  | t        |j                                    |j                  S )NzD{} does not accept dtype {}. Accepted dtypes are subtypes of number.)r   r  rb   rZ   numberrp   r}  r0   )r   r  r  r  s       rT   _reduce_number_dtype_ruler	    sM    			7=="))	4
 !!'ogmm.L!MO O	rV   c          	     \   t        j                  |      sJ |j                  j                  }t	        t        j                  t        j                  t        |            |            }t        | |||j                  j                         j                        }|j                  |k(  sJ |gS )Nr  )r&   r   r  rq   r   rZ   rh  r  r   r  r{  r   )rj  r  r  r  r  r  r   s          rT   _reduce_sum_transpose_ruler	    s    				((	(""+ryy3{3C)DdKL2<<113<<>& 
	$$	$
/rV   c                   ~|\  }t        |j                        D 	cg c]-  \  }}	t        |	t        j                        r||	j
                  f/ }
}}	t        | ||j                        |
      } | ||      gS c c}	}w rY   )rU  rq   r   r  BoundedAxisSizera   _replace_masked_valuesrb   )	traceableidentr  r  r  r  r  r  r  rz   padded_axesoperand_s               rT   _reducer_paddingr!	    sy    
%$(1$**(= 71q""4"45 QUU 7+ 7#GU4::->L(
Hd
#	$$7s   2A:c           	         |s| S t        j                  t              }|D cg c]  \  }}t        || j                  |      |k  ! }}}t        t        t        j                  |      | t        | |            S c c}}w rY   )
r   scalar_type_to_dtyper   r  rq   r  r  r  r  r  )rS   ra   r	  rb   r  rz   maskss          rT   r	  r	    sj    	Qh

%
%c
*%?J
Ktq!E177A.2
K%
K	u-q)As2C	DD Ls   $A9)r  c                   ~t              t        t                    k7  rt        d       t         fdD              st        d d  d      t	              t        fdt         j                        D              S )Nz(duplicate value in 'axes' of reduction: c              3  R   K   | ]  }d |cxk  xr j                   k  nc    ywrh   r   )rj   r   r  s     rT   rl   z(_reduce_op_shape_rule.<locals>.<genexpr>  s"     1qQ!"gll""1r  zreduction axes z$ contains out-of-bounds indices for rn   c              3  2   K   | ]  \  }}|vs|  y wrY   ri   )rj   r  rz   r  s      rT   rl   z(_reduce_op_shape_rule.<locals>.<genexpr>  s     GTQ$qGr  )r   r  r   ro   r  r   rU  rq   )r  r  r  r  s   ``  rT   _reduce_op_shape_ruler(	    s|    Y#c$i. 
?vF
GG	1D1	1
tf,PQXPYYZ[
\\	4$	GYw}}5G	GGrV   c                   |t        |t              sJ |S t              t        t	        fdt        | j                  j                        D               }| j                  j                  |      S )Nc              3  0   K   | ]  \  }}|vr|  y wrY   ri   rj   r  r   r  s      rT   rl   z,_reduce_sum_sharding_rule.<locals>.<genexpr>  #      (DAq$  (r  r   )	r   r8   r  r   r   rU  r   r   r   )r  r  r  r   s    `  rT   _reduce_sum_sharding_ruler-	    sp    lM222	4$ (Ig.>.>.C.C$D ( ( )(				 	 h	 	//rV   c                  |j                   j                  j                  rt        j                  d|      | j                  j                  x}rnt              t        fdt        |j                   j                        D              t        fd|D              st        j                  d|dd|       | S )Nz>operand passed to reduce_sum cannot be unreduced. Got operand=c              3  f   K   | ](  \  }}|v st        |t              r|n|fD ]  }|  * y wrY   )r   r   )rj   r  r   r   r  s       rT   rl   z-_reduce_sum_unreduced_rule.<locals>.<genexpr>  sG      AaQ$Y$T51$wA 	
A	As   1!1c              3  &   K   | ]  }|v  
 y wrY   ri   )rj   urj  s     rT   rl   z-_reduce_sum_unreduced_rule.<locals>.<genexpr>  s     9QqL 9s   z^out_sharding's unreduced axes should be in operand's specs that were summed over. Got operand=z, axes=z, unreduced_spec=)r   r   rR  r   rc  r  rU  ro   )rA  r  r  r  unreduced_specrj  s     `  @rT   _reduce_sum_unreduced_ruler3	    s    $$

 
 
I
KM Mzz+++^+T?D A"7#3#3#8#89A AL 9.99""-$+:Xw 7+,./ / 
,rV   c                   | j                  | j                  j                  |j                  j                  j                              S r=  r@  )rA  r  r  r  s       rT   _reduce_sum_reduced_ruler5	    r  rV   r  c               \    d }t        |t        | d   d      g| ||      \  }}|d   |d   fS )Nc                    t        | |      gS rY   r  r#  s     rT   r   z'_reduce_prod_jvp_rule.<locals>.<lambda>  s    #a) rV   r   rN   )r  r  )rF  rG  r  r  primals_outtangents_outs         rT   _reduce_prod_jvp_ruler:	    sC    $')'F71:q4I3J*18TC+|	Qa	((rV   c                   t              t        t        fdt        | j                  j
                        D               }| j                  j                  |      S )Nc              3  0   K   | ]  \  }}|vr|  y wrY   ri   r+	  s      rT   rl   z+_reduce_op_sharding_rule.<locals>.<genexpr>  r,	  r  r   )r  r   r   rU  r   r   r   )r  r  r   s    ` rT   _reduce_op_sharding_ruler=	    sT    	4$ (Ig.>.>.C.C$D ( ( )(				 	 h	 	//rV   r3  c          	        t        |j                        D cg c]  \  }}||v rdn| }}}t        t        |t	        ||            | j
                        }t        ||      }t        t        t        | |      |      |      S c c}}w rI  )	rU  rq   r  _eq_meetr  rb   r  rg  rd  )	r  r  r  r  r  rz   rq   location_indicatorscountss	            rT   _reduce_chooser_jvp_rulerB	    s     .7w}}-E
FTQT	1q 
F%
F,wU+,agg7)40&	ZA23T:F	CC	 Gs   Br:  r<  c                  |\  }d|cxk  rt        | j                        k  sn t        d| d| j                         | j                  |   dk  rt        d| j                   d|      t        j                  | j                  |      S )Nr   zInvalid axis r  rN   zEargmin and argmax require non-empty reduced dimension. operand.shape=z axis=)r   rq   r   r   r1  r  r  r  r)  s       rT   _argminmax_shape_rulerE	    s    
%$
t
(c'--(
(
}TF*=gmm_M
NN]]41
 &&-mm_GdW> ? ?			7==$	//rV   c                   |\  }| j                   j                  t        j                  | j                   j                  |            S Nr   )r   r   r   r1  r   rD	  s       rT   _argminmax_sharding_rulerH	    sC    
%$				 	 
((--t4 
! 
6 6rV   c                   t        j                  |t        j                        s#t	        dj                  t        |                  |S )Nz/index_dtype must be an integer type, but got {})r   r  rZ   r1  rp   r}  r0   )r  r  r  s      rT   _argminmax_dtype_rulerJ	    s;    			;

	3
EVOK89; ;	rV   c                       e Zd ZddZd Zd Zy)_ArgMinMaxReducerc                    || _         y rY   )_value_comparator)r   value_comparators     rT   r   z_ArgMinMaxReducer.__init__&  s
    -DrV   c                6    d| j                   j                   dS )Nz_ArgMinMaxReducer(r/  )rN	  r   r7  s    rT   r8  z_ArgMinMaxReducer.__repr__)  s        6 6 ? ?@BBrV   c           
         |\  }}|\  }}t        | j                  ||      t        ||            }t        |t        t	        ||      t        ||                  }t        |||      t        |||      fS rY   )rQ  rN	  r~  rM  rz  r  r  )	r   op_val_indexacc_val_indexop_valop_indexacc_val	acc_indexpick_op_valpick_op_indexs	            rT   __call__z_ArgMinMaxReducer.__call__/  s    #FH&GYT33FGD/1K {*2fg+>+-h	+B DEM ;0=(I68 8rV   N)rO	  Callable[[Any, Any], Any])r   r   r   r   r8  rZ	  ri   rV   rT   rL	  rL	  $  s    .C8rV   rL	  c                   |\  }t        |t        j                  |      ||j                  j                        }t        ||g ||j                        t        j                  d|      gt        |       |      }|d   S )Nr  r   rN   )	r  rZ   rq   r  r   r  rb   r   rL	  )rO	  get_identityr  r  r  r)  r  r  s           rT   _compute_argminmaxr^	  <  sx     %$288G$d<<((*' 	!W]]+RXXa-EF !12	# 
Q-rV   r  r
  )inlinec                  | j                   t        j                  k7  rGt        j                  | j                   t        j                        st        d| j                    d      t        t        j                  | j                  |            S )Nz:logical reduction requires operand dtype bool or int, got rn   )	rb   rZ   r0  r  r1  rp   r   rh  rq   rV  s     rT   _reduce_logical_shape_rulera	  j  s_    ]]bhhr}}W]]BJJ'O
PQXQ^Q^P__`a
bb	ryy-	..rV   c               v    | j                   j                  t        | j                   j                  |            S rG	  )r   r   r1  r   rV  s     rT   _reduce_logical_sharding_rulerc	  o  s/    				 	 l73C3C3H3H$&O	 	PPrV   c                   | \  }t         j                  ||      }t        j                  |      j	                         |ddfdfS )NrT  Fri   c                .    t        j                        S rY   )r   r  )r   r  r  s     rT   r   z _reduce_or_lin.<locals>.<lambda>v  s    GLL$6 rV   )r]  r   r   r  to_tangent_aval)r  rS   r  r  r$  r  s        @rT   _reduce_or_linrg	  r  sE    #"qt$!	Q	'	'	)$	
E26	66rV   r5  r7  r8  c          	        |j                   \  }|j                  }t        j                  t	        j
                  |      g|gt	        j                   ||j                              gt	        j                  |            }t	        j
                  t        j                  d|            }	|j                  d   j                  j                  |	|	      }
t        j                  |
      5  t        j                   | |
j                    g       d d d        t	        j"                  ||j$                  |      gS # 1 sw Y   +xY w)Nri   r   )r  rb   r5   r	  r(   r  r  r  r   r!   r	  r		  r   r3   r
	  r	  r	  r  r   )r  unit_factoryr  rS   r  r  r  rb   r$  scalar_typereducer_regions              rT   r  r    s    mm)(
..%
||T))(34qc%%l8>>&BCD((.0" $$T%5%5b%%@A+::a=''..{KH.	( 6KK.223456

+
+CH
E	FF6 6s   &$D44D=c                   t        j                  |      }t        j                  |      }|dk  rt        d|       |dk  rt        d|       | j                  S )NrN   z6reduce_precision: exponent_bits must be positive; got r   z:reduce_precision: mantissa_bits must be non-negative; got )r  r  r   rq   r  s      rT   _reduce_precision_shape_rulerm	    s`    ../-../-Q
Mm_]
^^Q
QR_Q`a
bb	rV   c                   | j                   S rY   rx  r  s      rT   _reduce_precision_sharding_rulero	    r  rV   r  )r   rF  rG  c                0    t        j                  | fi |gS rY   )r  r   )r  r  s     rT   r   r     s    6H6M6Ma6ZSY6Z5[ rV   c                   | j                   \  }t        j                  |t        j                  |      t        j                  |            }t        j
                  | ||      gS rY   )r  r5   r  r(   r	  r  )r  r  r  r  r  r  s         rT   _reduce_precision_lowerrr	    sN    mm)(WdmmM&B!]]=9	;#

+
+Ch
?	@@rV   )       @   c                     t                t         fd dd  D              r&dj                  d  D              }t        d|        D cg c]N  }|j                  j
                  j                  s,|j                  j
                  j                  r|j                  P c}t        fddd  D              r0dj                  d D              }t        j                  d|        S c c}w )	Nc              3  V   K   | ]   }|j                   d    j                   k7   " ywrh   ry  )rj   r  r   s     rT   rl   z&_sort_abstract_eval.<locals>.<genexpr>  s"     :eAhnn	$:r  rN    c              3  F   K   | ]  }t        |j                          y wrY   r  rj   r   s     rT   rl   z&_sort_abstract_eval.<locals>.<genexpr>  s     2qc!''l2r  z/Arguments to sort must have equal shapes, got: c              3  .   K   | ]  }|d    k7    ywrh   ri   r  s     rT   rl   z&_sort_abstract_eval.<locals>.<genexpr>  r  r_  c              3  2   K   | ]  }t        |        y wrY   r_  r  s     rT   rl   z&_sort_abstract_eval.<locals>.<genexpr>  s     5AQ5s   z2Arguments to sort must have equal shardings, got: )
r   r  r   rp   r   rb  r  _any_axis_explicitr   rc  )r   r  ru   r   	shardingsr  s   `    @rT   _sort_abstract_evalr	    s    
,%:ab	::XX2E22F
EfXN
OOKZZ__""qzz'I'I jjK+ 	6k!"o66555I

 
 
<YKHJ J	,Ks   AC.c                
   t        t        | t        |             t        |       |       }t	        j
                  d      5  t        t        |       t        |t        j                        |      }d d d        |S # 1 sw Y   |S xY wr'  )
r  rz  r  r  r   
debug_nans_isnanr  rZ   nan)rS   r   s     rT   _canonicalize_float_for_sortr	    sl     "Qa/6!9a0& BF1Iy8&AFB 
-B 
-s   /A88B)rf  c           
     D   t        |d| i\  }}d }t        |d d d   |d d d         D ]t  \  }}t        j                  ||      \  }}|>t	        t
        j                  ||      t        t        j                  ||      |            nt
        j                  ||      }v |S Nrf  r  )	_operands_to_keysr   r   r   rQ  lt_to_pr   rM  eq_to_prf  r#  x_keysy_keysr  xkyks          rT   _sort_lt_comparatorr	        $hBB.&&
!F4R4L&2,/ $fb"''B/FBSTS`GLLR(+gll2r6JA*N	Oll2r" $ 
(rV   c           
     D   t        |d| i\  }}d }t        |d d d   |d d d         D ]t  \  }}t        j                  ||      \  }}|>t	        t
        j                  ||      t        t        j                  ||      |            nt        j                  ||      }v |S r	  )
r	  r   r   r   rQ  r	  r   rM  r	  le_to_pr	  s          rT   _sort_le_comparatorr	    r	  rV   c           	        t        |      dk\  rt        |      dz  dk(  sJ |       t        |      dz  | k\  s	J || f       g g }}t        |d d| z  d   |dd| z  d         D ]_  \  }}|j                  |j                  k(  sJ |j                  |j                  f       t        j                  |j                  t
        j                        ro|j                  t        t        |            t        t        |            g       |j                  t        t        |            t        t        |            g       t        j                  |j                  t
        j                        r6|j                  t        |             |j                  t        |             >|j                  |       |j                  |       b ||fS )NrM   r   rN   )r   r   rb   r   r  rZ   r  r.  r	  r(  r,  r  r   )rf  r#  r	  r	  rS   r$  s         rT   r	  r	    s}   	X!	H 1Q 6@@	6	X!	x	'=(H)==	'r&&(=AhJq=)8AajN+CD 
da77agg111""4"45mm1$q':<XY]^_Y`<abcmm1$q':<XY]^_Y`<abc			177BKK	0mm034mm034mmAmmA
 
rV   c          	        | d   j                   }t        j                  |d      }t        j                  g | t        |||      |||d}t        t        j                  t        j                  t        |      t        j                        |            }t        j                  d|f|f||      }	t        |d   t        |      f      }
t        t        j                   |
|	d	t        |      z  t        j"                  j$                  
      }|D cg c]'  }t'        |      t(        j*                  u r|n ||      ) }}t        |d d       |fS c c}w )Nr   Fr  rj  r  ri   )offset_dimscollapsed_slice_dimsstart_index_mapoperand_batching_dimsstart_indices_batching_dimsr  r   )r  r  slice_sizesr  )rq   r  r  rk  r   r  r   rZ   rh  r  r   r  r+   GatherDimensionNumbersr  r   gatherGatherScatterModePROMISE_IN_BOUNDSr   r   r  )rF  rG  r!  re  rf  rq   r  sorted_primals_and_idxr  dnumsrk   
gather_idxr  r9	  s                 rT   	_sort_jvpr	  !  sM   
!*

%--eEB+!;; CC{E95C YC RYYryyU288D(* +*

(
(#L$ *% 	*2.U>#NND3u:<M		"	"	4	4* $% Aw',,.!JqMA %, %	%cr*	+\	99%s   ,Ec                  t        d t        | |      D              \  }}g }t        | |      D ]  \  }}	|	yt        j                  t        j                  |j
                        |      }
|j                  t        ||j                  |
t        j                  |      j                               |j                  t        j                  ||	|              |||k  z   }|ft        |      z  }t        j                   ||||d|fS )Nc              3  0   K   | ]  \  }}|	||f  y wrY   ri   )rj   r   r}  s      rT   rl   z#_sort_batch_rule.<locals>.<genexpr><  s#      !Gq!QF!Gs   
	r  rj  )r^  r   rZ   rh  r  rO   r   r  rq   r   r  r   r'   rm  r   rk  r   )r  r  r!  re  rf  prototype_argnew_bdimnew_argsr  r  r  new_dimensionr  s                rT   _sort_batch_ruler	  ;  s      !G<4!G G-(|Z0 >ic4|YYryy!3!34h?doo&
}""D{{=1::< = ooh''T8<=> x945-+H
%%
++x=IX`
a

 rV   rg  c          
        t        d | j                  D              sJ | j                         t        j                  | j                  D cg c]  }t        j                  |       c}t        j                  |      t        j                  |      t        j                  j                  |            }d }| j                  D cg c]  }|j                  d ||             }}t        t
        j                  |      }	 |j                  j                  j                   t#        j$                  t'        |	|	             }
t        j(                  |
      5  t        j*                  t-        t.              d      }| j1                  d t#        j$                  t'        ||            t3        j4                  dt6        j8                        g      } ||g|
j:                  d	|i}t        j<                  t        j                  |             d d d        |j>                  S c c}w c c}w # 1 sw Y   |j>                  S xY w)
Nc              3  P   K   | ]  }t        |t        j                           y wrY   r	  r  s     rT   rl   z_sort_lower.<locals>.<genexpr>V  r	  r  )r!  re  c                J    | j                   j                  t                     S rG	  )r   r   r   r   s    rT   r   z_sort_lower.<locals>.<lambda>[  s    qzz((ac(2 rV   ri   r   Fr  )	primitiver  r  rf  ) ro   r  r5   SortOpr  r(   r  r  r  r3   BoolAttrr  r   rE   
comparatorr		  r   r   flattenr   r
	  r  r   r	  r  r   r!   rZ   r0  r	  r	  r  )r  r!  re  rf  r#  r  rg  scalar_sscalar_avalsscalar_typesr	  lower_comparatorsub_ctxr  s                 rT   _sort_lowerr	  U  s   	CcllC	CQS\\Q	C	CMMJDT))$/J**84"mmI6 kkooi8
:$ 3(!ll, ++B$+@ ,, ,$..=,,t%%,,||Cl346*	$ -~~g.A&B7<>kkD#'<<L,0O#P%)%5%5b"((%C$D  FG 7
MZ%9%9
MH
MCKK&&s+,- 
' K
,
- 
s   H" H'B7H,,I c               n   t        j                  | j                  t        j                        rt        d      |dk  rt        d|       t        | j                        dk(  r$t        dj                  | j                              d|cxk  rt        | j                        k  sn t        d|d| j                        t        | j                        }||   |k  rt        d|d|d	|      t        j                  d
      j                  }	 ||   |dz   kD  }|rt        d| d| j                        |||<   | j                  || j                  | j                         | j                  |t        j                  t        j"                              fS # t        j                  $ r Y vw xY w)Nz,top_k is not compatible with complex inputs.r   rq  z.top_k operand must have >= 1 dimension, got {}z!axis argument out of range: axis=z for operand.shape=zBk argument to top_k must be no larger than size along axis; got k=z with shape=z
 and axis=r  rN   zetop_k returns int32 indices, which will overflow for array dimensions larger than the maximum int32 (z). Got operand.shape=rq   rb   r   r  )r   r  rb   rZ   r  r   r   rq   rp   r}  r   r[   r`   r   InconclusiveDimensionOperationr   r   r  )r  r  r)  rq   	int32_max	too_larges         rT   _top_k_abstract_evalr	  o  s   w}}b&8&89
C
DDU
DQCH
II1
DVGMM*, ,
t
(c'--(
(
9D7:N?OP
QQ
w}}
%
4[1_
  DuhkD7< = =ll7#'')]ty1},I  99BCY7==JZ\ ] ]%+
..uGMM#*#4#4  6
..uBHHRXX,>.
?
A A 
	,	, 		s   F F43F4c               0   | \  }|\  }t        ||      }t        |      t        j                  u r#t        j                  j	                  |d         }n|\  }}	|	j
                  }
t        |
      }|
dz   }t        |	|      }d|z  }t        j                  dft        fdt        |      D              t        fdt        |      D              f      }t        j                  ||||      }||t        j                  j	                  |d         ffS )	Nro  r   r   ri   c              3  .   K   | ]  }|k7  s	|  y wrY   ri   rj   r  r)  s     rT   rl   z_top_k_jvp.<locals>.<genexpr>  s     #H!a4iA#H   
c              3  .   K   | ]  }|k7  s	|  y wrY   ri   r	  s     rT   rl   z_top_k_jvp.<locals>.<genexpr>  s     )NAI!)Nr	  )r	  r	  r	  r	  r	  rN   )ru  r   r   r  rD  rq   r   r  r+   r	  r   rQ   r	  )rF  rG  r  r)  r  r  r8	  r	  r   k_idxs	idx_shaper  gather_index_shapegather_indicesr	  r	  s      `            rT   
_top_k_jvpr	    s    ('('gqt,+	']gll",,00Q@KIAvIy>D"T)V%78N+K**"W##HuT{#HH$))NU4[)N$NE ...%MK	{GLL$B$B;q>$RS	SSrV   c               J    | \  }|\  }||k  r|dz  }t        |||      ||ffS )NrN   rr  )ru  )r  r  r  r)  r  r  s         rT   _top_k_batch_ruler	    s8    ('
%$	T\AID	w!$	'$	55rV   ru  c           	        t        | j                  d   j                        }||dz
  k7  rOt        t	        |            }|d   ||   c||<   |d<   t        j                  |t        j                  |            }nd }t        j                  |      r4t        j                  |t        j                  |            j                  }ntt        j                  | |f      \  }| j                   \  }}	t        j"                  dt        j$                  |      t        j$                  |	      g||g      j                  }|6|D 
cg c]+  }
t        j                  |
t        j                  |            - }}
|S c c}
w )Nr   rN   r  zstablehlo.dynamic_top_k)result_typesr#  )r   r  rq   r   rQ   r5   rP   r(   r  r   rs  r4   TopKOpr  r  eval_dynamic_shape_as_valsr  custom_callr  )r  r  r  r)  rO   r  r  k_valueout_values_avalout_indices_avalr   s              rT   _top_k_lowerr	    sP   	S\\!_""	#$	TAXdD8T$ZDJRmmGT%9%9$%?@GD 
!kk'4==#34<<G..sQD9HG),&O%!**?;-.07#	% &-W	  
$& }}VT%9%9$%?@ &G &	.&s   ?0E3c                ^    | \  }t        |      t        j                  j                  |      fS rY   )r  r   r  rD  )rF  rG  rS   s      rT   _stop_gradient_jvp_ruler	    s(    "!	q	7<<99!<	<<rV   c                ,    | \  }|\  }t        |      |fS rY   )r  )r  r  rS   r  s       rT   _stop_gradient_batch_ruler	    s     "!	$#	q	3	rV   c                *    t         j                         S )zCreates an XLA token value with no preconditions for sequencing effects.

  Experimental.

  The argument is ignored. It exists for backward compatibility.
  )create_token_pr   r  s    rT   create_tokenr	    s     
			rV   r	  c                     t         S rY   r"   r  s    rT   r   r     s    N rV   c                H    | j                   \  }t        j                         gS rY   )r  r5   r	  r  r#  r  s      rT   _create_token_loweringr	    s    mm)(



	rV   c                 J    t        j                  |  } t        j                  |  S )zWMerges one or more XLA token values. Experimental.

  Wraps the XLA after all operator.)r   r   after_all_pr   r#  s    rT   	after_allr	    s%     ''2(			8	$$rV   c                 H    t        d | D              rt        d      t        S )Nc              3  ,   K   | ]  }|t         u  y wrY   r	  r  s     rT   rl   z+_after_all_abstract_eval.<locals>.<genexpr>  s     3Q.	 3s   z%Arguments to after_all must be tokens)r  rp   r"   r	  s    rT   _after_all_abstract_evalr	    s"    3(33
;
<<	rV   r	  c                J    | j                   \  }t        j                  |      gS rY   )r  r5   r	  r	  s      rT   _after_all_loweringr	    s    mm)(
--
!	""rV   c                v    t        j                  | |      \  } }t        j                  | |t	        |            S )a  Stateful PRNG generator. Experimental and its use is discouraged.

  Returns uniformly distributed random numbers in the range [a, b). If
  b <= a, then the result is undefined, and different implementations may
  return different results.

  You should use jax.random for most purposes; this function exists only for
  niche use cases with special performance requirements.

  This API may be removed at any time.
  ry  )r   r   rng_uniform_pr   r   r   r}  rq   s      rT   rng_uniformr	     s6     
	#	#Aq	)$!Q			Aqe		55rV   c                  | j                   |j                   k7  r/t        dj                  | j                   |j                               | j                  dk7  s|j                  dk7  r/t        dj                  | j                  |j                              | j	                  || j                   | j
                  xr |j
                        S )NzCArguments to rng_uniform must have identical dtypes, got {} and {}.ri   z?Arguments to rng_uniform must be scalars; got shapes {} and {}.r	  )rb   r   r}  rq   r   r   r	  s      rT   _rng_uniform_abstract_evalr	     s    WW
qww(* * WW]aggm
Gvaggqww! ! 
QWW[[8Q[[ 
 
; ;rV   r	  c                  | j                   \  }t        j                  t        j                  |j
                  t        j                              }t        j                  |||t        j                  j                  d            gS )NUNIFORM)r  r(   r  rZ   r   rq   r  r5   rngRngDistributionAttrr  )r  r   r}  rq   r  s        rT   _rng_uniform_loweringr	  $   sY    mm)(


288HNNBHH=
>%
''!Qs66::9E
F	GGrV   c               4    ~~| j                   t        |      fS rY   )rq   r   r   rq   rb   r  r  s        rT   _rng_bit_generator_shape_ruler	  ,   s    Y
))U5\	""rV   c                   | j                   |fS rY   rx  r	  s        rT    _rng_bit_generator_sharding_ruler	  0   s    
,,	%%rV   c               .    | j                   t               fS rY   )r  r  r	  s        rT   _rng_bit_generator_vma_ruler	  4   s    
''9;	rV   c               "    ~~| j                   |fS rY   r  r	  s        rT   _rng_bit_generator_dtype_ruler	  7   s    Y
))U	rV   c               $    ~~~| j                   dfS r'  r   r	  s        rT   !_rng_bit_generator_weak_type_ruler	  ;   s    UI
--	rV   c                       e Zd ZdZdZ	 dZ	 dZy)RandomAlgorithmz<Describes which PRNG algorithm to use for rng_bit_generator.r   rN   rM   N)r   r   r   r   RNG_DEFAULTRNG_THREE_FRY
RNG_PHILOXri   rV   rT   r 
  r 
  A   s    D+%-%*#rV   r 
  c                    | j                   S rY   r;  r  s    rT   r   r   N   s
    INN rV   c                2   | t         j                  k(  rt        j                  j	                  d      S | t         j
                  k(  rt        j                  j	                  d      S | t         j                  k(  rt        j                  j	                  d      S J )N	THREE_FRYPHILOXr   )r 
  r
  r5   RngAlgorithmAttrr  r
  r
  r
  s    rT   _rng_algorithmr

  P   sv    ////##K00O...##H--O///##I..5rV   c          
     `   t        j                  |j                        }|j                  |j                  }}t         j
                  j                  d      }	t         j
                  j                  d      }
|dgk(  r||	k(  s|dgk(  r||
k(  s	J ||f       t        j                  |      }t        j                  |      }|t        j                  d      t        j                  d      t        j                  d      t        j                  d      fv r|}|}n|	}t        j                  }||	k(  rit        j                  t         j                  j                  dg|
      t        j                  t         j                  j                  ddg|	      |            }t!        |      }| j"                  \  }}t%        d	 | j"                  D              rt        j&                  t        j(                  | |j                              }t        j*                  d
|j                  t        j,                  t/        j0                  ||            g||gt3        |            j4                  \  }}nMt        j6                  |j                  t         j                  j                  ||      ||      j4                  \  }}||	k(  rit        j                  t         j                  j                  dg|	      t        j                  t         j                  j                  ddg|	      |            }||k7  r[t        j8                  t         j                  j                  t        j                  |j                        j                  |      |      }t        j:                  | ||      t        j:                  | ||      gS )Nrt	  ru	  r  rM   uint8uint16r  uint64c              3  \   K   | ]$  }t        j                  |j                          & y wrY   )r   r&  rq   rz	  s     rT   rl   z._rng_bit_generator_lowering.<locals>.<genexpr>y   s"     DT##AGG,	,Ds   *,z#stablehlo.dynamic_rng_bit_generator)rng_algorithm)r	  r#  extra_attributes)r3   RankedTensorTyper   rq   element_typeIntegerTypeget_unsignedrZ   rb   r(   rU  r  r5   r  r  r  r

  r  r  r  eval_dynamic_shaper	  r  r   r!   r  r  RngBitGeneratorOpr)  r  )r  r   rq   rb   r  r  key_type	key_shape	key_etypeu32_typeu64_typeetype	rbg_etype	rbg_dtypealgorithm_attrout_key_avalout_vals_avaloutput_shapeout_keyout_valss                       rT   _rng_bit_generator_loweringr&
  Z   s     *(!)>)>Y) ^^((,(^^((,(	X 5	X 5P:CY9OP 7
((5/%



&%
rxx "((8"4bhhx6Hxx!# #III		I(



X.B''++QFH=sCEC "),. #,DcmmDD$$
c=#6#679L((-hh**4+;+;E9+MNP|$N;=
 >EW GX --
y1 %W GX (kk
X.##QFH5w	@AG %{{b11(--@FFNH 
+
+C,
G

+
+C=
I
K KrV   rng_bit_generatorc                ,    t         j                  |       S rY   copy_pr   )arrs    rT   _array_copyr,
     s    	S	rV   c                    d }t        | j                  j                        D ]4  \  }} t        | t        j
                  t        j                  f      s1|} |S  |S rY   )rU  sharding_specr   r   r*   	UnstackedChunked)r   sharded_dimr  s      rT   _which_dim_shardedr2
     sV    +001 da!dnndll34k		 
rV   c                    | S rY   ri   rR   s    rT   _identity_fnr4
     s    AXrV   c                   t        j                  t        d dd| |       \  }}}t        j                  t        | | ||d d d ||
      }t	        j
                  |j                  g|j                  d ||j                  |j                  |j                  |j                  |j                  |j                  j                  |j                  |j                  d
}t!        j"                  |j%                         |      S )Nri   )
backend	axis_name	axis_sizeglobal_axis_sizedevicesr8  out_axes_thunkr   donated_invarsis_explicit_global_axis_size)r   _shared_code_pmapr4
  _prepare_pmapr*   xla_pmap_implr  r  local_axis_sizer9
  r:
  in_axes_flatr;
  r   r<
  r=
  r   r  r  )r1
  r  r  r7
  static_broadcasted_tupledonate_tupler  r  s           rT   _copy_impl_pmap_shardingrE
     s    696K6K$B[7:3)%|	K.FD$dF4!   jj;;(,	!!A4F4Fii%%AJJ,?,?%%#$#A#A( 
	!	!!**,	99rV   c                   |\  }t        |t              rYt        |j                  t              r?t	        |j                        }|t        j                  | g|i |S t        |g|i |S t        j                  | g|i |S rY   )r   r<   r   r7   r2
  r   apply_primitiverE
  )rL  r  r  r   r1
  s        rT   
_copy_implrH
     s    "!5j\B$QZZ0K%%d<T<V<<#KA$A&AA		!	!$	8	8	88rV   copyc                    | S rY   ri   rR   s    rT   r   r      s    1 rV   c                    |gS rY   ri   r  s     rT   r   r      s    qc rV   c                .    t         j                  |       gS rY   r)
  )r  s    rT   r   r      s    A/ rV   c                L    t        j                  t        j                  |        y rY   )r   r  
dce_sink_pr   )ra   s    rT   dce_sinkrO
     s    Z__c*rV   c                      e Zd Zy)NoDCEEffectN)r   r   r   ri   rV   rT   rQ
  rQ
     s    rV   rQ
  rO
  c                    g S rY   ri   r  s    rT   r   r      s    b rV   c                    g t         hfS rY   )no_dce_effectr  s    rT   r   r      s    "}o1F rV   c                    g S rY   ri   )r  r   s     rT   r   r      s    " rV   c                    g S rY   ri   r  s    rT   r   r      s    2 rV   c                
    | |fS rY   ri   )rS   bds     rT   r   r      s
    B rV   c          	        t        j                  |      }t        j                  |d      }t	        |d      }t        j                  |      t        j                  d      t        j                  d      t        j                  d      t        j                  d      hvrt        d|       t        t        j                  | ||||            S )a  Stateless PRNG bit generator. Experimental and its use is discouraged.

  Returns uniformly distributed random bits with the specified shape and dtype
  (what is required to be an integer type) using the platform specific
  default algorithm or the one specified.

  It provides direct access to the RngBitGenerator primitive exposed by XLA
  (https://www.openxla.org/xla/operation_semantics#rngbitgenerator) for low
  level API access.

  Most users should use `jax.random` instead for a stable and more user
  friendly API.
  r'
  r
  r
  r  r
  z%rng_bit_generator: unsupported dtype )rq   rb   r  r  )r   r#   r   r  r:   rZ   rb   rp   r   rng_bit_generator_pr   r	  s        rT   r'
  r'
     s      
!
!%
(%

2
25:M
N%&|5HI,XXe_RXXg.0BXXh/(1CE E
;E7C
DD	
U%9#  %
& &rV   c                    t        dd|       t         fdt        D              sDd}t               }d t        D        }t	        |j                  |dj                  |                  d|cxk  rt        |      k  sn t        d|d	|      |3t        j                  t        j                  d gt        |      z   
      }t        | |      S )Nr  rq   c              3  J   K   | ]  }t        j                  |        y wrY   r
  )rj   r  rb   s     rT   rl   z&_iota_abstract_eval.<locals>.<genexpr>	!  s     7QVua(7r   zBiota does not accept dtype {}. Accepted dtypes are subtypes of {}.c              3  4   K   | ]  }|j                     y wrY   r0  r  s     rT   rl   z&_iota_abstract_eval.<locals>.<genexpr>!  s     3!**3r1  r   r   z?iota dimension must be between 0 and len(shape), got dimension=z for shape=r   rx  )rX  r  _numr0   rp   r}  r   r   r   r   r  r   r!   )rb   rq   r!  r   rs   r9  r:  s   `      rT   _iota_abstract_evalr_
  !  s    67E*	7$7	7
NCu%H3d3
CJJx3E)FG
HH	
i	$#e*	$
 #!|<2 3 3))tvvvE
7J/KLH	UEH	55rV   r  c                R    t        ||||      }| j                  t        d||      S )Nr  ri   ru  )r  rw  r  )r  rv  rb   rq   r!  r   rh  s          rT   _iota_staging_rulera
  !  s8    e5I!#&		(	(V7B 
) 
D DrV   c                D    t         j                  ||||      \  }}|g|fS )Nr  )r  rd  )r   rb   rq   r!  r   r,  r   s          rT   _iota_typecheck_rulerc
  !!  s3    **)h + H(G
W	rV   c                    ~| j                   \  }t        j                  | ||      }t        j                  | ||      gS )Nr.  )r  r(   r  r  )r  rb   rq   r!  r   r  r  s          rT   _iota_lowerre
  '!  s:    mm)(		#x95#

+
+Ch
?	@@rV   c                    t        j                  t        j                  |d            sd}t        |j	                  |            dt        |       t        |      z
  z  t        |      z   }t        t        t        j                  | |            S )zCUtility function for computing the shape resulting from a dilation.r   z'All dilations must be positive, got {}.r   )
rZ   ro   greaterrp   r}  r   r   r   r   r  )rq   dilationrs   s      rT   _dilate_shaperi
  3!  sj    	

8Q'	(
3C
CJJx(
))SZ#h-/05?B(	s4??E84	55rV   c                V    t        j                  t        j                  |       |       S rY   )rZ   floor_divider  r   s     rT   _ceil_dividerl
  ;!  s    
//"++b/2
.	..rV   c                      e Zd ZdZdZdZy)PaddingTyperN   rM   rx  N)r   r   r   VALIDSAME
SAME_LOWERri   rV   rT   rn
  rn
  ?!  s    
%	
$*rV   rn
  c                2   t        |t              rDt        j                  t        j                  t        j
                  d}	 ||j                            }|t        j                  k(  s|t        j
                  k(  rt        | |      }d |dz
  |z  |z   | z
  D        }|t        j                  k(  r|D 	cg c]  }	|	dz  |	|	dz  z
  f }
}	n|D 	cg c]  }	|	|	dz  z
  |	dz  f }
}	|
D cg c].  }t        |t        j                        r|j                         n|0 c}S |t        j                  k(  rdgt        |       z  S d}t        |j                  |            # t        $ r"}d}t        |j                  |            |d}~ww xY wc c}	w c c}	w c c}w )	z6Convert padding string to list of pairs of pad values.)ro
  rp
  rq
  z>Unrecognized padding type: expected 'VALID' or 'SAME', got {}.Nc              3  H   K   | ]  }t        j                  |d         ywrh   )r   r]   r  s     rT   rl   z"padtype_to_pads.<locals>.<genexpr>V!  s#      3 a# 3s    "rN   rM   )r   r   zUnknown padding type: {}.)r   r   rn
  ro
  rp
  rq
  upperKeyErrorRuntimeErrorr}  rl
  rZ   r   itemr   rp   )in_shapewindow_shapewindow_stridesr  mappingr   rs   r  	pad_sizespad_sizepadsr  s               rT   padtype_to_padsr
  E!  s    ""  !,,G
7(g
    G{/E/E$EX~6I3$q=N:&')123I +"""DM8@8q=(X]2
3d 
 EN8@8h!m#X]
3d  CGGQ
1bjj1AFFHq8GG+###8c(m##
%C
CJJw'
((/  7LcG,-367 Hs*   E 3F
F(3F	F%FFfabsarccosarccosharcsinarcsinharctanarctan2arctanhrM  rJ  rQ  rT  r;  r2  rg
  r  r  
less_equallogical_andlogical_not
logical_orlogical_xormaximumminimumr  	not_equalr  float_powerr  
left_shiftright_shiftsubtractc           	     0   t        d |D              ryt        |      dk  ry|d   j                  t        fd|dd D              rMd}| t        v rt        |    }|d| d	z  }t	        |j                  | d
j                  d |D                          y)z;Check that dtypes agree, possibly ignoring float precision.c              3  x   K   | ]2  }t        j                  |j                  t         j                         4 y wrY   )r   r  rb   r~  )rj   r  s     rT   rl   z$check_same_dtypes.<locals>.<genexpr>!  s%     JD		4::v	7Js   8:NrM   r   c              3  <   K   | ]  }|j                   k7    y wrY   r  )rj   r  rb   s     rT   rl   z$check_same_dtypes.<locals>.<genexpr>!  s     3u	3r  rN   z:lax.{} requires arguments to have the same dtypes, got {}.z (Tip: jnp.zE is a similar function that does automatic type promotion on inputs).r   c              3  F   K   | ]  }t        |j                          y wrY   )r   rb   rz	  s     rT   rl   z$check_same_dtypes.<locals>.<genexpr>!  s     .Ks177|.Kr  )r  r   rb   _JNP_FUNCTION_EQUIVALENTSrp   r}  r   )r   r   rs   equivrb   s       @rT   rV  rV  !  s     	JEJJ
Z!^

(..%3qr33
FC(('-e	{5'!fggc
CJJtTYY.KU.K%KL
MM 4rV   c                h   t        |t        t        t        j                  f      s'd}t        |j                  | |t        |                  t        |      syt        j                  |      }|j                  dk7  r&d}t        |j                  |j                              	 t        |       |rdnd\  }t        fd|D              sd	}t        |j                  | |||            y# t
        $ r;}d}t        |j                  | |t        t        t        |                        |d}~ww xY w)
zHCheck that `obj` is a shape-like value (e.g. tuple of nonnegative ints).z1{} {} must be of type tuple/list/ndarray, got {}.NrN   z${} {} must be 1-dimensional, got {}.z9{} {} must have every element be an integer type, got {}.)rN   zstrictly positive)r   nonnegativec              3  (   K   | ]	  }|k\    y wrY   ri   )rj   rz   lower_bounds     rT   rl   z#_check_shapelike.<locals>.<genexpr>!  s     /!Q+/r0  z,{} {} must have every element be {}, got {}.)r   r   r   rZ   r   rp   r}  r   r   r   rO   r#   r   ro   )	fun_namer  objnon_zero_shapers   obj_arrr   bound_errorr
  s	           @rT   rX  rX  !  s   	C%rzz2	3
=C
CJJx49=
>>	S
HHSM'\\Q
0C
CJJw||,
--Tw
 #16H +{	/w/	/
8C
CJJx;D
EE 
0 
 T
EC
CJJx5T33HI
JPSSTs   %C- -	D166D,,D1c                   t        |       }t        j                  |       rA t        j                  |       |      }|t        |      k(  r|S t	        j
                  ||      S t        j                  t	        j
                  ||      d      S )NFr   )r1  r   is_python_scalarscalar_type_ofrZ   r   r   r   )examplera   rb   s      rT   r  r  !  so    
/%W%
(&


(
-C6#;&3@BHHS%,@@			rxxU3u	EErV   )r  r  c           	         t        j                  |       }t        | dd|j                  j	                  t                           }|S )Nri   r   r   rq   r  r   r   r  r  r   r   r   rS   r  r  s      rT   r  r  !  <    ==&!2!!??11qs1;	=#	*rV   r"  c           	         t        j                  |       }t        | dd|j                  j	                  t                           }|S )Nri   rN   r   r
  r
  r
  s      rT   r  r  !  r
  rV   c                    t        j                  |       }t        j                  |j                        }|j	                  |j
                  j	                  d            }t        | dd|      S )Nri   rq  r   rN   r
  )r   r  %primal_sharding_to_cotangent_shardingr   r   r   r  )rS   r  ct_ss      rT   _one_vjpr
  !  sW    ==&		3	3FOO	D$	$))**b*9	:$	1B1t	<<rV   rM   _twosri   )rq   r  _twor1  c                    t        | |       S rY   )r~  rR   s    rT   r	  r	  !  s    	Aq/rV   c                \    t        j                  t        |       t        j                        S rY   )r   r  r1  rZ   r  rR   s    rT   r  r  !  s    			6!9b&8&8	99rV   c               '  `   K   d}| D ]#  }t        |      }t        |||z          ||z  }% y wrC  )r   rQ   )r>  startrS   x_lens       rT   ru  ru  !  s=     
% aFE
uu}
%%	UNEs   ,.c                l    t        t        j                  |       }| D cg c]	  }||vs| c}S c c}w rY   )r  	itertoolschain)originalremoved_listsremovedr  s       rT   rt  rt  !  s0    	/0'	2'!1!	22	2s   	11c                .   | ?t         j                  j                  y	 t        t         j                  j                        S t        | t              r(| t        v rt        |       t        |       fS 	 t        |    S t        | t              r| | fS t        | t        t        f      r| S t        | t
        t        f      r=t        |       dk(  r/t        d | D              rt!        t        t        t        f   |       S t        | t
        t        f      rt        |       dk(  rt        d | D              rvt!        t        t        t        f   |       \  }}t!        t        t        t        f   t        |            d   }t!        t        t        t        f   t        |            d   }||fS t	        dt        t               d	|  d
      # t        $ r8 t	        dt        t               dt         j                  j                         dw xY w# t        $ r Y nw xY w)zTurns an API precision specification into a pair of enumeration values.

  The API can take the precision as a string, or int, and either as a single
  value to apply to both operands, or as a sequence of two values.
  NzBjax_default_matmul_precision flag must be set to None, a value in z3, or the name of a lax.DotAlgorithmPreset, but got rM   c              3  <   K   | ]  }t        |t                y wrY   )r   r/  )rj   r  s     rT   rl   z)canonicalize_precision.<locals>.<genexpr>!"  s     8Jq)$8r  c              3  <   K   | ]  }t        |t                y wrY   )r   r   r  s     rT   rl   z)canonicalize_precision.<locals>.<genexpr>$"  s     21Jq#2r  r   z9Precision argument must be one of:
- None,
- a string in z,
- a lax.Precision value,
- a tuple of two lax.Precision values or strings,
- a lax.DotAlgorithmPreset or the name of one of these presets, or
- a lax.DotAlgorithm value;
but got rn   )r   default_matmul_precisionr  r  r   r   r-  r   r   r/  r[  ru
  rL  r   r   ro   	type_cast)r  s1s2p1p2s        rT   r  r  "  s    &&,,4#F$C$C$I$IJJ )S!&&y!9Y#777!),, )Y'i)l,>?@9tUm,Y11D8i88U9i/0)<<9tUm,Y11D2	22uS#X	2FB	5I-.0Fr0J	KA	NB	5I-.0Fr0J	KA	NB8O./0 1
 1	 7  
N$%& '44::;= 	  s   "G 1H AH	HHc           
         t        t        t        | |      t        |      t	        |            t        t        ||      t        |      t        |                  S rY   )rg  r  r?	  r"  r  r
  )rS   r  r$  s      rT   rx  rx  4"  sB    	VHQNE!HfQi8HQNE!HeAh7
9 9rV   c                    t        |       t        |      }}||k7  r4t        j                  ||      }||k(  rt        | |      } nt        ||      }t	        | |      S rY   )r1  r   rt  r  rz  )r   r}  a_dtypeb_dtypehigher_dtypes        rT   r?	  r?	  9"  sX    AYq	7'''9Lw
q'
*a
q'
*a	Aq/rV   c               J    t        |d      }t        j                  | ||      S )a  Create an empty array of possibly uninitialized values.

  This initialization is backend dependent.

  Args:
    shape: int or sequence of ints specifying the shape of the created array.
    dtype: dtype for the created array.
    out_sharding: (optional) :class:`~jax.sharding.PartitionSpec` or
      :class:`~jax.NamedSharding` representing the sharding of the created
      array (see `explicit sharding`_ for more details).

  Returns:
    Uninitialized array of the specified shape, dtype, and sharding.

  Examples:
    >>> jnp.empty(3, jnp.float32)  # doctest: +SKIP
    Array([-5.7326739e+29 -7.7323739e+29 -3.14159256e-29], dtype=float32)

  .. _explicit sharding: https://docs.jax.dev/en/latest/notebooks/explicit-sharding.html
  z	lax.emptyrq   rb   r  )r:   empty_pr   r
  s      rT   r  r  D"  s%    * '|[A,	E\	JJrV   r  c                2    t        j                  | ||      S )Nrx  r   r!   r
  s      rT   _empty_abstract_evalr
  _"  s    			%	>>rV   c                  t        j                  |      st        | |||      S t        j                  |t        j
                        r|nt        j                  |      }t        j                  |||      }t        j                  |      }t        j                  t        j                  j                  j                  t!        |j"                        t        j$                  |j                              gg t        j                  j&                  j                  d      t        j                  j(                  j                  d            }t+        |j,                        dk(  sJ |j,                  d   }t        j.                  | ||      gS )Nr
  rx  AllocateBufferF)call_target_namehas_side_effectrN   r   )r   r&  _empty_lowerr   r  r~  rZ   rb   r!   r  r5   CustomCallOpr(   r3   r
  r  r   rq   rU  r  r	  r   r  r  )r  rq   rb   r  r  	phys_avalcustom_call_opr  s           rT   _empty_custom_call_lowerr
  c"  s*   				&5LQQ$$UFOO<%"((5/%eU\B(  *)##ww##
y
!6!6y!GI Jww))--.>?gg&&**51. 
^##	$	))	)q!#

+
+Ci
@	AArV   r  rR  c                  t        j                  |t         j                        r|nt        j                  |      }t        j                  |||      }t        j                  |      }t        j                  t        j                  d|j                              }t        j                  | ||g       }t        j                  | ||      gS )Nrx  ri   r  )r   r  r~  rZ   rb   r   r!   r  r(   r  r  r  r  )r  rq   rb   r  r  r
  r  s          rT   r
  r
  v"  s    $$UFOO<%"((5/%eU\B(  *)"ioo67#c3	K#

+
+Ci
@	AArV   c                   t        |d| j                        }|d nt        j                  | |d      }t        j                  |||      }|dfS )Nr   r
  )rJ   r  r'   r  r
  r   )	r  vals_indims_inrq   rb   r  batched_shapebatched_out_shardingr$  s	            rT   _empty_batcherr
  "  sX    ua8-"d$$Ya@  lle 4  6!	
A+rV   c               0    t         j                  | |      S )Nrb   r  )empty2_pr   r
  s     rT   empty2r
  "  s    	U	>>rV   r
  c                2    t        j                  d| |      S )Nri   )r  r
  r
  s     rT   _empty2_abstract_evalr
  "  s    			"e,	??rV   c               F   t        j                  |t         j                        r|nt        j                  |      }t        j                  t        j                  d|            }t        j                  t        j                  |j                  |j                              gS r%  )r   r  r~  rZ   rb   r   r  r!   r(   r  r  rq   )r  rb   r  r
  s       rT   _empty2_lowerr
  "  sh    $$UFOO<%"((5/%  !1!1"e!<=)


288IOOY__E
F	GGrV   tiec                    |S rY   ri   r#  s     rT   r   r   "  s    A rV   c                    |S rY   ri   r#  s     rT   r   r   "  s    Q rV   c                    |gS rY   ri   )r  rS   r$  s      rT   r   r   "  s     rV   c                0    t        j                  |  |d   fS rA  )tie_pr   )rF  rG  s     rT   r   r   "  s    uzz73Xb\B rV   c                
    d | gS rY   ri   )rg  rS   r   s      rT   r   r   "  s
    4* rV   c                   t        j                  |       \  }}t        j                  | }t	        j
                  | }t        j                  ||      S )a  Prevents the compiler from moving operations across the barrier.

  Optimization barriers have a number of possible uses:

  * An optimization barrier ensures that every output of the barrier that is
    used by any operator, has been evaluated before any operator that depends
    on one of the barrier's outputs. This can be used to enforce a particular
    order of operations.

    Note that all operands must be used through the barrier for this to work.
    There are no ordering constraints between an operator that uses one of the
    barrier's outputs, and an operator that directly (not through the barrier)
    uses one of the barrier's inputs.
  * An optimization barrier prevents common subexpression elimination. This is
    used by JAX to implement rematerialization.
  * Optimization barriers prevent compiler fusions. That is, operations before
    the barrier may not be fused into the same kernel as operations after the
    barrier by the compiler.

  JAX does not define derivative or batching rules for an optimization barrier.

  Optimization barriers have no effect outside a compiled function.

  Args:
    operand: a pytree of JAX values.

  Returns:
    A pytree of JAX values, with the same structure and contents as ``operand``.

  Examples:
    Prevents common-subexpression elimination between the two calls to `sin`:

    >>> def f(x):
    ...   return jax.lax.optimization_barrier(jax.lax.sin(x)) + jax.lax.sin(x)
    >>> jax.jit(f)(0.)
    Array(0., dtype=float32, weak_type=True)
  )r   r  r   r   optimization_barrier_pr   r  )r  r  r  r  s       rT   optimization_barrierr
  "  sM    L !--g6)W(()4)##Y/#		!	!'3	//rV   c                 2    t        j                  dg|   | S )Nr
  )r   rq  )r  s    rT   #_optimization_barrier_abstract_evalr
  "  s    /7$7	+rV   c                    t        t        j                  | j                        }t        j                  |      }t        j                  |      }t        j                  |j                  |      S rY   )	r   r(   r  r  r  r5   OptimizationBarrierOpunflatten_ir_values_like_typesr  )r  r  barrier_typesr  
barrier_ops        rT   #_optimization_barrier_lowering_ruler
  "  sQ    d**CLL9-$$T*)((3*		,	,Z-?-?	OOrV   r
  c                0    t        j                  | i ||fS rY   )r
  r   )r  r  rh  s      rT   _optimization_barrier_batcherr
  "  s    		$	$l	=f	=z	IIrV   c                |    |D cg c]  }t        j                  |       }}t        |       t        |      fS c c}w rY   r&   instantiate_zerosr
  )rF  rG  r  s      rT   _opt_barrier_jvpr  "  s;    /78!b""1%8(8	g	&(<X(F	FF 9s   9c                f    | D cg c]  }t        j                  |       } }t        |       S c c}w rY   r
  )ctsrF  rg  s      rT   _opt_barrier_transposer  "  s0    ,/0b		b	!0#0	c	"" 	1s   .)rS   r<   r?  r<   )ra   r>   rW   r   r?  r   )ru   zSequence[Shape])ru   tuple[int, ...]r   r   r?  r  )rS   r=   r?  r<   )ru   r  r?  r  )ru   tuple[int | core.Tracer, ...]r?  r  )r   r=   r   r=   r?  r<   )rS   r=   r   r   r?  r<   rY   )rS   r=   r$  r=   r?  r<   )rS   r=   r$  r   r?  r<   )r  r=   r  z DTypeLike | dtypes.ExtendedDTyper?  r<   )NFNT)
r  z!ArrayLike | literals.TypedNdArrayr  zDType | Noner   r   r   Sharding | Noner  r   )r  r=   r  rA   r?  r<   )r^   r=   rS   r=   r`   r=   r?  r<   )
r  r   r  tree_util.PyTreeDefr  zSequence[core.AbstractValue]r   r   r  core.DebugInfor  )r  r   r   r   r  r   )r  mlir.LoweringRuleContextr  r   r   r   r  z:Sequence[tuple[str, tuple[Any, ...], tree_util.PyTreeDef]]r  r   r  core.ClosedJaxpr)r#  zArray | Sequence[ArrayLike]r!  r   r?  r<   )r  r=   r(  r  r)  r   r?  Sequence[Array])NN)r  r=   r  r=   r  r  r  PrecisionLiker  r  r?  r<   )r  r=   r  r=   r  zDotDimensionNumbers | Noner  r  r  r  r?  r<   )NNN)r  r<   r  r<   r  r<   r  r  r  r  r  Array | Noner?  r<   )r  z/RaggedDotDimensionNumbers | DotDimensionNumbersr?  r  )r  r<   r  r<   r  r<   r  r  r  r  r  r  r  r  r?  r<   )r  r=   r(  r  r?  r<   )r  r=   rq   rB   r  r  r?  r<   )rS   r=   r  r   r?  r<   )
r  r=   r  rB   r  zSequence[int] | Noner  NamedSharding | P | Noner?  r<   )r  r=   r  r=   r  zSequence[tuple[int, int, int]]r?  r<   )r  r=   r  r  r?  r<   )r  r=   r  r=   r  r=   r?  r<   )r  r=   r  r=   r?  r<   )r  r=   r  zSequence[int] | np.ndarrayr?  r<   )r  r=   r)  r   r  rA   r?  r<   )r#  r   r  r   r  r[	  r  r  r  r  r?  r   )r  r   r  zcore.AbstractValue)r  r[	  r  r	  r+  r  )r=  r   r>  r  r?  zCallable | None)rb   rA   r?  z
np.ndarray)r  r=   r  r  r?  r<   )r  TrN   )
r  r<   r!  r   re  r   rf  r   r?  r<   )
r  r  r!  r   re  r   rf  r   r?  ztuple[Array, ...])
r  zArray | Sequence[Array]r!  r   re  r   rf  r   r?  zArray | tuple[Array, ...])r  T)
rm  r<   r  r=   r!  r   re  r   r?  tuple[Array, Array])r  r=   r  r   r)  r   r?  r  )rS   r   r$  rK   r?  rK   )
rq   rB   r  r=   rb   r  r   r  r?  r<   )r  r!   r?  r<   )r  zstate.AbstractRefr?  zcore.Ref)rb   rA   r  r   r?  r<   )rb   rA   rq   rB   r!  r   r?  r<   )rb   rA   rq   rB   r  r>   r?  r<   )rb   rA   rq   rB   r  r  r?  r<   )rS   rK   r?  rK   )r  zfloat | ArrayLiker  r   r  r   r?  r<   )r   r=   r  r  r?  r<   )rS   zArrayLike | DuckTypedArrayr  r=   rb   r  rq   zShape | Noner   r  r?  r<   )r  r<   r  r   r  
int | Noner?  r<   )r  r<   r  r<   r  r  r?  r<   )T)FTNN)r  zcore.ShapedArrayr   zSequence[core.ShapedArray]r  Sequence[ir.Value]r?  r  )r$  r   r  zir.Valuer?  r  )r  r   )r  r   r  r   )r  r  )r  r  r   r   )r?  zpp.Doc)r  r/  r?  ztuple[Precision, Precision])r  r/  r?  zir.ArrayAttr)r  CanonicalPrecisionrV  rA   rW  rA   r?  r  )
r  z!DotAlgorithm | DotAlgorithmPresetrV  rA   rW  rA   r  r  r?  z;tuple[DTypeLike | None, DTypeLike | None, DTypeLike | None])r?  zhlo.ResultAccuracyAttr)r  np.dtype | Noner  r   )r  r   r  r  r?  ztuple[RaggedDotMode, int])r  r   r  r  r?  r  )r  r   r  r  r?  r   )r  r<   r  r<   r  r<   r  r  r  r  r?  znp.dtype)r  r  r  r  )r  r  r  r  r  r   )r?  r  )rq   z
core.Shape)r  r
  r  r  )r  r 
  )r+
  r=   r?  r<   )r   r7   r?  r  )r   r   r   r!   r?  None)F)r?  r   )r  r  r?  r  (  
__future__r   r   collections.abcr   r   dataclassesr  r  r   r
  r  r  typingr   r   r	   r
   r   r
  r   r  numpyrZ   jax._srcr   r   r   r   r   r   r   r   r   r   r   r   r  r   r   ppr   r   r   r   jax._src.abstract_arraysr   jax._src.corer    r!   r"   r#   jax._src.errorsr$   jax._src.hashable_arrayr%   jax._src.interpretersr&   r'   r(   r)   r  r*   r/  r+   r,   r  jax._src.meshr-   r.   jax._src.lax.utilsr/   r0   r1   r2   jax._src.lib.mlirr3   jax._src.lib.mlir.dialectsr4   r5   jax._src.shardingr6   jax._src.sharding_implsr7   r8   r9   r   r:   r;   jax._src.typingr<   r=   r>   r?   r@   rA   rB   jax._src.utilrC   rD   rE   rF   rG   rH   rI   rJ   r`   r   r^   r  r  r  rK   r   
unsafe_mapr   
unsafe_zip
set_moduleexportrU   rd   rv   r   r   r   r   r   r   r   r   r   r   r   r   IntEnumr   r   r   r   r   Enumr   r  r  r  r  r  r  r  r  r   r%  r(  r,  r   r2  r5  r8  r=  r@  rD  rG  rJ  rM  rQ  rT  rW  rZ  r]  ra  rd  rg  rj  rq  rt  rw  rz  r~  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  def_impldef_abstract_evalr  primitive_jvpsprimitive_transposesregister_loweringr%  r,  r-  rY  r/  r   rA  r   rL  r[  r   r   r  r  r   r  r  r  r  	dataclassr  r  r  r  r  r  r  r  r  r  r  r  rP   r  r
  r&  r  r  r6  r4  rG  rJ  r9  r;  r  r3  r:  r<  r5  r7  r8  rg  rn  ru  rw  rz  r  aval_zeros_likersr  AbstractRefr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r	  r  r  aval_methodr  staticmethodr  r!  r
  python_scalar_typesr  typed_scalar_typesr  raw_jaxval_adders_fixed_dtype_complex_basetype_strip_weak_typer;  rB  rM  standard_unoprI  rY  r[  r   rm  ru  standard_naryopr~  r  r  r  r  r  r1  r  r2  rD  ri  _complex_elem_typesr1  r0  r0  _boolr  
_signedintr^
  _any_bool_or_int_orderedr   
deflinear2negater   defjvp_zeror  r   
next_afterr   r   r   r  r   r  defjvp2r  pp_eqn_rulesr  r  r  defjvpr  exponential_minus_oner  log_plus_oner  r  r  r  r  r  r  r  primitive_linearizationsr  r  r  r  r  r  r  r  r"  r  r  r  r  r  r'  r+  r  r  r.  r0  r	  r  
linear_jvpr4  r  r  r  r?  rC  rF  r  r  r  r7  r%  r'  r-  r3  r6  r<  rJ  r9  r=  r  rI  not_rL  r  rP  or_rS  rB  rV  popcntrY  count_leading_zerosrK  rN  rX  r\  rZ  r\  r`  r
  ra  rc  defbilinearr  rk  rf  r;  ri  	remainderru  rl  max_hlorn  min_hlorp  rs  rv  r  AndOpr  OrOpr  r  r  ry  r}  r  r  r  r  r	  r	  r	  r  r  r  r  r  r  r  r  r   r   r  r  r  r  rq  r  r  def_bind_with_tracerG
  r  fancy_primitive_batchersskippable_batchersconst_fold_rulesforwarding_rulesr  r  r  r  r  r  r   r  r  r  r  r  r-  r"  r=  rK  rF  rV  rX  r1  ri  ra  re  r  r  r  r  r  r  r  r  _dot_general_batch_ruler  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r
  r  r   r#  r&  r)  r  rM  rQ  r[  ra  re  rj  rq  rs  rx  r|  r~  r  r  r  custom_partial_eval_rulescustom_staging_rulescustom_typechecksr  r  _clamp_dtype_ruler  r  primitive_batchersr  r  r  r  r  r  r  r"  r  r  r  r  r  r  r  r  r  r*  r  r  r  r   r  r  r  r
  r  r  r  r  r  r"  r  r$  r'  r,  r6  r9  rI  r@  rR  rA  rB  rZ  r\  ra  rc  re  rg  r  rj  rl  rp  r  rt  rx  r{  r~  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r	  r  r	  r	  r	  r!	  r	  r(	  r-	  r3	  r5	  rR  
defreducerr:	  r=	  rU  rB	  rX  r[  rE	  rH	  rJ	  rL	  r^	  r  r  ra	  rc	  rg	  r]  r_  rb  r  AddOpMulOpXorOprm	  ro	  r  	deflinearrr	  rb   r
  r  r
  _UINT_DTYPESint16r  r  _INT_DTYPESr	  r	  r	  r	  r	  r	  r	  rk  r	  r	  r	  r	  rt  r	  r	  r	  r  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r 
  r<  r

  r&
  rZ
  r,
  r2
  r4
  rE
  rH
  r*
  rO
  EffectrQ
  rT
  control_flow_allowed_effectsadd_typelowerable_effectsrN
  def_effectful_abstract_evalr
  r'
  r_
  r  ra
  rc
  re
  rO   _ndimri
  rl
  rn
  r
  r
  rV  rX  r  r  r  r"  r  r
  r
  r
  r1  r	  r  ru  rt  r  rx  r?	  r  r
  r
  r
  r
  r
  r
  r
  simple_implr
  r
  r
  r
  r
  r
  r
  r
  r  r  ri   rV   rT   <module>rw     sB   #  .        O O         !     &  ) %    0/ / 1 1 $ * & 4 &   + >  ! + * &Z Z ^ ^ ^2 2 2 ||||


CLCZCZ		#D=
	'6P 
 F 
 F	=7= 
= (/ (/T - 	-^&G*  
  & ( (T " "<  (  (T\\  ,:,I,I!:)!:!: !:F  ( "499  * *6+8 , ,8 * *2 , ,8 + +6 / /$ * *: * *:  0  *  *  2 / /2  &  2 $ $* + +4 , ,6 + +4  .  4  4  4 $ $(  &  .  .  .  :  6  2  2 ! !2 - -4 * *4  <  <  <  <  <  < "D$D"DIN"D "DL # $)-D.DD D 	D
 #'DL  C  CD
# (':((D( %(( +9	( (, dd
d dN6	!66 6 K	6
 6 6r)
 dnn[)   _ %   6 7# !.  + ':   $   {$7 8<4 BB+B( ,. ( -#		 #L !* 1 1 9  ) 1 1 9 &^^ 6 $-NN = !&/nn ? # ) 1 1 9 !*!2!2 :  ) 1 1 9 $,, 4 W: Wte eP 	#s(O	)Y
 	)Y
  E(3-#">?!(3-#">?@ A  ,0;?W
 "W#6W(W )9W
 ',W" 9=#'37	m75m7 m7 !1m7 $	m7h  $/3!%		  	
 -  
@ d#M M $M6J '@C!:Bx0#' #  $/3!%=	=	= = #<	=
 = -= = =@ IM 55, KOO+8OOB, 04<8<<,<5<AF<|:R6:R;@:Rx;26(6
>5
>:?
>G!G&+GG!G&+G 59	-3-31-3 %-3 2	-3 >A	-3^ - 	* 5*85 *=5 	5+0?6$	<	< !Q%*Q8746*6*5,6,6, 
*,12BB+.B7<B 
B 
4612NN+.N7HN 
N =?12#Y#Y+.#Y7P#YJ CE#' ,? 68 '/R%(%)%("%(.3%(N	* *A  + & 0G  %++ ,- &*	A.3	A4/4$4%l>$'>$'>,1>6?& @DFJ6#6,<6!64C6OT6t +/%'%38%: -1*)*5:*& * *8  &  &  (  &  &  &  &  , )((3 (((3 &d&&w/ 	Q !'  

eoo->
! -A "-'A- : M +  *.,.R i(? $(e(63*/XA6 FKGK &+.
R$
K'A
!30 26AA&AAE ++zz2::. 


|	

f}xf}x%'e|&=5 dE" e0 1   ugoszzB C	tV	$ v    v /vv.<   {GOT__$M N

( w    w C D	vv	& v    vwA B

( w '   w -<)6;? {    {GOS]]$K Lfx'/ 


59 :   ugosG H7  % 	v(&	1 



K   v{ +8  & fx'/ 			%1 2   ugosww? @7  % 
)7
3 


   w0I0IJL9  ' 
)7
3 			'A B   w9I9I J K9  ' 	v(&	1 



5
   vwA B8  & 6H,j9
 


/)
   z%t~~meLN <  * G >*
 	fx'/ 			%I J%-  E "   um ,7  % 
G@ 	fx'/ 				H   um ,7  % fx'/ 


5T U   ugosww? @7  % 	v(&	1 			&J K   vw		B C	v(&	1 			&O P   vw		B C  
v(&	1 			&C D   vw		B C
6H,fx.?@'
J 			'
C
HJ   w C D	v(&	1 			&. /   vw		B C	v(&	1 			&. /   vw		B C
)7
3 			'F G   w D E
)7
3 			' >?   w D E
)7
3 			'
PR   w D E	6	2 fH I   vwA B	6	2 fM N   vwA B8$B>$79L#M	 i0 1   y'/3;;"G H	n1H<f	E!   v%t~~j5IK $BMM6:  & "6   
V 3h >"'	)   ugosww? @. 

5-  77	v(&	1 


6O P   vwA B8  & 
)7
3 


I   w C D9  ' 	vv	& 



   vwA B8  & 18<
 

8C D   x!2 3	< 	(!2D6MH4L M%	1$P 

5, -/   uj )S #g/J'+e2DF   } % 			-) *?$A"   }&; <BlE* u    ugosxx@ A|4e< u    ugosxx@ Al3T: t    tW_cgg> ?|4e< u    ugosww? @"4);<    )7?CJJ+O PdE"   ugos7N7NO P'
>U, +d|U)<>y >#  % !/      ugosww? @'	C 	te,#  % !/      ugos||D E5: 	te<OP 			%
)
)+ uG@B   ugos||D E; 	te, 			%
#
AC "5      ugoszzB Cv6> 				SLN   ugos}}E F (te<~ < 


5??A   ugot||D E'te<~ < 


5??A   ugot||D Ed|\: |    |W_cnn%M N*D$<9QR  ' (   /0J0JKM (t6KL  $ %   ,0G0GHJ; D#))-FHD#((,DF	N;  l288$tTlDtT t    tW%7uE Fl288$tTlDtT t    tW%7uE Fl288$x&:DA t    tW%7uE Fl288$x&:DA t    tW%7uE Fl288$x&:DA t    tW%7uE Fl288$x&:DA t    tW%7uE F
bhh'$w
? w    w(:D$ G H
bhh'(H)=w
G w    w(:D$ G H
bhh'(H)=w
G w    w(:D$ G H	2
.
O JJ    	.	E ,$&F+O5T++-CD735   * *+P Q   (@(@BX Y Z 


!#A B2V  . /Q =` ! !"8 96B  2 3.L  * +.H  * +,E  ( ) 4	A   -/J K3j $   WX55{C D   6 7 			+NO G    $   { #   {$: ;6 -(   wx77G H    : ; 			-MN @    &   } %   }&< =(D ,$&F+;5T++-CD	F 
 % &   - .A
   -/J K&4?Q4D?QB?(
)E7G)EVW0A 7H:4D:03::  7<7G47G&' -&'RE1NM #,T++];.*

 })+EG+)++""	  4K ! !- 0-9  M *#7  -  >"+>0G> #'	(0(( (  	(
 A(8	F6V 6?:I/26   }&8 9 ,H$ !3hG"*,,DII 1J.MM1JMM1J		.W -Wt		  #<	 - 40!fh -h hV
(' -': *""T++\:	  +G  & '0R  , -:X ! !"6 74@  0 1  $/3!%d	d	d d #<	d
 d -d d 
d` "&9 ,9 9 9x   +%t~~&>7<>?  H$'(;"HI
8&BA);A	D $T^^$67   $ $%D E   GH$<$<>PQ R(B  $ %.N  * +8T ! !"4 52>  . /*D  & '3Q  / 0.L  * +-M  ) *   )+B C -{T4<N#% #&J .0A7+?&-d.D.Dg&NP 
		'%%78 (9  G $   w C DH8A!
1 #4m,T++];*	,
 m8 9)D   &-D  M *A   }&8 9'+2$%
 $..
!    /:K46J   117; < g, -'8  G $   w --(%&<( 	?OU);$+D,B,BE$J	L e^ $%4  E "A   uj )?>.
D&; ,i(T++Y7&	(	
 i0 1)<  I &A   y. 1((VA;2020(02
/ AB 24G(8N(/0F0F	(RT	 i0 1/B ! !) ,)5  I &   y. 1$;  y !%:  	 "	
, 	?K);$+D,B,BE$J	L eB C%4  E "A   uj )BJ
2.,A !;*T++[9,(* kOQ+@  K (   {$4 5
")"($T
(4 @D  *J)9NT++Z8:
 !,  * &<  
 #0B ! !* -*6  J '   z#7 8J#
(
G
*2B
N 4>>(#     '(22H= >   /;M 68M );  H %.  ( >&6>.   x /%E 9= H0 . "!:LI74))<8+') l6 7   L"3 4)0 #!:MJ74))=9; $9  -     M#5 6D ";*T++\:< 

<1 2   L"3 4 ";*T++\:< 

<1 2   L"3 406
8 80 35J&7G,D'.t/E/Ex'PR   H/ 0 x 35J&7G,D'.t/E/Ex'PR   H/ 0 x    DNN"B(9:    DNN"B(9: /
Q7 ![#3PT++[9;   K!9 :+9  K ( "\#3PT++\:<   L"; < "\#3PT++\:<   L": ;
G   |W-@#))->&@ A   }g.A399.@'B C   {G,?,D%F G   |W-@#))-F&H I   |W-@#))-E&G H   |W-@$,,->&@ A   |W-@$,,->&@ A ( OY0BC	+JT++-?@	B 
 ![ \   ) *A   )+B C bhhryybhhryybhhryy bhhrxxbhhrxxbhhrxx0 -.  -.  +, $:4$ 
6	  00&9 :   , -%  & &6  F #.   v{ +A8T.6 G
    117; <   . /8   w -'  ' '8  G $=

 .E  ')) *7P  G33 4 >*    8 8.I J     !: ;   ~'= >% $   WX55{C D   6 7#   {$7 86
; -(   wx77G H    : ;H
   }&; <#&  
$dll 
$ ; 7Kt   34 '+  $   H$$&9:<  % %/1D)+H-/O')*
   *24 :&9 
	 
F+ ,    %   v1 2 V/ 0   v +'..   $ $ - -k :    " "; /T^^J'
 
  L !"
  
 & &'F G   z#4 5 Z &*?  J '(*		 / ; ;&&*&86 
6	 00&9 :   , -D #5    "6  v A
   v{ + 	6/$)) ")L55(5 
95 	5
 	(5 
95 	(5 
95 
95 5 5 5 5 	&5 	&5  !5" #5$ 	&%5& '5( )5* +5, 
7-5. 
7/50 Y152 ?354 	&556 758 95: ;5< =5> ?5@ A5B 
7C5D E5F G5H I5J K5L M5N {O5P Q5R 
7S5T GU5V W5X Y5Z M[5\ 	&]5^ _5` 	&a5b 	&c5d e5f g5h 	&i5 nN$F0F 93 3 )2x 2= )2x 2";h ;,,x << :3
.b9
 )- K0 $..
!   117; <?   . /B    w 8% @   w 8% @B   w - .< ! !' *?4>>(#   X @   0 1H   x / 	u ~     '   u3 4B   % !<      u )0XP ((>? *.  '   H$$&<=?  ( ()L M   -:<J6S  2 3G -=  ( )# 3I  . /rV   