common_utils.py 206 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027
  1. # mypy: ignore-errors
  2. r"""Importing this file must **not** initialize CUDA context. test_distributed
  3. relies on this assumption to properly run. This means that when this is imported
  4. no CUDA calls shall be made, including torch.cuda.device_count(), etc.
  5. torch.testing._internal.common_cuda.py can freely initialize CUDA context when imported.
  6. """
  7. import argparse
  8. import contextlib
  9. import copy
  10. import ctypes
  11. import errno
  12. import functools
  13. import gc
  14. import inspect
  15. import io
  16. import json
  17. import logging
  18. import math
  19. import operator
  20. import os
  21. import platform
  22. import random
  23. import re
  24. import shutil
  25. import signal
  26. import socket
  27. import subprocess
  28. import sys
  29. import tempfile
  30. import threading
  31. import time
  32. import types
  33. import unittest
  34. import warnings
  35. from collections.abc import Mapping, Sequence
  36. from contextlib import closing, contextmanager
  37. from copy import deepcopy
  38. from dataclasses import dataclass
  39. from enum import Enum
  40. from functools import partial, wraps
  41. from itertools import product, chain
  42. from pathlib import Path
  43. from statistics import mean
  44. from typing import (
  45. Any,
  46. Callable,
  47. Dict,
  48. Iterable,
  49. Iterator,
  50. List,
  51. Optional,
  52. Tuple,
  53. Type,
  54. TypeVar,
  55. Union,
  56. )
  57. from unittest.mock import MagicMock
  58. import expecttest
  59. import numpy as np
  60. import __main__ # type: ignore[import]
  61. import torch
  62. import torch.backends.cudnn
  63. import torch.backends.mkl
  64. import torch.backends.mps
  65. import torch.backends.xnnpack
  66. import torch.cuda
  67. from torch import Tensor
  68. from torch._C import ScriptDict, ScriptList # type: ignore[attr-defined]
  69. from torch._utils_internal import get_writable_path
  70. from torch.nn import (
  71. ModuleDict,
  72. ModuleList,
  73. ParameterDict,
  74. ParameterList,
  75. Sequential,
  76. )
  77. from torch.onnx import (
  78. register_custom_op_symbolic,
  79. unregister_custom_op_symbolic,
  80. )
  81. from torch.testing import make_tensor
  82. from torch.testing._comparison import (
  83. BooleanPair,
  84. NonePair,
  85. NumberPair,
  86. Pair,
  87. TensorLikePair,
  88. )
  89. from torch.testing._comparison import not_close_error_metas
  90. from torch.testing._internal.common_dtype import get_all_dtypes
  91. from torch.utils._import_utils import _check_module_exists
  92. import torch.utils._pytree as pytree
  93. try:
  94. import pytest
  95. has_pytest = True
  96. except ImportError:
  97. has_pytest = False
  98. def freeze_rng_state(*args, **kwargs):
  99. return torch.testing._utils.freeze_rng_state(*args, **kwargs)
  100. # Class to keep track of test flags configurable by environment variables.
  101. # Flags set here are intended to be read-only and should not be modified after
  102. # definition.
  103. # TODO: Expand this class to handle abritrary settings in addition to boolean flags?
  104. class TestEnvironment:
  105. # Set of env vars to set for the repro command that is output on test failure.
  106. # Specifically, this includes env vars that are set to non-default values and
  107. # are not implied. Maps from env var name -> value (int)
  108. repro_env_vars: dict = {}
  109. # Defines a flag usable throughout the test suite, determining its value by querying
  110. # the specified environment variable.
  111. #
  112. # Args:
  113. # name (str): The name of the flag. A global variable with this name will be set
  114. # for convenient access throughout the test suite.
  115. # env_var (str): The name of the primary environment variable from which to
  116. # determine the value of this flag. If this is None or the environment variable
  117. # is unset, the default value will be used unless otherwise implied (see
  118. # implied_by_fn). Default: None
  119. # default (bool): The default value to use for the flag if unset by the environment
  120. # variable and unimplied. Default: False
  121. # include_in_repro (bool): Indicates whether this flag should be included in the
  122. # repro command that is output on test failure (i.e. whether it is possibly
  123. # relevant to reproducing the test failure). Default: True
  124. # enabled_fn (Callable): Callable returning whether the flag should be enabled
  125. # given the environment variable value and the default value. Default: Lambda
  126. # requiring "0" to disable if on by default OR "1" to enable if off by default.
  127. # implied_by_fn (Callable): Thunk returning a bool to imply this flag as enabled
  128. # by something outside of its primary environment variable setting. For example,
  129. # this can be useful if the value of another environment variable implies the flag
  130. # as enabled. Default: Lambda returning False to indicate no implications.
  131. @staticmethod
  132. def def_flag(
  133. name,
  134. env_var=None,
  135. default=False,
  136. include_in_repro=True,
  137. enabled_fn=lambda env_var_val, default: (
  138. (env_var_val != "0") if default else (env_var_val == "1")),
  139. implied_by_fn=lambda: False,
  140. ):
  141. enabled = default
  142. if env_var is not None:
  143. env_var_val = os.getenv(env_var)
  144. enabled = enabled_fn(env_var_val, default)
  145. implied = implied_by_fn()
  146. enabled = enabled or implied
  147. if include_in_repro and (env_var is not None) and (enabled != default) and not implied:
  148. TestEnvironment.repro_env_vars[env_var] = env_var_val
  149. # export flag globally for convenience
  150. assert name not in globals(), f"duplicate definition of flag '{name}'"
  151. globals()[name] = enabled
  152. # Returns a string prefix usable to set environment variables for any test
  153. # settings that should be explicitly set to match this instantiation of the
  154. # test suite.
  155. # Example: "PYTORCH_TEST_WITH_ASAN=1 PYTORCH_TEST_WITH_ROCM=1"
  156. @staticmethod
  157. def repro_env_var_prefix() -> str:
  158. return " ".join([f"{env_var}={value}"
  159. for env_var, value in TestEnvironment.repro_env_vars.items()])
  160. log = logging.getLogger(__name__)
  161. torch.backends.disable_global_flags()
  162. FILE_SCHEMA = "file://"
  163. if sys.platform == 'win32':
  164. FILE_SCHEMA = "file:///"
  165. # NB: This flag differs semantically from others in that setting the env var to any
  166. # non-empty value will cause it to be true:
  167. # CI=1, CI="true", CI=0, etc. all set the flag to be true.
  168. # CI= and an unset CI set the flag to be false.
  169. # GitHub sets the value to CI="true" to enable it.
  170. TestEnvironment.def_flag("IS_CI", env_var="CI", include_in_repro=False,
  171. enabled_fn=lambda env_var_value, _: bool(env_var_value))
  172. TestEnvironment.def_flag(
  173. "IS_SANDCASTLE",
  174. env_var="SANDCASTLE",
  175. implied_by_fn=lambda: os.getenv("TW_JOB_USER") == "sandcastle",
  176. include_in_repro=False)
  177. _is_fbcode_default = (
  178. hasattr(torch._utils_internal, "IS_FBSOURCE") and
  179. torch._utils_internal.IS_FBSOURCE
  180. )
  181. TestEnvironment.def_flag("IS_FBCODE", env_var="PYTORCH_TEST_FBCODE",
  182. default=_is_fbcode_default,
  183. include_in_repro=False)
  184. TestEnvironment.def_flag("IS_REMOTE_GPU", env_var="PYTORCH_TEST_REMOTE_GPU",
  185. include_in_repro=False)
  186. TestEnvironment.def_flag(
  187. "DISABLE_RUNNING_SCRIPT_CHK",
  188. env_var="PYTORCH_DISABLE_RUNNING_SCRIPT_CHK",
  189. include_in_repro=False)
  190. # NB: enabled by default unless in an fbcode context.
  191. TestEnvironment.def_flag("PRINT_REPRO_ON_FAILURE", env_var="PYTORCH_PRINT_REPRO_ON_FAILURE",
  192. default=(not IS_FBCODE), include_in_repro=False) # noqa: F821
  193. DEFAULT_DISABLED_TESTS_FILE = '.pytorch-disabled-tests.json'
  194. DEFAULT_SLOW_TESTS_FILE = '.pytorch-slow-tests.json'
  195. disabled_tests_dict = {}
  196. slow_tests_dict = {}
  197. def maybe_load_json(filename):
  198. if os.path.isfile(filename):
  199. with open(filename) as fp:
  200. return json.load(fp)
  201. log.warning("Attempted to load json file '%s' but it does not exist.", filename)
  202. return {}
  203. # set them here in case the tests are running in a subprocess that doesn't call run_tests
  204. if os.getenv("SLOW_TESTS_FILE", ""):
  205. slow_tests_dict = maybe_load_json(os.getenv("SLOW_TESTS_FILE", ""))
  206. if os.getenv("DISABLED_TESTS_FILE", ""):
  207. disabled_tests_dict = maybe_load_json(os.getenv("DISABLED_TESTS_FILE", ""))
  208. NATIVE_DEVICES = ('cpu', 'cuda', 'meta', torch._C._get_privateuse1_backend_name())
  209. check_names = ['orin', 'concord', 'galen', 'xavier', 'nano', 'jetson', 'tegra']
  210. IS_JETSON = any(name in platform.platform() for name in check_names)
  211. def gcIfJetson(fn):
  212. # Irregular Jetson host/device memory setup requires cleanup to avoid tests being killed
  213. @functools.wraps(fn)
  214. def wrapper(*args, **kwargs):
  215. if IS_JETSON:
  216. gc.collect()
  217. torch.cuda.empty_cache()
  218. fn(*args, **kwargs)
  219. return wrapper
  220. # Tries to extract the current test function by crawling the stack.
  221. # If unsuccessful, return None.
  222. def extract_test_fn() -> Optional[Callable]:
  223. try:
  224. stack = inspect.stack()
  225. for frame_info in stack:
  226. frame = frame_info.frame
  227. if "self" not in frame.f_locals:
  228. continue
  229. self_val = frame.f_locals["self"]
  230. if isinstance(self_val, unittest.TestCase):
  231. test_id = self_val.id()
  232. test_name = test_id.split('.')[2]
  233. test_fn = getattr(self_val, test_name).__func__
  234. return test_fn
  235. except Exception:
  236. pass
  237. return None
  238. # Contains tracked input data useful for debugging purposes
  239. @dataclass
  240. class TrackedInput:
  241. index: int
  242. val: Any
  243. type_desc: str
  244. # Attempt to pull out tracked input information from the test function.
  245. # A TrackedInputIter is used to insert this information.
  246. def get_tracked_input() -> Optional[TrackedInput]:
  247. test_fn = extract_test_fn()
  248. if test_fn is None:
  249. return None
  250. if not hasattr(test_fn, "tracked_input"):
  251. return None
  252. return test_fn.tracked_input
  253. def clear_tracked_input():
  254. test_fn = extract_test_fn()
  255. if test_fn is None:
  256. return
  257. if not hasattr(test_fn, "tracked_input"):
  258. return None
  259. test_fn.tracked_input = None
  260. # Wraps an iterator and tracks the most recent value the iterator produces
  261. # for debugging purposes. Tracked values are stored on the test function.
  262. class TrackedInputIter:
  263. def __init__(self, child_iter, input_type_desc, callback=lambda x: x):
  264. self.child_iter = enumerate(child_iter)
  265. # Input type describes the things we're tracking (e.g. "sample input", "error input").
  266. self.input_type_desc = input_type_desc
  267. # Callback is run on each iterated thing to get the thing to track.
  268. self.callback = callback
  269. self.test_fn = extract_test_fn()
  270. def __iter__(self):
  271. return self
  272. def __next__(self):
  273. # allow StopIteration to bubble up
  274. input_idx, input_val = next(self.child_iter)
  275. self._set_tracked_input(
  276. TrackedInput(
  277. index=input_idx, val=self.callback(input_val), type_desc=self.input_type_desc
  278. )
  279. )
  280. return input_val
  281. def _set_tracked_input(self, tracked_input: TrackedInput):
  282. if self.test_fn is None:
  283. return
  284. if not hasattr(self.test_fn, "tracked_input"):
  285. return
  286. self.test_fn.tracked_input = tracked_input
  287. class _TestParametrizer:
  288. """
  289. Decorator class for parametrizing a test function, yielding a set of new tests spawned
  290. from the original generic test, each specialized for a specific set of test inputs. For
  291. example, parametrizing a test across the set of ops will result in a test function per op.
  292. The decision of how to parametrize / what to parametrize over is intended to be implemented
  293. by each derived class.
  294. In the details, the decorator adds a 'parametrize_fn' property to the test function. This function
  295. is intended to be called later by one of:
  296. * Device-specific test instantiation via instantiate_device_type_tests(). Note that for this
  297. case there is no need to explicitly parametrize over device type, as that is handled separately.
  298. * Device-agnostic parametrized test instantiation via instantiate_parametrized_tests().
  299. If the decorator is applied to a test function that already has a 'parametrize_fn' property, a new
  300. composite 'parametrize_fn' will be created that generates tests with the product of the parameters
  301. generated by the old and new parametrize_fns. This allows for convenient composability of decorators.
  302. """
  303. def _parametrize_test(self, test, generic_cls, device_cls):
  304. """
  305. Parametrizes the given test function across whatever dimension is specified by the derived class.
  306. Tests can be parametrized over any arbitrary dimension or combination of dimensions, such as all
  307. ops, all modules, or all ops + their associated dtypes.
  308. Args:
  309. test (fn): Test function to parametrize over
  310. generic_cls (class): Generic test class object containing tests (e.g. TestFoo)
  311. device_cls (class): Device-specialized test class object (e.g. TestFooCPU); set to None
  312. if the tests are not part of a device-specific set
  313. Returns:
  314. Generator object returning 4-tuples of:
  315. test (fn): Parametrized test function; must support a device arg and args for any params
  316. test_name (str): Parametrized suffix for the test (e.g. opname_int64); will be appended to
  317. the base name of the test
  318. param_kwargs (dict): Param kwargs to pass to the test (e.g. {'op': 'add', 'dtype': torch.int64})
  319. decorator_fn (callable): Callable[[Dict], List] for list of decorators to apply given param_kwargs
  320. """
  321. raise NotImplementedError
  322. def __call__(self, fn):
  323. if hasattr(fn, 'parametrize_fn'):
  324. # Do composition with the product of args.
  325. old_parametrize_fn = fn.parametrize_fn
  326. new_parametrize_fn = self._parametrize_test
  327. fn.parametrize_fn = compose_parametrize_fns(old_parametrize_fn, new_parametrize_fn)
  328. else:
  329. fn.parametrize_fn = self._parametrize_test
  330. return fn
  331. def compose_parametrize_fns(old_parametrize_fn, new_parametrize_fn):
  332. """
  333. Returns a parametrize_fn that parametrizes over the product of the parameters handled
  334. by the given parametrize_fns. Each given parametrize_fn should each have the signature
  335. f(test, generic_cls, device_cls).
  336. The test names will be a combination of the names produced by the parametrize_fns in
  337. "<new_name>_<old_name>" order. This order is done to match intuition for constructed names
  338. when composing multiple decorators; the names will be built in top to bottom order when stacking
  339. parametrization decorators.
  340. Args:
  341. old_parametrize_fn (callable) - First parametrize_fn to compose.
  342. new_parametrize_fn (callable) - Second parametrize_fn to compose.
  343. """
  344. def composite_fn(test, generic_cls, device_cls,
  345. old_parametrize_fn=old_parametrize_fn,
  346. new_parametrize_fn=new_parametrize_fn):
  347. old_tests = list(old_parametrize_fn(test, generic_cls, device_cls))
  348. for (old_test, old_test_name, old_param_kwargs, old_dec_fn) in old_tests:
  349. for (new_test, new_test_name, new_param_kwargs, new_dec_fn) in \
  350. new_parametrize_fn(old_test, generic_cls, device_cls):
  351. redundant_params = set(old_param_kwargs.keys()).intersection(new_param_kwargs.keys())
  352. if redundant_params:
  353. raise RuntimeError('Parametrization over the same parameter by multiple parametrization '
  354. f'decorators is not supported. For test "{test.__name__}", the following parameters '
  355. f'are handled multiple times: {redundant_params}')
  356. full_param_kwargs = {**old_param_kwargs, **new_param_kwargs}
  357. merged_test_name = '{}{}{}'.format(new_test_name,
  358. '_' if old_test_name != '' and new_test_name != '' else '',
  359. old_test_name)
  360. def merged_decorator_fn(param_kwargs, old_dec_fn=old_dec_fn, new_dec_fn=new_dec_fn):
  361. return list(old_dec_fn(param_kwargs)) + list(new_dec_fn(param_kwargs))
  362. yield (new_test, merged_test_name, full_param_kwargs, merged_decorator_fn)
  363. return composite_fn
  364. def instantiate_parametrized_tests(generic_cls):
  365. """
  366. Instantiates tests that have been decorated with a parametrize_fn. This is generally performed by a
  367. decorator subclass of _TestParametrizer. The generic test will be replaced on the test class by
  368. parametrized tests with specialized names. This should be used instead of
  369. instantiate_device_type_tests() if the test class contains device-agnostic tests.
  370. You can also use it as a class decorator. E.g.
  371. ```
  372. @instantiate_parametrized_tests
  373. class TestFoo(TestCase):
  374. ...
  375. ```
  376. Args:
  377. generic_cls (class): Generic test class object containing tests (e.g. TestFoo)
  378. """
  379. for attr_name in tuple(dir(generic_cls)):
  380. class_attr = getattr(generic_cls, attr_name)
  381. if not hasattr(class_attr, 'parametrize_fn'):
  382. continue
  383. # Remove the generic test from the test class.
  384. delattr(generic_cls, attr_name)
  385. # Add parametrized tests to the test class.
  386. def instantiate_test_helper(cls, name, test, param_kwargs):
  387. @wraps(test)
  388. def instantiated_test(self, param_kwargs=param_kwargs):
  389. test(self, **param_kwargs)
  390. assert not hasattr(generic_cls, name), f"Redefinition of test {name}"
  391. setattr(generic_cls, name, instantiated_test)
  392. for (test, test_suffix, param_kwargs, decorator_fn) in class_attr.parametrize_fn(
  393. class_attr, generic_cls=generic_cls, device_cls=None):
  394. full_name = f'{test.__name__}_{test_suffix}'
  395. # Apply decorators based on full param kwargs.
  396. for decorator in decorator_fn(param_kwargs):
  397. test = decorator(test)
  398. instantiate_test_helper(cls=generic_cls, name=full_name, test=test, param_kwargs=param_kwargs)
  399. return generic_cls
  400. class subtest:
  401. """
  402. Explicit subtest case for use with test parametrization.
  403. Allows for explicit naming of individual subtest cases as well as applying
  404. decorators to the parametrized test.
  405. Args:
  406. arg_values (iterable): Iterable of arg values (e.g. range(10)) or
  407. tuples of arg values (e.g. [(1, 2), (3, 4)]).
  408. name (str): Optional name to use for the test.
  409. decorators (iterable): Iterable of decorators to apply to the generated test.
  410. """
  411. __slots__ = ['arg_values', 'name', 'decorators']
  412. def __init__(self, arg_values, name=None, decorators=None):
  413. self.arg_values = arg_values
  414. self.name = name
  415. self.decorators = decorators if decorators else []
  416. class parametrize(_TestParametrizer):
  417. """
  418. Decorator for applying generic test parametrizations.
  419. The interface for this decorator is modeled after `@pytest.mark.parametrize`.
  420. Basic usage between this decorator and pytest's is identical. The first argument
  421. should be a string containing comma-separated names of parameters for the test, and
  422. the second argument should be an iterable returning values or tuples of values for
  423. the case of multiple parameters.
  424. Beyond this basic usage, the decorator provides some additional functionality that
  425. pytest does not.
  426. 1. Parametrized tests end up as generated test functions on unittest test classes.
  427. Since this differs from how pytest works, this decorator takes on the additional
  428. responsibility of naming these test functions. The default test names consists of
  429. the test's base name followed by each parameter name + value (e.g. "test_bar_x_1_y_foo"),
  430. but custom names can be defined using `name_fn` or the `subtest` structure (see below).
  431. 2. The decorator specially handles parameter values of type `subtest`, which allows for
  432. more fine-grained control over both test naming and test execution. In particular, it can
  433. be used to tag subtests with explicit test names or apply arbitrary decorators (see examples
  434. below).
  435. Examples::
  436. @parametrize("x", range(5))
  437. def test_foo(self, x):
  438. ...
  439. @parametrize("x,y", [(1, 'foo'), (2, 'bar'), (3, 'baz')])
  440. def test_bar(self, x, y):
  441. ...
  442. @parametrize("x,y", [(1, 'foo'), (2, 'bar'), (3, 'baz')],
  443. name_fn=lambda x, y: '{}_{}'.format(x, y))
  444. def test_bar_custom_names(self, x, y):
  445. ...
  446. @parametrize("x, y", [subtest((1, 2), name='double'),
  447. subtest((1, 3), name='triple', decorators=[unittest.expectedFailure]),
  448. subtest((1, 4), name='quadruple')])
  449. def test_baz(self, x, y):
  450. ...
  451. To actually instantiate the parametrized tests, one of instantiate_parametrized_tests() or
  452. instantiate_device_type_tests() should be called. The former is intended for test classes
  453. that contain device-agnostic tests, while the latter should be used for test classes that
  454. contain device-specific tests. Both support arbitrary parametrizations using the decorator.
  455. Args:
  456. arg_str (str): String of arg names separate by commas (e.g. "x,y").
  457. arg_values (iterable): Iterable of arg values (e.g. range(10)) or
  458. tuples of arg values (e.g. [(1, 2), (3, 4)]).
  459. name_fn (Callable): Optional function that takes in parameters and returns subtest name.
  460. """
  461. def __init__(self, arg_str, arg_values, name_fn=None):
  462. self.arg_names: List[str] = [s.strip() for s in arg_str.split(',') if s != '']
  463. self.arg_values = arg_values
  464. self.name_fn = name_fn
  465. def _formatted_str_repr(self, idx, name, value):
  466. """ Returns a string representation for the given arg that is suitable for use in test function names. """
  467. if isinstance(value, torch.dtype):
  468. return dtype_name(value)
  469. elif isinstance(value, torch.device):
  470. return str(value)
  471. # Can't use isinstance as it would cause a circular import
  472. elif type(value).__name__ in {'OpInfo', 'ModuleInfo'}:
  473. return value.formatted_name
  474. elif isinstance(value, (int, float, str)):
  475. return f"{name}_{str(value).replace('.', '_')}"
  476. else:
  477. return f"{name}{idx}"
  478. def _default_subtest_name(self, idx, values):
  479. return '_'.join([self._formatted_str_repr(idx, a, v) for a, v in zip(self.arg_names, values)])
  480. def _get_subtest_name(self, idx, values, explicit_name=None):
  481. if explicit_name:
  482. subtest_name = explicit_name
  483. elif self.name_fn:
  484. subtest_name = self.name_fn(*values)
  485. else:
  486. subtest_name = self._default_subtest_name(idx, values)
  487. return subtest_name
  488. def _parametrize_test(self, test, generic_cls, device_cls):
  489. if len(self.arg_names) == 0:
  490. # No additional parameters needed for the test.
  491. test_name = ''
  492. yield (test, test_name, {}, lambda _: [])
  493. else:
  494. # Each "values" item is expected to be either:
  495. # * A tuple of values with one for each arg. For a single arg, a single item is expected.
  496. # * A subtest instance with arg_values matching the previous.
  497. values = check_exhausted_iterator = object()
  498. for idx, values in enumerate(self.arg_values):
  499. maybe_name = None
  500. decorators = []
  501. if isinstance(values, subtest):
  502. sub = values
  503. values = sub.arg_values
  504. maybe_name = sub.name
  505. @wraps(test)
  506. def test_wrapper(*args, **kwargs):
  507. return test(*args, **kwargs)
  508. decorators = sub.decorators
  509. gen_test = test_wrapper
  510. else:
  511. gen_test = test
  512. values = list(values) if len(self.arg_names) > 1 else [values]
  513. if len(values) != len(self.arg_names):
  514. raise RuntimeError(f'Expected # values == # arg names, but got: {len(values)} '
  515. f'values and {len(self.arg_names)} names for test "{test.__name__}"')
  516. param_kwargs = dict(zip(self.arg_names, values))
  517. test_name = self._get_subtest_name(idx, values, explicit_name=maybe_name)
  518. def decorator_fn(_, decorators=decorators):
  519. return decorators
  520. yield (gen_test, test_name, param_kwargs, decorator_fn)
  521. if values is check_exhausted_iterator:
  522. raise ValueError(f'{test}: An empty arg_values was passed to @parametrize. '
  523. 'Note that this may result from reuse of a generator.')
  524. class decorateIf(_TestParametrizer):
  525. """
  526. Decorator for applying parameter-specific conditional decoration.
  527. Composes with other test parametrizers (e.g. @modules, @ops, @parametrize, etc.).
  528. Examples::
  529. @decorateIf(unittest.skip, lambda params: params["x"] == 2)
  530. @parametrize("x", range(5))
  531. def test_foo(self, x):
  532. ...
  533. @parametrize("x,y", [(1, 'foo'), (2, 'bar'), (3, 'baz')])
  534. @decorateIf(
  535. unittest.expectedFailure,
  536. lambda params: params["x"] == 3 and params["y"] == "baz"
  537. )
  538. def test_bar(self, x, y):
  539. ...
  540. @decorateIf(
  541. unittest.expectedFailure,
  542. lambda params: params["op"].name == "add" and params["dtype"] == torch.float16
  543. )
  544. @ops(op_db)
  545. def test_op_foo(self, device, dtype, op):
  546. ...
  547. @decorateIf(
  548. unittest.skip,
  549. lambda params: params["module_info"].module_cls is torch.nn.Linear and \
  550. params["device"] == "cpu"
  551. )
  552. @modules(module_db)
  553. def test_module_foo(self, device, dtype, module_info):
  554. ...
  555. Args:
  556. decorator: Test decorator to apply if the predicate is satisfied.
  557. predicate_fn (Callable): Function taking in a dict of params and returning a boolean
  558. indicating whether the decorator should be applied or not.
  559. """
  560. def __init__(self, decorator, predicate_fn):
  561. self.decorator = decorator
  562. self.predicate_fn = predicate_fn
  563. def _parametrize_test(self, test, generic_cls, device_cls):
  564. # Leave test as-is and return the appropriate decorator_fn.
  565. def decorator_fn(params, decorator=self.decorator, predicate_fn=self.predicate_fn):
  566. if predicate_fn(params):
  567. return [decorator]
  568. else:
  569. return []
  570. @wraps(test)
  571. def test_wrapper(*args, **kwargs):
  572. return test(*args, **kwargs)
  573. test_name = ''
  574. yield (test_wrapper, test_name, {}, decorator_fn)
  575. class ProfilingMode(Enum):
  576. LEGACY = 1
  577. SIMPLE = 2
  578. PROFILING = 3
  579. def cppProfilingFlagsToProfilingMode():
  580. old_prof_exec_state = torch._C._jit_set_profiling_executor(True)
  581. old_prof_mode_state = torch._C._get_graph_executor_optimize(True)
  582. torch._C._jit_set_profiling_executor(old_prof_exec_state)
  583. torch._C._get_graph_executor_optimize(old_prof_mode_state)
  584. if old_prof_exec_state:
  585. if old_prof_mode_state:
  586. return ProfilingMode.PROFILING
  587. else:
  588. return ProfilingMode.SIMPLE
  589. else:
  590. return ProfilingMode.LEGACY
  591. @contextmanager
  592. def enable_profiling_mode_for_profiling_tests():
  593. if GRAPH_EXECUTOR == ProfilingMode.PROFILING:
  594. old_prof_exec_state = torch._C._jit_set_profiling_executor(True)
  595. old_prof_mode_state = torch._C._get_graph_executor_optimize(True)
  596. try:
  597. yield
  598. finally:
  599. if GRAPH_EXECUTOR == ProfilingMode.PROFILING:
  600. torch._C._jit_set_profiling_executor(old_prof_exec_state)
  601. torch._C._get_graph_executor_optimize(old_prof_mode_state)
  602. @contextmanager
  603. def enable_profiling_mode():
  604. old_prof_exec_state = torch._C._jit_set_profiling_executor(True)
  605. old_prof_mode_state = torch._C._get_graph_executor_optimize(True)
  606. try:
  607. yield
  608. finally:
  609. torch._C._jit_set_profiling_executor(old_prof_exec_state)
  610. torch._C._get_graph_executor_optimize(old_prof_mode_state)
  611. @contextmanager
  612. def num_profiled_runs(num_runs):
  613. old_num_runs = torch._C._jit_set_num_profiled_runs(num_runs)
  614. try:
  615. yield
  616. finally:
  617. torch._C._jit_set_num_profiled_runs(old_num_runs)
  618. func_call = torch._C.ScriptFunction.__call__
  619. meth_call = torch._C.ScriptMethod.__call__
  620. def prof_callable(callable, *args, **kwargs):
  621. if 'profile_and_replay' in kwargs:
  622. del kwargs['profile_and_replay']
  623. if GRAPH_EXECUTOR == ProfilingMode.PROFILING:
  624. with enable_profiling_mode_for_profiling_tests():
  625. callable(*args, **kwargs)
  626. return callable(*args, **kwargs)
  627. return callable(*args, **kwargs)
  628. def prof_func_call(*args, **kwargs):
  629. return prof_callable(func_call, *args, **kwargs)
  630. def prof_meth_call(*args, **kwargs):
  631. return prof_callable(meth_call, *args, **kwargs)
  632. torch._C.ScriptFunction.__call__ = prof_func_call # type: ignore[method-assign]
  633. torch._C.ScriptMethod.__call__ = prof_meth_call # type: ignore[method-assign]
  634. def _get_test_report_path():
  635. # allow users to override the test file location. We need this
  636. # because the distributed tests run the same test file multiple
  637. # times with different configurations.
  638. override = os.environ.get('TEST_REPORT_SOURCE_OVERRIDE')
  639. test_source = override if override is not None else 'python-unittest'
  640. return os.path.join('test-reports', test_source)
  641. is_running_via_run_test = "run_test.py" in getattr(__main__, "__file__", "")
  642. parser = argparse.ArgumentParser(add_help=not is_running_via_run_test, allow_abbrev=False)
  643. parser.add_argument('--subprocess', action='store_true',
  644. help='whether to run each test in a subprocess')
  645. parser.add_argument('--seed', type=int, default=1234)
  646. parser.add_argument('--accept', action='store_true')
  647. parser.add_argument('--jit-executor', '--jit_executor', type=str)
  648. parser.add_argument('--repeat', type=int, default=1)
  649. parser.add_argument('--test-bailouts', '--test_bailouts', action='store_true')
  650. parser.add_argument('--use-pytest', action='store_true')
  651. parser.add_argument('--save-xml', nargs='?', type=str,
  652. const=_get_test_report_path(),
  653. default=_get_test_report_path() if IS_CI else None) # noqa: F821
  654. parser.add_argument('--discover-tests', action='store_true')
  655. parser.add_argument('--log-suffix', type=str, default="")
  656. parser.add_argument('--run-parallel', type=int, default=1)
  657. parser.add_argument('--import-slow-tests', type=str, nargs='?', const=DEFAULT_SLOW_TESTS_FILE)
  658. parser.add_argument('--import-disabled-tests', type=str, nargs='?', const=DEFAULT_DISABLED_TESTS_FILE)
  659. parser.add_argument('--rerun-disabled-tests', action='store_true')
  660. parser.add_argument('--pytest-single-test', type=str, nargs=1)
  661. # Only run when -h or --help flag is active to display both unittest and parser help messages.
  662. def run_unittest_help(argv):
  663. unittest.main(argv=argv)
  664. if '-h' in sys.argv or '--help' in sys.argv:
  665. help_thread = threading.Thread(target=run_unittest_help, args=(sys.argv,))
  666. help_thread.start()
  667. help_thread.join()
  668. args, remaining = parser.parse_known_args()
  669. if args.jit_executor == 'legacy':
  670. GRAPH_EXECUTOR = ProfilingMode.LEGACY
  671. elif args.jit_executor == 'profiling':
  672. GRAPH_EXECUTOR = ProfilingMode.PROFILING
  673. elif args.jit_executor == 'simple':
  674. GRAPH_EXECUTOR = ProfilingMode.SIMPLE
  675. else:
  676. # infer flags based on the default settings
  677. GRAPH_EXECUTOR = cppProfilingFlagsToProfilingMode()
  678. RERUN_DISABLED_TESTS = args.rerun_disabled_tests
  679. SLOW_TESTS_FILE = args.import_slow_tests
  680. DISABLED_TESTS_FILE = args.import_disabled_tests
  681. LOG_SUFFIX = args.log_suffix
  682. RUN_PARALLEL = args.run_parallel
  683. TEST_BAILOUTS = args.test_bailouts
  684. USE_PYTEST = args.use_pytest
  685. PYTEST_SINGLE_TEST = args.pytest_single_test
  686. TEST_DISCOVER = args.discover_tests
  687. TEST_IN_SUBPROCESS = args.subprocess
  688. TEST_SAVE_XML = args.save_xml
  689. REPEAT_COUNT = args.repeat
  690. SEED = args.seed
  691. if not getattr(expecttest, "ACCEPT", False):
  692. expecttest.ACCEPT = args.accept
  693. UNITTEST_ARGS = [sys.argv[0]] + remaining
  694. torch.manual_seed(SEED)
  695. # CI Prefix path used only on CI environment
  696. CI_TEST_PREFIX = str(Path(os.getcwd()))
  697. CI_PT_ROOT = str(Path(os.getcwd()).parent)
  698. CI_FUNCTORCH_ROOT = str(os.path.join(Path(os.getcwd()).parent, "functorch"))
  699. def wait_for_process(p, timeout=None):
  700. try:
  701. return p.wait(timeout=timeout)
  702. except KeyboardInterrupt:
  703. # Give `p` a chance to handle KeyboardInterrupt. Without this,
  704. # `pytest` can't print errors it collected so far upon KeyboardInterrupt.
  705. exit_status = p.wait(timeout=5)
  706. if exit_status is not None:
  707. return exit_status
  708. else:
  709. p.kill()
  710. raise
  711. except subprocess.TimeoutExpired:
  712. # send SIGINT to give pytest a chance to make xml
  713. p.send_signal(signal.SIGINT)
  714. exit_status = None
  715. try:
  716. exit_status = p.wait(timeout=5)
  717. # try to handle the case where p.wait(timeout=5) times out as well as
  718. # otherwise the wait() call in the finally block can potentially hang
  719. except subprocess.TimeoutExpired:
  720. pass
  721. if exit_status is not None:
  722. return exit_status
  723. else:
  724. p.kill()
  725. raise
  726. except: # noqa: B001,E722, copied from python core library
  727. p.kill()
  728. raise
  729. finally:
  730. # Always call p.wait() to ensure exit
  731. p.wait()
  732. def shell(command, cwd=None, env=None, stdout=None, stderr=None, timeout=None):
  733. sys.stdout.flush()
  734. sys.stderr.flush()
  735. # The following cool snippet is copied from Py3 core library subprocess.call
  736. # only the with
  737. # 1. `except KeyboardInterrupt` block added for SIGINT handling.
  738. # 2. In Py2, subprocess.Popen doesn't return a context manager, so we do
  739. # `p.wait()` in a `final` block for the code to be portable.
  740. #
  741. # https://github.com/python/cpython/blob/71b6c1af727fbe13525fb734568057d78cea33f3/Lib/subprocess.py#L309-L323
  742. assert not isinstance(command, str), "Command to shell should be a list or tuple of tokens"
  743. p = subprocess.Popen(command, universal_newlines=True, cwd=cwd, env=env, stdout=stdout, stderr=stderr)
  744. return wait_for_process(p, timeout=timeout)
  745. def retry_shell(
  746. command,
  747. cwd=None,
  748. env=None,
  749. stdout=None,
  750. stderr=None,
  751. timeout=None,
  752. retries=1,
  753. was_rerun=False,
  754. ) -> Tuple[int, bool]:
  755. # Returns exicode + whether it was rerun
  756. assert (
  757. retries >= 0
  758. ), f"Expecting non negative number for number of retries, got {retries}"
  759. try:
  760. exit_code = shell(
  761. command, cwd=cwd, env=env, stdout=stdout, stderr=stderr, timeout=timeout
  762. )
  763. if exit_code == 0 or retries == 0:
  764. return exit_code, was_rerun
  765. print(
  766. f"Got exit code {exit_code}, retrying (retries left={retries})",
  767. file=stdout,
  768. flush=True,
  769. )
  770. except subprocess.TimeoutExpired:
  771. if retries == 0:
  772. print(
  773. f"Command took >{timeout // 60}min, returning 124",
  774. file=stdout,
  775. flush=True,
  776. )
  777. return 124, was_rerun
  778. print(
  779. f"Command took >{timeout // 60}min, retrying (retries left={retries})",
  780. file=stdout,
  781. flush=True,
  782. )
  783. return retry_shell(
  784. command,
  785. cwd=cwd,
  786. env=env,
  787. stdout=stdout,
  788. stderr=stderr,
  789. timeout=timeout,
  790. retries=retries - 1,
  791. was_rerun=True,
  792. )
  793. def discover_test_cases_recursively(suite_or_case):
  794. if isinstance(suite_or_case, unittest.TestCase):
  795. return [suite_or_case]
  796. rc = []
  797. for element in suite_or_case:
  798. print(element)
  799. rc.extend(discover_test_cases_recursively(element))
  800. return rc
  801. def get_test_names(test_cases):
  802. return ['.'.join(case.id().split('.')[-2:]) for case in test_cases]
  803. def _print_test_names():
  804. suite = unittest.TestLoader().loadTestsFromModule(__main__)
  805. test_cases = discover_test_cases_recursively(suite)
  806. for name in get_test_names(test_cases):
  807. print(name)
  808. def chunk_list(lst, nchunks):
  809. return [lst[i::nchunks] for i in range(nchunks)]
  810. # sanitize filename e.g., distributed/pipeline/sync/skip/test_api.py -> distributed.pipeline.sync.skip.test_api
  811. def sanitize_test_filename(filename):
  812. # inspect.getfile returns absolute path in some CI jobs, converting it to relative path if needed
  813. if filename.startswith(CI_TEST_PREFIX):
  814. filename = filename[len(CI_TEST_PREFIX) + 1:]
  815. strip_py = re.sub(r'.py$', '', filename)
  816. return re.sub('/', r'.', strip_py)
  817. def lint_test_case_extension(suite):
  818. succeed = True
  819. for test_case_or_suite in suite:
  820. test_case = test_case_or_suite
  821. if isinstance(test_case_or_suite, unittest.TestSuite):
  822. first_test = test_case_or_suite._tests[0] if len(test_case_or_suite._tests) > 0 else None
  823. if first_test is not None and isinstance(first_test, unittest.TestSuite):
  824. return succeed and lint_test_case_extension(test_case_or_suite)
  825. test_case = first_test
  826. if test_case is not None:
  827. test_class = test_case.id().split('.', 1)[1].split('.')[0]
  828. if not isinstance(test_case, TestCase):
  829. err = "This test class should extend from torch.testing._internal.common_utils.TestCase but it doesn't."
  830. print(f"{test_class} - failed. {err}")
  831. succeed = False
  832. return succeed
  833. def get_report_path(argv=UNITTEST_ARGS, pytest=False):
  834. test_filename = sanitize_test_filename(argv[0])
  835. test_report_path = TEST_SAVE_XML + LOG_SUFFIX
  836. test_report_path = os.path.join(test_report_path, test_filename)
  837. if pytest:
  838. test_report_path = test_report_path.replace('python-unittest', 'python-pytest')
  839. os.makedirs(test_report_path, exist_ok=True)
  840. test_report_path = os.path.join(test_report_path, f"{test_filename}-{os.urandom(8).hex()}.xml")
  841. return test_report_path
  842. os.makedirs(test_report_path, exist_ok=True)
  843. return test_report_path
  844. def sanitize_pytest_xml(xml_file: str):
  845. # pytext xml is different from unittext xml, this function makes pytest xml more similar to unittest xml
  846. # consider somehow modifying the XML logger in conftest to do this instead
  847. import xml.etree.ElementTree as ET
  848. tree = ET.parse(xml_file)
  849. for testcase in tree.iter('testcase'):
  850. full_classname = testcase.attrib.get("classname")
  851. if full_classname is None:
  852. continue
  853. # The test prefix is optional
  854. regex_result = re.search(r"^(test\.)?(?P<file>.*)\.(?P<classname>[^\.]*)$", full_classname)
  855. if regex_result is None:
  856. continue
  857. classname = regex_result.group("classname")
  858. file = regex_result.group("file").replace(".", "/")
  859. testcase.set("classname", classname)
  860. testcase.set("file", f"{file}.py")
  861. tree.write(xml_file)
  862. def get_pytest_test_cases(argv: List[str]) -> List[str]:
  863. class TestCollectorPlugin:
  864. def __init__(self):
  865. self.tests = []
  866. def pytest_collection_finish(self, session):
  867. for item in session.items:
  868. self.tests.append(session.config.cwd_relative_nodeid(item.nodeid))
  869. test_collector_plugin = TestCollectorPlugin()
  870. import pytest
  871. pytest.main(
  872. [arg for arg in argv if arg != '-vv'] + ['--collect-only', '-qq', '--use-main-module'],
  873. plugins=[test_collector_plugin]
  874. )
  875. return test_collector_plugin.tests
  876. def run_tests(argv=UNITTEST_ARGS):
  877. # import test files.
  878. if SLOW_TESTS_FILE:
  879. if os.path.exists(SLOW_TESTS_FILE):
  880. with open(SLOW_TESTS_FILE) as fp:
  881. global slow_tests_dict
  882. slow_tests_dict = json.load(fp)
  883. # use env vars so pytest-xdist subprocesses can still access them
  884. os.environ['SLOW_TESTS_FILE'] = SLOW_TESTS_FILE
  885. else:
  886. warnings.warn(f'slow test file provided but not found: {SLOW_TESTS_FILE}')
  887. if DISABLED_TESTS_FILE:
  888. if os.path.exists(DISABLED_TESTS_FILE):
  889. with open(DISABLED_TESTS_FILE) as fp:
  890. global disabled_tests_dict
  891. disabled_tests_dict = json.load(fp)
  892. os.environ['DISABLED_TESTS_FILE'] = DISABLED_TESTS_FILE
  893. else:
  894. warnings.warn(f'disabled test file provided but not found: {DISABLED_TESTS_FILE}')
  895. # Determine the test launch mechanism
  896. if TEST_DISCOVER:
  897. _print_test_names()
  898. return
  899. # Before running the tests, lint to check that every test class extends from TestCase
  900. suite = unittest.TestLoader().loadTestsFromModule(__main__)
  901. if not lint_test_case_extension(suite):
  902. sys.exit(1)
  903. if TEST_IN_SUBPROCESS:
  904. other_args = []
  905. if DISABLED_TESTS_FILE:
  906. other_args.append("--import-disabled-tests")
  907. if SLOW_TESTS_FILE:
  908. other_args.append("--import-slow-tests")
  909. if USE_PYTEST:
  910. other_args.append("--use-pytest")
  911. if RERUN_DISABLED_TESTS:
  912. other_args.append("--rerun-disabled-tests")
  913. if TEST_SAVE_XML:
  914. other_args += ['--save-xml', args.save_xml]
  915. test_cases = (
  916. get_pytest_test_cases(argv) if USE_PYTEST else
  917. [case.id().split('.', 1)[1] for case in discover_test_cases_recursively(suite)]
  918. )
  919. failed_tests = []
  920. for test_case_full_name in test_cases:
  921. cmd = (
  922. [sys.executable] + [argv[0]] + other_args + argv[1:] +
  923. (["--pytest-single-test"] if USE_PYTEST else []) +
  924. [test_case_full_name]
  925. )
  926. string_cmd = " ".join(cmd)
  927. timeout = None if RERUN_DISABLED_TESTS else 15 * 60
  928. exitcode, _ = retry_shell(cmd, timeout=timeout, retries=0 if RERUN_DISABLED_TESTS else 1)
  929. if exitcode != 0:
  930. # This is sort of hacky, but add on relevant env variables for distributed tests.
  931. if 'TestDistBackendWithSpawn' in test_case_full_name:
  932. backend = os.environ.get("BACKEND", "")
  933. world_size = os.environ.get("WORLD_SIZE", "")
  934. env_prefix = f"BACKEND={backend} WORLD_SIZE={world_size}"
  935. string_cmd = env_prefix + " " + string_cmd
  936. # Log the command to reproduce the failure.
  937. print(f"Test exited with non-zero exitcode {exitcode}. Command to reproduce: {string_cmd}")
  938. failed_tests.append(test_case_full_name)
  939. assert len(failed_tests) == 0, "{} unit test(s) failed:\n\t{}".format(
  940. len(failed_tests), '\n\t'.join(failed_tests))
  941. elif RUN_PARALLEL > 1:
  942. test_cases = discover_test_cases_recursively(suite)
  943. test_batches = chunk_list(get_test_names(test_cases), RUN_PARALLEL)
  944. processes = []
  945. for i in range(RUN_PARALLEL):
  946. command = [sys.executable] + argv + [f'--log-suffix=-shard-{i + 1}'] + test_batches[i]
  947. processes.append(subprocess.Popen(command, universal_newlines=True))
  948. failed = False
  949. for p in processes:
  950. failed |= wait_for_process(p) != 0
  951. assert not failed, "Some test shards have failed"
  952. elif USE_PYTEST:
  953. pytest_args = argv + ["--use-main-module"]
  954. if TEST_SAVE_XML:
  955. test_report_path = get_report_path(pytest=True)
  956. print(f'Test results will be stored in {test_report_path}')
  957. pytest_args.append(f'--junit-xml-reruns={test_report_path}')
  958. if PYTEST_SINGLE_TEST:
  959. pytest_args = PYTEST_SINGLE_TEST + pytest_args[1:]
  960. import pytest
  961. os.environ["NO_COLOR"] = "1"
  962. exit_code = pytest.main(args=pytest_args)
  963. if TEST_SAVE_XML:
  964. sanitize_pytest_xml(test_report_path)
  965. if not RERUN_DISABLED_TESTS:
  966. # exitcode of 5 means no tests were found, which happens since some test configs don't
  967. # run tests from certain files
  968. sys.exit(0 if exit_code == 5 else exit_code)
  969. else:
  970. # Only record the test report and always return a success code when running under rerun
  971. # disabled tests mode
  972. sys.exit(0)
  973. elif TEST_SAVE_XML is not None:
  974. # import here so that non-CI doesn't need xmlrunner installed
  975. import xmlrunner # type: ignore[import]
  976. from xmlrunner.result import _XMLTestResult # type: ignore[import]
  977. class XMLTestResultVerbose(_XMLTestResult):
  978. """
  979. Adding verbosity to test outputs:
  980. by default test summary prints 'skip',
  981. but we want to also print the skip reason.
  982. GH issue: https://github.com/pytorch/pytorch/issues/69014
  983. This works with unittest_xml_reporting<=3.2.0,>=2.0.0
  984. (3.2.0 is latest at the moment)
  985. """
  986. def __init__(self, *args, **kwargs):
  987. super().__init__(*args, **kwargs)
  988. def addSkip(self, test, reason):
  989. super().addSkip(test, reason)
  990. for c in self.callback.__closure__:
  991. if isinstance(c.cell_contents, str) and c.cell_contents == 'skip':
  992. # this message is printed in test summary;
  993. # it stands for `verbose_str` captured in the closure
  994. c.cell_contents = f"skip: {reason}"
  995. def printErrors(self) -> None:
  996. super().printErrors()
  997. self.printErrorList("XPASS", self.unexpectedSuccesses)
  998. test_report_path = get_report_path()
  999. verbose = '--verbose' in argv or '-v' in argv
  1000. if verbose:
  1001. print(f'Test results will be stored in {test_report_path}')
  1002. unittest.main(argv=argv, testRunner=xmlrunner.XMLTestRunner(
  1003. output=test_report_path,
  1004. verbosity=2 if verbose else 1,
  1005. resultclass=XMLTestResultVerbose))
  1006. elif REPEAT_COUNT > 1:
  1007. for _ in range(REPEAT_COUNT):
  1008. if not unittest.main(exit=False, argv=argv).result.wasSuccessful():
  1009. sys.exit(-1)
  1010. else:
  1011. unittest.main(argv=argv)
  1012. IS_LINUX = sys.platform == "linux"
  1013. IS_WINDOWS = sys.platform == "win32"
  1014. IS_MACOS = sys.platform == "darwin"
  1015. IS_PPC = platform.machine() == "ppc64le"
  1016. IS_X86 = platform.machine() in ('x86_64', 'i386')
  1017. IS_ARM64 = platform.machine() in ('arm64', 'aarch64')
  1018. def is_avx512_vnni_supported():
  1019. if sys.platform != 'linux':
  1020. return False
  1021. with open("/proc/cpuinfo", encoding="ascii") as f:
  1022. lines = f.read()
  1023. return "vnni" in lines
  1024. IS_AVX512_VNNI_SUPPORTED = is_avx512_vnni_supported()
  1025. if IS_WINDOWS:
  1026. @contextmanager
  1027. def TemporaryFileName(*args, **kwargs):
  1028. # Ideally we would like to not have to manually delete the file, but NamedTemporaryFile
  1029. # opens the file, and it cannot be opened multiple times in Windows. To support Windows,
  1030. # close the file after creation and try to remove it manually
  1031. if 'delete' in kwargs:
  1032. if kwargs['delete'] is not False:
  1033. raise UserWarning("only TemporaryFileName with delete=False is supported on Windows.")
  1034. else:
  1035. kwargs['delete'] = False
  1036. f = tempfile.NamedTemporaryFile(*args, **kwargs)
  1037. try:
  1038. f.close()
  1039. yield f.name
  1040. finally:
  1041. os.unlink(f.name)
  1042. else:
  1043. @contextmanager # noqa: T484
  1044. def TemporaryFileName(*args, **kwargs):
  1045. with tempfile.NamedTemporaryFile(*args, **kwargs) as f:
  1046. yield f.name
  1047. if IS_WINDOWS:
  1048. @contextmanager
  1049. def TemporaryDirectoryName(suffix=None):
  1050. # On Windows the directory created by TemporaryDirectory is likely to be removed prematurely,
  1051. # so we first create the directory using mkdtemp and then remove it manually
  1052. try:
  1053. dir_name = tempfile.mkdtemp(suffix=suffix)
  1054. yield dir_name
  1055. finally:
  1056. shutil.rmtree(dir_name)
  1057. else:
  1058. @contextmanager # noqa: T484
  1059. def TemporaryDirectoryName(suffix=None):
  1060. with tempfile.TemporaryDirectory(suffix=suffix) as d:
  1061. yield d
  1062. IS_FILESYSTEM_UTF8_ENCODING = sys.getfilesystemencoding() == 'utf-8'
  1063. TEST_NUMPY = _check_module_exists('numpy')
  1064. TEST_FAIRSEQ = _check_module_exists('fairseq')
  1065. TEST_SCIPY = _check_module_exists('scipy')
  1066. TEST_MKL = torch.backends.mkl.is_available()
  1067. TEST_MPS = torch.backends.mps.is_available()
  1068. TEST_XPU = torch.xpu.is_available()
  1069. TEST_CUDA = torch.cuda.is_available()
  1070. custom_device_mod = getattr(torch, torch._C._get_privateuse1_backend_name(), None)
  1071. custom_device_is_available = hasattr(custom_device_mod, "is_available") and custom_device_mod.is_available()
  1072. TEST_PRIVATEUSE1 = True if custom_device_is_available else False
  1073. TEST_PRIVATEUSE1_DEVICE_TYPE = torch._C._get_privateuse1_backend_name()
  1074. TEST_NUMBA = _check_module_exists('numba')
  1075. TEST_TRANSFORMERS = _check_module_exists('transformers')
  1076. TEST_DILL = _check_module_exists('dill')
  1077. TEST_LIBROSA = _check_module_exists('librosa') and not IS_ARM64
  1078. TEST_OPT_EINSUM = _check_module_exists('opt_einsum')
  1079. TEST_Z3 = _check_module_exists('z3')
  1080. BUILD_WITH_CAFFE2 = torch.onnx._CAFFE2_ATEN_FALLBACK
  1081. def split_if_not_empty(x: str):
  1082. return x.split(",") if len(x) != 0 else []
  1083. NOTEST_CPU = "cpu" in split_if_not_empty(os.getenv('PYTORCH_TESTING_DEVICE_EXCEPT_FOR', ''))
  1084. skipIfNoDill = unittest.skipIf(not TEST_DILL, "no dill")
  1085. # Python 2.7 doesn't have spawn
  1086. TestEnvironment.def_flag("NO_MULTIPROCESSING_SPAWN", env_var="NO_MULTIPROCESSING_SPAWN")
  1087. TestEnvironment.def_flag("TEST_WITH_ASAN", env_var="PYTORCH_TEST_WITH_ASAN")
  1088. TestEnvironment.def_flag("TEST_WITH_DEV_DBG_ASAN", env_var="PYTORCH_TEST_WITH_DEV_DBG_ASAN")
  1089. TestEnvironment.def_flag("TEST_WITH_TSAN", env_var="PYTORCH_TEST_WITH_TSAN")
  1090. TestEnvironment.def_flag("TEST_WITH_UBSAN", env_var="PYTORCH_TEST_WITH_UBSAN")
  1091. TestEnvironment.def_flag("TEST_WITH_ROCM", env_var="PYTORCH_TEST_WITH_ROCM")
  1092. # TODO: Remove PYTORCH_MIOPEN_SUGGEST_NHWC once ROCm officially supports NHWC in MIOpen
  1093. # See #64427
  1094. TEST_WITH_MIOPEN_SUGGEST_NHWC = os.getenv('PYTORCH_MIOPEN_SUGGEST_NHWC', '0') == '1'
  1095. # Enables tests that are slow to run (disabled by default)
  1096. TestEnvironment.def_flag("TEST_WITH_SLOW", env_var="PYTORCH_TEST_WITH_SLOW")
  1097. # Disables non-slow tests (these tests enabled by default)
  1098. # This is usually used in conjunction with TEST_WITH_SLOW to
  1099. # run *only* slow tests. (I could have done an enum, but
  1100. # it felt a little awkward.
  1101. TestEnvironment.def_flag("TEST_SKIP_FAST", env_var="PYTORCH_TEST_SKIP_FAST")
  1102. # Enables crossref tests, in addition to standard tests which
  1103. # are being run. crossref tests work by installing a torch
  1104. # function mode that runs extra compute alongside the regular
  1105. # computation that happens with the test. After both computations
  1106. # are done, we cross-reference them (thus the name) to check for
  1107. # correction, before throwing out the extra compute and proceeding
  1108. # as we had before. By default, we don't run these tests.
  1109. TestEnvironment.def_flag("TEST_WITH_CROSSREF", env_var="PYTORCH_TEST_WITH_CROSSREF")
  1110. TestEnvironment.def_flag("TEST_SKIP_CUDAGRAPH", env_var="PYTORCH_TEST_SKIP_CUDAGRAPH")
  1111. TEST_CUDA_GRAPH = TEST_CUDA and (not TEST_SKIP_CUDAGRAPH) and ( # noqa: F821
  1112. (torch.version.cuda and int(torch.version.cuda.split(".")[0]) >= 11) or
  1113. (torch.version.hip and float(".".join(torch.version.hip.split(".")[0:2])) >= 5.3)
  1114. )
  1115. if TEST_CUDA and 'NUM_PARALLEL_PROCS' in os.environ:
  1116. num_procs = int(os.getenv("NUM_PARALLEL_PROCS", "2"))
  1117. gb_available = torch.cuda.mem_get_info()[1] / 2 ** 30
  1118. # other libraries take up about a little under 1 GB of space per process
  1119. torch.cuda.set_per_process_memory_fraction(round((gb_available - num_procs * .85) / gb_available / num_procs, 2))
  1120. requires_cuda = unittest.skipUnless(torch.cuda.is_available(), "Requires CUDA")
  1121. def skipIfCrossRef(fn):
  1122. @wraps(fn)
  1123. def wrapper(*args, **kwargs):
  1124. if TEST_WITH_CROSSREF: # noqa: F821
  1125. raise unittest.SkipTest("test doesn't currently with crossref")
  1126. else:
  1127. fn(*args, **kwargs)
  1128. return wrapper
  1129. class CrossRefMode(torch.overrides.TorchFunctionMode):
  1130. def __torch_function__(self, func, types, args=(), kwargs=None):
  1131. kwargs = kwargs or {}
  1132. r = func(*args, **kwargs)
  1133. return r
  1134. # Run PyTorch tests with TorchDynamo
  1135. TestEnvironment.def_flag("TEST_WITH_TORCHINDUCTOR", env_var="PYTORCH_TEST_WITH_INDUCTOR")
  1136. # AOT_EAGER not tested in ci, useful for debugging
  1137. TestEnvironment.def_flag("TEST_WITH_AOT_EAGER", env_var="PYTORCH_TEST_WITH_AOT_EAGER")
  1138. TestEnvironment.def_flag("TEST_WITH_TORCHDYNAMO", env_var="PYTORCH_TEST_WITH_DYNAMO",
  1139. implied_by_fn=lambda: TEST_WITH_TORCHINDUCTOR or TEST_WITH_AOT_EAGER) # noqa: F821
  1140. if TEST_WITH_TORCHDYNAMO: # noqa: F821
  1141. import torch._dynamo
  1142. # Do not spend time on helper functions that are called with different inputs
  1143. torch._dynamo.config.accumulated_cache_size_limit = 8
  1144. # Do not log compilation metrics from unit tests
  1145. torch._dynamo.config.log_compilation_metrics = False
  1146. if TEST_WITH_TORCHINDUCTOR: # noqa: F821
  1147. import torch._inductor.config
  1148. torch._inductor.config.fallback_random = True
  1149. def xpassIfTorchDynamo(func):
  1150. return func if TEST_WITH_TORCHDYNAMO else unittest.expectedFailure(func) # noqa: F821
  1151. def xfailIfTorchDynamo(func):
  1152. return unittest.expectedFailure(func) if TEST_WITH_TORCHDYNAMO else func # noqa: F821
  1153. def skipIfTorchDynamo(msg="test doesn't currently work with dynamo"):
  1154. """
  1155. Usage:
  1156. @skipIfTorchDynamo(msg)
  1157. def test_blah(self):
  1158. ...
  1159. """
  1160. assert isinstance(msg, str), "Are you using skipIfTorchDynamo correctly?"
  1161. def decorator(fn):
  1162. if not isinstance(fn, type):
  1163. @wraps(fn)
  1164. def wrapper(*args, **kwargs):
  1165. if TEST_WITH_TORCHDYNAMO: # noqa: F821
  1166. raise unittest.SkipTest(msg)
  1167. else:
  1168. fn(*args, **kwargs)
  1169. return wrapper
  1170. assert isinstance(fn, type)
  1171. if TEST_WITH_TORCHDYNAMO: # noqa: F821
  1172. fn.__unittest_skip__ = True
  1173. fn.__unittest_skip_why__ = msg
  1174. return fn
  1175. return decorator
  1176. def skipIfTorchInductor(msg="test doesn't currently work with torchinductor",
  1177. condition=TEST_WITH_TORCHINDUCTOR): # noqa: F821
  1178. def decorator(fn):
  1179. if not isinstance(fn, type):
  1180. @wraps(fn)
  1181. def wrapper(*args, **kwargs):
  1182. if condition:
  1183. raise unittest.SkipTest(msg)
  1184. else:
  1185. fn(*args, **kwargs)
  1186. return wrapper
  1187. assert isinstance(fn, type)
  1188. if condition:
  1189. fn.__unittest_skip__ = True
  1190. fn.__unittest_skip_why__ = msg
  1191. return fn
  1192. return decorator
  1193. def serialTest(condition=True):
  1194. """
  1195. Decorator for running tests serially. Requires pytest
  1196. """
  1197. def decorator(fn):
  1198. if has_pytest and condition:
  1199. return pytest.mark.serial(fn)
  1200. return fn
  1201. return decorator
  1202. def unMarkDynamoStrictTest(cls=None):
  1203. def decorator(cls):
  1204. cls.dynamo_strict = False
  1205. return cls
  1206. if cls is None:
  1207. return decorator
  1208. else:
  1209. return decorator(cls)
  1210. def markDynamoStrictTest(cls_or_func=None, nopython=False):
  1211. """
  1212. Marks the test as 'strict'. In strict mode, we reset before and after the
  1213. test, and run without suppress errors.
  1214. Args:
  1215. - nopython: if we should run torch._dynamo.optimize with nopython={True/False}.
  1216. """
  1217. def decorator(cls_or_func):
  1218. if inspect.isclass(cls_or_func):
  1219. cls_or_func.dynamo_strict = True
  1220. cls_or_func.dynamo_strict_nopython = nopython
  1221. return cls_or_func
  1222. fn = cls_or_func
  1223. @wraps(fn)
  1224. def wrapper(*args, **kwargs):
  1225. torch._dynamo.reset()
  1226. with unittest.mock.patch("torch._dynamo.config.suppress_errors", False):
  1227. fn(*args, **kwargs)
  1228. torch._dynamo.reset()
  1229. return wrapper
  1230. if cls_or_func is None:
  1231. return decorator
  1232. else:
  1233. return decorator(cls_or_func)
  1234. def skipRocmIfTorchInductor(msg="test doesn't currently work with torchinductor on the ROCm stack"):
  1235. return skipIfTorchInductor(msg=msg, condition=TEST_WITH_ROCM and TEST_WITH_TORCHINDUCTOR) # noqa: F821
  1236. def skipIfLegacyJitExecutor(msg="test doesn't currently work with legacy JIT executor"):
  1237. def decorator(fn):
  1238. if not isinstance(fn, type):
  1239. @wraps(fn)
  1240. def wrapper(*args, **kwargs):
  1241. if GRAPH_EXECUTOR == ProfilingMode.LEGACY:
  1242. raise unittest.SkipTest(msg)
  1243. else:
  1244. fn(*args, **kwargs)
  1245. return wrapper
  1246. assert isinstance(fn, type)
  1247. if GRAPH_EXECUTOR == ProfilingMode.LEGACY:
  1248. fn.__unittest_skip__ = True
  1249. fn.__unittest_skip_why__ = msg
  1250. return fn
  1251. return decorator
  1252. # Run PyTorch tests with translation validation on.
  1253. TEST_WITH_TV = os.getenv('PYTORCH_TEST_WITH_TV') == '1'
  1254. if TEST_WITH_TV:
  1255. torch.fx.experimental._config.translation_validation = True
  1256. # Some tests take too long when dynamic_shapes is combined with
  1257. # translation_validation. Whenever that happens, we solve that by
  1258. # disabling translation_validation.
  1259. def disable_translation_validation_if_dynamic_shapes(fn):
  1260. @functools.wraps(fn)
  1261. def wrapper(*args, **kwargs):
  1262. if torch._dynamo.config.dynamic_shapes:
  1263. # Turning TV off due to high latency on dynamic shapes.
  1264. torch.fx.experimental._config.translation_validation = False
  1265. return fn(*args, **kwargs)
  1266. return wrapper
  1267. # Determine whether to enable cuda memory leak check.
  1268. # CUDA mem leak check is expensive and thus we don't want to execute it on every
  1269. # test case / configuration.
  1270. # If this is True then CUDA memory leak checks are skipped. If this is false
  1271. # then CUDA memory leak checks are performed.
  1272. # See: https://github.com/pytorch/pytorch/pull/59402#issuecomment-858811135
  1273. TestEnvironment.def_flag("TEST_CUDA_MEM_LEAK_CHECK", env_var="PYTORCH_TEST_CUDA_MEM_LEAK_CHECK")
  1274. # Dict of NumPy dtype -> torch dtype (when the correspondence exists)
  1275. numpy_to_torch_dtype_dict = {
  1276. np.bool_ : torch.bool,
  1277. np.uint8 : torch.uint8,
  1278. np.uint16 : torch.uint16,
  1279. np.uint32 : torch.uint32,
  1280. np.uint64 : torch.uint64,
  1281. np.int8 : torch.int8,
  1282. np.int16 : torch.int16,
  1283. np.int32 : torch.int32,
  1284. np.int64 : torch.int64,
  1285. np.float16 : torch.float16,
  1286. np.float32 : torch.float32,
  1287. np.float64 : torch.float64,
  1288. np.complex64 : torch.complex64,
  1289. np.complex128 : torch.complex128
  1290. }
  1291. # numpy dtypes like np.float64 are not instances, but rather classes. This leads to rather absurd cases like
  1292. # np.float64 != np.dtype("float64") but np.float64 == np.dtype("float64").type.
  1293. # Especially when checking against a reference we can't be sure which variant we get, so we simply try both.
  1294. def numpy_to_torch_dtype(np_dtype):
  1295. try:
  1296. return numpy_to_torch_dtype_dict[np_dtype]
  1297. except KeyError:
  1298. return numpy_to_torch_dtype_dict[np_dtype.type]
  1299. def has_corresponding_torch_dtype(np_dtype):
  1300. try:
  1301. numpy_to_torch_dtype(np_dtype)
  1302. return True
  1303. except KeyError:
  1304. return False
  1305. if IS_WINDOWS:
  1306. # Size of `np.intc` is platform defined.
  1307. # It is returned by functions like `bitwise_not`.
  1308. # On Windows `int` is 32-bit
  1309. # https://docs.microsoft.com/en-us/cpp/cpp/data-type-ranges?view=msvc-160
  1310. numpy_to_torch_dtype_dict[np.intc] = torch.int
  1311. # Dict of torch dtype -> NumPy dtype
  1312. torch_to_numpy_dtype_dict = {value : key for (key, value) in numpy_to_torch_dtype_dict.items()}
  1313. torch_to_numpy_dtype_dict.update({
  1314. torch.bfloat16: np.float32,
  1315. torch.complex32: np.complex64
  1316. })
  1317. def skipIfNNModuleInlined(
  1318. msg="test doesn't currently work with nn module inlining",
  1319. condition=torch._dynamo.config.inline_inbuilt_nn_modules,
  1320. ): # noqa: F821
  1321. def decorator(fn):
  1322. if not isinstance(fn, type):
  1323. @wraps(fn)
  1324. def wrapper(*args, **kwargs):
  1325. if condition:
  1326. raise unittest.SkipTest(msg)
  1327. else:
  1328. fn(*args, **kwargs)
  1329. return wrapper
  1330. assert isinstance(fn, type)
  1331. if condition:
  1332. fn.__unittest_skip__ = True
  1333. fn.__unittest_skip_why__ = msg
  1334. return fn
  1335. return decorator
  1336. def skipIfRocm(func=None, *, msg="test doesn't currently work on the ROCm stack"):
  1337. def dec_fn(fn):
  1338. reason = f"skipIfRocm: {msg}"
  1339. @wraps(fn)
  1340. def wrapper(*args, **kwargs):
  1341. if TEST_WITH_ROCM: # noqa: F821
  1342. raise unittest.SkipTest(reason)
  1343. else:
  1344. return fn(*args, **kwargs)
  1345. return wrapper
  1346. if func:
  1347. return dec_fn(func)
  1348. return dec_fn
  1349. def runOnRocm(fn):
  1350. @wraps(fn)
  1351. def wrapper(*args, **kwargs):
  1352. if TEST_WITH_ROCM: # noqa: F821
  1353. fn(*args, **kwargs)
  1354. else:
  1355. raise unittest.SkipTest("test currently only works on the ROCm stack")
  1356. return wrapper
  1357. def skipIfXpu(func=None, *, msg="test doesn't currently work on the XPU stack"):
  1358. def dec_fn(fn):
  1359. reason = f"skipIfXpu: {msg}"
  1360. @wraps(fn)
  1361. def wrapper(*args, **kwargs):
  1362. if TEST_XPU:
  1363. raise unittest.SkipTest(reason)
  1364. else:
  1365. return fn(*args, **kwargs)
  1366. return wrapper
  1367. if func:
  1368. return dec_fn(func)
  1369. return dec_fn
  1370. def skipIfMps(fn):
  1371. @wraps(fn)
  1372. def wrapper(*args, **kwargs):
  1373. if TEST_MPS:
  1374. raise unittest.SkipTest("test doesn't currently work with MPS")
  1375. else:
  1376. fn(*args, **kwargs)
  1377. return wrapper
  1378. # Skips a test on CUDA if ROCm is available and its version is lower than requested.
  1379. def skipIfRocmVersionLessThan(version=None):
  1380. def dec_fn(fn):
  1381. @wraps(fn)
  1382. def wrap_fn(self, *args, **kwargs):
  1383. if TEST_WITH_ROCM: # noqa: F821
  1384. rocm_version = str(torch.version.hip)
  1385. rocm_version = rocm_version.split("-")[0] # ignore git sha
  1386. rocm_version_tuple = tuple(int(x) for x in rocm_version.split("."))
  1387. if rocm_version_tuple is None or version is None or rocm_version_tuple < tuple(version):
  1388. reason = f"ROCm {rocm_version_tuple} is available but {version} required"
  1389. raise unittest.SkipTest(reason)
  1390. return fn(self, *args, **kwargs)
  1391. return wrap_fn
  1392. return dec_fn
  1393. def skipIfNotMiopenSuggestNHWC(fn):
  1394. @wraps(fn)
  1395. def wrapper(*args, **kwargs):
  1396. if not TEST_WITH_MIOPEN_SUGGEST_NHWC:
  1397. raise unittest.SkipTest("test doesn't currently work without MIOpen NHWC activation")
  1398. else:
  1399. fn(*args, **kwargs)
  1400. return wrapper
  1401. # Reverts the linalg backend back to default to make sure potential failures in one
  1402. # test do not affect other tests
  1403. def setLinalgBackendsToDefaultFinally(fn):
  1404. @wraps(fn)
  1405. def _fn(*args, **kwargs):
  1406. _preferred_backend = torch.backends.cuda.preferred_linalg_library()
  1407. try:
  1408. fn(*args, **kwargs)
  1409. finally:
  1410. torch.backends.cuda.preferred_linalg_library(_preferred_backend)
  1411. return _fn
  1412. # Reverts the blas backend back to default to make sure potential failures in one
  1413. # test do not affect other tests
  1414. def setBlasBackendsToDefaultFinally(fn):
  1415. @wraps(fn)
  1416. def _fn(*args, **kwargs):
  1417. _preferred_backend = torch.backends.cuda.preferred_blas_library()
  1418. try:
  1419. fn(*args, **kwargs)
  1420. finally:
  1421. torch.backends.cuda.preferred_blas_library(_preferred_backend)
  1422. return _fn
  1423. # Context manager for setting deterministic flag and automatically
  1424. # resetting it to its original value
  1425. class DeterministicGuard:
  1426. def __init__(self, deterministic, *, warn_only=False, fill_uninitialized_memory=True):
  1427. self.deterministic = deterministic
  1428. self.warn_only = warn_only
  1429. self.fill_uninitialized_memory = fill_uninitialized_memory
  1430. def __enter__(self):
  1431. self.deterministic_restore = torch.are_deterministic_algorithms_enabled()
  1432. self.warn_only_restore = torch.is_deterministic_algorithms_warn_only_enabled()
  1433. self.fill_uninitialized_memory_restore = torch.utils.deterministic.fill_uninitialized_memory
  1434. torch.use_deterministic_algorithms(
  1435. self.deterministic,
  1436. warn_only=self.warn_only)
  1437. torch.utils.deterministic.fill_uninitialized_memory = self.fill_uninitialized_memory
  1438. def __exit__(self, exception_type, exception_value, traceback):
  1439. torch.use_deterministic_algorithms(
  1440. self.deterministic_restore,
  1441. warn_only=self.warn_only_restore)
  1442. torch.utils.deterministic.fill_uninitialized_memory = self.fill_uninitialized_memory_restore
  1443. class AlwaysWarnTypedStorageRemoval:
  1444. def __init__(self, always_warn):
  1445. assert isinstance(always_warn, bool)
  1446. self.always_warn = always_warn
  1447. def __enter__(self):
  1448. self.always_warn_restore = torch.storage._get_always_warn_typed_storage_removal()
  1449. torch.storage._set_always_warn_typed_storage_removal(self.always_warn)
  1450. def __exit__(self, exception_type, exception_value, traceback):
  1451. torch.storage._set_always_warn_typed_storage_removal(self.always_warn_restore)
  1452. # Context manager for setting cuda sync debug mode and reset it
  1453. # to original value
  1454. # we are not exposing it to the core because sync debug mode is
  1455. # global and thus not thread safe
  1456. class CudaSyncGuard:
  1457. def __init__(self, sync_debug_mode):
  1458. self.mode = sync_debug_mode
  1459. def __enter__(self):
  1460. self.debug_mode_restore = torch.cuda.get_sync_debug_mode()
  1461. torch.cuda.set_sync_debug_mode(self.mode)
  1462. def __exit__(self, exception_type, exception_value, traceback):
  1463. torch.cuda.set_sync_debug_mode(self.debug_mode_restore)
  1464. # Context manager for setting torch.__future__.set_swap_module_params_on_conversion
  1465. # and automatically resetting it to its original value
  1466. class SwapTensorsGuard:
  1467. def __init__(self, use_swap_tensors):
  1468. self.use_swap_tensors = use_swap_tensors
  1469. def __enter__(self):
  1470. self.swap_tensors_restore = torch.__future__.get_swap_module_params_on_conversion()
  1471. if self.use_swap_tensors is not None:
  1472. torch.__future__.set_swap_module_params_on_conversion(self.use_swap_tensors)
  1473. def __exit__(self, exception_type, exception_value, traceback):
  1474. torch.__future__.set_swap_module_params_on_conversion(self.swap_tensors_restore)
  1475. # This decorator can be used for API tests that call
  1476. # torch.use_deterministic_algorithms(). When the test is finished, it will
  1477. # restore the previous deterministic flag setting.
  1478. #
  1479. # If CUDA >= 10.2, this will set the environment variable
  1480. # CUBLAS_WORKSPACE_CONFIG=:4096:8 so that the error associated with that
  1481. # setting is not thrown during the test unless the test changes that variable
  1482. # on purpose. The previous CUBLAS_WORKSPACE_CONFIG setting will also be
  1483. # restored once the test is finished.
  1484. #
  1485. # Note that if a test requires CUDA to actually register the changed
  1486. # CUBLAS_WORKSPACE_CONFIG variable, a new subprocess must be created, because
  1487. # CUDA only checks the variable when the runtime initializes. Tests can be
  1488. # run inside a subprocess like so:
  1489. #
  1490. # import subprocess, sys, os
  1491. # script = '''
  1492. # # Test code should go here
  1493. # '''
  1494. # try:
  1495. # subprocess.check_output(
  1496. # [sys.executable, '-c', script],
  1497. # stderr=subprocess.STDOUT,
  1498. # cwd=os.path.dirname(os.path.realpath(__file__)),
  1499. # env=os.environ.copy())
  1500. # except subprocess.CalledProcessError as e:
  1501. # error_message = e.output.decode('utf-8')
  1502. # # Handle exceptions raised by the subprocess here
  1503. #
  1504. def wrapDeterministicFlagAPITest(fn):
  1505. @wraps(fn)
  1506. def wrapper(*args, **kwargs):
  1507. with DeterministicGuard(
  1508. torch.are_deterministic_algorithms_enabled(),
  1509. warn_only=torch.is_deterministic_algorithms_warn_only_enabled()):
  1510. class CuBLASConfigGuard:
  1511. cublas_var_name = 'CUBLAS_WORKSPACE_CONFIG'
  1512. def __enter__(self):
  1513. self.is_cuda10_2_or_higher = (
  1514. (torch.version.cuda is not None)
  1515. and ([int(x) for x in torch.version.cuda.split(".")] >= [10, 2]))
  1516. if self.is_cuda10_2_or_higher:
  1517. self.cublas_config_restore = os.environ.get(self.cublas_var_name)
  1518. os.environ[self.cublas_var_name] = ':4096:8'
  1519. def __exit__(self, exception_type, exception_value, traceback):
  1520. if self.is_cuda10_2_or_higher:
  1521. cur_cublas_config = os.environ.get(self.cublas_var_name)
  1522. if self.cublas_config_restore is None:
  1523. if cur_cublas_config is not None:
  1524. del os.environ[self.cublas_var_name]
  1525. else:
  1526. os.environ[self.cublas_var_name] = self.cublas_config_restore
  1527. with CuBLASConfigGuard():
  1528. fn(*args, **kwargs)
  1529. return wrapper
  1530. # This decorator can be used for API tests that want to safely call
  1531. # torch.__future__.set_swap_module_params_on_conversion. `swap` can be set to
  1532. # True, False or None where None indicates that the context manager does not
  1533. # set the flag. When the test is finished, it will restore the previous swap
  1534. # flag setting.
  1535. def wrapSwapTensorsTest(swap=None):
  1536. def dec_fn(fn):
  1537. @wraps(fn)
  1538. def wrapper(*args, **kwargs):
  1539. with SwapTensorsGuard(swap):
  1540. fn(*args, **kwargs)
  1541. return wrapper
  1542. return dec_fn
  1543. # test parametrizer for swapping
  1544. class swap(_TestParametrizer):
  1545. def __init__(self, swap_values):
  1546. super().__init__()
  1547. self.swap_values = swap_values
  1548. def _parametrize_test(self, test, generic_cls, device_cls):
  1549. for swap in self.swap_values:
  1550. yield wrapSwapTensorsTest(swap)(test), f'swap_{swap}', {}, lambda _: []
  1551. def skipIfCompiledWithoutNumpy(fn):
  1552. # Even if the numpy module is present, if `USE_NUMPY=0` is used during the
  1553. # build, numpy tests will fail
  1554. numpy_support = TEST_NUMPY
  1555. if numpy_support:
  1556. try:
  1557. # The numpy module is present, verify that PyTorch is compiled with
  1558. # numpy support
  1559. torch.from_numpy(np.array([2, 2]))
  1560. except RuntimeError:
  1561. numpy_support = False
  1562. @wraps(fn)
  1563. def wrapper(*args, **kwargs):
  1564. if not numpy_support:
  1565. raise unittest.SkipTest("PyTorch was compiled without numpy support")
  1566. else:
  1567. fn(*args, **kwargs)
  1568. return wrapper
  1569. def _test_function(fn, device):
  1570. def run_test_function(self):
  1571. return fn(self, device)
  1572. return run_test_function
  1573. def skipIfNoXNNPACK(fn):
  1574. @wraps(fn)
  1575. def wrapper(*args, **kwargs):
  1576. if not torch.backends.xnnpack.enabled:
  1577. raise unittest.SkipTest('XNNPACK must be enabled for these tests. Please build with USE_XNNPACK=1.')
  1578. else:
  1579. fn(*args, **kwargs)
  1580. return wrapper
  1581. def skipIfNoLapack(fn):
  1582. @wraps(fn)
  1583. def wrapper(*args, **kwargs):
  1584. if not torch._C.has_lapack:
  1585. raise unittest.SkipTest('PyTorch compiled without Lapack')
  1586. else:
  1587. fn(*args, **kwargs)
  1588. return wrapper
  1589. def skipIfNotRegistered(op_name, message):
  1590. """Wraps the decorator to hide the import of the `core`.
  1591. Args:
  1592. op_name: Check if this op is registered in `core._REGISTERED_OPERATORS`.
  1593. message: message to fail with.
  1594. Usage:
  1595. @skipIfNotRegistered('MyOp', 'MyOp is not linked!')
  1596. This will check if 'MyOp' is in the caffe2.python.core
  1597. """
  1598. return unittest.skip("Pytorch is compiled without Caffe2")
  1599. def _decide_skip_caffe2(expect_caffe2, reason):
  1600. def skip_dec(func):
  1601. @wraps(func)
  1602. def wrapper(self):
  1603. if torch.onnx._CAFFE2_ATEN_FALLBACK != expect_caffe2:
  1604. raise unittest.SkipTest(reason)
  1605. return func(self)
  1606. return wrapper
  1607. return skip_dec
  1608. skipIfCaffe2 = _decide_skip_caffe2(False, "Not compatible with Caffe2")
  1609. skipIfNoCaffe2 = _decide_skip_caffe2(True, "Caffe2 is not available")
  1610. def skipIfNoSciPy(fn):
  1611. @wraps(fn)
  1612. def wrapper(*args, **kwargs):
  1613. if not TEST_SCIPY:
  1614. raise unittest.SkipTest("test require SciPy, but SciPy not found")
  1615. else:
  1616. fn(*args, **kwargs)
  1617. return wrapper
  1618. def skip_if_pytest(fn):
  1619. @wraps(fn)
  1620. def wrapped(*args, **kwargs):
  1621. if "PYTEST_CURRENT_TEST" in os.environ:
  1622. raise unittest.SkipTest("does not work under pytest")
  1623. return fn(*args, **kwargs)
  1624. return wrapped
  1625. def slowTest(fn):
  1626. @wraps(fn)
  1627. def wrapper(*args, **kwargs):
  1628. if not TEST_WITH_SLOW: # noqa: F821
  1629. raise unittest.SkipTest("test is slow; run with PYTORCH_TEST_WITH_SLOW to enable test")
  1630. else:
  1631. fn(*args, **kwargs)
  1632. wrapper.__dict__['slow_test'] = True
  1633. return wrapper
  1634. def slowTestIf(condition):
  1635. return slowTest if condition else lambda fn: fn
  1636. def skipCUDAMemoryLeakCheckIf(condition):
  1637. def dec(fn):
  1638. if getattr(fn, '_do_cuda_memory_leak_check', True): # if current True
  1639. fn._do_cuda_memory_leak_check = not condition
  1640. return fn
  1641. return dec
  1642. def skipCUDANonDefaultStreamIf(condition):
  1643. def dec(fn):
  1644. if getattr(fn, '_do_cuda_non_default_stream', True): # if current True
  1645. fn._do_cuda_non_default_stream = not condition
  1646. return fn
  1647. return dec
  1648. def suppress_warnings(fn):
  1649. @wraps(fn)
  1650. def wrapper(*args, **kwargs):
  1651. with warnings.catch_warnings():
  1652. warnings.simplefilter("ignore")
  1653. fn(*args, **kwargs)
  1654. return wrapper
  1655. def to_gpu(obj, type_map=None):
  1656. if type_map is None:
  1657. type_map = {}
  1658. if isinstance(obj, torch.Tensor):
  1659. assert obj.is_leaf
  1660. t = type_map.get(obj.dtype, obj.dtype)
  1661. with torch.no_grad():
  1662. res = obj.clone().to(dtype=t, device="cuda")
  1663. res.requires_grad = obj.requires_grad
  1664. return res
  1665. elif torch.is_storage(obj):
  1666. return obj.new().resize_(obj.size()).copy_(obj)
  1667. elif isinstance(obj, list):
  1668. return [to_gpu(o, type_map) for o in obj]
  1669. elif isinstance(obj, tuple):
  1670. return tuple(to_gpu(o, type_map) for o in obj)
  1671. else:
  1672. return deepcopy(obj)
  1673. def get_function_arglist(func):
  1674. return inspect.getfullargspec(func).args
  1675. def set_rng_seed(seed):
  1676. torch.manual_seed(seed)
  1677. random.seed(seed)
  1678. if TEST_NUMPY:
  1679. np.random.seed(seed)
  1680. @contextlib.contextmanager
  1681. def set_default_dtype(dtype):
  1682. saved_dtype = torch.get_default_dtype()
  1683. torch.set_default_dtype(dtype)
  1684. try:
  1685. yield
  1686. finally:
  1687. torch.set_default_dtype(saved_dtype)
  1688. @contextlib.contextmanager
  1689. def set_default_tensor_type(tensor_type):
  1690. saved_tensor_type = torch.tensor([]).type()
  1691. torch.set_default_tensor_type(tensor_type)
  1692. try:
  1693. yield
  1694. finally:
  1695. torch.set_default_tensor_type(saved_tensor_type)
  1696. def iter_indices(tensor):
  1697. if tensor.dim() == 0:
  1698. return range(0)
  1699. if tensor.dim() == 1:
  1700. return range(tensor.size(0))
  1701. return product(*(range(s) for s in tensor.size()))
  1702. def is_iterable(obj):
  1703. try:
  1704. iter(obj)
  1705. return True
  1706. except TypeError:
  1707. return False
  1708. def is_iterable_of_tensors(iterable, include_empty=False):
  1709. """ Returns True if iterable is an iterable of tensors and False o.w.
  1710. If the iterable is empty, the return value is :attr:`include_empty`
  1711. """
  1712. # Tensor itself is iterable so we check this first
  1713. if isinstance(iterable, torch.Tensor):
  1714. return False
  1715. try:
  1716. if len(iterable) == 0:
  1717. return include_empty
  1718. for t in iter(iterable):
  1719. if not isinstance(t, torch.Tensor):
  1720. return False
  1721. except TypeError as te:
  1722. return False
  1723. return True
  1724. class CudaNonDefaultStream:
  1725. def __enter__(self):
  1726. # Before starting CUDA test save currently active streams on all
  1727. # CUDA devices and set new non default streams to all CUDA devices
  1728. # to ensure CUDA tests do not use default stream by mistake.
  1729. beforeDevice = torch.cuda.current_device()
  1730. self.beforeStreams = []
  1731. for d in range(torch.cuda.device_count()):
  1732. self.beforeStreams.append(torch.cuda.current_stream(d))
  1733. deviceStream = torch.cuda.Stream(device=d)
  1734. self.beforeStreams[-1].synchronize()
  1735. torch._C._cuda_setStream(stream_id=deviceStream.stream_id,
  1736. device_index=deviceStream.device_index,
  1737. device_type=deviceStream.device_type)
  1738. torch._C._cuda_setDevice(beforeDevice)
  1739. def __exit__(self, exec_type, exec_value, traceback):
  1740. # After completing CUDA test load previously active streams on all
  1741. # CUDA devices.
  1742. beforeDevice = torch.cuda.current_device()
  1743. for d in range(torch.cuda.device_count()):
  1744. torch._C._cuda_setStream(stream_id=self.beforeStreams[d].stream_id,
  1745. device_index=self.beforeStreams[d].device_index,
  1746. device_type=self.beforeStreams[d].device_type)
  1747. torch._C._cuda_setDevice(beforeDevice)
  1748. class CudaMemoryLeakCheck:
  1749. def __init__(self, testcase, name=None):
  1750. self.name = testcase.id() if name is None else name
  1751. self.testcase = testcase
  1752. # initialize context & RNG to prevent false positive detections
  1753. # when the test is the first to initialize those
  1754. from torch.testing._internal.common_cuda import initialize_cuda_context_rng
  1755. initialize_cuda_context_rng()
  1756. # Stores CUDA memory data provided by PyTorch's caching allocator and
  1757. # the CUDA driver.
  1758. #
  1759. # NOTE: The undocumented torch.cuda.mem_get_info() returns
  1760. # (#free bytes, #total bytes available) on the GPU
  1761. def __enter__(self):
  1762. self.caching_allocator_befores = []
  1763. self.driver_befores = []
  1764. # Performs a gc if required (required if any CUDA memory is held)
  1765. num_devices = torch.cuda.device_count()
  1766. for i in range(num_devices):
  1767. caching_allocator_mem_allocated = torch.cuda.memory_allocated(i)
  1768. # NOTE: gc is based exclusively on caching allocator memory
  1769. # because the driver will always have some bytes in use (context size?)
  1770. if caching_allocator_mem_allocated > 0:
  1771. gc.collect()
  1772. torch._C._cuda_clearCublasWorkspaces()
  1773. torch.cuda.empty_cache()
  1774. break
  1775. # Acquires caching allocator and driver statistics before the test is run
  1776. for i in range(num_devices):
  1777. self.caching_allocator_befores.append(torch.cuda.memory_allocated(i))
  1778. bytes_free, bytes_total = torch.cuda.mem_get_info(i)
  1779. driver_mem_allocated = bytes_total - bytes_free
  1780. self.driver_befores.append(driver_mem_allocated)
  1781. def __exit__(self, exec_type, exec_value, traceback):
  1782. # Don't check for leaks if an exception was thrown
  1783. if exec_type is not None:
  1784. return
  1785. # Compares caching allocator before/after statistics
  1786. # An increase in allocated memory is a discrepancy indicating a possible
  1787. # memory leak
  1788. discrepancy_detected = False
  1789. num_devices = torch.cuda.device_count()
  1790. for i in range(num_devices):
  1791. # avoid counting cublasWorkspace allocations
  1792. torch._C._cuda_clearCublasWorkspaces()
  1793. caching_allocator_mem_allocated = torch.cuda.memory_allocated(i)
  1794. if caching_allocator_mem_allocated > self.caching_allocator_befores[i]:
  1795. discrepancy_detected = True
  1796. break
  1797. # Short-circuits if no discrepancy detected
  1798. if not discrepancy_detected:
  1799. return
  1800. # Validates the discrepancy persists after garbage collection and
  1801. # is confirmed by the driver API
  1802. # NOTE: driver API iscrepancies alone are ignored because with the jiterator
  1803. # some tests may permanently increase the CUDA context size and
  1804. # that will appear as a driver memory leak but is the expected behavior.
  1805. # GCs and clears the cache
  1806. gc.collect()
  1807. torch.cuda.empty_cache()
  1808. for i in range(num_devices):
  1809. discrepancy_detected = True
  1810. # Query memory multiple items to ensure leak was not transient
  1811. for n in range(3):
  1812. caching_allocator_mem_allocated = torch.cuda.memory_allocated(i)
  1813. bytes_free, bytes_total = torch.cuda.mem_get_info(i)
  1814. driver_mem_allocated = bytes_total - bytes_free
  1815. caching_allocator_discrepancy = False
  1816. driver_discrepancy = False
  1817. if caching_allocator_mem_allocated > self.caching_allocator_befores[i]:
  1818. caching_allocator_discrepancy = True
  1819. if driver_mem_allocated > self.driver_befores[i]:
  1820. driver_discrepancy = True
  1821. if not (caching_allocator_discrepancy or driver_discrepancy):
  1822. # Leak was false positive, exit loop
  1823. discrepancy_detected = False
  1824. break
  1825. if not discrepancy_detected:
  1826. continue
  1827. if caching_allocator_discrepancy and not driver_discrepancy:
  1828. # Just raises a warning if the leak is not validated by the
  1829. # driver API
  1830. # NOTE: this may be a problem with how the caching allocator collects its
  1831. # statistics or a leak too small to trigger the allocation of an
  1832. # additional block of memory by the CUDA driver
  1833. msg = ("CUDA caching allocator reports a memory leak not "
  1834. f"verified by the driver API in {self.name}! "
  1835. f"Caching allocator allocated memory was {self.caching_allocator_befores[i]} "
  1836. f"and is now reported as {caching_allocator_mem_allocated} "
  1837. f"on device {i}. "
  1838. f"CUDA driver allocated memory was {self.driver_befores[i]} and is now {driver_mem_allocated}.")
  1839. warnings.warn(msg)
  1840. elif caching_allocator_discrepancy and driver_discrepancy:
  1841. # A caching allocator discrepancy validated by the driver API is a
  1842. # failure (except on ROCm, see below)
  1843. msg = (f"CUDA driver API confirmed a leak in {self.name}! "
  1844. f"Caching allocator allocated memory was {self.caching_allocator_befores[i]} "
  1845. f"and is now reported as {caching_allocator_mem_allocated} "
  1846. f"on device {i}. "
  1847. f"CUDA driver allocated memory was {self.driver_befores[i]} and is now {driver_mem_allocated}.")
  1848. raise RuntimeError(msg)
  1849. @contextmanager
  1850. def skip_exception_type(exc_type):
  1851. try:
  1852. yield
  1853. except exc_type as e:
  1854. raise unittest.SkipTest(f"not implemented: {e}") from e
  1855. @contextmanager
  1856. def print_repro_on_failure(repro_str):
  1857. try:
  1858. yield
  1859. except unittest.SkipTest:
  1860. raise
  1861. except Exception as e:
  1862. # NB: Hacking the exception args is the cleanest way I've found to append
  1863. # failure reproduction info without poisoning the stack trace.
  1864. if len(e.args) >= 1:
  1865. e.args = (f"{e.args[0]}\n{repro_str}", *e.args[1:])
  1866. raise
  1867. # "min_satisfying_examples" setting has been deprecated in hypothesis
  1868. # 3.56.0 and removed in hypothesis 4.x
  1869. try:
  1870. import hypothesis
  1871. def settings(*args, **kwargs):
  1872. if 'min_satisfying_examples' in kwargs and hypothesis.version.__version_info__ >= (3, 56, 0):
  1873. kwargs.pop('min_satisfying_examples')
  1874. return hypothesis.settings(*args, **kwargs)
  1875. hypothesis.settings.register_profile(
  1876. "pytorch_ci",
  1877. settings(
  1878. derandomize=True,
  1879. suppress_health_check=[hypothesis.HealthCheck.too_slow],
  1880. database=None,
  1881. max_examples=50,
  1882. verbosity=hypothesis.Verbosity.normal))
  1883. hypothesis.settings.register_profile(
  1884. "dev",
  1885. settings(
  1886. suppress_health_check=[hypothesis.HealthCheck.too_slow],
  1887. database=None,
  1888. max_examples=10,
  1889. verbosity=hypothesis.Verbosity.normal))
  1890. hypothesis.settings.register_profile(
  1891. "debug",
  1892. settings(
  1893. suppress_health_check=[hypothesis.HealthCheck.too_slow],
  1894. database=None,
  1895. max_examples=1000,
  1896. verbosity=hypothesis.Verbosity.verbose))
  1897. hypothesis.settings.load_profile(
  1898. "pytorch_ci" if IS_CI else os.getenv('PYTORCH_HYPOTHESIS_PROFILE', 'dev') # noqa: F821
  1899. )
  1900. except ImportError:
  1901. print('Fail to import hypothesis in common_utils, tests are not derandomized')
  1902. # Used in check_if_enable to see if a test method should be disabled by an issue,
  1903. # sanitizes a test method name from appended suffixes by @dtypes parametrization.
  1904. # e.g., an issue with title "DISABLED test_bitwise_ops (__main__.TestBinaryUfuncs)" should
  1905. # disabled ALL parametrized test_bitwise_ops tests, such test_bitwise_ops_cuda_int32
  1906. def remove_device_and_dtype_suffixes(test_name: str) -> str:
  1907. # import statement is localized to avoid circular dependency issues with common_device_type.py
  1908. from torch.testing._internal.common_device_type import get_device_type_test_bases
  1909. device_suffixes = [x.device_type for x in get_device_type_test_bases()]
  1910. dtype_suffixes = [str(dt)[len("torch."):] for dt in get_all_dtypes()]
  1911. test_name_chunks = test_name.split("_")
  1912. if len(test_name_chunks) > 0 and test_name_chunks[-1] in dtype_suffixes:
  1913. if len(test_name_chunks) > 1 and test_name_chunks[-2] in device_suffixes:
  1914. return "_".join(test_name_chunks[0:-2])
  1915. return "_".join(test_name_chunks[0:-1])
  1916. return test_name
  1917. def check_if_enable(test: unittest.TestCase):
  1918. classname = str(test.__class__).split("'")[1].split(".")[-1]
  1919. sanitized_testname = remove_device_and_dtype_suffixes(test._testMethodName)
  1920. def matches_test(target: str):
  1921. target_test_parts = target.split()
  1922. if len(target_test_parts) < 2:
  1923. # poorly formed target test name
  1924. return False
  1925. target_testname = target_test_parts[0]
  1926. target_classname = target_test_parts[1][1:-1].split(".")[-1]
  1927. # if test method name or its sanitized version exactly matches the disabled
  1928. # test method name AND allow non-parametrized suite names to disable
  1929. # parametrized ones (TestSuite disables TestSuiteCPU)
  1930. return classname.startswith(target_classname) and (target_testname in (test._testMethodName, sanitized_testname))
  1931. if any(matches_test(x) for x in slow_tests_dict.keys()):
  1932. getattr(test, test._testMethodName).__dict__['slow_test'] = True
  1933. if not TEST_WITH_SLOW: # noqa: F821
  1934. raise unittest.SkipTest("test is slow; run with PYTORCH_TEST_WITH_SLOW to enable test")
  1935. if not IS_SANDCASTLE: # noqa: F821
  1936. should_skip = False
  1937. skip_msg = ""
  1938. for disabled_test, (issue_url, platforms) in disabled_tests_dict.items():
  1939. if matches_test(disabled_test):
  1940. platform_to_conditional: Dict = {
  1941. "mac": IS_MACOS,
  1942. "macos": IS_MACOS,
  1943. "win": IS_WINDOWS,
  1944. "windows": IS_WINDOWS,
  1945. "linux": IS_LINUX,
  1946. "rocm": TEST_WITH_ROCM, # noqa: F821
  1947. "xpu": TEST_XPU, # noqa: F821
  1948. "asan": TEST_WITH_ASAN, # noqa: F821
  1949. "dynamo": TEST_WITH_TORCHDYNAMO, # noqa: F821
  1950. "inductor": TEST_WITH_TORCHINDUCTOR, # noqa: F821
  1951. "slow": TEST_WITH_SLOW, # noqa: F821
  1952. }
  1953. invalid_platforms = list(filter(lambda p: p not in platform_to_conditional, platforms))
  1954. if len(invalid_platforms) > 0:
  1955. invalid_plats_str = ", ".join(invalid_platforms)
  1956. valid_plats = ", ".join(platform_to_conditional.keys())
  1957. print(f"Test {disabled_test} is disabled for some unrecognized ",
  1958. f"platforms: [{invalid_plats_str}]. Please edit issue {issue_url} to fix the platforms ",
  1959. 'assigned to this flaky test, changing "Platforms: ..." to a comma separated ',
  1960. f"subset of the following (or leave it blank to match all platforms): {valid_plats}")
  1961. # Sanitize the platforms list so that we continue to disable the test for any valid platforms given
  1962. platforms = list(filter(lambda p: p in platform_to_conditional, platforms))
  1963. if platforms == [] or any(platform_to_conditional[platform] for platform in platforms):
  1964. should_skip = True
  1965. skip_msg = f"Test is disabled because an issue exists disabling it: {issue_url}" \
  1966. f" for {'all' if platforms == [] else ''}platform(s) {', '.join(platforms)}. " \
  1967. "If you're seeing this on your local machine and would like to enable this test, " \
  1968. "please make sure CI is not set and you are not using the flag --import-disabled-tests."
  1969. break
  1970. if should_skip and not RERUN_DISABLED_TESTS:
  1971. # Skip the disabled test when not running under --rerun-disabled-tests verification mode
  1972. raise unittest.SkipTest(skip_msg)
  1973. if not should_skip and RERUN_DISABLED_TESTS:
  1974. skip_msg = "Test is enabled but --rerun-disabled-tests verification mode is set, so only" \
  1975. " disabled tests are run"
  1976. raise unittest.SkipTest(skip_msg)
  1977. if TEST_SKIP_FAST: # noqa: F821
  1978. if hasattr(test, test._testMethodName) and not getattr(test, test._testMethodName).__dict__.get('slow_test', False):
  1979. raise unittest.SkipTest("test is fast; we disabled it with PYTORCH_TEST_SKIP_FAST")
  1980. # `TestCase.assertEqual` is very permissive and coerced the inputs into a format that could be compared. This is very
  1981. # convenient when writing tests, but not so much while reviewing them. By default, the comparison `Pair` framework of
  1982. # `torch.testing._comparison.are_equal`, used for example by the public testing function
  1983. # `torch.testing.assert_close`, is more strict. In order to use the same framework and thus reduce the divergence
  1984. # between internal and external comparison logic as much as possible, we define some "relaxed" pairs here. They only
  1985. # change the supported inputs, but the comparison logic is the same.
  1986. # TODO: Revisit the relaxed pairs and check how much work it is to fix the tests that would fail without the relaxation.
  1987. class RelaxedBooleanPair(BooleanPair):
  1988. """Pair for boolean-like inputs.
  1989. In contrast to the builtin :class:`BooleanPair`, this class also supports one input being a number or a single
  1990. element tensor-like.
  1991. """
  1992. _supported_number_types = NumberPair(0, 0)._supported_types
  1993. def _process_inputs(self, actual, expected, *, id):
  1994. # We require only one of the inputs of the inputs to be a boolean and the other can also be a boolean, a
  1995. # number, or a single element tensor or array, whereas in default BooleanPair both inputs have to be booleans.
  1996. tensor_or_array_types: Tuple[Type, ...] = (torch.Tensor, np.ndarray)
  1997. other_supported_types = (*self._supported_types, *self._supported_number_types, *tensor_or_array_types)
  1998. if not (
  1999. (isinstance(actual, self._supported_types) and isinstance(expected, other_supported_types))
  2000. or (isinstance(expected, self._supported_types) and isinstance(actual, other_supported_types))
  2001. ):
  2002. self._inputs_not_supported()
  2003. return [self._to_bool(input, id=id) for input in (actual, expected)]
  2004. def _to_bool(self, bool_like, *, id):
  2005. if isinstance(bool_like, np.number):
  2006. return bool(bool_like.item())
  2007. elif type(bool_like) in self._supported_number_types:
  2008. return bool(bool_like)
  2009. elif isinstance(bool_like, (torch.Tensor, np.ndarray)):
  2010. numel = bool_like.numel() if isinstance(bool_like, torch.Tensor) else bool_like.size
  2011. if numel > 1:
  2012. self._fail(
  2013. ValueError,
  2014. f"Only single element tensor-likes can be compared against a boolean. "
  2015. f"Got {numel} elements instead.",
  2016. id=id
  2017. )
  2018. return bool(bool_like.item())
  2019. else:
  2020. return super()._to_bool(bool_like, id=id)
  2021. class RelaxedNumberPair(NumberPair):
  2022. """Pair for number-like inputs.
  2023. In contrast to the builtin :class:`NumberPair`, this class also supports one input being a single element
  2024. tensor-like or a :class:`enum.Enum`. (D)Type checks are disabled, meaning comparing 1 to 1.0 succeeds even when
  2025. ``check_dtype=True`` is passed.
  2026. In addition, this class uses looser default tolerances for :class:`float` and :class:`complex` inputs. Also
  2027. supports overriding the absolute and relative tolerance through the ``@precisionOverride`` and
  2028. ``@toleranceOverride`` decorators.
  2029. """
  2030. _TYPE_TO_DTYPE = {
  2031. int: torch.int64,
  2032. float: torch.float32,
  2033. complex: torch.complex64,
  2034. }
  2035. def __init__(
  2036. self, actual, expected, *, rtol_override=0.0, atol_override=0.0, check_dtype=None, **other_parameters
  2037. ) -> None:
  2038. super().__init__(actual, expected, check_dtype=False, **other_parameters)
  2039. self.rtol = max(self.rtol, rtol_override)
  2040. self.atol = max(self.atol, atol_override)
  2041. def _process_inputs(self, actual, expected, *, id):
  2042. # We require only one of the inputs of the inputs to be a number and the other can also be a number or a single
  2043. # element tensor or array, whereas in default NumberPair both inputs have to be numbers.
  2044. tensor_or_array_types: Tuple[Type, ...] = (torch.Tensor, np.ndarray)
  2045. other_supported_types = (*self._supported_types, *tensor_or_array_types)
  2046. if not (
  2047. (isinstance(actual, self._supported_types) and isinstance(expected, other_supported_types))
  2048. or (isinstance(expected, self._supported_types) and isinstance(actual, other_supported_types))
  2049. ):
  2050. self._inputs_not_supported()
  2051. return [self._to_number(input, id=id) for input in (actual, expected)]
  2052. def _to_number(self, number_like, *, id):
  2053. if isinstance(number_like, (torch.Tensor, np.ndarray)):
  2054. numel = number_like.numel() if isinstance(number_like, torch.Tensor) else number_like.size
  2055. if numel > 1:
  2056. self._fail(
  2057. ValueError,
  2058. f"Only single element tensor-likes can be compared against a number. "
  2059. f"Got {numel} elements instead.",
  2060. id=id
  2061. )
  2062. number = number_like.item()
  2063. if isinstance(number, bool):
  2064. number = int(number)
  2065. return number
  2066. elif isinstance(number_like, Enum):
  2067. return int(number_like) # type: ignore[call-overload]
  2068. else:
  2069. return super()._to_number(number_like, id=id)
  2070. class TensorOrArrayPair(TensorLikePair):
  2071. """Pair for tensor-like inputs.
  2072. On the one hand this class is stricter than the builtin :class:`TensorLikePair` since it only allows instances of
  2073. :class:`torch.Tensor` and :class:`numpy.ndarray` rather than allowing any tensor-like than can be converted into a
  2074. tensor. On the other hand this class is looser since it converts all inputs into tensors with no regard of their
  2075. relationship, e.g. comparing a :class:`torch.Tensor` to :class:`numpy.ndarray` is fine.
  2076. In addition, this class supports overriding the absolute and relative tolerance through the ``@precisionOverride``
  2077. and ``@toleranceOverride`` decorators.
  2078. """
  2079. def __init__(self, actual, expected, *, rtol_override=0.0, atol_override=0.0, **other_parameters):
  2080. super().__init__(actual, expected, **other_parameters)
  2081. self.rtol = max(self.rtol, rtol_override)
  2082. self.atol = max(self.atol, atol_override)
  2083. def _process_inputs(self, actual, expected, *, id, allow_subclasses):
  2084. self._check_inputs_isinstance(actual, expected, cls=(torch.Tensor, np.ndarray))
  2085. actual, expected = (self._to_tensor(input) for input in (actual, expected))
  2086. for tensor in (actual, expected):
  2087. self._check_supported(tensor, id=id)
  2088. return actual, expected
  2089. class TypedStoragePair(TensorLikePair):
  2090. """Pair for :class:`torch.storage.TypedStorage` inputs."""
  2091. def __init__(self, actual, expected, *, rtol_override=0.0, atol_override=0.0, **other_parameters):
  2092. self._check_inputs_isinstance(actual, expected, cls=torch.storage.TypedStorage)
  2093. super().__init__(actual, expected, **other_parameters)
  2094. self.rtol = max(self.rtol, rtol_override)
  2095. self.atol = max(self.atol, atol_override)
  2096. def _to_tensor(self, typed_storage):
  2097. return torch.tensor(
  2098. typed_storage._untyped_storage,
  2099. dtype={
  2100. torch.quint8: torch.uint8,
  2101. torch.quint4x2: torch.uint8,
  2102. torch.quint2x4: torch.uint8,
  2103. torch.qint32: torch.int32,
  2104. torch.qint8: torch.int8
  2105. }.get(typed_storage.dtype, typed_storage.dtype),
  2106. device=typed_storage.device,
  2107. )
  2108. class UnittestPair(Pair):
  2109. """Fallback ABC pair that handles non-numeric inputs.
  2110. To avoid recreating the mismatch messages of :meth:`unittest.TestCase.assertEqual`, this pair simply wraps it in
  2111. order to use it with the :class:`Pair` "framework" from :func:`are_equal`.
  2112. Define the :attr:`UnittestPair.CLS` in a subclass to indicate which class(es) of the inputs the pair should support.
  2113. """
  2114. CLS: Union[Type, Tuple[Type, ...]]
  2115. TYPE_NAME: Optional[str] = None
  2116. def __init__(self, actual, expected, **other_parameters):
  2117. self._check_inputs_isinstance(actual, expected, cls=self.CLS)
  2118. super().__init__(actual, expected, **other_parameters)
  2119. def compare(self):
  2120. test_case = unittest.TestCase()
  2121. try:
  2122. return test_case.assertEqual(self.actual, self.expected)
  2123. except test_case.failureException as error:
  2124. msg = str(error)
  2125. type_name = self.TYPE_NAME or (self.CLS if isinstance(self.CLS, type) else self.CLS[0]).__name__
  2126. self._fail(AssertionError, f"{type_name.title()} comparison failed: {msg}")
  2127. class StringPair(UnittestPair):
  2128. CLS = (str, bytes)
  2129. TYPE_NAME = "string"
  2130. class SetPair(UnittestPair):
  2131. CLS = set
  2132. class TypePair(UnittestPair):
  2133. CLS = type
  2134. class ObjectPair(UnittestPair):
  2135. CLS = object
  2136. # This implements a variant of assertRaises/assertRaisesRegex where we first test
  2137. # if the exception is NotImplementedError, and if so just skip the test instead
  2138. # of failing it.
  2139. #
  2140. # This is implemented by inheriting from the (private) implementation of
  2141. # assertRaises from unittest.case, and slightly tweaking it for this new
  2142. # behavior. The year is 2021: this private class hierarchy hasn't changed since
  2143. # 2010, seems low risk to inherit from.
  2144. class AssertRaisesContextIgnoreNotImplementedError(unittest.case._AssertRaisesContext):
  2145. def __exit__(self, exc_type, exc_value, tb):
  2146. if exc_type is not None and issubclass(exc_type, NotImplementedError):
  2147. self.test_case.skipTest(f"not_implemented: {exc_value}") # type: ignore[attr-defined]
  2148. return super().__exit__(exc_type, exc_value, tb)
  2149. @contextmanager
  2150. def set_warn_always_context(new_val: bool):
  2151. old_val = torch.is_warn_always_enabled()
  2152. torch.set_warn_always(new_val)
  2153. try:
  2154. yield
  2155. finally:
  2156. torch.set_warn_always(old_val)
  2157. class NoTest:
  2158. # causes pytest to not recognize this class as a test
  2159. __test__ = False
  2160. class TestCase(expecttest.TestCase):
  2161. # NOTE: "precision" lets classes and generated tests set minimum
  2162. # atol values when comparing tensors. Used by @precisionOverride and @toleranceOverride, for
  2163. # example.
  2164. # NOTE: "rel_tol" lets classes and generated tests set minimum
  2165. # rtol values when comparing tensors. Used by @toleranceOverride, for example.
  2166. _precision: float = 0
  2167. _rel_tol: float = 0
  2168. # Toggles whether to assert that `torch.get_default_dtype()` returns
  2169. # `torch.float` when `setUp` and `tearDown` are called.
  2170. _default_dtype_check_enabled: bool = False
  2171. # Always use difflib to print diffs on multi line equality.
  2172. # Undocumented feature in unittest
  2173. _diffThreshold = sys.maxsize
  2174. maxDiff = None
  2175. # checker to early terminate test suite if unrecoverable failure occurs.
  2176. def _should_stop_test_suite(self):
  2177. if torch.cuda.is_initialized():
  2178. # CUDA device side error will cause subsequence test cases to fail.
  2179. # stop entire test suite if catches RuntimeError during torch.cuda.synchronize().
  2180. try:
  2181. torch.cuda.synchronize()
  2182. except RuntimeError as rte:
  2183. print("TEST SUITE EARLY TERMINATION due to torch.cuda.synchronize() failure", file=sys.stderr)
  2184. print(str(rte), file=sys.stderr)
  2185. return True
  2186. return False
  2187. else:
  2188. return False
  2189. @property
  2190. def precision(self) -> float:
  2191. return self._precision
  2192. @precision.setter
  2193. def precision(self, prec: float) -> None:
  2194. self._precision = prec
  2195. @property
  2196. def rel_tol(self) -> float:
  2197. return self._rel_tol
  2198. @rel_tol.setter
  2199. def rel_tol(self, prec: float) -> None:
  2200. self._rel_tol = prec
  2201. _do_cuda_memory_leak_check = False
  2202. _do_cuda_non_default_stream = False
  2203. # When True, if a test case raises a NotImplementedError, instead of failing
  2204. # the test, skip it instead.
  2205. _ignore_not_implemented_error = False
  2206. def __init__(self, method_name='runTest', methodName='runTest'):
  2207. # methodName is the correct naming in unittest and testslide uses keyword arguments.
  2208. # So we need to use both to 1) not break BC and, 2) support testslide.
  2209. if methodName != "runTest":
  2210. method_name = methodName
  2211. super().__init__(method_name)
  2212. test_method = getattr(self, method_name, None)
  2213. if test_method is not None:
  2214. # Wraps the tested method if we should do CUDA memory check.
  2215. if TEST_CUDA_MEM_LEAK_CHECK: # noqa: F821
  2216. self._do_cuda_memory_leak_check &= getattr(test_method, '_do_cuda_memory_leak_check', True)
  2217. # FIXME: figure out the flaky -1024 anti-leaks on windows. See #8044
  2218. if self._do_cuda_memory_leak_check and not IS_WINDOWS:
  2219. self.wrap_with_cuda_policy(method_name, self.assertLeaksNoCudaTensors)
  2220. # Wraps the tested method if we should enforce non default CUDA stream.
  2221. self._do_cuda_non_default_stream &= getattr(test_method, '_do_cuda_non_default_stream', True)
  2222. if self._do_cuda_non_default_stream and not IS_WINDOWS:
  2223. self.wrap_with_cuda_policy(method_name, self.enforceNonDefaultStream)
  2224. if self._ignore_not_implemented_error:
  2225. self.wrap_with_policy(method_name, lambda: skip_exception_type(NotImplementedError))
  2226. if PRINT_REPRO_ON_FAILURE: # noqa: F821
  2227. env_var_prefix = TestEnvironment.repro_env_var_prefix()
  2228. try:
  2229. def _get_rel_test_path(abs_test_path):
  2230. # Attempt to get relative path based on the "test" dir.
  2231. # In CI, the working dir is not guaranteed to be the base repo dir so
  2232. # we can't just compute relative path from that.
  2233. parts = Path(abs_test_path).parts
  2234. for i, part in enumerate(parts):
  2235. if part == "test":
  2236. base_dir = os.path.join(*parts[:i]) if i > 0 else ''
  2237. return os.path.relpath(abs_test_path, start=base_dir)
  2238. # Can't determine containing dir; just return the test filename.
  2239. # The path isn't strictly correct but it's arguably better than nothing.
  2240. return os.path.split(abs_test_path)[1]
  2241. # NB: In Python 3.8, the getfile() call will return a path relative
  2242. # to the working directory, so convert that to absolute.
  2243. abs_test_path = os.path.abspath(inspect.getfile(type(self)))
  2244. test_filename = _get_rel_test_path(abs_test_path)
  2245. class_name = type(self).__name__
  2246. repro_str = f"""
  2247. To execute this test, run the following from the base repo dir:
  2248. {env_var_prefix} python {test_filename} -k {class_name}.{method_name}
  2249. This message can be suppressed by setting PYTORCH_PRINT_REPRO_ON_FAILURE=0"""
  2250. self.wrap_with_policy(
  2251. method_name,
  2252. lambda repro_str=repro_str: print_repro_on_failure(repro_str=repro_str))
  2253. except Exception as e:
  2254. # Don't fail entirely if we can't get the test filename
  2255. log.info("could not print repro string", extra=str(e))
  2256. def assertLeaksNoCudaTensors(self, name=None):
  2257. name = self.id() if name is None else name
  2258. return CudaMemoryLeakCheck(self, name)
  2259. def enforceNonDefaultStream(self):
  2260. return CudaNonDefaultStream()
  2261. def assertExpectedInline(self, actual, expect, skip=0):
  2262. return super().assertExpectedInline(actual if isinstance(actual, str) else str(actual), expect, skip + 1)
  2263. # Munges exceptions that internally contain stack traces, using munge_exc
  2264. def assertExpectedInlineMunged(
  2265. self, exc_type, callable, expect, *, suppress_suffix=True
  2266. ):
  2267. try:
  2268. callable()
  2269. except exc_type as e:
  2270. self.assertExpectedInline(
  2271. munge_exc(e, suppress_suffix=suppress_suffix, skip=1), expect, skip=1
  2272. )
  2273. return
  2274. self.fail(msg="Did not raise when expected to")
  2275. def assertLogs(self, logger=None, level=None):
  2276. if logger is None:
  2277. logger = logging.getLogger("torch")
  2278. return super().assertLogs(logger, level)
  2279. def assertNoLogs(self, logger=None, level=None):
  2280. if logger is None:
  2281. logger = logging.getLogger("torch")
  2282. return super().assertNoLogs(logger, level)
  2283. def wrap_with_cuda_policy(self, method_name, policy):
  2284. test_method = getattr(self, method_name)
  2285. # the import below may initialize CUDA context, so we do it only if
  2286. # self._do_cuda_memory_leak_check or self._do_cuda_non_default_stream
  2287. # is True.
  2288. # TODO: sure looks like we unconditionally initialize the context here
  2289. # -- ezyang
  2290. from torch.testing._internal.common_cuda import TEST_CUDA
  2291. fullname = self.id().lower() # class_name.method_name
  2292. if TEST_CUDA and ('gpu' in fullname or 'cuda' in fullname):
  2293. setattr(self, method_name, self.wrap_method_with_policy(test_method, policy))
  2294. def wrap_with_policy(self, method_name, policy):
  2295. test_method = getattr(self, method_name)
  2296. setattr(self, method_name, self.wrap_method_with_policy(test_method, policy))
  2297. # A policy is a zero-argument function that returns a context manager.
  2298. # We don't take the context manager directly as it may be necessary to
  2299. # construct it once per test method
  2300. def wrap_method_with_policy(self, method, policy):
  2301. # Assumes that `method` is the tested function in `self`.
  2302. # NOTE: Python Exceptions (e.g., unittest.Skip) keeps objects in scope
  2303. # alive, so this cannot be done in setUp and tearDown because
  2304. # tearDown is run unconditionally no matter whether the test
  2305. # passes or not. For the same reason, we can't wrap the `method`
  2306. # call in try-finally and always do the check.
  2307. @wraps(method)
  2308. def wrapper(self, *args, **kwargs):
  2309. with policy():
  2310. method(*args, **kwargs)
  2311. return types.MethodType(wrapper, self)
  2312. def wrap_with_cuda_memory_check(self, method):
  2313. return self.wrap_method_with_policy(method, self.assertLeaksNoCudaTensors)
  2314. def _run_custom(self, result=None):
  2315. using_unittest = isinstance(result, unittest.TestResult)
  2316. super_run = super().run
  2317. test_cls = super_run.__self__
  2318. # Are we compiling?
  2319. compiled = TEST_WITH_TORCHDYNAMO or TEST_WITH_AOT_EAGER or TEST_WITH_TORCHINDUCTOR # noqa: F821
  2320. # Is the class strict and compiling?
  2321. strict_default = False
  2322. if compiled:
  2323. try:
  2324. path = inspect.getfile(type(test_cls))
  2325. full_path = os.path.abspath(path)
  2326. match = re.match(r".*/test/(.*).py", full_path)
  2327. if match is not None:
  2328. filename = match.group(1)
  2329. if TEST_WITH_TORCHINDUCTOR: # noqa: F821
  2330. from .dynamo_test_failures import FIXME_inductor_non_strict
  2331. strict_default = filename not in FIXME_inductor_non_strict
  2332. else:
  2333. strict_default = True
  2334. # inspect.getfile can fail with these
  2335. except (OSError, TypeError):
  2336. pass
  2337. if "STRICT_DEFAULT" in os.environ:
  2338. if os.environ["STRICT_DEFAULT"] == "1":
  2339. strict_default = True
  2340. strict_mode = False
  2341. if compiled:
  2342. test_method = getattr(self, self._testMethodName)
  2343. if hasattr(test_method, "dynamo_strict"):
  2344. strict_mode = test_method.dynamo_strict
  2345. elif hasattr(test_cls, "dynamo_strict"):
  2346. strict_mode = test_cls.dynamo_strict
  2347. else:
  2348. strict_mode = strict_default
  2349. nopython = getattr(test_cls, "dynamo_strict_nopython", False) and compiled
  2350. if strict_mode:
  2351. torch._dynamo.reset()
  2352. # TODO: Remove this; this is grandfathered in because we suppressed errors
  2353. # on test suite previously
  2354. # When strict mode is False, suppress_errors is True
  2355. if compiled:
  2356. suppress_errors = not strict_mode
  2357. else:
  2358. suppress_errors = torch._dynamo.config.suppress_errors
  2359. with unittest.mock.patch("torch._dynamo.config.suppress_errors", suppress_errors):
  2360. if TEST_WITH_TORCHINDUCTOR: # noqa: F821
  2361. super_run = torch._dynamo.optimize("inductor")(super_run)
  2362. elif TEST_WITH_AOT_EAGER: # noqa: F821
  2363. super_run = torch._dynamo.optimize("aot_eager_decomp_partition")(super_run)
  2364. elif TEST_WITH_TORCHDYNAMO: # noqa: F821
  2365. # TorchDynamo optimize annotation
  2366. # Assume eager-generated GraphModules will not error out.
  2367. # If we do, this is probably a Dynamo bug!
  2368. super_run = torch._dynamo.optimize("eager_noexcept", nopython=nopython)(super_run)
  2369. key = f"{self.__class__.__name__}.{self._testMethodName}"
  2370. from .dynamo_test_failures import dynamo_expected_failures, dynamo_skips
  2371. def expect_failure(f, test_name):
  2372. @wraps(f)
  2373. def wrapper(*args, **kwargs):
  2374. try:
  2375. f(*args, **kwargs)
  2376. except BaseException as e:
  2377. self.skipTest(e)
  2378. raise RuntimeError(f"Unexpected success, please remove `test/dynamo_expected_failures/{test_name}`")
  2379. return wrapper
  2380. if key in dynamo_expected_failures:
  2381. method = getattr(self, self._testMethodName)
  2382. setattr(self, self._testMethodName, expect_failure(method, key))
  2383. def ignore_failure(f, test_name):
  2384. @wraps(f)
  2385. def wrapper(*args, **kwargs):
  2386. try:
  2387. f(*args, **kwargs)
  2388. except BaseException as e:
  2389. self.skipTest(e)
  2390. method = getattr(self, self._testMethodName)
  2391. if getattr(method, "__unittest_expecting_failure__", False):
  2392. self.skipTest("unexpected success")
  2393. else:
  2394. self.skipTest(f"This test passed, maybe we can remove `test/dynamo_skips/{test_name}`")
  2395. return wrapper
  2396. if key in dynamo_skips:
  2397. method = getattr(self, self._testMethodName)
  2398. setattr(self, self._testMethodName, ignore_failure(method, key))
  2399. super_run(result=result)
  2400. if strict_mode:
  2401. torch._dynamo.reset()
  2402. # Early terminate test if necessary. If using pytest, use the -x flag instead
  2403. if using_unittest and self._should_stop_test_suite():
  2404. if result.wasSuccessful():
  2405. case = TestCase()
  2406. if TEST_SAVE_XML is not None:
  2407. # This is a big hacky, XMLRunner modifies expected type from TestCase to TestInfo
  2408. # Create dummy TestInfo to record results correctly
  2409. from xmlrunner.result import _TestInfo # type: ignore[import]
  2410. case = _TestInfo(result, case)
  2411. case.output = _TestInfo.ERROR
  2412. case.elapsed_time = 0.0
  2413. case.test_description = "TestSuiteEarlyFailure"
  2414. # This shouldn't really happen, but if does add fake failure
  2415. # For more details see https://github.com/pytorch/pytorch/issues/71973
  2416. result.failures.append((case, "TestSuite execution was aborted early"))
  2417. assert result.wasSuccessful() is False
  2418. result.stop()
  2419. def run(self, result=None):
  2420. with contextlib.ExitStack() as stack:
  2421. if TEST_WITH_CROSSREF: # noqa: F821
  2422. stack.enter_context(CrossRefMode())
  2423. self._run_custom(
  2424. result=result,
  2425. )
  2426. def setUp(self):
  2427. check_if_enable(self)
  2428. set_rng_seed(SEED)
  2429. # Save global check sparse tensor invariants state that can be
  2430. # restored from tearDown:
  2431. self._check_invariants = torch.sparse.check_sparse_tensor_invariants.is_enabled()
  2432. # Enable invariant checks for all sparse tensors constructions
  2433. # including the unsafe ones. If this is not desired for some
  2434. # test case, use check_invariants=False optional argument to
  2435. # sparse tensor constructors or
  2436. # @torch.sparse.check_sparse_tensor_invariants(False)
  2437. # decorator to disable the invariant checks.
  2438. torch.sparse.check_sparse_tensor_invariants.enable()
  2439. if self._default_dtype_check_enabled:
  2440. assert torch.get_default_dtype() == torch.float
  2441. # attempt to reset some global state at the end of the test
  2442. self._prev_grad_state = torch.is_grad_enabled()
  2443. def tearDown(self):
  2444. # There exists test cases that override TestCase.setUp
  2445. # definition, so we cannot assume that _check_invariants
  2446. # attribute is defined in general.
  2447. if hasattr(self, '_check_invariants'):
  2448. # Restore the global check sparse tensor invariants state
  2449. if self._check_invariants:
  2450. torch.sparse.check_sparse_tensor_invariants.enable()
  2451. else:
  2452. torch.sparse.check_sparse_tensor_invariants.disable()
  2453. if self._default_dtype_check_enabled:
  2454. assert torch.get_default_dtype() == torch.float
  2455. # attribute may not be defined, per above
  2456. if hasattr(self, '_prev_grad_state'):
  2457. torch.set_grad_enabled(self._prev_grad_state)
  2458. @staticmethod
  2459. def _make_crow_indices(n_rows, n_cols, nnz,
  2460. *, device, dtype, random=True):
  2461. """Return crow_indices of a CSR tensor with size (n_rows, n_cols) and
  2462. the number of specified elements nnz.
  2463. If random is True, the column counts of rows are in random
  2464. order. Otherwise, the column counts of rows are defined by the
  2465. used sampling method.
  2466. Sampling method
  2467. ---------------
  2468. The used sampling method was introduced in
  2469. https://pearu.github.io/csr_sampling.html, and here we give
  2470. only an overall description of the method.
  2471. Notice that crow_indices can be defined as cumsum(counts)
  2472. where counts is a sequence of non-negative integers satisfying
  2473. the following conditions:
  2474. len(counts) == n_rows + 1
  2475. counts.max() <= n_cols
  2476. while counts[i + 1] is interpreted as the number of specified
  2477. elements in the i-th row.
  2478. The used sampling method aims at increasing the diversity of
  2479. CSR samples, that is, a CSR sample should contain (i) rows
  2480. that are all filled, (ii) rows with no elements at all, and
  2481. (iii) rows that are partially filled. At the same time and for
  2482. the given total number of specified elements (nnz), there
  2483. should be minimal preference to rows with a given number of
  2484. elements. To achieve this, the sampling method is built-up on
  2485. using a sawteeth model for counts. In the simplest case, we
  2486. would have
  2487. counts = arange(n_rows + 1) % (n_cols + 1)
  2488. that has equal number of all possible column counts per row.
  2489. This formula can be used only for specific input values of
  2490. n_rows, n_cols, and nnz. To generalize this model to any
  2491. combinations of inputs, the counts model above is extended
  2492. with an incomplete sawtooth, and the right and lower
  2493. rectangular parts that will guarantee that
  2494. counts.sum() == nnz
  2495. for any combination of n_rows, n_cols, and nnz. Basically,
  2496. we'll find a maximal window in (n_rows + 1, n_cols + 1)-grid
  2497. that is able to hold a sequence of sawteeth and so-called
  2498. final correction, while the external part of the window is
  2499. filled with counts to meet the nnz constraint exactly.
  2500. """
  2501. assert 0 <= nnz <= n_rows * n_cols, (nnz, n_rows, n_cols)
  2502. def sawteeth(n, m):
  2503. # return the total number of counts in the sequence of
  2504. # sawteeth where n and m define a window in (n_rows+1,
  2505. # n_cols+1) rectangle where the sequence of sawteeth
  2506. # perfectly fit.
  2507. M = (n_cols - m) * (n_cols - m + 1) // 2
  2508. K = (n_rows - n) % (n_cols - m + 1)
  2509. return M * ((n_rows - n) // (n_cols - m + 1)) + K * (K - 1) // 2
  2510. # Different from the original method description, here counts
  2511. # has leading 0 required by crow_indices:
  2512. counts = torch.zeros(n_rows + 1, dtype=dtype, device=torch.device('cpu'))
  2513. n = m = 0
  2514. N = sawteeth(n, m)
  2515. if N and nnz >= max(N, n_cols):
  2516. # determine the width of the sawteeth window. We use bisection to solve
  2517. # N(n, 0) == 0 or nnz - n * n_cols < max(N(n, 0), n_cols)
  2518. # for n
  2519. n_left = n
  2520. n_right = n_rows - 1
  2521. N_right = sawteeth(n_right, m)
  2522. while n_right - n_left > 1:
  2523. n_middle = (n_left + n_right) // 2
  2524. N_middle = sawteeth(n_middle, m)
  2525. if N_middle == 0 or nnz - n_middle * n_cols < max(N_middle, n_cols):
  2526. n_right, N_right = n_middle, N_middle
  2527. else:
  2528. n_left = n_middle
  2529. n, N = n_right, N_right
  2530. # fill the right rectangle with counts:
  2531. assert n
  2532. counts[-n:].fill_(n_cols)
  2533. if N and nnz - n * n_cols >= max(N, n_rows - n):
  2534. # determine the height of the sawteeth window. We use bisection to solve
  2535. # N(n, m) == 0 or nnz - n * n_cols - m * (n_rows - n) < max(N(n, m), n_rows - n)
  2536. # for m.
  2537. m_left = m
  2538. m_right = n_cols - 1
  2539. N_right = sawteeth(n, m_right)
  2540. while m_right - m_left > 1:
  2541. m_middle = (m_left + m_right) // 2
  2542. N_middle = sawteeth(n, m_middle)
  2543. if N_middle == 0 or nnz - n * n_cols - m_middle * (n_rows - n) < max(N_middle, n_rows - n):
  2544. m_right, N_right = m_middle, N_middle
  2545. else:
  2546. m_left = m_middle
  2547. m, N = m_right, N_right
  2548. # fill the bottom rectangle with counts:
  2549. assert m
  2550. counts[1:n_rows - n + 1].fill_(m)
  2551. if N:
  2552. # fill the sawteeth window with counts
  2553. q, r = divmod(nnz - n * n_cols - m * (n_rows - n),
  2554. (n_cols - m) * (n_cols - m + 1) // 2)
  2555. p = 1 + q * (n_cols - m + 1)
  2556. k = math.isqrt(2 * r)
  2557. if k * (k + 1) > 2 * r:
  2558. k -= 1
  2559. corr = r - k * (k + 1) // 2
  2560. assert not ((p > 1) and (m > 0)) # full sawteeth are never on top of a bottom rectangle
  2561. # sequence of full sawteeth:
  2562. counts[1:p] = torch.arange(p - 1, dtype=dtype, device=counts.device) % (n_cols - m + 1)
  2563. # incomplete sawtooth:
  2564. counts[p:p + k + 1] += torch.arange(k + 1, dtype=dtype, device=counts.device)
  2565. else:
  2566. # given input does not support sawteeth
  2567. p = 1
  2568. corr = nnz - n * n_cols - m * (n_rows - n)
  2569. # correction that will guarantee counts.sum() == nnz:
  2570. counts[p] += corr
  2571. if random:
  2572. # randomize crow_indices by shuffling the sawteeth
  2573. # sequence:
  2574. perm = torch.randperm(n_rows, device=counts.device)
  2575. counts[1:] = counts[1:][perm]
  2576. # compute crow_indices:
  2577. crow_indices = counts
  2578. crow_indices.cumsum_(dim=0)
  2579. return crow_indices.to(device=device)
  2580. def genSparseCompressedTensor(self, size, nnz, *, layout, device, dtype, index_dtype, blocksize=(), dense_dims=0):
  2581. from operator import mul
  2582. from functools import reduce
  2583. sparse_dim = 2
  2584. assert all(size[d] > 0 for d in range(len(size))) or nnz == 0, 'invalid arguments'
  2585. assert len(size) >= sparse_dim
  2586. if blocksize:
  2587. assert len(blocksize) == 2, (size, blocksize)
  2588. assert size[-2 - dense_dims] % blocksize[0] == 0, (size, blocksize)
  2589. assert size[-1 - dense_dims] % blocksize[1] == 0, (size, blocksize)
  2590. blocksize0, blocksize1 = blocksize
  2591. else:
  2592. blocksize0 = blocksize1 = 1
  2593. size = tuple(size)
  2594. dense_size = size[(len(size) - dense_dims):]
  2595. def random_sparse_compressed(n_compressed_dims, n_plain_dims, nnz):
  2596. compressed_indices = self._make_crow_indices(n_compressed_dims, n_plain_dims, nnz, device=device, dtype=index_dtype)
  2597. plain_indices = torch.zeros(nnz, dtype=index_dtype, device=device)
  2598. for i in range(n_compressed_dims):
  2599. count = compressed_indices[i + 1] - compressed_indices[i]
  2600. plain_indices[compressed_indices[i]:compressed_indices[i + 1]], _ = torch.sort(
  2601. torch.randperm(n_plain_dims, dtype=index_dtype, device=device)[:count])
  2602. low = -1 if dtype != torch.uint8 else 0
  2603. high = 1 if dtype != torch.uint8 else 2
  2604. values = make_tensor((nnz,) + blocksize + dense_size, device=device, dtype=dtype, low=low, high=high)
  2605. return values, compressed_indices, plain_indices
  2606. batch_shape = size[:-2 - dense_dims]
  2607. n_batch = reduce(mul, batch_shape, 1)
  2608. if layout in {torch.sparse_csr, torch.sparse_bsr}:
  2609. n_compressed_dims, n_plain_dims = size[-2 - dense_dims] // blocksize0, size[-1 - dense_dims] // blocksize1
  2610. else:
  2611. n_compressed_dims, n_plain_dims = size[-1 - dense_dims] // blocksize1, size[-2 - dense_dims] // blocksize0
  2612. blocknnz = nnz // (blocksize0 * blocksize1)
  2613. sparse_tensors = [random_sparse_compressed(n_compressed_dims, n_plain_dims, blocknnz) for _ in range(n_batch)]
  2614. sparse_tensors_it = map(list, zip(*sparse_tensors))
  2615. values = torch.stack(next(sparse_tensors_it)).reshape(*batch_shape, blocknnz, *blocksize, *dense_size)
  2616. compressed_indices = torch.stack(next(sparse_tensors_it)).reshape(*batch_shape, -1)
  2617. plain_indices = torch.stack(next(sparse_tensors_it)).reshape(*batch_shape, -1)
  2618. return torch.sparse_compressed_tensor(compressed_indices, plain_indices,
  2619. values, size=size, dtype=dtype, layout=layout, device=device)
  2620. def genSparseCSRTensor(self, size, nnz, *, device, dtype, index_dtype, dense_dims=0):
  2621. return self.genSparseCompressedTensor(size, nnz, layout=torch.sparse_csr, device=device,
  2622. dtype=dtype, index_dtype=index_dtype, blocksize=(), dense_dims=dense_dims)
  2623. def genSparseCSCTensor(self, size, nnz, *, device, dtype, index_dtype, dense_dims=0):
  2624. return self.genSparseCompressedTensor(size, nnz, layout=torch.sparse_csc, device=device,
  2625. dtype=dtype, index_dtype=index_dtype, blocksize=(), dense_dims=0)
  2626. def genSparseBSRTensor(self, size, blocksize, nnz, *, device, dtype, index_dtype, dense_dims=0):
  2627. assert len(blocksize) == 2
  2628. return self.genSparseCompressedTensor(size, nnz, layout=torch.sparse_bsr, device=device,
  2629. dtype=dtype, index_dtype=index_dtype, blocksize=blocksize, dense_dims=dense_dims)
  2630. def genSparseBSCTensor(self, size, blocksize, nnz, *, device, dtype, index_dtype, dense_dims=0):
  2631. assert len(blocksize) == 2
  2632. return self.genSparseCompressedTensor(size, nnz, layout=torch.sparse_bsc, device=device,
  2633. dtype=dtype, index_dtype=index_dtype, blocksize=blocksize, dense_dims=dense_dims)
  2634. def genSparseTensor(self, size, sparse_dim, nnz, is_uncoalesced, device, dtype):
  2635. # Assert not given impossible combination, where the sparse dims have
  2636. # empty numel, but nnz > 0 makes the indices containing values.
  2637. assert all(size[d] > 0 for d in range(sparse_dim)) or nnz == 0, 'invalid arguments'
  2638. v_size = [nnz] + list(size[sparse_dim:])
  2639. v = make_tensor(v_size, device=device, dtype=dtype, low=-1, high=1)
  2640. i = torch.rand(sparse_dim, nnz, device=device)
  2641. i.mul_(torch.tensor(size[:sparse_dim]).unsqueeze(1).to(i))
  2642. i = i.to(torch.long)
  2643. if is_uncoalesced:
  2644. i1 = i[:, :(nnz // 2), ...]
  2645. i2 = i[:, :((nnz + 1) // 2), ...]
  2646. i = torch.cat([i1, i2], 1)
  2647. x = torch.sparse_coo_tensor(i, v, torch.Size(size), dtype=dtype, device=device)
  2648. if not is_uncoalesced:
  2649. x = x.coalesce()
  2650. else:
  2651. # FIXME: `x` is a sparse view of `v`. Currently rebase_history for
  2652. # sparse views is not implemented, so this workaround is
  2653. # needed for inplace operations done on `x`, e.g., copy_().
  2654. # Remove after implementing something equivalent to CopySlice
  2655. # for sparse views.
  2656. # NOTE: We do clone() after detach() here because we need to be able to change size/storage of x afterwards
  2657. x = x.detach().clone()._coalesced_(False)
  2658. return x, x._indices().clone(), x._values().clone()
  2659. def generate_simple_inputs(self, layout,
  2660. device=None,
  2661. dtype=None,
  2662. index_dtype=None,
  2663. enable_batch=True,
  2664. enable_hybrid=True,
  2665. enable_zero_sized=True,
  2666. enable_non_contiguous_indices=True,
  2667. enable_non_contiguous_values=True,
  2668. enable_batch_variable_nse=False,
  2669. output_tensor=True,
  2670. patterns=None):
  2671. """Generator of simple inputs for tensor constructors of the given layout.
  2672. The generated tensor inputs have the following properties:
  2673. - tensor shapes are minimal but not trivial
  2674. - tensor values are sorted sequences for COO and CSR formats, e.g. [1, 2, 3, 4]
  2675. - the generated tensors represent the same mathematical tensor for all layouts
  2676. - the generated tensors include regular, zero-sized, and optionally, batched or/and hybrid tensors.
  2677. - the generated tensors include contiguous or non-contiguous tensors both in indices and values
  2678. If output_tensor is True, yield tensors with the given
  2679. layout. Otherwise, yield inputs to the corresponding tensor
  2680. constructors:
  2681. - sparse compressed input is defined as
  2682. (compressed_indices, plain_indices, values), dict(size=expected_size_from_shape_inference, device=device, dtype=dtype)
  2683. - sparse COO input is defined as
  2684. (indices, values), dict(size=expected_size_from_shape_inference, device=device, dtype=dtype)
  2685. - strided input is defined as
  2686. (values,), dict(device=device, dtype=dtype)
  2687. """
  2688. if index_dtype is None:
  2689. index_dtype = torch.int64
  2690. is_compressed_sparse_layout = layout in {torch.sparse_csr, torch.sparse_csc, torch.sparse_bsr, torch.sparse_bsc}
  2691. if output_tensor:
  2692. for args, kwargs in self.generate_simple_inputs(layout, device=device, dtype=dtype, index_dtype=index_dtype,
  2693. enable_batch=enable_batch, enable_hybrid=enable_hybrid,
  2694. enable_zero_sized=enable_zero_sized,
  2695. enable_non_contiguous_indices=enable_non_contiguous_indices,
  2696. enable_non_contiguous_values=enable_non_contiguous_values,
  2697. enable_batch_variable_nse=enable_batch_variable_nse,
  2698. output_tensor=False):
  2699. if layout is torch.strided:
  2700. assert len(args) == 1
  2701. size = kwargs.pop('size', None) # to ensure that a zero-sized tensor has the desired shape
  2702. assert size is not None
  2703. yield args[0].reshape(size)
  2704. elif layout is torch.sparse_coo:
  2705. yield torch.sparse_coo_tensor(*args, **kwargs)
  2706. elif is_compressed_sparse_layout:
  2707. kwargs.update(layout=layout)
  2708. yield torch.sparse_compressed_tensor(*args, **kwargs)
  2709. else:
  2710. assert 0 # unreachable
  2711. return
  2712. def get_blockpattern(pattern, blocksize):
  2713. basesize = pattern.shape
  2714. assert basesize[0] % blocksize[0] == 0, (basesize, blocksize)
  2715. assert basesize[1] % blocksize[1] == 0, (basesize, blocksize)
  2716. blockpattern = pattern.reshape(-1,
  2717. blocksize[0],
  2718. basesize[1] // blocksize[1],
  2719. blocksize[1]).transpose(-3, -2).any(-1).any(-1)
  2720. block_ids = torch.arange(1, blockpattern.numel() + 1).reshape(blockpattern.shape)
  2721. return (blockpattern != 0) * block_ids
  2722. def get_sparse_data(pattern):
  2723. basesize = pattern.shape
  2724. assert len(basesize) == 2, basesize # pattern is expected to be a matrix
  2725. # We cannot use `torch.sparse_xyz_tensor(pattern)` to
  2726. # compute the sparse layout indices and values because
  2727. # generate_simple_inputs is used to generate the inputs to
  2728. # test `torch.sparse_xyz_tensor` factory functions, so
  2729. # we'll compute the indices and values independently of
  2730. # the factory functions.
  2731. indices = torch.where(pattern != 0)
  2732. coo_indices = torch.stack(indices)
  2733. crow_indices = torch.zeros(basesize[0] + 1, dtype=torch.int64)
  2734. crow_indices[1:] = torch.cumsum(coo_indices[0].bincount(minlength=basesize[0]), 0)
  2735. col_indices = coo_indices[1]
  2736. strided_values = torch.zeros(basesize, dtype=torch.int64)
  2737. # the property of `values == range(1, 1+nnz)` is used in
  2738. # get_sparse_data_with_block to relate BSR and BSC values,
  2739. # so, don't change the following line:
  2740. values = torch.arange(1, 1 + len(indices[0]), dtype=torch.int64)
  2741. strided_values[indices] = values
  2742. indices_T = torch.where(pattern.transpose(0, 1) != 0)
  2743. coo_indices_T = torch.stack(indices_T)
  2744. ccol_indices = torch.zeros(basesize[1] + 1, dtype=torch.int64)
  2745. ccol_indices[1:] = torch.cumsum(coo_indices_T[0].bincount(minlength=basesize[1]), 0)
  2746. row_indices = coo_indices_T[1]
  2747. csc_values = strided_values.transpose(0, 1)[indices_T]
  2748. return {torch.sparse_coo: (coo_indices, values),
  2749. torch.sparse_csr: (crow_indices, col_indices, values),
  2750. torch.sparse_csc: (ccol_indices, row_indices, csc_values),
  2751. torch.strided: (strided_values,)}
  2752. def get_sparse_data_with_block(pattern, blocksize):
  2753. nonblock_data = get_sparse_data(pattern)
  2754. blockpattern = get_blockpattern(pattern, blocksize)
  2755. block_data = get_sparse_data(blockpattern)
  2756. strided_values = nonblock_data[torch.strided][0]
  2757. block_indices = block_data[torch.sparse_coo][0]
  2758. bsr_values = torch.stack([strided_values[bi * blocksize[0]:(bi + 1) * blocksize[0],
  2759. bj * blocksize[1]:(bj + 1) * blocksize[1]]
  2760. for bi, bj in block_indices.transpose(0, 1)])
  2761. # here we use the property `values == range(1, 1+nnz)` and
  2762. # `values` relation to `csc_values` (see get_sparse_data)
  2763. # to get BSC blocks via reordering the BSR blocks:
  2764. bsc_values = bsr_values[block_data[torch.sparse_csc][2] - 1]
  2765. return {torch.sparse_bsr: (*block_data[torch.sparse_csr][:2], bsr_values),
  2766. torch.sparse_bsc: (*block_data[torch.sparse_csc][:2], bsc_values),
  2767. **nonblock_data}
  2768. def get_batch_sparse_data(pattern, blocksize):
  2769. size = pattern.shape
  2770. if len(size) <= 2: # non-batch
  2771. return get_sparse_data_with_block(pattern, blocksize)
  2772. # batch data is created recursively:
  2773. batch_data = {}
  2774. for i, item in enumerate(pattern):
  2775. for layout, d in get_batch_sparse_data(item, blocksize).items():
  2776. target = batch_data.get(layout)
  2777. if layout is torch.sparse_coo:
  2778. # a "batch COO" means a COO with the leading
  2779. # sparse dimensions interpreted as batch
  2780. # dimensions
  2781. ext_coo_indices1 = torch.cat((torch.full((1, len(d[1])), i, dtype=torch.int64), d[0]))
  2782. if target is None:
  2783. target = batch_data[layout] = (ext_coo_indices1, d[1])
  2784. else:
  2785. target[0].set_(torch.cat((target[0], ext_coo_indices1), 1))
  2786. target[1].set_(torch.cat((target[1], d[1])))
  2787. else:
  2788. if target is None:
  2789. target = batch_data[layout] = tuple(d[j].unsqueeze(0) for j in range(len(d)))
  2790. else:
  2791. for j in range(len(d)):
  2792. target[j].set_(torch.cat((target[j], d[j].unsqueeze(0))))
  2793. return batch_data
  2794. def generate_values(base, densesize):
  2795. """Generates a tensor of shape densesize with values equal to
  2796. base + i_1 * 10^0 + ... + i_d * 10^{d - 1}
  2797. at indices i_1, ..., i_d (with 0 <= i_j < densesize[j] for any 1 <= j <=
  2798. len(densesize))
  2799. This mapping produces unique values as long as
  2800. densesize[i] < 10 for all i in range(len(densesize)).
  2801. """
  2802. if not densesize:
  2803. return base
  2804. if not isinstance(base, int) and base.ndim > 0:
  2805. return torch.stack([generate_values(b, densesize) for b in base])
  2806. if base == 0:
  2807. return torch.zeros(densesize, dtype=torch.int64)
  2808. r = torch.arange(densesize[0], dtype=torch.int64)
  2809. for i, d in enumerate(densesize[1:]):
  2810. y = torch.arange(d, dtype=torch.int64) * (10 ** (i + 1))
  2811. r = r[..., None] + y[None, ...]
  2812. r.add_(base)
  2813. return r
  2814. if patterns is None:
  2815. # A pattern is a 3-tuple with the following items:
  2816. #
  2817. # - a list of integers with the depth of two or more. The
  2818. # integers define the sparsity patterns of the generated
  2819. # inputs: zero values correspond to unspecified
  2820. # elements/blocks, and non-zero values to the specified
  2821. # elements.
  2822. #
  2823. # For debugging convenience, the elements with the same
  2824. # value typically belong to the same block. However, it
  2825. # is not a hard requirement: as long as the shape of a
  2826. # pattern divides with block sizes, the pattern will be
  2827. # a valid one.
  2828. #
  2829. # If the depth of the list is larger than two, inputs
  2830. # with batch dimensions will be generated.
  2831. #
  2832. # - a list of 2-tuples of block sizes, used to generate
  2833. # BSR/BSC tensors with various block size parameters
  2834. #
  2835. # - a list of tuples of dense dimensions, used to generate
  2836. # hybrid tensors with various dense dimensions
  2837. #
  2838. patterns = [
  2839. # a simple 3 x 2 tensor: non-hybrid, hybrid with 1 and 2 dense dimensions
  2840. ([[1, 2, 0],
  2841. [1, 0, 3]], [(2, 1), (1, 3)], [(), (2,), (4, 5)]),
  2842. # 2 x 3 batch of 3 x 2 tensors: non-hybrid and hybrid with 2 dense dimensions
  2843. ([[[[1, 2, 0],
  2844. [1, 0, 3]],
  2845. [[1, 2, 3],
  2846. [1, 0, 0]],
  2847. [[1, 0, 0],
  2848. [1, 2, 3]]],
  2849. [[[0, 2, 0],
  2850. [1, 2, 3]],
  2851. [[1, 0, 3],
  2852. [1, 2, 0]],
  2853. [[1, 2, 3],
  2854. [0, 2, 0]]]], [(2, 1), (2, 3)], [(), (2,)]),
  2855. # tensor with non-trivial blocksize
  2856. ([[0, 1, 0, 2, 0, 2],
  2857. [0, 1, 0, 0, 2, 0],
  2858. [3, 3, 3, 0, 0, 0],
  2859. [0, 0, 0, 0, 0, 0],
  2860. [0, 5, 0, 6, 6, 6],
  2861. [5, 0, 5, 6, 6, 6],
  2862. [0, 0, 0, 0, 8, 8],
  2863. [7, 7, 7, 0, 8, 8]], [(2, 3)], [(), (4, 5)]),
  2864. # batch tensor with variable NSE
  2865. # Requires https://github.com/pytorch/pytorch/pull/84843 or similar.
  2866. ([[[1, 2],
  2867. [3, 4]],
  2868. [[1, 0],
  2869. [0, 0]]], [(1, 1)], ([()] if enable_batch_variable_nse else []))]
  2870. def non_contiguous_copy(t, dim=-1, offset=0):
  2871. # return a copy of t that is non-contiguous along the
  2872. # given dimension and with the given storage offset
  2873. self.assertTrue(t.is_contiguous())
  2874. if dim < 0:
  2875. dim = dim + t.ndim
  2876. assert dim >= 0 and dim < t.ndim
  2877. step = max(2, offset + 1)
  2878. tmp = torch.zeros((*t.shape[:dim], t.shape[dim] * step, *t.shape[dim + 1:]), dtype=t.dtype, device=t.device)
  2879. dim_slices = (*((slice(None),) * dim), slice(offset, None, step))
  2880. r = tmp[dim_slices].copy_(t)
  2881. self.assertFalse(r.is_contiguous())
  2882. self.assertEqual(t, r)
  2883. return r
  2884. # the main loop of the method:
  2885. for pattern, blocksizes, densesizes in patterns:
  2886. if not enable_hybrid:
  2887. densesizes = [s for s in densesizes if not s]
  2888. if not (densesizes and blocksizes):
  2889. continue
  2890. pattern = torch.tensor(pattern, dtype=torch.int64)
  2891. if not enable_batch and pattern.ndim > 2:
  2892. continue
  2893. for blocksize in blocksizes:
  2894. data = get_batch_sparse_data(pattern, blocksize)[layout]
  2895. for densesize in densesizes:
  2896. indices = [a.to(device=device, dtype=index_dtype) for a in data[:-1]]
  2897. values = generate_values(data[-1], densesize).to(device=device, dtype=dtype)
  2898. yield (*indices, values), dict(device=device, dtype=dtype,
  2899. size=pattern.shape + densesize)
  2900. if enable_non_contiguous_indices and pattern.ndim > 2:
  2901. # sparse compressed indices can be sliced only along batch dimensions
  2902. for (dim, offset) in {(0, 1), (-2, 0)}:
  2903. indices_copy = [non_contiguous_copy(a, dim=dim, offset=offset) for a in indices]
  2904. yield (*indices_copy, values), dict(device=device, dtype=dtype,
  2905. size=pattern.shape + densesize)
  2906. if enable_non_contiguous_values:
  2907. values_copy = non_contiguous_copy(values, dim=-1, offset=1)
  2908. yield (*indices_copy, values_copy), dict(device=device, dtype=dtype,
  2909. size=pattern.shape + densesize)
  2910. if enable_non_contiguous_values:
  2911. values_copy = non_contiguous_copy(values, dim=-1, offset=1)
  2912. yield (*indices, values_copy), dict(device=device, dtype=dtype,
  2913. size=pattern.shape + densesize)
  2914. # zero-sized tensor inputs, non-batch, non-hybrid/hybrid
  2915. if enable_zero_sized:
  2916. for basesize, blocksizes, densesizes in [
  2917. ((2, 0), [(1, 2)], [(), (2,), (2, 3)] if enable_hybrid else [()]),
  2918. ((0, 2), [(1, 2), (2, 1), (3, 2)], [()]),
  2919. ((0, 0), [(1, 2)], [()]),
  2920. ]:
  2921. for blocksize in blocksizes:
  2922. for densesize in densesizes:
  2923. if layout == torch.strided:
  2924. indices = ()
  2925. values = torch.empty((basesize + densesize), device=device, dtype=dtype)
  2926. elif layout == torch.sparse_coo:
  2927. indices = (torch.empty(len(basesize), 0, device=device, dtype=index_dtype),)
  2928. values = torch.empty((0, *densesize), device=device, dtype=dtype)
  2929. elif layout == torch.sparse_csr:
  2930. crow_indices = torch.tensor([0] * (basesize[0] + 1), device=device, dtype=index_dtype)
  2931. col_indices = torch.empty(0, device=device, dtype=index_dtype)
  2932. indices = (crow_indices, col_indices)
  2933. values = torch.empty((0, *densesize), device=device, dtype=dtype)
  2934. elif layout == torch.sparse_csc:
  2935. ccol_indices = torch.tensor([0] * (basesize[1] + 1), device=device, dtype=index_dtype)
  2936. row_indices = torch.empty(0, device=device, dtype=index_dtype)
  2937. indices = (ccol_indices, row_indices)
  2938. values = torch.empty((0, *densesize), device=device, dtype=dtype)
  2939. elif layout == torch.sparse_bsr:
  2940. crow_indices = torch.tensor([0] * (basesize[0] // blocksize[0] + 1), device=device, dtype=index_dtype)
  2941. col_indices = torch.empty(0, device=device, dtype=index_dtype)
  2942. indices = (crow_indices, col_indices)
  2943. values = torch.empty((0, *blocksize, *densesize), device=device, dtype=dtype)
  2944. elif layout == torch.sparse_bsc:
  2945. ccol_indices = torch.tensor([0] * (basesize[1] // blocksize[1] + 1), device=device, dtype=index_dtype)
  2946. row_indices = torch.empty(0, device=device, dtype=index_dtype)
  2947. indices = (ccol_indices, row_indices)
  2948. values = torch.empty((0, *blocksize, *densesize), device=device, dtype=dtype)
  2949. else:
  2950. assert 0 # unreachable
  2951. yield (*indices, values), dict(device=device, dtype=dtype, size=basesize + densesize)
  2952. def safeToDense(self, t):
  2953. # coalesce is only implemented for COO
  2954. if t.layout == torch.sparse_coo:
  2955. t = t.coalesce()
  2956. return t.to_dense()
  2957. # Compares a torch function with a reference function for a given sample input (object of SampleInput)
  2958. # Note: only values are compared, type comparison is not done here
  2959. def compare_with_reference(self, torch_fn, ref_fn, sample_input, **kwargs):
  2960. numpy_sample = sample_input.numpy()
  2961. n_inp, n_args, n_kwargs = numpy_sample.input, numpy_sample.args, numpy_sample.kwargs
  2962. t_inp, t_args, t_kwargs = sample_input.input, sample_input.args, sample_input.kwargs
  2963. actual = torch_fn(t_inp, *t_args, **t_kwargs)
  2964. expected = ref_fn(n_inp, *n_args, **n_kwargs)
  2965. self.assertEqual(actual, expected, exact_device=False, **kwargs)
  2966. # Compares the given Torch and NumPy functions on the given tensor-like object.
  2967. # NOTE: both torch_fn and np_fn should be functions that take a single
  2968. # tensor (array). If the torch and/or NumPy function require additional
  2969. # arguments then wrap the function in a lambda or pass a partial function.
  2970. # TODO: add args/kwargs for passing to assertEqual (e.g. rtol, atol)
  2971. def compare_with_numpy(self, torch_fn, np_fn, tensor_like,
  2972. device=None, dtype=None, **kwargs):
  2973. assert TEST_NUMPY
  2974. if isinstance(tensor_like, torch.Tensor):
  2975. assert device is None
  2976. assert dtype is None
  2977. t_cpu = tensor_like.detach().cpu()
  2978. if t_cpu.dtype is torch.bfloat16:
  2979. t_cpu = t_cpu.float()
  2980. a = t_cpu.numpy()
  2981. t = tensor_like
  2982. else:
  2983. d = copy.copy(torch_to_numpy_dtype_dict)
  2984. d[torch.bfloat16] = np.float32
  2985. a = np.array(tensor_like, dtype=d[dtype])
  2986. t = torch.tensor(tensor_like, device=device, dtype=dtype)
  2987. np_result = np_fn(a)
  2988. torch_result = torch_fn(t).cpu()
  2989. # Converts arrays to tensors
  2990. if isinstance(np_result, np.ndarray):
  2991. try:
  2992. np_result = torch.from_numpy(np_result)
  2993. except Exception:
  2994. # NOTE: copying an array before conversion is necessary when,
  2995. # for example, the array has negative strides.
  2996. np_result = torch.from_numpy(np_result.copy())
  2997. if t.dtype is torch.bfloat16 and torch_result.dtype is torch.bfloat16 and np_result.dtype is torch.float:
  2998. torch_result = torch_result.to(torch.float)
  2999. self.assertEqual(np_result, torch_result, **kwargs)
  3000. def assertEqualIgnoreType(self, *args, **kwargs) -> None:
  3001. # If you are seeing this function used, that means test is written wrongly
  3002. # and deserves detailed investigation
  3003. return self.assertEqual(*args, exact_dtype=False, **kwargs)
  3004. def assertEqualBroadcasting(self, x, y, *args, **kwargs) -> None:
  3005. r"""Tests if tensor x equals to y, if y to be broadcast to x.shape.
  3006. """
  3007. if not isinstance(y, Iterable):
  3008. # int, float, etc. or different shape tensors
  3009. y = torch.ones_like(x) * y
  3010. if not isinstance(y, torch.Tensor):
  3011. # iterable, but not a tensor
  3012. y = torch.ones_like(x) * torch.tensor(y)
  3013. return self.assertEqual(x, y, *args, **kwargs)
  3014. def assertEqual(
  3015. self,
  3016. x,
  3017. y,
  3018. msg: Optional[Union[str, Callable[[str], str]]] = None,
  3019. *,
  3020. atol: Optional[float] = None,
  3021. rtol: Optional[float] = None,
  3022. equal_nan=True,
  3023. exact_dtype=True,
  3024. # TODO: default this to True
  3025. exact_device=False,
  3026. exact_layout=False,
  3027. exact_stride=False,
  3028. exact_is_coalesced=False
  3029. ):
  3030. # Hide this function from `pytest`'s traceback
  3031. __tracebackhide__ = True
  3032. # numpy's dtypes are a superset of what PyTorch supports. In case we encounter an unsupported dtype, we fall
  3033. # back to an elementwise comparison. Note that this has to happen here and not for example in
  3034. # `TensorOrArrayPair`, since at that stage we can no longer split the array into its elements and perform
  3035. # multiple comparisons.
  3036. if any(
  3037. isinstance(input, np.ndarray) and not has_corresponding_torch_dtype(input.dtype) for input in (x, y)
  3038. ):
  3039. def to_list(input):
  3040. return input.tolist() if isinstance(input, (torch.Tensor, np.ndarray)) else list(input)
  3041. x = to_list(x)
  3042. y = to_list(y)
  3043. # When comparing a sequence of numbers to a tensor, we need to convert the sequence to a tensor here.
  3044. # Otherwise, the pair origination of `are_equal` will fail, because the sequence is recognized as container
  3045. # that should be checked elementwise while the tensor is not.
  3046. elif isinstance(x, torch.Tensor) and isinstance(y, Sequence):
  3047. y = torch.as_tensor(y, dtype=x.dtype, device=x.device)
  3048. elif isinstance(x, Sequence) and isinstance(y, torch.Tensor):
  3049. x = torch.as_tensor(x, dtype=y.dtype, device=y.device)
  3050. # If x or y are tensors and nested then we unbind them to a list of tensors this should allow us to compare
  3051. # a nested tensor to a nested tensor and a nested tensor to a list of expected tensors
  3052. if isinstance(x, torch.Tensor) and x.is_nested:
  3053. x = x.unbind()
  3054. if isinstance(y, torch.Tensor) and y.is_nested:
  3055. y = y.unbind()
  3056. error_metas = not_close_error_metas(
  3057. x,
  3058. y,
  3059. pair_types=(
  3060. NonePair,
  3061. RelaxedBooleanPair,
  3062. RelaxedNumberPair,
  3063. TensorOrArrayPair,
  3064. TypedStoragePair,
  3065. StringPair,
  3066. SetPair,
  3067. TypePair,
  3068. ObjectPair,
  3069. ),
  3070. sequence_types=(
  3071. Sequence,
  3072. Sequential,
  3073. ModuleList,
  3074. ParameterList,
  3075. ScriptList,
  3076. torch.utils.data.dataset.Subset,
  3077. ),
  3078. mapping_types=(Mapping, ModuleDict, ParameterDict, ScriptDict),
  3079. rtol=rtol,
  3080. rtol_override=self.rel_tol,
  3081. atol=atol,
  3082. atol_override=self.precision,
  3083. equal_nan=equal_nan,
  3084. check_device=exact_device,
  3085. check_dtype=exact_dtype,
  3086. check_layout=exact_layout,
  3087. check_stride=exact_stride,
  3088. check_is_coalesced=exact_is_coalesced,
  3089. )
  3090. if error_metas:
  3091. # See [ErrorMeta Cycles]
  3092. error_metas = [error_metas]
  3093. # TODO: compose all metas into one AssertionError
  3094. raise error_metas.pop()[0].to_error(
  3095. # This emulates unittest.TestCase's behavior if a custom message passed and
  3096. # TestCase.longMessage (https://docs.python.org/3/library/unittest.html#unittest.TestCase.longMessage)
  3097. # is True (default)
  3098. (lambda generated_msg: f"{generated_msg}\n{msg}") if isinstance(msg, str) and self.longMessage else msg
  3099. )
  3100. def assertNotEqual(self, x, y, msg: Optional[str] = None, *, # type: ignore[override]
  3101. atol: Optional[float] = None, rtol: Optional[float] = None, **kwargs) -> None:
  3102. with self.assertRaises(AssertionError, msg=msg):
  3103. self.assertEqual(x, y, msg, atol=atol, rtol=rtol, **kwargs)
  3104. def assertEqualTypeString(self, x, y) -> None:
  3105. # This API is used simulate deprecated x.type() == y.type()
  3106. self.assertEqual(x.device, y.device)
  3107. self.assertEqual(x.dtype, y.dtype)
  3108. self.assertEqual(x.is_sparse, y.is_sparse)
  3109. def assertObjectIn(self, obj: Any, iterable: Iterable[Any]) -> None:
  3110. for elem in iterable:
  3111. if id(obj) == id(elem):
  3112. return
  3113. raise AssertionError("object not found in iterable")
  3114. # Reimplemented to provide special behavior when
  3115. # _ignore_not_implemented_error is True
  3116. def assertRaises(self, expected_exception, *args, **kwargs):
  3117. if self._ignore_not_implemented_error:
  3118. context: Optional[AssertRaisesContextIgnoreNotImplementedError] = \
  3119. AssertRaisesContextIgnoreNotImplementedError(expected_exception, self) # type: ignore[call-arg]
  3120. try:
  3121. return context.handle('assertRaises', args, kwargs) # type: ignore[union-attr]
  3122. finally:
  3123. # see https://bugs.python.org/issue23890
  3124. context = None
  3125. else:
  3126. return super().assertRaises(expected_exception, *args, **kwargs)
  3127. # Reimplemented to provide special behavior when
  3128. # _ignore_not_implemented_error is True
  3129. def assertRaisesRegex(self, expected_exception, expected_regex, *args, **kwargs):
  3130. # Verifies that an exception with the type expected_exception and message
  3131. # matching the regular expression defined by expected_regex is thrown.
  3132. # If the test is instantiated for a non-native device type (like XLA)
  3133. # then the message is not validated.
  3134. # Checks whether the test is instantiated for a device type by testing
  3135. # if the test class has defined the device_type attribute and,
  3136. # if so, tests whether the instantiated device type is native or not
  3137. if hasattr(self, 'device_type') and self.device_type not in NATIVE_DEVICES and self.device_type != "mps": # type: ignore[attr-defined]
  3138. # empty string matches any string
  3139. expected_regex = ''
  3140. if self._ignore_not_implemented_error:
  3141. context = AssertRaisesContextIgnoreNotImplementedError( # type: ignore[call-arg]
  3142. expected_exception, self, expected_regex)
  3143. return context.handle('assertRaisesRegex', args, kwargs) # type: ignore[attr-defined]
  3144. else:
  3145. return super().assertRaisesRegex(expected_exception, expected_regex, *args, **kwargs)
  3146. # Verifies that no unraisable exceptions are raised by callable. Unlike regular
  3147. # exceptions, these do not actually propagate to the caller and are
  3148. # suppressed. We must test for them specially.
  3149. def assertNoUnraisable(self, callable, *args, **kwargs):
  3150. raised = None
  3151. def record_unraisable(unraisable):
  3152. nonlocal raised
  3153. raised = unraisable
  3154. # Disable GC when running the callable to prevent spurious flakiness
  3155. # from unlucky GCs inside the callable
  3156. prev = gc.isenabled()
  3157. gc.disable()
  3158. try:
  3159. with unittest.mock.patch("sys.unraisablehook", record_unraisable):
  3160. callable(*args, **kwargs)
  3161. finally:
  3162. if prev:
  3163. gc.enable()
  3164. self.assertIsNone(raised)
  3165. # TODO: Support context manager interface
  3166. # NB: The kwargs forwarding to callable robs the 'subname' parameter.
  3167. # If you need it, manually apply your callable in a lambda instead.
  3168. def assertExpectedRaises(self, exc_type, callable, *args, **kwargs):
  3169. subname = None
  3170. if 'subname' in kwargs:
  3171. subname = kwargs['subname']
  3172. del kwargs['subname']
  3173. try:
  3174. callable(*args, **kwargs)
  3175. except exc_type as e:
  3176. self.assertExpected(str(e), subname)
  3177. return
  3178. # Don't put this in the try block; the AssertionError will catch it
  3179. self.fail(msg="Did not raise when expected to")
  3180. def assertNotWarn(self, callable, msg=''):
  3181. r"""
  3182. Test if :attr:`callable` does not raise a warning.
  3183. """
  3184. with warnings.catch_warnings(record=True) as ws:
  3185. warnings.simplefilter("always") # allow any warning to be raised
  3186. with set_warn_always_context(True):
  3187. callable()
  3188. self.assertTrue(len(ws) == 0, msg)
  3189. @contextmanager
  3190. def assertWarnsOnceRegex(self, category, regex=''):
  3191. """Context manager for code that *must always* warn
  3192. This filters expected warnings from the test and fails if
  3193. the expected warning is not caught. It uses set_warn_always() to force
  3194. TORCH_WARN_ONCE to behave like TORCH_WARN
  3195. """
  3196. pattern = re.compile(regex)
  3197. with warnings.catch_warnings(record=True) as ws:
  3198. warnings.simplefilter("always") # allow any warning to be raised
  3199. with set_warn_always_context(True):
  3200. yield
  3201. if len(ws) == 0:
  3202. self.fail('no warning caught')
  3203. self.assertTrue(any(type(w.message) is category for w in ws))
  3204. self.assertTrue(
  3205. any(re.match(pattern, str(w.message)) for w in ws),
  3206. f'{pattern}, {[w.message for w in ws if type(w.message) is category]}')
  3207. def assertExpected(self, s, subname=None):
  3208. r"""
  3209. Test that a string matches the recorded contents of a file
  3210. derived from the name of this test and subname. This file
  3211. is placed in the 'expect' directory in the same directory
  3212. as the test script. You can automatically update the recorded test
  3213. output using --accept.
  3214. If you call this multiple times in a single function, you must
  3215. give a unique subname each time.
  3216. """
  3217. if not isinstance(s, str):
  3218. raise TypeError("assertExpected is strings only")
  3219. def remove_prefix(text, prefix):
  3220. if text.startswith(prefix):
  3221. return text[len(prefix):]
  3222. return text
  3223. # NB: we take __file__ from the module that defined the test
  3224. # class, so we place the expect directory where the test script
  3225. # lives, NOT where test/common_utils.py lives. This doesn't matter in
  3226. # PyTorch where all test scripts are in the same directory as
  3227. # test/common_utils.py, but it matters in onnx-pytorch
  3228. module_id = self.__class__.__module__
  3229. munged_id = remove_prefix(self.id(), module_id + ".")
  3230. test_file = os.path.realpath(sys.modules[module_id].__file__)
  3231. expected_file = os.path.join(os.path.dirname(test_file),
  3232. "expect",
  3233. munged_id)
  3234. subname_output = ""
  3235. if subname:
  3236. expected_file += "-" + subname
  3237. subname_output = f" ({subname})"
  3238. expected_file += ".expect"
  3239. expected = None
  3240. def accept_output(update_type):
  3241. print(f"Accepting {update_type} for {munged_id}{subname_output}:\n\n{s}")
  3242. with open(expected_file, 'w') as f:
  3243. # Adjust for producer_version, leave s unmodified
  3244. s_tag = re.sub(r'(producer_version): "[0-9.]*"',
  3245. r'\1: "CURRENT_VERSION"', s)
  3246. f.write(s_tag)
  3247. try:
  3248. with open(expected_file) as f:
  3249. expected = f.read()
  3250. except OSError as e:
  3251. if e.errno != errno.ENOENT:
  3252. raise
  3253. elif expecttest.ACCEPT:
  3254. return accept_output("output")
  3255. else:
  3256. raise RuntimeError(
  3257. f"I got this output for {munged_id}{subname_output}:\n\n{s}\n\n"
  3258. "No expect file exists; to accept the current output, run:\n"
  3259. f"python {__main__.__file__} {munged_id} --accept") from None
  3260. # a hack for JIT tests
  3261. if IS_WINDOWS:
  3262. expected = re.sub(r'CppOp\[(.+?)\]', 'CppOp[]', expected)
  3263. s = re.sub(r'CppOp\[(.+?)\]', 'CppOp[]', s)
  3264. # Adjust for producer_version
  3265. expected = expected.replace(
  3266. 'producer_version: "CURRENT_VERSION"',
  3267. f'producer_version: "{torch.onnx.producer_version}"'
  3268. )
  3269. if expecttest.ACCEPT:
  3270. if expected != s:
  3271. return accept_output("updated output")
  3272. else:
  3273. if hasattr(self, "assertMultiLineEqual"):
  3274. # Python 2.7 only
  3275. # NB: Python considers lhs "old" and rhs "new".
  3276. self.assertMultiLineEqual(expected, s)
  3277. else:
  3278. self.assertEqual(s, expected)
  3279. def assertExpectedStripMangled(self, s, subname=None):
  3280. s = re.sub(r'__torch__[^ ]+', '', s)
  3281. self.assertExpected(s, subname)
  3282. def assertGreaterAlmostEqual(self, first, second, places=None, msg=None, delta=None):
  3283. """Assert that ``first`` is greater than or almost equal to ``second``.
  3284. The equality of ``first`` and ``second`` is determined in a similar way to
  3285. the ``assertAlmostEqual`` function of the standard library.
  3286. """
  3287. if delta is not None and places is not None:
  3288. raise TypeError("specify delta or places not both")
  3289. if first >= second:
  3290. return
  3291. diff = second - first
  3292. if delta is not None:
  3293. if diff <= delta:
  3294. return
  3295. standardMsg = f"{first} not greater than or equal to {second} within {delta} delta"
  3296. else:
  3297. if places is None:
  3298. places = 7
  3299. if round(diff, places) == 0:
  3300. return
  3301. standardMsg = f"{first} not greater than or equal to {second} within {places} places"
  3302. msg = self._formatMessage(msg, standardMsg)
  3303. raise self.failureException(msg)
  3304. def assertAtenOp(self, onnx_model, operator, overload_name=""):
  3305. all_aten_nodes = [p for p in onnx_model.graph.node
  3306. if p.op_type == "ATen" and p.domain == "org.pytorch.aten"]
  3307. self.assertTrue(all_aten_nodes)
  3308. for op in all_aten_nodes:
  3309. attrs = {attr.name: attr.s.decode() for attr in op.attribute}
  3310. if attrs.get("operator") == operator:
  3311. break
  3312. self.assertEqual(attrs["operator"], operator)
  3313. self.assertEqual(attrs.get("overload_name", ""), overload_name)
  3314. def check_nondeterministic_alert(self, fn, caller_name, should_alert=True):
  3315. '''Checks that an operation produces a nondeterministic alert when
  3316. expected while `torch.use_deterministic_algorithms(True)` is set.
  3317. Args:
  3318. fn (callable): Function to check for a nondeterministic alert
  3319. caller_name (str): Name of the operation that produces the
  3320. nondeterministic alert. This name is expected to appear at the
  3321. beginning of the error/warning message.
  3322. should_alert (bool, optional): If True, then the check will only pass
  3323. if calling `fn` produces a nondeterministic error/warning with the
  3324. expected message. If False, then the check will only pass if
  3325. calling `fn` does not produce an error. Default: `True`.
  3326. '''
  3327. alert_message = '^' + caller_name + ' does not have a deterministic implementation, but you set'
  3328. # Check that errors are thrown correctly
  3329. with DeterministicGuard(True):
  3330. if should_alert:
  3331. with self.assertRaisesRegex(
  3332. RuntimeError,
  3333. alert_message,
  3334. msg='expected a non-deterministic error, but it was not raised'):
  3335. fn()
  3336. else:
  3337. # If a nondeterministic error is not expected, make sure
  3338. # that it is not raised
  3339. try:
  3340. fn()
  3341. except RuntimeError as e:
  3342. if 'does not have a deterministic implementation' in str(e):
  3343. self.fail(
  3344. 'did not expect non-deterministic error message, '
  3345. + 'but got one anyway: "' + str(e) + '"')
  3346. # Reraise exceptions unrelated to nondeterminism
  3347. raise
  3348. # Check that warnings are thrown correctly
  3349. with DeterministicGuard(True, warn_only=True):
  3350. if should_alert:
  3351. with self.assertWarnsRegex(
  3352. UserWarning,
  3353. alert_message):
  3354. fn()
  3355. else:
  3356. with warnings.catch_warnings(record=True) as w:
  3357. warnings.simplefilter("always")
  3358. fn()
  3359. for warning in w:
  3360. if isinstance(warning, UserWarning):
  3361. self.assertTrue(re.search(alert_message, str(warning)) is None)
  3362. # run code in subprocess and capture exceptions.
  3363. @staticmethod
  3364. def run_process_no_exception(code, env=None):
  3365. import subprocess
  3366. popen = subprocess.Popen(
  3367. [sys.executable, '-c', code],
  3368. stdout=subprocess.PIPE,
  3369. stderr=subprocess.PIPE,
  3370. env=env)
  3371. (stdout, stderr) = popen.communicate()
  3372. return (stdout, stderr)
  3373. # returns captured stderr
  3374. @staticmethod
  3375. def runWithPytorchAPIUsageStderr(code):
  3376. env = os.environ.copy()
  3377. env["PYTORCH_API_USAGE_STDERR"] = "1"
  3378. # remove CI flag since this is a wrapped test process.
  3379. # CI flag should be set in the parent process only.
  3380. if "CI" in env.keys():
  3381. del env["CI"]
  3382. (stdout, stderr) = TestCase.run_process_no_exception(code, env=env)
  3383. return stderr.decode('ascii')
  3384. class TestCaseBase(TestCase):
  3385. # Calls to super() in dynamically created classes are a bit odd.
  3386. # See https://github.com/pytorch/pytorch/pull/118586 for more info
  3387. # Subclassing this class and then calling super(TestCaseBase) will run
  3388. # TestCase's setUp, tearDown etc functions
  3389. pass
  3390. def download_file(url, binary=True):
  3391. from urllib.parse import urlsplit
  3392. from urllib import request, error
  3393. filename = os.path.basename(urlsplit(url)[2])
  3394. data_dir = get_writable_path(os.path.join(os.path.dirname(__file__), 'data'))
  3395. path = os.path.join(data_dir, filename)
  3396. if os.path.exists(path):
  3397. return path
  3398. try:
  3399. data = request.urlopen(url, timeout=15).read()
  3400. with open(path, 'wb' if binary else 'w') as f:
  3401. f.write(data)
  3402. return path
  3403. except error.URLError as e:
  3404. msg = f"could not download test file '{url}'"
  3405. warnings.warn(msg, RuntimeWarning)
  3406. raise unittest.SkipTest(msg) from e
  3407. def find_free_port():
  3408. """
  3409. Finds an available port and returns that port number.
  3410. NOTE: If this function is being used to allocate a port to Store (or
  3411. indirectly via init_process_group or init_rpc), it should be used
  3412. in conjuction with the `retry_on_connect_failures` decorator as there is a potential
  3413. race condition where the allocated port may become unavailable before it can be used
  3414. """
  3415. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  3416. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  3417. sock.bind(('localhost', 0))
  3418. _, port = sock.getsockname()
  3419. return port
  3420. # Errors that we can get in c10d initialization for which we should retry tests for.
  3421. ADDRESS_IN_USE = "Address already in use"
  3422. CONNECT_TIMEOUT = "connect() timed out."
  3423. def retry_on_connect_failures(func=None, connect_errors=(ADDRESS_IN_USE)):
  3424. """Reruns a test if the test returns a RuntimeError and the exception
  3425. contains one of the strings in connect_errors."""
  3426. # This if block is executed when using this function as a decorator with arguments.
  3427. if func is None:
  3428. return partial(retry_on_connect_failures, connect_errors=connect_errors)
  3429. @wraps(func)
  3430. def wrapper(*args, **kwargs):
  3431. n_retries = 10
  3432. tries_remaining = n_retries
  3433. while True:
  3434. try:
  3435. return func(*args, **kwargs)
  3436. except RuntimeError as error:
  3437. if any(connect_error in str(error) for connect_error in connect_errors):
  3438. tries_remaining -= 1
  3439. if tries_remaining == 0:
  3440. raise RuntimeError(f"Failing after {n_retries} retries with error: {str(error)}") from error
  3441. time.sleep(random.random())
  3442. continue
  3443. raise
  3444. return wrapper
  3445. # Decorator to retry upon certain Exceptions.
  3446. def retry(ExceptionToCheck, tries=3, delay=3, skip_after_retries=False):
  3447. def deco_retry(f):
  3448. @wraps(f)
  3449. def f_retry(*args, **kwargs):
  3450. mtries, mdelay = tries, delay
  3451. while mtries > 1:
  3452. try:
  3453. return f(*args, **kwargs)
  3454. except ExceptionToCheck as e:
  3455. msg = "%s, Retrying in %d seconds..." % (str(e), mdelay)
  3456. print(msg)
  3457. time.sleep(mdelay)
  3458. mtries -= 1
  3459. try:
  3460. return f(*args, **kwargs)
  3461. except ExceptionToCheck as e:
  3462. raise unittest.SkipTest(f"Skipping after {tries} consecutive {str(e)}") from e if skip_after_retries else e
  3463. return f_retry # true decorator
  3464. return deco_retry
  3465. # FIXME: modernize these to be consistent with make_tensor
  3466. # and review including them in torch.testing
  3467. # Methods for matrix generation
  3468. def random_square_matrix_of_rank(l, rank, dtype=torch.double, device='cpu'):
  3469. assert rank <= l
  3470. A = torch.randn(l, l, dtype=dtype, device=device)
  3471. u, s, vh = torch.linalg.svd(A, full_matrices=False)
  3472. for i in range(l):
  3473. if i >= rank:
  3474. s[i] = 0
  3475. elif s[i] == 0:
  3476. s[i] = 1
  3477. return (u * s.to(dtype).unsqueeze(-2)) @ vh
  3478. def random_well_conditioned_matrix(*shape, dtype, device, mean=1.0, sigma=0.001):
  3479. """
  3480. Returns a random rectangular matrix (batch of matrices)
  3481. with singular values sampled from a Gaussian with
  3482. mean `mean` and standard deviation `sigma`.
  3483. The smaller the `sigma`, the better conditioned
  3484. the output matrix is.
  3485. """
  3486. primitive_dtype = {
  3487. torch.float: torch.float,
  3488. torch.double: torch.double,
  3489. torch.cfloat: torch.float,
  3490. torch.cdouble: torch.double
  3491. }
  3492. x = torch.rand(shape, dtype=dtype, device=device)
  3493. m = x.size(-2)
  3494. n = x.size(-1)
  3495. u, _, vh = torch.linalg.svd(x, full_matrices=False)
  3496. s = (torch.randn(*(shape[:-2] + (min(m, n),)), dtype=primitive_dtype[dtype], device=device) * sigma + mean) \
  3497. .sort(-1, descending=True).values.to(dtype)
  3498. return (u * s.unsqueeze(-2)) @ vh
  3499. # Returns a noncontiguous (tensor with the same shape and values as t
  3500. # The noncontiguous tensor is constructed such that elements in the innermost
  3501. # dimension are separated by zeros or (whenever possible) nans
  3502. # TODO: consider more complicated noncontiguity schemes
  3503. def noncontiguous_like(t):
  3504. # Short-circuits if t is already noncontiguous
  3505. if not t.is_contiguous():
  3506. return t
  3507. # Choose a "weird" value that won't be accessed
  3508. if t.dtype.is_floating_point or t.dtype.is_complex:
  3509. value = math.nan
  3510. elif t.dtype == torch.bool:
  3511. value = True
  3512. else:
  3513. value = 12
  3514. result = t.new_empty(t.shape + (2,))
  3515. result[..., 0] = value
  3516. result[..., 1] = t.detach()
  3517. result = result[..., 1]
  3518. result.requires_grad_(t.requires_grad)
  3519. return result
  3520. # TODO: remove this (prefer make_symmetric_matrices below)
  3521. def random_symmetric_matrix(l, *batches, **kwargs):
  3522. dtype = kwargs.get('dtype', torch.double)
  3523. device = kwargs.get('device', 'cpu')
  3524. A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device)
  3525. A = (A + A.mT).div_(2)
  3526. return A
  3527. # Creates a symmetric matrix or batch of symmetric matrices
  3528. # Shape must be a square matrix or batch of square matrices
  3529. def make_symmetric_matrices(*shape, device, dtype):
  3530. assert shape[-1] == shape[-2]
  3531. t = make_tensor(shape, device=device, dtype=dtype)
  3532. t = (t + t.mT).div_(2)
  3533. return t
  3534. def random_hermitian_matrix(l, *batches, **kwargs):
  3535. dtype = kwargs.get('dtype', torch.double)
  3536. device = kwargs.get('device', 'cpu')
  3537. A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device)
  3538. A = (A + A.mH).div_(2)
  3539. return A
  3540. def random_symmetric_psd_matrix(l, *batches, **kwargs):
  3541. """
  3542. Returns a batch of random symmetric positive-semi-definite matrices.
  3543. The shape of the result is batch_dims + (matrix_size, matrix_size)
  3544. The following example creates a tensor of size 2 x 4 x 3 x 3
  3545. >>> # xdoctest: +SKIP("undefined variables")
  3546. >>> matrices = random_symmetric_psd_matrix(3, 2, 4, dtype=dtype, device=device)
  3547. """
  3548. dtype = kwargs.get('dtype', torch.double)
  3549. device = kwargs.get('device', 'cpu')
  3550. A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device)
  3551. return A @ A.mT
  3552. def random_hermitian_psd_matrix(matrix_size, *batch_dims, dtype=torch.double, device='cpu'):
  3553. """
  3554. Returns a batch of random Hermitian positive-semi-definite matrices.
  3555. The shape of the result is batch_dims + (matrix_size, matrix_size)
  3556. The following example creates a tensor of size 2 x 4 x 3 x 3
  3557. >>> # xdoctest: +SKIP("undefined variables")
  3558. >>> matrices = random_hermitian_psd_matrix(3, 2, 4, dtype=dtype, device=device)
  3559. """
  3560. A = torch.randn(*(batch_dims + (matrix_size, matrix_size)), dtype=dtype, device=device)
  3561. return A @ A.mH
  3562. # TODO: remove this (prefer make_symmetric_pd_matrices below)
  3563. def random_symmetric_pd_matrix(matrix_size, *batch_dims, **kwargs):
  3564. dtype = kwargs.get('dtype', torch.double)
  3565. device = kwargs.get('device', 'cpu')
  3566. A = torch.randn(*(batch_dims + (matrix_size, matrix_size)),
  3567. dtype=dtype, device=device)
  3568. return torch.matmul(A, A.mT) \
  3569. + torch.eye(matrix_size, dtype=dtype, device=device) * 1e-5
  3570. # Creates a symmetric positive-definite matrix or batch of
  3571. # such matrices
  3572. def make_symmetric_pd_matrices(*shape, device, dtype):
  3573. assert shape[-1] == shape[-2]
  3574. t = make_tensor(shape, device=device, dtype=dtype)
  3575. i = torch.eye(shape[-1], device=device, dtype=dtype) * 1e-5
  3576. return t @ t.mT + i
  3577. def random_hermitian_pd_matrix(matrix_size, *batch_dims, dtype, device):
  3578. """
  3579. Returns a batch of random Hermitian positive-definite matrices.
  3580. The shape of the result is batch_dims + (matrix_size, matrix_size)
  3581. The following example creates a tensor of size 2 x 4 x 3 x 3
  3582. >>> # xdoctest: +SKIP("undefined variables")
  3583. >>> matrices = random_hermitian_pd_matrix(3, 2, 4, dtype=dtype, device=device)
  3584. """
  3585. A = torch.randn(*(batch_dims + (matrix_size, matrix_size)),
  3586. dtype=dtype, device=device)
  3587. return A @ A.mH + torch.eye(matrix_size, dtype=dtype, device=device)
  3588. # Creates a full rank matrix with distinct singular values or
  3589. # a batch of such matrices
  3590. def make_fullrank_matrices_with_distinct_singular_values(*shape, device, dtype, requires_grad=False):
  3591. with torch.no_grad():
  3592. t = make_tensor(shape, device=device, dtype=dtype)
  3593. u, _, vh = torch.linalg.svd(t, full_matrices=False)
  3594. real_dtype = t.real.dtype if t.dtype.is_complex else t.dtype
  3595. k = min(shape[-1], shape[-2])
  3596. # We choose the singular values to be "around one"
  3597. # This is to make the matrix well conditioned
  3598. # s = [2, 3, ..., k+1]
  3599. s = torch.arange(2, k + 2, dtype=real_dtype, device=device)
  3600. # s = [2, -3, 4, ..., (-1)^k k+1]
  3601. s[1::2] *= -1.
  3602. # 1 + 1/s so that the singular values are in the range [2/3, 3/2]
  3603. # This gives a condition number of 9/4, which should be good enough
  3604. s.reciprocal_().add_(1.)
  3605. # Note that the singular values need not be ordered in an SVD so
  3606. # we don't need need to sort S
  3607. x = (u * s.to(u.dtype)) @ vh
  3608. x.requires_grad_(requires_grad)
  3609. return x
  3610. def random_matrix(rows, columns, *batch_dims, **kwargs):
  3611. """Return rectangular matrix or batches of rectangular matrices.
  3612. Parameters:
  3613. dtype - the data type
  3614. device - the device kind
  3615. singular - when True, the output will be singular
  3616. """
  3617. dtype = kwargs.get('dtype', torch.double)
  3618. device = kwargs.get('device', 'cpu')
  3619. silent = kwargs.get("silent", False)
  3620. singular = kwargs.get("singular", False)
  3621. if silent and not torch._C.has_lapack:
  3622. return torch.ones(rows, columns, dtype=dtype, device=device)
  3623. A = torch.randn(batch_dims + (rows, columns), dtype=dtype, device=device)
  3624. if A.numel() == 0:
  3625. return A
  3626. u, _, vh = torch.linalg.svd(A, full_matrices=False)
  3627. k = min(rows, columns)
  3628. s = torch.linspace(1 / (k + 1), 1, k, dtype=dtype, device=device)
  3629. if singular:
  3630. # make matrix singular
  3631. s[k - 1] = 0
  3632. if k > 2:
  3633. # increase the order of singularity so that the pivoting
  3634. # in LU factorization will be non-trivial
  3635. s[0] = 0
  3636. return (u * s.unsqueeze(-2)) @ vh
  3637. def random_lowrank_matrix(rank, rows, columns, *batch_dims, **kwargs):
  3638. """Return rectangular matrix or batches of rectangular matrices with
  3639. given rank.
  3640. """
  3641. B = random_matrix(rows, rank, *batch_dims, **kwargs)
  3642. C = random_matrix(rank, columns, *batch_dims, **kwargs)
  3643. return B.matmul(C)
  3644. def random_sparse_matrix(rows, columns, density=0.01, **kwargs):
  3645. """Return rectangular random sparse matrix within given density.
  3646. The density of the result approaches to given density as the size
  3647. of the matrix is increased and a relatively small value of density
  3648. is specified but higher than min(rows, columns)/(rows * columns)
  3649. for non-singular matrices.
  3650. """
  3651. dtype = kwargs.get('dtype', torch.double)
  3652. device = kwargs.get('device', 'cpu')
  3653. singular = kwargs.get("singular", False)
  3654. k = min(rows, columns)
  3655. nonzero_elements = max(min(rows, columns), int(rows * columns * density))
  3656. row_indices = [i % rows for i in range(nonzero_elements)]
  3657. column_indices = [i % columns for i in range(nonzero_elements)]
  3658. random.shuffle(column_indices)
  3659. indices = [row_indices, column_indices]
  3660. values = torch.randn(nonzero_elements, dtype=dtype, device=device)
  3661. # ensure that the diagonal dominates
  3662. values *= torch.tensor([-float(i - j)**2 for i, j in zip(*indices)], dtype=dtype, device=device).exp()
  3663. indices_tensor = torch.tensor(indices)
  3664. A = torch.sparse_coo_tensor(indices_tensor, values, (rows, columns), device=device)
  3665. return A.coalesce()
  3666. def random_sparse_pd_matrix(matrix_size, density=0.01, **kwargs):
  3667. """Return random sparse positive-definite matrix with given density.
  3668. The eigenvalues of the matrix are defined as::
  3669. arange(1, matrix_size+1)/matrix_size
  3670. Algorithm:
  3671. A = diag(arange(1, matrix_size+1)/matrix_size)
  3672. while <A density is smaller than required>:
  3673. <choose random i, j in range(matrix_size), theta in [0, 2*pi]>
  3674. R = <rotation matrix (i,j,theta)>
  3675. A = R^T A R
  3676. """
  3677. import math
  3678. torch = kwargs.get('torch', globals()['torch'])
  3679. dtype = kwargs.get('dtype', torch.double)
  3680. device = kwargs.get('device', 'cpu')
  3681. data = {(i, i): float(i + 1) / matrix_size
  3682. for i in range(matrix_size)}
  3683. def multiply(data, N, i, j, cs, sn, left=True):
  3684. for k in range(N):
  3685. if left:
  3686. ik, jk = (k, i), (k, j)
  3687. else:
  3688. ik, jk = (i, k), (j, k)
  3689. aik, ajk = data.get(ik, 0), data.get(jk, 0)
  3690. aik, ajk = cs * aik + sn * ajk, -sn * aik + cs * ajk
  3691. if aik:
  3692. data[ik] = aik
  3693. else:
  3694. data.pop(ik, None)
  3695. if ajk:
  3696. data[jk] = ajk
  3697. else:
  3698. data.pop(jk, None)
  3699. target_nnz = density * matrix_size * matrix_size
  3700. while len(data) < target_nnz:
  3701. i = random.randint(0, matrix_size - 1)
  3702. j = random.randint(0, matrix_size - 1)
  3703. if i != j:
  3704. theta = random.uniform(0, 2 * math.pi)
  3705. cs = math.cos(theta)
  3706. sn = math.sin(theta)
  3707. multiply(data, matrix_size, i, j, cs, sn, left=True)
  3708. multiply(data, matrix_size, i, j, cs, sn, left=False)
  3709. icoords, jcoords, values = [], [], []
  3710. for (i, j), v in sorted(data.items()):
  3711. icoords.append(i)
  3712. jcoords.append(j)
  3713. values.append(v)
  3714. indices_tensor = torch.tensor([icoords, jcoords])
  3715. return torch.sparse_coo_tensor(indices_tensor, values, (matrix_size, matrix_size), dtype=dtype, device=device)
  3716. # FIXME: remove this by updating test suites using it
  3717. def do_test_dtypes(self, dtypes, layout, device):
  3718. for dtype in dtypes:
  3719. if dtype != torch.float16:
  3720. out = torch.zeros((2, 3), dtype=dtype, layout=layout, device=device)
  3721. self.assertIs(dtype, out.dtype)
  3722. self.assertIs(layout, out.layout)
  3723. self.assertEqual(device, out.device)
  3724. # FIXME: remove this by updating test suites using it
  3725. def do_test_empty_full(self, dtypes, layout, device):
  3726. shape = torch.Size([2, 3])
  3727. def check_value(tensor, dtype, layout, device, value, requires_grad):
  3728. self.assertEqual(shape, tensor.shape)
  3729. self.assertIs(dtype, tensor.dtype)
  3730. self.assertIs(layout, tensor.layout)
  3731. self.assertEqual(tensor.requires_grad, requires_grad)
  3732. if tensor.is_cuda and device is not None:
  3733. self.assertEqual(device, tensor.device)
  3734. if value is not None:
  3735. fill = tensor.new(shape).fill_(value)
  3736. self.assertEqual(tensor, fill)
  3737. def get_int64_dtype(dtype):
  3738. module = '.'.join(str(dtype).split('.')[1:-1])
  3739. if not module:
  3740. return torch.int64
  3741. return operator.attrgetter(module)(torch).int64
  3742. default_dtype = torch.get_default_dtype()
  3743. check_value(torch.empty(shape), default_dtype, torch.strided, -1, None, False)
  3744. check_value(torch.full(shape, -5.), default_dtype, torch.strided, -1, None, False)
  3745. for dtype in dtypes:
  3746. for rg in {dtype.is_floating_point, False}:
  3747. int64_dtype = get_int64_dtype(dtype)
  3748. v = torch.empty(shape, dtype=dtype, device=device, layout=layout, requires_grad=rg)
  3749. check_value(v, dtype, layout, device, None, rg)
  3750. out = v.new()
  3751. check_value(torch.empty(shape, out=out, device=device, layout=layout, requires_grad=rg),
  3752. dtype, layout, device, None, rg)
  3753. check_value(v.new_empty(shape), dtype, layout, device, None, False)
  3754. check_value(v.new_empty(shape, dtype=int64_dtype, device=device, requires_grad=False),
  3755. int64_dtype, layout, device, None, False)
  3756. check_value(torch.empty_like(v), dtype, layout, device, None, False)
  3757. check_value(torch.empty_like(v, dtype=int64_dtype, layout=layout, device=device, requires_grad=False),
  3758. int64_dtype, layout, device, None, False)
  3759. if dtype is not torch.float16 and layout != torch.sparse_coo:
  3760. fv = 3
  3761. v = torch.full(shape, fv, dtype=dtype, layout=layout, device=device, requires_grad=rg)
  3762. check_value(v, dtype, layout, device, fv, rg)
  3763. check_value(v.new_full(shape, fv + 1), dtype, layout, device, fv + 1, False)
  3764. out = v.new()
  3765. check_value(torch.full(shape, fv + 2, out=out, device=device, layout=layout, requires_grad=rg),
  3766. dtype, layout, device, fv + 2, rg)
  3767. check_value(v.new_full(shape, fv + 3, dtype=int64_dtype, device=device, requires_grad=False),
  3768. int64_dtype, layout, device, fv + 3, False)
  3769. check_value(torch.full_like(v, fv + 4), dtype, layout, device, fv + 4, False)
  3770. check_value(torch.full_like(v, fv + 5,
  3771. dtype=int64_dtype, layout=layout, device=device, requires_grad=False),
  3772. int64_dtype, layout, device, fv + 5, False)
  3773. # FIXME: improve load_tests() documentation here
  3774. running_script_path = None
  3775. def set_running_script_path():
  3776. global running_script_path
  3777. try:
  3778. running_file = os.path.abspath(os.path.realpath(sys.argv[0]))
  3779. if running_file.endswith('.py'): # skip if the running file is not a script
  3780. running_script_path = running_file
  3781. except Exception:
  3782. pass
  3783. def check_test_defined_in_running_script(test_case):
  3784. if running_script_path is None:
  3785. return
  3786. test_case_class_file = os.path.abspath(os.path.realpath(inspect.getfile(test_case.__class__)))
  3787. assert test_case_class_file == running_script_path, f'Class of loaded TestCase "{test_case.id()}" ' \
  3788. f'is not defined in the running script "{running_script_path}", but in "{test_case_class_file}". Did you ' \
  3789. "accidentally import a unittest.TestCase from another file?"
  3790. def load_tests(loader, tests, pattern):
  3791. set_running_script_path()
  3792. test_suite = unittest.TestSuite()
  3793. for test_group in tests:
  3794. if not DISABLE_RUNNING_SCRIPT_CHK: # noqa: F821
  3795. for test in test_group:
  3796. check_test_defined_in_running_script(test)
  3797. if test_group._tests:
  3798. test_suite.addTest(test_group)
  3799. return test_suite
  3800. # FIXME: document this and move it to test_serialization
  3801. class BytesIOContext(io.BytesIO):
  3802. def __enter__(self):
  3803. return self
  3804. def __exit__(self, *args):
  3805. pass
  3806. # Tentative value for nondet_tol for gradcheck when backward implementation
  3807. # relies on nondeterministic operations, i.e., those listed here:
  3808. # https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html
  3809. #
  3810. # For more information see https://github.com/pytorch/pytorch/issues/56202
  3811. GRADCHECK_NONDET_TOL = 1e-12
  3812. TestEnvironment.def_flag("TEST_WITH_SLOW_GRADCHECK", env_var="PYTORCH_TEST_WITH_SLOW_GRADCHECK")
  3813. skipIfSlowGradcheckEnv = unittest.skipIf(
  3814. TEST_WITH_SLOW_GRADCHECK, # noqa: F821
  3815. "Tests that don't use gradcheck don't need to run on slow_gradcheck CI"
  3816. )
  3817. def gradcheck(fn, inputs, **kwargs):
  3818. # Wrapper around gradcheck that enables certain keys by default.
  3819. # Use this testing-internal gradcheck instead of autograd.gradcheck so that new features like vmap and
  3820. # forward-mode AD are tested by default. We create this wrapper because we'd like to keep new checks
  3821. # to be disabled to default for the public-facing api to avoid breaking user code.
  3822. #
  3823. # All PyTorch devs doing testing should use this wrapper instead of autograd.gradcheck.
  3824. default_values = {
  3825. "check_batched_grad": True,
  3826. "fast_mode": True,
  3827. }
  3828. if TEST_WITH_SLOW_GRADCHECK: # noqa: F821
  3829. default_values["fast_mode"] = False
  3830. for key, value in default_values.items():
  3831. # default value override values explicitly set to None
  3832. k = kwargs.get(key, None)
  3833. kwargs[key] = k if k is not None else value
  3834. return torch.autograd.gradcheck(fn, inputs, **kwargs)
  3835. def gradgradcheck(fn, inputs, grad_outputs=None, **kwargs):
  3836. # Wrapper around gradgradcheck that enables certain keys by default
  3837. # See gradcheck above for an explanation of why we need something like this.
  3838. #
  3839. # All PyTorch devs doing testing should use this wrapper instead of autograd.gradgradcheck
  3840. default_values = {
  3841. "check_batched_grad": True,
  3842. "fast_mode": True,
  3843. }
  3844. if TEST_WITH_SLOW_GRADCHECK: # noqa: F821
  3845. default_values["fast_mode"] = False
  3846. for key, value in default_values.items():
  3847. # default value override values explicitly set to None
  3848. k = kwargs.get(key, None)
  3849. kwargs[key] = k if k is not None else value
  3850. return torch.autograd.gradgradcheck(fn, inputs, grad_outputs, **kwargs)
  3851. def _assertGradAndGradgradChecks(test_case, apply_fn, inputs, **kwargs):
  3852. # call assert function rather than returning a bool since it's nicer
  3853. # if we get whether this failed on the gradcheck or the gradgradcheck.
  3854. test_case.assertTrue(gradcheck(apply_fn, inputs, **kwargs))
  3855. test_case.assertTrue(gradgradcheck(apply_fn, inputs, **kwargs))
  3856. @contextmanager
  3857. def set_cwd(path: str) -> Iterator[None]:
  3858. old_cwd = os.getcwd()
  3859. try:
  3860. os.chdir(path)
  3861. yield
  3862. finally:
  3863. os.chdir(old_cwd)
  3864. # FIXME: delete this
  3865. # Using @toleranceOverride specific to your test is the recommended way
  3866. # of doing this. These are just some values that worked for test_nn.
  3867. dtype2prec_DONTUSE = {torch.float: 1e-5,
  3868. torch.double: 1e-5,
  3869. torch.half: 1e-2,
  3870. torch.bfloat16: 1e-1}
  3871. # FIXME: move to test_sparse or sparse utils
  3872. # This is a wrapper that wraps a test to run this test twice, one with
  3873. # coalesced=True, another with coalesced=False for coalesced/uncoalesced sparse tensors.
  3874. def coalescedonoff(f):
  3875. @wraps(f)
  3876. def wrapped(self, *args, **kwargs):
  3877. f(self, *args, **kwargs, coalesced=True)
  3878. f(self, *args, **kwargs, coalesced=False)
  3879. return wrapped
  3880. def is_coalesced_indices(s):
  3881. indices = s._indices()
  3882. hash_coeffs = (1,) + s.shape[s.sparse_dim() - 1:0:-1]
  3883. hash_indices = torch.tensor(hash_coeffs, device=s.device).cumprod(-1).flip(-1)
  3884. if s.sparse_dim() > 1:
  3885. hash_indices.unsqueeze_(-1)
  3886. hash_indices = (indices * hash_indices).sum(0)
  3887. else:
  3888. hash_indices = indices * hash_indices
  3889. # check if indices are sorted
  3890. res = torch.allclose(hash_indices, hash_indices.sort()[0])
  3891. # check if there are no repeated indices
  3892. res = res and torch.allclose(hash_indices, hash_indices.unique())
  3893. return res
  3894. @contextlib.contextmanager
  3895. def disable_gc():
  3896. if gc.isenabled():
  3897. try:
  3898. gc.disable()
  3899. yield
  3900. finally:
  3901. gc.enable()
  3902. else:
  3903. yield
  3904. def find_library_location(lib_name: str) -> Path:
  3905. # return the shared library file in the installed folder if exist,
  3906. # else the file in the build folder
  3907. torch_root = Path(torch.__file__).resolve().parent
  3908. path = torch_root / 'lib' / lib_name
  3909. if os.path.exists(path):
  3910. return path
  3911. torch_root = Path(__file__).resolve().parent.parent.parent
  3912. return torch_root / 'build' / 'lib' / lib_name
  3913. def skip_but_pass_in_sandcastle(reason):
  3914. """
  3915. Similar to unittest.skip, however in the sandcastle environment it just
  3916. "passes" the test instead to avoid creating tasks complaining about tests
  3917. skipping continuously.
  3918. """
  3919. def decorator(func):
  3920. if not IS_SANDCASTLE: # noqa: F821
  3921. func.__unittest_skip__ = True
  3922. func.__unittest_skip_why__ = reason
  3923. return func
  3924. @wraps(func)
  3925. def wrapper(*args, **kwargs):
  3926. print(f'Skipping {func.__name__} on sandcastle for following reason: {reason}', file=sys.stderr)
  3927. return
  3928. return wrapper
  3929. return decorator
  3930. def mock_wrapper(method):
  3931. """
  3932. Returns a function that calls the real implementation of a method
  3933. in addition to passing args to a mock object.
  3934. """
  3935. mock = MagicMock()
  3936. @wraps(method)
  3937. def wrapper(self, *args, **kwargs):
  3938. mock(*args, **kwargs)
  3939. return method(self, *args, **kwargs)
  3940. wrapper.mock = mock # type: ignore[attr-defined]
  3941. return wrapper
  3942. def get_tensors_from(args, kwargs):
  3943. """ Returns a set of all Tensor objects in the given args and kwargs. """
  3944. return set([arg for arg in args if isinstance(arg, Tensor)] +
  3945. [v for v in kwargs.values() if isinstance(v, Tensor)])
  3946. # Returns scalar tensor representation of a list of integer byte values
  3947. def bytes_to_scalar(byte_list: List[int], dtype: torch.dtype, device: torch.device):
  3948. dtype_to_ctype: Dict[torch.dtype, Any] = {
  3949. torch.int8: ctypes.c_int8,
  3950. torch.uint8: ctypes.c_uint8,
  3951. torch.uint16: ctypes.c_uint16,
  3952. torch.uint32: ctypes.c_uint32,
  3953. torch.uint64: ctypes.c_uint64,
  3954. torch.int16: ctypes.c_int16,
  3955. torch.int32: ctypes.c_int32,
  3956. torch.int64: ctypes.c_int64,
  3957. torch.bool: ctypes.c_bool,
  3958. torch.float32: ctypes.c_float,
  3959. torch.complex64: ctypes.c_float,
  3960. torch.float64: ctypes.c_double,
  3961. torch.complex128: ctypes.c_double,
  3962. }
  3963. ctype = dtype_to_ctype[dtype]
  3964. num_bytes = ctypes.sizeof(ctype)
  3965. def check_bytes(byte_list):
  3966. for byte in byte_list:
  3967. assert 0 <= byte <= 255
  3968. if dtype.is_complex:
  3969. assert len(byte_list) == (num_bytes * 2)
  3970. check_bytes(byte_list)
  3971. real = ctype.from_buffer((ctypes.c_byte * num_bytes)(
  3972. *byte_list[:num_bytes])).value
  3973. imag = ctype.from_buffer((ctypes.c_byte * num_bytes)(
  3974. *byte_list[num_bytes:])).value
  3975. res = real + 1j * imag
  3976. else:
  3977. assert len(byte_list) == num_bytes
  3978. check_bytes(byte_list)
  3979. res = ctype.from_buffer((ctypes.c_byte * num_bytes)(
  3980. *byte_list)).value
  3981. return torch.tensor(res, device=device, dtype=dtype)
  3982. def copy_func(f):
  3983. """Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)"""
  3984. g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__,
  3985. argdefs=f.__defaults__,
  3986. closure=f.__closure__)
  3987. g = functools.update_wrapper(g, f)
  3988. g.__kwdefaults__ = f.__kwdefaults__
  3989. return g
  3990. def xfail_inherited_tests(tests):
  3991. """
  3992. Given a list of test names which are defined by a superclass of the
  3993. class this decorates, mark them as expected failure. This is useful
  3994. if you are doing poor man's parameterized tests by subclassing a generic
  3995. test class.
  3996. """
  3997. def deco(cls):
  3998. for t in tests:
  3999. # NB: expectedFailure operates by mutating the method in question,
  4000. # which is why you have to copy the function first
  4001. setattr(cls, t, unittest.expectedFailure(copy_func(getattr(cls, t))))
  4002. return cls
  4003. return deco
  4004. def skip_but_pass_in_sandcastle_if(condition, reason):
  4005. """
  4006. Similar to unittest.skipIf, however in the sandcastle environment it just
  4007. "passes" the test instead to avoid creating tasks complaining about tests
  4008. skipping continuously.
  4009. """
  4010. def decorator(func):
  4011. if condition:
  4012. if IS_SANDCASTLE: # noqa: F821
  4013. @wraps(func)
  4014. def wrapper(*args, **kwargs):
  4015. print(f'Skipping {func.__name__} on sandcastle for following reason: {reason}', file=sys.stderr)
  4016. return wrapper
  4017. else:
  4018. func.__unittest_skip__ = True
  4019. func.__unittest_skip_why__ = reason
  4020. return func
  4021. return decorator
  4022. def dtype_name(dtype):
  4023. """ Returns the pretty name of the dtype (e.g. torch.int64 -> int64). """
  4024. return str(dtype).split('.')[1]
  4025. dtype_abbrs = {
  4026. torch.bfloat16: 'bf16',
  4027. torch.float64: 'f64',
  4028. torch.float32: 'f32',
  4029. torch.float16: 'f16',
  4030. torch.complex32: 'c32',
  4031. torch.complex64: 'c64',
  4032. torch.complex128: 'c128',
  4033. torch.int8: 'i8',
  4034. torch.int16: 'i16',
  4035. torch.int32: 'i32',
  4036. torch.int64: 'i64',
  4037. torch.bool: 'b8',
  4038. torch.uint8: 'u8',
  4039. }
  4040. @functools.lru_cache
  4041. def get_cycles_per_ms() -> float:
  4042. """Measure and return approximate number of cycles per millisecond for torch.cuda._sleep
  4043. """
  4044. def measure() -> float:
  4045. start = torch.cuda.Event(enable_timing=True)
  4046. end = torch.cuda.Event(enable_timing=True)
  4047. start.record()
  4048. torch.cuda._sleep(1000000)
  4049. end.record()
  4050. end.synchronize()
  4051. cycles_per_ms = 1000000 / start.elapsed_time(end)
  4052. return cycles_per_ms
  4053. # Get 10 values and remove the 2 max and 2 min and return the avg.
  4054. # This is to avoid system disturbance that skew the results, e.g.
  4055. # the very first cuda call likely does a bunch of init, which takes
  4056. # much longer than subsequent calls.
  4057. #
  4058. # Tested on both Tesla V100, Quadro GP100, Titan RTX, RTX 3090 GPUs
  4059. # and seems to return stable values. Therefore, we enable caching
  4060. # using lru_cache decorator above.
  4061. num = 10
  4062. vals = []
  4063. for _ in range(num):
  4064. vals.append(measure())
  4065. vals = sorted(vals)
  4066. return mean(vals[2 : num - 2])
  4067. # OpInfo utils
  4068. T = TypeVar('T')
  4069. def first_sample(self: unittest.TestCase, samples: Iterable[T]) -> T:
  4070. """
  4071. Returns the first sample from an iterable of samples, like those returned by OpInfo.
  4072. The test will be skipped if no samples are available.
  4073. """
  4074. try:
  4075. return next(iter(samples))
  4076. except StopIteration as e:
  4077. raise unittest.SkipTest('Skipped! Need at least 1 sample input') from e
  4078. # this helper method is to recursively
  4079. # clone the tensor-type input of operators tested by OpInfo
  4080. def clone_input_helper(input):
  4081. if isinstance(input, torch.Tensor):
  4082. return torch.clone(input)
  4083. if isinstance(input, Sequence):
  4084. return tuple(map(clone_input_helper, input))
  4085. return input
  4086. @contextmanager
  4087. def custom_op(opname, symbolic_fn, opset_version):
  4088. """Context manager/decorator to test ONNX export with custom operator"""
  4089. try:
  4090. register_custom_op_symbolic(opname, symbolic_fn, opset_version)
  4091. yield
  4092. finally:
  4093. unregister_custom_op_symbolic(opname, opset_version)
  4094. def outs_and_grads(fn, graph_inps, inps):
  4095. outs = fn(*graph_inps)
  4096. for out in pytree.tree_leaves(outs):
  4097. if isinstance(out, torch.Tensor) and out.requires_grad:
  4098. out.sum().backward(retain_graph=True)
  4099. grads = [inp.grad for inp in pytree.tree_leaves(inps) if isinstance(inp, torch.Tensor)]
  4100. for inp in pytree.tree_leaves(inps):
  4101. if isinstance(inp, torch.Tensor):
  4102. inp.grad = None
  4103. return outs, grads
  4104. def compare_equal_outs_and_grads(test, m1, m2, inps):
  4105. r1, g1 = outs_and_grads(m1, inps, inps)
  4106. r2, g2 = outs_and_grads(m2, inps, inps)
  4107. test.assertEqual(r1, r2)
  4108. test.assertEqual(g1, g2)
  4109. class TestGradients(TestCase):
  4110. exact_dtype = True
  4111. # Copies inputs to inplace operations to avoid inplace modifications
  4112. # to leaves requiring gradient
  4113. def _get_safe_inplace(self, inplace_variant):
  4114. @wraps(inplace_variant)
  4115. def _fn(t, *args, **kwargs):
  4116. return inplace_variant(t.clone(), *args, **kwargs)
  4117. return _fn
  4118. def _check_helper(self, device, dtype, op, variant, check, *, check_forward_ad=False, check_backward_ad=True,
  4119. check_batched_grad=None, check_batched_forward_grad=False):
  4120. assert check in ('gradcheck', 'bwgrad_bwgrad', 'fwgrad_bwgrad')
  4121. # NB: check_backward_ad does not affect gradgradcheck (always True)
  4122. if variant is None:
  4123. self.skipTest("Skipped! Variant not implemented.")
  4124. if not op.supports_dtype(dtype, torch.device(device).type):
  4125. self.skipTest(f"Skipped! {op.name} does not support dtype {str(dtype)}")
  4126. def is_inplace(variant):
  4127. if hasattr(variant, "__wrapped__"):
  4128. return variant.__wrapped__ is op.get_inplace()
  4129. return variant is op.get_inplace()
  4130. include_conjugated_inputs = op.test_conjugated_samples and dtype.is_complex
  4131. samples = op.sample_inputs(device, dtype, requires_grad=True, include_conjugated_inputs=include_conjugated_inputs,
  4132. small_inputs_only=TEST_WITH_SLOW_GRADCHECK) # noqa: F821
  4133. for sample in samples:
  4134. if sample.broadcasts_input and is_inplace(variant):
  4135. continue
  4136. # Gradcheck expects tensors as its input, but autograd actually supports tensorlists
  4137. # and tensors passed as kwargs. The following creates a function that accepts just
  4138. # the tensors that require grad as varargs, and then recomposes them back into the
  4139. # original input.
  4140. # Creates gradcheck inputs by identifying tensors requiring grad
  4141. all_args = None
  4142. if is_iterable_of_tensors(sample.input):
  4143. all_args = chain(sample.input, sample.args, sample.kwargs.values())
  4144. else:
  4145. all_args = tuple(chain((sample.input,), sample.args, sample.kwargs.values()))
  4146. gradcheck_args = tuple(x for x in all_args if (isinstance(x, torch.Tensor) and x.requires_grad))
  4147. # Verifies sample input tensors should have no grad
  4148. # This may happen if the same tensor is used in two different SampleInputs
  4149. for t in gradcheck_args:
  4150. self.assertIsNone(t.grad,
  4151. "A sampled input has a gradient before running autograd. "
  4152. "This usually means that (at least) one input tensor is reused "
  4153. "across different SampleInputs. "
  4154. "Please create a new tensor for each SampleInput.")
  4155. def _input_recomposition_helper(inputs, inp, input_idx):
  4156. if is_iterable_of_tensors(inp):
  4157. tensor_list = []
  4158. for x in inp:
  4159. if isinstance(x, torch.Tensor) and x.requires_grad:
  4160. tensor_list.append(inputs[input_idx])
  4161. input_idx = input_idx + 1
  4162. else:
  4163. tensor_list.append(x)
  4164. return tensor_list, input_idx
  4165. elif isinstance(inp, torch.Tensor) and inp.requires_grad:
  4166. return inputs[input_idx], input_idx + 1
  4167. else:
  4168. return inp, input_idx
  4169. def fn(*inputs):
  4170. # Puts inputs back into sample properly
  4171. positional_args = []
  4172. input_idx = 0
  4173. inp, input_idx = _input_recomposition_helper(inputs, sample.input, input_idx)
  4174. positional_args.append(inp)
  4175. for x in sample.args:
  4176. inp, input_idx = _input_recomposition_helper(inputs, x, input_idx)
  4177. positional_args.append(inp)
  4178. # Recreates kwargs
  4179. kwargs = {}
  4180. for k, v in sample.kwargs.items():
  4181. inp, input_idx = _input_recomposition_helper(inputs, v, input_idx)
  4182. kwargs[k] = inp
  4183. output = op.gradcheck_wrapper(variant, *positional_args, **kwargs)
  4184. if sample.output_process_fn_grad is not None:
  4185. return sample.output_process_fn_grad(output)
  4186. return output
  4187. if check == 'gradcheck':
  4188. if check_batched_grad is None:
  4189. check_batched_grad = op.check_batched_grad
  4190. self.assertTrue(gradcheck(fn, gradcheck_args,
  4191. check_batched_grad=check_batched_grad,
  4192. check_grad_dtypes=True,
  4193. nondet_tol=op.gradcheck_nondet_tol,
  4194. fast_mode=op.gradcheck_fast_mode,
  4195. check_forward_ad=check_forward_ad,
  4196. check_backward_ad=check_backward_ad,
  4197. check_undefined_grad=True,
  4198. check_batched_forward_grad=check_batched_forward_grad))
  4199. elif check in ('bwgrad_bwgrad', 'fwgrad_bwgrad'): # gradgrad check
  4200. self.assertFalse(check_forward_ad, msg="Cannot run forward AD check for gradgradcheck")
  4201. for gen_non_contig_grad_outputs in (False, True):
  4202. kwargs = {
  4203. "gen_non_contig_grad_outputs": gen_non_contig_grad_outputs,
  4204. "check_batched_grad": op.check_batched_gradgrad,
  4205. "check_grad_dtypes": True,
  4206. "nondet_tol": op.gradcheck_nondet_tol,
  4207. "fast_mode": op.gradcheck_fast_mode
  4208. }
  4209. if check == "fwgrad_bwgrad":
  4210. kwargs["check_fwd_over_rev"] = True
  4211. kwargs["check_rev_over_rev"] = False
  4212. kwargs["check_batched_grad"] = False
  4213. kwargs["check_undefined_grad"] = False
  4214. self.assertTrue(gradgradcheck(fn, gradcheck_args, **kwargs))
  4215. else:
  4216. self.assertTrue(False, msg="Unknown check requested!")
  4217. def _grad_test_helper(self, device, dtype, op, variant, *, check_forward_ad=False, check_backward_ad=True,
  4218. check_batched_grad=None, check_batched_forward_grad=False):
  4219. return self._check_helper(device, dtype, op, variant, 'gradcheck', check_forward_ad=check_forward_ad,
  4220. check_backward_ad=check_backward_ad, check_batched_grad=check_batched_grad,
  4221. check_batched_forward_grad=check_batched_forward_grad)
  4222. def _skip_helper(self, op, device, dtype):
  4223. if dtype not in op.supported_backward_dtypes(torch.device(device).type):
  4224. self.skipTest("Skipped! Op doesn't support autograd for this dtype.")
  4225. if not op.supports_autograd and not op.supports_forward_ad:
  4226. self.skipTest("Skipped! autograd not supported.")
  4227. def make_lazy_class(cls):
  4228. def lazy_init(self, cb):
  4229. self._cb = cb
  4230. self._value = None
  4231. cls.__init__ = lazy_init
  4232. for basename in [
  4233. "add", "sub", "mul", "truediv", "floordiv", "mod", "divmod", "pow",
  4234. "lshift", "rshift", "and", "or", "xor", "neg", "pos", "abs", "invert",
  4235. "eq", "ne", "lt", "le", "gt", "ge", "bool", "int", "index",
  4236. ]:
  4237. name = f"__{basename}__"
  4238. def inner_wrapper(name):
  4239. use_operator = basename not in ("bool", "int")
  4240. def wrapped(self, *args, **kwargs):
  4241. if self._cb is not None:
  4242. self._value = self._cb()
  4243. self._cb = None
  4244. if not use_operator:
  4245. return getattr(self._value, name)(*args, **kwargs)
  4246. else:
  4247. return getattr(operator, name)(self._value, *args, **kwargs)
  4248. return wrapped
  4249. setattr(cls, name, inner_wrapper(name))
  4250. return cls
  4251. @make_lazy_class
  4252. class LazyVal:
  4253. pass
  4254. def munge_exc(e, *, suppress_suffix=True, suppress_prefix=True, file=None, skip=0):
  4255. if file is None:
  4256. file = inspect.stack()[1 + skip].filename # skip one frame
  4257. s = str(e)
  4258. # Remove everything that looks like stack frames in NOT this file
  4259. def repl_frame(m):
  4260. if m.group(1) != file:
  4261. return ""
  4262. # Don't accept top-level, even for this script, these will wobble
  4263. # depending on how the testing script was invoked
  4264. if m.group(2) == "<module>":
  4265. return ""
  4266. return m.group(0)
  4267. s = re.sub(r' File "([^"]+)", line \d+, in (.+)\n .+\n( +[~^]+ *\n)?', repl_frame, s)
  4268. s = re.sub(r"line \d+", "line N", s)
  4269. s = re.sub(r".py:\d+", ".py:N", s)
  4270. s = re.sub(file, os.path.basename(file), s)
  4271. s = re.sub(os.path.join(os.path.dirname(torch.__file__), ""), "", s)
  4272. s = re.sub(r"\\", "/", s) # for Windows
  4273. if suppress_suffix:
  4274. s = re.sub(r"\n*Set TORCH_LOGS.+", "", s, flags=re.DOTALL)
  4275. s = re.sub(r"\n*You can suppress this exception.+", "", s, flags=re.DOTALL)
  4276. if suppress_prefix:
  4277. s = re.sub(r"Cannot export model.+\n\n", "", s)
  4278. s = re.sub(r" +$", "", s, flags=re.M)
  4279. return s