common_utils.py 180 KB

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