_torch_docs.py 425 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392
  1. # mypy: allow-untyped-defs
  2. """Adds docstrings to functions defined in the torch._C module."""
  3. import re
  4. import torch._C
  5. from torch._C import _add_docstr as add_docstr
  6. def parse_kwargs(desc):
  7. r"""Map a description of args to a dictionary of {argname: description}.
  8. Input:
  9. (' weight (Tensor): a weight tensor\n' +
  10. ' Some optional description')
  11. Output: {
  12. 'weight': \
  13. 'weight (Tensor): a weight tensor\n Some optional description'
  14. }
  15. """
  16. # Split on exactly 4 spaces after a newline
  17. regx = re.compile(r"\n\s{4}(?!\s)")
  18. kwargs = [section.strip() for section in regx.split(desc)]
  19. kwargs = [section for section in kwargs if len(section) > 0]
  20. return {desc.split(" ")[0]: desc for desc in kwargs}
  21. def merge_dicts(*dicts):
  22. """Merge dictionaries into a single dictionary."""
  23. return {x: d[x] for d in dicts for x in d}
  24. common_args = parse_kwargs(
  25. """
  26. input (Tensor): the input tensor.
  27. generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling
  28. out (Tensor, optional): the output tensor.
  29. memory_format (:class:`torch.memory_format`, optional): the desired memory format of
  30. returned tensor. Default: ``torch.preserve_format``.
  31. """
  32. )
  33. reduceops_common_args = merge_dicts(
  34. common_args,
  35. parse_kwargs(
  36. """
  37. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
  38. If specified, the input tensor is casted to :attr:`dtype` before the operation
  39. is performed. This is useful for preventing data type overflows. Default: None.
  40. keepdim (bool): whether the output tensor has :attr:`dim` retained or not.
  41. """
  42. ),
  43. {
  44. "opt_keepdim": """
  45. keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``.
  46. """
  47. },
  48. )
  49. multi_dim_common = merge_dicts(
  50. reduceops_common_args,
  51. parse_kwargs(
  52. """
  53. dim (int or tuple of ints): the dimension or dimensions to reduce.
  54. """
  55. ),
  56. {
  57. "keepdim_details": """
  58. If :attr:`keepdim` is ``True``, the output tensor is of the same size
  59. as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1.
  60. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the
  61. output tensor having 1 (or ``len(dim)``) fewer dimension(s).
  62. """
  63. },
  64. {
  65. "opt_dim": """
  66. dim (int or tuple of ints, optional): the dimension or dimensions to reduce.
  67. """
  68. },
  69. {
  70. "opt_dim_all_reduce": """
  71. dim (int or tuple of ints, optional): the dimension or dimensions to reduce.
  72. If ``None``, all dimensions are reduced.
  73. """
  74. },
  75. )
  76. single_dim_common = merge_dicts(
  77. reduceops_common_args,
  78. parse_kwargs(
  79. """
  80. dim (int): the dimension to reduce.
  81. """
  82. ),
  83. {
  84. "opt_dim": """
  85. dim (int, optional): the dimension to reduce.
  86. """
  87. },
  88. {
  89. "opt_dim_all_reduce": """
  90. dim (int, optional): the dimension to reduce.
  91. If ``None``, all dimensions are reduced.
  92. """
  93. },
  94. {
  95. "opt_dim_without_none": """
  96. dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported.
  97. """
  98. },
  99. {
  100. "keepdim_details": """If :attr:`keepdim` is ``True``, the output tensor is of the same size
  101. as :attr:`input` except in the dimension :attr:`dim` where it is of size 1.
  102. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in
  103. the output tensor having 1 fewer dimension than :attr:`input`."""
  104. },
  105. )
  106. factory_common_args = merge_dicts(
  107. common_args,
  108. parse_kwargs(
  109. """
  110. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
  111. Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
  112. layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
  113. Default: ``torch.strided``.
  114. device (:class:`torch.device`, optional): the desired device of returned tensor.
  115. Default: if ``None``, uses the current device for the default tensor type
  116. (see :func:`torch.set_default_device`). :attr:`device` will be the CPU
  117. for CPU tensor types and the current CUDA device for CUDA tensor types.
  118. requires_grad (bool, optional): If autograd should record operations on the
  119. returned tensor. Default: ``False``.
  120. pin_memory (bool, optional): If set, returned tensor would be allocated in
  121. the pinned memory. Works only for CPU tensors. Default: ``False``.
  122. memory_format (:class:`torch.memory_format`, optional): the desired memory format of
  123. returned Tensor. Default: ``torch.contiguous_format``.
  124. check_invariants (bool, optional): If sparse tensor invariants are checked.
  125. Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`,
  126. initially False.
  127. """
  128. ),
  129. {
  130. "sparse_factory_device_note": """\
  131. .. note::
  132. If the ``device`` argument is not specified the device of the given
  133. :attr:`values` and indices tensor(s) must match. If, however, the
  134. argument is specified the input Tensors will be converted to the
  135. given device and in turn determine the device of the constructed
  136. sparse tensor."""
  137. },
  138. )
  139. factory_like_common_args = parse_kwargs(
  140. """
  141. input (Tensor): the size of :attr:`input` will determine size of the output tensor.
  142. layout (:class:`torch.layout`, optional): the desired layout of returned tensor.
  143. Default: if ``None``, defaults to the layout of :attr:`input`.
  144. generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling.
  145. dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor.
  146. Default: if ``None``, defaults to the dtype of :attr:`input`.
  147. device (:class:`torch.device`, optional): the desired device of returned tensor.
  148. Default: if ``None``, defaults to the device of :attr:`input`.
  149. requires_grad (bool, optional): If autograd should record operations on the
  150. returned tensor. Default: ``False``.
  151. pin_memory (bool, optional): If set, returned tensor would be allocated in
  152. the pinned memory. Works only for CPU tensors. Default: ``False``.
  153. memory_format (:class:`torch.memory_format`, optional): the desired memory format of
  154. returned Tensor. Default: ``torch.preserve_format``.
  155. """
  156. )
  157. factory_data_common_args = parse_kwargs(
  158. """
  159. data (array_like): Initial data for the tensor. Can be a list, tuple,
  160. NumPy ``ndarray``, scalar, and other types.
  161. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
  162. Default: if ``None``, infers data type from :attr:`data`.
  163. device (:class:`torch.device`, optional): the desired device of returned tensor.
  164. Default: if ``None``, uses the current device for the default tensor type
  165. (see :func:`torch.set_default_device`). :attr:`device` will be the CPU
  166. for CPU tensor types and the current CUDA device for CUDA tensor types.
  167. requires_grad (bool, optional): If autograd should record operations on the
  168. returned tensor. Default: ``False``.
  169. pin_memory (bool, optional): If set, returned tensor would be allocated in
  170. the pinned memory. Works only for CPU tensors. Default: ``False``.
  171. """
  172. )
  173. tf32_notes = {
  174. "tf32_note": """This operator supports :ref:`TensorFloat32<tf32_on_ampere>`."""
  175. }
  176. rocm_fp16_notes = {
  177. "rocm_fp16_note": """On certain ROCm devices, when using float16 inputs this module will use \
  178. :ref:`different precision<fp16_on_mi200>` for backward."""
  179. }
  180. reproducibility_notes: dict[str, str] = {
  181. "forward_reproducibility_note": """This operation may behave nondeterministically when given tensors on \
  182. a CUDA device. See :doc:`/notes/randomness` for more information.""",
  183. "backward_reproducibility_note": """This operation may produce nondeterministic gradients when given tensors on \
  184. a CUDA device. See :doc:`/notes/randomness` for more information.""",
  185. "cudnn_reproducibility_note": """In some circumstances when given tensors on a CUDA device \
  186. and using CuDNN, this operator may select a nondeterministic algorithm to increase performance. If this is \
  187. undesirable, you can try to make the operation deterministic (potentially at \
  188. a performance cost) by setting ``torch.backends.cudnn.deterministic = True``. \
  189. See :doc:`/notes/randomness` for more information.""",
  190. }
  191. sparse_support_notes = {
  192. "sparse_beta_warning": """
  193. .. warning::
  194. Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported,
  195. or may not have autograd support. If you notice missing functionality please
  196. open a feature request.""",
  197. }
  198. add_docstr(
  199. torch.abs,
  200. r"""
  201. abs(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  202. Computes the absolute value of each element in :attr:`input`.
  203. .. math::
  204. \text{out}_{i} = |\text{input}_{i}|
  205. """
  206. + r"""
  207. Args:
  208. {input}
  209. Keyword args:
  210. {out}
  211. Example::
  212. >>> torch.abs(torch.tensor([-1, -2, 3]))
  213. tensor([ 1, 2, 3])
  214. """.format(**common_args),
  215. )
  216. add_docstr(
  217. torch.absolute,
  218. r"""
  219. absolute(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  220. Alias for :func:`torch.abs`
  221. """,
  222. )
  223. add_docstr(
  224. torch.acos,
  225. r"""
  226. acos(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  227. Returns a new tensor with the arccosine (in radians) of each element in :attr:`input`.
  228. .. math::
  229. \text{out}_{i} = \cos^{-1}(\text{input}_{i})
  230. """
  231. + r"""
  232. Args:
  233. {input}
  234. Keyword args:
  235. {out}
  236. Example::
  237. >>> a = torch.randn(4)
  238. >>> a
  239. tensor([ 0.3348, -0.5889, 0.2005, -0.1584])
  240. >>> torch.acos(a)
  241. tensor([ 1.2294, 2.2004, 1.3690, 1.7298])
  242. """.format(**common_args),
  243. )
  244. add_docstr(
  245. torch.arccos,
  246. r"""
  247. arccos(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  248. Alias for :func:`torch.acos`.
  249. """,
  250. )
  251. add_docstr(
  252. torch.acosh,
  253. r"""
  254. acosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  255. Returns a new tensor with the inverse hyperbolic cosine of the elements of :attr:`input`.
  256. .. math::
  257. \text{out}_{i} = \cosh^{-1}(\text{input}_{i})
  258. Note:
  259. The domain of the inverse hyperbolic cosine is `[1, inf)` and values outside this range
  260. will be mapped to ``NaN``, except for `+ INF` for which the output is mapped to `+ INF`.
  261. """
  262. + r"""
  263. Args:
  264. {input}
  265. Keyword arguments:
  266. {out}
  267. Example::
  268. >>> a = torch.randn(4).uniform_(1, 2)
  269. >>> a
  270. tensor([ 1.3192, 1.9915, 1.9674, 1.7151 ])
  271. >>> torch.acosh(a)
  272. tensor([ 0.7791, 1.3120, 1.2979, 1.1341 ])
  273. """.format(**common_args),
  274. )
  275. add_docstr(
  276. torch.arccosh,
  277. r"""
  278. arccosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  279. Alias for :func:`torch.acosh`.
  280. """,
  281. )
  282. add_docstr(
  283. torch.index_add,
  284. r"""
  285. index_add(input: Tensor, dim: int, index: Tensor, source: Tensor, *, alpha: Union[Number, _complex] = 1, out: Optional[Tensor]) -> Tensor # noqa: B950
  286. See :meth:`~Tensor.index_add_` for function description.
  287. """,
  288. )
  289. add_docstr(
  290. torch.index_copy,
  291. r"""
  292. index_copy(input: Tensor, dim: int, index: Tensor, source: Tensor, *, out: Optional[Tensor]) -> Tensor
  293. See :meth:`~Tensor.index_add_` for function description.
  294. """,
  295. )
  296. add_docstr(
  297. torch.index_reduce,
  298. r"""
  299. index_reduce(input: Tensor, dim: int, index: Tensor, source: Tensor, reduce: str, *, include_self: bool = True, out: Optional[Tensor]) -> Tensor # noqa: B950
  300. See :meth:`~Tensor.index_reduce_` for function description.
  301. """,
  302. )
  303. add_docstr(
  304. torch.add,
  305. r"""
  306. add(input, other, *, alpha=1, out=None) -> Tensor
  307. Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`.
  308. .. math::
  309. \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i
  310. """
  311. + r"""
  312. Supports :ref:`broadcasting to a common shape <broadcasting-semantics>`,
  313. :ref:`type promotion <type-promotion-doc>`, and integer, float, and complex inputs.
  314. Args:
  315. {input}
  316. other (Tensor or Number): the tensor or number to add to :attr:`input`.
  317. Keyword arguments:
  318. alpha (Number): the multiplier for :attr:`other`.
  319. {out}
  320. Examples::
  321. >>> a = torch.randn(4)
  322. >>> a
  323. tensor([ 0.0202, 1.0985, 1.3506, -0.6056])
  324. >>> torch.add(a, 20)
  325. tensor([ 20.0202, 21.0985, 21.3506, 19.3944])
  326. >>> b = torch.randn(4)
  327. >>> b
  328. tensor([-0.9732, -0.3497, 0.6245, 0.4022])
  329. >>> c = torch.randn(4, 1)
  330. >>> c
  331. tensor([[ 0.3743],
  332. [-1.7724],
  333. [-0.5811],
  334. [-0.8017]])
  335. >>> torch.add(b, c, alpha=10)
  336. tensor([[ 2.7695, 3.3930, 4.3672, 4.1450],
  337. [-18.6971, -18.0736, -17.0994, -17.3216],
  338. [ -6.7845, -6.1610, -5.1868, -5.4090],
  339. [ -8.9902, -8.3667, -7.3925, -7.6147]])
  340. """.format(**common_args),
  341. )
  342. add_docstr(
  343. torch.addbmm,
  344. r"""
  345. addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor
  346. Performs a batch matrix-matrix product of matrices stored
  347. in :attr:`batch1` and :attr:`batch2`,
  348. with a reduced add step (all matrix multiplications get accumulated
  349. along the first dimension).
  350. :attr:`input` is added to the final result.
  351. :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the
  352. same number of matrices.
  353. If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a
  354. :math:`(b \times m \times p)` tensor, :attr:`input` must be
  355. :ref:`broadcastable <broadcasting-semantics>` with a :math:`(n \times p)` tensor
  356. and :attr:`out` will be a :math:`(n \times p)` tensor.
  357. .. math::
  358. out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i)
  359. If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in
  360. it will not be propagated.
  361. """
  362. + r"""
  363. For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha`
  364. must be real numbers, otherwise they should be integers.
  365. {tf32_note}
  366. {rocm_fp16_note}
  367. Args:
  368. input (Tensor): matrix to be added
  369. batch1 (Tensor): the first batch of matrices to be multiplied
  370. batch2 (Tensor): the second batch of matrices to be multiplied
  371. Keyword args:
  372. beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`)
  373. alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`)
  374. {out}
  375. Example::
  376. >>> M = torch.randn(3, 5)
  377. >>> batch1 = torch.randn(10, 3, 4)
  378. >>> batch2 = torch.randn(10, 4, 5)
  379. >>> torch.addbmm(M, batch1, batch2)
  380. tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653],
  381. [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743],
  382. [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]])
  383. """.format(**common_args, **tf32_notes, **rocm_fp16_notes),
  384. )
  385. add_docstr(
  386. torch.addcdiv,
  387. r"""
  388. addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor
  389. Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`,
  390. multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`.
  391. .. warning::
  392. Integer division with addcdiv is no longer supported, and in a future
  393. release addcdiv will perform a true division of tensor1 and tensor2.
  394. The historic addcdiv behavior can be implemented as
  395. (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype)
  396. for integer inputs and as (input + value * tensor1 / tensor2) for float inputs.
  397. The future addcdiv behavior is just the latter implementation:
  398. (input + value * tensor1 / tensor2), for all dtypes.
  399. .. math::
  400. \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i}
  401. """
  402. + r"""
  403. The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be
  404. :ref:`broadcastable <broadcasting-semantics>`.
  405. For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be
  406. a real number, otherwise an integer.
  407. Args:
  408. input (Tensor): the tensor to be added
  409. tensor1 (Tensor): the numerator tensor
  410. tensor2 (Tensor): the denominator tensor
  411. Keyword args:
  412. value (Number, optional): multiplier for :math:`\text{{tensor1}} / \text{{tensor2}}`
  413. {out}
  414. Example::
  415. >>> t = torch.randn(1, 3)
  416. >>> t1 = torch.randn(3, 1)
  417. >>> t2 = torch.randn(1, 3)
  418. >>> torch.addcdiv(t, t1, t2, value=0.1)
  419. tensor([[-0.2312, -3.6496, 0.1312],
  420. [-1.0428, 3.4292, -0.1030],
  421. [-0.5369, -0.9829, 0.0430]])
  422. """.format(**common_args),
  423. )
  424. add_docstr(
  425. torch.addcmul,
  426. r"""
  427. addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor
  428. Performs the element-wise multiplication of :attr:`tensor1`
  429. by :attr:`tensor2`, multiplies the result by the scalar :attr:`value`
  430. and adds it to :attr:`input`.
  431. .. math::
  432. \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i
  433. """
  434. + r"""
  435. The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be
  436. :ref:`broadcastable <broadcasting-semantics>`.
  437. For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be
  438. a real number, otherwise an integer.
  439. Args:
  440. input (Tensor): the tensor to be added
  441. tensor1 (Tensor): the tensor to be multiplied
  442. tensor2 (Tensor): the tensor to be multiplied
  443. Keyword args:
  444. value (Number, optional): multiplier for :math:`tensor1 .* tensor2`
  445. {out}
  446. Example::
  447. >>> t = torch.randn(1, 3)
  448. >>> t1 = torch.randn(3, 1)
  449. >>> t2 = torch.randn(1, 3)
  450. >>> torch.addcmul(t, t1, t2, value=0.1)
  451. tensor([[-0.8635, -0.6391, 1.6174],
  452. [-0.7617, -0.5879, 1.7388],
  453. [-0.8353, -0.6249, 1.6511]])
  454. """.format(**common_args),
  455. )
  456. add_docstr(
  457. torch.addmm,
  458. r"""
  459. addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor
  460. Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`.
  461. The matrix :attr:`input` is added to the final result.
  462. If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a
  463. :math:`(m \times p)` tensor, then :attr:`input` must be
  464. :ref:`broadcastable <broadcasting-semantics>` with a :math:`(n \times p)` tensor
  465. and :attr:`out` will be a :math:`(n \times p)` tensor.
  466. :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between
  467. :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively.
  468. .. math::
  469. \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i)
  470. If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in
  471. it will not be propagated.
  472. """
  473. + r"""
  474. For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and
  475. :attr:`alpha` must be real numbers, otherwise they should be integers.
  476. This operation has support for arguments with :ref:`sparse layouts<sparse-docs>`. If
  477. :attr:`input` is sparse the result will have the same layout and if :attr:`out`
  478. is provided it must have the same layout as :attr:`input`.
  479. {sparse_beta_warning}
  480. {tf32_note}
  481. {rocm_fp16_note}
  482. Args:
  483. input (Tensor): matrix to be added
  484. mat1 (Tensor): the first matrix to be matrix multiplied
  485. mat2 (Tensor): the second matrix to be matrix multiplied
  486. out_dtype (dtype, optional): the dtype of the output tensor,
  487. Supported only on CUDA and for torch.float32 given
  488. torch.float16/torch.bfloat16 input dtypes
  489. Keyword args:
  490. beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`)
  491. alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`)
  492. {out}
  493. Example::
  494. >>> M = torch.randn(2, 3)
  495. >>> mat1 = torch.randn(2, 3)
  496. >>> mat2 = torch.randn(3, 3)
  497. >>> torch.addmm(M, mat1, mat2)
  498. tensor([[-4.8716, 1.4671, -1.3746],
  499. [ 0.7573, -3.9555, -2.8681]])
  500. """.format(**common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes),
  501. )
  502. add_docstr(
  503. torch.adjoint,
  504. r"""
  505. adjoint(input: Tensor) -> Tensor
  506. Returns a view of the tensor conjugated and with the last two dimensions transposed.
  507. ``x.adjoint()`` is equivalent to ``x.transpose(-2, -1).conj()`` for complex tensors and
  508. to ``x.transpose(-2, -1)`` for real tensors.
  509. Args:
  510. {input}
  511. Example::
  512. >>> x = torch.arange(4, dtype=torch.float)
  513. >>> A = torch.complex(x, x).reshape(2, 2)
  514. >>> A
  515. tensor([[0.+0.j, 1.+1.j],
  516. [2.+2.j, 3.+3.j]])
  517. >>> A.adjoint()
  518. tensor([[0.-0.j, 2.-2.j],
  519. [1.-1.j, 3.-3.j]])
  520. >>> (A.adjoint() == A.mH).all()
  521. tensor(True)
  522. """,
  523. )
  524. add_docstr(
  525. torch.sspaddmm,
  526. r"""
  527. sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor
  528. Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor
  529. :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result.
  530. Note: This function is equivalent to :func:`torch.addmm`, except
  531. :attr:`input` and :attr:`mat1` are sparse.
  532. Args:
  533. input (Tensor): a sparse matrix to be added
  534. mat1 (Tensor): a sparse matrix to be matrix multiplied
  535. mat2 (Tensor): a dense matrix to be matrix multiplied
  536. Keyword args:
  537. beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`)
  538. alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`)
  539. {out}
  540. """.format(**common_args),
  541. )
  542. add_docstr(
  543. torch.smm,
  544. r"""
  545. smm(input, mat) -> Tensor
  546. Performs a matrix multiplication of the sparse matrix :attr:`input`
  547. with the dense matrix :attr:`mat`.
  548. Args:
  549. input (Tensor): a sparse matrix to be matrix multiplied
  550. mat (Tensor): a dense matrix to be matrix multiplied
  551. """,
  552. )
  553. add_docstr(
  554. torch.addmv,
  555. r"""
  556. addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor
  557. Performs a matrix-vector product of the matrix :attr:`mat` and
  558. the vector :attr:`vec`.
  559. The vector :attr:`input` is added to the final result.
  560. If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of
  561. size `m`, then :attr:`input` must be
  562. :ref:`broadcastable <broadcasting-semantics>` with a 1-D tensor of size `n` and
  563. :attr:`out` will be 1-D tensor of size `n`.
  564. :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between
  565. :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively.
  566. .. math::
  567. \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec})
  568. If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in
  569. it will not be propagated.
  570. """
  571. + r"""
  572. For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and
  573. :attr:`alpha` must be real numbers, otherwise they should be integers.
  574. Args:
  575. input (Tensor): vector to be added
  576. mat (Tensor): matrix to be matrix multiplied
  577. vec (Tensor): vector to be matrix multiplied
  578. Keyword args:
  579. beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`)
  580. alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`)
  581. {out}
  582. Example::
  583. >>> M = torch.randn(2)
  584. >>> mat = torch.randn(2, 3)
  585. >>> vec = torch.randn(3)
  586. >>> torch.addmv(M, mat, vec)
  587. tensor([-0.3768, -5.5565])
  588. """.format(**common_args),
  589. )
  590. add_docstr(
  591. torch.addr,
  592. r"""
  593. addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor
  594. Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2`
  595. and adds it to the matrix :attr:`input`.
  596. Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the
  597. outer product between :attr:`vec1` and :attr:`vec2` and the added matrix
  598. :attr:`input` respectively.
  599. .. math::
  600. \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2})
  601. If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in
  602. it will not be propagated.
  603. """
  604. + r"""
  605. If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector
  606. of size `m`, then :attr:`input` must be
  607. :ref:`broadcastable <broadcasting-semantics>` with a matrix of size
  608. :math:`(n \times m)` and :attr:`out` will be a matrix of size
  609. :math:`(n \times m)`.
  610. Args:
  611. input (Tensor): matrix to be added
  612. vec1 (Tensor): the first vector of the outer product
  613. vec2 (Tensor): the second vector of the outer product
  614. Keyword args:
  615. beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`)
  616. alpha (Number, optional): multiplier for :math:`\text{{vec1}} \otimes \text{{vec2}}` (:math:`\alpha`)
  617. {out}
  618. Example::
  619. >>> vec1 = torch.arange(1., 4.)
  620. >>> vec2 = torch.arange(1., 3.)
  621. >>> M = torch.zeros(3, 2)
  622. >>> torch.addr(M, vec1, vec2)
  623. tensor([[ 1., 2.],
  624. [ 2., 4.],
  625. [ 3., 6.]])
  626. """.format(**common_args),
  627. )
  628. add_docstr(
  629. torch.allclose,
  630. r"""
  631. allclose(input: Tensor, other: Tensor, rtol: float = 1e-05, atol: float = 1e-08, equal_nan: bool = False) -> bool
  632. This function checks if :attr:`input` and :attr:`other` satisfy the condition:
  633. .. math::
  634. \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other}_i \rvert
  635. """
  636. + r"""
  637. elementwise, for all elements of :attr:`input` and :attr:`other`. The behaviour of this function is analogous to
  638. `numpy.allclose <https://numpy.org/doc/stable/reference/generated/numpy.allclose.html>`_
  639. Args:
  640. input (Tensor): first tensor to compare
  641. other (Tensor): second tensor to compare
  642. atol (float, optional): absolute tolerance. Default: 1e-08
  643. rtol (float, optional): relative tolerance. Default: 1e-05
  644. equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False``
  645. Example::
  646. >>> torch.allclose(torch.tensor([10000., 1e-07]), torch.tensor([10000.1, 1e-08]))
  647. False
  648. >>> torch.allclose(torch.tensor([10000., 1e-08]), torch.tensor([10000.1, 1e-09]))
  649. True
  650. >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]))
  651. False
  652. >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]), equal_nan=True)
  653. True
  654. """,
  655. )
  656. add_docstr(
  657. torch.all,
  658. r"""
  659. all(input: Tensor, *, out=None) -> Tensor
  660. Tests if all elements in :attr:`input` evaluate to `True`.
  661. .. note:: This function matches the behaviour of NumPy in returning
  662. output of dtype `bool` for all supported dtypes except `uint8`.
  663. For `uint8` the dtype of output is `uint8` itself.
  664. Args:
  665. {input}
  666. Keyword args:
  667. {out}
  668. Example::
  669. >>> a = torch.rand(1, 2).bool()
  670. >>> a
  671. tensor([[False, True]], dtype=torch.bool)
  672. >>> torch.all(a)
  673. tensor(False, dtype=torch.bool)
  674. >>> a = torch.arange(0, 3)
  675. >>> a
  676. tensor([0, 1, 2])
  677. >>> torch.all(a)
  678. tensor(False)
  679. .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor
  680. :noindex:
  681. For each row of :attr:`input` in the given dimension :attr:`dim`,
  682. returns `True` if all elements in the row evaluate to `True` and `False` otherwise.
  683. {keepdim_details}
  684. Args:
  685. {input}
  686. {opt_dim_all_reduce}
  687. {opt_keepdim}
  688. Keyword args:
  689. {out}
  690. Example::
  691. >>> a = torch.rand(4, 2).bool()
  692. >>> a
  693. tensor([[True, True],
  694. [True, False],
  695. [True, True],
  696. [True, True]], dtype=torch.bool)
  697. >>> torch.all(a, dim=1)
  698. tensor([ True, False, True, True], dtype=torch.bool)
  699. >>> torch.all(a, dim=0)
  700. tensor([ True, False], dtype=torch.bool)
  701. """.format(**multi_dim_common),
  702. )
  703. add_docstr(
  704. torch.any,
  705. r"""
  706. any(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  707. Tests if any element in :attr:`input` evaluates to `True`.
  708. .. note:: This function matches the behaviour of NumPy in returning
  709. output of dtype `bool` for all supported dtypes except `uint8`.
  710. For `uint8` the dtype of output is `uint8` itself.
  711. Args:
  712. {input}
  713. Keyword args:
  714. {out}
  715. Example::
  716. >>> a = torch.rand(1, 2).bool()
  717. >>> a
  718. tensor([[False, True]], dtype=torch.bool)
  719. >>> torch.any(a)
  720. tensor(True, dtype=torch.bool)
  721. >>> a = torch.arange(0, 3)
  722. >>> a
  723. tensor([0, 1, 2])
  724. >>> torch.any(a)
  725. tensor(True)
  726. .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor
  727. :noindex:
  728. For each row of :attr:`input` in the given dimension :attr:`dim`,
  729. returns `True` if any element in the row evaluate to `True` and `False` otherwise.
  730. {keepdim_details}
  731. Args:
  732. {input}
  733. {opt_dim_all_reduce}
  734. {opt_keepdim}
  735. Keyword args:
  736. {out}
  737. Example::
  738. >>> a = torch.randn(4, 2) < 0
  739. >>> a
  740. tensor([[ True, True],
  741. [False, True],
  742. [ True, True],
  743. [False, False]])
  744. >>> torch.any(a, 1)
  745. tensor([ True, True, True, False])
  746. >>> torch.any(a, 0)
  747. tensor([True, True])
  748. """.format(**multi_dim_common),
  749. )
  750. add_docstr(
  751. torch.angle,
  752. r"""
  753. angle(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  754. Computes the element-wise angle (in radians) of the given :attr:`input` tensor.
  755. .. math::
  756. \text{out}_{i} = angle(\text{input}_{i})
  757. """
  758. + r"""
  759. Args:
  760. {input}
  761. Keyword args:
  762. {out}
  763. .. note:: Starting in PyTorch 1.8, angle returns pi for negative real numbers,
  764. zero for non-negative real numbers, and propagates NaNs. Previously
  765. the function would return zero for all real numbers and not propagate
  766. floating-point NaNs.
  767. Example::
  768. >>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159
  769. tensor([ 135., 135, -45])
  770. """.format(**common_args),
  771. )
  772. add_docstr(
  773. torch.as_strided,
  774. r"""
  775. as_strided(input, size, stride, storage_offset=None) -> Tensor
  776. Create a view of an existing `torch.Tensor` :attr:`input` with specified
  777. :attr:`size`, :attr:`stride` and :attr:`storage_offset`.
  778. .. warning::
  779. Prefer using other view functions, like :meth:`torch.Tensor.view` or
  780. :meth:`torch.Tensor.expand`, to setting a view's strides manually with
  781. `as_strided`, as this function will throw an error on non-standard Pytorch
  782. backends (that do not have a concept of stride) and the result will depend
  783. on the current layout in memory. The constructed view must only refer to
  784. elements within the Tensor's storage or a runtime error will be thrown.
  785. If the generated view is "overlapped" (with multiple indices referring to
  786. the same element in memory), the behavior of inplace operations on this view
  787. is undefined (and might not throw runtime errors).
  788. Args:
  789. {input}
  790. size (tuple or ints): the shape of the output tensor
  791. stride (tuple or ints): the stride of the output tensor
  792. storage_offset (int, optional): the offset in the underlying storage of the output tensor.
  793. If ``None``, the storage_offset of the output tensor will match the input tensor.
  794. Example::
  795. >>> x = torch.randn(3, 3)
  796. >>> x
  797. tensor([[ 0.9039, 0.6291, 1.0795],
  798. [ 0.1586, 2.1939, -0.4900],
  799. [-0.1909, -0.7503, 1.9355]])
  800. >>> t = torch.as_strided(x, (2, 2), (1, 2))
  801. >>> t
  802. tensor([[0.9039, 1.0795],
  803. [0.6291, 0.1586]])
  804. >>> t = torch.as_strided(x, (2, 2), (1, 2), 1)
  805. tensor([[0.6291, 0.1586],
  806. [1.0795, 2.1939]])
  807. """.format(**common_args),
  808. )
  809. add_docstr(
  810. torch.as_tensor,
  811. r"""
  812. as_tensor(data: Any, *, dtype: Optional[dtype] = None, device: Optional[DeviceLikeType]) -> Tensor
  813. Converts :attr:`data` into a tensor, sharing data and preserving autograd
  814. history if possible.
  815. If :attr:`data` is already a tensor with the requested dtype and device
  816. then :attr:`data` itself is returned, but if :attr:`data` is a
  817. tensor with a different dtype or device then it's copied as if using
  818. `data.to(dtype=dtype, device=device)`.
  819. If :attr:`data` is a NumPy array (an ndarray) with the same dtype and device then a
  820. tensor is constructed using :func:`torch.from_numpy`.
  821. If :attr:`data` is a CuPy array, the returned tensor will be located on the same device as the CuPy array unless
  822. specifically overwritten by :attr:`device` or a default device. The device of the CuPy array is inferred from the
  823. pointer of the array using `cudaPointerGetAttributes` unless :attr:`device` is provided with an explicit device index.
  824. .. seealso::
  825. :func:`torch.tensor` never shares its data and creates a new "leaf tensor" (see :doc:`/notes/autograd`).
  826. Args:
  827. {data}
  828. {dtype}
  829. device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor
  830. then the device of data is used. If None and data is not a tensor then
  831. the result tensor is constructed on the current device.
  832. Example::
  833. >>> a = numpy.array([1, 2, 3])
  834. >>> t = torch.as_tensor(a)
  835. >>> t
  836. tensor([ 1, 2, 3])
  837. >>> t[0] = -1
  838. >>> a
  839. array([-1, 2, 3])
  840. >>> a = numpy.array([1, 2, 3])
  841. >>> t = torch.as_tensor(a, device=torch.device('cuda'))
  842. >>> t
  843. tensor([ 1, 2, 3])
  844. >>> t[0] = -1
  845. >>> a
  846. array([1, 2, 3])
  847. """.format(**factory_data_common_args),
  848. )
  849. add_docstr(
  850. torch.asin,
  851. r"""
  852. asin(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  853. Returns a new tensor with the arcsine of the elements (in radians) in the :attr:`input` tensor.
  854. .. math::
  855. \text{out}_{i} = \sin^{-1}(\text{input}_{i})
  856. """
  857. + r"""
  858. Args:
  859. {input}
  860. Keyword args:
  861. {out}
  862. Example::
  863. >>> a = torch.randn(4)
  864. >>> a
  865. tensor([-0.5962, 1.4985, -0.4396, 1.4525])
  866. >>> torch.asin(a)
  867. tensor([-0.6387, nan, -0.4552, nan])
  868. """.format(**common_args),
  869. )
  870. add_docstr(
  871. torch.arcsin,
  872. r"""
  873. arcsin(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  874. Alias for :func:`torch.asin`.
  875. """,
  876. )
  877. add_docstr(
  878. torch.asinh,
  879. r"""
  880. asinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  881. Returns a new tensor with the inverse hyperbolic sine of the elements of :attr:`input`.
  882. .. math::
  883. \text{out}_{i} = \sinh^{-1}(\text{input}_{i})
  884. """
  885. + r"""
  886. Args:
  887. {input}
  888. Keyword arguments:
  889. {out}
  890. Example::
  891. >>> a = torch.randn(4)
  892. >>> a
  893. tensor([ 0.1606, -1.4267, -1.0899, -1.0250 ])
  894. >>> torch.asinh(a)
  895. tensor([ 0.1599, -1.1534, -0.9435, -0.8990 ])
  896. """.format(**common_args),
  897. )
  898. add_docstr(
  899. torch.arcsinh,
  900. r"""
  901. arcsinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  902. Alias for :func:`torch.asinh`.
  903. """,
  904. )
  905. add_docstr(
  906. torch.atan,
  907. r"""
  908. atan(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  909. Returns a new tensor with the arctangent of the elements (in radians) in the :attr:`input` tensor.
  910. .. math::
  911. \text{out}_{i} = \tan^{-1}(\text{input}_{i})
  912. """
  913. + r"""
  914. Args:
  915. {input}
  916. Keyword args:
  917. {out}
  918. Example::
  919. >>> a = torch.randn(4)
  920. >>> a
  921. tensor([ 0.2341, 0.2539, -0.6256, -0.6448])
  922. >>> torch.atan(a)
  923. tensor([ 0.2299, 0.2487, -0.5591, -0.5727])
  924. """.format(**common_args),
  925. )
  926. add_docstr(
  927. torch.arctan,
  928. r"""
  929. arctan(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  930. Alias for :func:`torch.atan`.
  931. """,
  932. )
  933. add_docstr(
  934. torch.atan2,
  935. r"""
  936. atan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor
  937. Element-wise arctangent of :math:`\text{{input}}_{{i}} / \text{{other}}_{{i}}`
  938. with consideration of the quadrant. Returns a new tensor with the signed angles
  939. in radians between vector :math:`(\text{{other}}_{{i}}, \text{{input}}_{{i}})`
  940. and vector :math:`(1, 0)`. (Note that :math:`\text{{other}}_{{i}}`, the second
  941. parameter, is the x-coordinate, while :math:`\text{{input}}_{{i}}`, the first
  942. parameter, is the y-coordinate.)
  943. The shapes of ``input`` and ``other`` must be
  944. :ref:`broadcastable <broadcasting-semantics>`.
  945. Args:
  946. input (Tensor): the first input tensor
  947. other (Tensor): the second input tensor
  948. Keyword args:
  949. {out}
  950. Example::
  951. >>> a = torch.randn(4)
  952. >>> a
  953. tensor([ 0.9041, 0.0196, -0.3108, -2.4423])
  954. >>> torch.atan2(a, torch.randn(4))
  955. tensor([ 0.9833, 0.0811, -1.9743, -1.4151])
  956. """.format(**common_args),
  957. )
  958. add_docstr(
  959. torch.arctan2,
  960. r"""
  961. arctan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor
  962. Alias for :func:`torch.atan2`.
  963. """,
  964. )
  965. add_docstr(
  966. torch.atanh,
  967. r"""
  968. atanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  969. Returns a new tensor with the inverse hyperbolic tangent of the elements of :attr:`input`.
  970. Note:
  971. The domain of the inverse hyperbolic tangent is `(-1, 1)` and values outside this range
  972. will be mapped to ``NaN``, except for the values `1` and `-1` for which the output is
  973. mapped to `+/-INF` respectively.
  974. .. math::
  975. \text{out}_{i} = \tanh^{-1}(\text{input}_{i})
  976. """
  977. + r"""
  978. Args:
  979. {input}
  980. Keyword arguments:
  981. {out}
  982. Example::
  983. >>> a = torch.randn(4).uniform_(-1, 1)
  984. >>> a
  985. tensor([ -0.9385, 0.2968, -0.8591, -0.1871 ])
  986. >>> torch.atanh(a)
  987. tensor([ -1.7253, 0.3060, -1.2899, -0.1893 ])
  988. """.format(**common_args),
  989. )
  990. add_docstr(
  991. torch.arctanh,
  992. r"""
  993. arctanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  994. Alias for :func:`torch.atanh`.
  995. """,
  996. )
  997. add_docstr(
  998. torch.asarray,
  999. r"""
  1000. asarray(obj: Any, *, dtype: Optional[dtype], device: Optional[DeviceLikeType], copy: Optional[bool] = None, requires_grad: bool = False) -> Tensor # noqa: B950
  1001. Converts :attr:`obj` to a tensor.
  1002. :attr:`obj` can be one of:
  1003. 1. a tensor
  1004. 2. a NumPy array or a NumPy scalar
  1005. 3. a DLPack capsule
  1006. 4. an object that implements Python's buffer protocol
  1007. 5. a scalar
  1008. 6. a sequence of scalars
  1009. When :attr:`obj` is a tensor, NumPy array, or DLPack capsule the returned tensor will,
  1010. by default, not require a gradient, have the same datatype as :attr:`obj`, be on the
  1011. same device, and share memory with it. These properties can be controlled with the
  1012. :attr:`dtype`, :attr:`device`, :attr:`copy`, and :attr:`requires_grad` keyword arguments.
  1013. If the returned tensor is of a different datatype, on a different device, or a copy is
  1014. requested then it will not share its memory with :attr:`obj`. If :attr:`requires_grad`
  1015. is ``True`` then the returned tensor will require a gradient, and if :attr:`obj` is
  1016. also a tensor with an autograd history then the returned tensor will have the same history.
  1017. When :attr:`obj` is not a tensor, NumPy array, or DLPack capsule but implements Python's
  1018. buffer protocol then the buffer is interpreted as an array of bytes grouped according to
  1019. the size of the datatype passed to the :attr:`dtype` keyword argument. (If no datatype is
  1020. passed then the default floating point datatype is used, instead.) The returned tensor
  1021. will have the specified datatype (or default floating point datatype if none is specified)
  1022. and, by default, be on the CPU device and share memory with the buffer.
  1023. When :attr:`obj` is a NumPy scalar, the returned tensor will be a 0-dimensional tensor on
  1024. the CPU and that doesn't share its memory (i.e. ``copy=True``). By default datatype will
  1025. be the PyTorch datatype corresponding to the NumPy's scalar's datatype.
  1026. When :attr:`obj` is none of the above but a scalar, or a sequence of scalars then the
  1027. returned tensor will, by default, infer its datatype from the scalar values, be on the
  1028. current default device, and not share its memory.
  1029. .. seealso::
  1030. :func:`torch.tensor` creates a tensor that always copies the data from the input object.
  1031. :func:`torch.from_numpy` creates a tensor that always shares memory from NumPy arrays.
  1032. :func:`torch.frombuffer` creates a tensor that always shares memory from objects that
  1033. implement the buffer protocol.
  1034. :func:`torch.from_dlpack` creates a tensor that always shares memory from
  1035. DLPack capsules.
  1036. Args:
  1037. obj (object): a tensor, NumPy array, DLPack Capsule, object that implements Python's
  1038. buffer protocol, scalar, or sequence of scalars.
  1039. Keyword args:
  1040. dtype (:class:`torch.dtype`, optional): the datatype of the returned tensor.
  1041. Default: ``None``, which causes the datatype of the returned tensor to be
  1042. inferred from :attr:`obj`.
  1043. copy (bool, optional): controls whether the returned tensor shares memory with :attr:`obj`.
  1044. Default: ``None``, which causes the returned tensor to share memory with :attr:`obj`
  1045. whenever possible. If ``True`` then the returned tensor does not share its memory.
  1046. If ``False`` then the returned tensor shares its memory with :attr:`obj` and an
  1047. error is thrown if it cannot.
  1048. device (:class:`torch.device`, optional): the device of the returned tensor.
  1049. Default: ``None``, which causes the device of :attr:`obj` to be used. Or, if
  1050. :attr:`obj` is a Python sequence, the current default device will be used.
  1051. requires_grad (bool, optional): whether the returned tensor requires grad.
  1052. Default: ``False``, which causes the returned tensor not to require a gradient.
  1053. If ``True``, then the returned tensor will require a gradient, and if :attr:`obj`
  1054. is also a tensor with an autograd history then the returned tensor will have
  1055. the same history.
  1056. Example::
  1057. >>> a = torch.tensor([1, 2, 3])
  1058. >>> # Shares memory with tensor 'a'
  1059. >>> b = torch.asarray(a)
  1060. >>> a.data_ptr() == b.data_ptr()
  1061. True
  1062. >>> # Forces memory copy
  1063. >>> c = torch.asarray(a, copy=True)
  1064. >>> a.data_ptr() == c.data_ptr()
  1065. False
  1066. >>> a = torch.tensor([1., 2., 3.], requires_grad=True)
  1067. >>> b = a + 2
  1068. >>> b
  1069. tensor([3., 4., 5.], grad_fn=<AddBackward0>)
  1070. >>> # Shares memory with tensor 'b', with no grad
  1071. >>> c = torch.asarray(b)
  1072. >>> c
  1073. tensor([3., 4., 5.])
  1074. >>> # Shares memory with tensor 'b', retaining autograd history
  1075. >>> d = torch.asarray(b, requires_grad=True)
  1076. >>> d
  1077. tensor([3., 4., 5.], grad_fn=<AddBackward0>)
  1078. >>> array = numpy.array([1, 2, 3])
  1079. >>> # Shares memory with array 'array'
  1080. >>> t1 = torch.asarray(array)
  1081. >>> array.__array_interface__['data'][0] == t1.data_ptr()
  1082. True
  1083. >>> # Copies memory due to dtype mismatch
  1084. >>> t2 = torch.asarray(array, dtype=torch.float32)
  1085. >>> array.__array_interface__['data'][0] == t2.data_ptr()
  1086. False
  1087. >>> scalar = numpy.float64(0.5)
  1088. >>> torch.asarray(scalar)
  1089. tensor(0.5000, dtype=torch.float64)
  1090. """,
  1091. )
  1092. add_docstr(
  1093. torch.baddbmm,
  1094. r"""
  1095. baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor
  1096. Performs a batch matrix-matrix product of matrices in :attr:`batch1`
  1097. and :attr:`batch2`.
  1098. :attr:`input` is added to the final result.
  1099. :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same
  1100. number of matrices.
  1101. If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a
  1102. :math:`(b \times m \times p)` tensor, then :attr:`input` must be
  1103. :ref:`broadcastable <broadcasting-semantics>` with a
  1104. :math:`(b \times n \times p)` tensor and :attr:`out` will be a
  1105. :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the
  1106. same as the scaling factors used in :meth:`torch.addbmm`.
  1107. .. math::
  1108. \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i)
  1109. If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in
  1110. it will not be propagated.
  1111. """
  1112. + r"""
  1113. For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and
  1114. :attr:`alpha` must be real numbers, otherwise they should be integers.
  1115. {tf32_note}
  1116. {rocm_fp16_note}
  1117. Args:
  1118. input (Tensor): the tensor to be added
  1119. batch1 (Tensor): the first batch of matrices to be multiplied
  1120. batch2 (Tensor): the second batch of matrices to be multiplied
  1121. out_dtype (dtype, optional): the dtype of the output tensor,
  1122. Supported only on CUDA and for torch.float32 given
  1123. torch.float16/torch.bfloat16 input dtypes
  1124. Keyword args:
  1125. beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`)
  1126. alpha (Number, optional): multiplier for :math:`\text{{batch1}} \mathbin{{@}} \text{{batch2}}` (:math:`\alpha`)
  1127. {out}
  1128. Example::
  1129. >>> M = torch.randn(10, 3, 5)
  1130. >>> batch1 = torch.randn(10, 3, 4)
  1131. >>> batch2 = torch.randn(10, 4, 5)
  1132. >>> torch.baddbmm(M, batch1, batch2).size()
  1133. torch.Size([10, 3, 5])
  1134. """.format(**common_args, **tf32_notes, **rocm_fp16_notes),
  1135. )
  1136. add_docstr(
  1137. torch.bernoulli,
  1138. r"""
  1139. bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) -> Tensor
  1140. Draws binary random numbers (0 or 1) from a Bernoulli distribution.
  1141. The :attr:`input` tensor should be a tensor containing probabilities
  1142. to be used for drawing the binary random number.
  1143. Hence, all values in :attr:`input` have to be in the range:
  1144. :math:`0 \leq \text{input}_i \leq 1`.
  1145. The :math:`\text{i}^{th}` element of the output tensor will draw a
  1146. value :math:`1` according to the :math:`\text{i}^{th}` probability value given
  1147. in :attr:`input`.
  1148. .. math::
  1149. \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i})
  1150. """
  1151. + r"""
  1152. The returned :attr:`out` tensor only has values 0 or 1 and is of the same
  1153. shape as :attr:`input`.
  1154. :attr:`out` can have integral ``dtype``, but :attr:`input` must have floating
  1155. point ``dtype``.
  1156. Args:
  1157. input (Tensor): the input tensor of probability values for the Bernoulli distribution
  1158. Keyword args:
  1159. {generator}
  1160. {out}
  1161. Example::
  1162. >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1]
  1163. >>> a
  1164. tensor([[ 0.1737, 0.0950, 0.3609],
  1165. [ 0.7148, 0.0289, 0.2676],
  1166. [ 0.9456, 0.8937, 0.7202]])
  1167. >>> torch.bernoulli(a)
  1168. tensor([[ 1., 0., 0.],
  1169. [ 0., 0., 0.],
  1170. [ 1., 1., 1.]])
  1171. >>> a = torch.ones(3, 3) # probability of drawing "1" is 1
  1172. >>> torch.bernoulli(a)
  1173. tensor([[ 1., 1., 1.],
  1174. [ 1., 1., 1.],
  1175. [ 1., 1., 1.]])
  1176. >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0
  1177. >>> torch.bernoulli(a)
  1178. tensor([[ 0., 0., 0.],
  1179. [ 0., 0., 0.],
  1180. [ 0., 0., 0.]])
  1181. """.format(**common_args),
  1182. )
  1183. add_docstr(
  1184. torch.bincount,
  1185. r"""
  1186. bincount(input, weights=None, minlength=0) -> Tensor
  1187. Count the frequency of each value in an array of non-negative ints.
  1188. The number of bins (size 1) is one larger than the largest value in
  1189. :attr:`input` unless :attr:`input` is empty, in which case the result is a
  1190. tensor of size 0. If :attr:`minlength` is specified, the number of bins is at least
  1191. :attr:`minlength` and if :attr:`input` is empty, then the result is tensor of size
  1192. :attr:`minlength` filled with zeros. If ``n`` is the value at position ``i``,
  1193. ``out[n] += weights[i]`` if :attr:`weights` is specified else
  1194. ``out[n] += 1``.
  1195. Note:
  1196. {backward_reproducibility_note}
  1197. Arguments:
  1198. input (Tensor): 1-d int tensor
  1199. weights (Tensor): optional, weight for each value in the input tensor.
  1200. Should be of same size as input tensor.
  1201. minlength (int): optional, minimum number of bins. Should be non-negative.
  1202. Returns:
  1203. output (Tensor): a tensor of shape ``Size([max(input) + 1])`` if
  1204. :attr:`input` is non-empty, else ``Size(0)``
  1205. Example::
  1206. >>> input = torch.randint(0, 8, (5,), dtype=torch.int64)
  1207. >>> weights = torch.linspace(0, 1, steps=5)
  1208. >>> input, weights
  1209. (tensor([4, 3, 6, 3, 4]),
  1210. tensor([ 0.0000, 0.2500, 0.5000, 0.7500, 1.0000])
  1211. >>> torch.bincount(input)
  1212. tensor([0, 0, 0, 2, 2, 0, 1])
  1213. >>> input.bincount(weights)
  1214. tensor([0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 0.0000, 0.5000])
  1215. """.format(**reproducibility_notes),
  1216. )
  1217. add_docstr(
  1218. torch.bitwise_not,
  1219. r"""
  1220. bitwise_not(input, *, out=None) -> Tensor
  1221. Computes the bitwise NOT of the given input tensor. The input tensor must be of
  1222. integral or Boolean types. For bool tensors, it computes the logical NOT.
  1223. Args:
  1224. {input}
  1225. Keyword args:
  1226. {out}
  1227. Example::
  1228. >>> torch.bitwise_not(torch.tensor([-1, -2, 3], dtype=torch.int8))
  1229. tensor([ 0, 1, -4], dtype=torch.int8)
  1230. """.format(**common_args),
  1231. )
  1232. add_docstr(
  1233. torch.bmm,
  1234. r"""
  1235. bmm(input, mat2, out_dtype=None, *, out=None) -> Tensor
  1236. Performs a batch matrix-matrix product of matrices stored in :attr:`input`
  1237. and :attr:`mat2`.
  1238. :attr:`input` and :attr:`mat2` must be 3-D tensors each containing
  1239. the same number of matrices.
  1240. If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a
  1241. :math:`(b \times m \times p)` tensor, :attr:`out` will be a
  1242. :math:`(b \times n \times p)` tensor.
  1243. .. math::
  1244. \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i
  1245. """
  1246. + r"""
  1247. {tf32_note}
  1248. {rocm_fp16_note}
  1249. .. note:: This function does not :ref:`broadcast <broadcasting-semantics>`.
  1250. For broadcasting matrix products, see :func:`torch.matmul`.
  1251. Args:
  1252. input (Tensor): the first batch of matrices to be multiplied
  1253. mat2 (Tensor): the second batch of matrices to be multiplied
  1254. out_dtype (dtype, optional): the dtype of the output tensor,
  1255. Supported only on CUDA and for torch.float32 given
  1256. torch.float16/torch.bfloat16 input dtypes
  1257. Keyword Args:
  1258. {out}
  1259. Example::
  1260. >>> input = torch.randn(10, 3, 4)
  1261. >>> mat2 = torch.randn(10, 4, 5)
  1262. >>> res = torch.bmm(input, mat2)
  1263. >>> res.size()
  1264. torch.Size([10, 3, 5])
  1265. """.format(**common_args, **tf32_notes, **rocm_fp16_notes),
  1266. )
  1267. add_docstr(
  1268. torch.bitwise_and,
  1269. r"""
  1270. bitwise_and(input, other, *, out=None) -> Tensor
  1271. Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of
  1272. integral or Boolean types. For bool tensors, it computes the logical AND.
  1273. Args:
  1274. input: the first input tensor
  1275. other: the second input tensor
  1276. Keyword args:
  1277. {out}
  1278. Example::
  1279. >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8))
  1280. tensor([1, 0, 3], dtype=torch.int8)
  1281. >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False]))
  1282. tensor([ False, True, False])
  1283. """.format(**common_args),
  1284. )
  1285. add_docstr(
  1286. torch.bitwise_or,
  1287. r"""
  1288. bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor
  1289. Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of
  1290. integral or Boolean types. For bool tensors, it computes the logical OR.
  1291. Args:
  1292. input: the first input tensor
  1293. other: the second input tensor
  1294. Keyword args:
  1295. {out}
  1296. Example::
  1297. >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8))
  1298. tensor([-1, -2, 3], dtype=torch.int8)
  1299. >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False]))
  1300. tensor([ True, True, False])
  1301. """.format(**common_args),
  1302. )
  1303. add_docstr(
  1304. torch.bitwise_xor,
  1305. r"""
  1306. bitwise_xor(input, other, *, out=None) -> Tensor
  1307. Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of
  1308. integral or Boolean types. For bool tensors, it computes the logical XOR.
  1309. Args:
  1310. input: the first input tensor
  1311. other: the second input tensor
  1312. Keyword args:
  1313. {out}
  1314. Example::
  1315. >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8))
  1316. tensor([-2, -2, 0], dtype=torch.int8)
  1317. >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False]))
  1318. tensor([ True, False, False])
  1319. """.format(**common_args),
  1320. )
  1321. add_docstr(
  1322. torch.bitwise_left_shift,
  1323. r"""
  1324. bitwise_left_shift(input, other, *, out=None) -> Tensor
  1325. Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits.
  1326. The input tensor must be of integral type. This operator supports
  1327. :ref:`broadcasting to a common shape <broadcasting-semantics>` and
  1328. :ref:`type promotion <type-promotion-doc>`.
  1329. The operation applied is:
  1330. .. math::
  1331. \text{{out}}_i = \text{{input}}_i << \text{{other}}_i
  1332. Args:
  1333. input (Tensor or Scalar): the first input tensor
  1334. other (Tensor or Scalar): the second input tensor
  1335. Keyword args:
  1336. {out}
  1337. Example::
  1338. >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8))
  1339. tensor([-2, -2, 24], dtype=torch.int8)
  1340. """.format(**common_args),
  1341. )
  1342. add_docstr(
  1343. torch.bitwise_right_shift,
  1344. r"""
  1345. bitwise_right_shift(input, other, *, out=None) -> Tensor
  1346. Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits.
  1347. The input tensor must be of integral type. This operator supports
  1348. :ref:`broadcasting to a common shape <broadcasting-semantics>` and
  1349. :ref:`type promotion <type-promotion-doc>`.
  1350. In any case, if the value of the right operand is negative or is greater
  1351. or equal to the number of bits in the promoted left operand, the behavior is undefined.
  1352. The operation applied is:
  1353. .. math::
  1354. \text{{out}}_i = \text{{input}}_i >> \text{{other}}_i
  1355. Args:
  1356. input (Tensor or Scalar): the first input tensor
  1357. other (Tensor or Scalar): the second input tensor
  1358. Keyword args:
  1359. {out}
  1360. Example::
  1361. >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8))
  1362. tensor([-1, -7, 3], dtype=torch.int8)
  1363. """.format(**common_args),
  1364. )
  1365. add_docstr(
  1366. torch.broadcast_to,
  1367. r"""
  1368. broadcast_to(input, shape) -> Tensor
  1369. Broadcasts :attr:`input` to the shape :attr:`\shape`.
  1370. Equivalent to calling ``input.expand(shape)``. See :meth:`~Tensor.expand` for details.
  1371. Args:
  1372. {input}
  1373. shape (list, tuple, or :class:`torch.Size`): the new shape.
  1374. Example::
  1375. >>> x = torch.tensor([1, 2, 3])
  1376. >>> torch.broadcast_to(x, (3, 3))
  1377. tensor([[1, 2, 3],
  1378. [1, 2, 3],
  1379. [1, 2, 3]])
  1380. """.format(**common_args),
  1381. )
  1382. add_docstr(
  1383. torch.stack,
  1384. r"""
  1385. stack(tensors, dim=0, *, out=None) -> Tensor
  1386. Concatenates a sequence of tensors along a new dimension.
  1387. All tensors need to be of the same size.
  1388. .. seealso::
  1389. :func:`torch.cat` concatenates the given sequence along an existing dimension.
  1390. Arguments:
  1391. tensors (sequence of Tensors): sequence of tensors to concatenate
  1392. dim (int, optional): dimension to insert. Has to be between 0 and the number
  1393. of dimensions of concatenated tensors (inclusive). Default: 0
  1394. Keyword args:
  1395. {out}
  1396. Example::
  1397. >>> x = torch.randn(2, 3)
  1398. >>> x
  1399. tensor([[ 0.3367, 0.1288, 0.2345],
  1400. [ 0.2303, -1.1229, -0.1863]])
  1401. >>> torch.stack((x, x)) # same as torch.stack((x, x), dim=0)
  1402. tensor([[[ 0.3367, 0.1288, 0.2345],
  1403. [ 0.2303, -1.1229, -0.1863]],
  1404. [[ 0.3367, 0.1288, 0.2345],
  1405. [ 0.2303, -1.1229, -0.1863]]])
  1406. >>> torch.stack((x, x)).size()
  1407. torch.Size([2, 2, 3])
  1408. >>> torch.stack((x, x), dim=1)
  1409. tensor([[[ 0.3367, 0.1288, 0.2345],
  1410. [ 0.3367, 0.1288, 0.2345]],
  1411. [[ 0.2303, -1.1229, -0.1863],
  1412. [ 0.2303, -1.1229, -0.1863]]])
  1413. >>> torch.stack((x, x), dim=2)
  1414. tensor([[[ 0.3367, 0.3367],
  1415. [ 0.1288, 0.1288],
  1416. [ 0.2345, 0.2345]],
  1417. [[ 0.2303, 0.2303],
  1418. [-1.1229, -1.1229],
  1419. [-0.1863, -0.1863]]])
  1420. >>> torch.stack((x, x), dim=-1)
  1421. tensor([[[ 0.3367, 0.3367],
  1422. [ 0.1288, 0.1288],
  1423. [ 0.2345, 0.2345]],
  1424. [[ 0.2303, 0.2303],
  1425. [-1.1229, -1.1229],
  1426. [-0.1863, -0.1863]]])
  1427. """.format(**common_args),
  1428. )
  1429. add_docstr(
  1430. torch.hstack,
  1431. r"""
  1432. hstack(tensors, *, out=None) -> Tensor
  1433. Stack tensors in sequence horizontally (column wise).
  1434. This is equivalent to concatenation along the first axis for 1-D tensors, and along the second axis for all other tensors.
  1435. Args:
  1436. tensors (sequence of Tensors): sequence of tensors to concatenate
  1437. Keyword args:
  1438. {out}
  1439. Example::
  1440. >>> a = torch.tensor([1, 2, 3])
  1441. >>> b = torch.tensor([4, 5, 6])
  1442. >>> torch.hstack((a,b))
  1443. tensor([1, 2, 3, 4, 5, 6])
  1444. >>> a = torch.tensor([[1],[2],[3]])
  1445. >>> b = torch.tensor([[4],[5],[6]])
  1446. >>> torch.hstack((a,b))
  1447. tensor([[1, 4],
  1448. [2, 5],
  1449. [3, 6]])
  1450. """.format(**common_args),
  1451. )
  1452. add_docstr(
  1453. torch.vstack,
  1454. r"""
  1455. vstack(tensors, *, out=None) -> Tensor
  1456. Stack tensors in sequence vertically (row wise).
  1457. This is equivalent to concatenation along the first axis after all 1-D tensors have been reshaped by :func:`torch.atleast_2d`.
  1458. Args:
  1459. tensors (sequence of Tensors): sequence of tensors to concatenate
  1460. Keyword args:
  1461. {out}
  1462. Example::
  1463. >>> a = torch.tensor([1, 2, 3])
  1464. >>> b = torch.tensor([4, 5, 6])
  1465. >>> torch.vstack((a,b))
  1466. tensor([[1, 2, 3],
  1467. [4, 5, 6]])
  1468. >>> a = torch.tensor([[1],[2],[3]])
  1469. >>> b = torch.tensor([[4],[5],[6]])
  1470. >>> torch.vstack((a,b))
  1471. tensor([[1],
  1472. [2],
  1473. [3],
  1474. [4],
  1475. [5],
  1476. [6]])
  1477. """.format(**common_args),
  1478. )
  1479. add_docstr(
  1480. torch.dstack,
  1481. r"""
  1482. dstack(tensors, *, out=None) -> Tensor
  1483. Stack tensors in sequence depthwise (along third axis).
  1484. This is equivalent to concatenation along the third axis after 1-D and 2-D tensors have been reshaped by :func:`torch.atleast_3d`.
  1485. Args:
  1486. tensors (sequence of Tensors): sequence of tensors to concatenate
  1487. Keyword args:
  1488. {out}
  1489. Example::
  1490. >>> a = torch.tensor([1, 2, 3])
  1491. >>> b = torch.tensor([4, 5, 6])
  1492. >>> torch.dstack((a,b))
  1493. tensor([[[1, 4],
  1494. [2, 5],
  1495. [3, 6]]])
  1496. >>> a = torch.tensor([[1],[2],[3]])
  1497. >>> b = torch.tensor([[4],[5],[6]])
  1498. >>> torch.dstack((a,b))
  1499. tensor([[[1, 4]],
  1500. [[2, 5]],
  1501. [[3, 6]]])
  1502. """.format(**common_args),
  1503. )
  1504. add_docstr(
  1505. torch.tensor_split,
  1506. r"""
  1507. tensor_split(input, indices_or_sections, dim=0) -> List of Tensors
  1508. Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`,
  1509. along dimension :attr:`dim` according to the indices or number of sections specified
  1510. by :attr:`indices_or_sections`. This function is based on NumPy's
  1511. :func:`numpy.array_split`.
  1512. Args:
  1513. input (Tensor): the tensor to split
  1514. indices_or_sections (Tensor, int or list or tuple of ints):
  1515. If :attr:`indices_or_sections` is an integer ``n`` or a zero dimensional long tensor
  1516. with value ``n``, :attr:`input` is split into ``n`` sections along dimension :attr:`dim`.
  1517. If :attr:`input` is divisible by ``n`` along dimension :attr:`dim`, each
  1518. section will be of equal size, :code:`input.size(dim) / n`. If :attr:`input`
  1519. is not divisible by ``n``, the sizes of the first :code:`int(input.size(dim) % n)`
  1520. sections will have size :code:`int(input.size(dim) / n) + 1`, and the rest will
  1521. have size :code:`int(input.size(dim) / n)`.
  1522. If :attr:`indices_or_sections` is a list or tuple of ints, or a one-dimensional long
  1523. tensor, then :attr:`input` is split along dimension :attr:`dim` at each of the indices
  1524. in the list, tuple or tensor. For instance, :code:`indices_or_sections=[2, 3]` and :code:`dim=0`
  1525. would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and :code:`input[3:]`.
  1526. If :attr:`indices_or_sections` is a tensor, it must be a zero-dimensional or one-dimensional
  1527. long tensor on the CPU.
  1528. dim (int, optional): dimension along which to split the tensor. Default: ``0``
  1529. Example::
  1530. >>> x = torch.arange(8)
  1531. >>> torch.tensor_split(x, 3)
  1532. (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7]))
  1533. >>> x = torch.arange(7)
  1534. >>> torch.tensor_split(x, 3)
  1535. (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6]))
  1536. >>> torch.tensor_split(x, (1, 6))
  1537. (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6]))
  1538. >>> x = torch.arange(14).reshape(2, 7)
  1539. >>> x
  1540. tensor([[ 0, 1, 2, 3, 4, 5, 6],
  1541. [ 7, 8, 9, 10, 11, 12, 13]])
  1542. >>> torch.tensor_split(x, 3, dim=1)
  1543. (tensor([[0, 1, 2],
  1544. [7, 8, 9]]),
  1545. tensor([[ 3, 4],
  1546. [10, 11]]),
  1547. tensor([[ 5, 6],
  1548. [12, 13]]))
  1549. >>> torch.tensor_split(x, (1, 6), dim=1)
  1550. (tensor([[0],
  1551. [7]]),
  1552. tensor([[ 1, 2, 3, 4, 5],
  1553. [ 8, 9, 10, 11, 12]]),
  1554. tensor([[ 6],
  1555. [13]]))
  1556. """,
  1557. )
  1558. add_docstr(
  1559. torch.chunk,
  1560. r"""
  1561. chunk(input: Tensor, chunks: int, dim: int = 0) -> Tuple[Tensor, ...]
  1562. Attempts to split a tensor into the specified number of chunks. Each chunk is a view of
  1563. the input tensor.
  1564. .. note::
  1565. This function may return fewer than the specified number of chunks!
  1566. .. seealso::
  1567. :func:`torch.tensor_split` a function that always returns exactly the specified number of chunks
  1568. If the tensor size along the given dimension :attr:`dim` is divisible by :attr:`chunks`,
  1569. all returned chunks will be the same size.
  1570. If the tensor size along the given dimension :attr:`dim` is not divisible by :attr:`chunks`,
  1571. all returned chunks will be the same size, except the last one.
  1572. If such division is not possible, this function may return fewer
  1573. than the specified number of chunks.
  1574. Arguments:
  1575. input (Tensor): the tensor to split
  1576. chunks (int): number of chunks to return
  1577. dim (int): dimension along which to split the tensor
  1578. Example:
  1579. >>> torch.arange(11).chunk(6)
  1580. (tensor([0, 1]),
  1581. tensor([2, 3]),
  1582. tensor([4, 5]),
  1583. tensor([6, 7]),
  1584. tensor([8, 9]),
  1585. tensor([10]))
  1586. >>> torch.arange(12).chunk(6)
  1587. (tensor([0, 1]),
  1588. tensor([2, 3]),
  1589. tensor([4, 5]),
  1590. tensor([6, 7]),
  1591. tensor([8, 9]),
  1592. tensor([10, 11]))
  1593. >>> torch.arange(13).chunk(6)
  1594. (tensor([0, 1, 2]),
  1595. tensor([3, 4, 5]),
  1596. tensor([6, 7, 8]),
  1597. tensor([ 9, 10, 11]),
  1598. tensor([12]))
  1599. """,
  1600. )
  1601. add_docstr(
  1602. torch.unsafe_chunk,
  1603. r"""
  1604. unsafe_chunk(input, chunks, dim=0) -> List of Tensors
  1605. Works like :func:`torch.chunk` but without enforcing the autograd restrictions
  1606. on inplace modification of the outputs.
  1607. .. warning::
  1608. This function is safe to use as long as only the input, or only the outputs
  1609. are modified inplace after calling this function. It is user's
  1610. responsibility to ensure that is the case. If both the input and one or more
  1611. of the outputs are modified inplace, gradients computed by autograd will be
  1612. silently incorrect.
  1613. """,
  1614. )
  1615. add_docstr(
  1616. torch.unsafe_split,
  1617. r"""
  1618. unsafe_split(tensor, split_size_or_sections, dim=0) -> List of Tensors
  1619. Works like :func:`torch.split` but without enforcing the autograd restrictions
  1620. on inplace modification of the outputs.
  1621. .. warning::
  1622. This function is safe to use as long as only the input, or only the outputs
  1623. are modified inplace after calling this function. It is user's
  1624. responsibility to ensure that is the case. If both the input and one or more
  1625. of the outputs are modified inplace, gradients computed by autograd will be
  1626. silently incorrect.
  1627. """,
  1628. )
  1629. add_docstr(
  1630. torch.hsplit,
  1631. r"""
  1632. hsplit(input, indices_or_sections) -> List of Tensors
  1633. Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors
  1634. horizontally according to :attr:`indices_or_sections`. Each split is a view of
  1635. :attr:`input`.
  1636. If :attr:`input` is one dimensional this is equivalent to calling
  1637. torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is
  1638. zero), and if :attr:`input` has two or more dimensions it's equivalent to calling
  1639. torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1),
  1640. except that if :attr:`indices_or_sections` is an integer it must evenly divide
  1641. the split dimension or a runtime error will be thrown.
  1642. This function is based on NumPy's :func:`numpy.hsplit`.
  1643. Args:
  1644. input (Tensor): tensor to split.
  1645. indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`.
  1646. Example::
  1647. >>> t = torch.arange(16.0).reshape(4,4)
  1648. >>> t
  1649. tensor([[ 0., 1., 2., 3.],
  1650. [ 4., 5., 6., 7.],
  1651. [ 8., 9., 10., 11.],
  1652. [12., 13., 14., 15.]])
  1653. >>> torch.hsplit(t, 2)
  1654. (tensor([[ 0., 1.],
  1655. [ 4., 5.],
  1656. [ 8., 9.],
  1657. [12., 13.]]),
  1658. tensor([[ 2., 3.],
  1659. [ 6., 7.],
  1660. [10., 11.],
  1661. [14., 15.]]))
  1662. >>> torch.hsplit(t, [3, 6])
  1663. (tensor([[ 0., 1., 2.],
  1664. [ 4., 5., 6.],
  1665. [ 8., 9., 10.],
  1666. [12., 13., 14.]]),
  1667. tensor([[ 3.],
  1668. [ 7.],
  1669. [11.],
  1670. [15.]]),
  1671. tensor([], size=(4, 0)))
  1672. """,
  1673. )
  1674. add_docstr(
  1675. torch.vsplit,
  1676. r"""
  1677. vsplit(input, indices_or_sections) -> List of Tensors
  1678. Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors
  1679. vertically according to :attr:`indices_or_sections`. Each split is a view of
  1680. :attr:`input`.
  1681. This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0)
  1682. (the split dimension is 0), except that if :attr:`indices_or_sections` is an integer
  1683. it must evenly divide the split dimension or a runtime error will be thrown.
  1684. This function is based on NumPy's :func:`numpy.vsplit`.
  1685. Args:
  1686. input (Tensor): tensor to split.
  1687. indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`.
  1688. Example::
  1689. >>> t = torch.arange(16.0).reshape(4,4)
  1690. >>> t
  1691. tensor([[ 0., 1., 2., 3.],
  1692. [ 4., 5., 6., 7.],
  1693. [ 8., 9., 10., 11.],
  1694. [12., 13., 14., 15.]])
  1695. >>> torch.vsplit(t, 2)
  1696. (tensor([[0., 1., 2., 3.],
  1697. [4., 5., 6., 7.]]),
  1698. tensor([[ 8., 9., 10., 11.],
  1699. [12., 13., 14., 15.]]))
  1700. >>> torch.vsplit(t, [3, 6])
  1701. (tensor([[ 0., 1., 2., 3.],
  1702. [ 4., 5., 6., 7.],
  1703. [ 8., 9., 10., 11.]]),
  1704. tensor([[12., 13., 14., 15.]]),
  1705. tensor([], size=(0, 4)))
  1706. """,
  1707. )
  1708. add_docstr(
  1709. torch.dsplit,
  1710. r"""
  1711. dsplit(input, indices_or_sections) -> List of Tensors
  1712. Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors
  1713. depthwise according to :attr:`indices_or_sections`. Each split is a view of
  1714. :attr:`input`.
  1715. This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2)
  1716. (the split dimension is 2), except that if :attr:`indices_or_sections` is an integer
  1717. it must evenly divide the split dimension or a runtime error will be thrown.
  1718. This function is based on NumPy's :func:`numpy.dsplit`.
  1719. Args:
  1720. input (Tensor): tensor to split.
  1721. indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`.
  1722. Example::
  1723. >>> t = torch.arange(16.0).reshape(2, 2, 4)
  1724. >>> t
  1725. tensor([[[ 0., 1., 2., 3.],
  1726. [ 4., 5., 6., 7.]],
  1727. [[ 8., 9., 10., 11.],
  1728. [12., 13., 14., 15.]]])
  1729. >>> torch.dsplit(t, 2)
  1730. (tensor([[[ 0., 1.],
  1731. [ 4., 5.]],
  1732. [[ 8., 9.],
  1733. [12., 13.]]]),
  1734. tensor([[[ 2., 3.],
  1735. [ 6., 7.]],
  1736. [[10., 11.],
  1737. [14., 15.]]]))
  1738. >>> torch.dsplit(t, [3, 6])
  1739. (tensor([[[ 0., 1., 2.],
  1740. [ 4., 5., 6.]],
  1741. [[ 8., 9., 10.],
  1742. [12., 13., 14.]]]),
  1743. tensor([[[ 3.],
  1744. [ 7.]],
  1745. [[11.],
  1746. [15.]]]),
  1747. tensor([], size=(2, 2, 0)))
  1748. """,
  1749. )
  1750. add_docstr(
  1751. torch.can_cast,
  1752. r"""
  1753. can_cast(from_, to) -> bool
  1754. Determines if a type conversion is allowed under PyTorch casting rules
  1755. described in the type promotion :ref:`documentation <type-promotion-doc>`.
  1756. Args:
  1757. from\_ (dtype): The original :class:`torch.dtype`.
  1758. to (dtype): The target :class:`torch.dtype`.
  1759. Example::
  1760. >>> torch.can_cast(torch.double, torch.float)
  1761. True
  1762. >>> torch.can_cast(torch.float, torch.int)
  1763. False
  1764. """,
  1765. )
  1766. add_docstr(
  1767. torch.corrcoef,
  1768. r"""
  1769. corrcoef(input) -> Tensor
  1770. Estimates the Pearson product-moment correlation coefficient matrix of the variables given by the :attr:`input` matrix,
  1771. where rows are the variables and columns are the observations.
  1772. .. note::
  1773. The correlation coefficient matrix R is computed using the covariance matrix C as given by
  1774. :math:`R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }`
  1775. .. note::
  1776. Due to floating point rounding, the resulting array may not be Hermitian and its diagonal elements may not be 1.
  1777. The real and imaginary values are clipped to the interval [-1, 1] in an attempt to improve this situation.
  1778. Args:
  1779. input (Tensor): A 2D matrix containing multiple variables and observations, or a
  1780. Scalar or 1D vector representing a single variable.
  1781. Returns:
  1782. (Tensor) The correlation coefficient matrix of the variables.
  1783. .. seealso::
  1784. :func:`torch.cov` covariance matrix.
  1785. Example::
  1786. >>> x = torch.tensor([[0, 1, 2], [2, 1, 0]])
  1787. >>> torch.corrcoef(x)
  1788. tensor([[ 1., -1.],
  1789. [-1., 1.]])
  1790. >>> x = torch.randn(2, 4)
  1791. >>> x
  1792. tensor([[-0.2678, -0.0908, -0.3766, 0.2780],
  1793. [-0.5812, 0.1535, 0.2387, 0.2350]])
  1794. >>> torch.corrcoef(x)
  1795. tensor([[1.0000, 0.3582],
  1796. [0.3582, 1.0000]])
  1797. >>> torch.corrcoef(x[0])
  1798. tensor(1.)
  1799. """,
  1800. )
  1801. add_docstr(
  1802. torch.cov,
  1803. r"""
  1804. cov(input, *, correction=1, fweights=None, aweights=None) -> Tensor
  1805. Estimates the covariance matrix of the variables given by the :attr:`input` matrix, where rows are
  1806. the variables and columns are the observations.
  1807. A covariance matrix is a square matrix giving the covariance of each pair of variables. The diagonal contains
  1808. the variance of each variable (covariance of a variable with itself). By definition, if :attr:`input` represents
  1809. a single variable (Scalar or 1D) then its variance is returned.
  1810. The sample covariance of the variables :math:`x` and :math:`y` is given by:
  1811. .. math::
  1812. \text{cov}(x,y) = \frac{\sum^{N}_{i = 1}(x_{i} - \bar{x})(y_{i} - \bar{y})}{\max(0,~N~-~\delta N)}
  1813. where :math:`\bar{x}` and :math:`\bar{y}` are the simple means of the :math:`x` and :math:`y` respectively, and
  1814. :math:`\delta N` is the :attr:`correction`.
  1815. If :attr:`fweights` and/or :attr:`aweights` are provided, the weighted covariance
  1816. is calculated, which is given by:
  1817. .. math::
  1818. \text{cov}_w(x,y) = \frac{\sum^{N}_{i = 1}w_i(x_{i} - \mu_x^*)(y_{i} - \mu_y^*)}
  1819. {\max(0,~\sum^{N}_{i = 1}w_i~-~\frac{\sum^{N}_{i = 1}w_ia_i}{\sum^{N}_{i = 1}w_i}~\delta N)}
  1820. where :math:`w` denotes :attr:`fweights` or :attr:`aweights` (``f`` and ``a`` for brevity) based on whichever is
  1821. provided, or :math:`w = f \times a` if both are provided, and
  1822. :math:`\mu_x^* = \frac{\sum^{N}_{i = 1}w_ix_{i} }{\sum^{N}_{i = 1}w_i}` is the weighted mean of the variable. If not
  1823. provided, ``f`` and/or ``a`` can be seen as a :math:`\mathbb{1}` vector of appropriate size.
  1824. Args:
  1825. input (Tensor): A 2D matrix containing multiple variables and observations, or a
  1826. Scalar or 1D vector representing a single variable.
  1827. Keyword Args:
  1828. correction (int, optional): difference between the sample size and sample degrees of freedom.
  1829. Defaults to Bessel's correction, ``correction = 1`` which returns the unbiased estimate,
  1830. even if both :attr:`fweights` and :attr:`aweights` are specified. ``correction = 0``
  1831. will return the simple average. Defaults to ``1``.
  1832. fweights (tensor, optional): A Scalar or 1D tensor of observation vector frequencies representing the number of
  1833. times each observation should be repeated. Its numel must equal the number of columns of :attr:`input`.
  1834. Must have integral dtype. Ignored if ``None``. Defaults to ``None``.
  1835. aweights (tensor, optional): A Scalar or 1D array of observation vector weights.
  1836. These relative weights are typically large for observations considered "important" and smaller for
  1837. observations considered less "important". Its numel must equal the number of columns of :attr:`input`.
  1838. Must have floating point dtype. Ignored if ``None``. Defaults to ``None``.
  1839. Returns:
  1840. (Tensor) The covariance matrix of the variables.
  1841. .. seealso::
  1842. :func:`torch.corrcoef` normalized covariance matrix.
  1843. Example::
  1844. >>> x = torch.tensor([[0, 2], [1, 1], [2, 0]]).T
  1845. >>> x
  1846. tensor([[0, 1, 2],
  1847. [2, 1, 0]])
  1848. >>> torch.cov(x)
  1849. tensor([[ 1., -1.],
  1850. [-1., 1.]])
  1851. >>> torch.cov(x, correction=0)
  1852. tensor([[ 0.6667, -0.6667],
  1853. [-0.6667, 0.6667]])
  1854. >>> fw = torch.randint(1, 10, (3,))
  1855. >>> fw
  1856. tensor([1, 6, 9])
  1857. >>> aw = torch.rand(3)
  1858. >>> aw
  1859. tensor([0.4282, 0.0255, 0.4144])
  1860. >>> torch.cov(x, fweights=fw, aweights=aw)
  1861. tensor([[ 0.4169, -0.4169],
  1862. [-0.4169, 0.4169]])
  1863. """,
  1864. )
  1865. add_docstr(
  1866. torch.cat,
  1867. r"""
  1868. cat(tensors, dim=0, *, out=None) -> Tensor
  1869. Concatenates the given sequence of tensors in :attr:`tensors` in the given dimension.
  1870. All tensors must either have the same shape (except in the concatenating
  1871. dimension) or be a 1-D empty tensor with size ``(0,)``.
  1872. :func:`torch.cat` can be seen as an inverse operation for :func:`torch.split`
  1873. and :func:`torch.chunk`.
  1874. :func:`torch.cat` can be best understood via examples.
  1875. .. seealso::
  1876. :func:`torch.stack` concatenates the given sequence along a new dimension.
  1877. Args:
  1878. tensors (sequence of Tensors): Non-empty tensors provided must have the same shape,
  1879. except in the cat dimension.
  1880. dim (int, optional): the dimension over which the tensors are concatenated
  1881. Keyword args:
  1882. {out}
  1883. Example::
  1884. >>> x = torch.randn(2, 3)
  1885. >>> x
  1886. tensor([[ 0.6580, -1.0969, -0.4614],
  1887. [-0.1034, -0.5790, 0.1497]])
  1888. >>> torch.cat((x, x, x), 0)
  1889. tensor([[ 0.6580, -1.0969, -0.4614],
  1890. [-0.1034, -0.5790, 0.1497],
  1891. [ 0.6580, -1.0969, -0.4614],
  1892. [-0.1034, -0.5790, 0.1497],
  1893. [ 0.6580, -1.0969, -0.4614],
  1894. [-0.1034, -0.5790, 0.1497]])
  1895. >>> torch.cat((x, x, x), 1)
  1896. tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580,
  1897. -1.0969, -0.4614],
  1898. [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034,
  1899. -0.5790, 0.1497]])
  1900. """.format(**common_args),
  1901. )
  1902. add_docstr(
  1903. torch.concat,
  1904. r"""
  1905. concat(tensors, dim=0, *, out=None) -> Tensor
  1906. Alias of :func:`torch.cat`.
  1907. """,
  1908. )
  1909. add_docstr(
  1910. torch.concatenate,
  1911. r"""
  1912. concatenate(tensors, axis=0, out=None) -> Tensor
  1913. Alias of :func:`torch.cat`.
  1914. """,
  1915. )
  1916. add_docstr(
  1917. torch.ceil,
  1918. r"""
  1919. ceil(input, *, out=None) -> Tensor
  1920. Returns a new tensor with the ceil of the elements of :attr:`input`,
  1921. the smallest integer greater than or equal to each element.
  1922. For integer inputs, follows the array-api convention of returning a
  1923. copy of the input tensor.
  1924. .. math::
  1925. \text{out}_{i} = \left\lceil \text{input}_{i} \right\rceil
  1926. """
  1927. + r"""
  1928. Args:
  1929. {input}
  1930. Keyword args:
  1931. {out}
  1932. Example::
  1933. >>> a = torch.randn(4)
  1934. >>> a
  1935. tensor([-0.6341, -1.4208, -1.0900, 0.5826])
  1936. >>> torch.ceil(a)
  1937. tensor([-0., -1., -1., 1.])
  1938. """.format(**common_args),
  1939. )
  1940. add_docstr(
  1941. torch.real,
  1942. r"""
  1943. real(input) -> Tensor
  1944. Returns a new tensor containing real values of the :attr:`self` tensor.
  1945. The returned tensor and :attr:`self` share the same underlying storage.
  1946. Args:
  1947. {input}
  1948. Example::
  1949. >>> x=torch.randn(4, dtype=torch.cfloat)
  1950. >>> x
  1951. tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)])
  1952. >>> x.real
  1953. tensor([ 0.3100, -0.5445, -1.6492, -0.0638])
  1954. """.format(**common_args),
  1955. )
  1956. add_docstr(
  1957. torch.imag,
  1958. r"""
  1959. imag(input) -> Tensor
  1960. Returns a new tensor containing imaginary values of the :attr:`self` tensor.
  1961. The returned tensor and :attr:`self` share the same underlying storage.
  1962. .. warning::
  1963. :func:`imag` is only supported for tensors with complex dtypes.
  1964. Args:
  1965. {input}
  1966. Example::
  1967. >>> x=torch.randn(4, dtype=torch.cfloat)
  1968. >>> x
  1969. tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)])
  1970. >>> x.imag
  1971. tensor([ 0.3553, -0.7896, -0.0633, -0.8119])
  1972. """.format(**common_args),
  1973. )
  1974. add_docstr(
  1975. torch.view_as_real,
  1976. r"""
  1977. view_as_real(input) -> Tensor
  1978. Returns a view of :attr:`input` as a real tensor. For an input complex tensor of
  1979. :attr:`size` :math:`m1, m2, \dots, mi`, this function returns a new
  1980. real tensor of size :math:`m1, m2, \dots, mi, 2`, where the last dimension of size 2
  1981. represents the real and imaginary components of complex numbers.
  1982. .. warning::
  1983. :func:`view_as_real` is only supported for tensors with ``complex dtypes``.
  1984. Args:
  1985. {input}
  1986. Example::
  1987. >>> x=torch.randn(4, dtype=torch.cfloat)
  1988. >>> x
  1989. tensor([(0.4737-0.3839j), (-0.2098-0.6699j), (0.3470-0.9451j), (-0.5174-1.3136j)])
  1990. >>> torch.view_as_real(x)
  1991. tensor([[ 0.4737, -0.3839],
  1992. [-0.2098, -0.6699],
  1993. [ 0.3470, -0.9451],
  1994. [-0.5174, -1.3136]])
  1995. """.format(**common_args),
  1996. )
  1997. add_docstr(
  1998. torch.view_as_complex,
  1999. r"""
  2000. view_as_complex(input) -> Tensor
  2001. Returns a view of :attr:`input` as a complex tensor. For an input complex
  2002. tensor of :attr:`size` :math:`m1, m2, \dots, mi, 2`, this function returns a
  2003. new complex tensor of :attr:`size` :math:`m1, m2, \dots, mi` where the last
  2004. dimension of the input tensor is expected to represent the real and imaginary
  2005. components of complex numbers.
  2006. .. warning::
  2007. :func:`view_as_complex` is only supported for tensors with
  2008. :class:`torch.dtype` ``torch.float64`` and ``torch.float32``. The input is
  2009. expected to have the last dimension of :attr:`size` 2. In addition, the
  2010. tensor must have a `stride` of 1 for its last dimension. The strides of all
  2011. other dimensions must be even numbers.
  2012. Args:
  2013. {input}
  2014. Example::
  2015. >>> x=torch.randn(4, 2)
  2016. >>> x
  2017. tensor([[ 1.6116, -0.5772],
  2018. [-1.4606, -0.9120],
  2019. [ 0.0786, -1.7497],
  2020. [-0.6561, -1.6623]])
  2021. >>> torch.view_as_complex(x)
  2022. tensor([(1.6116-0.5772j), (-1.4606-0.9120j), (0.0786-1.7497j), (-0.6561-1.6623j)])
  2023. """.format(**common_args),
  2024. )
  2025. add_docstr(
  2026. torch.reciprocal,
  2027. r"""
  2028. reciprocal(input, *, out=None) -> Tensor
  2029. Returns a new tensor with the reciprocal of the elements of :attr:`input`
  2030. .. math::
  2031. \text{out}_{i} = \frac{1}{\text{input}_{i}}
  2032. .. note::
  2033. Unlike NumPy's reciprocal, torch.reciprocal supports integral inputs. Integral
  2034. inputs to reciprocal are automatically :ref:`promoted <type-promotion-doc>` to
  2035. the default scalar type.
  2036. """
  2037. + r"""
  2038. Args:
  2039. {input}
  2040. Keyword args:
  2041. {out}
  2042. Example::
  2043. >>> a = torch.randn(4)
  2044. >>> a
  2045. tensor([-0.4595, -2.1219, -1.4314, 0.7298])
  2046. >>> torch.reciprocal(a)
  2047. tensor([-2.1763, -0.4713, -0.6986, 1.3702])
  2048. """.format(**common_args),
  2049. )
  2050. add_docstr(
  2051. torch.cholesky,
  2052. r"""
  2053. cholesky(input, upper=False, *, out=None) -> Tensor
  2054. Computes the Cholesky decomposition of a symmetric positive-definite
  2055. matrix :math:`A` or for batches of symmetric positive-definite matrices.
  2056. If :attr:`upper` is ``True``, the returned matrix ``U`` is upper-triangular, and
  2057. the decomposition has the form:
  2058. .. math::
  2059. A = U^TU
  2060. If :attr:`upper` is ``False``, the returned matrix ``L`` is lower-triangular, and
  2061. the decomposition has the form:
  2062. .. math::
  2063. A = LL^T
  2064. If :attr:`upper` is ``True``, and :math:`A` is a batch of symmetric positive-definite
  2065. matrices, then the returned tensor will be composed of upper-triangular Cholesky factors
  2066. of each of the individual matrices. Similarly, when :attr:`upper` is ``False``, the returned
  2067. tensor will be composed of lower-triangular Cholesky factors of each of the individual
  2068. matrices.
  2069. .. warning::
  2070. :func:`torch.cholesky` is deprecated in favor of :func:`torch.linalg.cholesky`
  2071. and will be removed in a future PyTorch release.
  2072. ``L = torch.cholesky(A)`` should be replaced with
  2073. .. code:: python
  2074. L = torch.linalg.cholesky(A)
  2075. ``U = torch.cholesky(A, upper=True)`` should be replaced with
  2076. .. code:: python
  2077. U = torch.linalg.cholesky(A).mH
  2078. This transform will produce equivalent results for all valid (symmetric positive definite) inputs.
  2079. Args:
  2080. input (Tensor): the input tensor :math:`A` of size :math:`(*, n, n)` where `*` is zero or more
  2081. batch dimensions consisting of symmetric positive-definite matrices.
  2082. upper (bool, optional): flag that indicates whether to return a
  2083. upper or lower triangular matrix. Default: ``False``
  2084. Keyword args:
  2085. out (Tensor, optional): the output matrix
  2086. Example::
  2087. >>> a = torch.randn(3, 3)
  2088. >>> a = a @ a.mT + 1e-3 # make symmetric positive-definite
  2089. >>> l = torch.cholesky(a)
  2090. >>> a
  2091. tensor([[ 2.4112, -0.7486, 1.4551],
  2092. [-0.7486, 1.3544, 0.1294],
  2093. [ 1.4551, 0.1294, 1.6724]])
  2094. >>> l
  2095. tensor([[ 1.5528, 0.0000, 0.0000],
  2096. [-0.4821, 1.0592, 0.0000],
  2097. [ 0.9371, 0.5487, 0.7023]])
  2098. >>> l @ l.mT
  2099. tensor([[ 2.4112, -0.7486, 1.4551],
  2100. [-0.7486, 1.3544, 0.1294],
  2101. [ 1.4551, 0.1294, 1.6724]])
  2102. >>> a = torch.randn(3, 2, 2) # Example for batched input
  2103. >>> a = a @ a.mT + 1e-03 # make symmetric positive-definite
  2104. >>> l = torch.cholesky(a)
  2105. >>> z = l @ l.mT
  2106. >>> torch.dist(z, a)
  2107. tensor(2.3842e-07)
  2108. """,
  2109. )
  2110. add_docstr(
  2111. torch.cholesky_solve,
  2112. r"""
  2113. cholesky_solve(B, L, upper=False, *, out=None) -> Tensor
  2114. Computes the solution of a system of linear equations with complex Hermitian
  2115. or real symmetric positive-definite lhs given its Cholesky decomposition.
  2116. Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix,
  2117. and :math:`L` its Cholesky decomposition such that:
  2118. .. math::
  2119. A = LL^{\text{H}}
  2120. where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex,
  2121. and the transpose when :math:`L` is real-valued.
  2122. Returns the solution :math:`X` of the following linear system:
  2123. .. math::
  2124. AX = B
  2125. Supports inputs of float, double, cfloat and cdouble dtypes.
  2126. Also supports batches of matrices, and if :math:`A` or :math:`B` is a batch of matrices
  2127. then the output has the same batch dimensions.
  2128. Args:
  2129. B (Tensor): right-hand side tensor of shape `(*, n, k)`
  2130. where :math:`*` is zero or more batch dimensions
  2131. L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions
  2132. consisting of lower or upper triangular Cholesky decompositions of
  2133. symmetric or Hermitian positive-definite matrices.
  2134. upper (bool, optional): flag that indicates whether :math:`L` is lower triangular
  2135. or upper triangular. Default: ``False``.
  2136. Keyword args:
  2137. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  2138. Example::
  2139. >>> A = torch.randn(3, 3)
  2140. >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix
  2141. >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition
  2142. >>> B = torch.randn(3, 2)
  2143. >>> torch.cholesky_solve(B, L)
  2144. tensor([[ -8.1625, 19.6097],
  2145. [ -5.8398, 14.2387],
  2146. [ -4.3771, 10.4173]])
  2147. >>> A.inverse() @ B
  2148. tensor([[ -8.1626, 19.6097],
  2149. [ -5.8398, 14.2387],
  2150. [ -4.3771, 10.4173]])
  2151. >>> A = torch.randn(3, 2, 2, dtype=torch.complex64)
  2152. >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices
  2153. >>> L = torch.linalg.cholesky(A)
  2154. >>> B = torch.randn(2, 1, dtype=torch.complex64)
  2155. >>> X = torch.cholesky_solve(B, L)
  2156. >>> torch.dist(X, A.inverse() @ B)
  2157. tensor(1.6881e-5)
  2158. """,
  2159. )
  2160. add_docstr(
  2161. torch.cholesky_inverse,
  2162. r"""
  2163. cholesky_inverse(L, upper=False, *, out=None) -> Tensor
  2164. Computes the inverse of a complex Hermitian or real symmetric
  2165. positive-definite matrix given its Cholesky decomposition.
  2166. Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix,
  2167. and :math:`L` its Cholesky decomposition such that:
  2168. .. math::
  2169. A = LL^{\text{H}}
  2170. where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex,
  2171. and the transpose when :math:`L` is real-valued.
  2172. Computes the inverse matrix :math:`A^{-1}`.
  2173. Supports input of float, double, cfloat and cdouble dtypes.
  2174. Also supports batches of matrices, and if :math:`A` is a batch of matrices
  2175. then the output has the same batch dimensions.
  2176. Args:
  2177. L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions
  2178. consisting of lower or upper triangular Cholesky decompositions of
  2179. symmetric or Hermitian positive-definite matrices.
  2180. upper (bool, optional): flag that indicates whether :math:`L` is lower triangular
  2181. or upper triangular. Default: ``False``
  2182. Keyword args:
  2183. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  2184. Example::
  2185. >>> A = torch.randn(3, 3)
  2186. >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix
  2187. >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition
  2188. >>> torch.cholesky_inverse(L)
  2189. tensor([[ 1.9314, 1.2251, -0.0889],
  2190. [ 1.2251, 2.4439, 0.2122],
  2191. [-0.0889, 0.2122, 0.1412]])
  2192. >>> A.inverse()
  2193. tensor([[ 1.9314, 1.2251, -0.0889],
  2194. [ 1.2251, 2.4439, 0.2122],
  2195. [-0.0889, 0.2122, 0.1412]])
  2196. >>> A = torch.randn(3, 2, 2, dtype=torch.complex64)
  2197. >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices
  2198. >>> L = torch.linalg.cholesky(A)
  2199. >>> torch.dist(torch.inverse(A), torch.cholesky_inverse(L))
  2200. tensor(5.6358e-7)
  2201. """,
  2202. )
  2203. add_docstr(
  2204. torch.clone,
  2205. r"""
  2206. clone(input, *, memory_format=torch.preserve_format) -> Tensor
  2207. Returns a copy of :attr:`input`.
  2208. .. note::
  2209. This function is differentiable, so gradients will flow back from the
  2210. result of this operation to :attr:`input`. To create a tensor without an
  2211. autograd relationship to :attr:`input` see :meth:`~Tensor.detach`.
  2212. In addition, when ``torch.preserve_format`` is used:
  2213. If the input tensor is dense (i.e., non-overlapping strided),
  2214. its memory format (including strides) is retained.
  2215. Otherwise (e.g., a non-dense view like a stepped slice),
  2216. the output is converted to the dense (contiguous) format.
  2217. Args:
  2218. {input}
  2219. Keyword args:
  2220. {memory_format}
  2221. """.format(**common_args),
  2222. )
  2223. add_docstr(
  2224. torch.clamp,
  2225. r"""
  2226. clamp(input, min=None, max=None, *, out=None) -> Tensor
  2227. Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`.
  2228. Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns:
  2229. .. math::
  2230. y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i)
  2231. If :attr:`min` is ``None``, there is no lower bound.
  2232. Or, if :attr:`max` is ``None`` there is no upper bound.
  2233. """
  2234. + r"""
  2235. .. note::
  2236. If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) <torch.clamp>`
  2237. sets all elements in :attr:`input` to the value of :attr:`max`.
  2238. Args:
  2239. {input}
  2240. min (Number or Tensor, optional): lower-bound of the range to be clamped to
  2241. max (Number or Tensor, optional): upper-bound of the range to be clamped to
  2242. Keyword args:
  2243. {out}
  2244. Example::
  2245. >>> a = torch.randn(4)
  2246. >>> a
  2247. tensor([-1.7120, 0.1734, -0.0478, -0.0922])
  2248. >>> torch.clamp(a, min=-0.5, max=0.5)
  2249. tensor([-0.5000, 0.1734, -0.0478, -0.0922])
  2250. >>> min = torch.linspace(-1, 1, steps=4)
  2251. >>> torch.clamp(a, min=min)
  2252. tensor([-1.0000, 0.1734, 0.3333, 1.0000])
  2253. """.format(**common_args),
  2254. )
  2255. add_docstr(
  2256. torch.clip,
  2257. r"""
  2258. clip(input, min=None, max=None, *, out=None) -> Tensor
  2259. Alias for :func:`torch.clamp`.
  2260. """,
  2261. )
  2262. add_docstr(
  2263. torch.column_stack,
  2264. r"""
  2265. column_stack(tensors, *, out=None) -> Tensor
  2266. Creates a new tensor by horizontally stacking the tensors in :attr:`tensors`.
  2267. Equivalent to ``torch.hstack(tensors)``, except each zero or one dimensional tensor ``t``
  2268. in :attr:`tensors` is first reshaped into a ``(t.numel(), 1)`` column before being stacked horizontally.
  2269. Args:
  2270. tensors (sequence of Tensors): sequence of tensors to concatenate
  2271. Keyword args:
  2272. {out}
  2273. Example::
  2274. >>> a = torch.tensor([1, 2, 3])
  2275. >>> b = torch.tensor([4, 5, 6])
  2276. >>> torch.column_stack((a, b))
  2277. tensor([[1, 4],
  2278. [2, 5],
  2279. [3, 6]])
  2280. >>> a = torch.arange(5)
  2281. >>> b = torch.arange(10).reshape(5, 2)
  2282. >>> torch.column_stack((a, b, b))
  2283. tensor([[0, 0, 1, 0, 1],
  2284. [1, 2, 3, 2, 3],
  2285. [2, 4, 5, 4, 5],
  2286. [3, 6, 7, 6, 7],
  2287. [4, 8, 9, 8, 9]])
  2288. """.format(**common_args),
  2289. )
  2290. add_docstr(
  2291. torch.complex,
  2292. r"""
  2293. complex(real, imag, *, out=None) -> Tensor
  2294. Constructs a complex tensor with its real part equal to :attr:`real` and its
  2295. imaginary part equal to :attr:`imag`.
  2296. Args:
  2297. real (Tensor): The real part of the complex tensor. Must be half, float or double.
  2298. imag (Tensor): The imaginary part of the complex tensor. Must be same dtype
  2299. as :attr:`real`.
  2300. Keyword args:
  2301. out (Tensor): If the inputs are ``torch.float32``, must be
  2302. ``torch.complex64``. If the inputs are ``torch.float64``, must be
  2303. ``torch.complex128``.
  2304. Example::
  2305. >>> real = torch.tensor([1, 2], dtype=torch.float32)
  2306. >>> imag = torch.tensor([3, 4], dtype=torch.float32)
  2307. >>> z = torch.complex(real, imag)
  2308. >>> z
  2309. tensor([(1.+3.j), (2.+4.j)])
  2310. >>> z.dtype
  2311. torch.complex64
  2312. """,
  2313. )
  2314. add_docstr(
  2315. torch.polar,
  2316. r"""
  2317. polar(abs, angle, *, out=None) -> Tensor
  2318. Constructs a complex tensor whose elements are Cartesian coordinates
  2319. corresponding to the polar coordinates with absolute value :attr:`abs` and angle
  2320. :attr:`angle`.
  2321. .. math::
  2322. \text{out} = \text{abs} \cdot \cos(\text{angle}) + \text{abs} \cdot \sin(\text{angle}) \cdot j
  2323. .. note::
  2324. `torch.polar` is similar to
  2325. `std::polar <https://en.cppreference.com/w/cpp/numeric/complex/polar>`_
  2326. and does not compute the polar decomposition
  2327. of a complex tensor like Python's `cmath.polar` and SciPy's `linalg.polar` do.
  2328. The behavior of this function is undefined if `abs` is negative or NaN, or if `angle` is
  2329. infinite.
  2330. """
  2331. + r"""
  2332. Args:
  2333. abs (Tensor): The absolute value the complex tensor. Must be float or double.
  2334. angle (Tensor): The angle of the complex tensor. Must be same dtype as
  2335. :attr:`abs`.
  2336. Keyword args:
  2337. out (Tensor): If the inputs are ``torch.float32``, must be
  2338. ``torch.complex64``. If the inputs are ``torch.float64``, must be
  2339. ``torch.complex128``.
  2340. Example::
  2341. >>> import numpy as np
  2342. >>> abs = torch.tensor([1, 2], dtype=torch.float64)
  2343. >>> angle = torch.tensor([np.pi / 2, 5 * np.pi / 4], dtype=torch.float64)
  2344. >>> z = torch.polar(abs, angle)
  2345. >>> z
  2346. tensor([(0.0000+1.0000j), (-1.4142-1.4142j)], dtype=torch.complex128)
  2347. """,
  2348. )
  2349. add_docstr(
  2350. torch.conj_physical,
  2351. r"""
  2352. conj_physical(input, *, out=None) -> Tensor
  2353. Computes the element-wise conjugate of the given :attr:`input` tensor.
  2354. If :attr:`input` has a non-complex dtype, this function just returns :attr:`input`.
  2355. .. note::
  2356. This performs the conjugate operation regardless of the fact conjugate bit is set or not.
  2357. .. warning:: In the future, :func:`torch.conj_physical` may return a non-writeable view for an :attr:`input` of
  2358. non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical`
  2359. when :attr:`input` is of non-complex dtype to be compatible with this change.
  2360. .. math::
  2361. \text{out}_{i} = conj(\text{input}_{i})
  2362. """
  2363. + r"""
  2364. Args:
  2365. {input}
  2366. Keyword args:
  2367. {out}
  2368. Example::
  2369. >>> torch.conj_physical(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))
  2370. tensor([-1 - 1j, -2 - 2j, 3 + 3j])
  2371. """.format(**common_args),
  2372. )
  2373. add_docstr(
  2374. torch.conj,
  2375. r"""
  2376. conj(input) -> Tensor
  2377. Returns a view of :attr:`input` with a flipped conjugate bit. If :attr:`input` has a non-complex dtype,
  2378. this function just returns :attr:`input`.
  2379. .. note::
  2380. :func:`torch.conj` performs a lazy conjugation, but the actual conjugated tensor can be materialized
  2381. at any time using :func:`torch.resolve_conj`.
  2382. .. warning:: In the future, :func:`torch.conj` may return a non-writeable view for an :attr:`input` of
  2383. non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical`
  2384. when :attr:`input` is of non-complex dtype to be compatible with this change.
  2385. Args:
  2386. {input}
  2387. Example::
  2388. >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j])
  2389. >>> x.is_conj()
  2390. False
  2391. >>> y = torch.conj(x)
  2392. >>> y.is_conj()
  2393. True
  2394. """.format(**common_args),
  2395. )
  2396. add_docstr(
  2397. torch.resolve_conj,
  2398. r"""
  2399. resolve_conj(input) -> Tensor
  2400. Returns a new tensor with materialized conjugation if :attr:`input`'s conjugate bit is set to `True`,
  2401. else returns :attr:`input`. The output tensor will always have its conjugate bit set to `False`.
  2402. Args:
  2403. {input}
  2404. Example::
  2405. >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j])
  2406. >>> y = x.conj()
  2407. >>> y.is_conj()
  2408. True
  2409. >>> z = y.resolve_conj()
  2410. >>> z
  2411. tensor([-1 - 1j, -2 - 2j, 3 + 3j])
  2412. >>> z.is_conj()
  2413. False
  2414. """.format(**common_args),
  2415. )
  2416. add_docstr(
  2417. torch.resolve_neg,
  2418. r"""
  2419. resolve_neg(input) -> Tensor
  2420. Returns a new tensor with materialized negation if :attr:`input`'s negative bit is set to `True`,
  2421. else returns :attr:`input`. The output tensor will always have its negative bit set to `False`.
  2422. Args:
  2423. {input}
  2424. Example::
  2425. >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j])
  2426. >>> y = x.conj()
  2427. >>> z = y.imag
  2428. >>> z.is_neg()
  2429. True
  2430. >>> out = z.resolve_neg()
  2431. >>> out
  2432. tensor([-1., -2., 3.])
  2433. >>> out.is_neg()
  2434. False
  2435. """.format(**common_args),
  2436. )
  2437. add_docstr(
  2438. torch.copysign,
  2439. r"""
  2440. copysign(input, other, *, out=None) -> Tensor
  2441. Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise.
  2442. .. math::
  2443. \text{out}_{i} = \begin{cases}
  2444. -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\
  2445. |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\
  2446. \end{cases}
  2447. """
  2448. + r"""
  2449. Supports :ref:`broadcasting to a common shape <broadcasting-semantics>`,
  2450. and integer and float inputs.
  2451. Args:
  2452. input (Tensor): magnitudes.
  2453. other (Tensor or Number): contains value(s) whose signbit(s) are
  2454. applied to the magnitudes in :attr:`input`.
  2455. Keyword args:
  2456. {out}
  2457. Example::
  2458. >>> a = torch.randn(5)
  2459. >>> a
  2460. tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244])
  2461. >>> torch.copysign(a, 1)
  2462. tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244])
  2463. >>> a = torch.randn(4, 4)
  2464. >>> a
  2465. tensor([[ 0.7079, 0.2778, -1.0249, 0.5719],
  2466. [-0.0059, -0.2600, -0.4475, -1.3948],
  2467. [ 0.3667, -0.9567, -2.5757, -0.1751],
  2468. [ 0.2046, -0.0742, 0.2998, -0.1054]])
  2469. >>> b = torch.randn(4)
  2470. tensor([ 0.2373, 0.3120, 0.3190, -1.1128])
  2471. >>> torch.copysign(a, b)
  2472. tensor([[ 0.7079, 0.2778, 1.0249, -0.5719],
  2473. [ 0.0059, 0.2600, 0.4475, -1.3948],
  2474. [ 0.3667, 0.9567, 2.5757, -0.1751],
  2475. [ 0.2046, 0.0742, 0.2998, -0.1054]])
  2476. >>> a = torch.tensor([1.])
  2477. >>> b = torch.tensor([-0.])
  2478. >>> torch.copysign(a, b)
  2479. tensor([-1.])
  2480. .. note::
  2481. copysign handles signed zeros. If the other argument has a negative zero (-0),
  2482. the corresponding output value will be negative.
  2483. """.format(**common_args),
  2484. )
  2485. add_docstr(
  2486. torch.cos,
  2487. r"""
  2488. cos(input, *, out=None) -> Tensor
  2489. Returns a new tensor with the cosine of the elements of :attr:`input` given in radians.
  2490. .. math::
  2491. \text{out}_{i} = \cos(\text{input}_{i})
  2492. """
  2493. + r"""
  2494. Args:
  2495. {input}
  2496. Keyword args:
  2497. {out}
  2498. Example::
  2499. >>> a = torch.randn(4)
  2500. >>> a
  2501. tensor([ 1.4309, 1.2706, -0.8562, 0.9796])
  2502. >>> torch.cos(a)
  2503. tensor([ 0.1395, 0.2957, 0.6553, 0.5574])
  2504. """.format(**common_args),
  2505. )
  2506. add_docstr(
  2507. torch.cosh,
  2508. r"""
  2509. cosh(input, *, out=None) -> Tensor
  2510. Returns a new tensor with the hyperbolic cosine of the elements of
  2511. :attr:`input`.
  2512. .. math::
  2513. \text{out}_{i} = \cosh(\text{input}_{i})
  2514. """
  2515. + r"""
  2516. Args:
  2517. {input}
  2518. Keyword args:
  2519. {out}
  2520. Example::
  2521. >>> a = torch.randn(4)
  2522. >>> a
  2523. tensor([ 0.1632, 1.1835, -0.6979, -0.7325])
  2524. >>> torch.cosh(a)
  2525. tensor([ 1.0133, 1.7860, 1.2536, 1.2805])
  2526. .. note::
  2527. When :attr:`input` is on the CPU, the implementation of torch.cosh may use
  2528. the Sleef library, which rounds very large results to infinity or negative
  2529. infinity. See `here <https://sleef.org/purec.xhtml>`_ for details.
  2530. """.format(**common_args),
  2531. )
  2532. add_docstr(
  2533. torch.cross,
  2534. r"""
  2535. cross(input, other, dim=None, *, out=None) -> Tensor
  2536. Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input`
  2537. and :attr:`other`.
  2538. Supports input of float, double, cfloat and cdouble dtypes. Also supports batches
  2539. of vectors, for which it computes the product along the dimension :attr:`dim`.
  2540. In this case, the output has the same batch dimensions as the inputs.
  2541. .. warning::
  2542. If :attr:`dim` is not given, it defaults to the first dimension found
  2543. with the size 3. Note that this might be unexpected.
  2544. This behavior is deprecated and will be changed to match that of :func:`torch.linalg.cross`
  2545. in a future release.
  2546. .. seealso::
  2547. :func:`torch.linalg.cross` which has dim=-1 as default.
  2548. Args:
  2549. {input}
  2550. other (Tensor): the second input tensor
  2551. dim (int, optional): the dimension to take the cross-product in.
  2552. Keyword args:
  2553. {out}
  2554. Example::
  2555. >>> a = torch.randn(4, 3)
  2556. >>> a
  2557. tensor([[-0.3956, 1.1455, 1.6895],
  2558. [-0.5849, 1.3672, 0.3599],
  2559. [-1.1626, 0.7180, -0.0521],
  2560. [-0.1339, 0.9902, -2.0225]])
  2561. >>> b = torch.randn(4, 3)
  2562. >>> b
  2563. tensor([[-0.0257, -1.4725, -1.2251],
  2564. [-1.1479, -0.7005, -1.9757],
  2565. [-1.3904, 0.3726, -1.1836],
  2566. [-0.9688, -0.7153, 0.2159]])
  2567. >>> torch.cross(a, b, dim=1)
  2568. tensor([[ 1.0844, -0.5281, 0.6120],
  2569. [-2.4490, -1.5687, 1.9792],
  2570. [-0.8304, -1.3037, 0.5650],
  2571. [-1.2329, 1.9883, 1.0551]])
  2572. >>> torch.cross(a, b)
  2573. tensor([[ 1.0844, -0.5281, 0.6120],
  2574. [-2.4490, -1.5687, 1.9792],
  2575. [-0.8304, -1.3037, 0.5650],
  2576. [-1.2329, 1.9883, 1.0551]])
  2577. """.format(**common_args),
  2578. )
  2579. add_docstr(
  2580. torch.logcumsumexp,
  2581. r"""
  2582. logcumsumexp(input, dim, *, out=None) -> Tensor
  2583. Returns the logarithm of the cumulative summation of the exponentiation of
  2584. elements of :attr:`input` in the dimension :attr:`dim`.
  2585. For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is
  2586. .. math::
  2587. \text{{logcumsumexp}}(x)_{{ij}} = \log \sum\limits_{{k=0}}^{{j}} \exp(x_{{ik}})
  2588. Args:
  2589. {input}
  2590. dim (int): the dimension to do the operation over
  2591. Keyword args:
  2592. {out}
  2593. Example::
  2594. >>> a = torch.randn(10)
  2595. >>> torch.logcumsumexp(a, dim=0)
  2596. tensor([-0.42296738, -0.04462666, 0.86278635, 0.94622083, 1.05277811,
  2597. 1.39202815, 1.83525007, 1.84492621, 2.06084887, 2.06844475]))
  2598. """.format(**reduceops_common_args),
  2599. )
  2600. add_docstr(
  2601. torch.cummax,
  2602. r"""
  2603. cummax(input, dim, *, out=None) -> (Tensor, LongTensor)
  2604. Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative maximum of
  2605. elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index
  2606. location of each maximum value found in the dimension :attr:`dim`.
  2607. .. math::
  2608. y_i = max(x_1, x_2, x_3, \dots, x_i)
  2609. Args:
  2610. {input}
  2611. dim (int): the dimension to do the operation over
  2612. Keyword args:
  2613. out (tuple, optional): the result tuple of two output tensors (values, indices)
  2614. Example::
  2615. >>> a = torch.randn(10)
  2616. >>> a
  2617. tensor([-0.3449, -1.5447, 0.0685, -1.5104, -1.1706, 0.2259, 1.4696, -1.3284,
  2618. 1.9946, -0.8209])
  2619. >>> torch.cummax(a, dim=0)
  2620. torch.return_types.cummax(
  2621. values=tensor([-0.3449, -0.3449, 0.0685, 0.0685, 0.0685, 0.2259, 1.4696, 1.4696,
  2622. 1.9946, 1.9946]),
  2623. indices=tensor([0, 0, 2, 2, 2, 5, 6, 6, 8, 8]))
  2624. """.format(**reduceops_common_args),
  2625. )
  2626. add_docstr(
  2627. torch.cummin,
  2628. r"""
  2629. cummin(input, dim, *, out=None) -> (Tensor, LongTensor)
  2630. Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative minimum of
  2631. elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index
  2632. location of each maximum value found in the dimension :attr:`dim`.
  2633. .. math::
  2634. y_i = min(x_1, x_2, x_3, \dots, x_i)
  2635. Args:
  2636. {input}
  2637. dim (int): the dimension to do the operation over
  2638. Keyword args:
  2639. out (tuple, optional): the result tuple of two output tensors (values, indices)
  2640. Example::
  2641. >>> a = torch.randn(10)
  2642. >>> a
  2643. tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762,
  2644. 0.9165, 1.6684])
  2645. >>> torch.cummin(a, dim=0)
  2646. torch.return_types.cummin(
  2647. values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298,
  2648. -1.3298, -1.3298]),
  2649. indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4]))
  2650. """.format(**reduceops_common_args),
  2651. )
  2652. add_docstr(
  2653. torch.cumprod,
  2654. r"""
  2655. cumprod(input, dim, *, dtype=None, out=None) -> Tensor
  2656. Returns the cumulative product of elements of :attr:`input` in the dimension
  2657. :attr:`dim`.
  2658. For example, if :attr:`input` is a vector of size N, the result will also be
  2659. a vector of size N, with elements.
  2660. .. math::
  2661. y_i = x_1 \times x_2\times x_3\times \dots \times x_i
  2662. Args:
  2663. {input}
  2664. dim (int): the dimension to do the operation over
  2665. Keyword args:
  2666. {dtype}
  2667. {out}
  2668. Example::
  2669. >>> a = torch.randn(10)
  2670. >>> a
  2671. tensor([ 0.6001, 0.2069, -0.1919, 0.9792, 0.6727, 1.0062, 0.4126,
  2672. -0.2129, -0.4206, 0.1968])
  2673. >>> torch.cumprod(a, dim=0)
  2674. tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0158, -0.0065,
  2675. 0.0014, -0.0006, -0.0001])
  2676. >>> a[5] = 0.0
  2677. >>> torch.cumprod(a, dim=0)
  2678. tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0000, -0.0000,
  2679. 0.0000, -0.0000, -0.0000])
  2680. """.format(**reduceops_common_args),
  2681. )
  2682. add_docstr(
  2683. torch.cumsum,
  2684. r"""
  2685. cumsum(input, dim, *, dtype=None, out=None) -> Tensor
  2686. Returns the cumulative sum of elements of :attr:`input` in the dimension
  2687. :attr:`dim`.
  2688. For example, if :attr:`input` is a vector of size N, the result will also be
  2689. a vector of size N, with elements.
  2690. .. math::
  2691. y_i = x_1 + x_2 + x_3 + \dots + x_i
  2692. Args:
  2693. {input}
  2694. dim (int): the dimension to do the operation over
  2695. Keyword args:
  2696. {dtype}
  2697. {out}
  2698. Example::
  2699. >>> a = torch.randint(1, 20, (10,))
  2700. >>> a
  2701. tensor([13, 7, 3, 10, 13, 3, 15, 10, 9, 10])
  2702. >>> torch.cumsum(a, dim=0)
  2703. tensor([13, 20, 23, 33, 46, 49, 64, 74, 83, 93])
  2704. """.format(**reduceops_common_args),
  2705. )
  2706. add_docstr(
  2707. torch.count_nonzero,
  2708. r"""
  2709. count_nonzero(input, dim=None) -> Tensor
  2710. Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`.
  2711. If no dim is specified then all non-zeros in the tensor are counted.
  2712. Args:
  2713. {input}
  2714. dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros.
  2715. Example::
  2716. >>> x = torch.zeros(3,3)
  2717. >>> x[torch.randn(3,3) > 0.5] = 1
  2718. >>> x
  2719. tensor([[0., 1., 1.],
  2720. [0., 0., 0.],
  2721. [0., 0., 1.]])
  2722. >>> torch.count_nonzero(x)
  2723. tensor(3)
  2724. >>> torch.count_nonzero(x, dim=0)
  2725. tensor([0, 1, 2])
  2726. """.format(**reduceops_common_args),
  2727. )
  2728. add_docstr(
  2729. torch.dequantize,
  2730. r"""
  2731. dequantize(tensor) -> Tensor
  2732. Returns an fp32 Tensor by dequantizing a quantized Tensor
  2733. Args:
  2734. tensor (Tensor): A quantized Tensor
  2735. .. function:: dequantize(tensors) -> sequence of Tensors
  2736. :noindex:
  2737. Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors
  2738. Args:
  2739. tensors (sequence of Tensors): A list of quantized Tensors
  2740. """,
  2741. )
  2742. add_docstr(
  2743. torch.diag,
  2744. r"""
  2745. diag(input, diagonal=0, *, out=None) -> Tensor
  2746. - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor
  2747. with the elements of :attr:`input` as the diagonal.
  2748. - If :attr:`input` is a matrix (2-D tensor), then returns a 1-D tensor with
  2749. the diagonal elements of :attr:`input`.
  2750. The argument :attr:`diagonal` controls which diagonal to consider:
  2751. - If :attr:`diagonal` = 0, it is the main diagonal.
  2752. - If :attr:`diagonal` > 0, it is above the main diagonal.
  2753. - If :attr:`diagonal` < 0, it is below the main diagonal.
  2754. Args:
  2755. {input}
  2756. diagonal (int, optional): the diagonal to consider
  2757. Keyword args:
  2758. {out}
  2759. .. seealso::
  2760. :func:`torch.diagonal` always returns the diagonal of its input.
  2761. :func:`torch.diagflat` always constructs a tensor with diagonal elements
  2762. specified by the input.
  2763. Examples:
  2764. Get the square matrix where the input vector is the diagonal::
  2765. >>> a = torch.randn(3)
  2766. >>> a
  2767. tensor([ 0.5950,-0.0872, 2.3298])
  2768. >>> torch.diag(a)
  2769. tensor([[ 0.5950, 0.0000, 0.0000],
  2770. [ 0.0000,-0.0872, 0.0000],
  2771. [ 0.0000, 0.0000, 2.3298]])
  2772. >>> torch.diag(a, 1)
  2773. tensor([[ 0.0000, 0.5950, 0.0000, 0.0000],
  2774. [ 0.0000, 0.0000,-0.0872, 0.0000],
  2775. [ 0.0000, 0.0000, 0.0000, 2.3298],
  2776. [ 0.0000, 0.0000, 0.0000, 0.0000]])
  2777. Get the k-th diagonal of a given matrix::
  2778. >>> a = torch.randn(3, 3)
  2779. >>> a
  2780. tensor([[-0.4264, 0.0255,-0.1064],
  2781. [ 0.8795,-0.2429, 0.1374],
  2782. [ 0.1029,-0.6482,-1.6300]])
  2783. >>> torch.diag(a, 0)
  2784. tensor([-0.4264,-0.2429,-1.6300])
  2785. >>> torch.diag(a, 1)
  2786. tensor([ 0.0255, 0.1374])
  2787. """.format(**common_args),
  2788. )
  2789. add_docstr(
  2790. torch.diag_embed,
  2791. r"""
  2792. diag_embed(input, offset=0, dim1=-2, dim2=-1) -> Tensor
  2793. Creates a tensor whose diagonals of certain 2D planes (specified by
  2794. :attr:`dim1` and :attr:`dim2`) are filled by :attr:`input`.
  2795. To facilitate creating batched diagonal matrices, the 2D planes formed by
  2796. the last two dimensions of the returned tensor are chosen by default.
  2797. The argument :attr:`offset` controls which diagonal to consider:
  2798. - If :attr:`offset` = 0, it is the main diagonal.
  2799. - If :attr:`offset` > 0, it is above the main diagonal.
  2800. - If :attr:`offset` < 0, it is below the main diagonal.
  2801. The size of the new matrix will be calculated to make the specified diagonal
  2802. of the size of the last input dimension.
  2803. Note that for :attr:`offset` other than :math:`0`, the order of :attr:`dim1`
  2804. and :attr:`dim2` matters. Exchanging them is equivalent to changing the
  2805. sign of :attr:`offset`.
  2806. Applying :meth:`torch.diagonal` to the output of this function with
  2807. the same arguments yields a matrix identical to input. However,
  2808. :meth:`torch.diagonal` has different default dimensions, so those
  2809. need to be explicitly specified.
  2810. Args:
  2811. {input} Must be at least 1-dimensional.
  2812. offset (int, optional): which diagonal to consider. Default: 0
  2813. (main diagonal).
  2814. dim1 (int, optional): first dimension with respect to which to
  2815. take diagonal. Default: -2.
  2816. dim2 (int, optional): second dimension with respect to which to
  2817. take diagonal. Default: -1.
  2818. Example::
  2819. >>> a = torch.randn(2, 3)
  2820. >>> torch.diag_embed(a)
  2821. tensor([[[ 1.5410, 0.0000, 0.0000],
  2822. [ 0.0000, -0.2934, 0.0000],
  2823. [ 0.0000, 0.0000, -2.1788]],
  2824. [[ 0.5684, 0.0000, 0.0000],
  2825. [ 0.0000, -1.0845, 0.0000],
  2826. [ 0.0000, 0.0000, -1.3986]]])
  2827. >>> torch.diag_embed(a, offset=1, dim1=0, dim2=2)
  2828. tensor([[[ 0.0000, 1.5410, 0.0000, 0.0000],
  2829. [ 0.0000, 0.5684, 0.0000, 0.0000]],
  2830. [[ 0.0000, 0.0000, -0.2934, 0.0000],
  2831. [ 0.0000, 0.0000, -1.0845, 0.0000]],
  2832. [[ 0.0000, 0.0000, 0.0000, -2.1788],
  2833. [ 0.0000, 0.0000, 0.0000, -1.3986]],
  2834. [[ 0.0000, 0.0000, 0.0000, 0.0000],
  2835. [ 0.0000, 0.0000, 0.0000, 0.0000]]])
  2836. """.format(**common_args),
  2837. )
  2838. add_docstr(
  2839. torch.diagflat,
  2840. r"""
  2841. diagflat(input, offset=0) -> Tensor
  2842. - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor
  2843. with the elements of :attr:`input` as the diagonal.
  2844. - If :attr:`input` is a tensor with more than one dimension, then returns a
  2845. 2-D tensor with diagonal elements equal to a flattened :attr:`input`.
  2846. The argument :attr:`offset` controls which diagonal to consider:
  2847. - If :attr:`offset` = 0, it is the main diagonal.
  2848. - If :attr:`offset` > 0, it is above the main diagonal.
  2849. - If :attr:`offset` < 0, it is below the main diagonal.
  2850. Args:
  2851. {input}
  2852. offset (int, optional): the diagonal to consider. Default: 0 (main
  2853. diagonal).
  2854. Examples::
  2855. >>> a = torch.randn(3)
  2856. >>> a
  2857. tensor([-0.2956, -0.9068, 0.1695])
  2858. >>> torch.diagflat(a)
  2859. tensor([[-0.2956, 0.0000, 0.0000],
  2860. [ 0.0000, -0.9068, 0.0000],
  2861. [ 0.0000, 0.0000, 0.1695]])
  2862. >>> torch.diagflat(a, 1)
  2863. tensor([[ 0.0000, -0.2956, 0.0000, 0.0000],
  2864. [ 0.0000, 0.0000, -0.9068, 0.0000],
  2865. [ 0.0000, 0.0000, 0.0000, 0.1695],
  2866. [ 0.0000, 0.0000, 0.0000, 0.0000]])
  2867. >>> a = torch.randn(2, 2)
  2868. >>> a
  2869. tensor([[ 0.2094, -0.3018],
  2870. [-0.1516, 1.9342]])
  2871. >>> torch.diagflat(a)
  2872. tensor([[ 0.2094, 0.0000, 0.0000, 0.0000],
  2873. [ 0.0000, -0.3018, 0.0000, 0.0000],
  2874. [ 0.0000, 0.0000, -0.1516, 0.0000],
  2875. [ 0.0000, 0.0000, 0.0000, 1.9342]])
  2876. """.format(**common_args),
  2877. )
  2878. add_docstr(
  2879. torch.diagonal,
  2880. r"""
  2881. diagonal(input, offset=0, dim1=0, dim2=1) -> Tensor
  2882. Returns a partial view of :attr:`input` with the its diagonal elements
  2883. with respect to :attr:`dim1` and :attr:`dim2` appended as a dimension
  2884. at the end of the shape.
  2885. The argument :attr:`offset` controls which diagonal to consider:
  2886. - If :attr:`offset` = 0, it is the main diagonal.
  2887. - If :attr:`offset` > 0, it is above the main diagonal.
  2888. - If :attr:`offset` < 0, it is below the main diagonal.
  2889. Applying :meth:`torch.diag_embed` to the output of this function with
  2890. the same arguments yields a diagonal matrix with the diagonal entries
  2891. of the input. However, :meth:`torch.diag_embed` has different default
  2892. dimensions, so those need to be explicitly specified.
  2893. Args:
  2894. {input} Must be at least 2-dimensional.
  2895. offset (int, optional): which diagonal to consider. Default: 0
  2896. (main diagonal).
  2897. dim1 (int, optional): first dimension with respect to which to
  2898. take diagonal. Default: 0.
  2899. dim2 (int, optional): second dimension with respect to which to
  2900. take diagonal. Default: 1.
  2901. .. note:: To take a batch diagonal, pass in dim1=-2, dim2=-1.
  2902. Examples::
  2903. >>> a = torch.randn(3, 3)
  2904. >>> a
  2905. tensor([[-1.0854, 1.1431, -0.1752],
  2906. [ 0.8536, -0.0905, 0.0360],
  2907. [ 0.6927, -0.3735, -0.4945]])
  2908. >>> torch.diagonal(a)
  2909. tensor([-1.0854, -0.0905, -0.4945])
  2910. >>> torch.diagonal(a, 1)
  2911. tensor([ 1.1431, 0.0360])
  2912. >>> b = torch.randn(2, 5)
  2913. >>> b
  2914. tensor([[-1.7948, -1.2731, -0.3181, 2.0200, -1.6745],
  2915. [ 1.8262, -1.5049, 0.4114, 1.0704, -1.2607]])
  2916. >>> torch.diagonal(b, 1, 1, 0)
  2917. tensor([1.8262])
  2918. >>> x = torch.randn(2, 5, 4, 2)
  2919. >>> torch.diagonal(x, offset=-1, dim1=1, dim2=2)
  2920. tensor([[[-1.2631, 0.3755, -1.5977, -1.8172],
  2921. [-1.1065, 1.0401, -0.2235, -0.7938]],
  2922. [[-1.7325, -0.3081, 0.6166, 0.2335],
  2923. [ 1.0500, 0.7336, -0.3836, -1.1015]]])
  2924. """.format(**common_args),
  2925. )
  2926. add_docstr(
  2927. torch.diagonal_scatter,
  2928. r"""
  2929. diagonal_scatter(input, src, offset=0, dim1=0, dim2=1) -> Tensor
  2930. Embeds the values of the :attr:`src` tensor into :attr:`input` along
  2931. the diagonal elements of :attr:`input`, with respect to :attr:`dim1`
  2932. and :attr:`dim2`.
  2933. This function returns a tensor with fresh storage; it does not
  2934. return a view.
  2935. The argument :attr:`offset` controls which diagonal to consider:
  2936. - If :attr:`offset` = 0, it is the main diagonal.
  2937. - If :attr:`offset` > 0, it is above the main diagonal.
  2938. - If :attr:`offset` < 0, it is below the main diagonal.
  2939. Args:
  2940. {input} Must be at least 2-dimensional.
  2941. src (Tensor): the tensor to embed into :attr:`input`.
  2942. offset (int, optional): which diagonal to consider. Default: 0
  2943. (main diagonal).
  2944. dim1 (int, optional): first dimension with respect to which to
  2945. take diagonal. Default: 0.
  2946. dim2 (int, optional): second dimension with respect to which to
  2947. take diagonal. Default: 1.
  2948. .. note::
  2949. :attr:`src` must be of the proper size in order to be embedded
  2950. into :attr:`input`. Specifically, it should have the same shape as
  2951. ``torch.diagonal(input, offset, dim1, dim2)``
  2952. Examples::
  2953. >>> a = torch.zeros(3, 3)
  2954. >>> a
  2955. tensor([[0., 0., 0.],
  2956. [0., 0., 0.],
  2957. [0., 0., 0.]])
  2958. >>> torch.diagonal_scatter(a, torch.ones(3), 0)
  2959. tensor([[1., 0., 0.],
  2960. [0., 1., 0.],
  2961. [0., 0., 1.]])
  2962. >>> torch.diagonal_scatter(a, torch.ones(2), 1)
  2963. tensor([[0., 1., 0.],
  2964. [0., 0., 1.],
  2965. [0., 0., 0.]])
  2966. """.format(**common_args),
  2967. )
  2968. add_docstr(
  2969. torch.as_strided_scatter,
  2970. r"""
  2971. as_strided_scatter(input, src, size, stride, storage_offset=None) -> Tensor
  2972. Embeds the values of the :attr:`src` tensor into :attr:`input` along
  2973. the elements corresponding to the result of calling
  2974. input.as_strided(size, stride, storage_offset).
  2975. This function returns a tensor with fresh storage; it does not
  2976. return a view.
  2977. Args:
  2978. {input}
  2979. size (tuple or ints): the shape of the output tensor
  2980. stride (tuple or ints): the stride of the output tensor
  2981. storage_offset (int, optional): the offset in the underlying storage of the output tensor
  2982. .. note::
  2983. :attr:`src` must be of the proper size in order to be embedded
  2984. into :attr:`input`. Specifically, it should have the same shape as
  2985. `torch.as_strided(input, size, stride, storage_offset)`
  2986. Example::
  2987. >>> a = torch.arange(4).reshape(2, 2) + 1
  2988. >>> a
  2989. tensor([[1, 2],
  2990. [3, 4]])
  2991. >>> b = torch.zeros(3, 3)
  2992. >>> b
  2993. tensor([[0., 0., 0.],
  2994. [0., 0., 0.],
  2995. [0., 0., 0.]])
  2996. >>> torch.as_strided_scatter(b, a, (2, 2), (1, 2))
  2997. tensor([[1., 3., 2.],
  2998. [4., 0., 0.],
  2999. [0., 0., 0.]])
  3000. """.format(**common_args),
  3001. )
  3002. add_docstr(
  3003. torch.diff,
  3004. r"""
  3005. diff(input, n=1, dim=-1, prepend=None, append=None) -> Tensor
  3006. Computes the n-th forward difference along the given dimension.
  3007. The first-order differences are given by `out[i] = input[i + 1] - input[i]`. Higher-order
  3008. differences are calculated by using :func:`torch.diff` recursively.
  3009. Args:
  3010. input (Tensor): the tensor to compute the differences on
  3011. n (int, optional): the number of times to recursively compute the difference
  3012. dim (int, optional): the dimension to compute the difference along.
  3013. Default is the last dimension.
  3014. prepend, append (Tensor, optional): values to prepend or append to
  3015. :attr:`input` along :attr:`dim` before computing the difference.
  3016. Their dimensions must be equivalent to that of input, and their shapes
  3017. must match input's shape except on :attr:`dim`.
  3018. Keyword args:
  3019. {out}
  3020. Example::
  3021. >>> a = torch.tensor([1, 3, 2])
  3022. >>> torch.diff(a)
  3023. tensor([ 2, -1])
  3024. >>> b = torch.tensor([4, 5])
  3025. >>> torch.diff(a, append=b)
  3026. tensor([ 2, -1, 2, 1])
  3027. >>> c = torch.tensor([[1, 2, 3], [3, 4, 5]])
  3028. >>> torch.diff(c, dim=0)
  3029. tensor([[2, 2, 2]])
  3030. >>> torch.diff(c, dim=1)
  3031. tensor([[1, 1],
  3032. [1, 1]])
  3033. """.format(**common_args),
  3034. )
  3035. add_docstr(
  3036. torch.digamma,
  3037. r"""
  3038. digamma(input, *, out=None) -> Tensor
  3039. Alias for :func:`torch.special.digamma`.
  3040. """,
  3041. )
  3042. add_docstr(
  3043. torch.dist,
  3044. r"""
  3045. dist(input, other, p=2) -> Tensor
  3046. Returns the p-norm of (:attr:`input` - :attr:`other`)
  3047. The shapes of :attr:`input` and :attr:`other` must be
  3048. :ref:`broadcastable <broadcasting-semantics>`.
  3049. Args:
  3050. {input}
  3051. other (Tensor): the Right-hand-side input tensor
  3052. p (float, optional): the norm to be computed
  3053. Example::
  3054. >>> x = torch.randn(4)
  3055. >>> x
  3056. tensor([-1.5393, -0.8675, 0.5916, 1.6321])
  3057. >>> y = torch.randn(4)
  3058. >>> y
  3059. tensor([ 0.0967, -1.0511, 0.6295, 0.8360])
  3060. >>> torch.dist(x, y, 3.5)
  3061. tensor(1.6727)
  3062. >>> torch.dist(x, y, 3)
  3063. tensor(1.6973)
  3064. >>> torch.dist(x, y, 0)
  3065. tensor(4.)
  3066. >>> torch.dist(x, y, 1)
  3067. tensor(2.6537)
  3068. """.format(**common_args),
  3069. )
  3070. add_docstr(
  3071. torch.div,
  3072. r"""
  3073. div(input, other, *, rounding_mode=None, out=None) -> Tensor
  3074. Divides each element of the input ``input`` by the corresponding element of
  3075. :attr:`other`.
  3076. .. math::
  3077. \text{{out}}_i = \frac{{\text{{input}}_i}}{{\text{{other}}_i}}
  3078. .. note::
  3079. By default, this performs a "true" division like Python 3.
  3080. See the :attr:`rounding_mode` argument for floor division.
  3081. Supports :ref:`broadcasting to a common shape <broadcasting-semantics>`,
  3082. :ref:`type promotion <type-promotion-doc>`, and integer, float, and complex inputs.
  3083. Always promotes integer types to the default scalar type.
  3084. Args:
  3085. input (Tensor): the dividend
  3086. other (Tensor or Number): the divisor
  3087. Keyword args:
  3088. rounding_mode (str, optional): Type of rounding applied to the result:
  3089. * None - default behavior. Performs no rounding and, if both :attr:`input` and
  3090. :attr:`other` are integer types, promotes the inputs to the default scalar type.
  3091. Equivalent to true division in Python (the ``/`` operator) and NumPy's ``np.true_divide``.
  3092. * ``"trunc"`` - rounds the results of the division towards zero.
  3093. Equivalent to C-style integer division.
  3094. * ``"floor"`` - rounds the results of the division down.
  3095. Equivalent to floor division in Python (the ``//`` operator) and NumPy's ``np.floor_divide``.
  3096. {out}
  3097. Examples::
  3098. >>> x = torch.tensor([ 0.3810, 1.2774, -0.2972, -0.3719, 0.4637])
  3099. >>> torch.div(x, 0.5)
  3100. tensor([ 0.7620, 2.5548, -0.5944, -0.7438, 0.9274])
  3101. >>> a = torch.tensor([[-0.3711, -1.9353, -0.4605, -0.2917],
  3102. ... [ 0.1815, -1.0111, 0.9805, -1.5923],
  3103. ... [ 0.1062, 1.4581, 0.7759, -1.2344],
  3104. ... [-0.1830, -0.0313, 1.1908, -1.4757]])
  3105. >>> b = torch.tensor([ 0.8032, 0.2930, -0.8113, -0.2308])
  3106. >>> torch.div(a, b)
  3107. tensor([[-0.4620, -6.6051, 0.5676, 1.2639],
  3108. [ 0.2260, -3.4509, -1.2086, 6.8990],
  3109. [ 0.1322, 4.9764, -0.9564, 5.3484],
  3110. [-0.2278, -0.1068, -1.4678, 6.3938]])
  3111. >>> torch.div(a, b, rounding_mode='trunc')
  3112. tensor([[-0., -6., 0., 1.],
  3113. [ 0., -3., -1., 6.],
  3114. [ 0., 4., -0., 5.],
  3115. [-0., -0., -1., 6.]])
  3116. >>> torch.div(a, b, rounding_mode='floor')
  3117. tensor([[-1., -7., 0., 1.],
  3118. [ 0., -4., -2., 6.],
  3119. [ 0., 4., -1., 5.],
  3120. [-1., -1., -2., 6.]])
  3121. """.format(**common_args),
  3122. )
  3123. add_docstr(
  3124. torch.divide,
  3125. r"""
  3126. divide(input, other, *, rounding_mode=None, out=None) -> Tensor
  3127. Alias for :func:`torch.div`.
  3128. """,
  3129. )
  3130. add_docstr(
  3131. torch.dot,
  3132. r"""
  3133. dot(input, tensor, *, out=None) -> Tensor
  3134. Computes the dot product of two 1D tensors.
  3135. .. note::
  3136. Unlike NumPy's dot, torch.dot intentionally only supports computing the dot product
  3137. of two 1D tensors with the same number of elements.
  3138. Args:
  3139. input (Tensor): first tensor in the dot product, must be 1D.
  3140. tensor (Tensor): second tensor in the dot product, must be 1D.
  3141. Keyword args:
  3142. {out}
  3143. Example::
  3144. >>> torch.dot(torch.tensor([2, 3]), torch.tensor([2, 1]))
  3145. tensor(7)
  3146. >>> t1, t2 = torch.tensor([0, 1]), torch.tensor([2, 3])
  3147. >>> torch.dot(t1, t2)
  3148. tensor(3)
  3149. """.format(**common_args),
  3150. )
  3151. add_docstr(
  3152. torch.vdot,
  3153. r"""
  3154. vdot(input, other, *, out=None) -> Tensor
  3155. Computes the dot product of two 1D vectors along a dimension.
  3156. In symbols, this function computes
  3157. .. math::
  3158. \sum_{i=1}^n \overline{x_i}y_i.
  3159. where :math:`\overline{x_i}` denotes the conjugate for complex
  3160. vectors, and it is the identity for real vectors.
  3161. .. note::
  3162. Unlike NumPy's vdot, torch.vdot intentionally only supports computing the dot product
  3163. of two 1D tensors with the same number of elements.
  3164. .. seealso::
  3165. :func:`torch.linalg.vecdot` computes the dot product of two batches of vectors along a dimension.
  3166. Args:
  3167. input (Tensor): first tensor in the dot product, must be 1D. Its conjugate is used if it's complex.
  3168. other (Tensor): second tensor in the dot product, must be 1D.
  3169. Keyword args:
  3170. """
  3171. + rf"""
  3172. .. note:: {common_args["out"]}
  3173. """
  3174. + r"""
  3175. Example::
  3176. >>> torch.vdot(torch.tensor([2, 3]), torch.tensor([2, 1]))
  3177. tensor(7)
  3178. >>> a = torch.tensor((1 +2j, 3 - 1j))
  3179. >>> b = torch.tensor((2 +1j, 4 - 0j))
  3180. >>> torch.vdot(a, b)
  3181. tensor([16.+1.j])
  3182. >>> torch.vdot(b, a)
  3183. tensor([16.-1.j])
  3184. """,
  3185. )
  3186. add_docstr(
  3187. torch.eq,
  3188. r"""
  3189. eq(input, other, *, out=None) -> Tensor
  3190. Computes element-wise equality
  3191. The second argument can be a number or a tensor whose shape is
  3192. :ref:`broadcastable <broadcasting-semantics>` with the first argument.
  3193. Args:
  3194. input (Tensor): the tensor to compare
  3195. other (Tensor or float): the tensor or value to compare
  3196. Keyword args:
  3197. {out}
  3198. Returns:
  3199. A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere
  3200. Example::
  3201. >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
  3202. tensor([[ True, False],
  3203. [False, True]])
  3204. """.format(**common_args),
  3205. )
  3206. add_docstr(
  3207. torch.equal,
  3208. r"""
  3209. equal(input, other) -> bool
  3210. ``True`` if two tensors have the same size and elements, ``False`` otherwise.
  3211. .. note::
  3212. Tensors containing NaNs are never equal to each other. Additionally, this function does not
  3213. differentiate between the data types of the tensors during comparison. For more thorough tensor checks,
  3214. use :meth:`torch.testing.assert_close`.
  3215. Example::
  3216. >>> torch.equal(torch.tensor([1, 2]), torch.tensor([1, 2]))
  3217. True
  3218. >>> torch.equal(torch.tensor([3, torch.nan]), torch.tensor([3, torch.nan]))
  3219. False
  3220. >>> torch.equal(torch.tensor([1, 2, 3], dtype=torch.int32), torch.tensor([1, 2, 3], dtype=torch.float32))
  3221. True
  3222. """,
  3223. )
  3224. add_docstr(
  3225. torch.erf,
  3226. r"""
  3227. erf(input, *, out=None) -> Tensor
  3228. Alias for :func:`torch.special.erf`.
  3229. """,
  3230. )
  3231. add_docstr(
  3232. torch.erfc,
  3233. r"""
  3234. erfc(input, *, out=None) -> Tensor
  3235. Alias for :func:`torch.special.erfc`.
  3236. """,
  3237. )
  3238. add_docstr(
  3239. torch.erfinv,
  3240. r"""
  3241. erfinv(input, *, out=None) -> Tensor
  3242. Alias for :func:`torch.special.erfinv`.
  3243. """,
  3244. )
  3245. add_docstr(
  3246. torch.exp,
  3247. r"""
  3248. exp(input, *, out=None) -> Tensor
  3249. Returns a new tensor with the exponential of the elements
  3250. of the input tensor :attr:`input`.
  3251. .. math::
  3252. y_{i} = e^{x_{i}}
  3253. """
  3254. + r"""
  3255. Args:
  3256. {input}
  3257. Keyword args:
  3258. {out}
  3259. Example::
  3260. >>> torch.exp(torch.tensor([0, math.log(2.)]))
  3261. tensor([ 1., 2.])
  3262. """.format(**common_args),
  3263. )
  3264. add_docstr(
  3265. torch.exp2,
  3266. r"""
  3267. exp2(input, *, out=None) -> Tensor
  3268. Alias for :func:`torch.special.exp2`.
  3269. """,
  3270. )
  3271. add_docstr(
  3272. torch.expm1,
  3273. r"""
  3274. expm1(input, *, out=None) -> Tensor
  3275. Alias for :func:`torch.special.expm1`.
  3276. """,
  3277. )
  3278. add_docstr(
  3279. torch.eye,
  3280. r"""
  3281. eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
  3282. Returns a 2-D tensor with ones on the diagonal and zeros elsewhere.
  3283. Args:
  3284. n (int): the number of rows
  3285. m (int, optional): the number of columns with default being :attr:`n`
  3286. Keyword arguments:
  3287. {out}
  3288. {dtype}
  3289. {layout}
  3290. {device}
  3291. {requires_grad}
  3292. Returns:
  3293. Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere
  3294. Example::
  3295. >>> torch.eye(3)
  3296. tensor([[ 1., 0., 0.],
  3297. [ 0., 1., 0.],
  3298. [ 0., 0., 1.]])
  3299. """.format(**factory_common_args),
  3300. )
  3301. add_docstr(
  3302. torch.floor,
  3303. r"""
  3304. floor(input, *, out=None) -> Tensor
  3305. Returns a new tensor with the floor of the elements of :attr:`input`,
  3306. the largest integer less than or equal to each element.
  3307. For integer inputs, follows the array-api convention of returning a
  3308. copy of the input tensor.
  3309. .. math::
  3310. \text{out}_{i} = \left\lfloor \text{input}_{i} \right\rfloor
  3311. """
  3312. + r"""
  3313. Args:
  3314. {input}
  3315. Keyword args:
  3316. {out}
  3317. Example::
  3318. >>> a = torch.randn(4)
  3319. >>> a
  3320. tensor([-0.8166, 1.5308, -0.2530, -0.2091])
  3321. >>> torch.floor(a)
  3322. tensor([-1., 1., -1., -1.])
  3323. """.format(**common_args),
  3324. )
  3325. add_docstr(
  3326. torch.floor_divide,
  3327. r"""
  3328. floor_divide(input, other, *, out=None) -> Tensor
  3329. .. note::
  3330. Before PyTorch 1.13 :func:`torch.floor_divide` incorrectly performed
  3331. truncation division. To restore the previous behavior use
  3332. :func:`torch.div` with ``rounding_mode='trunc'``.
  3333. Computes :attr:`input` divided by :attr:`other`, elementwise, and floors
  3334. the result.
  3335. .. math::
  3336. \text{{out}}_i = \text{floor} \left( \frac{{\text{{input}}_i}}{{\text{{other}}_i}} \right)
  3337. """
  3338. + r"""
  3339. Supports broadcasting to a common shape, type promotion, and integer and float inputs.
  3340. Args:
  3341. input (Tensor or Number): the dividend
  3342. other (Tensor or Number): the divisor
  3343. Keyword args:
  3344. {out}
  3345. Example::
  3346. >>> a = torch.tensor([4.0, 3.0])
  3347. >>> b = torch.tensor([2.0, 2.0])
  3348. >>> torch.floor_divide(a, b)
  3349. tensor([2.0, 1.0])
  3350. >>> torch.floor_divide(a, 1.4)
  3351. tensor([2.0, 2.0])
  3352. """.format(**common_args),
  3353. )
  3354. add_docstr(
  3355. torch.fmod,
  3356. r"""
  3357. fmod(input, other, *, out=None) -> Tensor
  3358. Applies C++'s `std::fmod <https://en.cppreference.com/w/cpp/numeric/math/fmod>`_ entrywise.
  3359. The result has the same sign as the dividend :attr:`input` and its absolute value
  3360. is less than that of :attr:`other`.
  3361. This function may be defined in terms of :func:`torch.div` as
  3362. .. code:: python
  3363. torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b
  3364. Supports :ref:`broadcasting to a common shape <broadcasting-semantics>`,
  3365. :ref:`type promotion <type-promotion-doc>`, and integer and float inputs.
  3366. .. note::
  3367. When the divisor is zero, returns ``NaN`` for floating point dtypes
  3368. on both CPU and GPU; raises ``RuntimeError`` for integer division by
  3369. zero on CPU; Integer division by zero on GPU may return any value.
  3370. .. note::
  3371. Complex inputs are not supported. In some cases, it is not mathematically
  3372. possible to satisfy the definition of a modulo operation with complex numbers.
  3373. .. seealso::
  3374. :func:`torch.remainder` which implements Python's modulus operator.
  3375. This one is defined using division rounding down the result.
  3376. Args:
  3377. input (Tensor): the dividend
  3378. other (Tensor or Scalar): the divisor
  3379. Keyword args:
  3380. {out}
  3381. Example::
  3382. >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2)
  3383. tensor([-1., -0., -1., 1., 0., 1.])
  3384. >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5)
  3385. tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000])
  3386. """.format(**common_args),
  3387. )
  3388. add_docstr(
  3389. torch.frac,
  3390. r"""
  3391. frac(input, *, out=None) -> Tensor
  3392. Computes the fractional portion of each element in :attr:`input`.
  3393. .. math::
  3394. \text{out}_{i} = \text{input}_{i} - \left\lfloor |\text{input}_{i}| \right\rfloor * \operatorname{sgn}(\text{input}_{i})
  3395. Example::
  3396. >>> torch.frac(torch.tensor([1, 2.5, -3.2]))
  3397. tensor([ 0.0000, 0.5000, -0.2000])
  3398. """,
  3399. )
  3400. add_docstr(
  3401. torch.frexp,
  3402. r"""
  3403. frexp(input, *, out=None) -> (Tensor mantissa, Tensor exponent)
  3404. Decomposes :attr:`input` into mantissa and exponent tensors
  3405. such that :math:`\text{input} = \text{mantissa} \times 2^{\text{exponent}}`.
  3406. The range of mantissa is the open interval (-1, 1).
  3407. Supports float inputs.
  3408. Args:
  3409. input (Tensor): the input tensor
  3410. Keyword args:
  3411. out (tuple, optional): the output tensors
  3412. Example::
  3413. >>> x = torch.arange(9.)
  3414. >>> mantissa, exponent = torch.frexp(x)
  3415. >>> mantissa
  3416. tensor([0.0000, 0.5000, 0.5000, 0.7500, 0.5000, 0.6250, 0.7500, 0.8750, 0.5000])
  3417. >>> exponent
  3418. tensor([0, 1, 2, 2, 3, 3, 3, 3, 4], dtype=torch.int32)
  3419. >>> torch.ldexp(mantissa, exponent)
  3420. tensor([0., 1., 2., 3., 4., 5., 6., 7., 8.])
  3421. """,
  3422. )
  3423. add_docstr(
  3424. torch.from_numpy,
  3425. r"""
  3426. from_numpy(ndarray) -> Tensor
  3427. Creates a :class:`Tensor` from a :class:`numpy.ndarray`.
  3428. The returned tensor and :attr:`ndarray` share the same memory. Modifications to
  3429. the tensor will be reflected in the :attr:`ndarray` and vice versa. The returned
  3430. tensor is not resizable.
  3431. It currently accepts :attr:`ndarray` with dtypes of ``numpy.float64``,
  3432. ``numpy.float32``, ``numpy.float16``, ``numpy.complex64``, ``numpy.complex128``,
  3433. ``numpy.int64``, ``numpy.int32``, ``numpy.int16``, ``numpy.int8``, ``numpy.uint8``,
  3434. and ``bool``.
  3435. .. warning::
  3436. Writing to a tensor created from a read-only NumPy array is not supported and will result in undefined behavior.
  3437. Example::
  3438. >>> a = numpy.array([1, 2, 3])
  3439. >>> t = torch.from_numpy(a)
  3440. >>> t
  3441. tensor([ 1, 2, 3])
  3442. >>> t[0] = -1
  3443. >>> a
  3444. array([-1, 2, 3])
  3445. """,
  3446. )
  3447. add_docstr(
  3448. torch.frombuffer,
  3449. r"""
  3450. frombuffer(buffer, *, dtype, count=-1, offset=0, requires_grad=False) -> Tensor
  3451. Creates a 1-dimensional :class:`Tensor` from an object that implements
  3452. the Python buffer protocol.
  3453. Skips the first :attr:`offset` bytes in the buffer, and interprets the rest of
  3454. the raw bytes as a 1-dimensional tensor of type :attr:`dtype` with :attr:`count`
  3455. elements.
  3456. Note that either of the following must be true:
  3457. 1. :attr:`count` is a positive non-zero number, and the total number of bytes
  3458. in the buffer is more than :attr:`offset` plus :attr:`count` times the size
  3459. (in bytes) of :attr:`dtype`.
  3460. 2. :attr:`count` is negative, and the length (number of bytes) of the buffer
  3461. subtracted by the :attr:`offset` is a multiple of the size (in bytes) of
  3462. :attr:`dtype`.
  3463. The returned tensor and buffer share the same memory. Modifications to
  3464. the tensor will be reflected in the buffer and vice versa. The returned
  3465. tensor is not resizable.
  3466. .. note::
  3467. This function increments the reference count for the object that
  3468. owns the shared memory. Therefore, such memory will not be deallocated
  3469. before the returned tensor goes out of scope.
  3470. .. warning::
  3471. This function's behavior is undefined when passed an object implementing
  3472. the buffer protocol whose data is not on the CPU. Doing so is likely to
  3473. cause a segmentation fault.
  3474. .. warning::
  3475. This function does not try to infer the :attr:`dtype` (hence, it is not
  3476. optional). Passing a different :attr:`dtype` than its source may result
  3477. in unexpected behavior.
  3478. Args:
  3479. buffer (object): a Python object that exposes the buffer interface.
  3480. Keyword args:
  3481. dtype (:class:`torch.dtype`): the desired data type of returned tensor.
  3482. count (int, optional): the number of desired elements to be read.
  3483. If negative, all the elements (until the end of the buffer) will be
  3484. read. Default: -1.
  3485. offset (int, optional): the number of bytes to skip at the start of
  3486. the buffer. Default: 0.
  3487. {requires_grad}
  3488. Example::
  3489. >>> import array
  3490. >>> a = array.array('i', [1, 2, 3])
  3491. >>> t = torch.frombuffer(a, dtype=torch.int32)
  3492. >>> t
  3493. tensor([ 1, 2, 3])
  3494. >>> t[0] = -1
  3495. >>> a
  3496. array([-1, 2, 3])
  3497. >>> # Interprets the signed char bytes as 32-bit integers.
  3498. >>> # Each 4 signed char elements will be interpreted as
  3499. >>> # 1 signed 32-bit integer.
  3500. >>> import array
  3501. >>> a = array.array('b', [-1, 0, 0, 0])
  3502. >>> torch.frombuffer(a, dtype=torch.int32)
  3503. tensor([255], dtype=torch.int32)
  3504. """.format(**factory_common_args),
  3505. )
  3506. add_docstr(
  3507. torch.from_file,
  3508. r"""
  3509. from_file(filename, shared=None, size=0, *, dtype=None, layout=None, device=None, pin_memory=False)
  3510. Creates a CPU tensor with a storage backed by a memory-mapped file.
  3511. If ``shared`` is True, then memory is shared between processes. All changes are written to the file.
  3512. If ``shared`` is False, then changes to the tensor do not affect the file.
  3513. ``size`` is the number of elements in the Tensor. If ``shared`` is ``False``, then the file must contain
  3514. at least ``size * sizeof(dtype)`` bytes. If ``shared`` is ``True`` the file will be created if needed.
  3515. .. note::
  3516. Only CPU tensors can be mapped to files.
  3517. .. note::
  3518. For now, tensors with storages backed by a memory-mapped file cannot be created in pinned memory.
  3519. Args:
  3520. filename (str): file name to map
  3521. shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the
  3522. underlying `mmap(2) call <https://man7.org/linux/man-pages/man2/mmap.2.html>`_)
  3523. size (int): number of elements in the tensor
  3524. Keyword args:
  3525. {dtype}
  3526. {layout}
  3527. {device}
  3528. {pin_memory}
  3529. Example::
  3530. >>> t = torch.randn(2, 5, dtype=torch.float64)
  3531. >>> t.numpy().tofile('storage.pt')
  3532. >>> t_mapped = torch.from_file('storage.pt', shared=False, size=10, dtype=torch.float64)
  3533. """.format(**factory_common_args),
  3534. )
  3535. add_docstr(
  3536. torch.flatten,
  3537. r"""
  3538. flatten(input, start_dim=0, end_dim=-1) -> Tensor
  3539. Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim`
  3540. are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened.
  3541. The order of elements in :attr:`input` is unchanged.
  3542. Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view,
  3543. or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can
  3544. be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the
  3545. flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned.
  3546. .. note::
  3547. Flattening a zero-dimensional tensor will return a one-dimensional view.
  3548. Args:
  3549. {input}
  3550. start_dim (int): the first dim to flatten
  3551. end_dim (int): the last dim to flatten
  3552. Example::
  3553. >>> t = torch.tensor([[[1, 2],
  3554. ... [3, 4]],
  3555. ... [[5, 6],
  3556. ... [7, 8]]])
  3557. >>> torch.flatten(t)
  3558. tensor([1, 2, 3, 4, 5, 6, 7, 8])
  3559. >>> torch.flatten(t, start_dim=1)
  3560. tensor([[1, 2, 3, 4],
  3561. [5, 6, 7, 8]])
  3562. """.format(**common_args),
  3563. )
  3564. add_docstr(
  3565. torch.unflatten,
  3566. r"""
  3567. unflatten(input, dim, sizes) -> Tensor
  3568. Expands a dimension of the input tensor over multiple dimensions.
  3569. .. seealso::
  3570. :func:`torch.flatten` the inverse of this function. It coalesces several dimensions into one.
  3571. Args:
  3572. {input}
  3573. dim (int): Dimension to be unflattened, specified as an index into
  3574. ``input.shape``.
  3575. sizes (Tuple[int]): New shape of the unflattened dimension.
  3576. One of its elements can be `-1` in which case the corresponding output
  3577. dimension is inferred. Otherwise, the product of ``sizes`` *must*
  3578. equal ``input.shape[dim]``.
  3579. Returns:
  3580. A View of input with the specified dimension unflattened.
  3581. Examples::
  3582. >>> torch.unflatten(torch.randn(3, 4, 1), 1, (2, 2)).shape
  3583. torch.Size([3, 2, 2, 1])
  3584. >>> torch.unflatten(torch.randn(3, 4, 1), 1, (-1, 2)).shape
  3585. torch.Size([3, 2, 2, 1])
  3586. >>> torch.unflatten(torch.randn(5, 12, 3), -2, (2, 2, 3, 1, 1)).shape
  3587. torch.Size([5, 2, 2, 3, 1, 1, 3])
  3588. """.format(**common_args),
  3589. )
  3590. add_docstr(
  3591. torch.gather,
  3592. r"""
  3593. gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor
  3594. Gathers values along an axis specified by `dim`.
  3595. For a 3-D tensor the output is specified by::
  3596. out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0
  3597. out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1
  3598. out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2
  3599. :attr:`input` and :attr:`index` must have the same number of dimensions.
  3600. It is also required that ``index.size(d) <= input.size(d)`` for all
  3601. dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`.
  3602. Note that ``input`` and ``index`` do not broadcast against each other.
  3603. When :attr:`index` is empty, we always return an empty output with the same shape
  3604. without further error checking.
  3605. Args:
  3606. input (Tensor): the source tensor
  3607. dim (int): the axis along which to index
  3608. index (LongTensor): the indices of elements to gather
  3609. Keyword arguments:
  3610. sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor.
  3611. out (Tensor, optional): the destination tensor
  3612. Example::
  3613. >>> t = torch.tensor([[1, 2], [3, 4]])
  3614. >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]]))
  3615. tensor([[ 1, 1],
  3616. [ 4, 3]])
  3617. """,
  3618. )
  3619. add_docstr(
  3620. torch.gcd,
  3621. r"""
  3622. gcd(input, other, *, out=None) -> Tensor
  3623. Computes the element-wise greatest common divisor (GCD) of :attr:`input` and :attr:`other`.
  3624. Both :attr:`input` and :attr:`other` must have integer types.
  3625. .. note::
  3626. This defines :math:`gcd(0, 0) = 0`.
  3627. Args:
  3628. {input}
  3629. other (Tensor): the second input tensor
  3630. Keyword arguments:
  3631. {out}
  3632. Example::
  3633. >>> a = torch.tensor([5, 10, 15])
  3634. >>> b = torch.tensor([3, 4, 5])
  3635. >>> torch.gcd(a, b)
  3636. tensor([1, 2, 5])
  3637. >>> c = torch.tensor([3])
  3638. >>> torch.gcd(a, c)
  3639. tensor([1, 1, 3])
  3640. """.format(**common_args),
  3641. )
  3642. add_docstr(
  3643. torch.ge,
  3644. r"""
  3645. ge(input, other, *, out=None) -> Tensor
  3646. Computes :math:`\text{input} \geq \text{other}` element-wise.
  3647. """
  3648. + r"""
  3649. The second argument can be a number or a tensor whose shape is
  3650. :ref:`broadcastable <broadcasting-semantics>` with the first argument.
  3651. Args:
  3652. input (Tensor): the tensor to compare
  3653. other (Tensor or float): the tensor or value to compare
  3654. Keyword args:
  3655. {out}
  3656. Returns:
  3657. A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere
  3658. Example::
  3659. >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
  3660. tensor([[True, True], [False, True]])
  3661. """.format(**common_args),
  3662. )
  3663. add_docstr(
  3664. torch.greater_equal,
  3665. r"""
  3666. greater_equal(input, other, *, out=None) -> Tensor
  3667. Alias for :func:`torch.ge`.
  3668. """,
  3669. )
  3670. add_docstr(
  3671. torch.gradient,
  3672. r"""
  3673. gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors
  3674. Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in
  3675. one or more dimensions using the `second-order accurate central differences method
  3676. <https://www.ams.org/journals/mcom/1988-51-184/S0025-5718-1988-0935077-0/S0025-5718-1988-0935077-0.pdf>`_ and
  3677. either first or second order estimates at the boundaries.
  3678. The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not
  3679. specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates
  3680. to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional
  3681. :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and
  3682. :math:`g(1, 2, 3)\ == input[1, 2, 3]`.
  3683. When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates.
  3684. This is detailed in the "Keyword Arguments" section below.
  3685. The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is
  3686. accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be
  3687. improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative
  3688. is estimated using `Taylor's theorem with remainder <https://en.wikipedia.org/wiki/Taylor%27s_theorem>`_.
  3689. Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring
  3690. it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using:
  3691. .. math::
  3692. \begin{aligned}
  3693. f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\
  3694. f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\
  3695. \end{aligned}
  3696. Using the fact that :math:`f \in C^3` and solving the linear system, we derive:
  3697. .. math::
  3698. f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l)
  3699. + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} }
  3700. .. note::
  3701. We estimate the gradient of functions in complex domain
  3702. :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way.
  3703. The value of each partial derivative at the boundary points is computed differently. See edge_order below.
  3704. Args:
  3705. input (``Tensor``): the tensor that represents the values of the function
  3706. Keyword args:
  3707. spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify
  3708. how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then
  3709. the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the
  3710. indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding
  3711. indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9).
  3712. Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for
  3713. the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then
  3714. the coordinates are (t0[1], t1[2], t2[3])
  3715. dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default
  3716. the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of
  3717. the :attr:`spacing` argument must correspond with the specified dims."
  3718. edge_order (``int``, optional): 1 or 2, for `first-order
  3719. <https://www.ams.org/journals/mcom/1988-51-184/S0025-5718-1988-0935077-0/S0025-5718-1988-0935077-0.pdf>`_ or
  3720. `second-order <https://www.ams.org/journals/mcom/1988-51-184/S0025-5718-1988-0935077-0/S0025-5718-1988-0935077-0.pdf>`_
  3721. estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each
  3722. dimension size of :attr:`input` should be at least edge_order+1
  3723. Examples::
  3724. >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4]
  3725. >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),)
  3726. >>> values = torch.tensor([4., 1., 1., 16.], )
  3727. >>> torch.gradient(values, spacing = coordinates)
  3728. (tensor([-3., -2., 2., 5.]),)
  3729. >>> # Estimates the gradient of the R^2 -> R function whose samples are
  3730. >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost
  3731. >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates
  3732. >>> # partial derivative for both dimensions.
  3733. >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]])
  3734. >>> torch.gradient(t)
  3735. (tensor([[ 9., 18., 36., 72.],
  3736. [ 9., 18., 36., 72.]]),
  3737. tensor([[ 1.0000, 1.5000, 3.0000, 4.0000],
  3738. [10.0000, 15.0000, 30.0000, 40.0000]]))
  3739. >>> # A scalar value for spacing modifies the relationship between tensor indices
  3740. >>> # and input coordinates by multiplying the indices to find the
  3741. >>> # coordinates. For example, below the indices of the innermost
  3742. >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of
  3743. >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2].
  3744. >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1])
  3745. (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000],
  3746. [ 4.5000, 9.0000, 18.0000, 36.0000]]),
  3747. tensor([[ 0.5000, 0.7500, 1.5000, 2.0000],
  3748. [ 5.0000, 7.5000, 15.0000, 20.0000]]))
  3749. >>> # doubling the spacing between samples halves the estimated partial gradients.
  3750. >>>
  3751. >>> # Estimates only the partial derivative for dimension 1
  3752. >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.)
  3753. (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000],
  3754. [10.0000, 15.0000, 30.0000, 40.0000]]),)
  3755. >>> # When spacing is a list of scalars, the relationship between the tensor
  3756. >>> # indices and input coordinates changes based on dimension.
  3757. >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate
  3758. >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension
  3759. >>> # 0, 1 translate to coordinates of [0, 2].
  3760. >>> torch.gradient(t, spacing = [3., 2.])
  3761. (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000],
  3762. [ 4.5000, 9.0000, 18.0000, 36.0000]]),
  3763. tensor([[ 0.3333, 0.5000, 1.0000, 1.3333],
  3764. [ 3.3333, 5.0000, 10.0000, 13.3333]]))
  3765. >>> # The following example is a replication of the previous one with explicit
  3766. >>> # coordinates.
  3767. >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9]))
  3768. >>> torch.gradient(t, spacing = coords)
  3769. (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000],
  3770. [ 4.5000, 9.0000, 18.0000, 36.0000]]),
  3771. tensor([[ 0.3333, 0.5000, 1.0000, 1.3333],
  3772. [ 3.3333, 5.0000, 10.0000, 13.3333]]))
  3773. """,
  3774. )
  3775. add_docstr(
  3776. torch.geqrf,
  3777. r"""
  3778. geqrf(input, *, out=None) -> (Tensor, Tensor)
  3779. This is a low-level function for calling LAPACK's geqrf directly. This function
  3780. returns a namedtuple (a, tau) as defined in `LAPACK documentation for geqrf`_ .
  3781. Computes a QR decomposition of :attr:`input`.
  3782. Both `Q` and `R` matrices are stored in the same output tensor `a`.
  3783. The elements of `R` are stored on and above the diagonal.
  3784. Elementary reflectors (or Householder vectors) implicitly defining matrix `Q`
  3785. are stored below the diagonal.
  3786. The results of this function can be used together with :func:`torch.linalg.householder_product`
  3787. to obtain the `Q` matrix or
  3788. with :func:`torch.ormqr`, which uses an implicit representation of the `Q` matrix,
  3789. for an efficient matrix-matrix multiplication.
  3790. See `LAPACK documentation for geqrf`_ for further details.
  3791. .. note::
  3792. See also :func:`torch.linalg.qr`, which computes Q and R matrices, and :func:`torch.linalg.lstsq`
  3793. with the ``driver="gels"`` option for a function that can solve matrix equations using a QR decomposition.
  3794. Args:
  3795. input (Tensor): the input matrix
  3796. Keyword args:
  3797. out (tuple, optional): the output tuple of (Tensor, Tensor). Ignored if `None`. Default: `None`.
  3798. .. _LAPACK documentation for geqrf:
  3799. http://www.netlib.org/lapack/explore-html/df/dc5/group__variants_g_ecomputational_ga3766ea903391b5cf9008132f7440ec7b.html
  3800. """,
  3801. )
  3802. add_docstr(
  3803. torch.inner,
  3804. r"""
  3805. inner(input, other, *, out=None) -> Tensor
  3806. Computes the dot product for 1D tensors. For higher dimensions, sums the product
  3807. of elements from :attr:`input` and :attr:`other` along their last dimension.
  3808. .. note::
  3809. If either :attr:`input` or :attr:`other` is a scalar, the result is equivalent
  3810. to `torch.mul(input, other)`.
  3811. If both :attr:`input` and :attr:`other` are non-scalars, the size of their last
  3812. dimension must match and the result is equivalent to `torch.tensordot(input,
  3813. other, dims=([-1], [-1]))`
  3814. Args:
  3815. input (Tensor): First input tensor
  3816. other (Tensor): Second input tensor
  3817. Keyword args:
  3818. out (Tensor, optional): Optional output tensor to write result into. The output
  3819. shape is `input.shape[:-1] + other.shape[:-1]`.
  3820. Example::
  3821. # Dot product
  3822. >>> torch.inner(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 1]))
  3823. tensor(7)
  3824. # Multidimensional input tensors
  3825. >>> a = torch.randn(2, 3)
  3826. >>> a
  3827. tensor([[0.8173, 1.0874, 1.1784],
  3828. [0.3279, 0.1234, 2.7894]])
  3829. >>> b = torch.randn(2, 4, 3)
  3830. >>> b
  3831. tensor([[[-0.4682, -0.7159, 0.1506],
  3832. [ 0.4034, -0.3657, 1.0387],
  3833. [ 0.9892, -0.6684, 0.1774],
  3834. [ 0.9482, 1.3261, 0.3917]],
  3835. [[ 0.4537, 0.7493, 1.1724],
  3836. [ 0.2291, 0.5749, -0.2267],
  3837. [-0.7920, 0.3607, -0.3701],
  3838. [ 1.3666, -0.5850, -1.7242]]])
  3839. >>> torch.inner(a, b)
  3840. tensor([[[-0.9837, 1.1560, 0.2907, 2.6785],
  3841. [ 2.5671, 0.5452, -0.6912, -1.5509]],
  3842. [[ 0.1782, 2.9843, 0.7366, 1.5672],
  3843. [ 3.5115, -0.4864, -1.2476, -4.4337]]])
  3844. # Scalar input
  3845. >>> torch.inner(a, torch.tensor(2))
  3846. tensor([[1.6347, 2.1748, 2.3567],
  3847. [0.6558, 0.2469, 5.5787]])
  3848. """,
  3849. )
  3850. add_docstr(
  3851. torch.outer,
  3852. r"""
  3853. outer(input, vec2, *, out=None) -> Tensor
  3854. Outer product of :attr:`input` and :attr:`vec2`.
  3855. If :attr:`input` is a vector of size :math:`n` and :attr:`vec2` is a vector of
  3856. size :math:`m`, then :attr:`out` must be a matrix of size :math:`(n \times m)`.
  3857. .. note:: This function does not :ref:`broadcast <broadcasting-semantics>`.
  3858. Args:
  3859. input (Tensor): 1-D input vector
  3860. vec2 (Tensor): 1-D input vector
  3861. Keyword args:
  3862. out (Tensor, optional): optional output matrix
  3863. Example::
  3864. >>> v1 = torch.arange(1., 5.)
  3865. >>> v2 = torch.arange(1., 4.)
  3866. >>> torch.outer(v1, v2)
  3867. tensor([[ 1., 2., 3.],
  3868. [ 2., 4., 6.],
  3869. [ 3., 6., 9.],
  3870. [ 4., 8., 12.]])
  3871. """,
  3872. )
  3873. add_docstr(
  3874. torch.ger,
  3875. r"""
  3876. ger(input, vec2, *, out=None) -> Tensor
  3877. Alias of :func:`torch.outer`.
  3878. .. warning::
  3879. This function is deprecated and will be removed in a future PyTorch release.
  3880. Use :func:`torch.outer` instead.
  3881. """,
  3882. )
  3883. add_docstr(
  3884. torch.get_default_dtype,
  3885. r"""
  3886. get_default_dtype() -> torch.dtype
  3887. Get the current default floating point :class:`torch.dtype`.
  3888. Example::
  3889. >>> torch.get_default_dtype() # initial default for floating point is torch.float32
  3890. torch.float32
  3891. >>> torch.set_default_dtype(torch.float64)
  3892. >>> torch.get_default_dtype() # default is now changed to torch.float64
  3893. torch.float64
  3894. """,
  3895. )
  3896. add_docstr(
  3897. torch.get_num_threads,
  3898. r"""
  3899. get_num_threads() -> int
  3900. Returns the number of threads used for parallelizing CPU operations
  3901. """,
  3902. )
  3903. add_docstr(
  3904. torch.get_num_interop_threads,
  3905. r"""
  3906. get_num_interop_threads() -> int
  3907. Returns the number of threads used for inter-op parallelism on CPU
  3908. (e.g. in JIT interpreter)
  3909. """,
  3910. )
  3911. add_docstr(
  3912. torch.gt,
  3913. r"""
  3914. gt(input, other, *, out=None) -> Tensor
  3915. Computes :math:`\text{input} > \text{other}` element-wise.
  3916. """
  3917. + r"""
  3918. The second argument can be a number or a tensor whose shape is
  3919. :ref:`broadcastable <broadcasting-semantics>` with the first argument.
  3920. Args:
  3921. input (Tensor): the tensor to compare
  3922. other (Tensor or float): the tensor or value to compare
  3923. Keyword args:
  3924. {out}
  3925. Returns:
  3926. A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere
  3927. Example::
  3928. >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
  3929. tensor([[False, True], [False, False]])
  3930. """.format(**common_args),
  3931. )
  3932. add_docstr(
  3933. torch.greater,
  3934. r"""
  3935. greater(input, other, *, out=None) -> Tensor
  3936. Alias for :func:`torch.gt`.
  3937. """,
  3938. )
  3939. add_docstr(
  3940. torch.hash_tensor,
  3941. r"""
  3942. hash_tensor(input, *, mode=0) -> Tensor
  3943. Returns a hash of all elements in the :attr:`input` tensor.
  3944. Currently only mode=0 (reduction via xor) is supported. The output will always
  3945. be of type ``torch.uint64``. The elements of ``input`` are upcasted to their
  3946. 64 bit float / integer equivalent and bitcasted to ``torch.uint64`` before
  3947. reduction via xor.
  3948. Args:
  3949. {input}
  3950. Keyword Args:
  3951. mode (int) : The hash to use. Default: 0 (xor_reduction)
  3952. Example::
  3953. >>> a = torch.randn(1, 3)
  3954. >>> a
  3955. tensor([[ 1.1918, -1.1813, 0.3373]])
  3956. >>> torch.hash_tensor(a)
  3957. tensor(13822780554648485888, dtype=torch.uint64)
  3958. .. function:: hash_tensor(input, dim, *, keepdim=False, mode=0) -> Tensor
  3959. :noindex:
  3960. Returns the hash of each row of the :attr:`input` tensor in the given
  3961. dimension :attr:`dim` given by mode. If :attr:`dim` is a list of dimensions,
  3962. reduce over all of them.
  3963. {keepdim_details}
  3964. Args:
  3965. {input}
  3966. {opt_dim_all_reduce}
  3967. {opt_keepdim}
  3968. Keyword Args:
  3969. mode (int) : The hash to use. Default: 0 (xor_reduction)
  3970. Example::
  3971. >>> a = torch.randn(2, 4)
  3972. >>> a
  3973. tensor([[ 0.1317, -0.5554, -1.4724, -1.1391],
  3974. [ 0.0778, -0.6070, 0.6375, 0.1798]])
  3975. >>> torch.hash_tensor(a, 1)
  3976. tensor([9233691267014066176, 9255993250844508160], dtype=torch.uint64)
  3977. """.format(**multi_dim_common),
  3978. )
  3979. add_docstr(
  3980. torch.histc,
  3981. r"""
  3982. histc(input, bins=100, min=0, max=0, *, out=None) -> Tensor
  3983. Computes the histogram of a tensor.
  3984. The elements are sorted into equal width bins between :attr:`min` and
  3985. :attr:`max`. If :attr:`min` and :attr:`max` are both zero, the minimum and
  3986. maximum values of the data are used.
  3987. Elements lower than min and higher than max and ``NaN`` elements are ignored.
  3988. Args:
  3989. {input}
  3990. bins (int): number of histogram bins
  3991. min (Scalar): lower end of the range (inclusive)
  3992. max (Scalar): upper end of the range (inclusive)
  3993. Keyword args:
  3994. {out}
  3995. Returns:
  3996. Tensor: Histogram represented as a tensor
  3997. Example::
  3998. >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3)
  3999. tensor([ 0., 2., 1., 0.])
  4000. """.format(**common_args),
  4001. )
  4002. add_docstr(
  4003. torch.histogram,
  4004. r"""
  4005. histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor)
  4006. Computes a histogram of the values in a tensor.
  4007. :attr:`bins` can be an integer or a 1D tensor.
  4008. If :attr:`bins` is an int, it specifies the number of equal-width bins.
  4009. By default, the lower and upper range of the bins is determined by the
  4010. minimum and maximum elements of the input tensor. The :attr:`range`
  4011. argument can be provided to specify a range for the bins.
  4012. If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges
  4013. including the rightmost edge. It should contain at least 2 elements
  4014. and its elements should be increasing.
  4015. Args:
  4016. {input}
  4017. bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor,
  4018. defines the sequence of bin edges including the rightmost edge.
  4019. Keyword args:
  4020. range (tuple of float): Defines the range of the bins.
  4021. weight (Tensor): If provided, weight should have the same shape as input. Each value in
  4022. input contributes its associated weight towards its bin's result.
  4023. density (bool): If False, the result will contain the count (or total weight) in each bin.
  4024. If True, the result is the value of the probability density function over the bins,
  4025. normalized such that the integral over the range of the bins is 1.
  4026. {out} (tuple, optional): The result tuple of two output tensors (hist, bin_edges).
  4027. Returns:
  4028. hist (Tensor): 1D Tensor containing the values of the histogram.
  4029. bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins.
  4030. Example::
  4031. >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]))
  4032. (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.]))
  4033. >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True)
  4034. (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.]))
  4035. """.format(**common_args),
  4036. )
  4037. add_docstr(
  4038. torch.histogramdd,
  4039. r"""
  4040. histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[])
  4041. Computes a multi-dimensional histogram of the values in a tensor.
  4042. Interprets the elements of an input tensor whose innermost dimension has size N
  4043. as a collection of N-dimensional points. Maps each of the points into a set of
  4044. N-dimensional bins and returns the number of points (or total weight) in each bin.
  4045. :attr:`input` must be a tensor with at least 2 dimensions.
  4046. If input has shape (M, N), each of its M rows defines a point in N-dimensional space.
  4047. If input has three or more dimensions, all but the last dimension are flattened.
  4048. Each dimension is independently associated with its own strictly increasing sequence
  4049. of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D
  4050. tensors. Alternatively, bin edges may be constructed automatically by passing a
  4051. sequence of integers specifying the number of equal-width bins in each dimension.
  4052. For each N-dimensional point in input:
  4053. - Each of its coordinates is binned independently among the bin edges
  4054. corresponding to its dimension
  4055. - Binning results are combined to identify the N-dimensional bin (if any)
  4056. into which the point falls
  4057. - If the point falls into a bin, the bin's count (or total weight) is incremented
  4058. - Points which do not fall into any bin do not contribute to the output
  4059. :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int.
  4060. If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences
  4061. of bin edges. Each 1D tensor should contain a strictly increasing sequence with at
  4062. least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying
  4063. the left and right edges of all bins. Every bin is inclusive of its left edge. Only
  4064. the rightmost bin is inclusive of its right edge.
  4065. If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins
  4066. in each dimension. By default, the leftmost and rightmost bin edges in each dimension
  4067. are determined by the minimum and maximum elements of the input tensor in the
  4068. corresponding dimension. The :attr:`range` argument can be provided to manually
  4069. specify the leftmost and rightmost bin edges in each dimension.
  4070. If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions.
  4071. .. note::
  4072. See also :func:`torch.histogram`, which specifically computes 1D histograms.
  4073. While :func:`torch.histogramdd` infers the dimensionality of its bins and
  4074. binned values from the shape of :attr:`input`, :func:`torch.histogram`
  4075. accepts and flattens :attr:`input` of any shape.
  4076. Args:
  4077. {input}
  4078. bins: Tensor[], int[], or int.
  4079. If Tensor[], defines the sequences of bin edges.
  4080. If int[], defines the number of equal-width bins in each dimension.
  4081. If int, defines the number of equal-width bins for all dimensions.
  4082. Keyword args:
  4083. range (sequence of float): Defines the leftmost and rightmost bin edges
  4084. in each dimension.
  4085. weight (Tensor): By default, each value in the input has weight 1. If a weight
  4086. tensor is passed, each N-dimensional coordinate in input
  4087. contributes its associated weight towards its bin's result.
  4088. The weight tensor should have the same shape as the :attr:`input`
  4089. tensor excluding its innermost dimension N.
  4090. density (bool): If False (default), the result will contain the count (or total weight)
  4091. in each bin. If True, each count (weight) is divided by the total count
  4092. (total weight), then divided by the volume of its associated bin.
  4093. Returns:
  4094. hist (Tensor): N-dimensional Tensor containing the values of the histogram.
  4095. bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges.
  4096. Example::
  4097. >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3],
  4098. ... weight=torch.tensor([1., 2., 4., 8.]))
  4099. torch.return_types.histogramdd(
  4100. hist=tensor([[0., 1., 0.],
  4101. [2., 0., 0.],
  4102. [4., 0., 8.]]),
  4103. bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]),
  4104. tensor([0.0000, 0.6667, 1.3333, 2.0000])))
  4105. >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2],
  4106. ... range=[0., 1., 0., 1.], density=True)
  4107. torch.return_types.histogramdd(
  4108. hist=tensor([[2., 0.],
  4109. [0., 2.]]),
  4110. bin_edges=(tensor([0.0000, 0.5000, 1.0000]),
  4111. tensor([0.0000, 0.5000, 1.0000])))
  4112. """.format(**common_args),
  4113. )
  4114. # TODO: Fix via https://github.com/pytorch/pytorch/issues/75798
  4115. torch.histogramdd.__module__ = "torch"
  4116. add_docstr(
  4117. torch.hypot,
  4118. r"""
  4119. hypot(input, other, *, out=None) -> Tensor
  4120. Given the legs of a right triangle, return its hypotenuse.
  4121. .. math::
  4122. \text{out}_{i} = \sqrt{\text{input}_{i}^{2} + \text{other}_{i}^{2}}
  4123. The shapes of ``input`` and ``other`` must be
  4124. :ref:`broadcastable <broadcasting-semantics>`.
  4125. """
  4126. + r"""
  4127. Args:
  4128. input (Tensor): the first input tensor
  4129. other (Tensor): the second input tensor
  4130. Keyword args:
  4131. {out}
  4132. Example::
  4133. >>> a = torch.hypot(torch.tensor([4.0]), torch.tensor([3.0, 4.0, 5.0]))
  4134. tensor([5.0000, 5.6569, 6.4031])
  4135. """.format(**common_args),
  4136. )
  4137. add_docstr(
  4138. torch.i0,
  4139. r"""
  4140. i0(input, *, out=None) -> Tensor
  4141. Alias for :func:`torch.special.i0`.
  4142. """,
  4143. )
  4144. add_docstr(
  4145. torch.igamma,
  4146. r"""
  4147. igamma(input, other, *, out=None) -> Tensor
  4148. Alias for :func:`torch.special.gammainc`.
  4149. """,
  4150. )
  4151. add_docstr(
  4152. torch.igammac,
  4153. r"""
  4154. igammac(input, other, *, out=None) -> Tensor
  4155. Alias for :func:`torch.special.gammaincc`.
  4156. """,
  4157. )
  4158. add_docstr(
  4159. torch.index_select,
  4160. r"""
  4161. index_select(input, dim, index, *, out=None) -> Tensor
  4162. Returns a new tensor which indexes the :attr:`input` tensor along dimension
  4163. :attr:`dim` using the entries in :attr:`index`.
  4164. The returned tensor has the same number of dimensions as the original tensor
  4165. (:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length
  4166. of :attr:`index`; other dimensions have the same size as in the original tensor.
  4167. .. note:: The returned tensor does **not** use the same storage as the original
  4168. tensor. If :attr:`out` has a different shape than expected, we
  4169. silently change it to the correct shape, reallocating the underlying
  4170. storage if necessary.
  4171. Args:
  4172. {input}
  4173. dim (int): the dimension in which we index
  4174. index (IntTensor or LongTensor): the 1-D tensor containing the indices to index
  4175. Keyword args:
  4176. {out}
  4177. Example::
  4178. >>> x = torch.randn(3, 4)
  4179. >>> x
  4180. tensor([[ 0.1427, 0.0231, -0.5414, -1.0009],
  4181. [-0.4664, 0.2647, -0.1228, -1.1068],
  4182. [-1.1734, -0.6571, 0.7230, -0.6004]])
  4183. >>> indices = torch.tensor([0, 2])
  4184. >>> torch.index_select(x, 0, indices)
  4185. tensor([[ 0.1427, 0.0231, -0.5414, -1.0009],
  4186. [-1.1734, -0.6571, 0.7230, -0.6004]])
  4187. >>> torch.index_select(x, 1, indices)
  4188. tensor([[ 0.1427, -0.5414],
  4189. [-0.4664, -0.1228],
  4190. [-1.1734, 0.7230]])
  4191. """.format(**common_args),
  4192. )
  4193. add_docstr(
  4194. torch.inverse,
  4195. r"""
  4196. inverse(input, *, out=None) -> Tensor
  4197. Alias for :func:`torch.linalg.inv`
  4198. """,
  4199. )
  4200. add_docstr(
  4201. torch.isin,
  4202. r"""
  4203. isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor
  4204. Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns
  4205. a boolean tensor of the same shape as :attr:`elements` that is True for elements
  4206. in :attr:`test_elements` and False otherwise.
  4207. .. note::
  4208. One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both.
  4209. Args:
  4210. elements (Tensor or Scalar): Input elements
  4211. test_elements (Tensor or Scalar): Values against which to test for each input element
  4212. assume_unique (bool, optional): If True, assumes both :attr:`elements` and
  4213. :attr:`test_elements` contain unique elements, which can speed up the
  4214. calculation. Default: False
  4215. invert (bool, optional): If True, inverts the boolean return tensor, resulting in True
  4216. values for elements *not* in :attr:`test_elements`. Default: False
  4217. Returns:
  4218. A boolean tensor of the same shape as :attr:`elements` that is True for elements in
  4219. :attr:`test_elements` and False otherwise
  4220. Example:
  4221. >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3]))
  4222. tensor([[False, True],
  4223. [ True, False]])
  4224. """,
  4225. )
  4226. add_docstr(
  4227. torch.isinf,
  4228. r"""
  4229. isinf(input) -> Tensor
  4230. Tests if each element of :attr:`input` is infinite
  4231. (positive or negative infinity) or not.
  4232. .. note::
  4233. Complex values are infinite when their real or imaginary part is
  4234. infinite.
  4235. Args:
  4236. {input}
  4237. Returns:
  4238. A boolean tensor that is True where :attr:`input` is infinite and False elsewhere
  4239. Example::
  4240. >>> torch.isinf(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')]))
  4241. tensor([False, True, False, True, False])
  4242. """.format(**common_args),
  4243. )
  4244. add_docstr(
  4245. torch.isposinf,
  4246. r"""
  4247. isposinf(input, *, out=None) -> Tensor
  4248. Tests if each element of :attr:`input` is positive infinity or not.
  4249. Args:
  4250. {input}
  4251. Keyword args:
  4252. {out}
  4253. Example::
  4254. >>> a = torch.tensor([-float('inf'), float('inf'), 1.2])
  4255. >>> torch.isposinf(a)
  4256. tensor([False, True, False])
  4257. """.format(**common_args),
  4258. )
  4259. add_docstr(
  4260. torch.isneginf,
  4261. r"""
  4262. isneginf(input, *, out=None) -> Tensor
  4263. Tests if each element of :attr:`input` is negative infinity or not.
  4264. Args:
  4265. {input}
  4266. Keyword args:
  4267. {out}
  4268. Example::
  4269. >>> a = torch.tensor([-float('inf'), float('inf'), 1.2])
  4270. >>> torch.isneginf(a)
  4271. tensor([ True, False, False])
  4272. """.format(**common_args),
  4273. )
  4274. add_docstr(
  4275. torch.isclose,
  4276. r"""
  4277. isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor
  4278. Returns a new tensor with boolean elements representing if each element of
  4279. :attr:`input` is "close" to the corresponding element of :attr:`other`.
  4280. Closeness is defined as:
  4281. .. math::
  4282. \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{rtol} \times \lvert \text{other}_i \rvert + \texttt{atol}
  4283. """
  4284. + r"""
  4285. where :attr:`input` and :attr:`other` are finite. Where :attr:`input`
  4286. and/or :attr:`other` are nonfinite they are close if and only if
  4287. they are equal, with NaNs being considered equal to each other when
  4288. :attr:`equal_nan` is True.
  4289. Args:
  4290. input (Tensor): first tensor to compare
  4291. other (Tensor): second tensor to compare
  4292. rtol (float, optional): relative tolerance. Default: 1e-05
  4293. atol (float, optional): absolute tolerance. Default: 1e-08
  4294. equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False``
  4295. Examples::
  4296. >>> torch.isclose(torch.tensor((1., 2, 3)), torch.tensor((1 + 1e-10, 3, 4)))
  4297. tensor([ True, False, False])
  4298. >>> torch.isclose(torch.tensor((float('inf'), 4)), torch.tensor((float('inf'), 6)), rtol=.5)
  4299. tensor([True, True])
  4300. """,
  4301. )
  4302. add_docstr(
  4303. torch.isfinite,
  4304. r"""
  4305. isfinite(input) -> Tensor
  4306. Returns a new tensor with boolean elements representing if each element is `finite` or not.
  4307. Real values are finite when they are not NaN, negative infinity, or infinity.
  4308. Complex values are finite when both their real and imaginary parts are finite.
  4309. Args:
  4310. {input}
  4311. Returns:
  4312. A boolean tensor that is True where :attr:`input` is finite and False elsewhere
  4313. Example::
  4314. >>> torch.isfinite(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')]))
  4315. tensor([True, False, True, False, False])
  4316. """.format(**common_args),
  4317. )
  4318. add_docstr(
  4319. torch.isnan,
  4320. r"""
  4321. isnan(input) -> Tensor
  4322. Returns a new tensor with boolean elements representing if each element of :attr:`input`
  4323. is NaN or not. Complex values are considered NaN when either their real
  4324. and/or imaginary part is NaN.
  4325. Arguments:
  4326. {input}
  4327. Returns:
  4328. A boolean tensor that is True where :attr:`input` is NaN and False elsewhere
  4329. Example::
  4330. >>> torch.isnan(torch.tensor([1, float('nan'), 2]))
  4331. tensor([False, True, False])
  4332. """.format(**common_args),
  4333. )
  4334. add_docstr(
  4335. torch.isreal,
  4336. r"""
  4337. isreal(input) -> Tensor
  4338. Returns a new tensor with boolean elements representing if each element of :attr:`input` is real-valued or not.
  4339. All real-valued types are considered real. Complex values are considered real when their imaginary part is 0.
  4340. Arguments:
  4341. {input}
  4342. Returns:
  4343. A boolean tensor that is True where :attr:`input` is real and False elsewhere
  4344. Example::
  4345. >>> torch.isreal(torch.tensor([1, 1+1j, 2+0j]))
  4346. tensor([True, False, True])
  4347. """.format(**common_args),
  4348. )
  4349. add_docstr(
  4350. torch.is_floating_point,
  4351. r"""
  4352. is_floating_point(input: Tensor) -> bool
  4353. Returns True if the data type of :attr:`input` is a floating point data type i.e.,
  4354. one of ``torch.float64``, ``torch.float32``, ``torch.float16``, and ``torch.bfloat16``.
  4355. Args:
  4356. {input}
  4357. Example::
  4358. >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0]))
  4359. True
  4360. >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.int32))
  4361. False
  4362. >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16))
  4363. True
  4364. >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.complex64))
  4365. False
  4366. """.format(**common_args),
  4367. )
  4368. add_docstr(
  4369. torch.is_complex,
  4370. r"""
  4371. is_complex(input: Tensor) -> bool
  4372. Returns True if the data type of :attr:`input` is a complex data type i.e.,
  4373. one of ``torch.complex64``, and ``torch.complex128``.
  4374. Args:
  4375. {input}
  4376. Example::
  4377. >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex64))
  4378. True
  4379. >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex128))
  4380. True
  4381. >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.int32))
  4382. False
  4383. >>> torch.is_complex(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16))
  4384. False
  4385. """.format(**common_args),
  4386. )
  4387. add_docstr(
  4388. torch.is_grad_enabled,
  4389. r"""
  4390. is_grad_enabled() -> (bool)
  4391. Returns True if grad mode is currently enabled.
  4392. """.format(**common_args),
  4393. )
  4394. add_docstr(
  4395. torch.is_inference_mode_enabled,
  4396. r"""
  4397. is_inference_mode_enabled() -> (bool)
  4398. Returns True if inference mode is currently enabled.
  4399. """.format(**common_args),
  4400. )
  4401. add_docstr(
  4402. torch.is_inference,
  4403. r"""
  4404. is_inference(input) -> (bool)
  4405. Returns True if :attr:`input` is an inference tensor.
  4406. A non-view tensor is an inference tensor if and only if it was
  4407. allocated during inference mode. A view tensor is an inference
  4408. tensor if and only if the tensor it is a view of is an inference tensor.
  4409. For details on inference mode please see
  4410. `Inference Mode <https://pytorch.org/cppdocs/notes/inference_mode.html>`_.
  4411. Args:
  4412. {input}
  4413. """.format(**common_args),
  4414. )
  4415. add_docstr(
  4416. torch.is_conj,
  4417. r"""
  4418. is_conj(input) -> (bool)
  4419. Returns True if the :attr:`input` is a conjugated tensor, i.e. its conjugate bit is set to `True`.
  4420. Args:
  4421. {input}
  4422. """.format(**common_args),
  4423. )
  4424. add_docstr(
  4425. torch.is_nonzero,
  4426. r"""
  4427. is_nonzero(input) -> (bool)
  4428. Returns True if the :attr:`input` is a single element tensor which is not equal to zero
  4429. after type conversions.
  4430. i.e. not equal to ``torch.tensor([0.])`` or ``torch.tensor([0])`` or
  4431. ``torch.tensor([False])``.
  4432. Throws a ``RuntimeError`` if ``torch.numel() != 1`` (even in case
  4433. of sparse tensors).
  4434. Args:
  4435. {input}
  4436. Examples::
  4437. >>> torch.is_nonzero(torch.tensor([0.]))
  4438. False
  4439. >>> torch.is_nonzero(torch.tensor([1.5]))
  4440. True
  4441. >>> torch.is_nonzero(torch.tensor([False]))
  4442. False
  4443. >>> torch.is_nonzero(torch.tensor([3]))
  4444. True
  4445. >>> torch.is_nonzero(torch.tensor([1, 3, 5]))
  4446. Traceback (most recent call last):
  4447. ...
  4448. RuntimeError: Boolean value of Tensor with more than one value is ambiguous
  4449. >>> torch.is_nonzero(torch.tensor([]))
  4450. Traceback (most recent call last):
  4451. ...
  4452. RuntimeError: Boolean value of Tensor with no values is ambiguous
  4453. """.format(**common_args),
  4454. )
  4455. add_docstr(
  4456. torch.kron,
  4457. r"""
  4458. kron(input, other, *, out=None) -> Tensor
  4459. Computes the Kronecker product, denoted by :math:`\otimes`, of :attr:`input` and :attr:`other`.
  4460. If :attr:`input` is a :math:`(a_0 \times a_1 \times \dots \times a_n)` tensor and :attr:`other` is a
  4461. :math:`(b_0 \times b_1 \times \dots \times b_n)` tensor, the result will be a
  4462. :math:`(a_0*b_0 \times a_1*b_1 \times \dots \times a_n*b_n)` tensor with the following entries:
  4463. .. math::
  4464. (\text{input} \otimes \text{other})_{k_0, k_1, \dots, k_n} =
  4465. \text{input}_{i_0, i_1, \dots, i_n} * \text{other}_{j_0, j_1, \dots, j_n},
  4466. where :math:`k_t = i_t * b_t + j_t` for :math:`0 \leq t \leq n`.
  4467. If one tensor has fewer dimensions than the other it is unsqueezed until it has the same number of dimensions.
  4468. Supports real-valued and complex-valued inputs.
  4469. .. note::
  4470. This function generalizes the typical definition of the Kronecker product for two matrices to two tensors,
  4471. as described above. When :attr:`input` is a :math:`(m \times n)` matrix and :attr:`other` is a
  4472. :math:`(p \times q)` matrix, the result will be a :math:`(p*m \times q*n)` block matrix:
  4473. .. math::
  4474. \mathbf{A} \otimes \mathbf{B}=\begin{bmatrix}
  4475. a_{11} \mathbf{B} & \cdots & a_{1 n} \mathbf{B} \\
  4476. \vdots & \ddots & \vdots \\
  4477. a_{m 1} \mathbf{B} & \cdots & a_{m n} \mathbf{B} \end{bmatrix}
  4478. where :attr:`input` is :math:`\mathbf{A}` and :attr:`other` is :math:`\mathbf{B}`.
  4479. Arguments:
  4480. input (Tensor)
  4481. other (Tensor)
  4482. Keyword args:
  4483. out (Tensor, optional): The output tensor. Ignored if ``None``. Default: ``None``
  4484. Examples::
  4485. >>> mat1 = torch.eye(2)
  4486. >>> mat2 = torch.ones(2, 2)
  4487. >>> torch.kron(mat1, mat2)
  4488. tensor([[1., 1., 0., 0.],
  4489. [1., 1., 0., 0.],
  4490. [0., 0., 1., 1.],
  4491. [0., 0., 1., 1.]])
  4492. >>> mat1 = torch.eye(2)
  4493. >>> mat2 = torch.arange(1, 5).reshape(2, 2)
  4494. >>> torch.kron(mat1, mat2)
  4495. tensor([[1., 2., 0., 0.],
  4496. [3., 4., 0., 0.],
  4497. [0., 0., 1., 2.],
  4498. [0., 0., 3., 4.]])
  4499. """,
  4500. )
  4501. add_docstr(
  4502. torch.kthvalue,
  4503. r"""
  4504. kthvalue(input, k, dim=None, keepdim=False, *, out=None) -> (Tensor, LongTensor)
  4505. Returns a namedtuple ``(values, indices)`` where ``values`` is the :attr:`k` th
  4506. smallest element of each row of the :attr:`input` tensor in the given dimension
  4507. :attr:`dim`. And ``indices`` is the index location of each element found.
  4508. If :attr:`dim` is not given, the last dimension of the `input` is chosen.
  4509. If :attr:`keepdim` is ``True``, both the :attr:`values` and :attr:`indices` tensors
  4510. are the same size as :attr:`input`, except in the dimension :attr:`dim` where
  4511. they are of size 1. Otherwise, :attr:`dim` is squeezed
  4512. (see :func:`torch.squeeze`), resulting in both the :attr:`values` and
  4513. :attr:`indices` tensors having 1 fewer dimension than the :attr:`input` tensor.
  4514. .. note::
  4515. When :attr:`input` is a CUDA tensor and there are multiple valid
  4516. :attr:`k` th values, this function may nondeterministically return
  4517. :attr:`indices` for any of them.
  4518. Args:
  4519. {input}
  4520. k (int): k for the k-th smallest element
  4521. dim (int, optional): the dimension to find the kth value along
  4522. {opt_keepdim}
  4523. Keyword args:
  4524. out (tuple, optional): the output tuple of (Tensor, LongTensor)
  4525. can be optionally given to be used as output buffers
  4526. Example::
  4527. >>> x = torch.arange(1., 6.)
  4528. >>> x
  4529. tensor([ 1., 2., 3., 4., 5.])
  4530. >>> torch.kthvalue(x, 4)
  4531. torch.return_types.kthvalue(values=tensor(4.), indices=tensor(3))
  4532. >>> x=torch.arange(1.,7.).resize_(2,3)
  4533. >>> x
  4534. tensor([[ 1., 2., 3.],
  4535. [ 4., 5., 6.]])
  4536. >>> torch.kthvalue(x, 2, 0, True)
  4537. torch.return_types.kthvalue(values=tensor([[4., 5., 6.]]), indices=tensor([[1, 1, 1]]))
  4538. """.format(**single_dim_common),
  4539. )
  4540. add_docstr(
  4541. torch.lcm,
  4542. r"""
  4543. lcm(input, other, *, out=None) -> Tensor
  4544. Computes the element-wise least common multiple (LCM) of :attr:`input` and :attr:`other`.
  4545. Both :attr:`input` and :attr:`other` must have integer types.
  4546. .. note::
  4547. This defines :math:`lcm(0, 0) = 0` and :math:`lcm(0, a) = 0`.
  4548. Args:
  4549. {input}
  4550. other (Tensor): the second input tensor
  4551. Keyword arguments:
  4552. {out}
  4553. Example::
  4554. >>> a = torch.tensor([5, 10, 15])
  4555. >>> b = torch.tensor([3, 4, 5])
  4556. >>> torch.lcm(a, b)
  4557. tensor([15, 20, 15])
  4558. >>> c = torch.tensor([3])
  4559. >>> torch.lcm(a, c)
  4560. tensor([15, 30, 15])
  4561. """.format(**common_args),
  4562. )
  4563. add_docstr(
  4564. torch.ldexp,
  4565. r"""
  4566. ldexp(input, other, *, out=None) -> Tensor
  4567. Multiplies :attr:`input` by 2 ** :attr:`other`.
  4568. .. math::
  4569. \text{{out}}_i = \text{{input}}_i * 2^\text{{other}}_i
  4570. """
  4571. + r"""
  4572. Typically this function is used to construct floating point numbers by multiplying
  4573. mantissas in :attr:`input` with integral powers of two created from the exponents
  4574. in :attr:`other`.
  4575. Args:
  4576. {input}
  4577. other (Tensor): a tensor of exponents, typically integers.
  4578. Keyword args:
  4579. {out}
  4580. Example::
  4581. >>> torch.ldexp(torch.tensor([1.]), torch.tensor([1]))
  4582. tensor([2.])
  4583. >>> torch.ldexp(torch.tensor([1.0]), torch.tensor([1, 2, 3, 4]))
  4584. tensor([ 2., 4., 8., 16.])
  4585. """.format(**common_args),
  4586. )
  4587. add_docstr(
  4588. torch.le,
  4589. r"""
  4590. le(input, other, *, out=None) -> Tensor
  4591. Computes :math:`\text{input} \leq \text{other}` element-wise.
  4592. """
  4593. + r"""
  4594. The second argument can be a number or a tensor whose shape is
  4595. :ref:`broadcastable <broadcasting-semantics>` with the first argument.
  4596. Args:
  4597. input (Tensor): the tensor to compare
  4598. other (Tensor or Scalar): the tensor or value to compare
  4599. Keyword args:
  4600. {out}
  4601. Returns:
  4602. A boolean tensor that is True where :attr:`input` is less than or equal to
  4603. :attr:`other` and False elsewhere
  4604. Example::
  4605. >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
  4606. tensor([[True, False], [True, True]])
  4607. """.format(**common_args),
  4608. )
  4609. add_docstr(
  4610. torch.less_equal,
  4611. r"""
  4612. less_equal(input, other, *, out=None) -> Tensor
  4613. Alias for :func:`torch.le`.
  4614. """,
  4615. )
  4616. add_docstr(
  4617. torch.lerp,
  4618. r"""
  4619. lerp(input, end, weight, *, out=None)
  4620. Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based
  4621. on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor.
  4622. .. math::
  4623. \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i)
  4624. """
  4625. + r"""
  4626. The shapes of :attr:`start` and :attr:`end` must be
  4627. :ref:`broadcastable <broadcasting-semantics>`. If :attr:`weight` is a tensor, then
  4628. the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable <broadcasting-semantics>`.
  4629. Args:
  4630. input (Tensor): the tensor with the starting points
  4631. end (Tensor): the tensor with the ending points
  4632. weight (float or tensor): the weight for the interpolation formula
  4633. Keyword args:
  4634. {out}
  4635. Example::
  4636. >>> start = torch.arange(1., 5.)
  4637. >>> end = torch.empty(4).fill_(10)
  4638. >>> start
  4639. tensor([ 1., 2., 3., 4.])
  4640. >>> end
  4641. tensor([ 10., 10., 10., 10.])
  4642. >>> torch.lerp(start, end, 0.5)
  4643. tensor([ 5.5000, 6.0000, 6.5000, 7.0000])
  4644. >>> torch.lerp(start, end, torch.full_like(start, 0.5))
  4645. tensor([ 5.5000, 6.0000, 6.5000, 7.0000])
  4646. """.format(**common_args),
  4647. )
  4648. add_docstr(
  4649. torch.lgamma,
  4650. r"""
  4651. lgamma(input, *, out=None) -> Tensor
  4652. Computes the natural logarithm of the absolute value of the gamma function on :attr:`input`.
  4653. .. math::
  4654. \text{out}_{i} = \ln |\Gamma(\text{input}_{i})|
  4655. """
  4656. + """
  4657. Args:
  4658. {input}
  4659. Keyword args:
  4660. {out}
  4661. Example::
  4662. >>> a = torch.arange(0.5, 2, 0.5)
  4663. >>> torch.lgamma(a)
  4664. tensor([ 0.5724, 0.0000, -0.1208])
  4665. """.format(**common_args),
  4666. )
  4667. add_docstr(
  4668. torch.linspace,
  4669. r"""
  4670. linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
  4671. Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly
  4672. spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are:
  4673. .. math::
  4674. (\text{start},
  4675. \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1},
  4676. \ldots,
  4677. \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1},
  4678. \text{end})
  4679. """
  4680. + """
  4681. From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior.
  4682. Args:
  4683. start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional
  4684. end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional
  4685. steps (int): size of the constructed tensor
  4686. Keyword arguments:
  4687. {out}
  4688. dtype (torch.dtype, optional): the data type to perform the computation in.
  4689. Default: if None, uses the global default dtype (see torch.get_default_dtype())
  4690. when both :attr:`start` and :attr:`end` are real,
  4691. and corresponding complex dtype when either is complex.
  4692. {layout}
  4693. {device}
  4694. {requires_grad}
  4695. Example::
  4696. >>> torch.linspace(3, 10, steps=5)
  4697. tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000])
  4698. >>> torch.linspace(-10, 10, steps=5)
  4699. tensor([-10., -5., 0., 5., 10.])
  4700. >>> torch.linspace(start=-10, end=10, steps=5)
  4701. tensor([-10., -5., 0., 5., 10.])
  4702. >>> torch.linspace(start=-10, end=10, steps=1)
  4703. tensor([-10.])
  4704. """.format(**factory_common_args),
  4705. )
  4706. add_docstr(
  4707. torch.log,
  4708. r"""
  4709. log(input, *, out=None) -> Tensor
  4710. Returns a new tensor with the natural logarithm of the elements
  4711. of :attr:`input`.
  4712. .. math::
  4713. y_{i} = \log_{e} (x_{i})
  4714. """
  4715. + r"""
  4716. Args:
  4717. {input}
  4718. Keyword args:
  4719. {out}
  4720. Example::
  4721. >>> a = torch.rand(5) * 5
  4722. >>> a
  4723. tensor([4.7767, 4.3234, 1.2156, 0.2411, 4.5739])
  4724. >>> torch.log(a)
  4725. tensor([ 1.5637, 1.4640, 0.1952, -1.4226, 1.5204])
  4726. """.format(**common_args),
  4727. )
  4728. add_docstr(
  4729. torch.log10,
  4730. r"""
  4731. log10(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  4732. Returns a new tensor with the logarithm to the base 10 of the elements
  4733. of :attr:`input`.
  4734. .. math::
  4735. y_{i} = \log_{10} (x_{i})
  4736. """
  4737. + r"""
  4738. Args:
  4739. {input}
  4740. Keyword args:
  4741. {out}
  4742. Example::
  4743. >>> a = torch.rand(5)
  4744. >>> a
  4745. tensor([ 0.5224, 0.9354, 0.7257, 0.1301, 0.2251])
  4746. >>> torch.log10(a)
  4747. tensor([-0.2820, -0.0290, -0.1392, -0.8857, -0.6476])
  4748. """.format(**common_args),
  4749. )
  4750. add_docstr(
  4751. torch.log1p,
  4752. r"""
  4753. log1p(input, *, out=None) -> Tensor
  4754. Returns a new tensor with the natural logarithm of (1 + :attr:`input`).
  4755. .. math::
  4756. y_i = \log_{e} (x_i + 1)
  4757. """
  4758. + r"""
  4759. .. note:: This function is more accurate than :func:`torch.log` for small
  4760. values of :attr:`input`
  4761. Args:
  4762. {input}
  4763. Keyword args:
  4764. {out}
  4765. Example::
  4766. >>> a = torch.randn(5)
  4767. >>> a
  4768. tensor([-1.0090, -0.9923, 1.0249, -0.5372, 0.2492])
  4769. >>> torch.log1p(a)
  4770. tensor([ nan, -4.8653, 0.7055, -0.7705, 0.2225])
  4771. """.format(**common_args),
  4772. )
  4773. add_docstr(
  4774. torch.log2,
  4775. r"""
  4776. log2(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  4777. Returns a new tensor with the logarithm to the base 2 of the elements
  4778. of :attr:`input`.
  4779. .. math::
  4780. y_{i} = \log_{2} (x_{i})
  4781. """
  4782. + r"""
  4783. Args:
  4784. {input}
  4785. Keyword args:
  4786. {out}
  4787. Example::
  4788. >>> a = torch.rand(5)
  4789. >>> a
  4790. tensor([ 0.8419, 0.8003, 0.9971, 0.5287, 0.0490])
  4791. >>> torch.log2(a)
  4792. tensor([-0.2483, -0.3213, -0.0042, -0.9196, -4.3504])
  4793. """.format(**common_args),
  4794. )
  4795. add_docstr(
  4796. torch.logaddexp,
  4797. r"""
  4798. logaddexp(input, other, *, out=None) -> Tensor
  4799. Logarithm of the sum of exponentiations of the inputs.
  4800. Calculates pointwise :math:`\log\left(e^x + e^y\right)`. This function is useful
  4801. in statistics where the calculated probabilities of events may be so small as to
  4802. exceed the range of normal floating point numbers. In such cases the logarithm
  4803. of the calculated probability is stored. This function allows adding
  4804. probabilities stored in such a fashion.
  4805. This op should be disambiguated with :func:`torch.logsumexp` which performs a
  4806. reduction on a single tensor.
  4807. Args:
  4808. {input}
  4809. other (Tensor): the second input tensor
  4810. Keyword arguments:
  4811. {out}
  4812. Example::
  4813. >>> torch.logaddexp(torch.tensor([-1.0]), torch.tensor([-1.0, -2, -3]))
  4814. tensor([-0.3069, -0.6867, -0.8731])
  4815. >>> torch.logaddexp(torch.tensor([-100.0, -200, -300]), torch.tensor([-1.0, -2, -3]))
  4816. tensor([-1., -2., -3.])
  4817. >>> torch.logaddexp(torch.tensor([1.0, 2000, 30000]), torch.tensor([-1.0, -2, -3]))
  4818. tensor([1.1269e+00, 2.0000e+03, 3.0000e+04])
  4819. """.format(**common_args),
  4820. )
  4821. add_docstr(
  4822. torch.logaddexp2,
  4823. r"""
  4824. logaddexp2(input, other, *, out=None) -> Tensor
  4825. Logarithm of the sum of exponentiations of the inputs in base-2.
  4826. Calculates pointwise :math:`\log_2\left(2^x + 2^y\right)`. See
  4827. :func:`torch.logaddexp` for more details.
  4828. Args:
  4829. {input}
  4830. other (Tensor): the second input tensor
  4831. Keyword arguments:
  4832. {out}
  4833. """.format(**common_args),
  4834. )
  4835. add_docstr(
  4836. torch.xlogy,
  4837. r"""
  4838. xlogy(input, other, *, out=None) -> Tensor
  4839. Alias for :func:`torch.special.xlogy`.
  4840. """,
  4841. )
  4842. add_docstr(
  4843. torch.logical_and,
  4844. r"""
  4845. logical_and(input, other, *, out=None) -> Tensor
  4846. Computes the element-wise logical AND of the given input tensors. Zeros are treated as ``False`` and nonzeros are
  4847. treated as ``True``.
  4848. Args:
  4849. {input}
  4850. other (Tensor): the tensor to compute AND with
  4851. Keyword args:
  4852. {out}
  4853. Example::
  4854. >>> torch.logical_and(torch.tensor([True, False, True]), torch.tensor([True, False, False]))
  4855. tensor([ True, False, False])
  4856. >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8)
  4857. >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8)
  4858. >>> torch.logical_and(a, b)
  4859. tensor([False, False, True, False])
  4860. >>> torch.logical_and(a.double(), b.double())
  4861. tensor([False, False, True, False])
  4862. >>> torch.logical_and(a.double(), b)
  4863. tensor([False, False, True, False])
  4864. >>> torch.logical_and(a, b, out=torch.empty(4, dtype=torch.bool))
  4865. tensor([False, False, True, False])
  4866. """.format(**common_args),
  4867. )
  4868. add_docstr(
  4869. torch.logical_not,
  4870. r"""
  4871. logical_not(input, *, out=None) -> Tensor
  4872. Computes the element-wise logical NOT of the given input tensor. If not specified, the output tensor will have the bool
  4873. dtype. If the input tensor is not a bool tensor, zeros are treated as ``False`` and non-zeros are treated as ``True``.
  4874. Args:
  4875. {input}
  4876. Keyword args:
  4877. {out}
  4878. Example::
  4879. >>> torch.logical_not(torch.tensor([True, False]))
  4880. tensor([False, True])
  4881. >>> torch.logical_not(torch.tensor([0, 1, -10], dtype=torch.int8))
  4882. tensor([ True, False, False])
  4883. >>> torch.logical_not(torch.tensor([0., 1.5, -10.], dtype=torch.double))
  4884. tensor([ True, False, False])
  4885. >>> torch.logical_not(torch.tensor([0., 1., -10.], dtype=torch.double), out=torch.empty(3, dtype=torch.int16))
  4886. tensor([1, 0, 0], dtype=torch.int16)
  4887. """.format(**common_args),
  4888. )
  4889. add_docstr(
  4890. torch.logical_or,
  4891. r"""
  4892. logical_or(input, other, *, out=None) -> Tensor
  4893. Computes the element-wise logical OR of the given input tensors. Zeros are treated as ``False`` and nonzeros are
  4894. treated as ``True``.
  4895. Args:
  4896. {input}
  4897. other (Tensor): the tensor to compute OR with
  4898. Keyword args:
  4899. {out}
  4900. Example::
  4901. >>> torch.logical_or(torch.tensor([True, False, True]), torch.tensor([True, False, False]))
  4902. tensor([ True, False, True])
  4903. >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8)
  4904. >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8)
  4905. >>> torch.logical_or(a, b)
  4906. tensor([ True, True, True, False])
  4907. >>> torch.logical_or(a.double(), b.double())
  4908. tensor([ True, True, True, False])
  4909. >>> torch.logical_or(a.double(), b)
  4910. tensor([ True, True, True, False])
  4911. >>> torch.logical_or(a, b, out=torch.empty(4, dtype=torch.bool))
  4912. tensor([ True, True, True, False])
  4913. """.format(**common_args),
  4914. )
  4915. add_docstr(
  4916. torch.logical_xor,
  4917. r"""
  4918. logical_xor(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor
  4919. Computes the element-wise logical XOR of the given input tensors. Zeros are treated as ``False`` and nonzeros are
  4920. treated as ``True``.
  4921. Args:
  4922. {input}
  4923. other (Tensor): the tensor to compute XOR with
  4924. Keyword args:
  4925. {out}
  4926. Example::
  4927. >>> torch.logical_xor(torch.tensor([True, False, True]), torch.tensor([True, False, False]))
  4928. tensor([False, False, True])
  4929. >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8)
  4930. >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8)
  4931. >>> torch.logical_xor(a, b)
  4932. tensor([ True, True, False, False])
  4933. >>> torch.logical_xor(a.double(), b.double())
  4934. tensor([ True, True, False, False])
  4935. >>> torch.logical_xor(a.double(), b)
  4936. tensor([ True, True, False, False])
  4937. >>> torch.logical_xor(a, b, out=torch.empty(4, dtype=torch.bool))
  4938. tensor([ True, True, False, False])
  4939. """.format(**common_args),
  4940. )
  4941. add_docstr(
  4942. torch.logspace,
  4943. """
  4944. logspace(start, end, steps, base=10.0, *, \
  4945. out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
  4946. """
  4947. + r"""
  4948. Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly
  4949. spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to
  4950. :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale
  4951. with base :attr:`base`. That is, the values are:
  4952. .. math::
  4953. (\text{base}^{\text{start}},
  4954. \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})},
  4955. \ldots,
  4956. \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})},
  4957. \text{base}^{\text{end}})
  4958. """
  4959. + """
  4960. From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior.
  4961. Args:
  4962. start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional
  4963. end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional
  4964. steps (int): size of the constructed tensor
  4965. base (float, optional): base of the logarithm function. Default: ``10.0``.
  4966. Keyword arguments:
  4967. {out}
  4968. dtype (torch.dtype, optional): the data type to perform the computation in.
  4969. Default: if None, uses the global default dtype (see torch.get_default_dtype())
  4970. when both :attr:`start` and :attr:`end` are real,
  4971. and corresponding complex dtype when either is complex.
  4972. {layout}
  4973. {device}
  4974. {requires_grad}
  4975. Example::
  4976. >>> torch.logspace(start=-10, end=10, steps=5)
  4977. tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10])
  4978. >>> torch.logspace(start=0.1, end=1.0, steps=5)
  4979. tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000])
  4980. >>> torch.logspace(start=0.1, end=1.0, steps=1)
  4981. tensor([1.2589])
  4982. >>> torch.logspace(start=2, end=2, steps=1, base=2)
  4983. tensor([4.0])
  4984. """.format(**factory_common_args),
  4985. )
  4986. add_docstr(
  4987. torch.logsumexp,
  4988. r"""
  4989. logsumexp(input, dim, keepdim=False, *, out=None)
  4990. Returns the log of summed exponentials of each row of the :attr:`input`
  4991. tensor in the given dimension :attr:`dim`. The computation is numerically
  4992. stabilized.
  4993. For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is
  4994. .. math::
  4995. \text{{logsumexp}}(x)_{{i}} = \log \sum_j \exp(x_{{ij}})
  4996. {keepdim_details}
  4997. Args:
  4998. {input}
  4999. {dim}
  5000. {opt_keepdim}
  5001. Keyword args:
  5002. {out}
  5003. Example::
  5004. >>> a = torch.randn(3, 3)
  5005. >>> torch.logsumexp(a, 1)
  5006. tensor([1.4907, 1.0593, 1.5696])
  5007. >>> torch.dist(torch.logsumexp(a, 1), torch.log(torch.sum(torch.exp(a), 1)))
  5008. tensor(1.6859e-07)
  5009. """.format(**multi_dim_common),
  5010. )
  5011. add_docstr(
  5012. torch.lt,
  5013. r"""
  5014. lt(input, other, *, out=None) -> Tensor
  5015. Computes :math:`\text{input} < \text{other}` element-wise.
  5016. """
  5017. + r"""
  5018. The second argument can be a number or a tensor whose shape is
  5019. :ref:`broadcastable <broadcasting-semantics>` with the first argument.
  5020. Args:
  5021. input (Tensor): the tensor to compare
  5022. other (Tensor or float): the tensor or value to compare
  5023. Keyword args:
  5024. {out}
  5025. Returns:
  5026. A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere
  5027. Example::
  5028. >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
  5029. tensor([[False, False], [True, False]])
  5030. """.format(**common_args),
  5031. )
  5032. add_docstr(
  5033. torch.lu_unpack,
  5034. r"""
  5035. lu_unpack(LU_data, LU_pivots, unpack_data=True, unpack_pivots=True, *, out=None) -> (Tensor, Tensor, Tensor)
  5036. Unpacks the LU decomposition returned by :func:`~linalg.lu_factor` into the `P, L, U` matrices.
  5037. .. seealso::
  5038. :func:`~linalg.lu` returns the matrices from the LU decomposition. Its gradient formula is more efficient
  5039. than that of doing :func:`~linalg.lu_factor` followed by :func:`~linalg.lu_unpack`.
  5040. Args:
  5041. LU_data (Tensor): the packed LU factorization data
  5042. LU_pivots (Tensor): the packed LU factorization pivots
  5043. unpack_data (bool): flag indicating if the data should be unpacked.
  5044. If ``False``, then the returned ``L`` and ``U`` are empty tensors.
  5045. Default: ``True``
  5046. unpack_pivots (bool): flag indicating if the pivots should be unpacked into a permutation matrix ``P``.
  5047. If ``False``, then the returned ``P`` is an empty tensor.
  5048. Default: ``True``
  5049. Keyword args:
  5050. out (tuple, optional): output tuple of three tensors. Ignored if `None`.
  5051. Returns:
  5052. A namedtuple ``(P, L, U)``
  5053. Examples::
  5054. >>> A = torch.randn(2, 3, 3)
  5055. >>> LU, pivots = torch.linalg.lu_factor(A)
  5056. >>> P, L, U = torch.lu_unpack(LU, pivots)
  5057. >>> # We can recover A from the factorization
  5058. >>> A_ = P @ L @ U
  5059. >>> torch.allclose(A, A_)
  5060. True
  5061. >>> # LU factorization of a rectangular matrix:
  5062. >>> A = torch.randn(2, 3, 2)
  5063. >>> LU, pivots = torch.linalg.lu_factor(A)
  5064. >>> P, L, U = torch.lu_unpack(LU, pivots)
  5065. >>> # P, L, U are the same as returned by linalg.lu
  5066. >>> P_, L_, U_ = torch.linalg.lu(A)
  5067. >>> torch.allclose(P, P_) and torch.allclose(L, L_) and torch.allclose(U, U_)
  5068. True
  5069. """.format(**common_args),
  5070. )
  5071. add_docstr(
  5072. torch.less,
  5073. r"""
  5074. less(input, other, *, out=None) -> Tensor
  5075. Alias for :func:`torch.lt`.
  5076. """,
  5077. )
  5078. add_docstr(
  5079. torch.lu_solve,
  5080. r"""
  5081. lu_solve(b, LU_data, LU_pivots, *, out=None) -> Tensor
  5082. Returns the LU solve of the linear system :math:`Ax = b` using the partially pivoted
  5083. LU factorization of A from :func:`~linalg.lu_factor`.
  5084. This function supports ``float``, ``double``, ``cfloat`` and ``cdouble`` dtypes for :attr:`input`.
  5085. .. warning::
  5086. :func:`torch.lu_solve` is deprecated in favor of :func:`torch.linalg.lu_solve`.
  5087. :func:`torch.lu_solve` will be removed in a future PyTorch release.
  5088. ``X = torch.lu_solve(B, LU, pivots)`` should be replaced with
  5089. .. code:: python
  5090. X = linalg.lu_solve(LU, pivots, B)
  5091. Arguments:
  5092. b (Tensor): the RHS tensor of size :math:`(*, m, k)`, where :math:`*`
  5093. is zero or more batch dimensions.
  5094. LU_data (Tensor): the pivoted LU factorization of A from :meth:`~linalg.lu_factor` of size :math:`(*, m, m)`,
  5095. where :math:`*` is zero or more batch dimensions.
  5096. LU_pivots (IntTensor): the pivots of the LU factorization from :meth:`~linalg.lu_factor` of size :math:`(*, m)`,
  5097. where :math:`*` is zero or more batch dimensions.
  5098. The batch dimensions of :attr:`LU_pivots` must be equal to the batch dimensions of
  5099. :attr:`LU_data`.
  5100. Keyword args:
  5101. {out}
  5102. Example::
  5103. >>> A = torch.randn(2, 3, 3)
  5104. >>> b = torch.randn(2, 3, 1)
  5105. >>> LU, pivots = torch.linalg.lu_factor(A)
  5106. >>> x = torch.lu_solve(b, LU, pivots)
  5107. >>> torch.dist(A @ x, b)
  5108. tensor(1.00000e-07 *
  5109. 2.8312)
  5110. """.format(**common_args),
  5111. )
  5112. add_docstr(
  5113. torch.masked_select,
  5114. r"""
  5115. masked_select(input, mask, *, out=None) -> Tensor
  5116. Returns a new 1-D tensor which indexes the :attr:`input` tensor according to
  5117. the boolean mask :attr:`mask` which is a `BoolTensor`.
  5118. The shapes of the :attr:`mask` tensor and the :attr:`input` tensor don't need
  5119. to match, but they must be :ref:`broadcastable <broadcasting-semantics>`.
  5120. .. note:: The returned tensor does **not** use the same storage
  5121. as the original tensor
  5122. Args:
  5123. {input}
  5124. mask (BoolTensor): the tensor containing the binary mask to index with
  5125. Keyword args:
  5126. {out}
  5127. Example::
  5128. >>> x = torch.randn(3, 4)
  5129. >>> x
  5130. tensor([[ 0.3552, -2.3825, -0.8297, 0.3477],
  5131. [-1.2035, 1.2252, 0.5002, 0.6248],
  5132. [ 0.1307, -2.0608, 0.1244, 2.0139]])
  5133. >>> mask = x.ge(0.5)
  5134. >>> mask
  5135. tensor([[False, False, False, False],
  5136. [False, True, True, True],
  5137. [False, False, False, True]])
  5138. >>> torch.masked_select(x, mask)
  5139. tensor([ 1.2252, 0.5002, 0.6248, 2.0139])
  5140. """.format(**common_args),
  5141. )
  5142. add_docstr(
  5143. torch.matrix_power,
  5144. r"""
  5145. matrix_power(input, n, *, out=None) -> Tensor
  5146. Alias for :func:`torch.linalg.matrix_power`
  5147. """,
  5148. )
  5149. add_docstr(
  5150. torch.matrix_exp,
  5151. r"""
  5152. matrix_exp(A) -> Tensor
  5153. Alias for :func:`torch.linalg.matrix_exp`.
  5154. """,
  5155. )
  5156. add_docstr(
  5157. torch.max,
  5158. r"""
  5159. max(input, *, out=None) -> Tensor
  5160. Returns the maximum value of all elements in the ``input`` tensor.
  5161. .. note::
  5162. The difference between ``max``/``min`` and ``amax``/``amin`` is:
  5163. - ``amax``/``amin`` supports reducing on multiple dimensions,
  5164. - ``amax``/``amin`` does not return indices.
  5165. Both ``amax``/``amin`` evenly distribute gradients between equal values
  5166. when there are multiple input elements with the same minimum or maximum value.
  5167. For ``max``/``min``:
  5168. - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values.
  5169. - If reduce over one specified axis, only propagate to the indexed element.
  5170. Args:
  5171. {input}
  5172. Keyword args:
  5173. {out}
  5174. Example::
  5175. >>> a = torch.randn(1, 3)
  5176. >>> a
  5177. tensor([[ 0.6763, 0.7445, -2.2369]])
  5178. >>> torch.max(a)
  5179. tensor(0.7445)
  5180. .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor)
  5181. :noindex:
  5182. Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum
  5183. value of each row of the :attr:`input` tensor in the given dimension
  5184. :attr:`dim`. And ``indices`` is the index location of each maximum value found
  5185. (argmax).
  5186. If ``keepdim`` is ``True``, the output tensors are of the same size
  5187. as ``input`` except in the dimension ``dim`` where they are of size 1.
  5188. Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting
  5189. in the output tensors having 1 fewer dimension than ``input``.
  5190. .. note:: If there are multiple maximal values in a reduced row then
  5191. the indices of the first maximal value are returned.
  5192. Args:
  5193. {input}
  5194. {opt_dim_without_none}
  5195. {opt_keepdim}
  5196. Keyword args:
  5197. out (tuple, optional): the result tuple of two output tensors (max, max_indices)
  5198. Example::
  5199. >>> a = torch.randn(4, 4)
  5200. >>> a
  5201. tensor([[-1.2360, -0.2942, -0.1222, 0.8475],
  5202. [ 1.1949, -1.1127, -2.2379, -0.6702],
  5203. [ 1.5717, -0.9207, 0.1297, -1.8768],
  5204. [-0.6172, 1.0036, -0.6060, -0.2432]])
  5205. >>> torch.max(a, 1)
  5206. torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1]))
  5207. >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
  5208. >>> a.max(dim=1, keepdim=True)
  5209. torch.return_types.max(
  5210. values=tensor([[2.], [4.]]),
  5211. indices=tensor([[1], [1]]))
  5212. >>> a.max(dim=1, keepdim=False)
  5213. torch.return_types.max(
  5214. values=tensor([2., 4.]),
  5215. indices=tensor([1, 1]))
  5216. .. function:: max(input, other, *, out=None) -> Tensor
  5217. :noindex:
  5218. See :func:`torch.maximum`.
  5219. """.format(**single_dim_common),
  5220. )
  5221. add_docstr(
  5222. torch.maximum,
  5223. r"""
  5224. maximum(input, other, *, out=None) -> Tensor
  5225. Computes the element-wise maximum of :attr:`input` and :attr:`other`.
  5226. .. note::
  5227. If one of the elements being compared is a NaN, then that element is returned.
  5228. :func:`maximum` is not supported for tensors with complex dtypes.
  5229. Args:
  5230. {input}
  5231. other (Tensor): the second input tensor
  5232. Keyword args:
  5233. {out}
  5234. Example::
  5235. >>> a = torch.tensor((1, 2, -1))
  5236. >>> b = torch.tensor((3, 0, 4))
  5237. >>> torch.maximum(a, b)
  5238. tensor([3, 2, 4])
  5239. """.format(**common_args),
  5240. )
  5241. add_docstr(
  5242. torch.fmax,
  5243. r"""
  5244. fmax(input, other, *, out=None) -> Tensor
  5245. Computes the element-wise maximum of :attr:`input` and :attr:`other`.
  5246. This is like :func:`torch.maximum` except it handles NaNs differently:
  5247. if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the maximum.
  5248. Only if both elements are NaN is NaN propagated.
  5249. This function is a wrapper around C++'s ``std::fmax`` and is similar to NumPy's ``fmax`` function.
  5250. Supports :ref:`broadcasting to a common shape <broadcasting-semantics>`,
  5251. :ref:`type promotion <type-promotion-doc>`, and integer and floating-point inputs.
  5252. Args:
  5253. {input}
  5254. other (Tensor): the second input tensor
  5255. Keyword args:
  5256. {out}
  5257. Example::
  5258. >>> a = torch.tensor([9.7, float('nan'), 3.1, float('nan')])
  5259. >>> b = torch.tensor([-2.2, 0.5, float('nan'), float('nan')])
  5260. >>> torch.fmax(a, b)
  5261. tensor([9.7000, 0.5000, 3.1000, nan])
  5262. """.format(**common_args),
  5263. )
  5264. add_docstr(
  5265. torch.amax,
  5266. r"""
  5267. amax(input, dim, keepdim=False, *, out=None) -> Tensor
  5268. Returns the maximum value of each slice of the :attr:`input` tensor in the given
  5269. dimension(s) :attr:`dim`.
  5270. .. note::
  5271. The difference between ``max``/``min`` and ``amax``/``amin`` is:
  5272. - ``amax``/``amin`` supports reducing on multiple dimensions,
  5273. - ``amax``/``amin`` does not return indices.
  5274. Both ``amax``/``amin`` evenly distribute gradients between equal values
  5275. when there are multiple input elements with the same minimum or maximum value.
  5276. For ``max``/``min``:
  5277. - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values.
  5278. - If reduce over one specified axis, only propagate to the indexed element.
  5279. {keepdim_details}
  5280. Args:
  5281. {input}
  5282. {opt_dim_all_reduce}
  5283. {opt_keepdim}
  5284. Keyword args:
  5285. {out}
  5286. Example::
  5287. >>> a = torch.randn(4, 4)
  5288. >>> a
  5289. tensor([[ 0.8177, 1.4878, -0.2491, 0.9130],
  5290. [-0.7158, 1.1775, 2.0992, 0.4817],
  5291. [-0.0053, 0.0164, -1.3738, -0.0507],
  5292. [ 1.9700, 1.1106, -1.0318, -1.0816]])
  5293. >>> torch.amax(a, 1)
  5294. tensor([1.4878, 2.0992, 0.0164, 1.9700])
  5295. """.format(**multi_dim_common),
  5296. )
  5297. add_docstr(
  5298. torch.argmax,
  5299. r"""
  5300. argmax(input) -> LongTensor
  5301. Returns the indices of the maximum value of all elements in the :attr:`input` tensor.
  5302. This is the second value returned by :meth:`torch.max`. See its
  5303. documentation for the exact semantics of this method.
  5304. .. note:: If there are multiple maximal values then the indices of the first maximal value are returned.
  5305. Args:
  5306. {input}
  5307. Example::
  5308. >>> a = torch.randn(4, 4)
  5309. >>> a
  5310. tensor([[ 1.3398, 0.2663, -0.2686, 0.2450],
  5311. [-0.7401, -0.8805, -0.3402, -1.1936],
  5312. [ 0.4907, -1.3948, -1.0691, -0.3132],
  5313. [-1.6092, 0.5419, -0.2993, 0.3195]])
  5314. >>> torch.argmax(a)
  5315. tensor(0)
  5316. .. function:: argmax(input, dim, keepdim=False) -> LongTensor
  5317. :noindex:
  5318. Returns the indices of the maximum values of a tensor across a dimension.
  5319. This is the second value returned by :meth:`torch.max`. See its
  5320. documentation for the exact semantics of this method.
  5321. Args:
  5322. {input}
  5323. {opt_dim} If ``None``, the argmax of the flattened input is returned.
  5324. {opt_keepdim}
  5325. Example::
  5326. >>> a = torch.randn(4, 4)
  5327. >>> a
  5328. tensor([[ 1.3398, 0.2663, -0.2686, 0.2450],
  5329. [-0.7401, -0.8805, -0.3402, -1.1936],
  5330. [ 0.4907, -1.3948, -1.0691, -0.3132],
  5331. [-1.6092, 0.5419, -0.2993, 0.3195]])
  5332. >>> torch.argmax(a, dim=1)
  5333. tensor([ 0, 2, 0, 1])
  5334. """.format(**single_dim_common),
  5335. )
  5336. add_docstr(
  5337. torch.argwhere,
  5338. r"""
  5339. argwhere(input) -> Tensor
  5340. Returns a tensor containing the indices of all non-zero elements of
  5341. :attr:`input`. Each row in the result contains the indices of a non-zero
  5342. element in :attr:`input`. The result is sorted lexicographically, with
  5343. the last index changing the fastest (C-style).
  5344. If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor
  5345. :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of
  5346. non-zero elements in the :attr:`input` tensor.
  5347. .. note::
  5348. This function is similar to NumPy's `argwhere`.
  5349. When :attr:`input` is on CUDA, this function causes host-device synchronization.
  5350. Args:
  5351. {input}
  5352. Example::
  5353. >>> t = torch.tensor([1, 0, 1])
  5354. >>> torch.argwhere(t)
  5355. tensor([[0],
  5356. [2]])
  5357. >>> t = torch.tensor([[1, 0, 1], [0, 1, 1]])
  5358. >>> torch.argwhere(t)
  5359. tensor([[0, 0],
  5360. [0, 2],
  5361. [1, 1],
  5362. [1, 2]])
  5363. """,
  5364. )
  5365. add_docstr(
  5366. torch.mean,
  5367. r"""
  5368. mean(input, *, dtype=None) -> Tensor
  5369. .. note::
  5370. If the `input` tensor is empty, ``torch.mean()`` returns ``nan``.
  5371. This behavior is consistent with NumPy and follows the definition
  5372. that the mean over an empty set is undefined.
  5373. Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex.
  5374. Args:
  5375. input (Tensor):
  5376. the input tensor, either of floating point or complex dtype
  5377. Keyword args:
  5378. {dtype}
  5379. Example::
  5380. >>> a = torch.randn(1, 3)
  5381. >>> a
  5382. tensor([[ 0.2294, -0.5481, 1.3288]])
  5383. >>> torch.mean(a)
  5384. tensor(0.3367)
  5385. .. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor
  5386. :noindex:
  5387. Returns the mean value of each row of the :attr:`input` tensor in the given
  5388. dimension :attr:`dim`. If :attr:`dim` is a list of dimensions,
  5389. reduce over all of them.
  5390. {keepdim_details}
  5391. Args:
  5392. {input}
  5393. {opt_dim_all_reduce}
  5394. {opt_keepdim}
  5395. Keyword args:
  5396. {dtype}
  5397. {out}
  5398. .. seealso::
  5399. :func:`torch.nanmean` computes the mean value of `non-NaN` elements.
  5400. Example::
  5401. >>> a = torch.randn(4, 4)
  5402. >>> a
  5403. tensor([[-0.3841, 0.6320, 0.4254, -0.7384],
  5404. [-0.9644, 1.0131, -0.6549, -1.4279],
  5405. [-0.2951, -1.3350, -0.7694, 0.5600],
  5406. [ 1.0842, -0.9580, 0.3623, 0.2343]])
  5407. >>> torch.mean(a, 1)
  5408. tensor([-0.0163, -0.5085, -0.4599, 0.1807])
  5409. >>> torch.mean(a, 1, True)
  5410. tensor([[-0.0163],
  5411. [-0.5085],
  5412. [-0.4599],
  5413. [ 0.1807]])
  5414. """.format(**multi_dim_common),
  5415. )
  5416. add_docstr(
  5417. torch.nanmean,
  5418. r"""
  5419. nanmean(input, dim=None, keepdim=False, *, dtype=None, out=None) -> Tensor
  5420. Computes the mean of all `non-NaN` elements along the specified dimensions.
  5421. Input must be floating point or complex.
  5422. This function is identical to :func:`torch.mean` when there are no `NaN` values
  5423. in the :attr:`input` tensor. In the presence of `NaN`, :func:`torch.mean` will
  5424. propagate the `NaN` to the output whereas :func:`torch.nanmean` will ignore the
  5425. `NaN` values (`torch.nanmean(a)` is equivalent to `torch.mean(a[~a.isnan()])`).
  5426. {keepdim_details}
  5427. Args:
  5428. input (Tensor): the input tensor, either of floating point or complex dtype
  5429. {opt_dim_all_reduce}
  5430. {opt_keepdim}
  5431. Keyword args:
  5432. {dtype}
  5433. {out}
  5434. .. seealso::
  5435. :func:`torch.mean` computes the mean value, propagating `NaN`.
  5436. Example::
  5437. >>> x = torch.tensor([[torch.nan, 1, 2], [1, 2, 3]])
  5438. >>> x.mean()
  5439. tensor(nan)
  5440. >>> x.nanmean()
  5441. tensor(1.8000)
  5442. >>> x.mean(dim=0)
  5443. tensor([ nan, 1.5000, 2.5000])
  5444. >>> x.nanmean(dim=0)
  5445. tensor([1.0000, 1.5000, 2.5000])
  5446. # If all elements in the reduced dimensions are NaN then the result is NaN
  5447. >>> torch.tensor([torch.nan]).nanmean()
  5448. tensor(nan)
  5449. """.format(**multi_dim_common),
  5450. )
  5451. add_docstr(
  5452. torch.median,
  5453. r"""
  5454. median(input) -> Tensor
  5455. Returns the median of the values in :attr:`input`.
  5456. .. note::
  5457. The median is not unique for :attr:`input` tensors with an even number
  5458. of elements. In this case the lower of the two medians is returned. To
  5459. compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead.
  5460. .. warning::
  5461. This function produces deterministic (sub)gradients unlike ``median(dim=0)``
  5462. Args:
  5463. {input}
  5464. Example::
  5465. >>> a = torch.randn(1, 3)
  5466. >>> a
  5467. tensor([[ 1.5219, -1.5212, 0.2202]])
  5468. >>> torch.median(a)
  5469. tensor(0.2202)
  5470. .. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor)
  5471. :noindex:
  5472. Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input`
  5473. in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`.
  5474. By default, :attr:`dim` is the last dimension of the :attr:`input` tensor.
  5475. If :attr:`keepdim` is ``True``, the output tensors are of the same size
  5476. as :attr:`input` except in the dimension :attr:`dim` where they are of size 1.
  5477. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in
  5478. the outputs tensor having 1 fewer dimension than :attr:`input`.
  5479. .. note::
  5480. The median is not unique for :attr:`input` tensors with an even number
  5481. of elements in the dimension :attr:`dim`. In this case the lower of the
  5482. two medians is returned. To compute the mean of both medians in
  5483. :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead.
  5484. .. warning::
  5485. ``indices`` does not necessarily contain the first occurrence of each
  5486. median value found, unless it is unique.
  5487. The exact implementation details are device-specific.
  5488. Do not expect the same result when run on CPU and GPU in general.
  5489. For the same reason do not expect the gradients to be deterministic.
  5490. Args:
  5491. {input}
  5492. {opt_dim_all_reduce}
  5493. {opt_keepdim}
  5494. Keyword args:
  5495. out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second
  5496. tensor, which must have dtype long, with their indices in the dimension
  5497. :attr:`dim` of :attr:`input`.
  5498. Example::
  5499. >>> a = torch.randn(4, 5)
  5500. >>> a
  5501. tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131],
  5502. [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270],
  5503. [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488],
  5504. [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]])
  5505. >>> torch.median(a, 1)
  5506. torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3]))
  5507. """.format(**single_dim_common),
  5508. )
  5509. add_docstr(
  5510. torch.nanmedian,
  5511. r"""
  5512. nanmedian(input) -> Tensor
  5513. Returns the median of the values in :attr:`input`, ignoring ``NaN`` values.
  5514. This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`.
  5515. When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``,
  5516. while this function will return the median of the non-``NaN`` elements in :attr:`input`.
  5517. If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``.
  5518. Args:
  5519. {input}
  5520. Example::
  5521. >>> a = torch.tensor([1, float('nan'), 3, 2])
  5522. >>> a.median()
  5523. tensor(nan)
  5524. >>> a.nanmedian()
  5525. tensor(2.)
  5526. .. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor)
  5527. :noindex:
  5528. Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input`
  5529. in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values
  5530. found in the dimension :attr:`dim`.
  5531. This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has
  5532. one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the
  5533. median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too.
  5534. Args:
  5535. {input}
  5536. {opt_dim_all_reduce}
  5537. {opt_keepdim}
  5538. Keyword args:
  5539. out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second
  5540. tensor, which must have dtype long, with their indices in the dimension
  5541. :attr:`dim` of :attr:`input`.
  5542. Example::
  5543. >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]])
  5544. >>> a
  5545. tensor([[2., 3., 1.],
  5546. [nan, 1., nan]])
  5547. >>> a.median(0)
  5548. torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1]))
  5549. >>> a.nanmedian(0)
  5550. torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0]))
  5551. """.format(**single_dim_common),
  5552. )
  5553. add_docstr(
  5554. torch.quantile,
  5555. r"""
  5556. quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor
  5557. Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`.
  5558. To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location
  5559. of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with
  5560. indices ``i`` and ``j`` in the sorted order, result is computed according to the given
  5561. :attr:`interpolation` method as follows:
  5562. - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index.
  5563. - ``lower``: ``a``.
  5564. - ``higher``: ``b``.
  5565. - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`).
  5566. - ``midpoint``: ``(a + b) / 2``.
  5567. If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size
  5568. equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction.
  5569. .. note::
  5570. By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation.
  5571. Args:
  5572. {input}
  5573. q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1].
  5574. {opt_dim}
  5575. {opt_keepdim}
  5576. Keyword arguments:
  5577. interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points.
  5578. Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``.
  5579. Default is ``linear``.
  5580. {out}
  5581. Example::
  5582. >>> a = torch.randn(2, 3)
  5583. >>> a
  5584. tensor([[ 0.0795, -1.2117, 0.9765],
  5585. [ 1.1707, 0.6706, 0.4884]])
  5586. >>> q = torch.tensor([0.25, 0.5, 0.75])
  5587. >>> torch.quantile(a, q, dim=1, keepdim=True)
  5588. tensor([[[-0.5661],
  5589. [ 0.5795]],
  5590. [[ 0.0795],
  5591. [ 0.6706]],
  5592. [[ 0.5280],
  5593. [ 0.9206]]])
  5594. >>> torch.quantile(a, q, dim=1, keepdim=True).shape
  5595. torch.Size([3, 2, 1])
  5596. >>> a = torch.arange(4.)
  5597. >>> a
  5598. tensor([0., 1., 2., 3.])
  5599. >>> torch.quantile(a, 0.6, interpolation='linear')
  5600. tensor(1.8000)
  5601. >>> torch.quantile(a, 0.6, interpolation='lower')
  5602. tensor(1.)
  5603. >>> torch.quantile(a, 0.6, interpolation='higher')
  5604. tensor(2.)
  5605. >>> torch.quantile(a, 0.6, interpolation='midpoint')
  5606. tensor(1.5000)
  5607. >>> torch.quantile(a, 0.6, interpolation='nearest')
  5608. tensor(2.)
  5609. >>> torch.quantile(a, 0.4, interpolation='nearest')
  5610. tensor(1.)
  5611. """.format(**single_dim_common),
  5612. )
  5613. add_docstr(
  5614. torch.nanquantile,
  5615. r"""
  5616. nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor
  5617. This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values,
  5618. computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did
  5619. not exist. If all values in a reduced row are ``NaN`` then the quantiles for
  5620. that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`.
  5621. Args:
  5622. {input}
  5623. q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1]
  5624. {opt_dim_all_reduce}
  5625. {opt_keepdim}
  5626. Keyword arguments:
  5627. interpolation (str): interpolation method to use when the desired quantile lies between two data points.
  5628. Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``.
  5629. Default is ``linear``.
  5630. {out}
  5631. Example::
  5632. >>> t = torch.tensor([float('nan'), 1, 2])
  5633. >>> t.quantile(0.5)
  5634. tensor(nan)
  5635. >>> t.nanquantile(0.5)
  5636. tensor(1.5000)
  5637. >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]])
  5638. >>> t
  5639. tensor([[nan, nan],
  5640. [1., 2.]])
  5641. >>> t.nanquantile(0.5, dim=0)
  5642. tensor([1., 2.])
  5643. >>> t.nanquantile(0.5, dim=1)
  5644. tensor([ nan, 1.5000])
  5645. """.format(**single_dim_common),
  5646. )
  5647. add_docstr(
  5648. torch.min,
  5649. r"""
  5650. min(input, *, out=None) -> Tensor
  5651. Returns the minimum value of all elements in the :attr:`input` tensor.
  5652. .. note::
  5653. The difference between ``max``/``min`` and ``amax``/``amin`` is:
  5654. - ``amax``/``amin`` supports reducing on multiple dimensions,
  5655. - ``amax``/``amin`` does not return indices.
  5656. Both ``amax``/``amin`` evenly distribute gradients between equal values
  5657. when there are multiple input elements with the same minimum or maximum value.
  5658. For ``max``/``min``:
  5659. - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values.
  5660. - If reduce over one specified axis, only propagate to the indexed element.
  5661. Args:
  5662. {input}
  5663. Keyword args:
  5664. {out}
  5665. Example::
  5666. >>> a = torch.randn(1, 3)
  5667. >>> a
  5668. tensor([[ 0.6750, 1.0857, 1.7197]])
  5669. >>> torch.min(a)
  5670. tensor(0.6750)
  5671. .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor)
  5672. :noindex:
  5673. Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum
  5674. value of each row of the :attr:`input` tensor in the given dimension
  5675. :attr:`dim`. And ``indices`` is the index location of each minimum value found
  5676. (argmin).
  5677. If :attr:`keepdim` is ``True``, the output tensors are of the same size as
  5678. :attr:`input` except in the dimension :attr:`dim` where they are of size 1.
  5679. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in
  5680. the output tensors having 1 fewer dimension than :attr:`input`.
  5681. .. note:: If there are multiple minimal values in a reduced row then
  5682. the indices of the first minimal value are returned.
  5683. Args:
  5684. {input}
  5685. {opt_dim_without_none}
  5686. {opt_keepdim}
  5687. Keyword args:
  5688. out (tuple, optional): the tuple of two output tensors (min, min_indices)
  5689. Example::
  5690. >>> a = torch.randn(4, 4)
  5691. >>> a
  5692. tensor([[-0.6248, 1.1334, -1.1899, -0.2803],
  5693. [-1.4644, -0.2635, -0.3651, 0.6134],
  5694. [ 0.2457, 0.0384, 1.0128, 0.7015],
  5695. [-0.1153, 2.9849, 2.1458, 0.5788]])
  5696. >>> torch.min(a, 1)
  5697. torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0]))
  5698. .. function:: min(input, other, *, out=None) -> Tensor
  5699. :noindex:
  5700. See :func:`torch.minimum`.
  5701. """.format(**single_dim_common),
  5702. )
  5703. add_docstr(
  5704. torch.minimum,
  5705. r"""
  5706. minimum(input, other, *, out=None) -> Tensor
  5707. Computes the element-wise minimum of :attr:`input` and :attr:`other`.
  5708. .. note::
  5709. If one of the elements being compared is a NaN, then that element is returned.
  5710. :func:`minimum` is not supported for tensors with complex dtypes.
  5711. Args:
  5712. {input}
  5713. other (Tensor): the second input tensor
  5714. Keyword args:
  5715. {out}
  5716. Example::
  5717. >>> a = torch.tensor((1, 2, -1))
  5718. >>> b = torch.tensor((3, 0, 4))
  5719. >>> torch.minimum(a, b)
  5720. tensor([1, 0, -1])
  5721. """.format(**common_args),
  5722. )
  5723. add_docstr(
  5724. torch.fmin,
  5725. r"""
  5726. fmin(input, other, *, out=None) -> Tensor
  5727. Computes the element-wise minimum of :attr:`input` and :attr:`other`.
  5728. This is like :func:`torch.minimum` except it handles NaNs differently:
  5729. if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the minimum.
  5730. Only if both elements are NaN is NaN propagated.
  5731. This function is a wrapper around C++'s ``std::fmin`` and is similar to NumPy's ``fmin`` function.
  5732. Supports :ref:`broadcasting to a common shape <broadcasting-semantics>`,
  5733. :ref:`type promotion <type-promotion-doc>`, and integer and floating-point inputs.
  5734. Args:
  5735. {input}
  5736. other (Tensor): the second input tensor
  5737. Keyword args:
  5738. {out}
  5739. Example::
  5740. >>> a = torch.tensor([2.2, float('nan'), 2.1, float('nan')])
  5741. >>> b = torch.tensor([-9.3, 0.1, float('nan'), float('nan')])
  5742. >>> torch.fmin(a, b)
  5743. tensor([-9.3000, 0.1000, 2.1000, nan])
  5744. """.format(**common_args),
  5745. )
  5746. add_docstr(
  5747. torch.amin,
  5748. r"""
  5749. amin(input, dim, keepdim=False, *, out=None) -> Tensor
  5750. Returns the minimum value of each slice of the :attr:`input` tensor in the given
  5751. dimension(s) :attr:`dim`.
  5752. .. note::
  5753. The difference between ``max``/``min`` and ``amax``/``amin`` is:
  5754. - ``amax``/``amin`` supports reducing on multiple dimensions,
  5755. - ``amax``/``amin`` does not return indices.
  5756. Both ``amax``/``amin`` evenly distribute gradients between equal values
  5757. when there are multiple input elements with the same minimum or maximum value.
  5758. For ``max``/``min``:
  5759. - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values.
  5760. - If reduce over one specified axis, only propagate to the indexed element.
  5761. {keepdim_details}
  5762. Args:
  5763. {input}
  5764. {opt_dim_all_reduce}
  5765. {opt_keepdim}
  5766. Keyword args:
  5767. {out}
  5768. Example::
  5769. >>> a = torch.randn(4, 4)
  5770. >>> a
  5771. tensor([[ 0.6451, -0.4866, 0.2987, -1.3312],
  5772. [-0.5744, 1.2980, 1.8397, -0.2713],
  5773. [ 0.9128, 0.9214, -1.7268, -0.2995],
  5774. [ 0.9023, 0.4853, 0.9075, -1.6165]])
  5775. >>> torch.amin(a, 1)
  5776. tensor([-1.3312, -0.5744, -1.7268, -1.6165])
  5777. """.format(**multi_dim_common),
  5778. )
  5779. add_docstr(
  5780. torch.aminmax,
  5781. r"""
  5782. aminmax(input, *, dim=None, keepdim=False, out=None) -> (Tensor min, Tensor max)
  5783. Computes the minimum and maximum values of the :attr:`input` tensor.
  5784. Args:
  5785. input (Tensor):
  5786. The input tensor
  5787. Keyword Args:
  5788. dim (Optional[int]):
  5789. The dimension along which to compute the values. If `None`,
  5790. computes the values over the entire :attr:`input` tensor.
  5791. Default is `None`.
  5792. keepdim (bool):
  5793. If `True`, the reduced dimensions will be kept in the output
  5794. tensor as dimensions with size 1 for broadcasting, otherwise
  5795. they will be removed, as if calling (:func:`torch.squeeze`).
  5796. Default is `False`.
  5797. out (Optional[Tuple[Tensor, Tensor]]):
  5798. Optional tensors on which to write the result. Must have the same
  5799. shape and dtype as the expected output.
  5800. Default is `None`.
  5801. Returns:
  5802. A named tuple `(min, max)` containing the minimum and maximum values.
  5803. Raises:
  5804. RuntimeError
  5805. If any of the dimensions to compute the values over has size 0.
  5806. .. note::
  5807. NaN values are propagated to the output if at least one value is NaN.
  5808. .. seealso::
  5809. :func:`torch.amin` computes just the minimum value
  5810. :func:`torch.amax` computes just the maximum value
  5811. Example::
  5812. >>> torch.aminmax(torch.tensor([1, -3, 5]))
  5813. torch.return_types.aminmax(
  5814. min=tensor(-3),
  5815. max=tensor(5))
  5816. >>> # aminmax propagates NaNs
  5817. >>> torch.aminmax(torch.tensor([1, -3, 5, torch.nan]))
  5818. torch.return_types.aminmax(
  5819. min=tensor(nan),
  5820. max=tensor(nan))
  5821. >>> t = torch.arange(10).view(2, 5)
  5822. >>> t
  5823. tensor([[0, 1, 2, 3, 4],
  5824. [5, 6, 7, 8, 9]])
  5825. >>> t.aminmax(dim=0, keepdim=True)
  5826. torch.return_types.aminmax(
  5827. min=tensor([[0, 1, 2, 3, 4]]),
  5828. max=tensor([[5, 6, 7, 8, 9]]))
  5829. """,
  5830. )
  5831. add_docstr(
  5832. torch.argmin,
  5833. r"""
  5834. argmin(input, dim=None, keepdim=False) -> LongTensor
  5835. Returns the indices of the minimum value(s) of the flattened tensor or along a dimension
  5836. This is the second value returned by :meth:`torch.min`. See its
  5837. documentation for the exact semantics of this method.
  5838. .. note:: If there are multiple minimal values then the indices of the first minimal value are returned.
  5839. Args:
  5840. {input}
  5841. {opt_dim} If ``None``, the argmin of the flattened input is returned.
  5842. {opt_keepdim}
  5843. Example::
  5844. >>> a = torch.randn(4, 4)
  5845. >>> a
  5846. tensor([[ 0.1139, 0.2254, -0.1381, 0.3687],
  5847. [ 1.0100, -1.1975, -0.0102, -0.4732],
  5848. [-0.9240, 0.1207, -0.7506, -1.0213],
  5849. [ 1.7809, -1.2960, 0.9384, 0.1438]])
  5850. >>> torch.argmin(a)
  5851. tensor(13)
  5852. >>> torch.argmin(a, dim=1)
  5853. tensor([ 2, 1, 3, 1])
  5854. >>> torch.argmin(a, dim=1, keepdim=True)
  5855. tensor([[2],
  5856. [1],
  5857. [3],
  5858. [1]])
  5859. """.format(**single_dim_common),
  5860. )
  5861. add_docstr(
  5862. torch.mm,
  5863. r"""
  5864. mm(input, mat2, out_dtype=None, *, out=None) -> Tensor
  5865. Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`.
  5866. If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a
  5867. :math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor.
  5868. .. note:: This function does not :ref:`broadcast <broadcasting-semantics>`.
  5869. For broadcasting matrix products, see :func:`torch.matmul`.
  5870. Supports strided and sparse 2-D tensors as inputs, autograd with
  5871. respect to strided inputs.
  5872. This operation has support for arguments with :ref:`sparse layouts<sparse-docs>`.
  5873. If :attr:`out` is provided its layout will be used. Otherwise, the result
  5874. layout will be deduced from that of :attr:`input`.
  5875. {sparse_beta_warning}
  5876. {tf32_note}
  5877. {rocm_fp16_note}
  5878. Args:
  5879. input (Tensor): the first matrix to be matrix multiplied
  5880. mat2 (Tensor): the second matrix to be matrix multiplied
  5881. out_dtype (dtype, optional): the dtype of the output tensor,
  5882. Supported only on CUDA and for torch.float32 given
  5883. torch.float16/torch.bfloat16 input dtypes
  5884. Keyword args:
  5885. {out}
  5886. Example::
  5887. >>> mat1 = torch.randn(2, 3)
  5888. >>> mat2 = torch.randn(3, 3)
  5889. >>> torch.mm(mat1, mat2)
  5890. tensor([[ 0.4851, 0.5037, -0.3633],
  5891. [-0.0760, -3.6705, 2.4784]])
  5892. """.format(**common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes),
  5893. )
  5894. add_docstr(
  5895. torch.hspmm,
  5896. r"""
  5897. hspmm(mat1, mat2, *, out=None) -> Tensor
  5898. Performs a matrix multiplication of a :ref:`sparse COO matrix
  5899. <sparse-coo-docs>` :attr:`mat1` and a strided matrix :attr:`mat2`. The
  5900. result is a (1 + 1)-dimensional :ref:`hybrid COO matrix
  5901. <sparse-hybrid-coo-docs>`.
  5902. Args:
  5903. mat1 (Tensor): the first sparse matrix to be matrix multiplied
  5904. mat2 (Tensor): the second strided matrix to be matrix multiplied
  5905. Keyword args:
  5906. {out}
  5907. """.format(**common_args),
  5908. )
  5909. add_docstr(
  5910. torch.matmul,
  5911. r"""
  5912. matmul(input, other, *, out=None) -> Tensor
  5913. Matrix product of two tensors.
  5914. The behavior depends on the dimensionality of the tensors as follows:
  5915. - If both tensors are 1-dimensional, the dot product (scalar) is returned.
  5916. - If both arguments are 2-dimensional, the matrix-matrix product is returned.
  5917. - If the first argument is 1-dimensional and the second argument is 2-dimensional,
  5918. a 1 is prepended to its dimension for the purpose of the matrix multiply.
  5919. After the matrix multiply, the prepended dimension is removed.
  5920. - If the first argument is 2-dimensional and the second argument is 1-dimensional,
  5921. the matrix-vector product is returned.
  5922. - If both arguments are at least 1-dimensional and at least one argument is
  5923. N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first
  5924. argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the
  5925. batched matrix multiply and removed after. If the second argument is 1-dimensional, a
  5926. 1 is appended to its dimension for the purpose of the batched matrix multiply and removed after.
  5927. The first N-2 dimensions of each argument, the batch dimensions, are
  5928. :ref:`broadcast <broadcasting-semantics>` (and thus must be broadcastable).
  5929. The last 2, the matrix dimensions, are handled as in the matrix-matrix product.
  5930. For example, if :attr:`input` is a
  5931. :math:`(j \times 1 \times n \times m)` tensor and :attr:`other` is a :math:`(k \times m \times p)`
  5932. tensor, the batch dimensions are :math:`(j \times 1)` and :math:`(k)`,
  5933. and the matrix dimensions are :math:`(n \times m)` and :math:`(m \times p)`.
  5934. :attr:`out` will be a :math:`(j \times k \times n \times p)` tensor.
  5935. This operation has support for arguments with :ref:`sparse layouts<sparse-docs>`. In particular the
  5936. matrix-matrix (both arguments 2-dimensional) supports sparse arguments with the same restrictions
  5937. as :func:`torch.mm`
  5938. {sparse_beta_warning}
  5939. {tf32_note}
  5940. {rocm_fp16_note}
  5941. .. note::
  5942. The 1-dimensional dot product version of this function does not support an :attr:`out` parameter.
  5943. Arguments:
  5944. input (Tensor): the first tensor to be multiplied
  5945. other (Tensor): the second tensor to be multiplied
  5946. Keyword args:
  5947. {out}
  5948. Example::
  5949. >>> # vector x vector
  5950. >>> tensor1 = torch.randn(3)
  5951. >>> tensor2 = torch.randn(3)
  5952. >>> torch.matmul(tensor1, tensor2).size()
  5953. torch.Size([])
  5954. >>> # matrix x vector
  5955. >>> tensor1 = torch.randn(3, 4)
  5956. >>> tensor2 = torch.randn(4)
  5957. >>> torch.matmul(tensor1, tensor2).size()
  5958. torch.Size([3])
  5959. >>> # batched matrix x broadcasted vector
  5960. >>> tensor1 = torch.randn(10, 3, 4)
  5961. >>> tensor2 = torch.randn(4)
  5962. >>> torch.matmul(tensor1, tensor2).size()
  5963. torch.Size([10, 3])
  5964. >>> # batched matrix x batched matrix
  5965. >>> tensor1 = torch.randn(10, 3, 4)
  5966. >>> tensor2 = torch.randn(10, 4, 5)
  5967. >>> torch.matmul(tensor1, tensor2).size()
  5968. torch.Size([10, 3, 5])
  5969. >>> # batched matrix x broadcasted matrix
  5970. >>> tensor1 = torch.randn(10, 3, 4)
  5971. >>> tensor2 = torch.randn(4, 5)
  5972. >>> torch.matmul(tensor1, tensor2).size()
  5973. torch.Size([10, 3, 5])
  5974. """.format(**common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes),
  5975. )
  5976. add_docstr(
  5977. torch.mode,
  5978. r"""
  5979. mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor)
  5980. Returns a namedtuple ``(values, indices)`` where ``values`` is the mode
  5981. value of each row of the :attr:`input` tensor in the given dimension
  5982. :attr:`dim`, i.e. a value which appears most often
  5983. in that row, and ``indices`` is the index location of each mode value found.
  5984. By default, :attr:`dim` is the last dimension of the :attr:`input` tensor.
  5985. If :attr:`keepdim` is ``True``, the output tensors are of the same size as
  5986. :attr:`input` except in the dimension :attr:`dim` where they are of size 1.
  5987. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting
  5988. in the output tensors having 1 fewer dimension than :attr:`input`.
  5989. Args:
  5990. {input}
  5991. {opt_dim}
  5992. {opt_keepdim}
  5993. Keyword args:
  5994. out (tuple, optional): the result tuple of two output tensors (values, indices)
  5995. Example::
  5996. >>> b = torch.tensor([[0, 0, 0, 2, 0, 0, 2],
  5997. ... [0, 3, 0, 0, 2, 0, 1],
  5998. ... [2, 2, 2, 0, 0, 0, 3],
  5999. ... [2, 2, 3, 0, 1, 1, 0],
  6000. ... [1, 1, 0, 0, 2, 0, 2]])
  6001. >>> torch.mode(b, 0)
  6002. torch.return_types.mode(
  6003. values=tensor([0, 2, 0, 0, 0, 0, 2]),
  6004. indices=tensor([1, 3, 4, 4, 2, 4, 4]))
  6005. """.format(**single_dim_common),
  6006. )
  6007. add_docstr(
  6008. torch.mul,
  6009. r"""
  6010. mul(input, other, *, out=None) -> Tensor
  6011. Multiplies :attr:`input` by :attr:`other`.
  6012. .. math::
  6013. \text{out}_i = \text{input}_i \times \text{other}_i
  6014. """
  6015. + r"""
  6016. Supports :ref:`broadcasting to a common shape <broadcasting-semantics>`,
  6017. :ref:`type promotion <type-promotion-doc>`, and integer, float, and complex inputs.
  6018. Args:
  6019. {input}
  6020. other (Tensor or Number): the tensor or number to multiply input by.
  6021. Keyword args:
  6022. {out}
  6023. Examples::
  6024. >>> a = torch.randn(3)
  6025. >>> a
  6026. tensor([ 0.2015, -0.4255, 2.6087])
  6027. >>> torch.mul(a, 100)
  6028. tensor([ 20.1494, -42.5491, 260.8663])
  6029. >>> b = torch.randn(4, 1)
  6030. >>> b
  6031. tensor([[ 1.1207],
  6032. [-0.3137],
  6033. [ 0.0700],
  6034. [ 0.8378]])
  6035. >>> c = torch.randn(1, 4)
  6036. >>> c
  6037. tensor([[ 0.5146, 0.1216, -0.5244, 2.2382]])
  6038. >>> torch.mul(b, c)
  6039. tensor([[ 0.5767, 0.1363, -0.5877, 2.5083],
  6040. [-0.1614, -0.0382, 0.1645, -0.7021],
  6041. [ 0.0360, 0.0085, -0.0367, 0.1567],
  6042. [ 0.4312, 0.1019, -0.4394, 1.8753]])
  6043. """.format(**common_args),
  6044. )
  6045. add_docstr(
  6046. torch.multiply,
  6047. r"""
  6048. multiply(input, other, *, out=None)
  6049. Alias for :func:`torch.mul`.
  6050. """,
  6051. )
  6052. add_docstr(
  6053. torch.multinomial,
  6054. r"""
  6055. multinomial(input, num_samples, replacement=False, *, generator=None, out=None) -> LongTensor
  6056. Returns a tensor where each row contains :attr:`num_samples` indices sampled
  6057. from the multinomial (a stricter definition would be multivariate,
  6058. refer to :class:`torch.distributions.multinomial.Multinomial` for more details)
  6059. probability distribution located in the corresponding row
  6060. of tensor :attr:`input`.
  6061. .. note::
  6062. The rows of :attr:`input` do not need to sum to one (in which case we use
  6063. the values as weights), but must be non-negative, finite and have
  6064. a non-zero sum.
  6065. Indices are ordered from left to right according to when each was sampled
  6066. (first samples are placed in first column).
  6067. If :attr:`input` is a vector, :attr:`out` is a vector of size :attr:`num_samples`.
  6068. If :attr:`input` is a matrix with `m` rows, :attr:`out` is an matrix of shape
  6069. :math:`(m \times \text{{num\_samples}})`.
  6070. If replacement is ``True``, samples are drawn with replacement.
  6071. If not, they are drawn without replacement, which means that when a
  6072. sample index is drawn for a row, it cannot be drawn again for that row.
  6073. .. note::
  6074. When drawn without replacement, :attr:`num_samples` must be lower than
  6075. number of non-zero elements in :attr:`input` (or the min number of non-zero
  6076. elements in each row of :attr:`input` if it is a matrix).
  6077. Args:
  6078. input (Tensor): the input tensor containing probabilities
  6079. num_samples (int): number of samples to draw
  6080. replacement (bool, optional): whether to draw with replacement or not
  6081. Keyword args:
  6082. {generator}
  6083. {out}
  6084. Example::
  6085. >>> weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights
  6086. >>> torch.multinomial(weights, 2)
  6087. tensor([1, 2])
  6088. >>> torch.multinomial(weights, 5) # ERROR!
  6089. RuntimeError: cannot sample n_sample > prob_dist.size(-1) samples without replacement
  6090. >>> torch.multinomial(weights, 4, replacement=True)
  6091. tensor([ 2, 1, 1, 1])
  6092. """.format(**common_args),
  6093. )
  6094. add_docstr(
  6095. torch.mv,
  6096. r"""
  6097. mv(input, vec, *, out=None) -> Tensor
  6098. Performs a matrix-vector product of the matrix :attr:`input` and the vector
  6099. :attr:`vec`.
  6100. If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of
  6101. size :math:`m`, :attr:`out` will be 1-D of size :math:`n`.
  6102. .. note:: This function does not :ref:`broadcast <broadcasting-semantics>`.
  6103. Args:
  6104. input (Tensor): matrix to be multiplied
  6105. vec (Tensor): vector to be multiplied
  6106. Keyword args:
  6107. {out}
  6108. Example::
  6109. >>> mat = torch.randn(2, 3)
  6110. >>> vec = torch.randn(3)
  6111. >>> torch.mv(mat, vec)
  6112. tensor([ 1.0404, -0.6361])
  6113. """.format(**common_args),
  6114. )
  6115. add_docstr(
  6116. torch.mvlgamma,
  6117. r"""
  6118. mvlgamma(input, p, *, out=None) -> Tensor
  6119. Alias for :func:`torch.special.multigammaln`.
  6120. """,
  6121. )
  6122. add_docstr(
  6123. torch.movedim,
  6124. r"""
  6125. movedim(input, source, destination) -> Tensor
  6126. Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source`
  6127. to the position(s) in :attr:`destination`.
  6128. Other dimensions of :attr:`input` that are not explicitly moved remain in
  6129. their original order and appear at the positions not specified in :attr:`destination`.
  6130. Args:
  6131. {input}
  6132. source (int or tuple of ints): Original positions of the dims to move. These must be unique.
  6133. destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique.
  6134. Examples::
  6135. >>> t = torch.randn(3,2,1)
  6136. >>> t
  6137. tensor([[[-0.3362],
  6138. [-0.8437]],
  6139. [[-0.9627],
  6140. [ 0.1727]],
  6141. [[ 0.5173],
  6142. [-0.1398]]])
  6143. >>> torch.movedim(t, 1, 0).shape
  6144. torch.Size([2, 3, 1])
  6145. >>> torch.movedim(t, 1, 0)
  6146. tensor([[[-0.3362],
  6147. [-0.9627],
  6148. [ 0.5173]],
  6149. [[-0.8437],
  6150. [ 0.1727],
  6151. [-0.1398]]])
  6152. >>> torch.movedim(t, (1, 2), (0, 1)).shape
  6153. torch.Size([2, 1, 3])
  6154. >>> torch.movedim(t, (1, 2), (0, 1))
  6155. tensor([[[-0.3362, -0.9627, 0.5173]],
  6156. [[-0.8437, 0.1727, -0.1398]]])
  6157. """.format(**common_args),
  6158. )
  6159. add_docstr(
  6160. torch.moveaxis,
  6161. r"""
  6162. moveaxis(input, source, destination) -> Tensor
  6163. Alias for :func:`torch.movedim`.
  6164. This function is equivalent to NumPy's moveaxis function.
  6165. Examples::
  6166. >>> t = torch.randn(3,2,1)
  6167. >>> t
  6168. tensor([[[-0.3362],
  6169. [-0.8437]],
  6170. [[-0.9627],
  6171. [ 0.1727]],
  6172. [[ 0.5173],
  6173. [-0.1398]]])
  6174. >>> torch.moveaxis(t, 1, 0).shape
  6175. torch.Size([2, 3, 1])
  6176. >>> torch.moveaxis(t, 1, 0)
  6177. tensor([[[-0.3362],
  6178. [-0.9627],
  6179. [ 0.5173]],
  6180. [[-0.8437],
  6181. [ 0.1727],
  6182. [-0.1398]]])
  6183. >>> torch.moveaxis(t, (1, 2), (0, 1)).shape
  6184. torch.Size([2, 1, 3])
  6185. >>> torch.moveaxis(t, (1, 2), (0, 1))
  6186. tensor([[[-0.3362, -0.9627, 0.5173]],
  6187. [[-0.8437, 0.1727, -0.1398]]])
  6188. """.format(**common_args),
  6189. )
  6190. add_docstr(
  6191. torch.swapdims,
  6192. r"""
  6193. swapdims(input, dim0, dim1) -> Tensor
  6194. Alias for :func:`torch.transpose`.
  6195. This function is equivalent to NumPy's swapaxes function.
  6196. Examples::
  6197. >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]])
  6198. >>> x
  6199. tensor([[[0, 1],
  6200. [2, 3]],
  6201. [[4, 5],
  6202. [6, 7]]])
  6203. >>> torch.swapdims(x, 0, 1)
  6204. tensor([[[0, 1],
  6205. [4, 5]],
  6206. [[2, 3],
  6207. [6, 7]]])
  6208. >>> torch.swapdims(x, 0, 2)
  6209. tensor([[[0, 4],
  6210. [2, 6]],
  6211. [[1, 5],
  6212. [3, 7]]])
  6213. """.format(**common_args),
  6214. )
  6215. add_docstr(
  6216. torch.swapaxes,
  6217. r"""
  6218. swapaxes(input, axis0, axis1) -> Tensor
  6219. Alias for :func:`torch.transpose`.
  6220. This function is equivalent to NumPy's swapaxes function.
  6221. Examples::
  6222. >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]])
  6223. >>> x
  6224. tensor([[[0, 1],
  6225. [2, 3]],
  6226. [[4, 5],
  6227. [6, 7]]])
  6228. >>> torch.swapaxes(x, 0, 1)
  6229. tensor([[[0, 1],
  6230. [4, 5]],
  6231. [[2, 3],
  6232. [6, 7]]])
  6233. >>> torch.swapaxes(x, 0, 2)
  6234. tensor([[[0, 4],
  6235. [2, 6]],
  6236. [[1, 5],
  6237. [3, 7]]])
  6238. """.format(**common_args),
  6239. )
  6240. add_docstr(
  6241. torch.narrow,
  6242. r"""
  6243. narrow(input, dim, start, length) -> Tensor
  6244. Returns a new tensor that is a narrowed version of :attr:`input` tensor. The
  6245. dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The
  6246. returned tensor and :attr:`input` tensor share the same underlying storage.
  6247. Args:
  6248. input (Tensor): the tensor to narrow
  6249. dim (int): the dimension along which to narrow
  6250. start (int or Tensor): index of the element to start the narrowed dimension
  6251. from. Can be negative, which means indexing from the end of `dim`. If
  6252. `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed)
  6253. length (int): length of the narrowed dimension, must be weakly positive
  6254. Example::
  6255. >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  6256. >>> torch.narrow(x, 0, 0, 2)
  6257. tensor([[ 1, 2, 3],
  6258. [ 4, 5, 6]])
  6259. >>> torch.narrow(x, 1, 1, 2)
  6260. tensor([[ 2, 3],
  6261. [ 5, 6],
  6262. [ 8, 9]])
  6263. >>> torch.narrow(x, -1, torch.tensor(-1), 1)
  6264. tensor([[3],
  6265. [6],
  6266. [9]])
  6267. """,
  6268. )
  6269. add_docstr(
  6270. torch.narrow_copy,
  6271. r"""
  6272. narrow_copy(input, dim, start, length, *, out=None) -> Tensor
  6273. Same as :meth:`Tensor.narrow` except this returns a copy rather
  6274. than shared storage. This is primarily for sparse tensors, which
  6275. do not have a shared-storage narrow method.
  6276. Args:
  6277. input (Tensor): the tensor to narrow
  6278. dim (int): the dimension along which to narrow
  6279. start (int): index of the element to start the narrowed dimension from. Can
  6280. be negative, which means indexing from the end of `dim`
  6281. length (int): length of the narrowed dimension, must be weakly positive
  6282. Keyword args:
  6283. {out}
  6284. Example::
  6285. >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  6286. >>> torch.narrow_copy(x, 0, 0, 2)
  6287. tensor([[ 1, 2, 3],
  6288. [ 4, 5, 6]])
  6289. >>> torch.narrow_copy(x, 1, 1, 2)
  6290. tensor([[ 2, 3],
  6291. [ 5, 6],
  6292. [ 8, 9]])
  6293. >>> s = torch.arange(16).reshape(2, 2, 2, 2).to_sparse(2)
  6294. >>> torch.narrow_copy(s, 0, 0, 1)
  6295. tensor(indices=tensor([[0, 0],
  6296. [0, 1]]),
  6297. values=tensor([[[0, 1],
  6298. [2, 3]],
  6299. [[4, 5],
  6300. [6, 7]]]),
  6301. size=(1, 2, 2, 2), nnz=2, layout=torch.sparse_coo)
  6302. .. seealso::
  6303. :func:`torch.narrow` for a non copy variant
  6304. """.format(**common_args),
  6305. )
  6306. add_docstr(
  6307. torch.nan_to_num,
  6308. r"""
  6309. nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None) -> Tensor
  6310. Replaces :literal:`NaN`, positive infinity, and negative infinity values in :attr:`input`
  6311. with the values specified by :attr:`nan`, :attr:`posinf`, and :attr:`neginf`, respectively.
  6312. By default, :literal:`NaN`\ s are replaced with zero, positive infinity is replaced with the
  6313. greatest finite value representable by :attr:`input`'s dtype, and negative infinity
  6314. is replaced with the least finite value representable by :attr:`input`'s dtype.
  6315. Args:
  6316. {input}
  6317. nan (Number, optional): the value to replace :literal:`NaN`\s with. Default is zero.
  6318. posinf (Number, optional): if a Number, the value to replace positive infinity values with.
  6319. If None, positive infinity values are replaced with the greatest finite value representable by :attr:`input`'s dtype.
  6320. Default is None.
  6321. neginf (Number, optional): if a Number, the value to replace negative infinity values with.
  6322. If None, negative infinity values are replaced with the lowest finite value representable by :attr:`input`'s dtype.
  6323. Default is None.
  6324. Keyword args:
  6325. {out}
  6326. Example::
  6327. >>> x = torch.tensor([float('nan'), float('inf'), -float('inf'), 3.14])
  6328. >>> torch.nan_to_num(x)
  6329. tensor([ 0.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00])
  6330. >>> torch.nan_to_num(x, nan=2.0)
  6331. tensor([ 2.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00])
  6332. >>> torch.nan_to_num(x, nan=2.0, posinf=1.0)
  6333. tensor([ 2.0000e+00, 1.0000e+00, -3.4028e+38, 3.1400e+00])
  6334. """.format(**common_args),
  6335. )
  6336. add_docstr(
  6337. torch.ne,
  6338. r"""
  6339. ne(input, other, *, out=None) -> Tensor
  6340. Computes :math:`\text{input} \neq \text{other}` element-wise.
  6341. """
  6342. + r"""
  6343. The second argument can be a number or a tensor whose shape is
  6344. :ref:`broadcastable <broadcasting-semantics>` with the first argument.
  6345. Args:
  6346. input (Tensor): the tensor to compare
  6347. other (Tensor or float): the tensor or value to compare
  6348. Keyword args:
  6349. {out}
  6350. Returns:
  6351. A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere
  6352. Example::
  6353. >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
  6354. tensor([[False, True], [True, False]])
  6355. """.format(**common_args),
  6356. )
  6357. add_docstr(
  6358. torch.not_equal,
  6359. r"""
  6360. not_equal(input, other, *, out=None) -> Tensor
  6361. Alias for :func:`torch.ne`.
  6362. """,
  6363. )
  6364. add_docstr(
  6365. torch.neg,
  6366. r"""
  6367. neg(input, *, out=None) -> Tensor
  6368. Returns a new tensor with the negative of the elements of :attr:`input`.
  6369. .. math::
  6370. \text{out} = -1 \times \text{input}
  6371. """
  6372. + r"""
  6373. Args:
  6374. {input}
  6375. Keyword args:
  6376. {out}
  6377. Example::
  6378. >>> a = torch.randn(5)
  6379. >>> a
  6380. tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940])
  6381. >>> torch.neg(a)
  6382. tensor([-0.0090, 0.2262, 0.0682, 0.2866, -0.3940])
  6383. """.format(**common_args),
  6384. )
  6385. add_docstr(
  6386. torch.negative,
  6387. r"""
  6388. negative(input, *, out=None) -> Tensor
  6389. Alias for :func:`torch.neg`
  6390. """,
  6391. )
  6392. add_docstr(
  6393. torch.nextafter,
  6394. r"""
  6395. nextafter(input, other, *, out=None) -> Tensor
  6396. Return the next floating-point value after :attr:`input` towards :attr:`other`, elementwise.
  6397. The shapes of ``input`` and ``other`` must be
  6398. :ref:`broadcastable <broadcasting-semantics>`.
  6399. Args:
  6400. input (Tensor): the first input tensor
  6401. other (Tensor): the second input tensor
  6402. Keyword args:
  6403. {out}
  6404. Example::
  6405. >>> eps = torch.finfo(torch.float32).eps
  6406. >>> torch.nextafter(torch.tensor([1.0, 2.0]), torch.tensor([2.0, 1.0])) == torch.tensor([eps + 1, 2 - eps])
  6407. tensor([True, True])
  6408. """.format(**common_args),
  6409. )
  6410. add_docstr(
  6411. torch.nonzero,
  6412. r"""
  6413. nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors
  6414. .. note::
  6415. :func:`torch.nonzero(..., as_tuple=False) <torch.nonzero>` (default) returns a
  6416. 2-D tensor where each row is the index for a nonzero value.
  6417. :func:`torch.nonzero(..., as_tuple=True) <torch.nonzero>` returns a tuple of 1-D
  6418. index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]``
  6419. gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor
  6420. contains nonzero indices for a certain dimension.
  6421. See below for more details on the two behaviors.
  6422. When :attr:`input` is on CUDA, :func:`torch.nonzero() <torch.nonzero>` causes
  6423. host-device synchronization.
  6424. **When** :attr:`as_tuple` **is** ``False`` **(default)**:
  6425. Returns a tensor containing the indices of all non-zero elements of
  6426. :attr:`input`. Each row in the result contains the indices of a non-zero
  6427. element in :attr:`input`. The result is sorted lexicographically, with
  6428. the last index changing the fastest (C-style).
  6429. If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor
  6430. :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of
  6431. non-zero elements in the :attr:`input` tensor.
  6432. **When** :attr:`as_tuple` **is** ``True``:
  6433. Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`,
  6434. each containing the indices (in that dimension) of all non-zero elements of
  6435. :attr:`input` .
  6436. If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n`
  6437. tensors of size :math:`z`, where :math:`z` is the total number of
  6438. non-zero elements in the :attr:`input` tensor.
  6439. As a special case, when :attr:`input` has zero dimensions and a nonzero scalar
  6440. value, it is treated as a one-dimensional tensor with one element.
  6441. Args:
  6442. {input}
  6443. Keyword args:
  6444. out (LongTensor, optional): the output tensor containing indices
  6445. Returns:
  6446. LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output
  6447. tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for
  6448. each dimension, containing the indices of each nonzero element along that
  6449. dimension.
  6450. Example::
  6451. >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]))
  6452. tensor([[ 0],
  6453. [ 1],
  6454. [ 2],
  6455. [ 4]])
  6456. >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0],
  6457. ... [0.0, 0.4, 0.0, 0.0],
  6458. ... [0.0, 0.0, 1.2, 0.0],
  6459. ... [0.0, 0.0, 0.0,-0.4]]))
  6460. tensor([[ 0, 0],
  6461. [ 1, 1],
  6462. [ 2, 2],
  6463. [ 3, 3]])
  6464. >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True)
  6465. (tensor([0, 1, 2, 4]),)
  6466. >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0],
  6467. ... [0.0, 0.4, 0.0, 0.0],
  6468. ... [0.0, 0.0, 1.2, 0.0],
  6469. ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True)
  6470. (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3]))
  6471. >>> torch.nonzero(torch.tensor(5), as_tuple=True)
  6472. (tensor([0]),)
  6473. """.format(**common_args),
  6474. )
  6475. add_docstr(
  6476. torch.normal,
  6477. r"""
  6478. normal(mean, std, *, generator=None, out=None) -> Tensor
  6479. Returns a tensor of random numbers drawn from separate normal distributions
  6480. whose mean and standard deviation are given.
  6481. The :attr:`mean` is a tensor with the mean of
  6482. each output element's normal distribution
  6483. The :attr:`std` is a tensor with the standard deviation of
  6484. each output element's normal distribution
  6485. The shapes of :attr:`mean` and :attr:`std` don't need to match, but the
  6486. total number of elements in each tensor need to be the same.
  6487. .. note:: When the shapes do not match, the shape of :attr:`mean`
  6488. is used as the shape for the returned output tensor
  6489. .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes
  6490. its device with the CPU.
  6491. Args:
  6492. mean (Tensor): the tensor of per-element means
  6493. std (Tensor): the tensor of per-element standard deviations
  6494. Keyword args:
  6495. {generator}
  6496. {out}
  6497. Example::
  6498. >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1))
  6499. tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134,
  6500. 8.0505, 8.1408, 9.0563, 10.0566])
  6501. .. function:: normal(mean=0.0, std, *, out=None) -> Tensor
  6502. :noindex:
  6503. Similar to the function above, but the means are shared among all drawn
  6504. elements.
  6505. Args:
  6506. mean (float, optional): the mean for all distributions
  6507. std (Tensor): the tensor of per-element standard deviations
  6508. Keyword args:
  6509. {out}
  6510. Example::
  6511. >>> torch.normal(mean=0.5, std=torch.arange(1., 6.))
  6512. tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303])
  6513. .. function:: normal(mean, std=1.0, *, out=None) -> Tensor
  6514. :noindex:
  6515. Similar to the function above, but the standard deviations are shared among
  6516. all drawn elements.
  6517. Args:
  6518. mean (Tensor): the tensor of per-element means
  6519. std (float, optional): the standard deviation for all distributions
  6520. Keyword args:
  6521. out (Tensor, optional): the output tensor
  6522. Example::
  6523. >>> torch.normal(mean=torch.arange(1., 6.))
  6524. tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361])
  6525. .. function:: normal(mean, std, size, *, out=None) -> Tensor
  6526. :noindex:
  6527. Similar to the function above, but the means and standard deviations are shared
  6528. among all drawn elements. The resulting tensor has size given by :attr:`size`.
  6529. Args:
  6530. mean (float): the mean for all distributions
  6531. std (float): the standard deviation for all distributions
  6532. size (int...): a sequence of integers defining the shape of the output tensor.
  6533. Keyword args:
  6534. {out}
  6535. Example::
  6536. >>> torch.normal(2, 3, size=(1, 4))
  6537. tensor([[-1.3987, -1.9544, 3.6048, 0.7909]])
  6538. """.format(**common_args),
  6539. )
  6540. add_docstr(
  6541. torch.numel,
  6542. r"""
  6543. numel(input: Tensor) -> int
  6544. Returns the total number of elements in the :attr:`input` tensor.
  6545. Args:
  6546. {input}
  6547. Example::
  6548. >>> a = torch.randn(1, 2, 3, 4, 5)
  6549. >>> torch.numel(a)
  6550. 120
  6551. >>> a = torch.zeros(4,4)
  6552. >>> torch.numel(a)
  6553. 16
  6554. """.format(**common_args),
  6555. )
  6556. add_docstr(
  6557. torch.ones,
  6558. r"""
  6559. ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
  6560. Returns a tensor filled with the scalar value `1`, with the shape defined
  6561. by the variable argument :attr:`size`.
  6562. Args:
  6563. size (int...): a sequence of integers defining the shape of the output tensor.
  6564. Can be a variable number of arguments or a collection like a list or tuple.
  6565. Keyword arguments:
  6566. {out}
  6567. {dtype}
  6568. {layout}
  6569. {device}
  6570. {requires_grad}
  6571. Example::
  6572. >>> torch.ones(2, 3)
  6573. tensor([[ 1., 1., 1.],
  6574. [ 1., 1., 1.]])
  6575. >>> torch.ones(5)
  6576. tensor([ 1., 1., 1., 1., 1.])
  6577. """.format(**factory_common_args),
  6578. )
  6579. add_docstr(
  6580. torch.ones_like,
  6581. r"""
  6582. ones_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor
  6583. Returns a tensor filled with the scalar value `1`, with the same size as
  6584. :attr:`input`. ``torch.ones_like(input)`` is equivalent to
  6585. ``torch.ones(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``.
  6586. .. warning::
  6587. As of 0.4, this function does not support an :attr:`out` keyword. As an alternative,
  6588. the old ``torch.ones_like(input, out=output)`` is equivalent to
  6589. ``torch.ones(input.size(), out=output)``.
  6590. Args:
  6591. {input}
  6592. Keyword arguments:
  6593. {dtype}
  6594. {layout}
  6595. {device}
  6596. {requires_grad}
  6597. {memory_format}
  6598. Example::
  6599. >>> input = torch.empty(2, 3)
  6600. >>> torch.ones_like(input)
  6601. tensor([[ 1., 1., 1.],
  6602. [ 1., 1., 1.]])
  6603. """.format(**factory_like_common_args),
  6604. )
  6605. add_docstr(
  6606. torch.orgqr,
  6607. r"""
  6608. orgqr(input, tau) -> Tensor
  6609. Alias for :func:`torch.linalg.householder_product`.
  6610. """,
  6611. )
  6612. add_docstr(
  6613. torch.ormqr,
  6614. r"""
  6615. ormqr(input, tau, other, left=True, transpose=False, *, out=None) -> Tensor
  6616. Computes the matrix-matrix multiplication of a product of Householder matrices with a general matrix.
  6617. Multiplies a :math:`m \times n` matrix `C` (given by :attr:`other`) with a matrix `Q`,
  6618. where `Q` is represented using Householder reflectors `(input, tau)`.
  6619. See `Representation of Orthogonal or Unitary Matrices`_ for further details.
  6620. If :attr:`left` is `True` then `op(Q)` times `C` is computed, otherwise the result is `C` times `op(Q)`.
  6621. When :attr:`left` is `True`, the implicit matrix `Q` has size :math:`m \times m`.
  6622. It has size :math:`n \times n` otherwise.
  6623. If :attr:`transpose` is `True` then `op` is the conjugate transpose operation, otherwise it's a no-op.
  6624. Supports inputs of float, double, cfloat and cdouble dtypes.
  6625. Also supports batched inputs, and, if the input is batched, the output is batched with the same dimensions.
  6626. .. seealso::
  6627. :func:`torch.geqrf` can be used to form the Householder representation `(input, tau)` of matrix `Q`
  6628. from the QR decomposition.
  6629. .. note::
  6630. This function supports backward but it is only fast when ``(input, tau)`` do not require gradients
  6631. and/or ``tau.size(-1)`` is very small.
  6632. ``
  6633. Args:
  6634. input (Tensor): tensor of shape `(*, mn, k)` where `*` is zero or more batch dimensions
  6635. and `mn` equals to `m` or `n` depending on the :attr:`left`.
  6636. tau (Tensor): tensor of shape `(*, min(mn, k))` where `*` is zero or more batch dimensions.
  6637. other (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.
  6638. left (bool): controls the order of multiplication.
  6639. transpose (bool): controls whether the matrix `Q` is conjugate transposed or not.
  6640. Keyword args:
  6641. out (Tensor, optional): the output Tensor. Ignored if `None`. Default: `None`.
  6642. .. _Representation of Orthogonal or Unitary Matrices:
  6643. https://www.netlib.org/lapack/lug/node128.html
  6644. """,
  6645. )
  6646. add_docstr(
  6647. torch.permute,
  6648. r"""
  6649. permute(input, dims) -> Tensor
  6650. Returns a view of the original tensor :attr:`input` with its dimensions permuted.
  6651. Args:
  6652. {input}
  6653. dims (torch.Size, tuple of int or list of int): the desired ordering of dimensions.
  6654. Example:
  6655. >>> x = torch.randn(2, 3, 5)
  6656. >>> x.size()
  6657. torch.Size([2, 3, 5])
  6658. >>> torch.permute(x, (2, 0, 1)).size()
  6659. torch.Size([5, 2, 3])
  6660. """.format(**common_args),
  6661. )
  6662. add_docstr(
  6663. torch.poisson,
  6664. r"""
  6665. poisson(input, generator=None) -> Tensor
  6666. Returns a tensor of the same size as :attr:`input` with each element
  6667. sampled from a Poisson distribution with rate parameter given by the corresponding
  6668. element in :attr:`input` i.e.,
  6669. .. math::
  6670. \text{{out}}_i \sim \text{{Poisson}}(\text{{input}}_i)
  6671. :attr:`input` must be non-negative.
  6672. Args:
  6673. input (Tensor): the input tensor containing the rates of the Poisson distribution
  6674. Keyword args:
  6675. {generator}
  6676. Example::
  6677. >>> rates = torch.rand(4, 4) * 5 # rate parameter between 0 and 5
  6678. >>> torch.poisson(rates)
  6679. tensor([[9., 1., 3., 5.],
  6680. [8., 6., 6., 0.],
  6681. [0., 4., 5., 3.],
  6682. [2., 1., 4., 2.]])
  6683. """.format(**common_args),
  6684. )
  6685. add_docstr(
  6686. torch.polygamma,
  6687. r"""
  6688. polygamma(n, input, *, out=None) -> Tensor
  6689. Alias for :func:`torch.special.polygamma`.
  6690. """,
  6691. )
  6692. add_docstr(
  6693. torch.positive,
  6694. r"""
  6695. positive(input) -> Tensor
  6696. Returns :attr:`input`.
  6697. Throws a runtime error if :attr:`input` is a bool tensor.
  6698. """
  6699. + r"""
  6700. Args:
  6701. {input}
  6702. Example::
  6703. >>> t = torch.randn(5)
  6704. >>> t
  6705. tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940])
  6706. >>> torch.positive(t)
  6707. tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940])
  6708. """.format(**common_args),
  6709. )
  6710. add_docstr(
  6711. torch.pow,
  6712. r"""
  6713. pow(input, exponent, *, out=None) -> Tensor
  6714. Takes the power of each element in :attr:`input` with :attr:`exponent` and
  6715. returns a tensor with the result.
  6716. :attr:`exponent` can be either a single ``float`` number or a `Tensor`
  6717. with the same number of elements as :attr:`input`.
  6718. When :attr:`exponent` is a scalar value, the operation applied is:
  6719. .. math::
  6720. \text{out}_i = x_i ^ \text{exponent}
  6721. When :attr:`exponent` is a tensor, the operation applied is:
  6722. .. math::
  6723. \text{out}_i = x_i ^ {\text{exponent}_i}
  6724. """
  6725. + r"""
  6726. When :attr:`exponent` is a tensor, the shapes of :attr:`input`
  6727. and :attr:`exponent` must be :ref:`broadcastable <broadcasting-semantics>`.
  6728. Args:
  6729. {input}
  6730. exponent (float or tensor): the exponent value
  6731. Keyword args:
  6732. {out}
  6733. Example::
  6734. >>> a = torch.randn(4)
  6735. >>> a
  6736. tensor([ 0.4331, 1.2475, 0.6834, -0.2791])
  6737. >>> torch.pow(a, 2)
  6738. tensor([ 0.1875, 1.5561, 0.4670, 0.0779])
  6739. >>> exp = torch.arange(1., 5.)
  6740. >>> a = torch.arange(1., 5.)
  6741. >>> a
  6742. tensor([ 1., 2., 3., 4.])
  6743. >>> exp
  6744. tensor([ 1., 2., 3., 4.])
  6745. >>> torch.pow(a, exp)
  6746. tensor([ 1., 4., 27., 256.])
  6747. .. function:: pow(self, exponent, *, out=None) -> Tensor
  6748. :noindex:
  6749. :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor.
  6750. The returned tensor :attr:`out` is of the same shape as :attr:`exponent`
  6751. The operation applied is:
  6752. .. math::
  6753. \text{{out}}_i = \text{{self}} ^ {{\text{{exponent}}_i}}
  6754. Args:
  6755. self (float): the scalar base value for the power operation
  6756. exponent (Tensor): the exponent tensor
  6757. Keyword args:
  6758. {out}
  6759. Example::
  6760. >>> exp = torch.arange(1., 5.)
  6761. >>> base = 2
  6762. >>> torch.pow(base, exp)
  6763. tensor([ 2., 4., 8., 16.])
  6764. """.format(**common_args),
  6765. )
  6766. add_docstr(
  6767. torch.float_power,
  6768. r"""
  6769. float_power(input, exponent, *, out=None) -> Tensor
  6770. Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision.
  6771. If neither input is complex returns a ``torch.float64`` tensor,
  6772. and if one or more inputs is complex returns a ``torch.complex128`` tensor.
  6773. .. note::
  6774. This function always computes in double precision, unlike :func:`torch.pow`,
  6775. which implements more typical :ref:`type promotion <type-promotion-doc>`.
  6776. This is useful when the computation needs to be performed in a wider or more precise dtype,
  6777. or the results of the computation may contain fractional values not representable in the input dtypes,
  6778. like when an integer base is raised to a negative integer exponent.
  6779. Args:
  6780. input (Tensor or Number): the base value(s)
  6781. exponent (Tensor or Number): the exponent value(s)
  6782. Keyword args:
  6783. {out}
  6784. Example::
  6785. >>> a = torch.randint(10, (4,))
  6786. >>> a
  6787. tensor([6, 4, 7, 1])
  6788. >>> torch.float_power(a, 2)
  6789. tensor([36., 16., 49., 1.], dtype=torch.float64)
  6790. >>> a = torch.arange(1, 5)
  6791. >>> a
  6792. tensor([ 1, 2, 3, 4])
  6793. >>> exp = torch.tensor([2, -3, 4, -5])
  6794. >>> exp
  6795. tensor([ 2, -3, 4, -5])
  6796. >>> torch.float_power(a, exp)
  6797. tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64)
  6798. """.format(**common_args),
  6799. )
  6800. add_docstr(
  6801. torch.prod,
  6802. r"""
  6803. prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor
  6804. Returns the product of all elements in the :attr:`input` tensor.
  6805. Args:
  6806. {input}
  6807. Keyword args:
  6808. {dtype}
  6809. Example::
  6810. >>> a = torch.randn(1, 3)
  6811. >>> a
  6812. tensor([[-0.8020, 0.5428, -1.5854]])
  6813. >>> torch.prod(a)
  6814. tensor(0.6902)
  6815. .. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor
  6816. :noindex:
  6817. Returns the product of each row of the :attr:`input` tensor in the given
  6818. dimension :attr:`dim`.
  6819. {keepdim_details}
  6820. Args:
  6821. {input}
  6822. {opt_dim_all_reduce}
  6823. {opt_keepdim}
  6824. Keyword args:
  6825. {dtype}
  6826. Example::
  6827. >>> a = torch.randn(4, 2)
  6828. >>> a
  6829. tensor([[ 0.5261, -0.3837],
  6830. [ 1.1857, -0.2498],
  6831. [-1.1646, 0.0705],
  6832. [ 1.1131, -1.0629]])
  6833. >>> torch.prod(a, 1)
  6834. tensor([-0.2018, -0.2962, -0.0821, -1.1831])
  6835. """.format(**single_dim_common),
  6836. )
  6837. add_docstr(
  6838. torch.promote_types,
  6839. r"""
  6840. promote_types(type1, type2) -> dtype
  6841. Returns the :class:`torch.dtype` with the smallest size and scalar kind that is
  6842. not smaller nor of lower kind than either `type1` or `type2`. See type promotion
  6843. :ref:`documentation <type-promotion-doc>` for more information on the type
  6844. promotion logic.
  6845. Args:
  6846. type1 (:class:`torch.dtype`)
  6847. type2 (:class:`torch.dtype`)
  6848. Example::
  6849. >>> torch.promote_types(torch.int32, torch.float32)
  6850. torch.float32
  6851. >>> torch.promote_types(torch.uint8, torch.long)
  6852. torch.long
  6853. """,
  6854. )
  6855. add_docstr(
  6856. torch.qr,
  6857. r"""
  6858. qr(input: Tensor, some: bool = True, *, out: Union[Tensor, Tuple[Tensor, ...], List[Tensor], None]) -> (Tensor, Tensor)
  6859. Computes the QR decomposition of a matrix or a batch of matrices :attr:`input`,
  6860. and returns a namedtuple (Q, R) of tensors such that :math:`\text{input} = Q R`
  6861. with :math:`Q` being an orthogonal matrix or batch of orthogonal matrices and
  6862. :math:`R` being an upper triangular matrix or batch of upper triangular matrices.
  6863. If :attr:`some` is ``True``, then this function returns the thin (reduced) QR factorization.
  6864. Otherwise, if :attr:`some` is ``False``, this function returns the complete QR factorization.
  6865. .. warning::
  6866. :func:`torch.qr` is deprecated in favor of :func:`torch.linalg.qr`
  6867. and will be removed in a future PyTorch release. The boolean parameter :attr:`some` has been
  6868. replaced with a string parameter :attr:`mode`.
  6869. ``Q, R = torch.qr(A)`` should be replaced with
  6870. .. code:: python
  6871. Q, R = torch.linalg.qr(A)
  6872. ``Q, R = torch.qr(A, some=False)`` should be replaced with
  6873. .. code:: python
  6874. Q, R = torch.linalg.qr(A, mode="complete")
  6875. .. warning::
  6876. If you plan to backpropagate through QR, note that the current backward implementation
  6877. is only well-defined when the first :math:`\min(input.size(-1), input.size(-2))`
  6878. columns of :attr:`input` are linearly independent.
  6879. This behavior will probably change once QR supports pivoting.
  6880. .. note:: This function uses LAPACK for CPU inputs and MAGMA for CUDA inputs,
  6881. and may produce different (valid) decompositions on different device types
  6882. or different platforms.
  6883. Args:
  6884. input (Tensor): the input tensor of size :math:`(*, m, n)` where `*` is zero or more
  6885. batch dimensions consisting of matrices of dimension :math:`m \times n`.
  6886. some (bool, optional): Set to ``True`` for reduced QR decomposition and ``False`` for
  6887. complete QR decomposition. If `k = min(m, n)` then:
  6888. * ``some=True`` : returns `(Q, R)` with dimensions (m, k), (k, n) (default)
  6889. * ``'some=False'``: returns `(Q, R)` with dimensions (m, m), (m, n)
  6890. Keyword args:
  6891. out (tuple, optional): tuple of `Q` and `R` tensors.
  6892. The dimensions of `Q` and `R` are detailed in the description of :attr:`some` above.
  6893. Example::
  6894. >>> a = torch.tensor([[12., -51, 4], [6, 167, -68], [-4, 24, -41]])
  6895. >>> q, r = torch.qr(a)
  6896. >>> q
  6897. tensor([[-0.8571, 0.3943, 0.3314],
  6898. [-0.4286, -0.9029, -0.0343],
  6899. [ 0.2857, -0.1714, 0.9429]])
  6900. >>> r
  6901. tensor([[ -14.0000, -21.0000, 14.0000],
  6902. [ 0.0000, -175.0000, 70.0000],
  6903. [ 0.0000, 0.0000, -35.0000]])
  6904. >>> torch.mm(q, r).round()
  6905. tensor([[ 12., -51., 4.],
  6906. [ 6., 167., -68.],
  6907. [ -4., 24., -41.]])
  6908. >>> torch.mm(q.t(), q).round()
  6909. tensor([[ 1., 0., 0.],
  6910. [ 0., 1., -0.],
  6911. [ 0., -0., 1.]])
  6912. >>> a = torch.randn(3, 4, 5)
  6913. >>> q, r = torch.qr(a, some=False)
  6914. >>> torch.allclose(torch.matmul(q, r), a)
  6915. True
  6916. >>> torch.allclose(torch.matmul(q.mT, q), torch.eye(5))
  6917. True
  6918. """,
  6919. )
  6920. add_docstr(
  6921. torch.rad2deg,
  6922. r"""
  6923. rad2deg(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  6924. Returns a new tensor with each of the elements of :attr:`input`
  6925. converted from angles in radians to degrees.
  6926. Args:
  6927. {input}
  6928. Keyword arguments:
  6929. {out}
  6930. Example::
  6931. >>> a = torch.tensor([[3.142, -3.142], [6.283, -6.283], [1.570, -1.570]])
  6932. >>> torch.rad2deg(a)
  6933. tensor([[ 180.0233, -180.0233],
  6934. [ 359.9894, -359.9894],
  6935. [ 89.9544, -89.9544]])
  6936. """.format(**common_args),
  6937. )
  6938. add_docstr(
  6939. torch.deg2rad,
  6940. r"""
  6941. deg2rad(input, *, out=None) -> Tensor
  6942. Returns a new tensor with each of the elements of :attr:`input`
  6943. converted from angles in degrees to radians.
  6944. Args:
  6945. {input}
  6946. Keyword arguments:
  6947. {out}
  6948. Example::
  6949. >>> a = torch.tensor([[180.0, -180.0], [360.0, -360.0], [90.0, -90.0]])
  6950. >>> torch.deg2rad(a)
  6951. tensor([[ 3.1416, -3.1416],
  6952. [ 6.2832, -6.2832],
  6953. [ 1.5708, -1.5708]])
  6954. """.format(**common_args),
  6955. )
  6956. add_docstr(
  6957. torch.heaviside,
  6958. r"""
  6959. heaviside(input, values, *, out=None) -> Tensor
  6960. Computes the Heaviside step function for each element in :attr:`input`.
  6961. The Heaviside step function is defined as:
  6962. .. math::
  6963. \text{{heaviside}}(input, values) = \begin{cases}
  6964. 0, & \text{if input < 0}\\
  6965. values, & \text{if input == 0}\\
  6966. 1, & \text{if input > 0}
  6967. \end{cases}
  6968. """
  6969. + r"""
  6970. Args:
  6971. {input}
  6972. values (Tensor): The values to use where :attr:`input` is zero.
  6973. Keyword arguments:
  6974. {out}
  6975. Example::
  6976. >>> input = torch.tensor([-1.5, 0, 2.0])
  6977. >>> values = torch.tensor([0.5])
  6978. >>> torch.heaviside(input, values)
  6979. tensor([0.0000, 0.5000, 1.0000])
  6980. >>> values = torch.tensor([1.2, -2.0, 3.5])
  6981. >>> torch.heaviside(input, values)
  6982. tensor([0., -2., 1.])
  6983. """.format(**common_args),
  6984. )
  6985. add_docstr(
  6986. torch.rand,
  6987. """
  6988. rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, \
  6989. requires_grad=False, pin_memory=False) -> Tensor
  6990. """
  6991. + r"""
  6992. Returns a tensor filled with random numbers from a uniform distribution
  6993. on the interval :math:`[0, 1)`
  6994. The shape of the tensor is defined by the variable argument :attr:`size`.
  6995. Args:
  6996. size (int...): a sequence of integers defining the shape of the output tensor.
  6997. Can be a variable number of arguments or a collection like a list or tuple.
  6998. Keyword args:
  6999. {generator}
  7000. {out}
  7001. {dtype}
  7002. {layout}
  7003. {device}
  7004. {requires_grad}
  7005. {pin_memory}
  7006. Example::
  7007. >>> torch.rand(4)
  7008. tensor([ 0.5204, 0.2503, 0.3525, 0.5673])
  7009. >>> torch.rand(2, 3)
  7010. tensor([[ 0.8237, 0.5781, 0.6879],
  7011. [ 0.3816, 0.7249, 0.0998]])
  7012. """.format(**factory_common_args),
  7013. )
  7014. add_docstr(
  7015. torch.rand_like,
  7016. """
  7017. rand_like(input, *, generator=None, dtype=None, layout=None, device=None, \
  7018. requires_grad=False, memory_format=torch.preserve_format) -> Tensor
  7019. """
  7020. + r"""
  7021. Returns a tensor with the same size as :attr:`input` that is filled with
  7022. random numbers from a uniform distribution on the interval :math:`[0, 1)`.
  7023. ``torch.rand_like(input)`` is equivalent to
  7024. ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``.
  7025. Args:
  7026. {input}
  7027. Keyword args:
  7028. {generator}
  7029. {dtype}
  7030. {layout}
  7031. {device}
  7032. {requires_grad}
  7033. {memory_format}
  7034. """.format(**factory_like_common_args),
  7035. )
  7036. add_docstr(
  7037. torch.randint,
  7038. """
  7039. randint(low=0, high, size, \\*, generator=None, out=None, \
  7040. dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
  7041. Returns a tensor filled with random integers generated uniformly
  7042. between :attr:`low` (inclusive) and :attr:`high` (exclusive).
  7043. The shape of the tensor is defined by the variable argument :attr:`size`.
  7044. .. note::
  7045. With the global dtype default (``torch.float32``), this function returns
  7046. a tensor with dtype ``torch.int64``.
  7047. Args:
  7048. low (int, optional): Lowest integer to be drawn from the distribution. Default: 0.
  7049. high (int): One above the highest integer to be drawn from the distribution.
  7050. size (tuple): a tuple defining the shape of the output tensor.
  7051. Keyword args:
  7052. {generator}
  7053. {out}
  7054. dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``,
  7055. this function returns a tensor with dtype ``torch.int64``.
  7056. {layout}
  7057. {device}
  7058. {requires_grad}
  7059. Example::
  7060. >>> torch.randint(3, 5, (3,))
  7061. tensor([4, 3, 4])
  7062. >>> torch.randint(10, (2, 2))
  7063. tensor([[0, 2],
  7064. [5, 5]])
  7065. >>> torch.randint(3, 10, (2, 2))
  7066. tensor([[4, 5],
  7067. [6, 7]])
  7068. """.format(**factory_common_args),
  7069. )
  7070. add_docstr(
  7071. torch.randint_like,
  7072. """
  7073. randint_like(input, low=0, high, \\*, generator=None, dtype=None, layout=torch.strided, \
  7074. device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor
  7075. """
  7076. + r"""
  7077. Returns a tensor with the same shape as Tensor :attr:`input` filled with
  7078. random integers generated uniformly between :attr:`low` (inclusive) and
  7079. :attr:`high` (exclusive).
  7080. .. note:
  7081. With the global dtype default (``torch.float32``), this function returns
  7082. a tensor with dtype ``torch.int64``.
  7083. Args:
  7084. {input}
  7085. low (int, optional): Lowest integer to be drawn from the distribution. Default: 0.
  7086. high (int): One above the highest integer to be drawn from the distribution.
  7087. Keyword args:
  7088. {generator}
  7089. {dtype}
  7090. {layout}
  7091. {device}
  7092. {requires_grad}
  7093. {memory_format}
  7094. """.format(**factory_like_common_args),
  7095. )
  7096. add_docstr(
  7097. torch.randn,
  7098. """
  7099. randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, \
  7100. pin_memory=False) -> Tensor
  7101. """
  7102. + r"""
  7103. Returns a tensor filled with random numbers from a normal distribution
  7104. with mean `0` and variance `1` (also called the standard normal
  7105. distribution).
  7106. .. math::
  7107. \text{{out}}_{{i}} \sim \mathcal{{N}}(0, 1)
  7108. For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and
  7109. unit variance as
  7110. .. math::
  7111. \text{{out}}_{{i}} \sim \mathcal{{CN}}(0, 1)
  7112. This is equivalent to separately sampling the real :math:`(\operatorname{{Re}})` and imaginary
  7113. :math:`(\operatorname{{Im}})` part of :math:`\text{{out}}_i` as
  7114. .. math::
  7115. \operatorname{{Re}}(\text{{out}}_{{i}}) \sim \mathcal{{N}}(0, \frac{{1}}{{2}}),\quad
  7116. \operatorname{{Im}}(\text{{out}}_{{i}}) \sim \mathcal{{N}}(0, \frac{{1}}{{2}})
  7117. The shape of the tensor is defined by the variable argument :attr:`size`.
  7118. Args:
  7119. size (int...): a sequence of integers defining the shape of the output tensor.
  7120. Can be a variable number of arguments or a collection like a list or tuple.
  7121. Keyword args:
  7122. {generator}
  7123. {out}
  7124. {dtype}
  7125. {layout}
  7126. {device}
  7127. {requires_grad}
  7128. {pin_memory}
  7129. Example::
  7130. >>> torch.randn(4)
  7131. tensor([-2.1436, 0.9966, 2.3426, -0.6366])
  7132. >>> torch.randn(2, 3)
  7133. tensor([[ 1.5954, 2.8929, -1.0923],
  7134. [ 1.1719, -0.4709, -0.1996]])
  7135. .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution
  7136. """.format(**factory_common_args),
  7137. )
  7138. add_docstr(
  7139. torch.randn_like,
  7140. """
  7141. randn_like(input, *, generator=None, dtype=None, layout=None, device=None, \
  7142. requires_grad=False, memory_format=torch.preserve_format) -> Tensor
  7143. """
  7144. + r"""
  7145. Returns a tensor with the same size as :attr:`input` that is filled with
  7146. random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the
  7147. sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to
  7148. ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``.
  7149. Args:
  7150. {input}
  7151. Keyword args:
  7152. {generator}
  7153. {dtype}
  7154. {layout}
  7155. {device}
  7156. {requires_grad}
  7157. {memory_format}
  7158. """.format(**factory_like_common_args),
  7159. )
  7160. add_docstr(
  7161. torch.randperm,
  7162. """
  7163. randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, \
  7164. device=None, requires_grad=False, pin_memory=False) -> Tensor
  7165. """
  7166. + r"""
  7167. Returns a random permutation of integers from ``0`` to ``n - 1``.
  7168. Args:
  7169. n (int): the upper bound (exclusive)
  7170. Keyword args:
  7171. {generator}
  7172. {out}
  7173. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
  7174. Default: ``torch.int64``.
  7175. {layout}
  7176. {device}
  7177. {requires_grad}
  7178. {pin_memory}
  7179. Example::
  7180. >>> torch.randperm(4)
  7181. tensor([2, 1, 0, 3])
  7182. """.format(**factory_common_args),
  7183. )
  7184. add_docstr(
  7185. torch.tensor,
  7186. r"""
  7187. tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) -> Tensor
  7188. Constructs a tensor with no autograd history (also known as a "leaf tensor", see :doc:`/notes/autograd`) by copying :attr:`data`.
  7189. .. warning::
  7190. When working with tensors prefer using :func:`torch.Tensor.clone`,
  7191. :func:`torch.Tensor.detach`, and :func:`torch.Tensor.requires_grad_` for
  7192. readability. Letting `t` be a tensor, ``torch.tensor(t)`` is equivalent to
  7193. ``t.detach().clone()``, and ``torch.tensor(t, requires_grad=True)``
  7194. is equivalent to ``t.detach().clone().requires_grad_(True)``.
  7195. .. seealso::
  7196. :func:`torch.as_tensor` preserves autograd history and avoids copies where possible.
  7197. :func:`torch.from_numpy` creates a tensor that shares storage with a NumPy array.
  7198. Args:
  7199. {data}
  7200. Keyword args:
  7201. {dtype}
  7202. device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor
  7203. then the device of data is used. If None and data is not a tensor then
  7204. the result tensor is constructed on the current device.
  7205. {requires_grad}
  7206. {pin_memory}
  7207. Example::
  7208. >>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
  7209. tensor([[ 0.1000, 1.2000],
  7210. [ 2.2000, 3.1000],
  7211. [ 4.9000, 5.2000]])
  7212. >>> torch.tensor([0, 1]) # Type inference on data
  7213. tensor([ 0, 1])
  7214. >>> torch.tensor([[0.11111, 0.222222, 0.3333333]],
  7215. ... dtype=torch.float64,
  7216. ... device=torch.device('cuda:0')) # creates a double tensor on a CUDA device
  7217. tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0')
  7218. >>> torch.tensor(3.14159) # Create a zero-dimensional (scalar) tensor
  7219. tensor(3.1416)
  7220. >>> torch.tensor([]) # Create an empty tensor (of size (0,))
  7221. tensor([])
  7222. """.format(**factory_data_common_args),
  7223. )
  7224. add_docstr(
  7225. torch.range,
  7226. r"""
  7227. range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
  7228. Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1`
  7229. with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is
  7230. the gap between two values in the tensor.
  7231. .. math::
  7232. \text{out}_{i+1} = \text{out}_i + \text{step}.
  7233. """
  7234. + r"""
  7235. .. warning::
  7236. This function is deprecated and will be removed in a future release because its behavior is inconsistent with
  7237. Python's range builtin. Instead, use :func:`torch.arange`, which produces values in [start, end).
  7238. Args:
  7239. start (float, optional): the starting value for the set of points. Default: ``0``.
  7240. end (float): the ending value for the set of points
  7241. step (float, optional): the gap between each pair of adjacent points. Default: ``1``.
  7242. Keyword args:
  7243. {out}
  7244. {dtype} If `dtype` is not given, infer the data type from the other input
  7245. arguments. If any of `start`, `end`, or `step` are floating-point, the
  7246. `dtype` is inferred to be the default dtype, see
  7247. :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to
  7248. be `torch.int64`.
  7249. {layout}
  7250. {device}
  7251. {requires_grad}
  7252. Example::
  7253. >>> torch.range(1, 4)
  7254. tensor([ 1., 2., 3., 4.])
  7255. >>> torch.range(1, 4, 0.5)
  7256. tensor([ 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000])
  7257. """.format(**factory_common_args),
  7258. )
  7259. add_docstr(
  7260. torch.arange,
  7261. r"""
  7262. arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
  7263. Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil`
  7264. with values from the interval ``[start, end)`` taken with common difference
  7265. :attr:`step` beginning from `start`.
  7266. Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``),
  7267. the results may be affected by floating-point rounding behavior. Some values in the sequence
  7268. might not be exactly representable in certain floating-point formats, which can lead to
  7269. repeated values or unexpected rounding. For precise sequences, it is recommended to use
  7270. integer dtypes instead of floating-point dtypes.
  7271. Note that non-integer :attr:`step` is subject to floating point rounding errors when
  7272. comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end`
  7273. in such cases.
  7274. .. math::
  7275. \text{out}_{{i+1}} = \text{out}_{i} + \text{step}
  7276. """
  7277. + r"""
  7278. Args:
  7279. start (Number, optional): the starting value for the set of points. Default: ``0``.
  7280. end (Number): the ending value for the set of points
  7281. step (Number, optional): the gap between each pair of adjacent points. Default: ``1``.
  7282. Keyword args:
  7283. {out}
  7284. {dtype} If `dtype` is not given, infer the data type from the other input
  7285. arguments. If any of `start`, `end`, or `stop` are floating-point, the
  7286. `dtype` is inferred to be the default dtype, see
  7287. :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to
  7288. be `torch.int64`.
  7289. {layout}
  7290. {device}
  7291. {requires_grad}
  7292. Example::
  7293. >>> torch.arange(5)
  7294. tensor([ 0, 1, 2, 3, 4])
  7295. >>> torch.arange(1, 4)
  7296. tensor([ 1, 2, 3])
  7297. >>> torch.arange(1, 2.5, 0.5)
  7298. tensor([ 1.0000, 1.5000, 2.0000])
  7299. """.format(**factory_common_args),
  7300. )
  7301. add_docstr(
  7302. torch.ravel,
  7303. r"""
  7304. ravel(input) -> Tensor
  7305. Return a contiguous flattened tensor. A copy is made only if needed.
  7306. Args:
  7307. {input}
  7308. Example::
  7309. >>> t = torch.tensor([[[1, 2],
  7310. ... [3, 4]],
  7311. ... [[5, 6],
  7312. ... [7, 8]]])
  7313. >>> torch.ravel(t)
  7314. tensor([1, 2, 3, 4, 5, 6, 7, 8])
  7315. """.format(**common_args),
  7316. )
  7317. add_docstr(
  7318. torch.remainder,
  7319. r"""
  7320. remainder(input, other, *, out=None) -> Tensor
  7321. Computes
  7322. `Python's modulus operation <https://docs.python.org/3/reference/expressions.html#binary-arithmetic-operations>`_
  7323. entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value
  7324. is less than that of :attr:`other`.
  7325. It may also be defined in terms of :func:`torch.div` as
  7326. .. code:: python
  7327. torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b
  7328. Supports :ref:`broadcasting to a common shape <broadcasting-semantics>`,
  7329. :ref:`type promotion <type-promotion-doc>`, and integer and float inputs.
  7330. .. note::
  7331. Complex inputs are not supported. In some cases, it is not mathematically
  7332. possible to satisfy the definition of a modulo operation with complex numbers.
  7333. See :func:`torch.fmod` for how division by zero is handled.
  7334. .. seealso::
  7335. :func:`torch.fmod` which implements C++'s `std::fmod <https://en.cppreference.com/w/cpp/numeric/math/fmod>`_.
  7336. This one is defined in terms of division rounding towards zero.
  7337. Args:
  7338. input (Tensor or Scalar): the dividend
  7339. other (Tensor or Scalar): the divisor
  7340. Keyword args:
  7341. {out}
  7342. Example::
  7343. >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2)
  7344. tensor([ 1., 0., 1., 1., 0., 1.])
  7345. >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5)
  7346. tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ])
  7347. """.format(**common_args),
  7348. )
  7349. add_docstr(
  7350. torch.renorm,
  7351. r"""
  7352. renorm(input, p, dim, maxnorm, *, out=None) -> Tensor
  7353. Returns a tensor where each sub-tensor of :attr:`input` along dimension
  7354. :attr:`dim` is normalized such that the `p`-norm of the sub-tensor is lower
  7355. than the value :attr:`maxnorm`
  7356. .. note:: If the norm of a row is lower than `maxnorm`, the row is unchanged
  7357. Args:
  7358. {input}
  7359. p (float): the power for the norm computation
  7360. dim (int): the dimension to slice over to get the sub-tensors
  7361. maxnorm (float): the maximum norm to keep each sub-tensor under
  7362. Keyword args:
  7363. {out}
  7364. Example::
  7365. >>> x = torch.ones(3, 3)
  7366. >>> x[1].fill_(2)
  7367. tensor([ 2., 2., 2.])
  7368. >>> x[2].fill_(3)
  7369. tensor([ 3., 3., 3.])
  7370. >>> x
  7371. tensor([[ 1., 1., 1.],
  7372. [ 2., 2., 2.],
  7373. [ 3., 3., 3.]])
  7374. >>> torch.renorm(x, 1, 0, 5)
  7375. tensor([[ 1.0000, 1.0000, 1.0000],
  7376. [ 1.6667, 1.6667, 1.6667],
  7377. [ 1.6667, 1.6667, 1.6667]])
  7378. """.format(**common_args),
  7379. )
  7380. add_docstr(
  7381. torch.reshape,
  7382. r"""
  7383. reshape(input, shape) -> Tensor
  7384. Returns a tensor with the same data and number of elements as :attr:`input`,
  7385. but with the specified shape. When possible, the returned tensor will be a view
  7386. of :attr:`input`. Otherwise, it will be a copy. Contiguous inputs and inputs
  7387. with compatible strides can be reshaped without copying, but you should not
  7388. depend on the copying vs. viewing behavior.
  7389. See :meth:`torch.Tensor.view` on when it is possible to return a view.
  7390. A single dimension may be -1, in which case it's inferred from the remaining
  7391. dimensions and the number of elements in :attr:`input`.
  7392. Args:
  7393. input (Tensor): the tensor to be reshaped
  7394. shape (tuple of int): the new shape
  7395. Example::
  7396. >>> a = torch.arange(4.)
  7397. >>> torch.reshape(a, (2, 2))
  7398. tensor([[ 0., 1.],
  7399. [ 2., 3.]])
  7400. >>> b = torch.tensor([[0, 1], [2, 3]])
  7401. >>> torch.reshape(b, (-1,))
  7402. tensor([ 0, 1, 2, 3])
  7403. """,
  7404. )
  7405. add_docstr(
  7406. torch.result_type,
  7407. r"""
  7408. result_type(tensor1, tensor2) -> dtype
  7409. Returns the :class:`torch.dtype` that would result from performing an arithmetic
  7410. operation on the provided input tensors. See type promotion :ref:`documentation <type-promotion-doc>`
  7411. for more information on the type promotion logic.
  7412. Args:
  7413. tensor1 (Tensor or Number): an input tensor or number
  7414. tensor2 (Tensor or Number): an input tensor or number
  7415. Example::
  7416. >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0)
  7417. torch.float32
  7418. >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1))
  7419. torch.uint8
  7420. """,
  7421. )
  7422. add_docstr(
  7423. torch.row_stack,
  7424. r"""
  7425. row_stack(tensors, *, out=None) -> Tensor
  7426. Alias of :func:`torch.vstack`.
  7427. """,
  7428. )
  7429. add_docstr(
  7430. torch.round,
  7431. r"""
  7432. round(input, *, decimals=0, out=None) -> Tensor
  7433. Rounds elements of :attr:`input` to the nearest integer.
  7434. For integer inputs, follows the array-api convention of returning a
  7435. copy of the input tensor.
  7436. The return type of output is same as that of input's dtype.
  7437. .. note::
  7438. This function implements the "round half to even" to
  7439. break ties when a number is equidistant from two
  7440. integers (e.g. `round(2.5)` is 2).
  7441. When the :attr:\`decimals\` argument is specified the
  7442. algorithm used is similar to NumPy's `around`. This
  7443. algorithm is fast but inexact and it can easily
  7444. overflow for low precision dtypes.
  7445. Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`.
  7446. .. seealso::
  7447. :func:`torch.ceil`, which rounds up.
  7448. :func:`torch.floor`, which rounds down.
  7449. :func:`torch.trunc`, which rounds towards zero.
  7450. Args:
  7451. {input}
  7452. decimals (int): Number of decimal places to round to (default: 0).
  7453. If decimals is negative, it specifies the number of positions
  7454. to the left of the decimal point.
  7455. Keyword args:
  7456. {out}
  7457. Example::
  7458. >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7)))
  7459. tensor([ 5., -2., 9., -8.])
  7460. >>> # Values equidistant from two integers are rounded towards the
  7461. >>> # the nearest even value (zero is treated as even)
  7462. >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5]))
  7463. tensor([-0., 0., 2., 2.])
  7464. >>> # A positive decimals argument rounds to the to that decimal place
  7465. >>> torch.round(torch.tensor([0.1234567]), decimals=3)
  7466. tensor([0.1230])
  7467. >>> # A negative decimals argument rounds to the left of the decimal
  7468. >>> torch.round(torch.tensor([1200.1234567]), decimals=-3)
  7469. tensor([1000.])
  7470. """.format(**common_args),
  7471. )
  7472. add_docstr(
  7473. torch.rsqrt,
  7474. r"""
  7475. rsqrt(input, *, out=None) -> Tensor
  7476. Returns a new tensor with the reciprocal of the square-root of each of
  7477. the elements of :attr:`input`.
  7478. .. math::
  7479. \text{out}_{i} = \frac{1}{\sqrt{\text{input}_{i}}}
  7480. """
  7481. + r"""
  7482. Args:
  7483. {input}
  7484. Keyword args:
  7485. {out}
  7486. Example::
  7487. >>> a = torch.randn(4)
  7488. >>> a
  7489. tensor([-0.0370, 0.2970, 1.5420, -0.9105])
  7490. >>> torch.rsqrt(a)
  7491. tensor([ nan, 1.8351, 0.8053, nan])
  7492. """.format(**common_args),
  7493. )
  7494. add_docstr(
  7495. torch.scatter,
  7496. r"""
  7497. scatter(input, dim, index, src) -> Tensor
  7498. Out-of-place version of :meth:`torch.Tensor.scatter_`
  7499. """,
  7500. )
  7501. add_docstr(
  7502. torch.scatter_add,
  7503. r"""
  7504. scatter_add(input, dim, index, src) -> Tensor
  7505. Out-of-place version of :meth:`torch.Tensor.scatter_add_`
  7506. """,
  7507. )
  7508. add_docstr(
  7509. torch.scatter_reduce,
  7510. r"""
  7511. scatter_reduce(input, dim, index, src, reduce, *, include_self=True) -> Tensor
  7512. Out-of-place version of :meth:`torch.Tensor.scatter_reduce_`
  7513. """,
  7514. )
  7515. add_docstr(
  7516. torch.segment_reduce,
  7517. r"""
  7518. segment_reduce(data: Tensor, reduce: str, *, lengths: Tensor | None = None, indices: Tensor | None = None, offsets: Tensor | None = None, axis: _int = 0, unsafe: _bool = False, initial: Number | _complex | None = None) -> Tensor # noqa: B950
  7519. Perform a segment reduction operation on the input tensor along the specified axis.
  7520. Args:
  7521. data (Tensor): The input tensor on which the segment reduction operation will be performed.
  7522. reduce (str): The type of reduction operation. Supported values are ``sum``, ``mean``, ``max``, ``min``, ``prod``.
  7523. Keyword args:
  7524. lengths (Tensor, optional): Length of each segment. Default: ``None``.
  7525. offsets (Tensor, optional): Offset of each segment. Default: ``None``.
  7526. axis (int, optional): The axis perform reduction. Default: ``0``.
  7527. unsafe (bool, optional): Skip validation If `True`. Default: ``False``.
  7528. initial (Number, optional): The initial value for the reduction operation. Default: ``None``.
  7529. Example::
  7530. >>> data = torch.tensor([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=torch.float32, device='cuda')
  7531. >>> lengths = torch.tensor([2, 1], device='cuda')
  7532. >>> torch.segment_reduce(data, 'max', lengths=lengths)
  7533. tensor([[ 5., 6., 7., 8.],
  7534. [ 9., 10., 11., 12.]], device='cuda:0')
  7535. """,
  7536. )
  7537. add_docstr(
  7538. torch.select,
  7539. r"""
  7540. select(input, dim, index) -> Tensor
  7541. Slices the :attr:`input` tensor along the selected dimension at the given index.
  7542. This function returns a view of the original tensor with the given dimension removed.
  7543. .. note:: If :attr:`input` is a sparse tensor and returning a view of
  7544. the tensor is not possible, a RuntimeError exception is
  7545. raised. In this is the case, consider using
  7546. :func:`torch.select_copy` function.
  7547. Args:
  7548. {input}
  7549. dim (int): the dimension to slice
  7550. index (int): the index to select with
  7551. .. note::
  7552. :meth:`select` is equivalent to slicing. For example,
  7553. ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and
  7554. ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``.
  7555. """.format(**common_args),
  7556. )
  7557. add_docstr(
  7558. torch.select_scatter,
  7559. r"""
  7560. select_scatter(input, src, dim, index) -> Tensor
  7561. Embeds the values of the :attr:`src` tensor into :attr:`input` at the given index.
  7562. This function returns a tensor with fresh storage; it does not create a view.
  7563. Args:
  7564. {input}
  7565. src (Tensor): The tensor to embed into :attr:`input`
  7566. dim (int): the dimension to insert the slice into.
  7567. index (int): the index to select with
  7568. .. note::
  7569. :attr:`src` must be of the proper size in order to be embedded
  7570. into :attr:`input`. Specifically, it should have the same shape as
  7571. ``torch.select(input, dim, index)``
  7572. Example::
  7573. >>> a = torch.zeros(2, 2)
  7574. >>> b = torch.ones(2)
  7575. >>> a.select_scatter(b, 0, 0)
  7576. tensor([[1., 1.],
  7577. [0., 0.]])
  7578. """.format(**common_args),
  7579. )
  7580. add_docstr(
  7581. torch.slice_scatter,
  7582. r"""
  7583. slice_scatter(input, src, dim=0, start=None, end=None, step=1) -> Tensor
  7584. Embeds the values of the :attr:`src` tensor into :attr:`input` at the given
  7585. dimension.
  7586. This function returns a tensor with fresh storage; it does not create a view.
  7587. Args:
  7588. {input}
  7589. src (Tensor): The tensor to embed into :attr:`input`
  7590. dim (int): the dimension to insert the slice into
  7591. start (Optional[int]): the start index of where to insert the slice
  7592. end (Optional[int]): the end index of where to insert the slice
  7593. step (int): the how many elements to skip in
  7594. Example::
  7595. >>> a = torch.zeros(8, 8)
  7596. >>> b = torch.ones(2, 8)
  7597. >>> a.slice_scatter(b, start=6)
  7598. tensor([[0., 0., 0., 0., 0., 0., 0., 0.],
  7599. [0., 0., 0., 0., 0., 0., 0., 0.],
  7600. [0., 0., 0., 0., 0., 0., 0., 0.],
  7601. [0., 0., 0., 0., 0., 0., 0., 0.],
  7602. [0., 0., 0., 0., 0., 0., 0., 0.],
  7603. [0., 0., 0., 0., 0., 0., 0., 0.],
  7604. [1., 1., 1., 1., 1., 1., 1., 1.],
  7605. [1., 1., 1., 1., 1., 1., 1., 1.]])
  7606. >>> b = torch.ones(8, 2)
  7607. >>> a.slice_scatter(b, dim=1, start=2, end=6, step=2)
  7608. tensor([[0., 0., 1., 0., 1., 0., 0., 0.],
  7609. [0., 0., 1., 0., 1., 0., 0., 0.],
  7610. [0., 0., 1., 0., 1., 0., 0., 0.],
  7611. [0., 0., 1., 0., 1., 0., 0., 0.],
  7612. [0., 0., 1., 0., 1., 0., 0., 0.],
  7613. [0., 0., 1., 0., 1., 0., 0., 0.],
  7614. [0., 0., 1., 0., 1., 0., 0., 0.],
  7615. [0., 0., 1., 0., 1., 0., 0., 0.]])
  7616. """.format(**common_args),
  7617. )
  7618. add_docstr(
  7619. torch.set_flush_denormal,
  7620. r"""
  7621. set_flush_denormal(mode) -> bool
  7622. Disables denormal floating numbers on CPU.
  7623. Returns ``True`` if your system supports flushing denormal numbers and it
  7624. successfully configures flush denormal mode. :meth:`~torch.set_flush_denormal`
  7625. is supported on x86 architectures supporting SSE3 and AArch64 architecture.
  7626. Args:
  7627. mode (bool): Controls whether to enable flush denormal mode or not
  7628. Example::
  7629. >>> torch.set_flush_denormal(True)
  7630. True
  7631. >>> torch.tensor([1e-323], dtype=torch.float64)
  7632. tensor([ 0.], dtype=torch.float64)
  7633. >>> torch.set_flush_denormal(False)
  7634. True
  7635. >>> torch.tensor([1e-323], dtype=torch.float64)
  7636. tensor(9.88131e-324 *
  7637. [ 1.0000], dtype=torch.float64)
  7638. """,
  7639. )
  7640. add_docstr(
  7641. torch.set_num_threads,
  7642. r"""
  7643. set_num_threads(int)
  7644. Sets the number of threads used for intraop parallelism on CPU.
  7645. .. warning::
  7646. To ensure that the correct number of threads is used, set_num_threads
  7647. must be called before running eager, JIT or autograd code.
  7648. """,
  7649. )
  7650. add_docstr(
  7651. torch.set_num_interop_threads,
  7652. r"""
  7653. set_num_interop_threads(int)
  7654. Sets the number of threads used for interop parallelism
  7655. (e.g. in JIT interpreter) on CPU.
  7656. .. warning::
  7657. Can only be called once and before any inter-op parallel work
  7658. is started (e.g. JIT execution).
  7659. """,
  7660. )
  7661. add_docstr(
  7662. torch.sigmoid,
  7663. r"""
  7664. sigmoid(input, *, out=None) -> Tensor
  7665. Alias for :func:`torch.special.expit`.
  7666. """,
  7667. )
  7668. add_docstr(
  7669. torch.logit,
  7670. r"""
  7671. logit(input, eps=None, *, out=None) -> Tensor
  7672. Alias for :func:`torch.special.logit`.
  7673. """,
  7674. )
  7675. add_docstr(
  7676. torch.sign,
  7677. r"""
  7678. sign(input, *, out=None) -> Tensor
  7679. Returns a new tensor with the signs of the elements of :attr:`input`.
  7680. .. math::
  7681. \text{out}_{i} = \operatorname{sgn}(\text{input}_{i})
  7682. """
  7683. + r"""
  7684. Args:
  7685. {input}
  7686. Keyword args:
  7687. {out}
  7688. Example::
  7689. >>> a = torch.tensor([0.7, -1.2, 0., 2.3])
  7690. >>> a
  7691. tensor([ 0.7000, -1.2000, 0.0000, 2.3000])
  7692. >>> torch.sign(a)
  7693. tensor([ 1., -1., 0., 1.])
  7694. """.format(**common_args),
  7695. )
  7696. add_docstr(
  7697. torch.signbit,
  7698. r"""
  7699. signbit(input, *, out=None) -> Tensor
  7700. Tests if each element of :attr:`input` has its sign bit set or not.
  7701. Args:
  7702. {input}
  7703. Keyword args:
  7704. {out}
  7705. Example::
  7706. >>> a = torch.tensor([0.7, -1.2, 0., 2.3])
  7707. >>> torch.signbit(a)
  7708. tensor([ False, True, False, False])
  7709. >>> a = torch.tensor([-0.0, 0.0])
  7710. >>> torch.signbit(a)
  7711. tensor([ True, False])
  7712. .. note::
  7713. signbit handles signed zeros, so negative zero (-0) returns True.
  7714. """.format(**common_args),
  7715. )
  7716. add_docstr(
  7717. torch.sgn,
  7718. r"""
  7719. sgn(input, *, out=None) -> Tensor
  7720. This function is an extension of torch.sign() to complex tensors.
  7721. It computes a new tensor whose elements have
  7722. the same angles as the corresponding elements of :attr:`input` and
  7723. absolute values (i.e. magnitudes) of one for complex tensors and
  7724. is equivalent to torch.sign() for non-complex tensors.
  7725. .. math::
  7726. \text{out}_{i} = \begin{cases}
  7727. 0 & |\text{{input}}_i| == 0 \\
  7728. \frac{{\text{{input}}_i}}{|{\text{{input}}_i}|} & \text{otherwise}
  7729. \end{cases}
  7730. """
  7731. + r"""
  7732. Args:
  7733. {input}
  7734. Keyword args:
  7735. {out}
  7736. Example::
  7737. >>> t = torch.tensor([3+4j, 7-24j, 0, 1+2j])
  7738. >>> t.sgn()
  7739. tensor([0.6000+0.8000j, 0.2800-0.9600j, 0.0000+0.0000j, 0.4472+0.8944j])
  7740. """.format(**common_args),
  7741. )
  7742. add_docstr(
  7743. torch.sin,
  7744. r"""
  7745. sin(input, *, out=None) -> Tensor
  7746. Returns a new tensor with the sine of the elements in the :attr:`input` tensor,
  7747. where each value in this input tensor is in radians.
  7748. .. math::
  7749. \text{out}_{i} = \sin(\text{input}_{i})
  7750. """
  7751. + r"""
  7752. Args:
  7753. {input}
  7754. Keyword args:
  7755. {out}
  7756. Example::
  7757. >>> a = torch.randn(4)
  7758. >>> a
  7759. tensor([-0.5461, 0.1347, -2.7266, -0.2746])
  7760. >>> torch.sin(a)
  7761. tensor([-0.5194, 0.1343, -0.4032, -0.2711])
  7762. """.format(**common_args),
  7763. )
  7764. add_docstr(
  7765. torch.sinc,
  7766. r"""
  7767. sinc(input, *, out=None) -> Tensor
  7768. Alias for :func:`torch.special.sinc`.
  7769. """,
  7770. )
  7771. add_docstr(
  7772. torch.sinh,
  7773. r"""
  7774. sinh(input, *, out=None) -> Tensor
  7775. Returns a new tensor with the hyperbolic sine of the elements of
  7776. :attr:`input`.
  7777. .. math::
  7778. \text{out}_{i} = \sinh(\text{input}_{i})
  7779. """
  7780. + r"""
  7781. Args:
  7782. {input}
  7783. Keyword args:
  7784. {out}
  7785. Example::
  7786. >>> a = torch.randn(4)
  7787. >>> a
  7788. tensor([ 0.5380, -0.8632, -0.1265, 0.9399])
  7789. >>> torch.sinh(a)
  7790. tensor([ 0.5644, -0.9744, -0.1268, 1.0845])
  7791. .. note::
  7792. When :attr:`input` is on the CPU, the implementation of torch.sinh may use
  7793. the Sleef library, which rounds very large results to infinity or negative
  7794. infinity. See `here <https://sleef.org/purec.xhtml>`_ for details.
  7795. """.format(**common_args),
  7796. )
  7797. add_docstr(
  7798. torch.sort,
  7799. r"""
  7800. sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor)
  7801. Sorts the elements of the :attr:`input` tensor along a given dimension
  7802. in ascending order by value.
  7803. If :attr:`dim` is not given, the last dimension of the `input` is chosen.
  7804. If :attr:`descending` is ``True`` then the elements are sorted in descending
  7805. order by value.
  7806. If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving
  7807. the order of equivalent elements.
  7808. A namedtuple of (values, indices) is returned, where the `values` are the
  7809. sorted values and `indices` are the indices of the elements in the original
  7810. `input` tensor.
  7811. Args:
  7812. {input}
  7813. dim (int, optional): the dimension to sort along
  7814. descending (bool, optional): controls the sorting order (ascending or descending)
  7815. Keyword args:
  7816. stable (bool, optional): makes the sorting routine stable, which guarantees that the order
  7817. of equivalent elements is preserved.
  7818. out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can
  7819. be optionally given to be used as output buffers
  7820. Example::
  7821. >>> x = torch.randn(3, 4)
  7822. >>> sorted, indices = torch.sort(x)
  7823. >>> sorted
  7824. tensor([[-0.2162, 0.0608, 0.6719, 2.3332],
  7825. [-0.5793, 0.0061, 0.6058, 0.9497],
  7826. [-0.5071, 0.3343, 0.9553, 1.0960]])
  7827. >>> indices
  7828. tensor([[ 1, 0, 2, 3],
  7829. [ 3, 1, 0, 2],
  7830. [ 0, 3, 1, 2]])
  7831. >>> sorted, indices = torch.sort(x, 0)
  7832. >>> sorted
  7833. tensor([[-0.5071, -0.2162, 0.6719, -0.5793],
  7834. [ 0.0608, 0.0061, 0.9497, 0.3343],
  7835. [ 0.6058, 0.9553, 1.0960, 2.3332]])
  7836. >>> indices
  7837. tensor([[ 2, 0, 0, 1],
  7838. [ 0, 1, 1, 2],
  7839. [ 1, 2, 2, 0]])
  7840. >>> x = torch.tensor([0, 1] * 9)
  7841. >>> x.sort()
  7842. torch.return_types.sort(
  7843. values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]),
  7844. indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1]))
  7845. >>> x.sort(stable=True)
  7846. torch.return_types.sort(
  7847. values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]),
  7848. indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17]))
  7849. """.format(**common_args),
  7850. )
  7851. add_docstr(
  7852. torch.argsort,
  7853. r"""
  7854. argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor
  7855. Returns the indices that sort a tensor along a given dimension in ascending
  7856. order by value.
  7857. This is the second value returned by :meth:`torch.sort`. See its documentation
  7858. for the exact semantics of this method.
  7859. If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving
  7860. the order of equivalent elements. If ``False``, the relative order of values
  7861. which compare equal is not guaranteed. ``True`` is slower.
  7862. Args:
  7863. {input}
  7864. dim (int, optional): the dimension to sort along
  7865. descending (bool, optional): controls the sorting order (ascending or descending)
  7866. Keyword args:
  7867. stable (bool, optional): controls the relative order of equivalent elements
  7868. Example::
  7869. >>> a = torch.randn(4, 4)
  7870. >>> a
  7871. tensor([[ 0.0785, 1.5267, -0.8521, 0.4065],
  7872. [ 0.1598, 0.0788, -0.0745, -1.2700],
  7873. [ 1.2208, 1.0722, -0.7064, 1.2564],
  7874. [ 0.0669, -0.2318, -0.8229, -0.9280]])
  7875. >>> torch.argsort(a, dim=1)
  7876. tensor([[2, 0, 3, 1],
  7877. [3, 2, 1, 0],
  7878. [2, 1, 0, 3],
  7879. [3, 2, 1, 0]])
  7880. """.format(**common_args),
  7881. )
  7882. add_docstr(
  7883. torch.msort,
  7884. r"""
  7885. msort(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  7886. Sorts the elements of the :attr:`input` tensor along its first dimension
  7887. in ascending order by value.
  7888. .. note:: `torch.msort(t)` is equivalent to `torch.sort(t, dim=0)[0]`.
  7889. See also :func:`torch.sort`.
  7890. Args:
  7891. {input}
  7892. Keyword args:
  7893. {out}
  7894. Example::
  7895. >>> t = torch.randn(3, 4)
  7896. >>> t
  7897. tensor([[-0.1321, 0.4370, -1.2631, -1.1289],
  7898. [-2.0527, -1.1250, 0.2275, 0.3077],
  7899. [-0.0881, -0.1259, -0.5495, 1.0284]])
  7900. >>> torch.msort(t)
  7901. tensor([[-2.0527, -1.1250, -1.2631, -1.1289],
  7902. [-0.1321, -0.1259, -0.5495, 0.3077],
  7903. [-0.0881, 0.4370, 0.2275, 1.0284]])
  7904. """.format(**common_args),
  7905. )
  7906. add_docstr(
  7907. torch.sparse_compressed_tensor,
  7908. r"""sparse_compressed_tensor(compressed_indices, plain_indices, values, size=None, """
  7909. r"""*, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor
  7910. Constructs a :ref:`sparse tensor in Compressed Sparse format - CSR,
  7911. CSC, BSR, or BSC - <sparse-compressed-docs>` with specified values at
  7912. the given :attr:`compressed_indices` and :attr:`plain_indices`. Sparse
  7913. matrix multiplication operations in Compressed Sparse format are
  7914. typically faster than that for sparse tensors in COO format. Make you
  7915. have a look at :ref:`the note on the data type of the indices
  7916. <sparse-compressed-docs>`.
  7917. {sparse_factory_device_note}
  7918. Args:
  7919. compressed_indices (array_like): (B+1)-dimensional array of size
  7920. ``(*batchsize, compressed_dim_size + 1)``. The last element of
  7921. each batch is the number of non-zero elements or blocks. This
  7922. tensor encodes the index in ``values`` and ``plain_indices``
  7923. depending on where the given compressed dimension (row or
  7924. column) starts. Each successive number in the tensor
  7925. subtracted by the number before it denotes the number of
  7926. elements or blocks in a given compressed dimension.
  7927. plain_indices (array_like): Plain dimension (column or row)
  7928. coordinates of each element or block in values. (B+1)-dimensional
  7929. tensor with the same length as values.
  7930. values (array_list): Initial values for the tensor. Can be a list,
  7931. tuple, NumPy ``ndarray``, scalar, and other types. that
  7932. represents a (1+K)-dimensional (for CSR and CSC layouts) or
  7933. (1+2+K)-dimensional tensor (for BSR and BSC layouts) where
  7934. ``K`` is the number of dense dimensions.
  7935. size (list, tuple, :class:`torch.Size`, optional): Size of the
  7936. sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols *
  7937. blocksize[1], *densesize)`` where ``blocksize[0] ==
  7938. blocksize[1] == 1`` for CSR and CSC formats. If not provided,
  7939. the size will be inferred as the minimum size big enough to
  7940. hold all non-zero elements or blocks.
  7941. Keyword args:
  7942. dtype (:class:`torch.dtype`, optional): the desired data type of
  7943. returned tensor. Default: if None, infers data type from
  7944. :attr:`values`.
  7945. layout (:class:`torch.layout`, required): the desired layout of
  7946. returned tensor: :attr:`torch.sparse_csr`,
  7947. :attr:`torch.sparse_csc`, :attr:`torch.sparse_bsr`, or
  7948. :attr:`torch.sparse_bsc`.
  7949. device (:class:`torch.device`, optional): the desired device of
  7950. returned tensor. Default: if None, uses the current device
  7951. for the default tensor type (see
  7952. :func:`torch.set_default_device`). :attr:`device` will be
  7953. the CPU for CPU tensor types and the current CUDA device for
  7954. CUDA tensor types.
  7955. {pin_memory}
  7956. {requires_grad}
  7957. {check_invariants}
  7958. Example::
  7959. >>> compressed_indices = [0, 2, 4]
  7960. >>> plain_indices = [0, 1, 0, 1]
  7961. >>> values = [1, 2, 3, 4]
  7962. >>> torch.sparse_compressed_tensor(torch.tensor(compressed_indices, dtype=torch.int64),
  7963. ... torch.tensor(plain_indices, dtype=torch.int64),
  7964. ... torch.tensor(values), dtype=torch.double, layout=torch.sparse_csr)
  7965. tensor(crow_indices=tensor([0, 2, 4]),
  7966. col_indices=tensor([0, 1, 0, 1]),
  7967. values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4,
  7968. dtype=torch.float64, layout=torch.sparse_csr)
  7969. """.format(**factory_common_args),
  7970. )
  7971. add_docstr(
  7972. torch.sparse_csr_tensor,
  7973. r"""sparse_csr_tensor(crow_indices, col_indices, values, size=None, """
  7974. r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor
  7975. Constructs a :ref:`sparse tensor in CSR (Compressed Sparse Row) <sparse-csr-docs>` with specified
  7976. values at the given :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix multiplication operations
  7977. in CSR format are typically faster than that for sparse tensors in COO format. Make you have a look
  7978. at :ref:`the note on the data type of the indices <sparse-csr-docs>`.
  7979. {sparse_factory_device_note}
  7980. Args:
  7981. crow_indices (array_like): (B+1)-dimensional array of size
  7982. ``(*batchsize, nrows + 1)``. The last element of each batch
  7983. is the number of non-zeros. This tensor encodes the index in
  7984. values and col_indices depending on where the given row
  7985. starts. Each successive number in the tensor subtracted by the
  7986. number before it denotes the number of elements in a given
  7987. row.
  7988. col_indices (array_like): Column coordinates of each element in
  7989. values. (B+1)-dimensional tensor with the same length
  7990. as values.
  7991. values (array_list): Initial values for the tensor. Can be a list,
  7992. tuple, NumPy ``ndarray``, scalar, and other types that
  7993. represents a (1+K)-dimensional tensor where ``K`` is the number
  7994. of dense dimensions.
  7995. size (list, tuple, :class:`torch.Size`, optional): Size of the
  7996. sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If
  7997. not provided, the size will be inferred as the minimum size
  7998. big enough to hold all non-zero elements.
  7999. Keyword args:
  8000. dtype (:class:`torch.dtype`, optional): the desired data type of
  8001. returned tensor. Default: if None, infers data type from
  8002. :attr:`values`.
  8003. device (:class:`torch.device`, optional): the desired device of
  8004. returned tensor. Default: if None, uses the current device
  8005. for the default tensor type (see
  8006. :func:`torch.set_default_device`). :attr:`device` will be
  8007. the CPU for CPU tensor types and the current CUDA device for
  8008. CUDA tensor types.
  8009. {pin_memory}
  8010. {requires_grad}
  8011. {check_invariants}
  8012. Example::
  8013. >>> crow_indices = [0, 2, 4]
  8014. >>> col_indices = [0, 1, 0, 1]
  8015. >>> values = [1, 2, 3, 4]
  8016. >>> torch.sparse_csr_tensor(torch.tensor(crow_indices, dtype=torch.int64),
  8017. ... torch.tensor(col_indices, dtype=torch.int64),
  8018. ... torch.tensor(values), dtype=torch.double)
  8019. tensor(crow_indices=tensor([0, 2, 4]),
  8020. col_indices=tensor([0, 1, 0, 1]),
  8021. values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4,
  8022. dtype=torch.float64, layout=torch.sparse_csr)
  8023. """.format(**factory_common_args),
  8024. )
  8025. add_docstr(
  8026. torch.sparse_csc_tensor,
  8027. r"""sparse_csc_tensor(ccol_indices, row_indices, values, size=None, """
  8028. r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor
  8029. Constructs a :ref:`sparse tensor in CSC (Compressed Sparse Column)
  8030. <sparse-csc-docs>` with specified values at the given
  8031. :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix
  8032. multiplication operations in CSC format are typically faster than that
  8033. for sparse tensors in COO format. Make you have a look at :ref:`the
  8034. note on the data type of the indices <sparse-csc-docs>`.
  8035. {sparse_factory_device_note}
  8036. Args:
  8037. ccol_indices (array_like): (B+1)-dimensional array of size
  8038. ``(*batchsize, ncols + 1)``. The last element of each batch
  8039. is the number of non-zeros. This tensor encodes the index in
  8040. values and row_indices depending on where the given column
  8041. starts. Each successive number in the tensor subtracted by the
  8042. number before it denotes the number of elements in a given
  8043. column.
  8044. row_indices (array_like): Row coordinates of each element in
  8045. values. (B+1)-dimensional tensor with the same length as
  8046. values.
  8047. values (array_list): Initial values for the tensor. Can be a list,
  8048. tuple, NumPy ``ndarray``, scalar, and other types that
  8049. represents a (1+K)-dimensional tensor where ``K`` is the number
  8050. of dense dimensions.
  8051. size (list, tuple, :class:`torch.Size`, optional): Size of the
  8052. sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If
  8053. not provided, the size will be inferred as the minimum size
  8054. big enough to hold all non-zero elements.
  8055. Keyword args:
  8056. dtype (:class:`torch.dtype`, optional): the desired data type of
  8057. returned tensor. Default: if None, infers data type from
  8058. :attr:`values`.
  8059. device (:class:`torch.device`, optional): the desired device of
  8060. returned tensor. Default: if None, uses the current device
  8061. for the default tensor type (see
  8062. :func:`torch.set_default_device`). :attr:`device` will be
  8063. the CPU for CPU tensor types and the current CUDA device for
  8064. CUDA tensor types.
  8065. {pin_memory}
  8066. {requires_grad}
  8067. {check_invariants}
  8068. Example::
  8069. >>> ccol_indices = [0, 2, 4]
  8070. >>> row_indices = [0, 1, 0, 1]
  8071. >>> values = [1, 2, 3, 4]
  8072. >>> torch.sparse_csc_tensor(torch.tensor(ccol_indices, dtype=torch.int64),
  8073. ... torch.tensor(row_indices, dtype=torch.int64),
  8074. ... torch.tensor(values), dtype=torch.double)
  8075. tensor(ccol_indices=tensor([0, 2, 4]),
  8076. row_indices=tensor([0, 1, 0, 1]),
  8077. values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4,
  8078. dtype=torch.float64, layout=torch.sparse_csc)
  8079. """.format(**factory_common_args),
  8080. )
  8081. add_docstr(
  8082. torch.sparse_bsr_tensor,
  8083. r"""sparse_bsr_tensor(crow_indices, col_indices, values, size=None, """
  8084. r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor
  8085. Constructs a :ref:`sparse tensor in BSR (Block Compressed Sparse Row))
  8086. <sparse-bsr-docs>` with specified 2-dimensional blocks at the given
  8087. :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix
  8088. multiplication operations in BSR format are typically faster than that
  8089. for sparse tensors in COO format. Make you have a look at :ref:`the
  8090. note on the data type of the indices <sparse-bsr-docs>`.
  8091. {sparse_factory_device_note}
  8092. Args:
  8093. crow_indices (array_like): (B+1)-dimensional array of size
  8094. ``(*batchsize, nrowblocks + 1)``. The last element of each
  8095. batch is the number of non-zeros. This tensor encodes the
  8096. block index in values and col_indices depending on where the
  8097. given row block starts. Each successive number in the tensor
  8098. subtracted by the number before it denotes the number of
  8099. blocks in a given row.
  8100. col_indices (array_like): Column block coordinates of each block
  8101. in values. (B+1)-dimensional tensor with the same length as
  8102. values.
  8103. values (array_list): Initial values for the tensor. Can be a list,
  8104. tuple, NumPy ``ndarray``, scalar, and other types that
  8105. represents a (1 + 2 + K)-dimensional tensor where ``K`` is the
  8106. number of dense dimensions.
  8107. size (list, tuple, :class:`torch.Size`, optional): Size of the
  8108. sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols *
  8109. blocksize[1], *densesize)`` where ``blocksize ==
  8110. values.shape[1:3]``. If not provided, the size will be
  8111. inferred as the minimum size big enough to hold all non-zero
  8112. blocks.
  8113. Keyword args:
  8114. dtype (:class:`torch.dtype`, optional): the desired data type of
  8115. returned tensor. Default: if None, infers data type from
  8116. :attr:`values`.
  8117. device (:class:`torch.device`, optional): the desired device of
  8118. returned tensor. Default: if None, uses the current device
  8119. for the default tensor type (see
  8120. :func:`torch.set_default_device`). :attr:`device` will be
  8121. the CPU for CPU tensor types and the current CUDA device for
  8122. CUDA tensor types.
  8123. {pin_memory}
  8124. {requires_grad}
  8125. {check_invariants}
  8126. Example::
  8127. >>> crow_indices = [0, 1, 2]
  8128. >>> col_indices = [0, 1]
  8129. >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
  8130. >>> torch.sparse_bsr_tensor(torch.tensor(crow_indices, dtype=torch.int64),
  8131. ... torch.tensor(col_indices, dtype=torch.int64),
  8132. ... torch.tensor(values), dtype=torch.double)
  8133. tensor(crow_indices=tensor([0, 1, 2]),
  8134. col_indices=tensor([0, 1]),
  8135. values=tensor([[[1., 2.],
  8136. [3., 4.]],
  8137. [[5., 6.],
  8138. [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64,
  8139. layout=torch.sparse_bsr)
  8140. """.format(**factory_common_args),
  8141. )
  8142. add_docstr(
  8143. torch.sparse_bsc_tensor,
  8144. r"""sparse_bsc_tensor(ccol_indices, row_indices, values, size=None, """
  8145. r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor
  8146. Constructs a :ref:`sparse tensor in BSC (Block Compressed Sparse
  8147. Column)) <sparse-bsc-docs>` with specified 2-dimensional blocks at the
  8148. given :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix
  8149. multiplication operations in BSC format are typically faster than that
  8150. for sparse tensors in COO format. Make you have a look at :ref:`the
  8151. note on the data type of the indices <sparse-bsc-docs>`.
  8152. {sparse_factory_device_note}
  8153. Args:
  8154. ccol_indices (array_like): (B+1)-dimensional array of size
  8155. ``(*batchsize, ncolblocks + 1)``. The last element of each
  8156. batch is the number of non-zeros. This tensor encodes the
  8157. index in values and row_indices depending on where the given
  8158. column starts. Each successive number in the tensor subtracted
  8159. by the number before it denotes the number of elements in a
  8160. given column.
  8161. row_indices (array_like): Row block coordinates of each block in
  8162. values. (B+1)-dimensional tensor with the same length
  8163. as values.
  8164. values (array_list): Initial blocks for the tensor. Can be a list,
  8165. tuple, NumPy ``ndarray``, and other types that
  8166. represents a (1 + 2 + K)-dimensional tensor where ``K`` is the
  8167. number of dense dimensions.
  8168. size (list, tuple, :class:`torch.Size`, optional): Size of the
  8169. sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols *
  8170. blocksize[1], *densesize)`` If not provided, the size will be
  8171. inferred as the minimum size big enough to hold all non-zero
  8172. blocks.
  8173. Keyword args:
  8174. dtype (:class:`torch.dtype`, optional): the desired data type of
  8175. returned tensor. Default: if None, infers data type from
  8176. :attr:`values`.
  8177. device (:class:`torch.device`, optional): the desired device of
  8178. returned tensor. Default: if None, uses the current device
  8179. for the default tensor type (see
  8180. :func:`torch.set_default_device`). :attr:`device` will be
  8181. the CPU for CPU tensor types and the current CUDA device for
  8182. CUDA tensor types.
  8183. {pin_memory}
  8184. {requires_grad}
  8185. {check_invariants}
  8186. Example::
  8187. >>> ccol_indices = [0, 1, 2]
  8188. >>> row_indices = [0, 1]
  8189. >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
  8190. >>> torch.sparse_bsc_tensor(torch.tensor(ccol_indices, dtype=torch.int64),
  8191. ... torch.tensor(row_indices, dtype=torch.int64),
  8192. ... torch.tensor(values), dtype=torch.double)
  8193. tensor(ccol_indices=tensor([0, 1, 2]),
  8194. row_indices=tensor([0, 1]),
  8195. values=tensor([[[1., 2.],
  8196. [3., 4.]],
  8197. [[5., 6.],
  8198. [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64,
  8199. layout=torch.sparse_bsc)
  8200. """.format(**factory_common_args),
  8201. )
  8202. add_docstr(
  8203. torch.sparse_coo_tensor,
  8204. r"""sparse_coo_tensor(indices, values, size=None, """
  8205. r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None, is_coalesced=None) -> Tensor
  8206. Constructs a :ref:`sparse tensor in COO(rdinate) format
  8207. <sparse-coo-docs>` with specified values at the given
  8208. :attr:`indices`.
  8209. .. note::
  8210. This function returns an :ref:`uncoalesced tensor
  8211. <sparse-uncoalesced-coo-docs>` when :attr:`is_coalesced` is
  8212. unspecified or ``None``.
  8213. {sparse_factory_device_note}
  8214. Args:
  8215. indices (array_like): Initial data for the tensor. Can be a list, tuple,
  8216. NumPy ``ndarray``, scalar, and other types. Will be cast to a :class:`torch.LongTensor`
  8217. internally. The indices are the coordinates of the non-zero values in the matrix, and thus
  8218. should be two-dimensional where the first dimension is the number of tensor dimensions and
  8219. the second dimension is the number of non-zero values.
  8220. values (array_like): Initial values for the tensor. Can be a list, tuple,
  8221. NumPy ``ndarray``, scalar, and other types.
  8222. size (list, tuple, or :class:`torch.Size`, optional): Size of the sparse tensor. If not
  8223. provided the size will be inferred as the minimum size big enough to hold all non-zero
  8224. elements.
  8225. Keyword args:
  8226. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
  8227. Default: if None, infers data type from :attr:`values`.
  8228. device (:class:`torch.device`, optional): the desired device of returned tensor.
  8229. Default: if None, uses the current device for the default tensor type
  8230. (see :func:`torch.set_default_device`). :attr:`device` will be the CPU
  8231. for CPU tensor types and the current CUDA device for CUDA tensor types.
  8232. {pin_memory}
  8233. {requires_grad}
  8234. {check_invariants}
  8235. is_coalesced (bool, optional): When``True``, the caller is
  8236. responsible for providing tensor indices that correspond to a
  8237. coalesced tensor. If the :attr:`check_invariants` flag is
  8238. False, no error will be raised if the prerequisites are not
  8239. met and this will lead to silently incorrect results. To force
  8240. coalescion please use :meth:`coalesce` on the resulting
  8241. Tensor.
  8242. Default: None: except for trivial cases (e.g. nnz < 2) the
  8243. resulting Tensor has is_coalesced set to ``False```.
  8244. Example::
  8245. >>> i = torch.tensor([[0, 1, 1],
  8246. ... [2, 0, 2]])
  8247. >>> v = torch.tensor([3, 4, 5], dtype=torch.float32)
  8248. >>> torch.sparse_coo_tensor(i, v, [2, 4])
  8249. tensor(indices=tensor([[0, 1, 1],
  8250. [2, 0, 2]]),
  8251. values=tensor([3., 4., 5.]),
  8252. size=(2, 4), nnz=3, layout=torch.sparse_coo)
  8253. >>> torch.sparse_coo_tensor(i, v) # Shape inference
  8254. tensor(indices=tensor([[0, 1, 1],
  8255. [2, 0, 2]]),
  8256. values=tensor([3., 4., 5.]),
  8257. size=(2, 3), nnz=3, layout=torch.sparse_coo)
  8258. >>> torch.sparse_coo_tensor(i, v, [2, 4],
  8259. ... dtype=torch.float64,
  8260. ... device=torch.device('cuda:0'))
  8261. tensor(indices=tensor([[0, 1, 1],
  8262. [2, 0, 2]]),
  8263. values=tensor([3., 4., 5.]),
  8264. device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64,
  8265. layout=torch.sparse_coo)
  8266. # Create an empty sparse tensor with the following invariants:
  8267. # 1. sparse_dim + dense_dim = len(SparseTensor.shape)
  8268. # 2. SparseTensor._indices().shape = (sparse_dim, nnz)
  8269. # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:])
  8270. #
  8271. # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and
  8272. # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0))
  8273. >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1])
  8274. tensor(indices=tensor([], size=(1, 0)),
  8275. values=tensor([], size=(0,)),
  8276. size=(1,), nnz=0, layout=torch.sparse_coo)
  8277. # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and
  8278. # sparse_dim = 1
  8279. >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2])
  8280. tensor(indices=tensor([], size=(1, 0)),
  8281. values=tensor([], size=(0, 2)),
  8282. size=(1, 2), nnz=0, layout=torch.sparse_coo)
  8283. .. _torch.sparse: https://pytorch.org/docs/stable/sparse.html
  8284. """.format(**factory_common_args),
  8285. )
  8286. add_docstr(
  8287. torch.sqrt,
  8288. r"""
  8289. sqrt(input, *, out=None) -> Tensor
  8290. Returns a new tensor with the square-root of the elements of :attr:`input`.
  8291. .. math::
  8292. \text{out}_{i} = \sqrt{\text{input}_{i}}
  8293. """
  8294. + r"""
  8295. Args:
  8296. {input}
  8297. Keyword args:
  8298. {out}
  8299. Example::
  8300. >>> a = torch.randn(4)
  8301. >>> a
  8302. tensor([-2.0755, 1.0226, 0.0831, 0.4806])
  8303. >>> torch.sqrt(a)
  8304. tensor([ nan, 1.0112, 0.2883, 0.6933])
  8305. """.format(**common_args),
  8306. )
  8307. add_docstr(
  8308. torch.square,
  8309. r"""
  8310. square(input: Tensor, *, out: Optional[Tensor]) -> Tensor
  8311. Returns a new tensor with the square of the elements of :attr:`input`.
  8312. Args:
  8313. {input}
  8314. Keyword args:
  8315. {out}
  8316. Example::
  8317. >>> a = torch.randn(4)
  8318. >>> a
  8319. tensor([-2.0755, 1.0226, 0.0831, 0.4806])
  8320. >>> torch.square(a)
  8321. tensor([ 4.3077, 1.0457, 0.0069, 0.2310])
  8322. """.format(**common_args),
  8323. )
  8324. add_docstr(
  8325. torch.squeeze,
  8326. r"""
  8327. squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor
  8328. Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed.
  8329. For example, if `input` is of shape:
  8330. :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()`
  8331. will be of shape: :math:`(A \times B \times C \times D)`.
  8332. When :attr:`dim` is given, a squeeze operation is done only in the given
  8333. dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`,
  8334. ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)``
  8335. will squeeze the tensor to the shape :math:`(A \times B)`.
  8336. .. note:: The returned tensor shares the storage with the input tensor,
  8337. so changing the contents of one will change the contents of the other.
  8338. .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)`
  8339. will also remove the batch dimension, which can lead to unexpected
  8340. errors. Consider specifying only the dims you wish to be squeezed.
  8341. Args:
  8342. {input}
  8343. dim (int or tuple of ints, optional): if given, the input will be squeezed
  8344. only in the specified dimensions.
  8345. .. versionchanged:: 2.0
  8346. :attr:`dim` now accepts tuples of dimensions.
  8347. Example::
  8348. >>> x = torch.zeros(2, 1, 2, 1, 2)
  8349. >>> x.size()
  8350. torch.Size([2, 1, 2, 1, 2])
  8351. >>> y = torch.squeeze(x)
  8352. >>> y.size()
  8353. torch.Size([2, 2, 2])
  8354. >>> y = torch.squeeze(x, 0)
  8355. >>> y.size()
  8356. torch.Size([2, 1, 2, 1, 2])
  8357. >>> y = torch.squeeze(x, 1)
  8358. >>> y.size()
  8359. torch.Size([2, 2, 1, 2])
  8360. >>> y = torch.squeeze(x, (1, 2, 3))
  8361. torch.Size([2, 2, 2])
  8362. """.format(**common_args),
  8363. )
  8364. add_docstr(
  8365. torch.std,
  8366. r"""
  8367. std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor
  8368. Calculates the standard deviation over the dimensions specified by :attr:`dim`.
  8369. :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to
  8370. reduce over all dimensions.
  8371. The standard deviation (:math:`\sigma`) is calculated as
  8372. .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2}
  8373. where :math:`x` is the sample set of elements, :math:`\bar{x}` is the
  8374. sample mean, :math:`N` is the number of samples and :math:`\delta N` is
  8375. the :attr:`correction`.
  8376. """
  8377. + r"""
  8378. {keepdim_details}
  8379. Args:
  8380. {input}
  8381. {opt_dim_all_reduce}
  8382. Keyword args:
  8383. correction (int): difference between the sample size and sample degrees of freedom.
  8384. Defaults to `Bessel's correction`_, ``correction=1``.
  8385. .. versionchanged:: 2.0
  8386. Previously this argument was called ``unbiased`` and was a boolean
  8387. with ``True`` corresponding to ``correction=1`` and ``False`` being
  8388. ``correction=0``.
  8389. {opt_keepdim}
  8390. {out}
  8391. Example:
  8392. >>> a = torch.tensor(
  8393. ... [[ 0.2035, 1.2959, 1.8101, -0.4644],
  8394. ... [ 1.5027, -0.3270, 0.5905, 0.6538],
  8395. ... [-1.5745, 1.3330, -0.5596, -0.6548],
  8396. ... [ 0.1264, -0.5080, 1.6420, 0.1992]]
  8397. ... ) # fmt: skip
  8398. >>> torch.std(a, dim=1, keepdim=True)
  8399. tensor([[1.0311],
  8400. [0.7477],
  8401. [1.2204],
  8402. [0.9087]])
  8403. .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction
  8404. """.format(**multi_dim_common),
  8405. )
  8406. add_docstr(
  8407. torch.std_mean,
  8408. r"""
  8409. std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor)
  8410. Calculates the standard deviation and mean over the dimensions specified by
  8411. :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or
  8412. ``None`` to reduce over all dimensions.
  8413. The standard deviation (:math:`\sigma`) is calculated as
  8414. .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2}
  8415. where :math:`x` is the sample set of elements, :math:`\bar{x}` is the
  8416. sample mean, :math:`N` is the number of samples and :math:`\delta N` is
  8417. the :attr:`correction`.
  8418. """
  8419. + r"""
  8420. {keepdim_details}
  8421. Args:
  8422. {input}
  8423. {opt_dim_all_reduce}
  8424. Keyword args:
  8425. correction (int): difference between the sample size and sample degrees of freedom.
  8426. Defaults to `Bessel's correction`_, ``correction=1``.
  8427. .. versionchanged:: 2.0
  8428. Previously this argument was called ``unbiased`` and was a boolean
  8429. with ``True`` corresponding to ``correction=1`` and ``False`` being
  8430. ``correction=0``.
  8431. {opt_keepdim}
  8432. {out}
  8433. Returns:
  8434. A tuple (std, mean) containing the standard deviation and mean.
  8435. Example:
  8436. >>> a = torch.tensor(
  8437. ... [[ 0.2035, 1.2959, 1.8101, -0.4644],
  8438. ... [ 1.5027, -0.3270, 0.5905, 0.6538],
  8439. ... [-1.5745, 1.3330, -0.5596, -0.6548],
  8440. ... [ 0.1264, -0.5080, 1.6420, 0.1992]]
  8441. ... ) # fmt: skip
  8442. >>> torch.std_mean(a, dim=0, keepdim=True)
  8443. (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]),
  8444. tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]]))
  8445. .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction
  8446. """.format(**multi_dim_common),
  8447. )
  8448. add_docstr(
  8449. torch.sub,
  8450. r"""
  8451. sub(input, other, *, alpha=1, out=None) -> Tensor
  8452. Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`.
  8453. .. math::
  8454. \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i
  8455. """
  8456. + r"""
  8457. Supports :ref:`broadcasting to a common shape <broadcasting-semantics>`,
  8458. :ref:`type promotion <type-promotion-doc>`, and integer, float, and complex inputs.
  8459. Args:
  8460. {input}
  8461. other (Tensor or Number): the tensor or number to subtract from :attr:`input`.
  8462. Keyword args:
  8463. alpha (Number): the multiplier for :attr:`other`.
  8464. {out}
  8465. Example::
  8466. >>> a = torch.tensor((1, 2))
  8467. >>> b = torch.tensor((0, 1))
  8468. >>> torch.sub(a, b, alpha=2)
  8469. tensor([1, 0])
  8470. """.format(**common_args),
  8471. )
  8472. add_docstr(
  8473. torch.subtract,
  8474. r"""
  8475. subtract(input, other, *, alpha=1, out=None) -> Tensor
  8476. Alias for :func:`torch.sub`.
  8477. """,
  8478. )
  8479. add_docstr(
  8480. torch.sum,
  8481. r"""
  8482. sum(input, *, dtype=None) -> Tensor
  8483. Returns the sum of all elements in the :attr:`input` tensor.
  8484. Args:
  8485. {input}
  8486. Keyword args:
  8487. {dtype}
  8488. .. note:: Use the `dtype` argument if you need the result in a specific tensor type.
  8489. Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`).
  8490. Example::
  8491. >>> a = torch.randn(1, 3)
  8492. >>> a
  8493. tensor([[ 0.1133, -0.9567, 0.2958]])
  8494. >>> torch.sum(a)
  8495. tensor(-0.5475)
  8496. .. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor
  8497. :noindex:
  8498. Returns the sum of each row of the :attr:`input` tensor in the given
  8499. dimension :attr:`dim`. If :attr:`dim` is a list of dimensions,
  8500. reduce over all of them.
  8501. {keepdim_details}
  8502. Args:
  8503. {input}
  8504. {opt_dim_all_reduce}
  8505. {opt_keepdim}
  8506. Keyword args:
  8507. {dtype}
  8508. Example::
  8509. >>> a = torch.randn(4, 4)
  8510. >>> a
  8511. tensor([[ 0.0569, -0.2475, 0.0737, -0.3429],
  8512. [-0.2993, 0.9138, 0.9337, -1.6864],
  8513. [ 0.1132, 0.7892, -0.1003, 0.5688],
  8514. [ 0.3637, -0.9906, -0.4752, -1.5197]])
  8515. >>> torch.sum(a, 1)
  8516. tensor([-0.4598, -0.1381, 1.3708, -2.6217])
  8517. >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6)
  8518. >>> torch.sum(b, (2, 1))
  8519. tensor([ 435., 1335., 2235., 3135.])
  8520. """.format(**multi_dim_common),
  8521. )
  8522. add_docstr(
  8523. torch.nansum,
  8524. r"""
  8525. nansum(input, *, dtype=None) -> Tensor
  8526. Returns the sum of all elements, treating Not a Numbers (NaNs) as zero.
  8527. Args:
  8528. {input}
  8529. Keyword args:
  8530. {dtype}
  8531. Example::
  8532. >>> a = torch.tensor([1., 2., float('nan'), 4.])
  8533. >>> torch.nansum(a)
  8534. tensor(7.)
  8535. .. function:: nansum(input, dim, keepdim=False, *, dtype=None) -> Tensor
  8536. :noindex:
  8537. Returns the sum of each row of the :attr:`input` tensor in the given
  8538. dimension :attr:`dim`, treating Not a Numbers (NaNs) as zero.
  8539. If :attr:`dim` is a list of dimensions, reduce over all of them.
  8540. {keepdim_details}
  8541. Args:
  8542. {input}
  8543. {opt_dim_all_reduce}
  8544. {opt_keepdim}
  8545. Keyword args:
  8546. {dtype}
  8547. Example::
  8548. >>> torch.nansum(torch.tensor([1., float("nan")]))
  8549. tensor(1.)
  8550. >>> a = torch.tensor([[1, 2], [3., float("nan")]])
  8551. >>> torch.nansum(a)
  8552. tensor(6.)
  8553. >>> torch.nansum(a, dim=0)
  8554. tensor([4., 2.])
  8555. >>> torch.nansum(a, dim=1)
  8556. tensor([3., 3.])
  8557. """.format(**multi_dim_common),
  8558. )
  8559. add_docstr(
  8560. torch.svd,
  8561. r"""
  8562. svd(input, some=True, compute_uv=True, *, out=None) -> (Tensor, Tensor, Tensor)
  8563. Computes the singular value decomposition of either a matrix or batch of
  8564. matrices :attr:`input`. The singular value decomposition is represented as a
  8565. namedtuple `(U, S, V)`, such that :attr:`input` :math:`= U \text{diag}(S) V^{\text{H}}`.
  8566. where :math:`V^{\text{H}}` is the transpose of `V` for real inputs,
  8567. and the conjugate transpose of `V` for complex inputs.
  8568. If :attr:`input` is a batch of matrices, then `U`, `S`, and `V` are also
  8569. batched with the same batch dimensions as :attr:`input`.
  8570. If :attr:`some` is `True` (default), the method returns the reduced singular
  8571. value decomposition. In this case, if the last two dimensions of :attr:`input` are
  8572. `m` and `n`, then the returned `U` and `V` matrices will contain only
  8573. `min(n, m)` orthonormal columns.
  8574. If :attr:`compute_uv` is `False`, the returned `U` and `V` will be
  8575. zero-filled matrices of shape `(m, m)` and `(n, n)`
  8576. respectively, and the same device as :attr:`input`. The argument :attr:`some`
  8577. has no effect when :attr:`compute_uv` is `False`.
  8578. Supports :attr:`input` of float, double, cfloat and cdouble data types.
  8579. The dtypes of `U` and `V` are the same as :attr:`input`'s. `S` will
  8580. always be real-valued, even if :attr:`input` is complex.
  8581. .. warning::
  8582. :func:`torch.svd` is deprecated in favor of :func:`torch.linalg.svd`
  8583. and will be removed in a future PyTorch release.
  8584. ``U, S, V = torch.svd(A, some=some, compute_uv=True)`` (default) should be replaced with
  8585. .. code:: python
  8586. U, S, Vh = torch.linalg.svd(A, full_matrices=not some)
  8587. V = Vh.mH
  8588. ``_, S, _ = torch.svd(A, some=some, compute_uv=False)`` should be replaced with
  8589. .. code:: python
  8590. S = torch.linalg.svdvals(A)
  8591. .. note:: Differences with :func:`torch.linalg.svd`:
  8592. * :attr:`some` is the opposite of
  8593. :func:`torch.linalg.svd`'s :attr:`full_matrices`. Note that
  8594. default value for both is `True`, so the default behavior is
  8595. effectively the opposite.
  8596. * :func:`torch.svd` returns `V`, whereas :func:`torch.linalg.svd` returns
  8597. `Vh`, that is, :math:`V^{\text{H}}`.
  8598. * If :attr:`compute_uv` is `False`, :func:`torch.svd` returns zero-filled
  8599. tensors for `U` and `Vh`, whereas :func:`torch.linalg.svd` returns
  8600. empty tensors.
  8601. .. note:: The singular values are returned in descending order. If :attr:`input` is a batch of matrices,
  8602. then the singular values of each matrix in the batch are returned in descending order.
  8603. .. note:: The `S` tensor can only be used to compute gradients if :attr:`compute_uv` is `True`.
  8604. .. note:: When :attr:`some` is `False`, the gradients on `U[..., :, min(m, n):]`
  8605. and `V[..., :, min(m, n):]` will be ignored in the backward pass, as those vectors
  8606. can be arbitrary bases of the corresponding subspaces.
  8607. .. note:: The implementation of :func:`torch.linalg.svd` on CPU uses LAPACK's routine `?gesdd`
  8608. (a divide-and-conquer algorithm) instead of `?gesvd` for speed. Analogously,
  8609. on GPU, it uses cuSOLVER's routines `gesvdj` and `gesvdjBatched` on CUDA 10.1.243
  8610. and later, and MAGMA's routine `gesdd` on earlier versions of CUDA.
  8611. .. note:: The returned `U` will not be contiguous. The matrix (or batch of matrices) will
  8612. be represented as a column-major matrix (i.e. Fortran-contiguous).
  8613. .. warning:: The gradients with respect to `U` and `V` will only be finite when the input does not
  8614. have zero nor repeated singular values.
  8615. .. warning:: If the distance between any two singular values is close to zero, the gradients with respect to
  8616. `U` and `V` will be numerically unstable, as they depends on
  8617. :math:`\frac{1}{\min_{i \neq j} \sigma_i^2 - \sigma_j^2}`. The same happens when the matrix
  8618. has small singular values, as these gradients also depend on `S^{-1}`.
  8619. .. warning:: For complex-valued :attr:`input` the singular value decomposition is not unique,
  8620. as `U` and `V` may be multiplied by an arbitrary phase factor :math:`e^{i \phi}` on every column.
  8621. The same happens when :attr:`input` has repeated singular values, where one may multiply
  8622. the columns of the spanning subspace in `U` and `V` by a rotation matrix
  8623. and `the resulting vectors will span the same subspace`_.
  8624. Different platforms, like NumPy, or inputs on different device types,
  8625. may produce different `U` and `V` tensors.
  8626. Args:
  8627. input (Tensor): the input tensor of size `(*, m, n)` where `*` is zero or more
  8628. batch dimensions consisting of `(m, n)` matrices.
  8629. some (bool, optional): controls whether to compute the reduced or full decomposition, and
  8630. consequently, the shape of returned `U` and `V`. Default: `True`.
  8631. compute_uv (bool, optional): controls whether to compute `U` and `V`. Default: `True`.
  8632. Keyword args:
  8633. out (tuple, optional): the output tuple of tensors
  8634. Example::
  8635. >>> a = torch.randn(5, 3)
  8636. >>> a
  8637. tensor([[ 0.2364, -0.7752, 0.6372],
  8638. [ 1.7201, 0.7394, -0.0504],
  8639. [-0.3371, -1.0584, 0.5296],
  8640. [ 0.3550, -0.4022, 1.5569],
  8641. [ 0.2445, -0.0158, 1.1414]])
  8642. >>> u, s, v = torch.svd(a)
  8643. >>> u
  8644. tensor([[ 0.4027, 0.0287, 0.5434],
  8645. [-0.1946, 0.8833, 0.3679],
  8646. [ 0.4296, -0.2890, 0.5261],
  8647. [ 0.6604, 0.2717, -0.2618],
  8648. [ 0.4234, 0.2481, -0.4733]])
  8649. >>> s
  8650. tensor([2.3289, 2.0315, 0.7806])
  8651. >>> v
  8652. tensor([[-0.0199, 0.8766, 0.4809],
  8653. [-0.5080, 0.4054, -0.7600],
  8654. [ 0.8611, 0.2594, -0.4373]])
  8655. >>> torch.dist(a, torch.mm(torch.mm(u, torch.diag(s)), v.t()))
  8656. tensor(8.6531e-07)
  8657. >>> a_big = torch.randn(7, 5, 3)
  8658. >>> u, s, v = torch.svd(a_big)
  8659. >>> torch.dist(a_big, torch.matmul(torch.matmul(u, torch.diag_embed(s)), v.mT))
  8660. tensor(2.6503e-06)
  8661. .. _the resulting vectors will span the same subspace:
  8662. (https://en.wikipedia.org/wiki/Singular_value_decomposition#Singular_values,_singular_vectors,_and_their_relation_to_the_SVD)
  8663. """,
  8664. )
  8665. add_docstr(
  8666. torch.t,
  8667. r"""
  8668. t(input) -> Tensor
  8669. Expects :attr:`input` to be <= 2-D tensor and transposes dimensions 0
  8670. and 1.
  8671. 0-D and 1-D tensors are returned as is. When input is a 2-D tensor this
  8672. is equivalent to ``transpose(input, 0, 1)``.
  8673. Args:
  8674. {input}
  8675. Example::
  8676. >>> x = torch.randn(())
  8677. >>> x
  8678. tensor(0.1995)
  8679. >>> torch.t(x)
  8680. tensor(0.1995)
  8681. >>> x = torch.randn(3)
  8682. >>> x
  8683. tensor([ 2.4320, -0.4608, 0.7702])
  8684. >>> torch.t(x)
  8685. tensor([ 2.4320, -0.4608, 0.7702])
  8686. >>> x = torch.randn(2, 3)
  8687. >>> x
  8688. tensor([[ 0.4875, 0.9158, -0.5872],
  8689. [ 0.3938, -0.6929, 0.6932]])
  8690. >>> torch.t(x)
  8691. tensor([[ 0.4875, 0.3938],
  8692. [ 0.9158, -0.6929],
  8693. [-0.5872, 0.6932]])
  8694. See also :func:`torch.transpose`.
  8695. """.format(**common_args),
  8696. )
  8697. add_docstr(
  8698. torch.flip,
  8699. r"""
  8700. flip(input, dims) -> Tensor
  8701. Reverse the order of an n-D tensor along given axis in dims.
  8702. .. note::
  8703. `torch.flip` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flip`,
  8704. which returns a view in constant time. Since copying a tensor's data is more work than viewing that data,
  8705. `torch.flip` is expected to be slower than `np.flip`.
  8706. Args:
  8707. {input}
  8708. dims (a list or tuple): axis to flip on
  8709. Example::
  8710. >>> x = torch.arange(8).view(2, 2, 2)
  8711. >>> x
  8712. tensor([[[ 0, 1],
  8713. [ 2, 3]],
  8714. [[ 4, 5],
  8715. [ 6, 7]]])
  8716. >>> torch.flip(x, [0, 1])
  8717. tensor([[[ 6, 7],
  8718. [ 4, 5]],
  8719. [[ 2, 3],
  8720. [ 0, 1]]])
  8721. """.format(**common_args),
  8722. )
  8723. add_docstr(
  8724. torch.fliplr,
  8725. r"""
  8726. fliplr(input) -> Tensor
  8727. Flip tensor in the left/right direction, returning a new tensor.
  8728. Flip the entries in each row in the left/right direction.
  8729. Columns are preserved, but appear in a different order than before.
  8730. Note:
  8731. Requires the tensor to be at least 2-D.
  8732. .. note::
  8733. `torch.fliplr` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.fliplr`,
  8734. which returns a view in constant time. Since copying a tensor's data is more work than viewing that data,
  8735. `torch.fliplr` is expected to be slower than `np.fliplr`.
  8736. Args:
  8737. input (Tensor): Must be at least 2-dimensional.
  8738. Example::
  8739. >>> x = torch.arange(4).view(2, 2)
  8740. >>> x
  8741. tensor([[0, 1],
  8742. [2, 3]])
  8743. >>> torch.fliplr(x)
  8744. tensor([[1, 0],
  8745. [3, 2]])
  8746. """.format(**common_args),
  8747. )
  8748. add_docstr(
  8749. torch.flipud,
  8750. r"""
  8751. flipud(input) -> Tensor
  8752. Flip tensor in the up/down direction, returning a new tensor.
  8753. Flip the entries in each column in the up/down direction.
  8754. Rows are preserved, but appear in a different order than before.
  8755. Note:
  8756. Requires the tensor to be at least 1-D.
  8757. .. note::
  8758. `torch.flipud` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flipud`,
  8759. which returns a view in constant time. Since copying a tensor's data is more work than viewing that data,
  8760. `torch.flipud` is expected to be slower than `np.flipud`.
  8761. Args:
  8762. input (Tensor): Must be at least 1-dimensional.
  8763. Example::
  8764. >>> x = torch.arange(4).view(2, 2)
  8765. >>> x
  8766. tensor([[0, 1],
  8767. [2, 3]])
  8768. >>> torch.flipud(x)
  8769. tensor([[2, 3],
  8770. [0, 1]])
  8771. """.format(**common_args),
  8772. )
  8773. add_docstr(
  8774. torch.roll,
  8775. r"""
  8776. roll(input, shifts, dims=None) -> Tensor
  8777. Roll the tensor :attr:`input` along the given dimension(s). Elements that are
  8778. shifted beyond the last position are re-introduced at the first position. If
  8779. :attr:`dims` is `None`, the tensor will be flattened before rolling and then
  8780. restored to the original shape.
  8781. Args:
  8782. {input}
  8783. shifts (int or tuple of ints): The number of places by which the elements
  8784. of the tensor are shifted. If shifts is a tuple, dims must be a tuple of
  8785. the same size, and each dimension will be rolled by the corresponding
  8786. value
  8787. dims (int or tuple of ints): Axis along which to roll
  8788. Example::
  8789. >>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2)
  8790. >>> x
  8791. tensor([[1, 2],
  8792. [3, 4],
  8793. [5, 6],
  8794. [7, 8]])
  8795. >>> torch.roll(x, 1)
  8796. tensor([[8, 1],
  8797. [2, 3],
  8798. [4, 5],
  8799. [6, 7]])
  8800. >>> torch.roll(x, 1, 0)
  8801. tensor([[7, 8],
  8802. [1, 2],
  8803. [3, 4],
  8804. [5, 6]])
  8805. >>> torch.roll(x, -1, 0)
  8806. tensor([[3, 4],
  8807. [5, 6],
  8808. [7, 8],
  8809. [1, 2]])
  8810. >>> torch.roll(x, shifts=(2, 1), dims=(0, 1))
  8811. tensor([[6, 5],
  8812. [8, 7],
  8813. [2, 1],
  8814. [4, 3]])
  8815. """.format(**common_args),
  8816. )
  8817. add_docstr(
  8818. torch.rot90,
  8819. r"""
  8820. rot90(input, k=1, dims=(0, 1)) -> Tensor
  8821. Rotate an n-D tensor by 90 degrees in the plane specified by dims axis.
  8822. Rotation direction is from the first towards the second axis if k > 0, and from the second towards the first for k < 0.
  8823. Args:
  8824. {input}
  8825. k (int): number of times to rotate. Default value is 1
  8826. dims (a list or tuple): axis to rotate. Default value is [0, 1]
  8827. Example::
  8828. >>> x = torch.arange(4).view(2, 2)
  8829. >>> x
  8830. tensor([[0, 1],
  8831. [2, 3]])
  8832. >>> torch.rot90(x, 1, [0, 1])
  8833. tensor([[1, 3],
  8834. [0, 2]])
  8835. >>> x = torch.arange(8).view(2, 2, 2)
  8836. >>> x
  8837. tensor([[[0, 1],
  8838. [2, 3]],
  8839. [[4, 5],
  8840. [6, 7]]])
  8841. >>> torch.rot90(x, 1, [1, 2])
  8842. tensor([[[1, 3],
  8843. [0, 2]],
  8844. [[5, 7],
  8845. [4, 6]]])
  8846. """.format(**common_args),
  8847. )
  8848. add_docstr(
  8849. torch.take,
  8850. r"""
  8851. take(input, index) -> Tensor
  8852. Returns a new tensor with the elements of :attr:`input` at the given indices.
  8853. The input tensor is treated as if it were viewed as a 1-D tensor. The result
  8854. takes the same shape as the indices.
  8855. Args:
  8856. {input}
  8857. index (LongTensor): the indices into tensor
  8858. Example::
  8859. >>> src = torch.tensor([[4, 3, 5],
  8860. ... [6, 7, 8]])
  8861. >>> torch.take(src, torch.tensor([0, 2, 5]))
  8862. tensor([ 4, 5, 8])
  8863. """.format(**common_args),
  8864. )
  8865. add_docstr(
  8866. torch.take_along_dim,
  8867. r"""
  8868. take_along_dim(input, indices, dim=None, *, out=None) -> Tensor
  8869. Selects values from :attr:`input` at the 1-dimensional indices from :attr:`indices` along the given :attr:`dim`.
  8870. If :attr:`dim` is None, the input array is treated as if it has been flattened to 1d.
  8871. Functions that return indices along a dimension, like :func:`torch.argmax` and :func:`torch.argsort`,
  8872. are designed to work with this function. See the examples below.
  8873. .. note::
  8874. This function is similar to NumPy's `take_along_axis`.
  8875. See also :func:`torch.gather`.
  8876. Args:
  8877. {input}
  8878. indices (LongTensor): the indices into :attr:`input`. Must have long dtype.
  8879. dim (int, optional): dimension to select along. Default: 0
  8880. Keyword args:
  8881. {out}
  8882. Example::
  8883. >>> t = torch.tensor([[10, 30, 20], [60, 40, 50]])
  8884. >>> max_idx = torch.argmax(t)
  8885. >>> torch.take_along_dim(t, max_idx)
  8886. tensor([60])
  8887. >>> sorted_idx = torch.argsort(t, dim=1)
  8888. >>> torch.take_along_dim(t, sorted_idx, dim=1)
  8889. tensor([[10, 20, 30],
  8890. [40, 50, 60]])
  8891. """.format(**common_args),
  8892. )
  8893. add_docstr(
  8894. torch.tan,
  8895. r"""
  8896. tan(input, *, out=None) -> Tensor
  8897. Returns a new tensor with the tangent of the elements in the :attr:`input` tensor,
  8898. where each value in this input tensor is in radians.
  8899. .. math::
  8900. \text{out}_{i} = \tan(\text{input}_{i})
  8901. """
  8902. + r"""
  8903. Args:
  8904. {input}
  8905. Keyword args:
  8906. {out}
  8907. Example::
  8908. >>> a = torch.randn(4)
  8909. >>> a
  8910. tensor([-1.2027, -1.7687, 0.4412, -1.3856])
  8911. >>> torch.tan(a)
  8912. tensor([-2.5930, 4.9859, 0.4722, -5.3366])
  8913. """.format(**common_args),
  8914. )
  8915. add_docstr(
  8916. torch.tanh,
  8917. r"""
  8918. tanh(input, *, out=None) -> Tensor
  8919. Returns a new tensor with the hyperbolic tangent of the elements
  8920. of :attr:`input`.
  8921. .. math::
  8922. \text{out}_{i} = \tanh(\text{input}_{i})
  8923. """
  8924. + r"""
  8925. Args:
  8926. {input}
  8927. Keyword args:
  8928. {out}
  8929. Example::
  8930. >>> a = torch.randn(4)
  8931. >>> a
  8932. tensor([ 0.8986, -0.7279, 1.1745, 0.2611])
  8933. >>> torch.tanh(a)
  8934. tensor([ 0.7156, -0.6218, 0.8257, 0.2553])
  8935. """.format(**common_args),
  8936. )
  8937. add_docstr(
  8938. # torch.softmax doc str. Point this to torch.nn.functional.softmax
  8939. torch.softmax,
  8940. r"""
  8941. softmax(input, dim, *, dtype=None) -> Tensor
  8942. Alias for :func:`torch.nn.functional.softmax`.
  8943. """,
  8944. )
  8945. add_docstr(
  8946. torch.topk,
  8947. r"""
  8948. topk(input, k, dim=None, largest=True, sorted=True, *, out=None) -> (Tensor, LongTensor)
  8949. Returns the :attr:`k` largest elements of the given :attr:`input` tensor along
  8950. a given dimension.
  8951. If :attr:`dim` is not given, the last dimension of the `input` is chosen.
  8952. If :attr:`largest` is ``False`` then the `k` smallest elements are returned.
  8953. A namedtuple of `(values, indices)` is returned with the `values` and
  8954. `indices` of the largest `k` elements of each row of the `input` tensor in the
  8955. given dimension `dim`.
  8956. The boolean option :attr:`sorted` if ``True``, will make sure that the returned
  8957. `k` elements are themselves sorted
  8958. .. note::
  8959. When using `torch.topk`, the indices of tied elements are not guaranteed to be stable
  8960. and may vary across different invocations.
  8961. Args:
  8962. {input}
  8963. k (int): the k in "top-k"
  8964. dim (int, optional): the dimension to sort along
  8965. largest (bool, optional): controls whether to return largest or
  8966. smallest elements
  8967. sorted (bool, optional): controls whether to return the elements
  8968. in sorted order
  8969. Keyword args:
  8970. out (tuple, optional): the output tuple of (Tensor, LongTensor) that can be
  8971. optionally given to be used as output buffers
  8972. Example::
  8973. >>> x = torch.arange(1., 6.)
  8974. >>> x
  8975. tensor([ 1., 2., 3., 4., 5.])
  8976. >>> torch.topk(x, 3)
  8977. torch.return_types.topk(values=tensor([5., 4., 3.]), indices=tensor([4, 3, 2]))
  8978. """.format(**common_args),
  8979. )
  8980. add_docstr(
  8981. torch.trace,
  8982. r"""
  8983. trace(input) -> Tensor
  8984. Returns the sum of the elements of the diagonal of the input 2-D matrix.
  8985. Example::
  8986. >>> x = torch.arange(1., 10.).view(3, 3)
  8987. >>> x
  8988. tensor([[ 1., 2., 3.],
  8989. [ 4., 5., 6.],
  8990. [ 7., 8., 9.]])
  8991. >>> torch.trace(x)
  8992. tensor(15.)
  8993. """,
  8994. )
  8995. add_docstr(
  8996. torch.transpose,
  8997. r"""
  8998. transpose(input, dim0, dim1) -> Tensor
  8999. Returns a tensor that is a transposed version of :attr:`input`.
  9000. The given dimensions :attr:`dim0` and :attr:`dim1` are swapped.
  9001. If :attr:`input` is a strided tensor then the resulting :attr:`out`
  9002. tensor shares its underlying storage with the :attr:`input` tensor, so
  9003. changing the content of one would change the content of the other.
  9004. If :attr:`input` is a :ref:`sparse tensor <sparse-docs>` then the
  9005. resulting :attr:`out` tensor *does not* share the underlying storage
  9006. with the :attr:`input` tensor.
  9007. If :attr:`input` is a :ref:`sparse tensor <sparse-docs>` with compressed
  9008. layout (SparseCSR, SparseBSR, SparseCSC or SparseBSC) the arguments
  9009. :attr:`dim0` and :attr:`dim1` must be both batch dimensions, or must
  9010. both be sparse dimensions. The batch dimensions of a sparse tensor are the
  9011. dimensions preceding the sparse dimensions.
  9012. .. note::
  9013. Transpositions which interchange the sparse dimensions of a `SparseCSR`
  9014. or `SparseCSC` layout tensor will result in the layout changing between
  9015. the two options. Transposition of the sparse dimensions of a ` SparseBSR`
  9016. or `SparseBSC` layout tensor will likewise generate a result with the
  9017. opposite layout.
  9018. Args:
  9019. {input}
  9020. dim0 (int): the first dimension to be transposed
  9021. dim1 (int): the second dimension to be transposed
  9022. Example::
  9023. >>> x = torch.randn(2, 3)
  9024. >>> x
  9025. tensor([[ 1.0028, -0.9893, 0.5809],
  9026. [-0.1669, 0.7299, 0.4942]])
  9027. >>> torch.transpose(x, 0, 1)
  9028. tensor([[ 1.0028, -0.1669],
  9029. [-0.9893, 0.7299],
  9030. [ 0.5809, 0.4942]])
  9031. See also :func:`torch.t`.
  9032. """.format(**common_args),
  9033. )
  9034. add_docstr(
  9035. torch.triangular_solve,
  9036. r"""
  9037. triangular_solve(b, A, upper=True, transpose=False, unitriangular=False, *, out=None) -> (Tensor, Tensor)
  9038. Solves a system of equations with a square upper or lower triangular invertible matrix :math:`A`
  9039. and multiple right-hand sides :math:`b`.
  9040. In symbols, it solves :math:`AX = b` and assumes :math:`A` is square upper-triangular
  9041. (or lower-triangular if :attr:`upper`\ `= False`) and does not have zeros on the diagonal.
  9042. `torch.triangular_solve(b, A)` can take in 2D inputs `b, A` or inputs that are
  9043. batches of 2D matrices. If the inputs are batches, then returns
  9044. batched outputs `X`
  9045. If the diagonal of :attr:`A` contains zeros or elements that are very close to zero and
  9046. :attr:`unitriangular`\ `= False` (default) or if the input matrix is badly conditioned,
  9047. the result may contain `NaN` s.
  9048. Supports input of float, double, cfloat and cdouble data types.
  9049. .. warning::
  9050. :func:`torch.triangular_solve` is deprecated in favor of :func:`torch.linalg.solve_triangular`
  9051. and will be removed in a future PyTorch release.
  9052. :func:`torch.linalg.solve_triangular` has its arguments reversed and does not return a
  9053. copy of one of the inputs.
  9054. ``X = torch.triangular_solve(B, A).solution`` should be replaced with
  9055. .. code:: python
  9056. X = torch.linalg.solve_triangular(A, B)
  9057. Args:
  9058. b (Tensor): multiple right-hand sides of size :math:`(*, m, k)` where
  9059. :math:`*` is zero of more batch dimensions
  9060. A (Tensor): the input triangular coefficient matrix of size :math:`(*, m, m)`
  9061. where :math:`*` is zero or more batch dimensions
  9062. upper (bool, optional): whether :math:`A` is upper or lower triangular. Default: ``True``.
  9063. transpose (bool, optional): solves `op(A)X = b` where `op(A) = A^T` if this flag is ``True``,
  9064. and `op(A) = A` if it is ``False``. Default: ``False``.
  9065. unitriangular (bool, optional): whether :math:`A` is unit triangular.
  9066. If True, the diagonal elements of :math:`A` are assumed to be
  9067. 1 and not referenced from :math:`A`. Default: ``False``.
  9068. Keyword args:
  9069. out ((Tensor, Tensor), optional): tuple of two tensors to write
  9070. the output to. Ignored if `None`. Default: `None`.
  9071. Returns:
  9072. A namedtuple `(solution, cloned_coefficient)` where `cloned_coefficient`
  9073. is a clone of :math:`A` and `solution` is the solution :math:`X` to :math:`AX = b`
  9074. (or whatever variant of the system of equations, depending on the keyword arguments.)
  9075. Examples::
  9076. >>> A = torch.randn(2, 2).triu()
  9077. >>> A
  9078. tensor([[ 1.1527, -1.0753],
  9079. [ 0.0000, 0.7986]])
  9080. >>> b = torch.randn(2, 3)
  9081. >>> b
  9082. tensor([[-0.0210, 2.3513, -1.5492],
  9083. [ 1.5429, 0.7403, -1.0243]])
  9084. >>> torch.triangular_solve(b, A)
  9085. torch.return_types.triangular_solve(
  9086. solution=tensor([[ 1.7841, 2.9046, -2.5405],
  9087. [ 1.9320, 0.9270, -1.2826]]),
  9088. cloned_coefficient=tensor([[ 1.1527, -1.0753],
  9089. [ 0.0000, 0.7986]]))
  9090. """,
  9091. )
  9092. add_docstr(
  9093. torch.tril,
  9094. r"""
  9095. tril(input, diagonal=0, *, out=None) -> Tensor
  9096. Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices
  9097. :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0.
  9098. The lower triangular part of the matrix is defined as the elements on and
  9099. below the diagonal.
  9100. The argument :attr:`diagonal` controls which diagonal to consider. If
  9101. :attr:`diagonal` = 0, all elements on and below the main diagonal are
  9102. retained. A positive value includes just as many diagonals above the main
  9103. diagonal, and similarly a negative value excludes just as many diagonals below
  9104. the main diagonal. The main diagonal are the set of indices
  9105. :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where
  9106. :math:`d_{1}, d_{2}` are the dimensions of the matrix.
  9107. """
  9108. + r"""
  9109. Args:
  9110. {input}
  9111. diagonal (int, optional): the diagonal to consider
  9112. Keyword args:
  9113. {out}
  9114. Example::
  9115. >>> a = torch.randn(3, 3)
  9116. >>> a
  9117. tensor([[-1.0813, -0.8619, 0.7105],
  9118. [ 0.0935, 0.1380, 2.2112],
  9119. [-0.3409, -0.9828, 0.0289]])
  9120. >>> torch.tril(a)
  9121. tensor([[-1.0813, 0.0000, 0.0000],
  9122. [ 0.0935, 0.1380, 0.0000],
  9123. [-0.3409, -0.9828, 0.0289]])
  9124. >>> b = torch.randn(4, 6)
  9125. >>> b
  9126. tensor([[ 1.2219, 0.5653, -0.2521, -0.2345, 1.2544, 0.3461],
  9127. [ 0.4785, -0.4477, 0.6049, 0.6368, 0.8775, 0.7145],
  9128. [ 1.1502, 3.2716, -1.1243, -0.5413, 0.3615, 0.6864],
  9129. [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0978]])
  9130. >>> torch.tril(b, diagonal=1)
  9131. tensor([[ 1.2219, 0.5653, 0.0000, 0.0000, 0.0000, 0.0000],
  9132. [ 0.4785, -0.4477, 0.6049, 0.0000, 0.0000, 0.0000],
  9133. [ 1.1502, 3.2716, -1.1243, -0.5413, 0.0000, 0.0000],
  9134. [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0000]])
  9135. >>> torch.tril(b, diagonal=-1)
  9136. tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
  9137. [ 0.4785, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
  9138. [ 1.1502, 3.2716, 0.0000, 0.0000, 0.0000, 0.0000],
  9139. [-0.0614, -0.7344, -1.3164, 0.0000, 0.0000, 0.0000]])
  9140. """.format(**common_args),
  9141. )
  9142. # docstr is split in two parts to avoid format mis-captureing :math: braces '{}'
  9143. # as common args.
  9144. add_docstr(
  9145. torch.tril_indices,
  9146. r"""
  9147. tril_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor
  9148. Returns the indices of the lower triangular part of a :attr:`row`-by-
  9149. :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row
  9150. coordinates of all indices and the second row contains column coordinates.
  9151. Indices are ordered based on rows and then columns.
  9152. The lower triangular part of the matrix is defined as the elements on and
  9153. below the diagonal.
  9154. The argument :attr:`offset` controls which diagonal to consider. If
  9155. :attr:`offset` = 0, all elements on and below the main diagonal are
  9156. retained. A positive value includes just as many diagonals above the main
  9157. diagonal, and similarly a negative value excludes just as many diagonals below
  9158. the main diagonal. The main diagonal are the set of indices
  9159. :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]`
  9160. where :math:`d_{1}, d_{2}` are the dimensions of the matrix.
  9161. .. note::
  9162. When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to
  9163. prevent overflow during calculation.
  9164. """
  9165. + r"""
  9166. Args:
  9167. row (``int``): number of rows in the 2-D matrix.
  9168. col (``int``): number of columns in the 2-D matrix.
  9169. offset (``int``): diagonal offset from the main diagonal.
  9170. Default: if not provided, 0.
  9171. Keyword args:
  9172. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor,
  9173. only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``.
  9174. {device}
  9175. layout (:class:`torch.layout`, optional): currently only support ``torch.strided``.
  9176. Example::
  9177. >>> a = torch.tril_indices(3, 3)
  9178. >>> a
  9179. tensor([[0, 1, 1, 2, 2, 2],
  9180. [0, 0, 1, 0, 1, 2]])
  9181. >>> a = torch.tril_indices(4, 3, -1)
  9182. >>> a
  9183. tensor([[1, 2, 2, 3, 3, 3],
  9184. [0, 0, 1, 0, 1, 2]])
  9185. >>> a = torch.tril_indices(4, 3, 1)
  9186. >>> a
  9187. tensor([[0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3],
  9188. [0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2]])
  9189. """.format(**factory_common_args),
  9190. )
  9191. add_docstr(
  9192. torch.triu,
  9193. r"""
  9194. triu(input, diagonal=0, *, out=None) -> Tensor
  9195. Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices
  9196. :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0.
  9197. The upper triangular part of the matrix is defined as the elements on and
  9198. above the diagonal.
  9199. The argument :attr:`diagonal` controls which diagonal to consider. If
  9200. :attr:`diagonal` = 0, all elements on and above the main diagonal are
  9201. retained. A positive value excludes just as many diagonals above the main
  9202. diagonal, and similarly a negative value includes just as many diagonals below
  9203. the main diagonal. The main diagonal are the set of indices
  9204. :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where
  9205. :math:`d_{1}, d_{2}` are the dimensions of the matrix.
  9206. """
  9207. + r"""
  9208. Args:
  9209. {input}
  9210. diagonal (int, optional): the diagonal to consider
  9211. Keyword args:
  9212. {out}
  9213. Example::
  9214. >>> a = torch.randn(3, 3)
  9215. >>> a
  9216. tensor([[ 0.2309, 0.5207, 2.0049],
  9217. [ 0.2072, -1.0680, 0.6602],
  9218. [ 0.3480, -0.5211, -0.4573]])
  9219. >>> torch.triu(a)
  9220. tensor([[ 0.2309, 0.5207, 2.0049],
  9221. [ 0.0000, -1.0680, 0.6602],
  9222. [ 0.0000, 0.0000, -0.4573]])
  9223. >>> torch.triu(a, diagonal=1)
  9224. tensor([[ 0.0000, 0.5207, 2.0049],
  9225. [ 0.0000, 0.0000, 0.6602],
  9226. [ 0.0000, 0.0000, 0.0000]])
  9227. >>> torch.triu(a, diagonal=-1)
  9228. tensor([[ 0.2309, 0.5207, 2.0049],
  9229. [ 0.2072, -1.0680, 0.6602],
  9230. [ 0.0000, -0.5211, -0.4573]])
  9231. >>> b = torch.randn(4, 6)
  9232. >>> b
  9233. tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235],
  9234. [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857],
  9235. [ 0.4333, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410],
  9236. [-0.9888, 1.0679, -1.3337, -1.6556, 0.4798, 0.2830]])
  9237. >>> torch.triu(b, diagonal=1)
  9238. tensor([[ 0.0000, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235],
  9239. [ 0.0000, 0.0000, -1.2919, 1.3378, -0.1768, -1.0857],
  9240. [ 0.0000, 0.0000, 0.0000, -1.0432, 0.9348, -0.4410],
  9241. [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4798, 0.2830]])
  9242. >>> torch.triu(b, diagonal=-1)
  9243. tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235],
  9244. [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857],
  9245. [ 0.0000, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410],
  9246. [ 0.0000, 0.0000, -1.3337, -1.6556, 0.4798, 0.2830]])
  9247. """.format(**common_args),
  9248. )
  9249. # docstr is split in two parts to avoid format mis-capturing :math: braces '{}'
  9250. # as common args.
  9251. add_docstr(
  9252. torch.triu_indices,
  9253. r"""
  9254. triu_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor
  9255. Returns the indices of the upper triangular part of a :attr:`row` by
  9256. :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row
  9257. coordinates of all indices and the second row contains column coordinates.
  9258. Indices are ordered based on rows and then columns.
  9259. The upper triangular part of the matrix is defined as the elements on and
  9260. above the diagonal.
  9261. The argument :attr:`offset` controls which diagonal to consider. If
  9262. :attr:`offset` = 0, all elements on and above the main diagonal are
  9263. retained. A positive value excludes just as many diagonals above the main
  9264. diagonal, and similarly a negative value includes just as many diagonals below
  9265. the main diagonal. The main diagonal are the set of indices
  9266. :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]`
  9267. where :math:`d_{1}, d_{2}` are the dimensions of the matrix.
  9268. .. note::
  9269. When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to
  9270. prevent overflow during calculation.
  9271. """
  9272. + r"""
  9273. Args:
  9274. row (``int``): number of rows in the 2-D matrix.
  9275. col (``int``): number of columns in the 2-D matrix.
  9276. offset (``int``): diagonal offset from the main diagonal.
  9277. Default: if not provided, 0.
  9278. Keyword args:
  9279. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor,
  9280. only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``.
  9281. {device}
  9282. layout (:class:`torch.layout`, optional): currently only support ``torch.strided``.
  9283. Example::
  9284. >>> a = torch.triu_indices(3, 3)
  9285. >>> a
  9286. tensor([[0, 0, 0, 1, 1, 2],
  9287. [0, 1, 2, 1, 2, 2]])
  9288. >>> a = torch.triu_indices(4, 3, -1)
  9289. >>> a
  9290. tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3],
  9291. [0, 1, 2, 0, 1, 2, 1, 2, 2]])
  9292. >>> a = torch.triu_indices(4, 3, 1)
  9293. >>> a
  9294. tensor([[0, 0, 1],
  9295. [1, 2, 2]])
  9296. """.format(**factory_common_args),
  9297. )
  9298. add_docstr(
  9299. torch.true_divide,
  9300. r"""
  9301. true_divide(dividend, divisor, *, out) -> Tensor
  9302. Alias for :func:`torch.div` with ``rounding_mode=None``.
  9303. """,
  9304. )
  9305. add_docstr(
  9306. torch.trunc,
  9307. r"""
  9308. trunc(input, *, out=None) -> Tensor
  9309. Returns a new tensor with the truncated integer values of
  9310. the elements of :attr:`input`.
  9311. For integer inputs, follows the array-api convention of returning a
  9312. copy of the input tensor.
  9313. Args:
  9314. {input}
  9315. Keyword args:
  9316. {out}
  9317. Example::
  9318. >>> a = torch.randn(4)
  9319. >>> a
  9320. tensor([ 3.4742, 0.5466, -0.8008, -0.9079])
  9321. >>> torch.trunc(a)
  9322. tensor([ 3., 0., -0., -0.])
  9323. """.format(**common_args),
  9324. )
  9325. add_docstr(
  9326. torch.fake_quantize_per_tensor_affine,
  9327. r"""
  9328. fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor
  9329. Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`,
  9330. :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`.
  9331. .. math::
  9332. \text{output} = (
  9333. min(
  9334. \text{quant\_max},
  9335. max(
  9336. \text{quant\_min},
  9337. \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point}
  9338. )
  9339. ) - \text{zero\_point}
  9340. ) \times \text{scale}
  9341. Args:
  9342. input (Tensor): the input value(s), ``torch.float32`` tensor
  9343. scale (double scalar or ``float32`` Tensor): quantization scale
  9344. zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point
  9345. quant_min (int64): lower bound of the quantized domain
  9346. quant_max (int64): upper bound of the quantized domain
  9347. Returns:
  9348. Tensor: A newly fake_quantized ``torch.float32`` tensor
  9349. Example::
  9350. >>> x = torch.randn(4)
  9351. >>> x
  9352. tensor([ 0.0552, 0.9730, 0.3973, -1.0780])
  9353. >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255)
  9354. tensor([0.1000, 1.0000, 0.4000, 0.0000])
  9355. >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255)
  9356. tensor([0.1000, 1.0000, 0.4000, 0.0000])
  9357. """,
  9358. )
  9359. add_docstr(
  9360. torch.fake_quantize_per_channel_affine,
  9361. r"""
  9362. fake_quantize_per_channel_affine(input, scale, zero_point, axis, quant_min, quant_max) -> Tensor
  9363. Returns a new tensor with the data in :attr:`input` fake quantized per channel using :attr:`scale`,
  9364. :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`, across the channel specified by :attr:`axis`.
  9365. .. math::
  9366. \text{output} = (
  9367. min(
  9368. \text{quant\_max},
  9369. max(
  9370. \text{quant\_min},
  9371. \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point}
  9372. )
  9373. ) - \text{zero\_point}
  9374. ) \times \text{scale}
  9375. Args:
  9376. input (Tensor): the input value(s), in ``torch.float32``
  9377. scale (Tensor): quantization scale, per channel in ``torch.float32``
  9378. zero_point (Tensor): quantization zero_point, per channel in ``torch.int32`` or ``torch.half`` or ``torch.float32``
  9379. axis (int32): channel axis
  9380. quant_min (int64): lower bound of the quantized domain
  9381. quant_max (int64): upper bound of the quantized domain
  9382. Returns:
  9383. Tensor: A newly fake_quantized per channel ``torch.float32`` tensor
  9384. Example::
  9385. >>> x = torch.randn(2, 2, 2)
  9386. >>> x
  9387. tensor([[[-0.2525, -0.0466],
  9388. [ 0.3491, -0.2168]],
  9389. [[-0.5906, 1.6258],
  9390. [ 0.6444, -0.0542]]])
  9391. >>> scales = (torch.randn(2) + 1) * 0.05
  9392. >>> scales
  9393. tensor([0.0475, 0.0486])
  9394. >>> zero_points = torch.zeros(2).to(torch.int32)
  9395. >>> zero_points
  9396. tensor([0, 0])
  9397. >>> torch.fake_quantize_per_channel_affine(x, scales, zero_points, 1, 0, 255)
  9398. tensor([[[0.0000, 0.0000],
  9399. [0.3405, 0.0000]],
  9400. [[0.0000, 1.6134],
  9401. [0.6323, 0.0000]]])
  9402. """,
  9403. )
  9404. add_docstr(
  9405. torch.fix,
  9406. r"""
  9407. fix(input, *, out=None) -> Tensor
  9408. Alias for :func:`torch.trunc`
  9409. """,
  9410. )
  9411. add_docstr(
  9412. torch.unsqueeze,
  9413. r"""
  9414. unsqueeze(input, dim) -> Tensor
  9415. Returns a new tensor with a dimension of size one inserted at the
  9416. specified position.
  9417. The returned tensor shares the same underlying data with this tensor.
  9418. A :attr:`dim` value within the range ``[-input.dim() - 1, input.dim() + 1)``
  9419. can be used. Negative :attr:`dim` will correspond to :meth:`unsqueeze`
  9420. applied at :attr:`dim` = ``dim + input.dim() + 1``.
  9421. Args:
  9422. {input}
  9423. dim (int): the index at which to insert the singleton dimension
  9424. Example::
  9425. >>> x = torch.tensor([1, 2, 3, 4])
  9426. >>> torch.unsqueeze(x, 0)
  9427. tensor([[ 1, 2, 3, 4]])
  9428. >>> torch.unsqueeze(x, 1)
  9429. tensor([[ 1],
  9430. [ 2],
  9431. [ 3],
  9432. [ 4]])
  9433. """.format(**common_args),
  9434. )
  9435. add_docstr(
  9436. torch.var,
  9437. r"""
  9438. var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor
  9439. Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim`
  9440. can be a single dimension, list of dimensions, or ``None`` to reduce over all
  9441. dimensions.
  9442. The variance (:math:`\sigma^2`) is calculated as
  9443. .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2
  9444. where :math:`x` is the sample set of elements, :math:`\bar{x}` is the
  9445. sample mean, :math:`N` is the number of samples and :math:`\delta N` is
  9446. the :attr:`correction`.
  9447. """
  9448. + r"""
  9449. {keepdim_details}
  9450. Args:
  9451. {input}
  9452. {opt_dim_all_reduce}
  9453. Keyword args:
  9454. correction (int): difference between the sample size and sample degrees of freedom.
  9455. Defaults to `Bessel's correction`_, ``correction=1``.
  9456. .. versionchanged:: 2.0
  9457. Previously this argument was called ``unbiased`` and was a boolean
  9458. with ``True`` corresponding to ``correction=1`` and ``False`` being
  9459. ``correction=0``.
  9460. {opt_keepdim}
  9461. {out}
  9462. Example:
  9463. >>> a = torch.tensor(
  9464. ... [[ 0.2035, 1.2959, 1.8101, -0.4644],
  9465. ... [ 1.5027, -0.3270, 0.5905, 0.6538],
  9466. ... [-1.5745, 1.3330, -0.5596, -0.6548],
  9467. ... [ 0.1264, -0.5080, 1.6420, 0.1992]]
  9468. ... ) # fmt: skip
  9469. >>> torch.var(a, dim=1, keepdim=True)
  9470. tensor([[1.0631],
  9471. [0.5590],
  9472. [1.4893],
  9473. [0.8258]])
  9474. .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction
  9475. """.format(**multi_dim_common),
  9476. )
  9477. add_docstr(
  9478. torch.var_mean,
  9479. r"""
  9480. var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor)
  9481. Calculates the variance and mean over the dimensions specified by :attr:`dim`.
  9482. :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to
  9483. reduce over all dimensions.
  9484. The variance (:math:`\sigma^2`) is calculated as
  9485. .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2
  9486. where :math:`x` is the sample set of elements, :math:`\bar{x}` is the
  9487. sample mean, :math:`N` is the number of samples and :math:`\delta N` is
  9488. the :attr:`correction`.
  9489. """
  9490. + r"""
  9491. {keepdim_details}
  9492. Args:
  9493. {input}
  9494. {opt_dim_all_reduce}
  9495. Keyword args:
  9496. correction (int): difference between the sample size and sample degrees of freedom.
  9497. Defaults to `Bessel's correction`_, ``correction=1``.
  9498. .. versionchanged:: 2.0
  9499. Previously this argument was called ``unbiased`` and was a boolean
  9500. with ``True`` corresponding to ``correction=1`` and ``False`` being
  9501. ``correction=0``.
  9502. {opt_keepdim}
  9503. {out}
  9504. Returns:
  9505. A tuple (var, mean) containing the variance and mean.
  9506. Example:
  9507. >>> a = torch.tensor(
  9508. ... [[ 0.2035, 1.2959, 1.8101, -0.4644],
  9509. ... [ 1.5027, -0.3270, 0.5905, 0.6538],
  9510. ... [-1.5745, 1.3330, -0.5596, -0.6548],
  9511. ... [ 0.1264, -0.5080, 1.6420, 0.1992]]
  9512. ... ) # fmt: skip
  9513. >>> torch.var_mean(a, dim=0, keepdim=True)
  9514. (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]),
  9515. tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]]))
  9516. .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction
  9517. """.format(**multi_dim_common),
  9518. )
  9519. add_docstr(
  9520. torch.zeros,
  9521. r"""
  9522. zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
  9523. Returns a tensor filled with the scalar value `0`, with the shape defined
  9524. by the variable argument :attr:`size`.
  9525. Args:
  9526. size (int...): a sequence of integers defining the shape of the output tensor.
  9527. Can be a variable number of arguments or a collection like a list or tuple.
  9528. Keyword args:
  9529. {out}
  9530. {dtype}
  9531. {layout}
  9532. {device}
  9533. {requires_grad}
  9534. Example::
  9535. >>> torch.zeros(2, 3)
  9536. tensor([[ 0., 0., 0.],
  9537. [ 0., 0., 0.]])
  9538. >>> torch.zeros(5)
  9539. tensor([ 0., 0., 0., 0., 0.])
  9540. """.format(**factory_common_args),
  9541. )
  9542. add_docstr(
  9543. torch.zeros_like,
  9544. r"""
  9545. zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor
  9546. Returns a tensor filled with the scalar value `0`, with the same size as
  9547. :attr:`input`. ``torch.zeros_like(input)`` is equivalent to
  9548. ``torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``.
  9549. .. warning::
  9550. As of 0.4, this function does not support an :attr:`out` keyword. As an alternative,
  9551. the old ``torch.zeros_like(input, out=output)`` is equivalent to
  9552. ``torch.zeros(input.size(), out=output)``.
  9553. Args:
  9554. {input}
  9555. Keyword args:
  9556. {dtype}
  9557. {layout}
  9558. {device}
  9559. {requires_grad}
  9560. {memory_format}
  9561. Example::
  9562. >>> input = torch.empty(2, 3)
  9563. >>> torch.zeros_like(input)
  9564. tensor([[ 0., 0., 0.],
  9565. [ 0., 0., 0.]])
  9566. """.format(**factory_like_common_args),
  9567. )
  9568. add_docstr(
  9569. torch.empty,
  9570. """
  9571. empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, \
  9572. memory_format=torch.contiguous_format) -> Tensor
  9573. Returns a tensor filled with uninitialized data. The shape of the tensor is
  9574. defined by the variable argument :attr:`size`.
  9575. .. note::
  9576. If :func:`torch.use_deterministic_algorithms()` and
  9577. :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to
  9578. ``True``, the output tensor is initialized to prevent any possible
  9579. nondeterministic behavior from using the data as an input to an operation.
  9580. Floating point and complex tensors are filled with NaN, and integer tensors
  9581. are filled with the maximum value.
  9582. Args:
  9583. size (int...): a sequence of integers defining the shape of the output tensor.
  9584. Can be a variable number of arguments or a collection like a list or tuple.
  9585. Keyword args:
  9586. {out}
  9587. {dtype}
  9588. {layout}
  9589. {device}
  9590. {requires_grad}
  9591. {pin_memory}
  9592. {memory_format}
  9593. Example::
  9594. >>> torch.empty((2,3), dtype=torch.int64)
  9595. tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13],
  9596. [ 7.5751e+18, 7.1428e+18, 7.5955e+18]])
  9597. """.format(**factory_common_args),
  9598. )
  9599. add_docstr(
  9600. torch.empty_like,
  9601. r"""
  9602. empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor
  9603. Returns an uninitialized tensor with the same size as :attr:`input`.
  9604. ``torch.empty_like(input)`` is equivalent to
  9605. ``torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``.
  9606. .. note::
  9607. If :func:`torch.use_deterministic_algorithms()` and
  9608. :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to
  9609. ``True``, the output tensor is initialized to prevent any possible
  9610. nondeterministic behavior from using the data as an input to an operation.
  9611. Floating point and complex tensors are filled with NaN, and integer tensors
  9612. are filled with the maximum value.
  9613. When ``torch.preserve_format`` is used:
  9614. If the input tensor is dense (i.e., non-overlapping strided),
  9615. its memory format (including strides) is retained.
  9616. Otherwise (e.g., a non-dense view like a stepped slice),
  9617. the output is converted to the dense format.
  9618. Args:
  9619. {input}
  9620. Keyword args:
  9621. {dtype}
  9622. {layout}
  9623. {device}
  9624. {requires_grad}
  9625. {memory_format}
  9626. Example::
  9627. >>> a=torch.empty((2,3), dtype=torch.int32, device = 'cuda')
  9628. >>> torch.empty_like(a)
  9629. tensor([[0, 0, 0],
  9630. [0, 0, 0]], device='cuda:0', dtype=torch.int32)
  9631. """.format(**factory_like_common_args),
  9632. )
  9633. add_docstr(
  9634. torch.empty_strided,
  9635. r"""
  9636. empty_strided(size, stride, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor
  9637. Creates a tensor with the specified :attr:`size` and :attr:`stride` and filled with undefined data.
  9638. .. warning::
  9639. If the constructed tensor is "overlapped" (with multiple indices referring to the same element
  9640. in memory) its behavior is undefined.
  9641. .. note::
  9642. If :func:`torch.use_deterministic_algorithms()` and
  9643. :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to
  9644. ``True``, the output tensor is initialized to prevent any possible
  9645. nondeterministic behavior from using the data as an input to an operation.
  9646. Floating point and complex tensors are filled with NaN, and integer tensors
  9647. are filled with the maximum value.
  9648. Args:
  9649. size (tuple of int): the shape of the output tensor
  9650. stride (tuple of int): the strides of the output tensor
  9651. Keyword args:
  9652. {dtype}
  9653. {layout}
  9654. {device}
  9655. {requires_grad}
  9656. {pin_memory}
  9657. Example::
  9658. >>> a = torch.empty_strided((2, 3), (1, 2))
  9659. >>> a
  9660. tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07],
  9661. [0.0000e+00, 0.0000e+00, 3.0705e-41]])
  9662. >>> a.stride()
  9663. (1, 2)
  9664. >>> a.size()
  9665. torch.Size([2, 3])
  9666. """.format(**factory_common_args),
  9667. )
  9668. add_docstr(
  9669. torch.empty_permuted,
  9670. r"""
  9671. empty_permuted(size, physical_layout, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor
  9672. Creates an uninitialized, non-overlapping and dense tensor with the
  9673. specified :attr:`size`, with :attr:`physical_layout` specifying how the
  9674. dimensions are physically laid out in memory (each logical dimension is listed
  9675. from outermost to innermost). :attr:`physical_layout` is a generalization
  9676. of NCHW/NHWC notation: if each dimension is assigned a number according to
  9677. what order they occur in size (N=0, C=1, H=2, W=3), then NCHW is ``(0, 1, 2, 3)``
  9678. while NHWC is ``(0, 2, 3, 1)``. Equivalently, the strides of the output
  9679. tensor ``t`` are such that ``t.stride(physical_layout[i]) == contiguous_strides[i]``
  9680. (notably, this function is *not* equivalent to ``torch.empty(size).permute(physical_layout)``).
  9681. Unlike :func:`torch.empty_strided`, this is guaranteed to produce a dense
  9682. tensor with no overlaps. If possible, prefer using this function over
  9683. :func:`torch.empty_strided` or manual use of :func:`torch.as_strided`.
  9684. .. note::
  9685. If :func:`torch.use_deterministic_algorithms()` and
  9686. :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to
  9687. ``True``, the output tensor is initialized to prevent any possible
  9688. nondeterministic behavior from using the data as an input to an operation.
  9689. Floating point and complex tensors are filled with NaN, and integer tensors
  9690. are filled with the maximum value.
  9691. Args:
  9692. size (tuple of int): the shape of the output tensor
  9693. physical_layout (tuple of int): the ordering of dimensions physically in memory
  9694. Keyword args:
  9695. {dtype}
  9696. {layout}
  9697. {device}
  9698. {requires_grad}
  9699. {pin_memory}
  9700. Examples:
  9701. >>> torch.empty((2, 3, 5, 7)).stride()
  9702. (105, 35, 7, 1)
  9703. >>> torch.empty_permuted((2, 3, 5, 7), (0, 1, 2, 3)).stride()
  9704. (105, 35, 7, 1)
  9705. >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).stride()
  9706. (105, 1, 21, 3)
  9707. >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).stride()
  9708. (105, 1, 21, 3)
  9709. >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).dim_order()
  9710. (0, 2, 3, 1)
  9711. """.format(**factory_common_args),
  9712. )
  9713. add_docstr(
  9714. torch.full,
  9715. r"""
  9716. full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
  9717. Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The
  9718. tensor's dtype is inferred from :attr:`fill_value`.
  9719. Args:
  9720. size (int...): a list, tuple, or :class:`torch.Size` of integers defining the
  9721. shape of the output tensor.
  9722. fill_value (Scalar): the value to fill the output tensor with.
  9723. Keyword args:
  9724. {out}
  9725. {dtype}
  9726. {layout}
  9727. {device}
  9728. {requires_grad}
  9729. Example::
  9730. >>> torch.full((2, 3), 3.141592)
  9731. tensor([[ 3.1416, 3.1416, 3.1416],
  9732. [ 3.1416, 3.1416, 3.1416]])
  9733. """.format(**factory_common_args),
  9734. )
  9735. add_docstr(
  9736. torch.full_like,
  9737. """
  9738. full_like(input, fill_value, \\*, dtype=None, layout=torch.strided, device=None, requires_grad=False, \
  9739. memory_format=torch.preserve_format) -> Tensor
  9740. Returns a tensor with the same size as :attr:`input` filled with :attr:`fill_value`.
  9741. ``torch.full_like(input, fill_value)`` is equivalent to
  9742. ``torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device)``.
  9743. Args:
  9744. {input}
  9745. fill_value: the number to fill the output tensor with.
  9746. Keyword args:
  9747. {dtype}
  9748. {layout}
  9749. {device}
  9750. {requires_grad}
  9751. {memory_format}
  9752. Example::
  9753. >>> x = torch.ones(2, 3)
  9754. >>> torch.full_like(x, 3.141592)
  9755. tensor([[ 3.1416, 3.1416, 3.1416],
  9756. [ 3.1416, 3.1416, 3.1416]])
  9757. >>> torch.full_like(x, 7)
  9758. tensor([[7., 7., 7.],
  9759. [7., 7., 7.]])
  9760. >>> torch.full_like(x, 0.5, dtype=torch.int32)
  9761. tensor([[0, 0, 0],
  9762. [0, 0, 0]], dtype=torch.int32)
  9763. >>> y = torch.randn(3, 4, dtype=torch.float64)
  9764. >>> torch.full_like(y, -1.0)
  9765. tensor([[-1., -1., -1., -1.],
  9766. [-1., -1., -1., -1.],
  9767. [-1., -1., -1., -1.]], dtype=torch.float64)
  9768. """.format(**factory_like_common_args),
  9769. )
  9770. add_docstr(
  9771. torch.det,
  9772. r"""
  9773. det(input) -> Tensor
  9774. Alias for :func:`torch.linalg.det`
  9775. """,
  9776. )
  9777. add_docstr(
  9778. torch.where,
  9779. r"""
  9780. where(condition, input, other, *, out=None) -> Tensor
  9781. Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`.
  9782. The operation is defined as:
  9783. .. math::
  9784. \text{out}_i = \begin{cases}
  9785. \text{input}_i & \text{if } \text{condition}_i \\
  9786. \text{other}_i & \text{otherwise} \\
  9787. \end{cases}
  9788. """
  9789. + r"""
  9790. .. note::
  9791. The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable <broadcasting-semantics>`.
  9792. Arguments:
  9793. condition (BoolTensor): When True (nonzero), yield input, otherwise yield other
  9794. input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices
  9795. where :attr:`condition` is ``True``
  9796. other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices
  9797. where :attr:`condition` is ``False``
  9798. Keyword args:
  9799. {out}
  9800. Returns:
  9801. Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other`
  9802. Example::
  9803. >>> x = torch.randn(3, 2)
  9804. >>> y = torch.ones(3, 2)
  9805. >>> x
  9806. tensor([[-0.4620, 0.3139],
  9807. [ 0.3898, -0.7197],
  9808. [ 0.0478, -0.1657]])
  9809. >>> torch.where(x > 0, 1.0, 0.0)
  9810. tensor([[0., 1.],
  9811. [1., 0.],
  9812. [1., 0.]])
  9813. >>> torch.where(x > 0, x, y)
  9814. tensor([[ 1.0000, 0.3139],
  9815. [ 0.3898, 1.0000],
  9816. [ 0.0478, 1.0000]])
  9817. >>> x = torch.randn(2, 2, dtype=torch.double)
  9818. >>> x
  9819. tensor([[ 1.0779, 0.0383],
  9820. [-0.8785, -1.1089]], dtype=torch.float64)
  9821. >>> torch.where(x > 0, x, 0.)
  9822. tensor([[1.0779, 0.0383],
  9823. [0.0000, 0.0000]], dtype=torch.float64)
  9824. .. function:: where(condition) -> tuple of LongTensor
  9825. :noindex:
  9826. ``torch.where(condition)`` is identical to
  9827. ``torch.nonzero(condition, as_tuple=True)``.
  9828. .. note::
  9829. See also :func:`torch.nonzero`.
  9830. """.format(**common_args),
  9831. )
  9832. add_docstr(
  9833. torch.logdet,
  9834. r"""
  9835. logdet(input) -> Tensor
  9836. Calculates log determinant of a square matrix or batches of square matrices.
  9837. It returns ``-inf`` if the input has a determinant of zero, and ``NaN`` if it has
  9838. a negative determinant.
  9839. .. note::
  9840. Backward through :meth:`logdet` internally uses SVD results when :attr:`input`
  9841. is not invertible. In this case, double backward through :meth:`logdet` will
  9842. be unstable in when :attr:`input` doesn't have distinct singular values. See
  9843. :func:`torch.linalg.svd` for details.
  9844. .. seealso::
  9845. :func:`torch.linalg.slogdet` computes the sign (resp. angle) and natural logarithm of the
  9846. absolute value of the determinant of real-valued (resp. complex) square matrices.
  9847. Arguments:
  9848. input (Tensor): the input tensor of size ``(*, n, n)`` where ``*`` is zero or more
  9849. batch dimensions.
  9850. Example::
  9851. >>> A = torch.randn(3, 3)
  9852. >>> torch.det(A)
  9853. tensor(0.2611)
  9854. >>> torch.logdet(A)
  9855. tensor(-1.3430)
  9856. >>> A
  9857. tensor([[[ 0.9254, -0.6213],
  9858. [-0.5787, 1.6843]],
  9859. [[ 0.3242, -0.9665],
  9860. [ 0.4539, -0.0887]],
  9861. [[ 1.1336, -0.4025],
  9862. [-0.7089, 0.9032]]])
  9863. >>> A.det()
  9864. tensor([1.1990, 0.4099, 0.7386])
  9865. >>> A.det().log()
  9866. tensor([ 0.1815, -0.8917, -0.3031])
  9867. """,
  9868. )
  9869. add_docstr(
  9870. torch.slogdet,
  9871. r"""
  9872. slogdet(input) -> (Tensor, Tensor)
  9873. Alias for :func:`torch.linalg.slogdet`
  9874. """,
  9875. )
  9876. add_docstr(
  9877. torch.pinverse,
  9878. r"""
  9879. pinverse(input, rcond=1e-15) -> Tensor
  9880. Alias for :func:`torch.linalg.pinv`
  9881. """,
  9882. )
  9883. add_docstr(
  9884. torch.hann_window,
  9885. """
  9886. hann_window(window_length, periodic=True, *, dtype=None, \
  9887. layout=torch.strided, device=None, requires_grad=False) -> Tensor
  9888. """
  9889. + r"""
  9890. Hann window function.
  9891. .. math::
  9892. w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] =
  9893. \sin^2 \left( \frac{\pi n}{N - 1} \right),
  9894. where :math:`N` is the full window size.
  9895. The input :attr:`window_length` is a positive integer controlling the
  9896. returned window size. :attr:`periodic` flag determines whether the returned
  9897. window trims off the last duplicate value from the symmetric window and is
  9898. ready to be used as a periodic window with functions like
  9899. :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in
  9900. above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have
  9901. ``torch.hann_window(L, periodic=True)`` equal to
  9902. ``torch.hann_window(L + 1, periodic=False)[:-1])``.
  9903. .. note::
  9904. If :attr:`window_length` :math:`=1`, the returned window contains a single value 1.
  9905. """
  9906. + r"""
  9907. Arguments:
  9908. window_length (int): the size of returned window
  9909. periodic (bool, optional): If True, returns a window to be used as periodic
  9910. function. If False, return a symmetric window.
  9911. Keyword args:
  9912. {dtype} Only floating point types are supported.
  9913. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only
  9914. ``torch.strided`` (dense layout) is supported.
  9915. {device}
  9916. {requires_grad}
  9917. Returns:
  9918. Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window
  9919. """.format(**factory_common_args),
  9920. )
  9921. add_docstr(
  9922. torch.hamming_window,
  9923. """
  9924. hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, \
  9925. requires_grad=False) -> Tensor
  9926. """
  9927. + r"""
  9928. Hamming window function.
  9929. .. math::
  9930. w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right),
  9931. where :math:`N` is the full window size.
  9932. The input :attr:`window_length` is a positive integer controlling the
  9933. returned window size. :attr:`periodic` flag determines whether the returned
  9934. window trims off the last duplicate value from the symmetric window and is
  9935. ready to be used as a periodic window with functions like
  9936. :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in
  9937. above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have
  9938. ``torch.hamming_window(L, periodic=True)`` equal to
  9939. ``torch.hamming_window(L + 1, periodic=False)[:-1])``.
  9940. .. note::
  9941. If :attr:`window_length` :math:`=1`, the returned window contains a single value 1.
  9942. .. note::
  9943. This is a generalized version of :meth:`torch.hann_window`.
  9944. """
  9945. + r"""
  9946. Arguments:
  9947. window_length (int): the size of returned window
  9948. Keyword args:
  9949. {dtype} Only floating point types are supported.
  9950. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only
  9951. ``torch.strided`` (dense layout) is supported.
  9952. {device}
  9953. {pin_memory}
  9954. {requires_grad}
  9955. Returns:
  9956. Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window.
  9957. .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \
  9958. pin_memory=False, requires_grad=False) -> Tensor
  9959. :noindex:
  9960. Hamming window function with periodic specified.
  9961. Arguments:
  9962. window_length (int): the size of returned window
  9963. periodic (bool): If True, returns a window to be used as periodic
  9964. function. If False, return a symmetric window.
  9965. Keyword args:
  9966. {dtype} Only floating point types are supported.
  9967. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only
  9968. ``torch.strided`` (dense layout) is supported.
  9969. {device}
  9970. {pin_memory}
  9971. {requires_grad}
  9972. Returns:
  9973. Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window.
  9974. .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \
  9975. pin_memory=False, requires_grad=False) -> Tensor
  9976. :noindex:
  9977. Hamming window function with periodic and alpha specified.
  9978. Arguments:
  9979. window_length (int): the size of returned window
  9980. periodic (bool): If True, returns a window to be used as periodic
  9981. function. If False, return a symmetric window.
  9982. alpha (float): The coefficient :math:`\alpha` in the equation above
  9983. Keyword args:
  9984. {dtype} Only floating point types are supported.
  9985. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only
  9986. ``torch.strided`` (dense layout) is supported.
  9987. {device}
  9988. {pin_memory}
  9989. {requires_grad}
  9990. Returns:
  9991. Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window.
  9992. .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \
  9993. device=None, pin_memory=False, requires_grad=False) -> Tensor
  9994. :noindex:
  9995. Hamming window function with periodic, alpha and beta specified.
  9996. Arguments:
  9997. window_length (int): the size of returned window
  9998. periodic (bool): If True, returns a window to be used as periodic
  9999. function. If False, return a symmetric window.
  10000. alpha (float): The coefficient :math:`\alpha` in the equation above
  10001. beta (float): The coefficient :math:`\beta` in the equation above
  10002. Keyword args:
  10003. {dtype} Only floating point types are supported.
  10004. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only
  10005. ``torch.strided`` (dense layout) is supported.
  10006. {device}
  10007. {pin_memory}
  10008. {requires_grad}
  10009. Returns:
  10010. Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window.
  10011. """.format(**factory_common_args),
  10012. )
  10013. add_docstr(
  10014. torch.bartlett_window,
  10015. """
  10016. bartlett_window(window_length, periodic=True, *, dtype=None, \
  10017. layout=torch.strided, device=None, requires_grad=False) -> Tensor
  10018. """
  10019. + r"""
  10020. Bartlett window function.
  10021. .. math::
  10022. w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases}
  10023. \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\
  10024. 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\
  10025. \end{cases},
  10026. where :math:`N` is the full window size.
  10027. The input :attr:`window_length` is a positive integer controlling the
  10028. returned window size. :attr:`periodic` flag determines whether the returned
  10029. window trims off the last duplicate value from the symmetric window and is
  10030. ready to be used as a periodic window with functions like
  10031. :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in
  10032. above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have
  10033. ``torch.bartlett_window(L, periodic=True)`` equal to
  10034. ``torch.bartlett_window(L + 1, periodic=False)[:-1])``.
  10035. .. note::
  10036. If :attr:`window_length` :math:`=1`, the returned window contains a single value 1.
  10037. """
  10038. + r"""
  10039. Arguments:
  10040. window_length (int): the size of returned window
  10041. periodic (bool, optional): If True, returns a window to be used as periodic
  10042. function. If False, return a symmetric window.
  10043. Keyword args:
  10044. {dtype} Only floating point types are supported.
  10045. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only
  10046. ``torch.strided`` (dense layout) is supported.
  10047. {device}
  10048. {requires_grad}
  10049. Returns:
  10050. Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window
  10051. """.format(**factory_common_args),
  10052. )
  10053. add_docstr(
  10054. torch.blackman_window,
  10055. """
  10056. blackman_window(window_length, periodic=True, *, dtype=None, \
  10057. layout=torch.strided, device=None, requires_grad=False) -> Tensor
  10058. """
  10059. + r"""
  10060. Blackman window function.
  10061. .. math::
  10062. w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right)
  10063. where :math:`N` is the full window size.
  10064. The input :attr:`window_length` is a positive integer controlling the
  10065. returned window size. :attr:`periodic` flag determines whether the returned
  10066. window trims off the last duplicate value from the symmetric window and is
  10067. ready to be used as a periodic window with functions like
  10068. :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in
  10069. above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have
  10070. ``torch.blackman_window(L, periodic=True)`` equal to
  10071. ``torch.blackman_window(L + 1, periodic=False)[:-1]``.
  10072. .. note::
  10073. If :attr:`window_length` :math:`=1`, the returned window contains a single value 1.
  10074. """
  10075. + r"""
  10076. Arguments:
  10077. window_length (int): the size of returned window
  10078. periodic (bool, optional): If True, returns a window to be used as periodic
  10079. function. If False, return a symmetric window.
  10080. Keyword args:
  10081. {dtype} Only floating point types are supported.
  10082. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only
  10083. ``torch.strided`` (dense layout) is supported.
  10084. {device}
  10085. {requires_grad}
  10086. Returns:
  10087. Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window
  10088. """.format(**factory_common_args),
  10089. )
  10090. add_docstr(
  10091. torch.kaiser_window,
  10092. """
  10093. kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, \
  10094. layout=torch.strided, device=None, requires_grad=False) -> Tensor
  10095. """
  10096. + r"""
  10097. Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`.
  10098. Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and
  10099. ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True,
  10100. where ``L`` is the :attr:`window_length`. This function computes:
  10101. .. math::
  10102. out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta )
  10103. Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling
  10104. ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``.
  10105. The :attr:`periodic` argument is intended as a helpful shorthand
  10106. to produce a periodic window as input to functions like :func:`torch.stft`.
  10107. .. note::
  10108. If :attr:`window_length` is one, then the returned window is a single element tensor containing a one.
  10109. """
  10110. + r"""
  10111. Args:
  10112. window_length (int): length of the window.
  10113. periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis.
  10114. If False, returns a symmetric window suitable for use in filter design.
  10115. beta (float, optional): shape parameter for the window.
  10116. Keyword args:
  10117. {dtype}
  10118. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only
  10119. ``torch.strided`` (dense layout) is supported.
  10120. {device}
  10121. {requires_grad}
  10122. """.format(**factory_common_args),
  10123. )
  10124. add_docstr(
  10125. torch.vander,
  10126. """
  10127. vander(x, N=None, increasing=False) -> Tensor
  10128. """
  10129. + r"""
  10130. Generates a Vandermonde matrix.
  10131. The columns of the output matrix are elementwise powers of the input vector :math:`x^{{(N-1)}}, x^{{(N-2)}}, ..., x^0`.
  10132. If increasing is True, the order of the columns is reversed :math:`x^0, x^1, ..., x^{{(N-1)}}`. Such a
  10133. matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde.
  10134. Arguments:
  10135. x (Tensor): 1-D input tensor.
  10136. N (int, optional): Number of columns in the output. If N is not specified,
  10137. a square array is returned :math:`(N = len(x))`.
  10138. increasing (bool, optional): Order of the powers of the columns. If True,
  10139. the powers increase from left to right, if False (the default) they are reversed.
  10140. Returns:
  10141. Tensor: Vandermonde matrix. If increasing is False, the first column is :math:`x^{{(N-1)}}`,
  10142. the second :math:`x^{{(N-2)}}` and so forth. If increasing is True, the columns
  10143. are :math:`x^0, x^1, ..., x^{{(N-1)}}`.
  10144. Example::
  10145. >>> x = torch.tensor([1, 2, 3, 5])
  10146. >>> torch.vander(x)
  10147. tensor([[ 1, 1, 1, 1],
  10148. [ 8, 4, 2, 1],
  10149. [ 27, 9, 3, 1],
  10150. [125, 25, 5, 1]])
  10151. >>> torch.vander(x, N=3)
  10152. tensor([[ 1, 1, 1],
  10153. [ 4, 2, 1],
  10154. [ 9, 3, 1],
  10155. [25, 5, 1]])
  10156. >>> torch.vander(x, N=3, increasing=True)
  10157. tensor([[ 1, 1, 1],
  10158. [ 1, 2, 4],
  10159. [ 1, 3, 9],
  10160. [ 1, 5, 25]])
  10161. """.format(**factory_common_args),
  10162. )
  10163. add_docstr(
  10164. torch.unbind,
  10165. r"""
  10166. unbind(input, dim=0) -> seq
  10167. Removes a tensor dimension.
  10168. Returns a tuple of all slices along a given dimension, already without it.
  10169. Arguments:
  10170. input (Tensor): the tensor to unbind
  10171. dim (int): dimension to remove
  10172. Example::
  10173. >>> torch.unbind(torch.tensor([[1, 2, 3],
  10174. >>> [4, 5, 6],
  10175. >>> [7, 8, 9]]))
  10176. (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7, 8, 9]))
  10177. """,
  10178. )
  10179. add_docstr(
  10180. torch.combinations,
  10181. r"""
  10182. combinations(input: Tensor, r: int = 2, with_replacement: bool = False) -> seq
  10183. Compute combinations of length :math:`r` of the given tensor. The behavior is similar to
  10184. python's `itertools.combinations` when `with_replacement` is set to `False`, and
  10185. `itertools.combinations_with_replacement` when `with_replacement` is set to `True`.
  10186. Arguments:
  10187. input (Tensor): 1D vector.
  10188. r (int, optional): number of elements to combine
  10189. with_replacement (bool, optional): whether to allow duplication in combination
  10190. Returns:
  10191. Tensor: A tensor equivalent to converting all the input tensors into lists, do
  10192. `itertools.combinations` or `itertools.combinations_with_replacement` on these
  10193. lists, and finally convert the resulting list into tensor.
  10194. Example::
  10195. >>> a = [1, 2, 3]
  10196. >>> list(itertools.combinations(a, r=2))
  10197. [(1, 2), (1, 3), (2, 3)]
  10198. >>> list(itertools.combinations(a, r=3))
  10199. [(1, 2, 3)]
  10200. >>> list(itertools.combinations_with_replacement(a, r=2))
  10201. [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
  10202. >>> tensor_a = torch.tensor(a)
  10203. >>> torch.combinations(tensor_a)
  10204. tensor([[1, 2],
  10205. [1, 3],
  10206. [2, 3]])
  10207. >>> torch.combinations(tensor_a, r=3)
  10208. tensor([[1, 2, 3]])
  10209. >>> torch.combinations(tensor_a, with_replacement=True)
  10210. tensor([[1, 1],
  10211. [1, 2],
  10212. [1, 3],
  10213. [2, 2],
  10214. [2, 3],
  10215. [3, 3]])
  10216. """,
  10217. )
  10218. add_docstr(
  10219. torch.trapezoid,
  10220. r"""
  10221. trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor
  10222. Computes the `trapezoidal rule <https://en.wikipedia.org/wiki/Trapezoidal_rule>`_ along
  10223. :attr:`dim`. By default the spacing between elements is assumed to be 1, but
  10224. :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be
  10225. used to specify arbitrary spacing along :attr:`dim`. Only one of :attr:`x` or :attr:`dx` should be specified.
  10226. Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`,
  10227. the default computation is
  10228. .. math::
  10229. \begin{aligned}
  10230. \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1})
  10231. \end{aligned}
  10232. When :attr:`dx` is specified the computation becomes
  10233. .. math::
  10234. \begin{aligned}
  10235. \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1})
  10236. \end{aligned}
  10237. effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified,
  10238. assuming :attr:`x` is also a one-dimensional tensor with
  10239. elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes
  10240. .. math::
  10241. \begin{aligned}
  10242. \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1})
  10243. \end{aligned}
  10244. When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed.
  10245. The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x`
  10246. and :attr:`y`, the function computes the difference between consecutive elements along
  10247. dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have
  10248. the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1.
  10249. After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule.
  10250. See the examples below for details.
  10251. .. note::
  10252. The trapezoidal rule is a technique for approximating the definite integral of a function
  10253. by averaging its left and right Riemann sums. The approximation becomes more accurate as
  10254. the resolution of the partition increases.
  10255. Arguments:
  10256. y (Tensor): Values to use when computing the trapezoidal rule.
  10257. x (Tensor): If specified, defines spacing between values as specified above.
  10258. Keyword arguments:
  10259. dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx`
  10260. are specified then this defaults to 1. Effectively multiplies the result by its value.
  10261. dim (int): The dimension along which to compute the trapezoidal rule.
  10262. The last (inner-most) dimension by default.
  10263. Examples::
  10264. >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1
  10265. >>> y = torch.tensor([1, 5, 10])
  10266. >>> torch.trapezoid(y)
  10267. tensor(10.5)
  10268. >>> # Computes the same trapezoidal rule directly to verify
  10269. >>> (1 + 10 + 10) / 2
  10270. 10.5
  10271. >>> # Computes the trapezoidal rule in 1D with constant spacing of 2
  10272. >>> # NOTE: the result is the same as before, but multiplied by 2
  10273. >>> torch.trapezoid(y, dx=2)
  10274. 21.0
  10275. >>> # Computes the trapezoidal rule in 1D with arbitrary spacing
  10276. >>> x = torch.tensor([1, 3, 6])
  10277. >>> torch.trapezoid(y, x)
  10278. 28.5
  10279. >>> # Computes the same trapezoidal rule directly to verify
  10280. >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2
  10281. 28.5
  10282. >>> # Computes the trapezoidal rule for each row of a 3x3 matrix
  10283. >>> y = torch.arange(9).reshape(3, 3)
  10284. tensor([[0, 1, 2],
  10285. [3, 4, 5],
  10286. [6, 7, 8]])
  10287. >>> torch.trapezoid(y)
  10288. tensor([ 2., 8., 14.])
  10289. >>> # Computes the trapezoidal rule for each column of the matrix
  10290. >>> torch.trapezoid(y, dim=0)
  10291. tensor([ 6., 8., 10.])
  10292. >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix
  10293. >>> # with the same arbitrary spacing
  10294. >>> y = torch.ones(3, 3)
  10295. >>> x = torch.tensor([1, 3, 6])
  10296. >>> torch.trapezoid(y, x)
  10297. array([5., 5., 5.])
  10298. >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix
  10299. >>> # with different arbitrary spacing per row
  10300. >>> y = torch.ones(3, 3)
  10301. >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]])
  10302. >>> torch.trapezoid(y, x)
  10303. array([2., 4., 6.])
  10304. """,
  10305. )
  10306. add_docstr(
  10307. torch.trapz,
  10308. r"""
  10309. trapz(y, x, *, dim=-1) -> Tensor
  10310. Alias for :func:`torch.trapezoid`.
  10311. """,
  10312. )
  10313. add_docstr(
  10314. torch.cumulative_trapezoid,
  10315. r"""
  10316. cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor
  10317. Cumulatively computes the `trapezoidal rule <https://en.wikipedia.org/wiki/Trapezoidal_rule>`_
  10318. along :attr:`dim`. By default the spacing between elements is assumed to be 1, but
  10319. :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be
  10320. used to specify arbitrary spacing along :attr:`dim`.
  10321. For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid`
  10322. and this function is that, :func:`torch.trapezoid` returns a value for each integration,
  10323. where as this function returns a cumulative value for every spacing within the integration. This
  10324. is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum.
  10325. Arguments:
  10326. y (Tensor): Values to use when computing the trapezoidal rule.
  10327. x (Tensor): If specified, defines spacing between values as specified above.
  10328. Keyword arguments:
  10329. dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx`
  10330. are specified then this defaults to 1. Effectively multiplies the result by its value.
  10331. dim (int): The dimension along which to compute the trapezoidal rule.
  10332. The last (inner-most) dimension by default.
  10333. Examples::
  10334. >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1.
  10335. >>> y = torch.tensor([1, 5, 10])
  10336. >>> torch.cumulative_trapezoid(y)
  10337. tensor([3., 10.5])
  10338. >>> # Computes the same trapezoidal rule directly up to each element to verify
  10339. >>> (1 + 5) / 2
  10340. 3.0
  10341. >>> (1 + 10 + 10) / 2
  10342. 10.5
  10343. >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2
  10344. >>> # NOTE: the result is the same as before, but multiplied by 2
  10345. >>> torch.cumulative_trapezoid(y, dx=2)
  10346. tensor([6., 21.])
  10347. >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing
  10348. >>> x = torch.tensor([1, 3, 6])
  10349. >>> torch.cumulative_trapezoid(y, x)
  10350. tensor([6., 28.5])
  10351. >>> # Computes the same trapezoidal rule directly up to each element to verify
  10352. >>> ((3 - 1) * (1 + 5)) / 2
  10353. 6.0
  10354. >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2
  10355. 28.5
  10356. >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix
  10357. >>> y = torch.arange(9).reshape(3, 3)
  10358. tensor([[0, 1, 2],
  10359. [3, 4, 5],
  10360. [6, 7, 8]])
  10361. >>> torch.cumulative_trapezoid(y)
  10362. tensor([[ 0.5, 2.],
  10363. [ 3.5, 8.],
  10364. [ 6.5, 14.]])
  10365. >>> # Cumulatively computes the trapezoidal rule for each column of the matrix
  10366. >>> torch.cumulative_trapezoid(y, dim=0)
  10367. tensor([[ 1.5, 2.5, 3.5],
  10368. [ 6.0, 8.0, 10.0]])
  10369. >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix
  10370. >>> # with the same arbitrary spacing
  10371. >>> y = torch.ones(3, 3)
  10372. >>> x = torch.tensor([1, 3, 6])
  10373. >>> torch.cumulative_trapezoid(y, x)
  10374. tensor([[2., 5.],
  10375. [2., 5.],
  10376. [2., 5.]])
  10377. >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix
  10378. >>> # with different arbitrary spacing per row
  10379. >>> y = torch.ones(3, 3)
  10380. >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]])
  10381. >>> torch.cumulative_trapezoid(y, x)
  10382. tensor([[1., 2.],
  10383. [2., 4.],
  10384. [3., 6.]])
  10385. """,
  10386. )
  10387. add_docstr(
  10388. torch.repeat_interleave,
  10389. r"""
  10390. repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor
  10391. Repeat elements of a tensor.
  10392. .. warning::
  10393. This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``.
  10394. Args:
  10395. {input}
  10396. repeats (Tensor or int): The number of repetitions for each element.
  10397. repeats is broadcasted to fit the shape of the given axis.
  10398. dim (int, optional): The dimension along which to repeat values.
  10399. By default, use the flattened input array, and return a flat output
  10400. array.
  10401. Keyword args:
  10402. output_size (int, optional): Total output size for the given axis
  10403. ( e.g. sum of repeats). If given, it will avoid stream synchronization
  10404. needed to calculate output shape of the tensor.
  10405. Returns:
  10406. Tensor: Repeated tensor which has the same shape as input, except along the given axis.
  10407. Example::
  10408. >>> x = torch.tensor([1, 2, 3])
  10409. >>> x.repeat_interleave(2)
  10410. tensor([1, 1, 2, 2, 3, 3])
  10411. >>> y = torch.tensor([[1, 2], [3, 4]])
  10412. >>> torch.repeat_interleave(y, 2)
  10413. tensor([1, 1, 2, 2, 3, 3, 4, 4])
  10414. >>> torch.repeat_interleave(y, 3, dim=1)
  10415. tensor([[1, 1, 1, 2, 2, 2],
  10416. [3, 3, 3, 4, 4, 4]])
  10417. >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0)
  10418. tensor([[1, 2],
  10419. [3, 4],
  10420. [3, 4]])
  10421. >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3)
  10422. tensor([[1, 2],
  10423. [3, 4],
  10424. [3, 4]])
  10425. If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be
  10426. `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times,
  10427. `1` appears `n2` times, `2` appears `n3` times, etc.
  10428. .. function:: repeat_interleave(repeats, *) -> Tensor
  10429. :noindex:
  10430. Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc.
  10431. Args:
  10432. repeats (Tensor): The number of repetitions for each element.
  10433. Returns:
  10434. Tensor: Repeated tensor of size `sum(repeats)`.
  10435. Example::
  10436. >>> torch.repeat_interleave(torch.tensor([1, 2, 3]))
  10437. tensor([0, 1, 1, 2, 2, 2])
  10438. """.format(**common_args),
  10439. )
  10440. add_docstr(
  10441. torch.tile,
  10442. r"""
  10443. tile(input, dims) -> Tensor
  10444. Constructs a tensor by repeating the elements of :attr:`input`.
  10445. The :attr:`dims` argument specifies the number of repetitions
  10446. in each dimension.
  10447. If :attr:`dims` specifies fewer dimensions than :attr:`input` has, then
  10448. ones are prepended to :attr:`dims` until all dimensions are specified.
  10449. For example, if :attr:`input` has shape (8, 6, 4, 2) and :attr:`dims`
  10450. is (2, 2), then :attr:`dims` is treated as (1, 1, 2, 2).
  10451. Analogously, if :attr:`input` has fewer dimensions than :attr:`dims`
  10452. specifies, then :attr:`input` is treated as if it were unsqueezed at
  10453. dimension zero until it has as many dimensions as :attr:`dims` specifies.
  10454. For example, if :attr:`input` has shape (4, 2) and :attr:`dims`
  10455. is (3, 3, 2, 2), then :attr:`input` is treated as if it had the
  10456. shape (1, 1, 4, 2).
  10457. .. note::
  10458. This function is similar to NumPy's tile function.
  10459. Args:
  10460. input (Tensor): the tensor whose elements to repeat.
  10461. dims (tuple): the number of repetitions per dimension.
  10462. Example::
  10463. >>> x = torch.tensor([1, 2, 3])
  10464. >>> x.tile((2,))
  10465. tensor([1, 2, 3, 1, 2, 3])
  10466. >>> y = torch.tensor([[1, 2], [3, 4]])
  10467. >>> torch.tile(y, (2, 2))
  10468. tensor([[1, 2, 1, 2],
  10469. [3, 4, 3, 4],
  10470. [1, 2, 1, 2],
  10471. [3, 4, 3, 4]])
  10472. """,
  10473. )
  10474. add_docstr(
  10475. torch.quantize_per_tensor,
  10476. r"""
  10477. quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor
  10478. Converts a float tensor to a quantized tensor with given scale and zero point.
  10479. Arguments:
  10480. input (Tensor): float tensor or list of tensors to quantize
  10481. scale (float or Tensor): scale to apply in quantization formula
  10482. zero_point (int or Tensor): offset in integer value that maps to float zero
  10483. dtype (:class:`torch.dtype`): the desired data type of returned tensor.
  10484. Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32``
  10485. Returns:
  10486. Tensor: A newly quantized tensor or list of quantized tensors.
  10487. Example::
  10488. >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8)
  10489. tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8,
  10490. quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10)
  10491. >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr()
  10492. tensor([ 0, 10, 20, 30], dtype=torch.uint8)
  10493. >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])],
  10494. >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8)
  10495. (tensor([-1., 0.], size=(2,), dtype=torch.quint8,
  10496. quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10),
  10497. tensor([-2., 2.], size=(2,), dtype=torch.quint8,
  10498. quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20))
  10499. >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8)
  10500. tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8,
  10501. quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10)
  10502. """,
  10503. )
  10504. add_docstr(
  10505. torch.quantize_per_tensor_dynamic,
  10506. r"""
  10507. quantize_per_tensor_dynamic(input, dtype, reduce_range) -> Tensor
  10508. Converts a float tensor to a quantized tensor with scale and zero_point calculated
  10509. dynamically based on the input.
  10510. Arguments:
  10511. input (Tensor): float tensor or list of tensors to quantize
  10512. dtype (:class:`torch.dtype`): the desired data type of returned tensor.
  10513. Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``
  10514. reduce_range (bool): a flag to indicate whether to reduce the range of quantized
  10515. data by 1 bit, it's required to avoid instruction overflow for some hardwares
  10516. Returns:
  10517. Tensor: A newly (dynamically) quantized tensor
  10518. Example::
  10519. >>> t = torch.quantize_per_tensor_dynamic(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.quint8, False)
  10520. >>> print(t)
  10521. tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8,
  10522. quantization_scheme=torch.per_tensor_affine, scale=0.011764705882352941,
  10523. zero_point=85)
  10524. >>> t.int_repr()
  10525. tensor([ 0, 85, 170, 255], dtype=torch.uint8)
  10526. """,
  10527. )
  10528. add_docstr(
  10529. torch.quantize_per_channel,
  10530. r"""
  10531. quantize_per_channel(input, scales, zero_points, axis, dtype) -> Tensor
  10532. Converts a float tensor to a per-channel quantized tensor with given scales and zero points.
  10533. Arguments:
  10534. input (Tensor): float tensor to quantize
  10535. scales (Tensor): float 1D tensor of scales to use, size should match ``input.size(axis)``
  10536. zero_points (int): integer 1D tensor of offset to use, size should match ``input.size(axis)``
  10537. axis (int): dimension on which apply per-channel quantization
  10538. dtype (:class:`torch.dtype`): the desired data type of returned tensor.
  10539. Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32``
  10540. Returns:
  10541. Tensor: A newly quantized tensor
  10542. Example::
  10543. >>> x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]])
  10544. >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8)
  10545. tensor([[-1., 0.],
  10546. [ 1., 2.]], size=(2, 2), dtype=torch.quint8,
  10547. quantization_scheme=torch.per_channel_affine,
  10548. scale=tensor([0.1000, 0.0100], dtype=torch.float64),
  10549. zero_point=tensor([10, 0]), axis=0)
  10550. >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8).int_repr()
  10551. tensor([[ 0, 10],
  10552. [100, 200]], dtype=torch.uint8)
  10553. """,
  10554. )
  10555. add_docstr(
  10556. torch.quantized_batch_norm,
  10557. r"""
  10558. quantized_batch_norm(input, weight=None, bias=None, mean, var, eps, output_scale, output_zero_point) -> Tensor
  10559. Applies batch normalization on a 4D (NCHW) quantized tensor.
  10560. .. math::
  10561. y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
  10562. Arguments:
  10563. input (Tensor): quantized tensor
  10564. weight (Tensor): float tensor that corresponds to the gamma, size C
  10565. bias (Tensor): float tensor that corresponds to the beta, size C
  10566. mean (Tensor): float mean value in batch normalization, size C
  10567. var (Tensor): float tensor for variance, size C
  10568. eps (float): a value added to the denominator for numerical stability.
  10569. output_scale (float): output quantized tensor scale
  10570. output_zero_point (int): output quantized tensor zero_point
  10571. Returns:
  10572. Tensor: A quantized tensor with batch normalization applied.
  10573. Example::
  10574. >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8)
  10575. >>> torch.quantized_batch_norm(qx, torch.ones(2), torch.zeros(2), torch.rand(2), torch.rand(2), 0.00001, 0.2, 2)
  10576. tensor([[[[-0.2000, -0.2000],
  10577. [ 1.6000, -0.2000]],
  10578. [[-0.4000, -0.4000],
  10579. [-0.4000, 0.6000]]],
  10580. [[[-0.2000, -0.2000],
  10581. [-0.2000, -0.2000]],
  10582. [[ 0.6000, -0.4000],
  10583. [ 0.6000, -0.4000]]]], size=(2, 2, 2, 2), dtype=torch.quint8,
  10584. quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=2)
  10585. """,
  10586. )
  10587. add_docstr(
  10588. torch.quantized_max_pool1d,
  10589. r"""
  10590. quantized_max_pool1d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor
  10591. Applies a 1D max pooling over an input quantized tensor composed of several input planes.
  10592. Arguments:
  10593. input (Tensor): quantized tensor
  10594. kernel_size (list of int): the size of the sliding window
  10595. stride (``list of int``, optional): the stride of the sliding window
  10596. padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2
  10597. dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1
  10598. ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape.
  10599. Defaults to False.
  10600. Returns:
  10601. Tensor: A quantized tensor with max_pool1d applied.
  10602. Example::
  10603. >>> qx = torch.quantize_per_tensor(torch.rand(2, 2), 1.5, 3, torch.quint8)
  10604. >>> torch.quantized_max_pool1d(qx, [2])
  10605. tensor([[0.0000],
  10606. [1.5000]], size=(2, 1), dtype=torch.quint8,
  10607. quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3)
  10608. """,
  10609. )
  10610. add_docstr(
  10611. torch.quantized_max_pool2d,
  10612. r"""
  10613. quantized_max_pool2d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor
  10614. Applies a 2D max pooling over an input quantized tensor composed of several input planes.
  10615. Arguments:
  10616. input (Tensor): quantized tensor
  10617. kernel_size (``list of int``): the size of the sliding window
  10618. stride (``list of int``, optional): the stride of the sliding window
  10619. padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2
  10620. dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1
  10621. ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape.
  10622. Defaults to False.
  10623. Returns:
  10624. Tensor: A quantized tensor with max_pool2d applied.
  10625. Example::
  10626. >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8)
  10627. >>> torch.quantized_max_pool2d(qx, [2,2])
  10628. tensor([[[[1.5000]],
  10629. [[1.5000]]],
  10630. [[[0.0000]],
  10631. [[0.0000]]]], size=(2, 2, 1, 1), dtype=torch.quint8,
  10632. quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3)
  10633. """,
  10634. )
  10635. add_docstr(
  10636. torch.Stream,
  10637. r"""
  10638. Stream(device, *, priority) -> Stream
  10639. An in-order queue of executing the respective tasks asynchronously in first in first out (FIFO) order.
  10640. It can control or synchronize the execution of other Stream or block the current host thread to ensure
  10641. the correct task sequencing. It supports with statement as a context manager to ensure the operators
  10642. within the with block are running on the corresponding stream.
  10643. See in-depth description of the CUDA behavior at :ref:`cuda-semantics` for details
  10644. on the exact semantic that applies to all devices.
  10645. Arguments:
  10646. device (:class:`torch.device`, optional): the desired device for the Stream.
  10647. If not given, the current :ref:`accelerator<accelerators>` type will be used.
  10648. priority (int, optional): priority of the stream, should be 0 or negative, where negative
  10649. numbers indicate higher priority. By default, streams have priority 0.
  10650. Returns:
  10651. Stream: An torch.Stream object.
  10652. Example::
  10653. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10654. >>> with torch.Stream(device='cuda') as s_cuda:
  10655. >>> a = torch.randn(10, 5, device='cuda')
  10656. >>> b = torch.randn(5, 10, device='cuda')
  10657. >>> c = torch.mm(a, b)
  10658. """,
  10659. )
  10660. add_docstr(
  10661. torch.Stream.query,
  10662. r"""
  10663. Stream.query() -> bool
  10664. Check if all the work submitted has been completed.
  10665. Returns:
  10666. bool: A boolean indicating if all kernels in this stream are completed.
  10667. Example::
  10668. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10669. >>> s_cuda = torch.Stream(device='cuda')
  10670. >>> s_cuda.query()
  10671. True
  10672. """,
  10673. )
  10674. add_docstr(
  10675. torch.Stream.record_event,
  10676. r"""
  10677. Stream.record_event(event) -> Event
  10678. Record an event. En-queuing it into the Stream to allow further synchronization from the current point in the FIFO queue.
  10679. Arguments:
  10680. event (:class:`torch.Event`, optional): event to record. If not given, a new one will be allocated.
  10681. Returns:
  10682. Event: Recorded event.
  10683. Example::
  10684. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10685. >>> s_cuda = torch.Stream(device='cuda')
  10686. >>> e_cuda = s_cuda.record_event()
  10687. """,
  10688. )
  10689. add_docstr(
  10690. torch.Stream.synchronize,
  10691. r"""
  10692. Stream.synchronize() -> None
  10693. Wait for all the kernels in this stream to complete.
  10694. Example::
  10695. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10696. >>> s_cuda = torch.Stream(device='cuda')
  10697. >>> s_cuda.synchronize()
  10698. """,
  10699. )
  10700. add_docstr(
  10701. torch.Stream.wait_event,
  10702. r"""
  10703. Stream.wait_event(event) -> None
  10704. Make all future work submitted to the stream wait for an event.
  10705. Arguments:
  10706. event (:class:`torch.Event`): an event to wait for.
  10707. Example::
  10708. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10709. >>> s1_cuda = torch.Stream(device='cuda')
  10710. >>> s2_cuda = torch.Stream(device='cuda')
  10711. >>> e_cuda = s1_cuda.record_event()
  10712. >>> s2_cuda.wait_event(e_cuda)
  10713. """,
  10714. )
  10715. add_docstr(
  10716. torch.Stream.wait_stream,
  10717. r"""
  10718. Stream.wait_stream(stream) -> None
  10719. Synchronize with another stream. All future work submitted to this stream will wait until all kernels
  10720. already submitted to the given stream are completed.
  10721. Arguments:
  10722. stream (:class:`torch.Stream`): a stream to synchronize.
  10723. Example::
  10724. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10725. >>> s1_cuda = torch.Stream(device='cuda')
  10726. >>> s2_cuda = torch.Stream(device='cuda')
  10727. >>> s2_cuda.wait_stream(s1_cuda)
  10728. """,
  10729. )
  10730. add_docstr(
  10731. torch.Event,
  10732. r"""
  10733. Event(device=None, *, enable_timing=False, blocking=False, interprocess=False)
  10734. Query and record Stream status to identify or control dependencies across Stream and measure timing.
  10735. Arguments:
  10736. device (:class:`torch.device`, optional): the desired device for the Event.
  10737. If not given, the current :ref:`accelerator<accelerators>` type will be used.
  10738. enable_timing (bool, optional): indicates if the event should measure time (default: ``False``)
  10739. blocking (bool, optional): if ``True``, :meth:`wait` will be blocking (default: ``False``)
  10740. interprocess (bool): if ``True``, the event can be shared between processes (default: ``False``)
  10741. .. warning::
  10742. Both blocking and interprocess are not supported right now and are noops.
  10743. Returns:
  10744. Event: An torch.Event object.
  10745. Example::
  10746. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10747. >>> event = torch.Event()
  10748. >>> e_cuda = torch.Event(device='cuda')
  10749. """,
  10750. )
  10751. add_docstr(
  10752. torch.Event.elapsed_time,
  10753. r"""
  10754. Event.elapsed_time(end_event) -> float
  10755. Returns the elapsed time in milliseconds between when this event and the :attr:`end_event` are
  10756. each recorded via :func:`torch.Stream.record_event`.
  10757. Arguments:
  10758. end_event (:class:`torch.Event`): The ending event has been recorded.
  10759. Returns:
  10760. float: Time between starting and ending event in milliseconds.
  10761. Example::
  10762. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10763. >>> s_cuda = torch.Stream(device='cuda')
  10764. >>> e1_cuda = s_cuda.record_event()
  10765. >>> e2_cuda = s_cuda.record_event()
  10766. >>> ms = e1_cuda.elapsed_time(e2_cuda)
  10767. """,
  10768. )
  10769. add_docstr(
  10770. torch.Event.query,
  10771. r"""
  10772. Event.query() -> bool
  10773. Check if the stream where this event was recorded already moved past the point where the event was recorded.
  10774. Always returns ``True`` if the Event was not recorded.
  10775. Returns:
  10776. bool: A boolean indicating if all work currently captured by event has completed.
  10777. Example::
  10778. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10779. >>> s_cuda = torch.Stream(device='cuda')
  10780. >>> e_cuda = s_cuda.record_event()
  10781. >>> e_cuda.query()
  10782. True
  10783. """,
  10784. )
  10785. add_docstr(
  10786. torch.Event.record,
  10787. r"""
  10788. Event.record(stream=None) -> None
  10789. Record the event in a given stream. The stream's device must match the event's device.
  10790. This function is equivalent to ``stream.record_event(self)``.
  10791. Arguments:
  10792. stream (:class:`torch.Stream`, optional): A stream to be recorded.
  10793. If not given, the current stream will be used.
  10794. Example::
  10795. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10796. >>> e_cuda = torch.Event(device='cuda')
  10797. >>> e_cuda.record()
  10798. """,
  10799. )
  10800. add_docstr(
  10801. torch.Event.synchronize,
  10802. r"""
  10803. Event.synchronize() -> None
  10804. Wait for the event to complete. This prevents the CPU thread from proceeding until the event completes.
  10805. Example::
  10806. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10807. >>> s_cuda = torch.Stream(device='cuda')
  10808. >>> e_cuda = s_cuda.record_event()
  10809. >>> e_cuda.synchronize()
  10810. """,
  10811. )
  10812. add_docstr(
  10813. torch.Event.wait,
  10814. r"""
  10815. Event.wait(stream=None) -> None
  10816. Make all future work submitted to the given stream wait for this event.
  10817. Arguments:
  10818. stream (:class:`torch.Stream`, optional): A stream to synchronize.
  10819. If not given, the current stream will be used.
  10820. Example::
  10821. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10822. >>> s1_cuda = torch.Stream(device='cuda')
  10823. >>> s2_cuda = torch.Stream(device='cuda')
  10824. >>> e_cuda = s1_cuda.record()
  10825. >>> e_cuda.wait(s2)
  10826. """,
  10827. )
  10828. add_docstr(
  10829. torch.Generator,
  10830. r"""
  10831. Generator(device='cpu') -> Generator
  10832. Creates and returns a generator object that manages the state of the algorithm which
  10833. produces pseudo random numbers. Used as a keyword argument in many :ref:`inplace-random-sampling`
  10834. functions.
  10835. Arguments:
  10836. device (:class:`torch.device`, optional): the desired device for the generator.
  10837. Returns:
  10838. Generator: An torch.Generator object.
  10839. Example::
  10840. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  10841. >>> g_cpu = torch.Generator()
  10842. >>> g_cuda = torch.Generator(device='cuda')
  10843. """,
  10844. )
  10845. add_docstr(
  10846. torch.Generator.set_state,
  10847. r"""
  10848. Generator.set_state(new_state) -> void
  10849. Sets the Generator state.
  10850. Arguments:
  10851. new_state (torch.ByteTensor): The desired state.
  10852. Example::
  10853. >>> g_cpu = torch.Generator()
  10854. >>> g_cpu_other = torch.Generator()
  10855. >>> g_cpu.set_state(g_cpu_other.get_state())
  10856. """,
  10857. )
  10858. add_docstr(
  10859. torch.Generator.get_state,
  10860. r"""
  10861. Generator.get_state() -> Tensor
  10862. Returns the Generator state as a ``torch.ByteTensor``.
  10863. Returns:
  10864. Tensor: A ``torch.ByteTensor`` which contains all the necessary bits
  10865. to restore a Generator to a specific point in time.
  10866. Example::
  10867. >>> g_cpu = torch.Generator()
  10868. >>> g_cpu.get_state()
  10869. """,
  10870. )
  10871. add_docstr(
  10872. torch.Generator.graphsafe_set_state,
  10873. r"""
  10874. Generator.graphsafe_set_state(state) -> None
  10875. Sets the state of the generator to the specified state in a manner that is safe for use in graph capture.
  10876. This method is crucial for ensuring that the generator's state can be captured in the CUDA graph.
  10877. Arguments:
  10878. state (torch.Generator): A Generator point to the new state for the generator, typically obtained from `graphsafe_get_state`.
  10879. Example:
  10880. >>> g_cuda = torch.Generator(device='cuda')
  10881. >>> g_cuda_other = torch.Generator(device='cuda')
  10882. >>> current_state = g_cuda_other.graphsafe_get_state()
  10883. >>> g_cuda.graphsafe_set_state(current_state)
  10884. """,
  10885. )
  10886. add_docstr(
  10887. torch.Generator.graphsafe_get_state,
  10888. r"""
  10889. Generator.graphsafe_get_state() -> torch.Generator
  10890. Retrieves the current state of the generator in a manner that is safe for graph capture.
  10891. This method is crucial for ensuring that the generator's state can be captured in the CUDA graph.
  10892. Returns:
  10893. torch.Generator: A Generator point to the current state of the generator
  10894. Example:
  10895. >>> g_cuda = torch.Generator(device='cuda')
  10896. >>> current_state = g_cuda.graphsafe_get_state()
  10897. """,
  10898. )
  10899. add_docstr(
  10900. torch.Generator.clone_state,
  10901. r"""
  10902. Generator.clone_state() -> torch.Generator
  10903. Clones the current state of the generator and returns a new generator pointing to this cloned state.
  10904. This method is beneficial for preserving a particular state of a generator to restore at a later point.
  10905. Returns:
  10906. torch.Generator: A Generator pointing to the newly cloned state.
  10907. Example:
  10908. >>> g_cuda = torch.Generator(device='cuda')
  10909. >>> cloned_state = g_cuda.clone_state()
  10910. """,
  10911. )
  10912. add_docstr(
  10913. torch.Generator.manual_seed,
  10914. r"""
  10915. Generator.manual_seed(seed) -> Generator
  10916. Sets the seed for generating random numbers. Returns a `torch.Generator` object. Any 32-bit integer is a valid seed.
  10917. Arguments:
  10918. seed (int): The desired seed. Value must be within the inclusive range
  10919. `[-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]`. Otherwise, a RuntimeError
  10920. is raised. Negative inputs are remapped to positive values with the formula
  10921. `0xffff_ffff_ffff_ffff + seed`.
  10922. Returns:
  10923. Generator: An torch.Generator object.
  10924. Example::
  10925. >>> g_cpu = torch.Generator()
  10926. >>> g_cpu.manual_seed(2147483647)
  10927. """,
  10928. )
  10929. add_docstr(
  10930. torch.Generator.initial_seed,
  10931. r"""
  10932. Generator.initial_seed() -> int
  10933. Returns the initial seed for generating random numbers.
  10934. Example::
  10935. >>> g_cpu = torch.Generator()
  10936. >>> g_cpu.initial_seed()
  10937. 2147483647
  10938. """,
  10939. )
  10940. add_docstr(
  10941. torch.Generator.seed,
  10942. r"""
  10943. Generator.seed() -> int
  10944. Gets a non-deterministic random number from std::random_device or the current
  10945. time and uses it to seed a Generator.
  10946. Example::
  10947. >>> g_cpu = torch.Generator()
  10948. >>> g_cpu.seed()
  10949. 1516516984916
  10950. """,
  10951. )
  10952. add_docstr(
  10953. torch.Generator.device,
  10954. r"""
  10955. Generator.device -> device
  10956. Gets the current device of the generator.
  10957. Example::
  10958. >>> g_cpu = torch.Generator()
  10959. >>> g_cpu.device
  10960. device(type='cpu')
  10961. """,
  10962. )
  10963. add_docstr(
  10964. torch._assert_async,
  10965. r"""
  10966. _assert_async(tensor) -> void
  10967. Asynchronously assert that the contents of tensor are nonzero. For CPU tensors,
  10968. this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for
  10969. CUDA tensors, we DO NOT synchronize and you may only find out the assertion
  10970. failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for
  10971. testing invariants in CUDA tensors without giving up performance. This function
  10972. is NOT intended to be used for regular error checking, as it will trash your CUDA
  10973. context if the assert fails (forcing you to restart your PyTorch process.)
  10974. Args:
  10975. tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero
  10976. elements (including False for boolean tensors) cause an assertion failure
  10977. to be raised.
  10978. """,
  10979. )
  10980. add_docstr(
  10981. torch.searchsorted,
  10982. r"""
  10983. searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor
  10984. Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the
  10985. corresponding values in :attr:`values` were inserted before the indices, when sorted, the order
  10986. of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved.
  10987. Return a new tensor with the same size as :attr:`values`. More formally,
  10988. the returned index satisfies the following rules:
  10989. .. list-table::
  10990. :widths: 12 10 78
  10991. :header-rows: 1
  10992. * - :attr:`sorted_sequence`
  10993. - :attr:`right`
  10994. - *returned index satisfies*
  10995. * - 1-D
  10996. - False
  10997. - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]``
  10998. * - 1-D
  10999. - True
  11000. - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]``
  11001. * - N-D
  11002. - False
  11003. - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]``
  11004. * - N-D
  11005. - True
  11006. - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]``
  11007. Args:
  11008. sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost*
  11009. dimension unless :attr:`sorter` is provided, in which case the sequence does not
  11010. need to be sorted
  11011. values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s).
  11012. Keyword args:
  11013. out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise.
  11014. Default value is False, i.e. default output data type is torch.int64.
  11015. right (bool, optional): if False, return the first suitable location that is found. If True, return the
  11016. last such index. If no suitable index found, return 0 for non-numerical value
  11017. (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence`
  11018. (one pass the last index of the *innermost* dimension). In other words, if False,
  11019. gets the lower bound index for each value in :attr:`values` on the corresponding
  11020. *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper
  11021. bound index instead. Default value is False. :attr:`side` does the same and is
  11022. preferred. It will error if :attr:`side` is set to "left" while this is True.
  11023. side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right`
  11024. and "right" corresponds to True for :attr:`right`. It will error if this is set to
  11025. "left" while :attr:`right` is True. Default value is None.
  11026. out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided.
  11027. sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted
  11028. :attr:`sorted_sequence` containing a sequence of indices that sort it in the
  11029. ascending order on the innermost dimension
  11030. Example::
  11031. >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]])
  11032. >>> sorted_sequence
  11033. tensor([[ 1, 3, 5, 7, 9],
  11034. [ 2, 4, 6, 8, 10]])
  11035. >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]])
  11036. >>> values
  11037. tensor([[3, 6, 9],
  11038. [3, 6, 9]])
  11039. >>> torch.searchsorted(sorted_sequence, values)
  11040. tensor([[1, 3, 4],
  11041. [1, 2, 4]])
  11042. >>> torch.searchsorted(sorted_sequence, values, side='right')
  11043. tensor([[2, 3, 5],
  11044. [1, 3, 4]])
  11045. >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9])
  11046. >>> sorted_sequence_1d
  11047. tensor([1, 3, 5, 7, 9])
  11048. >>> torch.searchsorted(sorted_sequence_1d, values)
  11049. tensor([[1, 3, 4],
  11050. [1, 3, 4]])
  11051. """,
  11052. )
  11053. add_docstr(
  11054. torch.bucketize,
  11055. r"""
  11056. bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor
  11057. Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the
  11058. boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size
  11059. as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that
  11060. this behavior is opposite the behavior of
  11061. `numpy.digitize <https://numpy.org/doc/stable/reference/generated/numpy.digitize.html>`_.
  11062. More formally, the returned index satisfies the following rules:
  11063. .. list-table::
  11064. :widths: 15 85
  11065. :header-rows: 1
  11066. * - :attr:`right`
  11067. - *returned index satisfies*
  11068. * - False
  11069. - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]``
  11070. * - True
  11071. - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]``
  11072. Args:
  11073. input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s).
  11074. boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined.
  11075. Keyword args:
  11076. out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise.
  11077. Default value is False, i.e. default output data type is torch.int64.
  11078. right (bool, optional): determines the behavior for values in :attr:`boundaries`. See the table above.
  11079. out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided.
  11080. Example::
  11081. >>> boundaries = torch.tensor([1, 3, 5, 7, 9])
  11082. >>> boundaries
  11083. tensor([1, 3, 5, 7, 9])
  11084. >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]])
  11085. >>> v
  11086. tensor([[3, 6, 9],
  11087. [3, 6, 9]])
  11088. >>> torch.bucketize(v, boundaries)
  11089. tensor([[1, 3, 4],
  11090. [1, 3, 4]])
  11091. >>> torch.bucketize(v, boundaries, right=True)
  11092. tensor([[2, 3, 5],
  11093. [2, 3, 5]])
  11094. """,
  11095. )
  11096. add_docstr(
  11097. torch.view_as_real_copy,
  11098. r"""
  11099. Performs the same operation as :func:`torch.view_as_real`, but all output tensors
  11100. are freshly created instead of aliasing the input.
  11101. """,
  11102. )
  11103. add_docstr(
  11104. torch.view_as_complex_copy,
  11105. r"""
  11106. Performs the same operation as :func:`torch.view_as_complex`, but all output tensors
  11107. are freshly created instead of aliasing the input.
  11108. """,
  11109. )
  11110. add_docstr(
  11111. torch.as_strided_copy,
  11112. r"""
  11113. Performs the same operation as :func:`torch.as_strided`, but all output tensors
  11114. are freshly created instead of aliasing the input.
  11115. """,
  11116. )
  11117. add_docstr(
  11118. torch.diagonal_copy,
  11119. r"""
  11120. Performs the same operation as :func:`torch.diagonal`, but all output tensors
  11121. are freshly created instead of aliasing the input.
  11122. """,
  11123. )
  11124. add_docstr(
  11125. torch.expand_copy,
  11126. r"""
  11127. Performs the same operation as :func:`torch.Tensor.expand`, but all output tensors
  11128. are freshly created instead of aliasing the input.
  11129. """,
  11130. )
  11131. add_docstr(
  11132. torch.permute_copy,
  11133. r"""
  11134. Performs the same operation as :func:`torch.permute`, but all output tensors
  11135. are freshly created instead of aliasing the input.
  11136. """,
  11137. )
  11138. add_docstr(
  11139. torch.select_copy,
  11140. r"""
  11141. Performs the same operation as :func:`torch.select`, but all output tensors
  11142. are freshly created instead of aliasing the input.
  11143. """,
  11144. )
  11145. add_docstr(
  11146. torch.detach_copy,
  11147. r"""
  11148. Performs the same operation as :func:`torch.detach`, but all output tensors
  11149. are freshly created instead of aliasing the input.
  11150. """,
  11151. )
  11152. add_docstr(
  11153. torch.slice_copy,
  11154. r"""
  11155. Performs the same operation as :func:`torch.slice`, but all output tensors
  11156. are freshly created instead of aliasing the input.
  11157. """,
  11158. )
  11159. add_docstr(
  11160. torch.split_copy,
  11161. r"""
  11162. Performs the same operation as :func:`torch.split`, but all output tensors
  11163. are freshly created instead of aliasing the input.
  11164. """,
  11165. )
  11166. add_docstr(
  11167. torch.split_with_sizes_copy,
  11168. r"""
  11169. Performs the same operation as :func:`torch.split_with_sizes`, but all output tensors
  11170. are freshly created instead of aliasing the input.
  11171. """,
  11172. )
  11173. add_docstr(
  11174. torch.squeeze_copy,
  11175. r"""
  11176. Performs the same operation as :func:`torch.squeeze`, but all output tensors
  11177. are freshly created instead of aliasing the input.
  11178. """,
  11179. )
  11180. add_docstr(
  11181. torch.t_copy,
  11182. r"""
  11183. Performs the same operation as :func:`torch.t`, but all output tensors
  11184. are freshly created instead of aliasing the input.
  11185. """,
  11186. )
  11187. add_docstr(
  11188. torch.transpose_copy,
  11189. r"""
  11190. Performs the same operation as :func:`torch.transpose`, but all output tensors
  11191. are freshly created instead of aliasing the input.
  11192. """,
  11193. )
  11194. add_docstr(
  11195. torch.unsqueeze_copy,
  11196. r"""
  11197. Performs the same operation as :func:`torch.unsqueeze`, but all output tensors
  11198. are freshly created instead of aliasing the input.
  11199. """,
  11200. )
  11201. add_docstr(
  11202. torch.indices_copy,
  11203. r"""
  11204. Performs the same operation as :func:`torch.indices`, but all output tensors
  11205. are freshly created instead of aliasing the input.
  11206. """,
  11207. )
  11208. add_docstr(
  11209. torch.values_copy,
  11210. r"""
  11211. Performs the same operation as :func:`torch.values`, but all output tensors
  11212. are freshly created instead of aliasing the input.
  11213. """,
  11214. )
  11215. add_docstr(
  11216. torch.crow_indices_copy,
  11217. r"""
  11218. Performs the same operation as :func:`torch.crow_indices`, but all output tensors
  11219. are freshly created instead of aliasing the input.
  11220. """,
  11221. )
  11222. add_docstr(
  11223. torch.col_indices_copy,
  11224. r"""
  11225. Performs the same operation as :func:`torch.col_indices`, but all output tensors
  11226. are freshly created instead of aliasing the input.
  11227. """,
  11228. )
  11229. add_docstr(
  11230. torch.unbind_copy,
  11231. r"""
  11232. Performs the same operation as :func:`torch.unbind`, but all output tensors
  11233. are freshly created instead of aliasing the input.
  11234. """,
  11235. )
  11236. add_docstr(
  11237. torch.view_copy,
  11238. r"""
  11239. Performs the same operation as :func:`torch.view`, but all output tensors
  11240. are freshly created instead of aliasing the input.
  11241. """,
  11242. )
  11243. add_docstr(
  11244. torch.unfold_copy,
  11245. r"""
  11246. Performs the same operation as :func:`torch.unfold`, but all output tensors
  11247. are freshly created instead of aliasing the input.
  11248. """,
  11249. )
  11250. add_docstr(
  11251. torch.alias_copy,
  11252. r"""
  11253. Performs the same operation as :func:`torch.alias`, but all output tensors
  11254. are freshly created instead of aliasing the input.
  11255. """,
  11256. )
  11257. for unary_base_func_name in (
  11258. "exp",
  11259. "sqrt",
  11260. "abs",
  11261. "acos",
  11262. "asin",
  11263. "atan",
  11264. "ceil",
  11265. "cos",
  11266. "cosh",
  11267. "erf",
  11268. "erfc",
  11269. "expm1",
  11270. "floor",
  11271. "log",
  11272. "log10",
  11273. "log1p",
  11274. "log2",
  11275. "neg",
  11276. "tan",
  11277. "tanh",
  11278. "sin",
  11279. "sinh",
  11280. "round",
  11281. "lgamma",
  11282. "frac",
  11283. "reciprocal",
  11284. "sigmoid",
  11285. "trunc",
  11286. "zero",
  11287. ):
  11288. unary_foreach_func_name = f"_foreach_{unary_base_func_name}"
  11289. if hasattr(torch, unary_foreach_func_name):
  11290. add_docstr(
  11291. getattr(torch, unary_foreach_func_name),
  11292. rf"""
  11293. {unary_foreach_func_name}(self: List[Tensor]) -> List[Tensor]
  11294. Apply :func:`torch.{unary_base_func_name}` to each Tensor of the input list.
  11295. """,
  11296. )
  11297. unary_inplace_foreach_func_name = f"{unary_foreach_func_name}_"
  11298. if hasattr(torch, unary_inplace_foreach_func_name):
  11299. add_docstr(
  11300. getattr(torch, unary_inplace_foreach_func_name),
  11301. rf"""
  11302. {unary_inplace_foreach_func_name}(self: List[Tensor]) -> None
  11303. Apply :func:`torch.{unary_base_func_name}` to each Tensor of the input list.
  11304. """,
  11305. )