common_modules.py 212 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445
  1. # mypy: ignore-errors
  2. import torch
  3. import unittest
  4. from copy import deepcopy
  5. from enum import Enum
  6. from functools import wraps, partial
  7. from itertools import chain, product
  8. import itertools
  9. import math
  10. import torch.nn.functional as F
  11. from torch.nn.utils.rnn import pack_padded_sequence
  12. from torch.testing import make_tensor
  13. from torch.testing._internal.common_cuda import TEST_CUDNN
  14. from torch.testing._internal.common_dtype import (
  15. floating_types, floating_and_complex_types_and, get_all_fp_dtypes)
  16. from torch.testing._internal.common_device_type import (
  17. _TestParametrizer, _update_param_kwargs, toleranceOverride, tol,
  18. skipCUDAIfCudnnVersionLessThan, skipCUDAIfRocm, precisionOverride, skipMeta, skipMPS, skipCUDAVersionIn)
  19. from torch.testing._internal.common_methods_invocations import DecorateInfo
  20. from torch.testing._internal.common_nn import (
  21. cosineembeddingloss_reference, cross_entropy_loss_reference, ctcloss_reference,
  22. hingeembeddingloss_reference, huberloss_reference, kldivloss_reference,
  23. marginrankingloss_reference, multimarginloss_reference, multilabelmarginloss_reference,
  24. nllloss_reference, nlllossNd_reference, smoothl1loss_reference, softmarginloss_reference, get_reduction)
  25. from torch.testing._internal.common_utils import (
  26. freeze_rng_state, skipIfMps, GRADCHECK_NONDET_TOL, TEST_WITH_ROCM, IS_WINDOWS,
  27. skipIfTorchDynamo)
  28. from types import ModuleType
  29. from typing import List, Tuple, Type, Set, Dict
  30. import operator
  31. # List of all namespaces containing modules to test.
  32. MODULE_NAMESPACES: List[ModuleType] = [
  33. torch.nn.modules,
  34. torch.ao.nn.qat.modules,
  35. torch.ao.nn.quantizable.modules,
  36. torch.ao.nn.quantized.modules,
  37. torch.ao.nn.quantized.modules,
  38. ]
  39. # Modules that shouldn't be tested for one reason or another.
  40. MODULES_TO_SKIP: Set[Type] = {
  41. torch.nn.Module, # abstract base class
  42. torch.nn.Container, # deprecated
  43. torch.nn.NLLLoss2d, # deprecated
  44. torch.ao.nn.quantized.MaxPool2d, # aliases to nn.MaxPool2d
  45. torch.ao.nn.quantized.MaxPool2d, # aliases to nn.MaxPool2d
  46. }
  47. # List of all module classes to test.
  48. MODULE_CLASSES: List[Type] = list(chain(*[
  49. [getattr(namespace, module_name) for module_name in namespace.__all__] # type: ignore[attr-defined]
  50. for namespace in MODULE_NAMESPACES]))
  51. MODULE_CLASSES = [cls for cls in MODULE_CLASSES if cls not in MODULES_TO_SKIP]
  52. # Dict of module class -> common name. Useful for making test names more intuitive.
  53. # Example: torch.nn.modules.linear.Linear -> "nn.Linear"
  54. MODULE_CLASS_NAMES: Dict[Type, str] = {}
  55. for namespace in MODULE_NAMESPACES:
  56. for module_name in namespace.__all__: # type: ignore[attr-defined]
  57. module_cls = getattr(namespace, module_name)
  58. namespace_name = namespace.__name__.replace('torch.', '').replace('.modules', '')
  59. # Deal with any aliases by preferring earlier names.
  60. if module_cls not in MODULE_CLASS_NAMES:
  61. MODULE_CLASS_NAMES[module_cls] = f'{namespace_name}.{module_name}'
  62. # Specifies the modes (i.e. train, eval) to test over.
  63. TrainEvalMode = Enum('TrainEvalMode', ('train_only', 'eval_only', 'train_and_eval'))
  64. class modules(_TestParametrizer):
  65. """ PROTOTYPE: Decorator for specifying a list of modules over which to run a test. """
  66. def __init__(self, module_info_iterable, allowed_dtypes=None,
  67. train_eval_mode=TrainEvalMode.train_and_eval, skip_if_dynamo=True):
  68. self.module_info_list = list(module_info_iterable)
  69. self.allowed_dtypes = set(allowed_dtypes) if allowed_dtypes is not None else None
  70. self.train_eval_mode = train_eval_mode
  71. self.skip_if_dynamo = skip_if_dynamo
  72. def _get_training_flags(self, module_info):
  73. training_flags = []
  74. if (self.train_eval_mode == TrainEvalMode.train_only or
  75. self.train_eval_mode == TrainEvalMode.train_and_eval):
  76. training_flags.append(True)
  77. if (self.train_eval_mode == TrainEvalMode.eval_only or
  78. self.train_eval_mode == TrainEvalMode.train_and_eval):
  79. training_flags.append(False)
  80. # If train and eval modes don't differ for the module, don't bother using more than one.
  81. if not module_info.train_and_eval_differ:
  82. training_flags = training_flags[:1]
  83. return training_flags
  84. def _parametrize_test(self, test, generic_cls, device_cls):
  85. if device_cls is None:
  86. raise RuntimeError('The @modules decorator is only intended to be used in a device-specific '
  87. 'context; use it with instantiate_device_type_tests() instead of '
  88. 'instantiate_parametrized_tests()')
  89. for module_info in self.module_info_list:
  90. dtypes = set(module_info.supported_dtypes(device_cls.device_type))
  91. if self.allowed_dtypes is not None:
  92. dtypes = dtypes.intersection(self.allowed_dtypes)
  93. training_flags = self._get_training_flags(module_info)
  94. for (training, dtype) in product(training_flags, dtypes):
  95. # Construct the test name; device / dtype parts are handled outside.
  96. # See [Note: device and dtype suffix placement]
  97. test_name = module_info.formatted_name
  98. if len(training_flags) > 1:
  99. test_name += f"_{'train_mode' if training else 'eval_mode'}"
  100. # Construct parameter kwargs to pass to the test.
  101. param_kwargs = {'module_info': module_info}
  102. _update_param_kwargs(param_kwargs, 'dtype', dtype)
  103. _update_param_kwargs(param_kwargs, 'training', training)
  104. try:
  105. @wraps(test)
  106. def test_wrapper(*args, **kwargs):
  107. return test(*args, **kwargs)
  108. if self.skip_if_dynamo and not torch.testing._internal.common_utils.TEST_WITH_TORCHINDUCTOR:
  109. test_wrapper = skipIfTorchDynamo("Policy: we don't run ModuleInfo tests w/ Dynamo")(test_wrapper)
  110. decorator_fn = partial(module_info.get_decorators, generic_cls.__name__,
  111. test.__name__, device_cls.device_type, dtype)
  112. yield (test_wrapper, test_name, param_kwargs, decorator_fn)
  113. except Exception as ex:
  114. # Provides an error message for debugging before rethrowing the exception
  115. print(f"Failed to instantiate {test_name} for module {module_info.name}!")
  116. raise ex
  117. def get_module_common_name(module_cls):
  118. if module_cls in MODULE_CLASS_NAMES:
  119. # Example: "nn.Linear"
  120. return MODULE_CLASS_NAMES[module_cls]
  121. else:
  122. return module_cls.__name__
  123. class FunctionInput:
  124. """ Contains args and kwargs to pass as input to a function. """
  125. __slots__ = ['args', 'kwargs']
  126. def __init__(self, *args, **kwargs):
  127. self.args = args
  128. self.kwargs = kwargs
  129. class ModuleInput:
  130. """ Contains args / kwargs for module instantiation + forward pass. """
  131. __slots__ = ['constructor_input', 'forward_input', 'desc', 'reference_fn']
  132. def __init__(self, constructor_input, forward_input=None, desc='', reference_fn=None):
  133. self.constructor_input = constructor_input # Inputs to pass during construction
  134. self.forward_input = forward_input # Inputs to pass to forward()
  135. self.desc = desc # Description for this set of inputs
  136. self.reference_fn = reference_fn # Reference with signature: reference_fn(module, parameters, *args, **kwargs)
  137. if reference_fn is not None:
  138. @wraps(reference_fn)
  139. def copy_reference_fn(m, *args, **kwargs):
  140. # Copy inputs to avoid undesired side effects from calling the reference.
  141. args, kwargs = deepcopy(args), deepcopy(kwargs)
  142. # Note that module parameters are passed in for convenience.
  143. return reference_fn(m, list(m.parameters()), *args, **kwargs)
  144. self.reference_fn = copy_reference_fn
  145. class ModuleErrorEnum(Enum):
  146. """ Enumerates when error is raised when testing modules. """
  147. CONSTRUCTION_ERROR = 0
  148. FORWARD_ERROR = 1
  149. class ErrorModuleInput:
  150. """
  151. A ModuleInput that will cause the operation to throw an error plus information
  152. about the resulting error.
  153. """
  154. __slots__ = ["module_error_input", "error_on", "error_type", "error_regex"]
  155. def __init__(self,
  156. module_error_input,
  157. *,
  158. error_on=ModuleErrorEnum.CONSTRUCTION_ERROR,
  159. error_type=RuntimeError,
  160. error_regex):
  161. self.module_error_input = module_error_input
  162. self.error_on = error_on
  163. self.error_type = error_type
  164. self.error_regex = error_regex
  165. class ModuleInfo:
  166. """ Module information to be used in testing. """
  167. def __init__(self,
  168. module_cls, # Class object for the module under test
  169. *,
  170. module_inputs_func, # Function to generate module inputs
  171. skips=(), # Indicates which tests to skip
  172. decorators=None, # Additional decorators to apply to generated tests
  173. dtypes=floating_types(), # dtypes this function is expected to work with
  174. dtypesIfMPS=(torch.float16, torch.float32,), # dtypes this function is expected to work with on MPS
  175. supports_gradgrad=True, # whether the op supports second order gradients
  176. gradcheck_nondet_tol=0.0, # tolerance for nondeterminism while performing gradcheck
  177. module_memformat_affects_out=False, # whether converting module to channels last will generate
  178. # channels last output
  179. train_and_eval_differ=False, # whether the module has differing behavior between train and eval
  180. module_error_inputs_func=None, # Function to generate module inputs that error
  181. ):
  182. self.module_cls = module_cls
  183. self.module_inputs_func = module_inputs_func
  184. self.decorators = (*(decorators if decorators else []), *(skips if skips else []))
  185. self.dtypes = dtypes
  186. self.dtypesIfMPS = dtypesIfMPS
  187. self.supports_gradgrad = supports_gradgrad
  188. self.gradcheck_nondet_tol = gradcheck_nondet_tol
  189. self.module_memformat_affects_out = module_memformat_affects_out
  190. self.train_and_eval_differ = train_and_eval_differ
  191. self.module_error_inputs_func = module_error_inputs_func
  192. self.is_lazy = issubclass(module_cls, torch.nn.modules.lazy.LazyModuleMixin)
  193. def get_decorators(self, test_class, test_name, device, dtype, param_kwargs):
  194. result = []
  195. for decorator in self.decorators:
  196. if isinstance(decorator, DecorateInfo):
  197. if decorator.is_active(test_class, test_name, device, dtype, param_kwargs):
  198. result.extend(decorator.decorators)
  199. else:
  200. result.append(decorator)
  201. return result
  202. def supported_dtypes(self, device_type):
  203. if device_type == 'mps':
  204. return self.dtypesIfMPS
  205. else:
  206. return self.dtypes
  207. @property
  208. def name(self):
  209. return get_module_common_name(self.module_cls)
  210. @property
  211. def formatted_name(self):
  212. return self.name.replace('.', '_')
  213. # Start of module inputs functions.
  214. def module_inputs_torch_nn_Linear(module_info, device, dtype, requires_grad, training, **kwargs):
  215. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  216. module_inputs = [
  217. ModuleInput(constructor_input=FunctionInput(10, 8),
  218. forward_input=FunctionInput(input=make_input((4, 10))),
  219. reference_fn=lambda m, p, input: torch.mm(input, p[0].t()) + p[1].view(1, -1).expand(4, 8)),
  220. ModuleInput(constructor_input=FunctionInput(10, 8, bias=False),
  221. forward_input=FunctionInput(make_input((4, 10))),
  222. desc='no_bias',
  223. reference_fn=lambda m, p, i: torch.mm(i, p[0].t())),
  224. ModuleInput(constructor_input=FunctionInput(3, 5),
  225. forward_input=FunctionInput(make_input(3)),
  226. desc='no_batch_dim',
  227. reference_fn=lambda m, p, i: torch.mm(i.view(1, -1), p[0].t()).view(-1) + p[1])
  228. ]
  229. return module_inputs
  230. def module_inputs_torch_nn_Bilinear(module_info, device, dtype, requires_grad, training, **kwargs):
  231. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  232. def bilinear_reference_fn(m, p, x1, x2, bias=True):
  233. result = torch.einsum('bn,anm,bm->ba', x1, p[0], x2)
  234. if bias:
  235. if x1.shape[0] == 1:
  236. result = result.view(-1) + p[1]
  237. else:
  238. result = result + p[1].view(1, -1).expand(x1.shape[0], p[0].shape[0])
  239. return result
  240. module_inputs = [
  241. ModuleInput(constructor_input=FunctionInput(2, 3, 4),
  242. forward_input=FunctionInput(make_input((8, 2)), make_input((8, 3))),
  243. reference_fn=bilinear_reference_fn),
  244. ModuleInput(constructor_input=FunctionInput(2, 3, 4, bias=False),
  245. forward_input=FunctionInput(make_input((8, 2)), make_input((8, 3))),
  246. desc='no_bias',
  247. reference_fn=lambda m, p, x1, x2: bilinear_reference_fn(m, p, x1, x2, bias=False)),
  248. ModuleInput(constructor_input=FunctionInput(2, 3, 4),
  249. forward_input=FunctionInput(make_input(2), make_input(3)),
  250. desc='no_batch_dim',
  251. reference_fn=lambda m, p, x1, x2: bilinear_reference_fn(m, p, x1.view(1, -1), x2.view(1, -1))),
  252. ]
  253. return module_inputs
  254. def module_inputs_torch_nn_KLDivLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  255. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  256. cases: List[Tuple[str, dict]] = [
  257. ('', {}),
  258. ('reduction_sum', {'reduction': 'sum'}),
  259. ('reduction_batchmean', {'reduction': 'batchmean'}),
  260. ('reduction_none', {'reduction': 'none'}),
  261. ('log_target', {'log_target': True})
  262. ]
  263. module_inputs = []
  264. for desc, constructor_kwargs in cases:
  265. def reference_fn(m, p, i, t, constructor_kwargs=constructor_kwargs):
  266. return kldivloss_reference(i, t, **constructor_kwargs)
  267. input = make_input((10, 10)).log()
  268. target = make_input((10, 10)) if kwargs.get('log_target', False) else make_input((10, 10)).log()
  269. module_inputs.append(
  270. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  271. forward_input=FunctionInput(input, target),
  272. desc=desc,
  273. reference_fn=reference_fn)
  274. )
  275. scalar_input = make_input(()).log()
  276. scalar_target = make_input(()) if kwargs.get('log_target', False) else make_input(()).log()
  277. module_inputs.append(
  278. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  279. forward_input=FunctionInput(scalar_input, scalar_input),
  280. desc='scalar_' + desc,
  281. reference_fn=reference_fn)
  282. )
  283. return module_inputs
  284. def module_inputs_torch_nn_NLLLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  285. def make_input(shape, device=device, dtype=dtype, requires_grad=requires_grad):
  286. return make_tensor(shape, device=device, dtype=dtype,
  287. requires_grad=False).log_softmax(dim=1).requires_grad_(requires_grad)
  288. make_weight = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  289. cases: List[Tuple[str, dict]] = [
  290. ('', {}),
  291. ('reduction_sum', {'reduction': 'sum'}),
  292. ('reduction_none', {'reduction': 'none'}),
  293. ('ignore_index', {'ignore_index': 2}),
  294. ('weights', {'weight': make_weight(4).abs()}),
  295. ('weights_ignore_index', {'weight': make_weight(4).abs(), 'ignore_index': 2}),
  296. ('weights_ignore_index_neg', {'weight': make_weight(4).abs(), 'ignore_index': -1})
  297. ]
  298. # TODO: Uncomment when negative weights is supported.
  299. # negative_weight = make_weight(10)
  300. # negative_weight[0] = -1
  301. # cases.append(('weights_negative', {'weight': negative_weight}))
  302. module_inputs = []
  303. for desc, constructor_kwargs in cases:
  304. def reference_fn(m, p, i, t, constructor_kwargs=constructor_kwargs):
  305. return nllloss_reference(i, t, **constructor_kwargs)
  306. module_inputs.append(
  307. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  308. forward_input=FunctionInput(make_input((15, 4)),
  309. torch.empty(15, device=device).uniform_().mul(4).floor().long()),
  310. desc=desc,
  311. reference_fn=reference_fn)
  312. )
  313. def nd_reference_fn(m, p, i, t, constructor_kwargs=constructor_kwargs):
  314. return nlllossNd_reference(i, t, **constructor_kwargs)
  315. module_inputs.append(
  316. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  317. forward_input=FunctionInput(
  318. make_input((2, 4, 5, 5)),
  319. torch.empty(2, 5, 5, device=device).uniform_().mul(4).floor().long()),
  320. desc=f"nd_{desc}",
  321. reference_fn=nd_reference_fn)
  322. )
  323. module_inputs.append(
  324. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  325. forward_input=FunctionInput(
  326. make_input((2, 4, 5, 5, 2, 2)),
  327. torch.empty(2, 5, 5, 2, 2, device=device).uniform_().mul(4).floor().long()),
  328. desc=f"higher_dim_{desc}",
  329. reference_fn=nd_reference_fn)
  330. )
  331. module_inputs.append(
  332. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  333. forward_input=FunctionInput(
  334. make_input((2, 4, 5)),
  335. torch.empty(2, 5, device=device).uniform_().mul(4).floor().long()),
  336. desc=f"3d_{desc}",
  337. reference_fn=nd_reference_fn)
  338. )
  339. return module_inputs
  340. def module_inputs_torch_nn_GaussianNLLLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  341. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  342. make_target = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  343. cases: List[Tuple[str, dict]] = [
  344. ('', {}),
  345. ('reduction_sum', {'reduction': 'sum'}),
  346. ('reduction_mean', {'reduction': 'mean'}),
  347. ('reduction_none', {'reduction': 'none'}),
  348. ]
  349. module_inputs = []
  350. for desc, constructor_kwargs in cases:
  351. module_inputs.append(
  352. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  353. forward_input=FunctionInput(make_input(3),
  354. make_target(3),
  355. make_input(1).abs()),
  356. desc=desc,
  357. reference_fn=no_batch_dim_reference_fn)
  358. )
  359. return module_inputs
  360. def module_inputs_torch_nn_PoissonNLLLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  361. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  362. make_target = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  363. cases: List[Tuple[str, dict]] = [
  364. ('', {}),
  365. ('reduction_sum', {'reduction': 'sum'}),
  366. ('reduction_mean', {'reduction': 'mean'}),
  367. ('reduction_none', {'reduction': 'none'}),
  368. ('full', {'full': True}),
  369. ('no_log_input', {'log_input': False}),
  370. ('full_no_log_input', {'full': True, 'log_input': False}),
  371. ]
  372. def poissonnllloss_reference_fn(i, t, log_input=True, full=False, reduction='mean', eps=1e-8):
  373. if log_input:
  374. result = i.exp() - t.mul(i)
  375. else:
  376. result = i - t.mul((i + eps).log())
  377. if full:
  378. result += (t.mul(t.log()) - t + 0.5 * (2. * math.pi * t).log()).masked_fill(t <= 1, 0)
  379. if reduction == 'none':
  380. return result
  381. elif reduction == 'mean':
  382. return result.sum() / i.numel()
  383. else:
  384. return result.sum()
  385. module_inputs = []
  386. for desc, constructor_kwargs in cases:
  387. def reference_fn(m, p, i, t, constructor_kwargs=constructor_kwargs):
  388. return poissonnllloss_reference_fn(i, t, **constructor_kwargs)
  389. log_input = constructor_kwargs.get('log_input', True)
  390. input = make_input((2, 3, 4, 5)) if log_input else make_input((2, 3, 4, 5)).abs().add(0.001)
  391. module_inputs.append(
  392. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  393. forward_input=FunctionInput(input,
  394. make_target((2, 3, 4, 5)).floor_().abs_()),
  395. desc=desc,
  396. reference_fn=reference_fn)
  397. )
  398. return module_inputs
  399. def module_inputs_torch_nn_MSELoss(module_info, device, dtype, requires_grad, training, **kwargs):
  400. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  401. make_target = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  402. cases: List[Tuple[str, dict]] = [
  403. ('', {}),
  404. ('reduction_sum', {'reduction': 'sum'}),
  405. ('reduction_mean', {'reduction': 'mean'}),
  406. ('reduction_none', {'reduction': 'none'}),
  407. ]
  408. def mse_loss_reference_fn(m, p, i, t, reduction='mean'):
  409. if reduction == 'none':
  410. return (i - t).pow(2)
  411. elif reduction == 'mean':
  412. return (i - t).pow(2).sum() / i.numel()
  413. else:
  414. return (i - t).pow(2).sum()
  415. module_inputs = []
  416. for desc, constructor_kwargs in cases:
  417. module_inputs.append(
  418. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  419. forward_input=FunctionInput(make_input((2, 3, 4, 5)),
  420. make_target((2, 3, 4, 5))),
  421. desc=desc,
  422. reference_fn=partial(mse_loss_reference_fn, **constructor_kwargs))
  423. )
  424. module_inputs.append(
  425. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  426. forward_input=FunctionInput(make_input(()),
  427. make_target(())),
  428. desc=f'{desc}_scalar',
  429. reference_fn=partial(mse_loss_reference_fn, **constructor_kwargs))
  430. )
  431. return module_inputs
  432. def no_batch_dim_reference_fn(m, p, *args, **kwargs):
  433. """Reference function for modules supporting no batch dimensions.
  434. Unbatched inputs are unsqueezed to form a
  435. single batch input before passing them to the module.
  436. The output is squeezed to compare with the
  437. output of unbatched input to the module.
  438. Currently it only supports modules which return a single Tensor as output.
  439. You can bind the following kwargs.
  440. Kwargs:
  441. batch_first[bool] : If True, all the Tensors in `args` while be unsqueezed at dim `0` .
  442. and output will be squeezed at dim `0` else dim `1` for both.
  443. kwargs_to_batchify[dict] : Dictionary specifying the name of the argument and dimension to unsqueeze.
  444. Useful if there are few arguments whose batch dimension are different
  445. from the ones selected by `batch_first`.
  446. is_criterion[bool] : Specify if the module is a criterion and handle the reduction for output accordingly.
  447. """
  448. def get_and_pop(key, default):
  449. v = kwargs.get(key, default)
  450. if key in kwargs:
  451. kwargs.pop(key)
  452. return v
  453. batch_dim = 0 if get_and_pop('batch_first', True) else 1
  454. kwargs_to_batchify = get_and_pop('kwargs_to_batchify', None)
  455. is_criterion = get_and_pop('is_criterion', False)
  456. if kwargs_to_batchify is not None:
  457. assert isinstance(kwargs_to_batchify, dict)
  458. for k, v in kwargs.items():
  459. if k in kwargs_to_batchify and v is not None:
  460. bdim = kwargs_to_batchify[k]
  461. kwargs[k] = v.unsqueeze(bdim)
  462. single_batch_input_args = [input.unsqueeze(batch_dim) for input in args]
  463. with freeze_rng_state():
  464. output = m(*single_batch_input_args, **kwargs).squeeze(batch_dim)
  465. if is_criterion:
  466. reduction = get_reduction(m)
  467. if reduction == 'none':
  468. return output.squeeze(0)
  469. return output
  470. def no_batch_dim_reference_mha(m, p, *args, **kwargs):
  471. """Reference function for MultiheadAttention supporting no batch dimensions.
  472. Unbatched inputs are unsqueezed to form a
  473. single batch input before passing them to the module.
  474. The output is squeezed to compare with the
  475. output of unbatched input to the module.
  476. """
  477. batch_dim = 0 if kwargs.get('batch_first', True) else 1
  478. if 'batch_first' in kwargs:
  479. kwargs.pop('batch_first')
  480. if 'key_padding_mask' in kwargs and kwargs['key_padding_mask'] is not None:
  481. kwargs['key_padding_mask'] = kwargs['key_padding_mask'].unsqueeze(0)
  482. single_batch_input_args = [input.unsqueeze(batch_dim) for input in args]
  483. with freeze_rng_state():
  484. output = m(*single_batch_input_args, **kwargs)
  485. return (output[0].squeeze(batch_dim), output[1].squeeze(0))
  486. def no_batch_dim_reference_rnn_gru(m, p, *args, **kwargs):
  487. """Reference function for RNN and GRU supporting no batch dimensions.
  488. Unbatched inputs are unsqueezed to form a
  489. single batch input before passing them to the module.
  490. The output is squeezed to compare with the
  491. output of unbatched input to the module.
  492. """
  493. if len(args) == 1:
  494. inp, = args
  495. h = None
  496. elif len(args) == 2:
  497. inp, h = args
  498. h = h.unsqueeze(1)
  499. batch_dim = 0 if kwargs['batch_first'] else 1
  500. kwargs.pop('batch_first')
  501. inp = inp.unsqueeze(batch_dim)
  502. single_batch_input_args = (inp, h)
  503. with freeze_rng_state():
  504. output = m(*single_batch_input_args, **kwargs)
  505. return (output[0].squeeze(batch_dim), output[1].squeeze(1))
  506. def no_batch_dim_reference_lstm(m, p, *args, **kwargs):
  507. """Reference function for LSTM supporting no batch dimensions.
  508. Unbatched inputs are unsqueezed to form a
  509. single batch input before passing them to the module.
  510. The output is squeezed to compare with the
  511. output of unbatched input to the module.
  512. """
  513. if len(args) == 1:
  514. inp, = args
  515. h = None
  516. elif len(args) == 2:
  517. inp, h = args
  518. h = (h[0].unsqueeze(1), h[1].unsqueeze(1))
  519. batch_dim = 0 if kwargs['batch_first'] else 1
  520. kwargs.pop('batch_first')
  521. inp = inp.unsqueeze(batch_dim)
  522. single_batch_input_args = (inp, h)
  523. with freeze_rng_state():
  524. output = m(*single_batch_input_args, **kwargs)
  525. return (output[0].squeeze(batch_dim), (output[1][0].squeeze(1), output[1][1].squeeze(1)))
  526. def no_batch_dim_reference_lstmcell(m, p, *args, **kwargs):
  527. """Reference function for LSTMCell supporting no batch dimensions.
  528. The module is passed the input and target in batched form with a single item.
  529. The output is squeezed to compare with the no-batch input.
  530. """
  531. inp, (h, c) = args
  532. single_batch_input_args = (inp.unsqueeze(0), (h.unsqueeze(0), c.unsqueeze(0)))
  533. with freeze_rng_state():
  534. output = m(*single_batch_input_args, **kwargs)
  535. return (output[0].squeeze(0), output[1].squeeze(0))
  536. def generate_regression_criterion_inputs(make_input):
  537. return [
  538. ModuleInput(
  539. constructor_input=FunctionInput(reduction=reduction),
  540. forward_input=FunctionInput(make_input((4, )), make_input(4,)),
  541. reference_fn=partial(no_batch_dim_reference_fn, is_criterion=True),
  542. desc=f'no_batch_dim_{reduction}'
  543. ) for reduction in ['none', 'mean', 'sum']]
  544. def module_inputs_torch_nn_AvgPool1d(module_info, device, dtype, requires_grad, training, **kwargs):
  545. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  546. return [
  547. ModuleInput(constructor_input=FunctionInput(kernel_size=2),
  548. forward_input=FunctionInput(make_input((3, 6))),
  549. desc='no_batch_dim',
  550. reference_fn=no_batch_dim_reference_fn),
  551. ModuleInput(constructor_input=FunctionInput(2),
  552. forward_input=FunctionInput(make_input((2, 3, 6)))),
  553. ModuleInput(constructor_input=FunctionInput((2,), (2,)),
  554. forward_input=FunctionInput(make_input((2, 3, 6))),
  555. desc='stride'),
  556. ModuleInput(constructor_input=FunctionInput(2, 2, 1),
  557. forward_input=FunctionInput(make_input((2, 3, 6))),
  558. desc='stride_pad')]
  559. def module_inputs_torch_nn_AvgPool2d(module_info, device, dtype, requires_grad, training, **kwargs):
  560. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  561. return [
  562. ModuleInput(constructor_input=FunctionInput((2, 2)),
  563. forward_input=FunctionInput(make_input((3, 6, 6))),
  564. desc='no_batch_dim',
  565. reference_fn=no_batch_dim_reference_fn),
  566. ModuleInput(constructor_input=FunctionInput((2, 2)),
  567. forward_input=FunctionInput(make_input((2, 3, 6, 6)))),
  568. ModuleInput(constructor_input=FunctionInput((2, 2), (2, 2)),
  569. forward_input=FunctionInput(make_input((2, 3, 6, 6))),
  570. desc='stride'),
  571. ModuleInput(constructor_input=FunctionInput((2, 2), (2, 2), (1, 1)),
  572. forward_input=FunctionInput(make_input((2, 3, 6, 6))),
  573. desc='stride_pad'),
  574. ModuleInput(constructor_input=FunctionInput((2, 2), divisor_override=1),
  575. forward_input=FunctionInput(make_input((2, 3, 6, 6))),
  576. desc='divisor'),
  577. ModuleInput(constructor_input=FunctionInput((2, 2), (2, 2), divisor_override=1),
  578. forward_input=FunctionInput(make_input((2, 3, 6, 6))),
  579. desc='divisor_stride'),
  580. ModuleInput(constructor_input=FunctionInput((2, 2), (2, 2), (1, 1), divisor_override=1),
  581. forward_input=FunctionInput(make_input((2, 3, 6, 6))),
  582. desc='divisor_stride_pad')]
  583. def module_inputs_torch_nn_AvgPool3d(module_info, device, dtype, requires_grad, training, **kwargs):
  584. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  585. return [
  586. ModuleInput(constructor_input=FunctionInput((2, 2, 2)),
  587. forward_input=FunctionInput(make_input((3, 4, 4, 4))),
  588. desc='no_batch_dim',
  589. reference_fn=no_batch_dim_reference_fn),
  590. ModuleInput(constructor_input=FunctionInput((2, 2, 2)),
  591. forward_input=FunctionInput(make_input((2, 3, 4, 4, 4)))),
  592. ModuleInput(constructor_input=FunctionInput(2, (2, 2, 2)),
  593. forward_input=FunctionInput(make_input((2, 3, 5, 5, 5))),
  594. desc='stride'),
  595. ModuleInput(constructor_input=FunctionInput(2, 2, (1, 1, 1)),
  596. forward_input=FunctionInput(make_input((2, 3, 5, 5, 5))),
  597. desc='stride_pad'),
  598. ModuleInput(constructor_input=FunctionInput(4, 2, (1, 2, 1)),
  599. forward_input=FunctionInput(make_input((2, 3, 5, 5, 5))),
  600. desc='stride_pad_gpu_fixedkw_output'),
  601. ModuleInput(constructor_input=FunctionInput((2, 4, 8), 1, (1, 1, 2)),
  602. forward_input=FunctionInput(make_input((2, 3, 2, 4, 8))),
  603. desc='stride_pad_gpu_general_output'),
  604. ModuleInput(constructor_input=FunctionInput(3, 1, 0),
  605. forward_input=FunctionInput(make_input((2, 3, 4, 4, 4))),
  606. desc='stride1_pad0_gpu_input'),
  607. ModuleInput(constructor_input=FunctionInput(2, 2, (1, 1, 1)),
  608. forward_input=FunctionInput(make_input((2, 3, 4, 4, 4))),
  609. desc='stride_pad_gpu_input_nooverlap'),
  610. ModuleInput(constructor_input=FunctionInput((2, 2, 2), divisor_override=1),
  611. forward_input=FunctionInput(make_input((2, 3, 4, 4, 4))),
  612. desc='divisor'),
  613. ModuleInput(constructor_input=FunctionInput(2, (2, 2, 2), divisor_override=1),
  614. forward_input=FunctionInput(make_input((2, 3, 5, 5, 5))),
  615. desc='divisor_stride'),
  616. ModuleInput(constructor_input=FunctionInput(2, 2, (1, 1, 1), divisor_override=1),
  617. forward_input=FunctionInput(make_input((2, 3, 5, 5, 5))),
  618. desc='divisor_stride_pad'),
  619. ModuleInput(constructor_input=FunctionInput(4, 2, (1, 2, 1), divisor_override=1),
  620. forward_input=FunctionInput(make_input((2, 3, 5, 5, 5))),
  621. desc='divisor_stride_pad_gpu_fixedkw_output'),
  622. ModuleInput(constructor_input=FunctionInput((2, 4, 8), 1, (1, 1, 2), divisor_override=1),
  623. forward_input=FunctionInput(make_input((2, 3, 2, 4, 8))),
  624. desc='divisor_stride_pad_gpu_general_output'),
  625. ModuleInput(constructor_input=FunctionInput(3, 1, 0, divisor_override=1),
  626. forward_input=FunctionInput(make_input((2, 3, 4, 4, 4))),
  627. desc='divisor_stride1_pad0_gpu_input'),
  628. ModuleInput(constructor_input=FunctionInput(2, 2, (1, 1, 1), divisor_override=1),
  629. forward_input=FunctionInput(make_input((2, 3, 4, 4, 4))),
  630. desc='divisor_stride_pad_gpu_input_nooverlap')]
  631. def module_inputs_torch_nn_AdaptiveAvgPool1d(module_info, device, dtype, requires_grad, training, **kwargs):
  632. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  633. return [
  634. ModuleInput(constructor_input=FunctionInput(3,),
  635. forward_input=FunctionInput(make_input((1, 3, 5))),
  636. desc='single'),
  637. ModuleInput(constructor_input=FunctionInput(3,),
  638. forward_input=FunctionInput(make_input((3, 5))),
  639. reference_fn=no_batch_dim_reference_fn,
  640. desc='no_batch_dim'),
  641. ModuleInput(constructor_input=FunctionInput(1,),
  642. forward_input=FunctionInput(make_input((1, 3, 5))),
  643. desc='one_output')]
  644. def module_inputs_torch_nn_AdaptiveAvgPool2d(module_info, device, dtype, requires_grad, training, **kwargs):
  645. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  646. return [
  647. ModuleInput(constructor_input=FunctionInput(3,),
  648. forward_input=FunctionInput(make_input((1, 3, 5, 6))),
  649. desc='single'),
  650. ModuleInput(constructor_input=FunctionInput(3,),
  651. forward_input=FunctionInput(make_input((3, 5, 6))),
  652. reference_fn=no_batch_dim_reference_fn,
  653. desc='no_batch_dim'),
  654. ModuleInput(constructor_input=FunctionInput(1,),
  655. forward_input=FunctionInput(make_input((1, 3, 5, 6))),
  656. desc='single_1x1output'),
  657. ModuleInput(constructor_input=FunctionInput((3, 4)),
  658. forward_input=FunctionInput(make_input((1, 3, 5, 6))),
  659. desc='tuple'),
  660. ModuleInput(constructor_input=FunctionInput((3, None)),
  661. forward_input=FunctionInput(make_input((1, 3, 5, 6))),
  662. desc='tuple_none')]
  663. def module_inputs_torch_nn_AdaptiveAvgPool3d(module_info, device, dtype, requires_grad, training, **kwargs):
  664. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  665. return [
  666. ModuleInput(constructor_input=FunctionInput(3,),
  667. forward_input=FunctionInput(make_input((2, 3, 5, 2, 7))),
  668. desc='single'),
  669. ModuleInput(constructor_input=FunctionInput(3,),
  670. forward_input=FunctionInput(make_input((3, 5, 2, 7))),
  671. reference_fn=no_batch_dim_reference_fn,
  672. desc='no_batch_dim'),
  673. ModuleInput(constructor_input=FunctionInput((3, 4, 5)),
  674. forward_input=FunctionInput(make_input((2, 3, 5, 3, 7))),
  675. desc='tuple'),
  676. ModuleInput(constructor_input=FunctionInput((None, 4, 5)),
  677. forward_input=FunctionInput(make_input((2, 3, 5, 3, 7))),
  678. desc='tuple_none'),
  679. ModuleInput(constructor_input=FunctionInput((3, 2, 2)),
  680. forward_input=FunctionInput(make_input((1, 1, 3, 2, 6))),
  681. desc='last_dim')]
  682. def module_inputs_torch_nn_AdaptiveMaxPool1d(module_info, device, dtype, requires_grad, training, **kwargs):
  683. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  684. return [
  685. ModuleInput(constructor_input=FunctionInput(3,),
  686. forward_input=FunctionInput(make_input((1, 3, 5))),
  687. desc='single'),
  688. ModuleInput(constructor_input=FunctionInput(3,),
  689. forward_input=FunctionInput(make_input((3, 5))),
  690. reference_fn=no_batch_dim_reference_fn,
  691. desc='no_batch_dim')]
  692. def module_inputs_torch_nn_AdaptiveMaxPool2d(module_info, device, dtype, requires_grad, training, **kwargs):
  693. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  694. return [
  695. ModuleInput(constructor_input=FunctionInput(3,),
  696. forward_input=FunctionInput(make_input((1, 3, 5, 6))),
  697. desc='single'),
  698. ModuleInput(constructor_input=FunctionInput(3,),
  699. forward_input=FunctionInput(make_input((3, 5, 6))),
  700. reference_fn=no_batch_dim_reference_fn,
  701. desc='no_batch_dim'),
  702. ModuleInput(constructor_input=FunctionInput((3, 4)),
  703. forward_input=FunctionInput(make_input((1, 3, 5, 6))),
  704. desc='tuple'),
  705. ModuleInput(constructor_input=FunctionInput((3, None)),
  706. forward_input=FunctionInput(make_input((1, 3, 5, 6))),
  707. desc='tuple_none')]
  708. def module_inputs_torch_nn_AdaptiveMaxPool3d(module_info, device, dtype, requires_grad, training, **kwargs):
  709. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  710. return [
  711. ModuleInput(constructor_input=FunctionInput(3,),
  712. forward_input=FunctionInput(make_input((2, 3, 5, 6, 7))),
  713. desc='single'),
  714. ModuleInput(constructor_input=FunctionInput(3,),
  715. forward_input=FunctionInput(make_input((3, 5, 6, 7))),
  716. reference_fn=no_batch_dim_reference_fn,
  717. desc='no_batch_dim'),
  718. ModuleInput(constructor_input=FunctionInput((3, 4, 5)),
  719. forward_input=FunctionInput(make_input((2, 3, 5, 6, 7))),
  720. desc='tuple'),
  721. ModuleInput(constructor_input=FunctionInput((3, None, 5)),
  722. forward_input=FunctionInput(make_input((2, 3, 5, 6, 7))),
  723. desc='tuple_none'),
  724. ModuleInput(constructor_input=FunctionInput(3),
  725. forward_input=FunctionInput(make_input((2, 3, 12, 9, 3))),
  726. desc='single_nonatomic'),
  727. ModuleInput(constructor_input=FunctionInput((3, 4, 5)),
  728. forward_input=FunctionInput(make_input((2, 3, 6, 4, 10))),
  729. desc='tuple_nonatomic')]
  730. def module_inputs_torch_nn_BatchNorm1d(module_info, device, dtype, requires_grad, training, **kwargs):
  731. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  732. return [
  733. ModuleInput(constructor_input=FunctionInput(10,),
  734. forward_input=FunctionInput(make_input((4, 10))),
  735. desc='affine'),
  736. ModuleInput(constructor_input=FunctionInput(5,),
  737. forward_input=FunctionInput(make_input((4, 5, 3))),
  738. desc='3d_input'),
  739. ModuleInput(constructor_input=FunctionInput(10, 1e-3, None),
  740. forward_input=FunctionInput(make_input((4, 10))),
  741. desc='affine_simple_average'),
  742. ModuleInput(constructor_input=FunctionInput(10, 1e-3, 0.3, False),
  743. forward_input=FunctionInput(make_input((4, 10))),
  744. desc='not_affine'),
  745. ModuleInput(constructor_input=FunctionInput(10, 1e-3, 0.3, True, False),
  746. forward_input=FunctionInput(make_input((4, 10))),
  747. desc='not_tracking_stats'),
  748. ModuleInput(constructor_input=FunctionInput(5, 1e-3, 0.3, False),
  749. forward_input=FunctionInput(make_input((4, 5, 3))),
  750. desc='3d_input_not_affine'),
  751. ModuleInput(constructor_input=FunctionInput(5, 1e-3, 0.3, False),
  752. forward_input=FunctionInput(make_input((0, 5, 9))),
  753. desc='zero_batch')]
  754. def module_inputs_torch_nn_BatchNorm2d(module_info, device, dtype, requires_grad, training, **kwargs):
  755. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  756. return [
  757. ModuleInput(constructor_input=FunctionInput(3,),
  758. forward_input=FunctionInput(make_input((2, 3, 6, 6)))),
  759. ModuleInput(constructor_input=FunctionInput(3, 1e-3, None),
  760. forward_input=FunctionInput(make_input((2, 3, 6, 6))),
  761. desc='2d_simple_average'),
  762. ModuleInput(constructor_input=FunctionInput(3, 1e-3, 0.8),
  763. forward_input=FunctionInput(make_input((2, 3, 6, 6))),
  764. desc='momentum'),
  765. ModuleInput(constructor_input=FunctionInput(3, 1e-3, 0.8, False),
  766. forward_input=FunctionInput(make_input((2, 3, 6, 6))),
  767. desc='not_affine'),
  768. ModuleInput(constructor_input=FunctionInput(3, 1e-3, 0.8, True, False),
  769. forward_input=FunctionInput(make_input((2, 3, 6, 6))),
  770. desc='not_tracking_stats'),
  771. ModuleInput(constructor_input=FunctionInput(5, 1e-3, 0.3, False),
  772. forward_input=FunctionInput(make_input((0, 5, 2, 2))),
  773. desc='zero_batch')]
  774. def module_inputs_torch_nn_BatchNorm3d(module_info, device, dtype, requires_grad, training, **kwargs):
  775. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  776. return [
  777. ModuleInput(constructor_input=FunctionInput(3,),
  778. forward_input=FunctionInput(make_input((2, 3, 4, 4, 4)))),
  779. ModuleInput(constructor_input=FunctionInput(3, 1e-3, None),
  780. forward_input=FunctionInput(make_input((2, 3, 4, 4, 4))),
  781. desc='3d_simple_average'),
  782. ModuleInput(constructor_input=FunctionInput(3, 1e-3, 0.7),
  783. forward_input=FunctionInput(make_input((2, 3, 4, 4, 4))),
  784. desc='momentum'),
  785. ModuleInput(constructor_input=FunctionInput(3, 1e-3, 0.7, False),
  786. forward_input=FunctionInput(make_input((2, 3, 4, 4, 4))),
  787. desc='not_affine'),
  788. ModuleInput(constructor_input=FunctionInput(3, 1e-3, 0.7, True, False),
  789. forward_input=FunctionInput(make_input((2, 3, 4, 4, 4))),
  790. desc='not_tracking_stats'),
  791. ModuleInput(constructor_input=FunctionInput(5, 1e-3, 0.3, False),
  792. forward_input=FunctionInput(make_input((0, 5, 2, 2, 2))),
  793. desc='zero_batch')]
  794. def module_inputs_torch_nn_ConvNd(module_info, device, dtype, requires_grad, training, **kwargs):
  795. N = kwargs['N']
  796. lazy = kwargs.get('lazy', False)
  797. transposed = kwargs.get('transposed', False)
  798. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  799. conv_kwargs_list = [{}] if transposed else [{}, {'padding': 'same'}]
  800. kernel_size, C_in, C_out = 3, 4, 5
  801. input_no_batch_shape = (C_in,) + tuple(i + 3 for i in range(N))
  802. input_batch_shape = (2,) + input_no_batch_shape
  803. return [
  804. ModuleInput(constructor_input=(FunctionInput(C_out, kernel_size, **conv_kwargs) if lazy else
  805. FunctionInput(C_in, C_out, kernel_size, **conv_kwargs)),
  806. forward_input=FunctionInput(make_input(
  807. input_batch_shape if with_batch else input_no_batch_shape)),
  808. desc=('' if with_batch else 'no_batch_dim'),
  809. reference_fn=(None if with_batch else no_batch_dim_reference_fn))
  810. for with_batch, conv_kwargs in itertools.product([True, False], conv_kwargs_list)
  811. ]
  812. def module_inputs_torch_nn_CosineEmbeddingLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  813. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  814. make_target = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  815. cases: List[Tuple[str, dict]] = [
  816. ('', {}),
  817. ('reduction_sum', {'reduction': 'sum'}),
  818. ('reduction_mean', {'reduction': 'mean'}),
  819. ('reduction_none', {'reduction': 'none'}),
  820. ('margin', {'margin': 0.7})
  821. ]
  822. module_inputs = []
  823. for desc, constructor_kwargs in cases:
  824. def reference_fn(m, p, i1, i2, t, constructor_kwargs=constructor_kwargs):
  825. return cosineembeddingloss_reference(i1, i2, t, **constructor_kwargs)
  826. module_inputs.append(
  827. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  828. forward_input=FunctionInput(make_input((15, 10)), make_input((15, 10)),
  829. make_target((15,)).sign()),
  830. desc=desc,
  831. reference_fn=reference_fn)
  832. )
  833. return module_inputs
  834. def module_inputs_torch_nn_ELU(module_info, device, dtype, requires_grad, training, **kwargs):
  835. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  836. return [
  837. ModuleInput(constructor_input=FunctionInput(alpha=2.),
  838. forward_input=FunctionInput(make_input((3, 2, 5))),
  839. reference_fn=lambda m, p, i: torch.where(i >= 0, i, 2 * (i.exp() - 1))),
  840. ModuleInput(constructor_input=FunctionInput(alpha=2.),
  841. forward_input=FunctionInput(make_input(())),
  842. desc='scalar'),
  843. ModuleInput(constructor_input=FunctionInput(),
  844. forward_input=FunctionInput(make_input((3,))),
  845. desc='no_batch_dim',
  846. reference_fn=no_batch_dim_reference_fn),
  847. ModuleInput(constructor_input=FunctionInput(alpha=2.),
  848. forward_input=FunctionInput(make_input((2, 3, 2, 5))),
  849. desc='4d_input')]
  850. def module_inputs_torch_nn_CELU(module_info, device, dtype, requires_grad, training, **kwargs):
  851. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  852. return [
  853. ModuleInput(constructor_input=FunctionInput(alpha=2.),
  854. forward_input=FunctionInput(make_input((3, 2, 5))),
  855. reference_fn=lambda m, p, i: torch.where(i >= 0, i, 2. * ((.5 * i).exp() - 1))),
  856. ModuleInput(constructor_input=FunctionInput(alpha=2.),
  857. forward_input=FunctionInput(make_input(())),
  858. reference_fn=lambda m, p, i: torch.where(i >= 0, i, 2. * ((.5 * i).exp() - 1)),
  859. desc='scalar'),
  860. ModuleInput(constructor_input=FunctionInput(alpha=2.),
  861. forward_input=FunctionInput(make_input((3,))),
  862. desc='no_batch_dim',
  863. reference_fn=no_batch_dim_reference_fn)]
  864. def module_inputs_torch_nn_GLU(module_info, device, dtype, requires_grad, training, **kwargs):
  865. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  866. return [
  867. ModuleInput(constructor_input=FunctionInput(),
  868. forward_input=FunctionInput(make_input((5, 6)))),
  869. ModuleInput(constructor_input=FunctionInput(1),
  870. forward_input=FunctionInput(make_input((5, 6, 7))),
  871. desc='dim'),
  872. ModuleInput(constructor_input=FunctionInput(),
  873. forward_input=FunctionInput(make_input((4,))),
  874. desc='no_batch_dim',
  875. reference_fn=no_batch_dim_reference_fn)]
  876. def module_inputs_torch_nn_GELU(module_info, device, dtype, requires_grad, training, **kwargs):
  877. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  878. return [
  879. ModuleInput(constructor_input=FunctionInput('none'),
  880. forward_input=FunctionInput(make_input(())),
  881. reference_fn=lambda m, p, x, *_: x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))),
  882. desc='scalar'),
  883. ModuleInput(constructor_input=FunctionInput('none'),
  884. forward_input=FunctionInput(make_input((3, 2, 5))),
  885. reference_fn=lambda m, p, x, *_: x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))),
  886. ModuleInput(constructor_input=FunctionInput(),
  887. forward_input=FunctionInput(make_input((3,))),
  888. desc='no_batch_dim',
  889. reference_fn=no_batch_dim_reference_fn)]
  890. def module_inputs_torch_nn_ReLU(module_info, device, dtype, requires_grad, training, **kwargs):
  891. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  892. return [
  893. ModuleInput(constructor_input=FunctionInput(),
  894. forward_input=FunctionInput(make_input(())),
  895. desc='scalar'),
  896. ModuleInput(constructor_input=FunctionInput(),
  897. forward_input=FunctionInput(make_input(4)),
  898. reference_fn=no_batch_dim_reference_fn,
  899. desc='no_batch_dim'),
  900. ModuleInput(constructor_input=FunctionInput(),
  901. forward_input=FunctionInput(make_input((2, 3, 4, 5))),
  902. desc='channels_last_mem_format'),
  903. ModuleInput(constructor_input=FunctionInput(),
  904. forward_input=FunctionInput(make_input((2, 3, 3, 4, 5))),
  905. desc='channels_last_3d_mem_format')]
  906. def module_inputs_torch_nn_ReLU6(module_info, device, dtype, requires_grad, training, **kwargs):
  907. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  908. return [
  909. ModuleInput(constructor_input=FunctionInput(),
  910. forward_input=FunctionInput(make_input(())),
  911. desc='scalar'),
  912. ModuleInput(constructor_input=FunctionInput(),
  913. forward_input=FunctionInput(make_input(4)),
  914. reference_fn=no_batch_dim_reference_fn,
  915. desc='no_batch_dim'),
  916. ModuleInput(constructor_input=FunctionInput(),
  917. forward_input=FunctionInput(make_input((2, 3, 4, 5))),
  918. desc='channels_last_mem_format'),
  919. ModuleInput(constructor_input=FunctionInput(),
  920. forward_input=FunctionInput(make_input((2, 3, 3, 4, 5))),
  921. desc='channels_last_3d_mem_format')]
  922. def module_inputs_torch_nn_LeakyReLU(module_info, device, dtype, requires_grad, training, **kwargs):
  923. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  924. return [
  925. ModuleInput(constructor_input=FunctionInput(),
  926. forward_input=FunctionInput(make_input((3, 2, 5)))),
  927. ModuleInput(constructor_input=FunctionInput(),
  928. forward_input=FunctionInput(make_input(4)),
  929. reference_fn=no_batch_dim_reference_fn,
  930. desc='no_batch_dim'),
  931. ModuleInput(constructor_input=FunctionInput(0.5),
  932. forward_input=FunctionInput(make_input((3, 2, 5))),
  933. desc='with_negval'),
  934. ModuleInput(constructor_input=FunctionInput(0.0),
  935. forward_input=FunctionInput(make_input((10, 10))),
  936. desc='with_zero_negval'),
  937. ModuleInput(constructor_input=FunctionInput(0.5),
  938. forward_input=FunctionInput(make_input(())),
  939. desc='with_negval_scalar')]
  940. def module_inputs_torch_nn_PReLU(module_info, device, dtype, requires_grad, training, **kwargs):
  941. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  942. return [
  943. ModuleInput(constructor_input=FunctionInput(),
  944. forward_input=FunctionInput(make_input(())),
  945. desc='scalar'),
  946. ModuleInput(constructor_input=FunctionInput(),
  947. forward_input=FunctionInput(make_input(4)),
  948. reference_fn=no_batch_dim_reference_fn,
  949. desc='no_batch_dim'),
  950. ModuleInput(constructor_input=FunctionInput(),
  951. forward_input=FunctionInput(make_input((2, 3, 4))),
  952. reference_fn=lambda m, p, i: torch.clamp(i, min=0) + torch.clamp(i, max=0) * p[0][0],
  953. desc='1d'),
  954. ModuleInput(constructor_input=FunctionInput(3),
  955. forward_input=FunctionInput(make_input((2, 3, 4))),
  956. reference_fn=lambda m, p, i: torch.clamp(i, min=0) + torch.clamp(i, max=0) * p[0][0],
  957. desc='1d_multiparam'),
  958. ModuleInput(constructor_input=FunctionInput(),
  959. forward_input=FunctionInput(make_input((2, 3, 4, 5))),
  960. reference_fn=lambda m, p, i: torch.clamp(i, min=0) + torch.clamp(i, max=0) * p[0][0],
  961. desc='2d'),
  962. ModuleInput(constructor_input=FunctionInput(3),
  963. forward_input=FunctionInput(make_input((2, 3, 4, 5))),
  964. reference_fn=lambda m, p, i: torch.clamp(i, min=0) + torch.clamp(i, max=0) * p[0][0],
  965. desc='2d_multiparam'),
  966. ModuleInput(constructor_input=FunctionInput(),
  967. forward_input=FunctionInput(make_input((2, 3, 4, 5, 6))),
  968. reference_fn=lambda m, p, i: torch.clamp(i, min=0) + torch.clamp(i, max=0) * p[0][0],
  969. desc='3d'),
  970. ModuleInput(constructor_input=FunctionInput(3),
  971. forward_input=FunctionInput(make_input((2, 3, 4, 5, 6))),
  972. reference_fn=lambda m, p, i: torch.clamp(i, min=0) + torch.clamp(i, max=0) * p[0][0],
  973. desc='3d_multiparam')]
  974. def module_inputs_torch_nn_SELU(module_info, device, dtype, requires_grad, training, **kwargs):
  975. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  976. return [
  977. ModuleInput(constructor_input=FunctionInput(),
  978. forward_input=FunctionInput(make_input((3, 2, 5)))),
  979. ModuleInput(constructor_input=FunctionInput(),
  980. forward_input=FunctionInput(make_input(4)),
  981. reference_fn=no_batch_dim_reference_fn,
  982. desc='no_batch_dim'),
  983. ModuleInput(constructor_input=FunctionInput(),
  984. forward_input=FunctionInput(make_input(())),
  985. desc='scalar')]
  986. def module_inputs_torch_nn_SiLU(module_info, device, dtype, requires_grad, training, **kwargs):
  987. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  988. return [
  989. ModuleInput(constructor_input=FunctionInput(),
  990. forward_input=FunctionInput(make_input(())),
  991. reference_fn=lambda m, p, x, *_: x * torch.sigmoid(x),
  992. desc='scalar'),
  993. ModuleInput(constructor_input=FunctionInput(),
  994. forward_input=FunctionInput(make_input(4)),
  995. reference_fn=no_batch_dim_reference_fn,
  996. desc='no_batch_dim'),
  997. ModuleInput(constructor_input=FunctionInput(),
  998. forward_input=FunctionInput(make_input((5, 6, 7))),
  999. reference_fn=lambda m, p, x, *_: x * torch.sigmoid(x))]
  1000. def module_inputs_torch_nn_Softmax(module_info, device, dtype, requires_grad, training, **kwargs):
  1001. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1002. return [
  1003. ModuleInput(constructor_input=FunctionInput(1),
  1004. forward_input=FunctionInput(make_input((10, 20))),
  1005. reference_fn=lambda m, p, i: torch.exp(i).div(torch.exp(i).sum(1, True).expand(10, 20))),
  1006. ModuleInput(constructor_input=FunctionInput(0),
  1007. forward_input=FunctionInput(make_input(())),
  1008. reference_fn=lambda m, p, i: torch.exp(i).div(torch.exp(i).sum(0, True)),
  1009. desc='scalar'),
  1010. ModuleInput(constructor_input=FunctionInput(-1),
  1011. forward_input=FunctionInput(make_input((4, 5))),
  1012. reference_fn=no_batch_dim_reference_fn,
  1013. desc='no_batch_dim')]
  1014. def module_inputs_torch_nn_Softmax2d(module_info, device, dtype, requires_grad, training, **kwargs):
  1015. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1016. return [
  1017. ModuleInput(constructor_input=FunctionInput(),
  1018. forward_input=FunctionInput(make_input((1, 3, 10, 20))),
  1019. reference_fn=lambda m, p, i: torch.exp(i).div(torch.exp(i).sum(1, False))),
  1020. ModuleInput(constructor_input=FunctionInput(),
  1021. forward_input=FunctionInput(make_input((3, 4, 5))),
  1022. reference_fn=no_batch_dim_reference_fn,
  1023. desc='no_batch_dim')]
  1024. def module_inputs_torch_nn_LogSoftmax(module_info, device, dtype, requires_grad, training, **kwargs):
  1025. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1026. return [
  1027. ModuleInput(constructor_input=FunctionInput(1),
  1028. forward_input=FunctionInput(make_input((10, 20))),
  1029. reference_fn=lambda m, p, i: torch.exp(i).div_(torch.exp(i).sum(1, True).expand(10, 20)).log_()),
  1030. ModuleInput(constructor_input=FunctionInput(1),
  1031. forward_input=FunctionInput(make_input((1, 3, 10, 20))),
  1032. reference_fn=lambda m, p, i: torch.exp(i).div_(torch.exp(i).sum(1, False)).log_(),
  1033. desc='multiparam'),
  1034. ModuleInput(constructor_input=FunctionInput(0),
  1035. forward_input=FunctionInput(make_input(())),
  1036. reference_fn=lambda m, p, i: torch.exp(i).div_(torch.exp(i).sum(0, False)).log_(),
  1037. desc='multiparam_scalar'),
  1038. ModuleInput(constructor_input=FunctionInput(-1),
  1039. forward_input=FunctionInput(make_input((4, 5))),
  1040. reference_fn=no_batch_dim_reference_fn,
  1041. desc='no_batch_dim')]
  1042. def module_inputs_torch_nn_Softmin(module_info, device, dtype, requires_grad, training, **kwargs):
  1043. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1044. return [
  1045. ModuleInput(constructor_input=FunctionInput(1),
  1046. forward_input=FunctionInput(make_input((10, 20)))),
  1047. ModuleInput(constructor_input=FunctionInput(1),
  1048. forward_input=FunctionInput(make_input((2, 3, 5, 10))),
  1049. desc='multidim'),
  1050. ModuleInput(constructor_input=FunctionInput(0),
  1051. forward_input=FunctionInput(make_input(())),
  1052. desc='scalar'),
  1053. ModuleInput(constructor_input=FunctionInput(-1),
  1054. forward_input=FunctionInput(make_input((3, 4, 10))),
  1055. reference_fn=no_batch_dim_reference_fn,
  1056. desc='no_batch_dim')]
  1057. def module_inputs_torch_nn_Softplus(module_info, device, dtype, requires_grad, training, **kwargs):
  1058. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1059. return [
  1060. ModuleInput(constructor_input=FunctionInput(),
  1061. forward_input=FunctionInput(make_input((10, 20))),
  1062. reference_fn=lambda m, p, i: torch.log(1 + torch.exp(i))),
  1063. ModuleInput(constructor_input=FunctionInput(2),
  1064. forward_input=FunctionInput(make_input((10, 20))),
  1065. reference_fn=lambda m, p, i: 1. / 2. * torch.log(1 + torch.exp(2 * i)),
  1066. desc='beta'),
  1067. ModuleInput(constructor_input=FunctionInput(2, -100),
  1068. forward_input=FunctionInput(make_input((10, 20))),
  1069. reference_fn=(
  1070. lambda m, p, i: ((i * 2) > -100).type_as(i) * i
  1071. + ((i * 2) <= -100).type_as(i) * 1. / 2. * torch.log(1 + torch.exp(2 * i))),
  1072. desc='beta_threshold'),
  1073. ModuleInput(constructor_input=FunctionInput(2, -100),
  1074. forward_input=FunctionInput(make_input(())),
  1075. reference_fn=(
  1076. lambda m, p, i: ((i * 2) > -100).type_as(i) * i
  1077. + ((i * 2) <= -100).type_as(i) * 1. / 2. * torch.log(1 + torch.exp(2 * i))),
  1078. desc='beta_threshold_scalar'),
  1079. ModuleInput(constructor_input=FunctionInput(),
  1080. forward_input=FunctionInput(make_input(4)),
  1081. reference_fn=no_batch_dim_reference_fn,
  1082. desc='no_batch_dim')]
  1083. def module_inputs_torch_nn_Softshrink(module_info, device, dtype, requires_grad, training, **kwargs):
  1084. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1085. return [
  1086. ModuleInput(constructor_input=FunctionInput(),
  1087. forward_input=FunctionInput(make_input((3, 2, 5)))),
  1088. ModuleInput(constructor_input=FunctionInput(1,),
  1089. forward_input=FunctionInput(make_input((3, 2, 5))),
  1090. desc='lambda'),
  1091. ModuleInput(constructor_input=FunctionInput(1,),
  1092. forward_input=FunctionInput(make_input(())),
  1093. desc='lambda_scalar'),
  1094. ModuleInput(constructor_input=FunctionInput(),
  1095. forward_input=FunctionInput(make_input(4)),
  1096. reference_fn=no_batch_dim_reference_fn,
  1097. desc='no_batch_dim')]
  1098. def module_inputs_torch_nn_Softsign(module_info, device, dtype, requires_grad, training, **kwargs):
  1099. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1100. return [
  1101. ModuleInput(constructor_input=FunctionInput(),
  1102. forward_input=FunctionInput(make_input((3, 2, 5))),
  1103. reference_fn=lambda m, p, i: i.div(1 + torch.abs(i))),
  1104. ModuleInput(constructor_input=FunctionInput(),
  1105. forward_input=FunctionInput(make_input(())),
  1106. reference_fn=lambda m, p, i: i.div(1 + torch.abs(i)),
  1107. desc='scalar'),
  1108. ModuleInput(constructor_input=FunctionInput(),
  1109. forward_input=FunctionInput(make_input(4)),
  1110. reference_fn=no_batch_dim_reference_fn,
  1111. desc='no_batch_dim')]
  1112. def module_inputs_torch_nn_Tanh(module_info, device, dtype, requires_grad, training, **kwargs):
  1113. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1114. return [
  1115. ModuleInput(constructor_input=FunctionInput(),
  1116. forward_input=FunctionInput(make_input((2, 3, 4, 5)))),
  1117. ModuleInput(constructor_input=FunctionInput(),
  1118. forward_input=FunctionInput(make_input(())),
  1119. desc='scalar'),
  1120. ModuleInput(constructor_input=FunctionInput(),
  1121. forward_input=FunctionInput(make_input(4)),
  1122. reference_fn=no_batch_dim_reference_fn,
  1123. desc='no_batch_dim')]
  1124. def module_inputs_torch_nn_Tanhshrink(module_info, device, dtype, requires_grad, training, **kwargs):
  1125. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1126. return [
  1127. ModuleInput(constructor_input=FunctionInput(),
  1128. forward_input=FunctionInput(make_input((2, 3, 4, 5)))),
  1129. ModuleInput(constructor_input=FunctionInput(),
  1130. forward_input=FunctionInput(make_input(())),
  1131. desc='scalar'),
  1132. ModuleInput(constructor_input=FunctionInput(),
  1133. forward_input=FunctionInput(make_input(4)),
  1134. reference_fn=no_batch_dim_reference_fn,
  1135. desc='no_batch_dim')]
  1136. def module_inputs_torch_nn_Threshold(module_info, device, dtype, requires_grad, training, **kwargs):
  1137. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1138. return [
  1139. ModuleInput(constructor_input=FunctionInput(2., 1.),
  1140. forward_input=FunctionInput(make_input((2, 3, 4, 5))),
  1141. desc='threshold_value'),
  1142. ModuleInput(constructor_input=FunctionInput(2., 10.),
  1143. forward_input=FunctionInput(make_input((2, 3, 4, 5))),
  1144. desc='large_value'),
  1145. ModuleInput(constructor_input=FunctionInput(2., 1.),
  1146. forward_input=FunctionInput(make_input(())),
  1147. desc='threshold_value_scalar'),
  1148. ModuleInput(constructor_input=FunctionInput(2., 1.),
  1149. forward_input=FunctionInput(make_input(4)),
  1150. reference_fn=no_batch_dim_reference_fn,
  1151. desc='no_batch_dim')]
  1152. def module_inputs_torch_nn_Mish(module_info, device, dtype, requires_grad, training, **kwargs):
  1153. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1154. return [
  1155. ModuleInput(constructor_input=FunctionInput(),
  1156. forward_input=FunctionInput(make_input((5, 6, 7))),
  1157. reference_fn=lambda m, p, i: i * torch.tanh(F.softplus(i))),
  1158. ModuleInput(constructor_input=FunctionInput(),
  1159. forward_input=FunctionInput(make_input(())),
  1160. reference_fn=lambda m, p, i: i * torch.tanh(F.softplus(i)),
  1161. desc='scalar'),
  1162. ModuleInput(constructor_input=FunctionInput(),
  1163. forward_input=FunctionInput(make_input(4)),
  1164. reference_fn=no_batch_dim_reference_fn,
  1165. desc='no_batch_dim')]
  1166. def module_inputs_torch_nn_L1Loss(module_info, device, dtype, requires_grad, training, **kwargs):
  1167. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1168. return [
  1169. ModuleInput(constructor_input=FunctionInput(),
  1170. forward_input=FunctionInput(make_input((2, 3, 4)),
  1171. make_input((2, 3, 4))),
  1172. reference_fn=lambda m, p, i, t: 1. / i.numel() * sum((a - b).abs().sum()
  1173. for a, b in zip(i, t))),
  1174. ModuleInput(constructor_input=FunctionInput(),
  1175. forward_input=FunctionInput(make_input(()), make_input(())),
  1176. reference_fn=lambda m, p, i, t: 1. / i.numel() * (i - t).abs().sum(),
  1177. desc='scalar')] + generate_regression_criterion_inputs(make_input)
  1178. def module_inputs_torch_nn_SmoothL1Loss(module_info, device, dtype, requires_grad, training, **kwargs):
  1179. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1180. cases: List[Tuple[str, dict]] = [
  1181. ('', {}),
  1182. ('reduction_sum', {'reduction': 'sum'}),
  1183. ('reduction_mean', {'reduction': 'mean'}),
  1184. ('reduction_none', {'reduction': 'none'}),
  1185. ]
  1186. module_inputs = []
  1187. for desc, constructor_kwargs in cases:
  1188. def reference_fn(m, p, i, t, constructor_kwargs=constructor_kwargs):
  1189. return smoothl1loss_reference(i, t, **constructor_kwargs)
  1190. module_inputs.append(
  1191. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  1192. forward_input=FunctionInput(make_input((5, 10)),
  1193. make_input((5, 10))),
  1194. desc=desc,
  1195. reference_fn=reference_fn)
  1196. )
  1197. module_inputs.append(
  1198. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  1199. forward_input=FunctionInput(make_input(()),
  1200. make_input(())),
  1201. desc=f'scalar_{desc}',
  1202. reference_fn=reference_fn)
  1203. )
  1204. return module_inputs
  1205. def module_inputs_torch_nn_BCELoss(module_info, device, dtype, requires_grad, training, **kwargs):
  1206. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1207. make_target = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  1208. make_weight = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  1209. cases: List[Tuple[str, dict]] = [
  1210. ('', {}),
  1211. ('reduction_sum', {'reduction': 'sum'}),
  1212. ('reduction_mean', {'reduction': 'mean'}),
  1213. ('reduction_none', {'reduction': 'none'}),
  1214. ('weights', {'weight': make_weight((10,))}),
  1215. ]
  1216. def bce_loss_reference_fn(m, p, i, t, reduction='mean', weight=None):
  1217. result = -(t * i.log() + (1 - t) * (1 - i).log())
  1218. if weight is not None:
  1219. result = result * weight
  1220. if reduction == 'none':
  1221. return result
  1222. elif reduction == 'mean':
  1223. return result.sum() / i.numel()
  1224. else:
  1225. return result.sum()
  1226. module_inputs = []
  1227. for desc, constructor_kwargs in cases:
  1228. module_inputs.append(
  1229. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  1230. forward_input=FunctionInput(make_input((15, 10), low=1e-2, high=1 - 1e-2),
  1231. make_target((15, 10)).gt(0).to(dtype)),
  1232. desc=desc,
  1233. reference_fn=partial(bce_loss_reference_fn, **constructor_kwargs))
  1234. )
  1235. scalar_weight = make_weight(())
  1236. module_inputs.append(
  1237. ModuleInput(constructor_input=FunctionInput(weight=scalar_weight),
  1238. forward_input=FunctionInput(make_input((), low=1e-2, high=1 - 1e-2),
  1239. make_target(()).gt(0).to(dtype)),
  1240. desc='scalar_weight',
  1241. reference_fn=partial(bce_loss_reference_fn, weight=scalar_weight))
  1242. )
  1243. return module_inputs
  1244. def module_inputs_torch_nn_BCEWithLogitsLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  1245. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1246. make_target = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  1247. make_weight = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  1248. cases: List[Tuple[str, dict]] = [
  1249. ('', {}),
  1250. ('reduction_sum', {'reduction': 'sum'}),
  1251. ('reduction_mean', {'reduction': 'mean'}),
  1252. ('reduction_none', {'reduction': 'none'}),
  1253. ('weights', {'weight': make_weight((10,))}),
  1254. ('scalar_weights', {'weight': make_weight(())})
  1255. ]
  1256. def bce_withlogitsloss_reference_fn(m, p, i, t, reduction='mean', weight=None):
  1257. # TODO: add pos_weight to the definition here and corresponding SampleInputs
  1258. max_val = (-i).clamp(min=0)
  1259. result = (1 - t).mul_(i).add_(max_val).add_((-max_val).exp_().add_((-i - max_val).exp_()).log_())
  1260. if weight is not None:
  1261. result = result * weight
  1262. if reduction == 'none':
  1263. return result
  1264. elif reduction == 'mean':
  1265. return result.sum() / i.numel()
  1266. else:
  1267. return result.sum()
  1268. module_inputs = []
  1269. for desc, constructor_kwargs in cases:
  1270. module_inputs.append(
  1271. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  1272. forward_input=FunctionInput(make_input((15, 10), low=1e-2, high=1 - 1e-2),
  1273. make_target((15, 10)).gt(0).to(dtype)),
  1274. desc=desc,
  1275. reference_fn=partial(bce_withlogitsloss_reference_fn, **constructor_kwargs))
  1276. )
  1277. return module_inputs
  1278. def module_inputs_torch_nn_CrossEntropyLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  1279. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1280. make_target = partial(make_tensor, device=device, dtype=torch.long, requires_grad=False)
  1281. make_weight = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  1282. reductions: List[str] = ['mean', 'sum', 'none']
  1283. cases: List[Tuple[str, dict]] = [
  1284. ('', {}),
  1285. ('weights', {'weight': make_weight((3,))}),
  1286. ('ignore_index', {'ignore_index': 1}),
  1287. ('label_smoothing', {'label_smoothing': 0.15}),
  1288. ('ignore_index_label_smoothing', {'ignore_index': 1, 'label_smoothing': 0.15})
  1289. ]
  1290. module_inputs = []
  1291. for reduction, (desc, constructor_kwargs) in product(reductions, cases):
  1292. def reference_fn(m, p, i, t, reduction=reduction, constructor_kwargs=constructor_kwargs):
  1293. return cross_entropy_loss_reference(i, t, reduction=reduction, **constructor_kwargs)
  1294. module_inputs.append(
  1295. ModuleInput(constructor_input=FunctionInput(reduction=reduction, **constructor_kwargs),
  1296. forward_input=FunctionInput(make_input((2, 3, 5, 5)),
  1297. make_target((2, 5, 5), low=0, high=3)),
  1298. desc=f"4d_{desc}_{reduction}",
  1299. reference_fn=reference_fn)
  1300. )
  1301. module_inputs.append(
  1302. ModuleInput(constructor_input=FunctionInput(reduction=reduction, **constructor_kwargs),
  1303. forward_input=FunctionInput(make_input((2, 3, 5)),
  1304. make_target((2, 5), low=0, high=3)),
  1305. desc=f"3d_{desc}_{reduction}",
  1306. reference_fn=reference_fn)
  1307. )
  1308. module_inputs.append(
  1309. ModuleInput(constructor_input=FunctionInput(reduction=reduction, **constructor_kwargs),
  1310. forward_input=FunctionInput(make_input((2, 3)),
  1311. make_target((2), low=0, high=3)),
  1312. desc=f"2d_{desc}_{reduction}",
  1313. reference_fn=reference_fn)
  1314. )
  1315. module_inputs.append(
  1316. ModuleInput(constructor_input=FunctionInput(reduction=reduction, **constructor_kwargs),
  1317. forward_input=FunctionInput(make_input((2, 3, 5, 5, 2, 2)),
  1318. make_target((2, 5, 5, 2, 2), low=0, high=3)),
  1319. desc=f"higher_dim_{desc}_{reduction}",
  1320. reference_fn=reference_fn)
  1321. )
  1322. if constructor_kwargs.get('ignore_index', None) is None:
  1323. module_inputs.append(
  1324. ModuleInput(constructor_input=FunctionInput(reduction=reduction, **constructor_kwargs),
  1325. forward_input=FunctionInput(make_input((5, 3, 4, 2)),
  1326. make_input((5, 3, 4, 2)).softmax(dim=1)),
  1327. desc=f"4d_prob_target_{desc}_{reduction}",
  1328. reference_fn=reference_fn)
  1329. )
  1330. module_inputs.append(
  1331. ModuleInput(constructor_input=FunctionInput(reduction=reduction, **constructor_kwargs),
  1332. forward_input=FunctionInput(make_input((5, 3, 4)),
  1333. make_input((5, 3, 4)).softmax(dim=1)),
  1334. desc=f"3d_prob_target_{desc}_{reduction}",
  1335. reference_fn=reference_fn)
  1336. )
  1337. module_inputs.append(
  1338. ModuleInput(constructor_input=FunctionInput(reduction=reduction, **constructor_kwargs),
  1339. forward_input=FunctionInput(make_input((5, 3)),
  1340. make_input((5, 3)).softmax(dim=1)),
  1341. desc=f"2d_prob_target_{desc}_{reduction}",
  1342. reference_fn=reference_fn)
  1343. )
  1344. module_inputs.append(
  1345. ModuleInput(constructor_input=FunctionInput(reduction=reduction, **constructor_kwargs),
  1346. forward_input=FunctionInput(make_input((2, 3, 5, 5, 2, 2)),
  1347. make_input((2, 3, 5, 5, 2, 2)).softmax(dim=1)),
  1348. desc=f"higher_dim_prob_target_{desc}_{reduction}",
  1349. reference_fn=reference_fn)
  1350. )
  1351. module_inputs.append(
  1352. ModuleInput(constructor_input=FunctionInput(reduction=reduction, **constructor_kwargs),
  1353. forward_input=FunctionInput(make_input((3,)),
  1354. make_target((), low=0, high=3)),
  1355. desc=f"no_batch_dim_{desc}_{reduction}",
  1356. reference_fn=partial(no_batch_dim_reference_fn, is_criterion=True))
  1357. )
  1358. return module_inputs
  1359. def module_inputs_torch_nn_CTCLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  1360. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1361. make_target = partial(make_tensor, device=device, requires_grad=False)
  1362. cases: List[Tuple[str, dict]] = [
  1363. ('', {}),
  1364. ('reduction_sum', {'reduction': 'sum'}),
  1365. ('reduction_mean', {'reduction': 'mean'}),
  1366. ('reduction_none', {'reduction': 'none'}),
  1367. ('blank', {'blank': 14})
  1368. ]
  1369. target_dtypes = [torch.int, torch.long]
  1370. module_inputs = []
  1371. for target_dtype, (desc, constructor_kwargs) in product(target_dtypes, cases):
  1372. def reference_fn(m, p, i, t, il, tl, constructor_kwargs=constructor_kwargs):
  1373. return ctcloss_reference(i, t, il, tl, **constructor_kwargs)
  1374. blank = constructor_kwargs.get('blank', 0)
  1375. low = 0 if blank == 14 else 1
  1376. high = 14 if blank == 14 else 15
  1377. module_inputs.append(
  1378. ModuleInput(
  1379. constructor_input=FunctionInput(**constructor_kwargs),
  1380. forward_input=FunctionInput(make_input((50, 3, 15)).log_softmax(2),
  1381. make_target((3, 30), dtype=target_dtype, low=low, high=high),
  1382. (50, 50, 50), (30, 25, 20)),
  1383. desc=f'{desc}_lengths_intlists',
  1384. reference_fn=reference_fn)
  1385. )
  1386. module_inputs.append(
  1387. ModuleInput(
  1388. constructor_input=FunctionInput(**constructor_kwargs),
  1389. forward_input=FunctionInput(make_input((50, 3, 15)).log_softmax(2),
  1390. make_target((3, 30), dtype=target_dtype, low=low, high=high),
  1391. torch.tensor((50, 50, 50), device=device),
  1392. torch.tensor((30, 25, 20), device=device)),
  1393. desc=f'{desc}_lengths_tensors',
  1394. reference_fn=reference_fn)
  1395. )
  1396. module_inputs.append(
  1397. ModuleInput(
  1398. constructor_input=FunctionInput(**constructor_kwargs),
  1399. forward_input=FunctionInput(make_input((50, 3, 15)).log_softmax(2),
  1400. make_target((30 + 25 + 20,), dtype=target_dtype, low=low, high=high),
  1401. (50, 50, 50), (30, 25, 20)),
  1402. desc=f'{desc}_1d_target_lengths_intlists',
  1403. reference_fn=reference_fn)
  1404. )
  1405. module_inputs.append(
  1406. ModuleInput(
  1407. constructor_input=FunctionInput(**constructor_kwargs),
  1408. forward_input=FunctionInput(make_input((50, 3, 15)).log_softmax(2),
  1409. make_target((30 + 25 + 20,), dtype=target_dtype, low=low, high=high),
  1410. torch.tensor((50, 50, 50), device=device),
  1411. torch.tensor((30, 25, 20), device=device)),
  1412. desc=f'{desc}_1d_target_lengths_tensors',
  1413. reference_fn=reference_fn)
  1414. )
  1415. return module_inputs
  1416. def module_inputs_torch_nn_GroupNorm(module_info, device, dtype, requires_grad, training, **kwargs):
  1417. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1418. return [
  1419. ModuleInput(
  1420. constructor_input=FunctionInput(3, 6, 1e-3),
  1421. forward_input=FunctionInput(make_input((4, 6, 5))),
  1422. desc='1d_affine'),
  1423. ModuleInput(
  1424. constructor_input=FunctionInput(3, 12, 1e-3),
  1425. forward_input=FunctionInput(make_input((4, 12))),
  1426. desc='1d_affine_GN'),
  1427. ModuleInput(
  1428. constructor_input=FunctionInput(1, 6, 1e-3),
  1429. forward_input=FunctionInput(make_input((150, 6))),
  1430. desc='1d_affine_large_batch'),
  1431. ModuleInput(
  1432. constructor_input=FunctionInput(5, 5, 1e-3, False),
  1433. forward_input=FunctionInput(make_input((4, 5, 5))),
  1434. desc='1d_no_affine_IN'),
  1435. ModuleInput(
  1436. constructor_input=FunctionInput(1, 10, 1e-3, False),
  1437. forward_input=FunctionInput(make_input((4, 10))),
  1438. desc='1d_no_affine_LN'),
  1439. ModuleInput(
  1440. constructor_input=FunctionInput(3, 6, 1e-3),
  1441. forward_input=FunctionInput(make_input((4, 6, 2, 3))),
  1442. desc='2d_affine'),
  1443. ModuleInput(
  1444. constructor_input=FunctionInput(3, 6, 1e-3),
  1445. forward_input=FunctionInput(make_input((4, 6, 28, 28))),
  1446. desc='2d_affine_large_feature'),
  1447. ModuleInput(
  1448. constructor_input=FunctionInput(3, 51, 1e-5, False),
  1449. forward_input=FunctionInput(make_input((2, 51, 28, 28))),
  1450. desc='2d_no_affine_large_feature'),
  1451. ModuleInput(
  1452. constructor_input=FunctionInput(3, 3, 1e-3, False),
  1453. forward_input=FunctionInput(make_input((4, 3, 2, 3))),
  1454. desc='2d_no_affine_IN'),
  1455. ModuleInput(
  1456. constructor_input=FunctionInput(1, 3, 1e-3, False),
  1457. forward_input=FunctionInput(make_input((4, 3, 2, 3))),
  1458. desc='2d_no_affine_LN'),
  1459. ]
  1460. def module_inputs_torch_nn_Hardshrink(module_info, device, dtype, requires_grad, training, **kwargs):
  1461. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1462. return [
  1463. ModuleInput(
  1464. constructor_input=FunctionInput(2.),
  1465. forward_input=FunctionInput(make_input((4, 3, 2, 4))),
  1466. ),
  1467. ModuleInput(
  1468. constructor_input=FunctionInput(2.),
  1469. forward_input=FunctionInput(make_input(())),
  1470. desc='scalar',
  1471. ),
  1472. ModuleInput(
  1473. constructor_input=FunctionInput(),
  1474. forward_input=FunctionInput(make_input(4)),
  1475. reference_fn=no_batch_dim_reference_fn,
  1476. desc='no_batch_dim',
  1477. )
  1478. ]
  1479. def module_inputs_torch_nn_Hardswish(module_info, device, dtype, requires_grad, training, **kwargs):
  1480. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1481. return [
  1482. ModuleInput(
  1483. constructor_input=FunctionInput(),
  1484. forward_input=FunctionInput(make_input(4)),
  1485. reference_fn=no_batch_dim_reference_fn,
  1486. desc='no_batch_dim',
  1487. ),
  1488. ModuleInput(
  1489. constructor_input=FunctionInput(),
  1490. forward_input=FunctionInput(make_input((2, 3, 2, 5))),
  1491. desc='4d_input')
  1492. ]
  1493. def module_inputs_torch_nn_Hardtanh(module_info, device, dtype, requires_grad, training, **kwargs):
  1494. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1495. return [
  1496. ModuleInput(
  1497. constructor_input=FunctionInput(),
  1498. forward_input=FunctionInput(make_input((3, 2, 5))),
  1499. reference_fn=lambda m, p, i: i.clamp(-1, 1),
  1500. ),
  1501. ModuleInput(
  1502. constructor_input=FunctionInput(),
  1503. forward_input=FunctionInput(make_input(())),
  1504. reference_fn=lambda m, p, i: i.clamp(-1, 1),
  1505. desc='scalar',
  1506. ),
  1507. ModuleInput(
  1508. constructor_input=FunctionInput(),
  1509. forward_input=FunctionInput(make_input(4)),
  1510. reference_fn=no_batch_dim_reference_fn,
  1511. desc='no_batch_dim',
  1512. )
  1513. ]
  1514. def module_inputs_torch_nn_HingeEmbeddingLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  1515. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1516. make_target = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  1517. cases: List[Tuple[str, dict]] = [
  1518. ('', {}),
  1519. ('reduction_sum', {'reduction': 'sum'}),
  1520. ('reduction_mean', {'reduction': 'mean'}),
  1521. ('reduction_none', {'reduction': 'none'}),
  1522. ('margin', {'margin': 0.5})
  1523. ]
  1524. module_inputs = []
  1525. for desc, constructor_kwargs in cases:
  1526. def reference_fn(m, p, i, t, constructor_kwargs=constructor_kwargs):
  1527. return hingeembeddingloss_reference(i, t, **constructor_kwargs)
  1528. module_inputs.append(
  1529. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  1530. forward_input=FunctionInput(make_input((10,)),
  1531. make_target((10,)).gt(0).to(dtype).mul_(2).sub_(1)),
  1532. desc=desc,
  1533. reference_fn=reference_fn)
  1534. )
  1535. module_inputs.append(
  1536. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  1537. forward_input=FunctionInput(make_input(()),
  1538. make_target(()).gt(0).to(dtype).mul_(2).sub_(1)),
  1539. desc=f'scalar_{desc}',
  1540. reference_fn=reference_fn)
  1541. )
  1542. return module_inputs
  1543. def module_inputs_torch_nn_HuberLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  1544. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1545. cases: List[Tuple[str, dict]] = [
  1546. ('', {}),
  1547. ('reduction_sum', {'reduction': 'sum'}),
  1548. ('reduction_mean', {'reduction': 'mean'}),
  1549. ('reduction_none', {'reduction': 'none'}),
  1550. ]
  1551. module_inputs = []
  1552. for desc, constructor_kwargs in cases:
  1553. def reference_fn(m, p, i, t, constructor_kwargs=constructor_kwargs):
  1554. return huberloss_reference(i, t, **constructor_kwargs)
  1555. module_inputs.append(
  1556. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  1557. forward_input=FunctionInput(make_input((5, 10)),
  1558. make_input((5, 10))),
  1559. desc=desc,
  1560. reference_fn=reference_fn)
  1561. )
  1562. return module_inputs
  1563. def module_inputs_torch_nn_InstanceNormNd(module_info, device, dtype, requires_grad, training, **kwargs):
  1564. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1565. lazy = kwargs.get('lazy', False)
  1566. N = kwargs['N']
  1567. num_features, eps, momentum, affine, track_running_stats = 3, 1e-3, 0.3, False, True
  1568. input_no_batch_shape_dict = {1: (3, 15), 2: (3, 6, 6), 3: (3, 4, 4, 4)}
  1569. input_no_batch_shape = input_no_batch_shape_dict[N]
  1570. input_batch_shape = (4,) + input_no_batch_shape
  1571. return [
  1572. ModuleInput(
  1573. constructor_input=(
  1574. FunctionInput(eps, momentum) if lazy else FunctionInput(num_features, eps, momentum)
  1575. ),
  1576. forward_input=FunctionInput(make_input(input_batch_shape))),
  1577. ModuleInput(
  1578. constructor_input=(
  1579. FunctionInput(eps, momentum, affine, track_running_stats) if lazy else
  1580. FunctionInput(num_features, eps, momentum, affine, track_running_stats)
  1581. ),
  1582. forward_input=FunctionInput(make_input(input_batch_shape)),
  1583. desc='tracking_stats'),
  1584. ModuleInput(
  1585. constructor_input=(
  1586. FunctionInput(eps, momentum) if lazy else FunctionInput(num_features, eps, momentum)
  1587. ),
  1588. forward_input=FunctionInput(make_input(input_no_batch_shape)),
  1589. reference_fn=no_batch_dim_reference_fn,
  1590. desc='tracking_stats_no_batch_dim'),
  1591. ModuleInput(
  1592. constructor_input=(
  1593. FunctionInput(eps, momentum, affine, track_running_stats) if lazy else
  1594. FunctionInput(num_features, eps, momentum, affine, track_running_stats)
  1595. ),
  1596. forward_input=FunctionInput(make_input(input_no_batch_shape)),
  1597. reference_fn=no_batch_dim_reference_fn,
  1598. desc='no_batch_dim')
  1599. ]
  1600. def module_inputs_torch_nn_LayerNorm(module_info, device, dtype, requires_grad, training, **kwargs):
  1601. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1602. return [
  1603. ModuleInput(
  1604. constructor_input=FunctionInput([5], 1e-3),
  1605. forward_input=FunctionInput(make_input((4, 5, 5))),
  1606. desc='1d_elementwise_affine'),
  1607. ModuleInput(
  1608. constructor_input=FunctionInput([5], 1e-3),
  1609. forward_input=FunctionInput(make_input((128, 5, 5))),
  1610. desc='1d_elementwise_affine_large_batch'),
  1611. ModuleInput(
  1612. constructor_input=FunctionInput([5], 1e-3, False),
  1613. forward_input=FunctionInput(make_input((4, 5, 5))),
  1614. desc='1d_no_elementwise_affine'),
  1615. ModuleInput(
  1616. constructor_input=FunctionInput([2, 2, 5], 1e-3),
  1617. forward_input=FunctionInput(make_input((4, 2, 2, 5))),
  1618. desc='3d_elementwise_affine'),
  1619. ModuleInput(
  1620. constructor_input=FunctionInput([2, 2, 5], 1e-3, False),
  1621. forward_input=FunctionInput(make_input((4, 2, 2, 5))),
  1622. desc='3d_no_elementwise_affine'),
  1623. ModuleInput(
  1624. constructor_input=FunctionInput([5], 1e-3),
  1625. forward_input=FunctionInput(make_input((0, 5))),
  1626. desc='1d_empty_elementwise_affine'),
  1627. ModuleInput(
  1628. constructor_input=FunctionInput([2, 2, 5], 1e-3, elementwise_affine=True, bias=False),
  1629. forward_input=FunctionInput(make_input((4, 2, 2, 5))),
  1630. desc='3d_elementwise_affine_no_bias'),
  1631. ]
  1632. def module_inputs_torch_nn_RMSNorm(module_info, device, dtype, requires_grad, training, **kwargs):
  1633. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1634. def rms_norm_reference_fn(m, p, i):
  1635. eps = m.eps
  1636. if eps is None:
  1637. eps = torch.finfo(i.dtype).eps
  1638. ndim = i.ndim
  1639. normalized_shape = m.normalized_shape
  1640. weight = m.weight
  1641. dims = [ndim - i - 1 for i in range(len(normalized_shape))]
  1642. result = i * torch.rsqrt(i.pow(2).mean(dim=dims, keepdim=True) + m.eps)
  1643. if weight is not None:
  1644. result *= weight
  1645. return result
  1646. return [
  1647. ModuleInput(
  1648. constructor_input=FunctionInput([5], 1e-3),
  1649. forward_input=FunctionInput(make_input((4, 5, 5))),
  1650. desc='1d_elementwise_affine',
  1651. reference_fn=rms_norm_reference_fn),
  1652. ModuleInput(
  1653. constructor_input=FunctionInput([5], 1e-3),
  1654. forward_input=FunctionInput(make_input((128, 5, 5))),
  1655. desc='1d_elementwise_affine_large_batch',
  1656. reference_fn=rms_norm_reference_fn),
  1657. ModuleInput(
  1658. constructor_input=FunctionInput([5], 1e-3, False),
  1659. forward_input=FunctionInput(make_input((4, 5, 5))),
  1660. desc='1d_no_elementwise_affine',
  1661. reference_fn=rms_norm_reference_fn),
  1662. ModuleInput(
  1663. constructor_input=FunctionInput([2, 2, 5], 1e-3),
  1664. forward_input=FunctionInput(make_input((4, 2, 2, 5))),
  1665. desc='3d_elementwise_affine',
  1666. reference_fn=rms_norm_reference_fn),
  1667. ModuleInput(
  1668. constructor_input=FunctionInput([2, 2, 5], 1e-3, False),
  1669. forward_input=FunctionInput(make_input((4, 2, 2, 5))),
  1670. desc='3d_no_elementwise_affine',
  1671. reference_fn=rms_norm_reference_fn),
  1672. ModuleInput(
  1673. constructor_input=FunctionInput([5], 1e-3),
  1674. forward_input=FunctionInput(make_input((0, 5))),
  1675. desc='1d_empty_elementwise_affine',
  1676. reference_fn=rms_norm_reference_fn),
  1677. ]
  1678. def module_inputs_torch_nn_LocalResponseNorm(module_info, device, dtype, requires_grad, training, **kwargs):
  1679. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1680. return [
  1681. ModuleInput(
  1682. constructor_input=FunctionInput(3,),
  1683. forward_input=FunctionInput(make_input((1, 5, 7))),
  1684. desc='1d'),
  1685. ModuleInput(
  1686. constructor_input=FunctionInput(2,),
  1687. forward_input=FunctionInput(make_input((1, 5, 7, 7))),
  1688. desc='2d_uneven_pad'),
  1689. ModuleInput(
  1690. constructor_input=FunctionInput(1, 1., 0.5, 2.),
  1691. forward_input=FunctionInput(make_input((1, 5, 7, 7, 7))),
  1692. desc='3d_custom_params'),
  1693. ]
  1694. def module_inputs_torch_nn_LPPool1d(module_info, device, dtype, requires_grad, training, **kwargs):
  1695. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1696. return [
  1697. ModuleInput(
  1698. constructor_input=FunctionInput(1.5, 2),
  1699. forward_input=FunctionInput(make_input((1, 3, 7))),
  1700. desc='norm'),
  1701. ModuleInput(
  1702. constructor_input=FunctionInput(2, 2, 3),
  1703. forward_input=FunctionInput(make_input((1, 3, 7)))),
  1704. ModuleInput(
  1705. constructor_input=FunctionInput(2, 2, 3),
  1706. forward_input=FunctionInput(make_input((3, 7))),
  1707. reference_fn=no_batch_dim_reference_fn,
  1708. desc='no_batch_dim'),
  1709. ]
  1710. def module_inputs_torch_nn_LPPool2d(module_info, device, dtype, requires_grad, training, **kwargs):
  1711. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1712. return [
  1713. ModuleInput(
  1714. constructor_input=FunctionInput(2, 2, 2),
  1715. forward_input=FunctionInput(make_input((1, 3, 7, 7)))),
  1716. ModuleInput(
  1717. constructor_input=FunctionInput(2, 2, 2),
  1718. forward_input=FunctionInput(make_input((3, 7, 7))),
  1719. reference_fn=no_batch_dim_reference_fn,
  1720. desc='no_batch_dim'),
  1721. ModuleInput(
  1722. constructor_input=FunctionInput(1.5, 2),
  1723. forward_input=FunctionInput(make_input((1, 3, 7, 7))),
  1724. desc='norm'),
  1725. ]
  1726. def module_inputs_torch_nn_LPPool3d(module_info, device, dtype, requires_grad, training, **kwargs):
  1727. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1728. return [
  1729. ModuleInput(
  1730. constructor_input=FunctionInput(2, 2, 2),
  1731. forward_input=FunctionInput(make_input((1, 3, 7, 7, 7)))),
  1732. ModuleInput(
  1733. constructor_input=FunctionInput(2, 2, 2),
  1734. forward_input=FunctionInput(make_input((3, 7, 7, 7))),
  1735. reference_fn=no_batch_dim_reference_fn,
  1736. desc='no_batch_dim'),
  1737. ModuleInput(
  1738. constructor_input=FunctionInput(1.5, 2),
  1739. forward_input=FunctionInput(make_input((1, 3, 7, 7, 7))),
  1740. desc='norm'),
  1741. ]
  1742. def module_inputs_torch_nn_MaxPool1d(module_info, device, dtype, requires_grad, training, **kwargs):
  1743. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1744. return [
  1745. ModuleInput(
  1746. constructor_input=FunctionInput(4),
  1747. forward_input=FunctionInput(make_input((2, 10, 4))),
  1748. desc='3d_input'),
  1749. ModuleInput(
  1750. constructor_input=FunctionInput(4, 4),
  1751. forward_input=FunctionInput(make_input((2, 10, 4))),
  1752. desc='stride'),
  1753. ModuleInput(
  1754. constructor_input=FunctionInput(4, return_indices=True),
  1755. forward_input=FunctionInput(make_input((2, 10, 4))),
  1756. desc='return_indices'),
  1757. ]
  1758. def module_inputs_torch_nn_MaxPool2d(module_info, device, dtype, requires_grad, training, **kwargs):
  1759. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1760. return [
  1761. ModuleInput(
  1762. constructor_input=FunctionInput((3, 3), (2, 2), (1, 1)),
  1763. forward_input=FunctionInput(make_input((3, 7, 7))),
  1764. desc='3d_input'),
  1765. ModuleInput(
  1766. constructor_input=FunctionInput((3, 3), (2, 2), (1, 1)),
  1767. forward_input=FunctionInput(make_input((1, 3, 7, 7))),
  1768. desc='4d_input'),
  1769. ModuleInput(
  1770. constructor_input=FunctionInput((3, 3), (2, 2), (1, 1), return_indices=True),
  1771. forward_input=FunctionInput(make_input((1, 3, 7, 7))),
  1772. desc='return_indices'),
  1773. ]
  1774. def module_inputs_torch_nn_MaxPool3d(module_info, device, dtype, requires_grad, training, **kwargs):
  1775. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1776. return [
  1777. ModuleInput(
  1778. constructor_input=FunctionInput((2, 2, 2)),
  1779. forward_input=FunctionInput(make_input((2, 3, 5, 5, 5)))),
  1780. ModuleInput(
  1781. constructor_input=FunctionInput(2, (2, 2, 2)),
  1782. forward_input=FunctionInput(make_input((2, 3, 5, 5, 5))),
  1783. desc='stride'),
  1784. ModuleInput(
  1785. constructor_input=FunctionInput(2, 2, (1, 1, 1)),
  1786. forward_input=FunctionInput(make_input((2, 3, 5, 5, 5))),
  1787. desc='stride_padding'),
  1788. ModuleInput(
  1789. constructor_input=FunctionInput(2, 2, (1, 1, 1), return_indices=True),
  1790. forward_input=FunctionInput(make_input((2, 3, 5, 5, 5))),
  1791. desc='return_indices'),
  1792. ]
  1793. def module_inputs_torch_nn_FractionalMaxPool2d(module_info, device, dtype, requires_grad, training, **kwargs):
  1794. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1795. def make_random_samples():
  1796. return torch.empty((1, 3, 2), dtype=torch.double, device=device).uniform_()
  1797. return [
  1798. ModuleInput(
  1799. constructor_input=FunctionInput(2, output_ratio=0.5, _random_samples=make_random_samples()),
  1800. forward_input=FunctionInput(make_input((1, 3, 5, 7))),
  1801. desc='ratio'),
  1802. ModuleInput(
  1803. constructor_input=FunctionInput((2, 3), output_size=(4, 3), _random_samples=make_random_samples()),
  1804. forward_input=FunctionInput(make_input((1, 3, 7, 6))),
  1805. desc='size'),
  1806. ModuleInput(
  1807. constructor_input=FunctionInput(
  1808. 2, output_ratio=0.5, _random_samples=make_random_samples(), return_indices=True
  1809. ),
  1810. forward_input=FunctionInput(make_input((1, 3, 5, 7))),
  1811. desc='ratio_return_indices'),
  1812. ModuleInput(
  1813. constructor_input=FunctionInput(2, output_ratio=0.5, _random_samples=make_random_samples()),
  1814. forward_input=FunctionInput(make_input((3, 5, 7))),
  1815. reference_fn=no_batch_dim_reference_fn,
  1816. desc='ratio_no_batch_dim'),
  1817. ModuleInput(
  1818. constructor_input=FunctionInput((2, 3), output_size=(4, 3), _random_samples=make_random_samples()),
  1819. forward_input=FunctionInput(make_input((3, 7, 6))),
  1820. reference_fn=no_batch_dim_reference_fn,
  1821. desc='size_no_batch_dim'),
  1822. ]
  1823. def module_inputs_torch_nn_FractionalMaxPool3d(module_info, device, dtype, requires_grad, training, **kwargs):
  1824. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1825. def make_random_samples():
  1826. return torch.empty((2, 4, 3), dtype=torch.double, device=device).uniform_()
  1827. return [
  1828. ModuleInput(
  1829. constructor_input=FunctionInput(2, output_ratio=0.5, _random_samples=make_random_samples()),
  1830. forward_input=FunctionInput(make_input((2, 4, 5, 5, 5))),
  1831. desc='ratio'),
  1832. ModuleInput(
  1833. constructor_input=FunctionInput((2, 2, 2), output_size=(4, 4, 4), _random_samples=make_random_samples()),
  1834. forward_input=FunctionInput(make_input((2, 4, 7, 7, 7))),
  1835. desc='size'),
  1836. ModuleInput(
  1837. constructor_input=FunctionInput((4, 2, 3), output_size=(10, 3, 2), _random_samples=make_random_samples()),
  1838. forward_input=FunctionInput(make_input((2, 4, 16, 7, 5))),
  1839. desc='asymsize'),
  1840. ModuleInput(
  1841. constructor_input=FunctionInput(
  1842. 2, output_ratio=0.5, _random_samples=make_random_samples(), return_indices=True
  1843. ),
  1844. forward_input=FunctionInput(make_input((2, 4, 5, 5, 5))),
  1845. desc='ratio_return_indices'),
  1846. ModuleInput(
  1847. constructor_input=FunctionInput(2, output_ratio=0.5, _random_samples=make_random_samples()),
  1848. forward_input=FunctionInput(make_input((4, 5, 5, 5))),
  1849. reference_fn=no_batch_dim_reference_fn,
  1850. desc='ratio_no_batch_dim'),
  1851. ModuleInput(
  1852. constructor_input=FunctionInput((2, 2, 2), output_size=(4, 4, 4), _random_samples=make_random_samples()),
  1853. forward_input=FunctionInput(make_input((4, 7, 7, 7))),
  1854. reference_fn=no_batch_dim_reference_fn,
  1855. desc='size_no_batch_dim'),
  1856. ]
  1857. def module_inputs_torch_nn_Sigmoid(module_info, device, dtype, requires_grad, training, **kwargs):
  1858. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1859. return [
  1860. ModuleInput(
  1861. constructor_input=FunctionInput(),
  1862. forward_input=FunctionInput(make_input(())),
  1863. desc='scalar'
  1864. ),
  1865. ModuleInput(
  1866. constructor_input=FunctionInput(),
  1867. forward_input=FunctionInput(make_input(4)),
  1868. reference_fn=no_batch_dim_reference_fn,
  1869. desc='no_batch_dim',
  1870. ),
  1871. ModuleInput(
  1872. constructor_input=FunctionInput(),
  1873. forward_input=FunctionInput(make_input((2, 3, 4, 5))),
  1874. desc='channels_last_mem_format'
  1875. ),
  1876. ModuleInput(
  1877. constructor_input=FunctionInput(),
  1878. forward_input=FunctionInput(make_input((2, 3, 3, 4, 5))),
  1879. desc='channels_last_3d_mem_format'
  1880. )
  1881. ]
  1882. def module_inputs_torch_nn_LogSigmoid(module_info, device, dtype, requires_grad, training, **kwargs):
  1883. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1884. return [
  1885. ModuleInput(
  1886. constructor_input=FunctionInput(),
  1887. forward_input=FunctionInput(make_input(())),
  1888. reference_fn=lambda m, p, i: i.sigmoid().log(),
  1889. desc='scalar'
  1890. ),
  1891. ModuleInput(
  1892. constructor_input=FunctionInput(),
  1893. forward_input=FunctionInput(make_input((2, 3, 4))),
  1894. reference_fn=lambda m, p, i: i.sigmoid().log(),
  1895. ),
  1896. ModuleInput(
  1897. constructor_input=FunctionInput(),
  1898. forward_input=FunctionInput(make_input(4)),
  1899. reference_fn=no_batch_dim_reference_fn,
  1900. desc='no_batch_dim',
  1901. ),
  1902. ]
  1903. def module_inputs_torch_nn_MarginRankingLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  1904. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1905. make_target = partial(make_tensor, device=device, dtype=torch.long, requires_grad=False)
  1906. cases: List[Tuple[str, dict]] = [
  1907. ('', {}),
  1908. ('reduction_sum', {'reduction': 'sum'}),
  1909. ('reduction_mean', {'reduction': 'mean'}),
  1910. ('reduction_none', {'reduction': 'none'}),
  1911. ('margin', {'margin': 0.5})
  1912. ]
  1913. module_inputs = []
  1914. for desc, constructor_kwargs in cases:
  1915. def reference_fn(m, p, i1, i2, t, constructor_kwargs=constructor_kwargs):
  1916. return marginrankingloss_reference(i1, i2, t, **constructor_kwargs)
  1917. module_inputs.append(
  1918. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  1919. forward_input=FunctionInput(make_input((50,)), make_input((50,)),
  1920. make_target((50,)).sign()),
  1921. desc=desc,
  1922. reference_fn=reference_fn)
  1923. )
  1924. return module_inputs
  1925. def module_inputs_torch_nn_MultiLabelMarginLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  1926. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1927. make_target = partial(make_tensor, device=device, dtype=torch.long, requires_grad=False)
  1928. cases: List[Tuple[str, dict]] = [
  1929. ('', {}),
  1930. ('reduction_sum', {'reduction': 'sum'}),
  1931. ('reduction_mean', {'reduction': 'mean'}),
  1932. ('reduction_none', {'reduction': 'none'}),
  1933. ]
  1934. module_inputs = []
  1935. for desc, constructor_kwargs in cases:
  1936. def reference_fn(m, p, i, t, constructor_kwargs=constructor_kwargs):
  1937. return multilabelmarginloss_reference(i, t, **constructor_kwargs)
  1938. module_inputs.append(
  1939. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  1940. forward_input=FunctionInput(make_input((10,)),
  1941. make_target((10), low=0, high=10)),
  1942. desc=f'1d_{desc}',
  1943. reference_fn=reference_fn)
  1944. )
  1945. module_inputs.append(
  1946. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  1947. forward_input=FunctionInput(make_input((5, 10)),
  1948. make_target((5, 10), low=0, high=10)),
  1949. desc=desc,
  1950. reference_fn=reference_fn)
  1951. )
  1952. return module_inputs
  1953. def module_inputs_torch_nn_MultiMarginLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  1954. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1955. make_target = partial(make_tensor, device=device, dtype=torch.long, requires_grad=False)
  1956. make_weight = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  1957. cases: List[Tuple[str, dict]] = [
  1958. ('', {}),
  1959. ('reduction_sum', {'reduction': 'sum'}),
  1960. ('reduction_mean', {'reduction': 'mean'}),
  1961. ('reduction_none', {'reduction': 'none'}),
  1962. ('p', {'p': 2}),
  1963. ('margin', {'margin': 0.5}),
  1964. ('weights', {'weight': make_weight(10)})
  1965. ]
  1966. module_inputs = []
  1967. for desc, constructor_kwargs in cases:
  1968. def reference_fn(m, p, i, t, constructor_kwargs=constructor_kwargs):
  1969. return multimarginloss_reference(i, t, **constructor_kwargs)
  1970. module_inputs.append(
  1971. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  1972. forward_input=FunctionInput(make_input((5, 10)),
  1973. make_target((5), low=0, high=10)),
  1974. desc=desc,
  1975. reference_fn=reference_fn)
  1976. )
  1977. return module_inputs
  1978. def module_inputs_torch_nn_MultiLabelSoftMarginLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  1979. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  1980. make_target = partial(make_tensor, device=device, dtype=torch.long, requires_grad=False)
  1981. make_weight = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  1982. cases: List[Tuple[str, dict]] = [
  1983. ('', {}),
  1984. ('reduction_sum', {'reduction': 'sum'}),
  1985. ('reduction_mean', {'reduction': 'mean'}),
  1986. ('reduction_none', {'reduction': 'none'}),
  1987. ('weight', {'weight': make_weight(10)}),
  1988. ]
  1989. def multilabelsoftmargin_loss_reference_fn(m, p, i, t, reduction='mean', weight=None):
  1990. result = t * i.sigmoid().log() + (1 - t) * (-i).sigmoid().log()
  1991. if weight is not None:
  1992. result *= weight
  1993. result = (-result).sum(i.dim() - 1) / i.size(-1)
  1994. if reduction == 'none':
  1995. return result
  1996. elif reduction == 'mean':
  1997. return result.mean()
  1998. else:
  1999. return result.sum()
  2000. module_inputs = []
  2001. for desc, constructor_kwargs in cases:
  2002. module_inputs.append(
  2003. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  2004. forward_input=FunctionInput(make_input((5, 10)),
  2005. make_target((5, 10), low=0, high=2)),
  2006. desc=desc,
  2007. reference_fn=partial(multilabelsoftmargin_loss_reference_fn, **constructor_kwargs))
  2008. )
  2009. return module_inputs
  2010. def module_inputs_torch_nn_SoftMarginLoss(module_info, device, dtype, requires_grad, training, **kwargs):
  2011. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2012. make_target = partial(make_tensor, device=device, dtype=dtype, requires_grad=False)
  2013. cases: List[Tuple[str, dict]] = [
  2014. ('', {}),
  2015. ('reduction_sum', {'reduction': 'sum'}),
  2016. ('reduction_mean', {'reduction': 'mean'}),
  2017. ('reduction_none', {'reduction': 'none'}),
  2018. ]
  2019. module_inputs = []
  2020. for desc, constructor_kwargs in cases:
  2021. def reference_fn(m, p, i, t, constructor_kwargs=constructor_kwargs):
  2022. return softmarginloss_reference(i, t, **constructor_kwargs)
  2023. module_inputs.append(
  2024. ModuleInput(constructor_input=FunctionInput(**constructor_kwargs),
  2025. forward_input=FunctionInput(make_input((5, 5)),
  2026. make_target((5, 5)).sign()),
  2027. desc=desc,
  2028. reference_fn=reference_fn)
  2029. )
  2030. return module_inputs
  2031. def module_inputs_torch_nn_TransformerEncoder(module_info, device, dtype, requires_grad, training, **kwargs):
  2032. # Reuse the TransformerEncoderLayer samples since the forward args are nearly the same.
  2033. samples = []
  2034. for layer_module_input in module_inputs_torch_nn_TransformerEncoderLayer(
  2035. None, device, dtype, requires_grad, training):
  2036. # Construct a TransformerEncoderLayer object to pass to TransformerEncoder.
  2037. l_args, l_kwargs = (layer_module_input.constructor_input.args,
  2038. layer_module_input.constructor_input.kwargs)
  2039. l_kwargs['device'] = device
  2040. l_kwargs['dtype'] = dtype
  2041. encoder_layer = torch.nn.TransformerEncoderLayer(*l_args, **l_kwargs)
  2042. num_layers = 2
  2043. # Note: TransformerEncoderLayer takes a "src_mask" while
  2044. # TransformerEncoder takes a "mask"; rename kwarg appropriately.
  2045. forward_input = layer_module_input.forward_input
  2046. if 'src_mask' in forward_input.kwargs:
  2047. forward_input.kwargs['mask'] = forward_input.kwargs['src_mask']
  2048. del forward_input.kwargs['src_mask']
  2049. samples.append(ModuleInput(
  2050. constructor_input=FunctionInput(encoder_layer, num_layers),
  2051. forward_input=forward_input,
  2052. desc=layer_module_input.desc
  2053. ))
  2054. return samples
  2055. def module_inputs_torch_nn_TransformerEncoderLayer(module_info, device, dtype, requires_grad, training, **kwargs):
  2056. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2057. samples = [
  2058. ModuleInput(
  2059. constructor_input=FunctionInput(4, 2, 16, 0.0),
  2060. forward_input=FunctionInput(
  2061. make_input((2, 3, 4))
  2062. ),
  2063. desc='relu_activation'
  2064. ),
  2065. ModuleInput(
  2066. constructor_input=FunctionInput(4, 2, 8, 0.0, F.gelu),
  2067. forward_input=FunctionInput(
  2068. make_input((2, 3, 4))
  2069. ),
  2070. desc='gelu_activation'
  2071. ),
  2072. ModuleInput(
  2073. constructor_input=FunctionInput(4, 2, 8, 0.0, bias=False),
  2074. forward_input=FunctionInput(
  2075. make_input((2, 3, 4))
  2076. ),
  2077. desc='no_bias'
  2078. ),]
  2079. # Samples below are for validating the no-batch-dim support.
  2080. key_padding_masks = (None, torch.tensor([False, False, True], device=device, dtype=torch.bool))
  2081. attn_masks = (None, torch.tensor([False, False, True], device=device, dtype=torch.bool).expand((3, 3)))
  2082. for src_mask, src_key_padding_mask, norm_first, batch_first, bias in \
  2083. itertools.product(attn_masks, key_padding_masks, (True, False), (True, False), (True, False)):
  2084. samples.append(
  2085. ModuleInput(
  2086. constructor_input=FunctionInput(d_model=4, nhead=2, dim_feedforward=8,
  2087. dropout=0.0, batch_first=batch_first,
  2088. norm_first=norm_first, bias=bias),
  2089. forward_input=FunctionInput(
  2090. make_input((3, 4)), src_mask=src_mask, src_key_padding_mask=src_key_padding_mask
  2091. ),
  2092. reference_fn=partial(no_batch_dim_reference_fn,
  2093. batch_first=batch_first, kwargs_to_batchify={'src_key_padding_mask': 0}),
  2094. desc=f'no_batch_dim_batch_first_{batch_first}'
  2095. ))
  2096. # Samples below where we pass reference_fn are for validating the fast path,
  2097. # since the fast path requires no_grad mode, we run the fast path in .eval()
  2098. # and no_grad() in the reference_fn and verify that against the results in train mode.
  2099. def fast_path_reference_fn(module, parameters, *args, **kwargs):
  2100. assert module.training
  2101. module.train(False)
  2102. with torch.no_grad():
  2103. output = module(*args, **kwargs)
  2104. module.train(True)
  2105. return output
  2106. if training:
  2107. for norm_first, bias in itertools.product((True, False), (True, False)):
  2108. samples.append(
  2109. ModuleInput(
  2110. constructor_input=FunctionInput(
  2111. 4, 2, 8, dropout=0.0, batch_first=True, norm_first=norm_first, bias=bias
  2112. ),
  2113. forward_input=FunctionInput(
  2114. make_input((2, 3, 4)),
  2115. ),
  2116. # fastpath doesn't run when bias=False
  2117. reference_fn=fast_path_reference_fn if bias else None,
  2118. desc=f'fastpath_{bias}_norm_first_{norm_first}'
  2119. )
  2120. )
  2121. return samples
  2122. def module_inputs_torch_nn_TransformerDecoderLayer(module_info, device, dtype, requires_grad, training, **kwargs):
  2123. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2124. samples = [
  2125. ModuleInput(
  2126. constructor_input=FunctionInput(4, 2, 16, 0.0),
  2127. forward_input=FunctionInput(
  2128. make_input((2, 3, 4)), make_input((2, 3, 4))
  2129. ),
  2130. desc='relu_activation'
  2131. ),
  2132. ModuleInput(
  2133. constructor_input=FunctionInput(4, 2, 8, 0.0, F.gelu),
  2134. forward_input=FunctionInput(
  2135. make_input((2, 3, 4)), make_input((2, 3, 4))
  2136. ),
  2137. desc='gelu_activation'
  2138. ),
  2139. ModuleInput(
  2140. constructor_input=FunctionInput(4, 2, 8, 0.0, bias=False),
  2141. forward_input=FunctionInput(
  2142. make_input((2, 3, 4)), make_input((2, 3, 4))
  2143. ),
  2144. desc='no_bias'
  2145. ), ]
  2146. key_padding_masks = (None, torch.tensor([False, False, True], device=device, dtype=torch.bool))
  2147. attn_masks = (None, torch.tensor([False, False, True], device=device, dtype=torch.bool).expand((3, 3)))
  2148. for tgt_mask, tgt_key_padding_mask, norm_first, bias, batch_first in \
  2149. itertools.product(attn_masks, key_padding_masks, (True, False), (True, False), (True, False)):
  2150. # Using same mask for tgt and memory
  2151. memory_mask = tgt_mask
  2152. memory_key_padding_mask = tgt_key_padding_mask
  2153. samples.append(
  2154. ModuleInput(
  2155. constructor_input=FunctionInput(d_model=4, nhead=2, dim_feedforward=8,
  2156. dropout=0.0, batch_first=batch_first,
  2157. norm_first=norm_first, bias=bias),
  2158. forward_input=FunctionInput(
  2159. make_input((3, 4)), make_input((3, 4)), tgt_mask=tgt_mask, memory_mask=memory_mask,
  2160. tgt_key_padding_mask=tgt_key_padding_mask, memory_key_padding_mask=memory_key_padding_mask
  2161. ),
  2162. reference_fn=partial(no_batch_dim_reference_fn,
  2163. batch_first=batch_first,
  2164. kwargs_to_batchify={'tgt_key_padding_mask': 0, 'memory_key_padding_mask': 0}),
  2165. desc=f'no_batch_dim_batch_first_{batch_first}'
  2166. ))
  2167. src, tgt = make_input((2, 3, 4)), make_input((2, 3, 4))
  2168. if not batch_first:
  2169. src, tgt = src.transpose(0, 1), tgt.transpose(0, 1)
  2170. if tgt_key_padding_mask is not None:
  2171. memory_key_padding_mask, tgt_key_padding_mask = (tgt_key_padding_mask.expand(2, 3),) * 2
  2172. samples.append(
  2173. ModuleInput(
  2174. constructor_input=FunctionInput(d_model=4, nhead=2, dim_feedforward=8,
  2175. dropout=0.0, batch_first=batch_first,
  2176. norm_first=norm_first, bias=bias),
  2177. forward_input=FunctionInput(
  2178. src, tgt, tgt_mask=tgt_mask, memory_mask=memory_mask,
  2179. tgt_key_padding_mask=tgt_key_padding_mask, memory_key_padding_mask=memory_key_padding_mask
  2180. ),
  2181. desc=f'norm_first_{norm_first}_batch_first_{batch_first}_bias_{bias}'
  2182. ))
  2183. return samples
  2184. def module_inputs_torch_nn_Transformer(module_info, device, dtype, requires_grad, training, **kwargs):
  2185. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2186. samples = []
  2187. # Samples below are for validating the no-batch-dim support.
  2188. key_padding_masks = (None, torch.tensor([False, False, True], device=device, dtype=torch.bool))
  2189. attn_masks = (None, torch.tensor([False, False, True], device=device, dtype=torch.bool).expand((3, 3)))
  2190. for mask, key_padding_mask, norm_first, bias, batch_first in \
  2191. itertools.product(attn_masks, key_padding_masks, (True, False), (True, False), (True, False)):
  2192. # Using same mask for tgt and memory
  2193. src_mask , tgt_mask = (mask,) * 2
  2194. src_key_padding_mask, tgt_key_padding_mask = (key_padding_mask,) * 2
  2195. samples.append(
  2196. ModuleInput(
  2197. constructor_input=FunctionInput(d_model=4, nhead=2, dim_feedforward=8,
  2198. num_encoder_layers=1, num_decoder_layers=1,
  2199. dropout=0.0, batch_first=batch_first, norm_first=norm_first, bias=bias),
  2200. forward_input=FunctionInput(
  2201. make_input((3, 4)), make_input((3, 4)), tgt_mask=tgt_mask, src_mask=src_mask,
  2202. tgt_key_padding_mask=tgt_key_padding_mask, src_key_padding_mask=src_key_padding_mask
  2203. ),
  2204. reference_fn=partial(no_batch_dim_reference_fn,
  2205. batch_first=batch_first,
  2206. kwargs_to_batchify={'tgt_key_padding_mask': 0, 'src_key_padding_mask': 0}),
  2207. desc=f'no_batch_dim_batch_first_{batch_first}'
  2208. ))
  2209. src, tgt = make_input((2, 3, 4)), make_input((2, 3, 4))
  2210. if not batch_first:
  2211. src = src.transpose(0, 1)
  2212. tgt = tgt.transpose(0, 1)
  2213. if key_padding_mask is not None:
  2214. src_key_padding_mask, tgt_key_padding_mask = (key_padding_mask.expand(2, 3),) * 2
  2215. samples.append(
  2216. ModuleInput(
  2217. constructor_input=FunctionInput(d_model=4, nhead=2, dim_feedforward=8,
  2218. num_encoder_layers=1, num_decoder_layers=1,
  2219. dropout=0.0, batch_first=batch_first, norm_first=norm_first, bias=bias),
  2220. forward_input=FunctionInput(
  2221. src, tgt, tgt_mask=tgt_mask, src_mask=src_mask,
  2222. tgt_key_padding_mask=tgt_key_padding_mask, src_key_padding_mask=src_key_padding_mask
  2223. ),
  2224. ))
  2225. return samples
  2226. def module_inputs_torch_nn_Embedding(module_info, device, dtype, requires_grad, training, **kwargs):
  2227. make_empty = partial(torch.empty, device=device, dtype=torch.long, requires_grad=False)
  2228. return [
  2229. ModuleInput(
  2230. constructor_input=FunctionInput(num_embeddings=4, embedding_dim=3),
  2231. forward_input=FunctionInput(make_empty(2, 3).random_(4))
  2232. ),
  2233. ModuleInput(
  2234. constructor_input=FunctionInput(num_embeddings=4, embedding_dim=3),
  2235. forward_input=FunctionInput(make_empty(1, 512).random_(4).expand(7, 512)),
  2236. desc='discontiguous'
  2237. ),
  2238. ]
  2239. def module_inputs_torch_nn_MultiheadAttention(module_info, device, dtype, requires_grad, training, **kwargs):
  2240. # Currently all samples below are for validating the no-batch-dim support.
  2241. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2242. samples = []
  2243. bool_vals = (True, False)
  2244. key_padding_masks = (None, torch.tensor([False, False, True], device=device, dtype=torch.bool))
  2245. attn_masks = (None, torch.tensor([False, False, True], device=device, dtype=torch.bool).expand((3, 3, 3)))
  2246. products = itertools.product(bool_vals, bool_vals, bool_vals, key_padding_masks, attn_masks)
  2247. for bias, add_bias_kv, add_zero_attn, key_padding_mask, attn_mask in products:
  2248. samples.append(
  2249. ModuleInput(
  2250. constructor_input=FunctionInput(embed_dim=3, num_heads=3, batch_first=True,
  2251. bias=bias, add_bias_kv=add_bias_kv, add_zero_attn=add_zero_attn),
  2252. forward_input=FunctionInput(make_input((3, 3)), make_input((3, 3)), make_input((3, 3)),
  2253. key_padding_mask=key_padding_mask, attn_mask=attn_mask),
  2254. reference_fn=no_batch_dim_reference_mha,
  2255. )
  2256. )
  2257. samples.append(
  2258. ModuleInput(
  2259. constructor_input=FunctionInput(embed_dim=3, num_heads=3, batch_first=False,
  2260. bias=bias, add_bias_kv=add_bias_kv, add_zero_attn=add_zero_attn),
  2261. forward_input=FunctionInput(make_input((3, 3)), make_input((3, 3)), make_input((3, 3)),
  2262. key_padding_mask=key_padding_mask, attn_mask=attn_mask),
  2263. reference_fn=partial(no_batch_dim_reference_mha, batch_first=False),
  2264. )
  2265. )
  2266. return samples
  2267. def module_inputs_torch_nn_RNN_GRU_Cell(module_info, device, dtype, requires_grad, training, **kwargs):
  2268. # Currently all samples below are for validating the no-batch-dim support.
  2269. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2270. samples = [
  2271. ModuleInput(
  2272. constructor_input=FunctionInput(5, 10),
  2273. forward_input=FunctionInput(make_input(5), make_input(10)),
  2274. reference_fn=no_batch_dim_reference_fn,
  2275. ),
  2276. ModuleInput(
  2277. constructor_input=FunctionInput(5, 10, bias=True),
  2278. forward_input=FunctionInput(make_input(5), make_input(10)),
  2279. reference_fn=no_batch_dim_reference_fn,
  2280. )
  2281. ]
  2282. is_rnn = kwargs.get('is_rnn', False)
  2283. if is_rnn:
  2284. # RNN also supports `nonlinearity` argument.
  2285. # `tanh` is the default, so we check with `relu`
  2286. samples.append(
  2287. ModuleInput(
  2288. constructor_input=FunctionInput(5, 10, bias=True, nonlinearity='relu'),
  2289. forward_input=FunctionInput(make_input(5), make_input(10)),
  2290. reference_fn=no_batch_dim_reference_fn,
  2291. )
  2292. )
  2293. return samples
  2294. def module_inputs_torch_nn_LSTMCell(module_info, device, dtype, requires_grad, training, **kwargs):
  2295. # Currently all samples below are for validating the no-batch-dim support.
  2296. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2297. samples = (
  2298. ModuleInput(
  2299. constructor_input=FunctionInput(5, 10),
  2300. forward_input=FunctionInput(make_input(5), (make_input(10), make_input(10))),
  2301. reference_fn=no_batch_dim_reference_lstmcell,
  2302. ),
  2303. ModuleInput(
  2304. constructor_input=FunctionInput(5, 10, bias=True),
  2305. forward_input=FunctionInput(make_input(5), (make_input(10), make_input(10))),
  2306. reference_fn=no_batch_dim_reference_lstmcell,
  2307. ),
  2308. )
  2309. return samples
  2310. def make_packed_sequence(inp, batch_sizes):
  2311. required_grad = inp.requires_grad
  2312. inp.requires_grad_(False) # user won't have access to inp so won't be able to get its grads
  2313. seq = pack_padded_sequence(inp, batch_sizes)
  2314. seq.data.requires_grad_(required_grad)
  2315. return seq
  2316. def module_inputs_torch_nn_RNN_GRU(module_info, device, dtype, requires_grad, training, with_packed_sequence=False, **kwargs):
  2317. # Currently all samples below are for validating the no-batch-dim support.
  2318. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2319. is_rnn = kwargs['is_rnn']
  2320. nonlinearity = ('relu', 'tanh')
  2321. bias = (False, True)
  2322. batch_first = (False, True)
  2323. bidirectional = (False, True)
  2324. samples = []
  2325. if is_rnn:
  2326. prod_gen = product(nonlinearity, bias, batch_first, bidirectional)
  2327. else:
  2328. prod_gen = product(bias, batch_first, bidirectional)
  2329. for args in prod_gen:
  2330. if is_rnn:
  2331. nl, b, b_f, bidir = args
  2332. else:
  2333. b, b_f, bidir = args
  2334. cons_args = {'input_size': 2, 'hidden_size': 2, 'num_layers': 2,
  2335. 'batch_first': b_f, 'bias': b, 'bidirectional': bidir}
  2336. cons_args_hidden = {'input_size': 2, 'hidden_size': 3, 'num_layers': 2,
  2337. 'batch_first': b_f, 'bias': b, 'bidirectional': bidir}
  2338. if is_rnn:
  2339. cons_args['nonlinearity'] = nl
  2340. cons_args_hidden['nonlinearity'] = nl
  2341. samples.append(
  2342. ModuleInput(
  2343. constructor_input=FunctionInput(**cons_args),
  2344. forward_input=FunctionInput(make_input((3, 2))),
  2345. reference_fn=partial(no_batch_dim_reference_rnn_gru, batch_first=b_f),
  2346. )
  2347. )
  2348. samples.append(
  2349. ModuleInput(
  2350. constructor_input=FunctionInput(**cons_args_hidden),
  2351. forward_input=FunctionInput(make_input((3, 2)), make_input((4 if bidir else 2, 3))),
  2352. reference_fn=partial(no_batch_dim_reference_rnn_gru, batch_first=b_f),
  2353. )
  2354. )
  2355. if with_packed_sequence:
  2356. samples.append(
  2357. ModuleInput(
  2358. constructor_input=FunctionInput(**cons_args),
  2359. forward_input=FunctionInput(make_packed_sequence(make_input((5, 2, 2)), torch.tensor([5, 3]))),
  2360. reference_fn=partial(no_batch_dim_reference_rnn_gru, batch_first=b_f),
  2361. )
  2362. )
  2363. samples.append(
  2364. ModuleInput(
  2365. constructor_input=FunctionInput(**cons_args),
  2366. forward_input=FunctionInput(make_packed_sequence(make_input((5, 5, 2)), torch.tensor([5, 3, 3, 2, 2]))),
  2367. reference_fn=partial(no_batch_dim_reference_rnn_gru, batch_first=b_f),
  2368. )
  2369. )
  2370. return samples
  2371. def module_inputs_torch_nn_LSTM(module_info, device, dtype, requires_grad, training, **kwargs):
  2372. # Currently all samples below are for validating the no-batch-dim support.
  2373. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2374. bias = (False, True)
  2375. batch_first = (False, True)
  2376. bidirectional = (False, True)
  2377. proj_sizes = (0, 2)
  2378. samples = []
  2379. prod_gen = product(bias, batch_first, bidirectional, proj_sizes)
  2380. for args in prod_gen:
  2381. b, b_f, bidir, proj_size = args
  2382. hidden_size = 3
  2383. cons_args = {'input_size': 2, 'hidden_size': hidden_size, 'num_layers': 2, 'proj_size': proj_size,
  2384. 'batch_first': b_f, 'bias': b, 'bidirectional': bidir}
  2385. cons_args_hidden = {'input_size': 2, 'hidden_size': hidden_size, 'num_layers': 2, 'proj_size': proj_size,
  2386. 'batch_first': b_f, 'bias': b, 'bidirectional': bidir}
  2387. samples.append(
  2388. ModuleInput(
  2389. constructor_input=FunctionInput(**cons_args),
  2390. forward_input=FunctionInput(make_input((2, 2))),
  2391. reference_fn=partial(no_batch_dim_reference_lstm, batch_first=b_f),
  2392. )
  2393. )
  2394. h_out = proj_size if proj_size > 0 else hidden_size
  2395. hx = (make_input((4 if bidir else 2, h_out)), make_input((4 if bidir else 2, hidden_size)))
  2396. samples.append(
  2397. ModuleInput(
  2398. constructor_input=FunctionInput(**cons_args_hidden),
  2399. forward_input=FunctionInput(make_input((3, 2)), hx),
  2400. reference_fn=partial(no_batch_dim_reference_lstm, batch_first=b_f),
  2401. )
  2402. )
  2403. return samples
  2404. def module_inputs_torch_nn_ReflectionPad1d(module_info, device, dtype, requires_grad, training, **kwargs):
  2405. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2406. return [
  2407. ModuleInput(
  2408. constructor_input=FunctionInput(1),
  2409. forward_input=FunctionInput(make_input((2, 3))),
  2410. reference_fn=no_batch_dim_reference_fn,
  2411. ),
  2412. ModuleInput(
  2413. constructor_input=FunctionInput((1, 2)),
  2414. forward_input=FunctionInput(make_input((2, 3, 4))),
  2415. ),
  2416. ]
  2417. def module_inputs_torch_nn_ReflectionPad2d(module_info, device, dtype, requires_grad, training, **kwargs):
  2418. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2419. return [
  2420. ModuleInput(
  2421. constructor_input=FunctionInput(1),
  2422. forward_input=FunctionInput(make_input((3, 4, 5))),
  2423. reference_fn=no_batch_dim_reference_fn,
  2424. ),
  2425. ModuleInput(
  2426. constructor_input=FunctionInput((1, 2, 3, 4)),
  2427. forward_input=FunctionInput(make_input((3, 4, 5, 6))),
  2428. ),
  2429. ]
  2430. def module_inputs_torch_nn_ReflectionPad3d(module_info, device, dtype, requires_grad, training, **kwargs):
  2431. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2432. return [
  2433. ModuleInput(
  2434. constructor_input=FunctionInput(1),
  2435. forward_input=FunctionInput(make_input((2, 3, 4, 5))),
  2436. reference_fn=no_batch_dim_reference_fn
  2437. ),
  2438. ModuleInput(
  2439. constructor_input=FunctionInput((1, 2, 1, 2, 1, 2)),
  2440. forward_input=FunctionInput(make_input((3, 3, 3, 3, 3))),
  2441. ),
  2442. ]
  2443. def module_inputs_torch_nn_ReplicationPad1d(module_info, device, dtype, requires_grad, training, **kwargs):
  2444. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2445. return [
  2446. ModuleInput(
  2447. constructor_input=FunctionInput(1),
  2448. forward_input=FunctionInput(make_input((3, 4))),
  2449. reference_fn=no_batch_dim_reference_fn
  2450. ),
  2451. ModuleInput(
  2452. constructor_input=FunctionInput((1, 2)),
  2453. forward_input=FunctionInput(make_input((3, 4, 5))),
  2454. ),
  2455. ]
  2456. def module_inputs_torch_nn_ReplicationPad2d(module_info, device, dtype, requires_grad, training, **kwargs):
  2457. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2458. return [
  2459. ModuleInput(
  2460. constructor_input=FunctionInput(1),
  2461. forward_input=FunctionInput(make_input((3, 4, 5))),
  2462. reference_fn=no_batch_dim_reference_fn,
  2463. ),
  2464. ModuleInput(
  2465. constructor_input=FunctionInput((1, 2, 3, 4)),
  2466. forward_input=FunctionInput(make_input((3, 4, 5, 6))),
  2467. ),
  2468. ]
  2469. def module_inputs_torch_nn_ReplicationPad3d(module_info, device, dtype, requires_grad, training, **kwargs):
  2470. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2471. return [
  2472. ModuleInput(
  2473. constructor_input=FunctionInput(1),
  2474. forward_input=FunctionInput(make_input((3, 4, 5, 6))),
  2475. reference_fn=no_batch_dim_reference_fn,
  2476. ),
  2477. ModuleInput(
  2478. constructor_input=FunctionInput((1, 2, 3, 4, 5, 6)),
  2479. forward_input=FunctionInput(make_input((3, 4, 5, 6, 7))),
  2480. ),
  2481. ]
  2482. def module_inputs_torch_nn_ZeroPad1d(module_info, device, dtype, requires_grad, training, **kwargs):
  2483. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2484. return [
  2485. ModuleInput(
  2486. constructor_input=FunctionInput(1),
  2487. forward_input=FunctionInput(make_input((3, 4))),
  2488. reference_fn=no_batch_dim_reference_fn,
  2489. ),
  2490. ModuleInput(
  2491. constructor_input=FunctionInput((1, 2)),
  2492. forward_input=FunctionInput(make_input((3, 4, 5))),
  2493. ),
  2494. ]
  2495. def module_inputs_torch_nn_ZeroPad2d(module_info, device, dtype, requires_grad, training, **kwargs):
  2496. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2497. return [
  2498. ModuleInput(
  2499. constructor_input=FunctionInput(1),
  2500. forward_input=FunctionInput(make_input((1, 2, 3))),
  2501. reference_fn=no_batch_dim_reference_fn
  2502. ),
  2503. ModuleInput(
  2504. constructor_input=FunctionInput((1, 2, 3, 4)),
  2505. forward_input=FunctionInput(make_input((1, 2, 3, 4))),
  2506. ),
  2507. ]
  2508. def module_inputs_torch_nn_ZeroPad3d(module_info, device, dtype, requires_grad, training, **kwargs):
  2509. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2510. return [
  2511. ModuleInput(
  2512. constructor_input=FunctionInput(1),
  2513. forward_input=FunctionInput(make_input((3, 4, 5, 6))),
  2514. reference_fn=no_batch_dim_reference_fn,
  2515. ),
  2516. ModuleInput(
  2517. constructor_input=FunctionInput((1, 2, 3, 4, 5, 6)),
  2518. forward_input=FunctionInput(make_input((1, 2, 3, 4, 5))),
  2519. ),
  2520. ]
  2521. def module_inputs_torch_nn_ConstantPad1d(module_info, device, dtype, requires_grad, training, **kwargs):
  2522. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2523. return [
  2524. ModuleInput(
  2525. constructor_input=FunctionInput(1, 2),
  2526. forward_input=FunctionInput(make_input((3, 4))),
  2527. reference_fn=no_batch_dim_reference_fn,
  2528. ),
  2529. ModuleInput(
  2530. constructor_input=FunctionInput((1, 2), 3),
  2531. forward_input=FunctionInput(make_input((3, 4, 5))),
  2532. ),
  2533. ]
  2534. def module_inputs_torch_nn_ConstantPad2d(module_info, device, dtype, requires_grad, training, **kwargs):
  2535. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2536. return [
  2537. ModuleInput(
  2538. constructor_input=FunctionInput(1, 3),
  2539. forward_input=FunctionInput(make_input((3, 4, 5))),
  2540. reference_fn=no_batch_dim_reference_fn
  2541. ),
  2542. ModuleInput(
  2543. constructor_input=FunctionInput((1, 2, 3, 4), 5),
  2544. forward_input=FunctionInput(make_input((1, 2, 3, 4))),
  2545. ),
  2546. ]
  2547. def module_inputs_torch_nn_ConstantPad3d(module_info, device, dtype, requires_grad, training, **kwargs):
  2548. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2549. return [
  2550. ModuleInput(
  2551. constructor_input=FunctionInput(1, 3),
  2552. forward_input=FunctionInput(make_input((3, 4, 5, 6))),
  2553. reference_fn=no_batch_dim_reference_fn,
  2554. ),
  2555. ModuleInput(
  2556. constructor_input=FunctionInput((1, 2, 3, 4, 5, 6), 7),
  2557. forward_input=FunctionInput(make_input((1, 2, 1, 2, 1))),
  2558. ),
  2559. ]
  2560. def module_inputs_torch_nn_CircularPad1d(module_info, device, dtype, requires_grad, training, **kwargs):
  2561. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2562. def padding1d_circular_ref(inp, pad):
  2563. r""" input:
  2564. [[[0., 1., 2.],
  2565. [3., 4., 5.]]]
  2566. pad: (1, 2)
  2567. output:
  2568. [[[2., 0., 1., 2., 0., 1.],
  2569. [5., 3., 4., 5., 3., 4.]]]
  2570. """
  2571. return torch.cat([inp[:, :, -pad[0]:], inp, inp[:, :, :pad[1]]], dim=2)
  2572. return [
  2573. ModuleInput(
  2574. constructor_input=FunctionInput(1),
  2575. forward_input=FunctionInput(make_input((3, 4))),
  2576. reference_fn=no_batch_dim_reference_fn
  2577. ),
  2578. ModuleInput(
  2579. constructor_input=FunctionInput((1, 2)),
  2580. forward_input=FunctionInput(make_input((1, 2, 3))),
  2581. reference_fn=lambda m, p, i: padding1d_circular_ref(i, m.padding),
  2582. ),
  2583. ModuleInput(
  2584. constructor_input=FunctionInput((3, 1)),
  2585. forward_input=FunctionInput(make_input((1, 2, 3))),
  2586. reference_fn=lambda m, p, i: padding1d_circular_ref(i, m.padding),
  2587. ),
  2588. ModuleInput(
  2589. constructor_input=FunctionInput((3, 3)),
  2590. forward_input=FunctionInput(make_input((1, 2, 3))),
  2591. reference_fn=lambda m, p, i: padding1d_circular_ref(i, m.padding),
  2592. ),
  2593. ]
  2594. def module_inputs_torch_nn_CircularPad2d(module_info, device, dtype, requires_grad, training, **kwargs):
  2595. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2596. def padding2d_circular_ref(inp, pad):
  2597. r"""input:
  2598. [[[[0., 1., 2],
  2599. [3., 4., 5.]]]]
  2600. pad: (1, 2, 2, 1)
  2601. output:
  2602. [[[[2., 0., 1., 2., 0., 1.],
  2603. [5., 3., 4., 5., 3., 4.],
  2604. [2., 0., 1., 2., 0., 1.],
  2605. [5., 3., 4., 5., 3., 4.],
  2606. [2., 0., 1., 2., 0., 1.]]]]
  2607. """
  2608. inp = torch.cat([inp[:, :, -pad[2]:], inp, inp[:, :, :pad[3]]], dim=2)
  2609. return torch.cat([inp[:, :, :, -pad[0]:], inp, inp[:, :, :, :pad[1]]], dim=3)
  2610. return [
  2611. ModuleInput(
  2612. constructor_input=FunctionInput(1),
  2613. forward_input=FunctionInput(make_input((3, 4, 5))),
  2614. reference_fn=no_batch_dim_reference_fn,
  2615. ),
  2616. ModuleInput(
  2617. constructor_input=FunctionInput((1, 2, 2, 1)),
  2618. forward_input=FunctionInput(make_input((1, 1, 2, 3))),
  2619. reference_fn=lambda m, p, i: padding2d_circular_ref(i, m.padding),
  2620. ),
  2621. ModuleInput(
  2622. constructor_input=FunctionInput((2, 3, 2, 2)),
  2623. forward_input=FunctionInput(make_input((1, 1, 2, 3))),
  2624. reference_fn=lambda m, p, i: padding2d_circular_ref(i, m.padding),
  2625. ),
  2626. ModuleInput(
  2627. constructor_input=FunctionInput((3, 3, 3, 1)),
  2628. forward_input=FunctionInput(make_input((1, 1, 3, 3))),
  2629. reference_fn=lambda m, p, i: padding2d_circular_ref(i, m.padding),
  2630. ),
  2631. ]
  2632. def module_inputs_torch_nn_CircularPad3d(module_info, device, dtype, requires_grad, training, **kwargs):
  2633. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2634. def padding3d_circular_ref(inp, pad):
  2635. r"""input:
  2636. [[[[[ 0., 1., 2.],
  2637. [ 3., 4., 5.]],
  2638. [[ 6., 7., 8.],
  2639. [ 9., 10., 11.]]]]]
  2640. pad: (1, 2, 2, 1, 1, 2)
  2641. output: [[[[[ 8., 6., 7., 8., 6., 7.],
  2642. [11., 9., 10., 11., 9., 10.],
  2643. [ 8., 6., 7., 8., 6., 7.],
  2644. [11., 9., 10., 11., 9., 10.],
  2645. [ 8., 6., 7., 8., 6., 7.]],
  2646. [[ 2., 0., 1., 2., 0., 1.],
  2647. [ 5., 3., 4., 5., 3., 4.],
  2648. [ 2., 0., 1., 2., 0., 1.],
  2649. [ 5., 3., 4., 5., 3., 4.],
  2650. [ 2., 0., 1., 2., 0., 1.]],
  2651. [[ 8., 6., 7., 8., 6., 7.],
  2652. [11., 9., 10., 11., 9., 10.],
  2653. [ 8., 6., 7., 8., 6., 7.],
  2654. [11., 9., 10., 11., 9., 10.],
  2655. [ 8., 6., 7., 8., 6., 7.]],
  2656. [[ 2., 0., 1., 2., 0., 1.],
  2657. [ 5., 3., 4., 5., 3., 4.],
  2658. [ 2., 0., 1., 2., 0., 1.],
  2659. [ 5., 3., 4., 5., 3., 4.],
  2660. [ 2., 0., 1., 2., 0., 1.]],
  2661. [[ 8., 6., 7., 8., 6., 7.],
  2662. [11., 9., 10., 11., 9., 10.],
  2663. [ 8., 6., 7., 8., 6., 7.],
  2664. [11., 9., 10., 11., 9., 10.],
  2665. [ 8., 6., 7., 8., 6., 7.]]]]]
  2666. """
  2667. inp = torch.cat([inp[:, :, -pad[4]:], inp, inp[:, :, :pad[5]]], dim=2)
  2668. inp = torch.cat([inp[:, :, :, -pad[2]:], inp, inp[:, :, :, :pad[3]]], dim=3)
  2669. return torch.cat([inp[:, :, :, :, -pad[0]:], inp, inp[:, :, :, :, :pad[1]]], dim=4)
  2670. return [
  2671. ModuleInput(
  2672. constructor_input=FunctionInput(1),
  2673. forward_input=FunctionInput(make_input((3, 4, 5, 6))),
  2674. reference_fn=no_batch_dim_reference_fn,
  2675. ),
  2676. ModuleInput(
  2677. constructor_input=FunctionInput((1, 2, 1, 2, 1, 2)),
  2678. forward_input=FunctionInput(make_input((1, 1, 2, 2, 3))),
  2679. reference_fn=lambda m, p, i: padding3d_circular_ref(i, m.padding)
  2680. ),
  2681. ModuleInput(
  2682. constructor_input=FunctionInput((3, 2, 2, 1, 1, 2)),
  2683. forward_input=FunctionInput(make_input((1, 1, 2, 2, 3))),
  2684. reference_fn=lambda m, p, i: padding3d_circular_ref(i, m.padding)
  2685. ),
  2686. ModuleInput(
  2687. constructor_input=FunctionInput((3, 3, 2, 1, 2, 2)),
  2688. forward_input=FunctionInput(make_input((1, 1, 2, 2, 3))),
  2689. reference_fn=lambda m, p, i: padding3d_circular_ref(i, m.padding)
  2690. ),
  2691. ]
  2692. # All these operators share similar issues on cuDNN and MIOpen
  2693. rnn_gru_lstm_module_info_decorators = (
  2694. # RuntimeError: Batching rule not implemented for aten::_cudnn_rnn_backward.
  2695. # We could not generate a fallback
  2696. DecorateInfo(
  2697. unittest.expectedFailure, "TestModule", "test_grad",
  2698. active_if=(TEST_CUDNN and not TEST_WITH_ROCM), device_type='cuda'
  2699. ),
  2700. # NotImplementedError: the derivative for '_cudnn_rnn_backward' is not implemented.
  2701. # Double backwards is not supported for CuDNN RNNs due to limitations in the CuDNN API
  2702. DecorateInfo(
  2703. unittest.expectedFailure, "TestModule", "test_gradgrad",
  2704. active_if=(TEST_CUDNN and not TEST_WITH_ROCM), device_type='cuda'
  2705. ),
  2706. # CUDNN GRU doesn't accept non-contiguous hx
  2707. DecorateInfo(
  2708. unittest.expectedFailure, "TestModule", "test_non_contiguous_tensors",
  2709. active_if=(TEST_CUDNN and not TEST_WITH_ROCM), device_type='cuda'
  2710. ),
  2711. # MIOPEN GRU doesn't accept non-contiguous hx (this is dispatched to miopen only for float).
  2712. DecorateInfo(
  2713. unittest.expectedFailure, "TestModule", "test_non_contiguous_tensors",
  2714. active_if=(TEST_CUDNN and TEST_WITH_ROCM), dtypes=(torch.float,), device_type='cuda'
  2715. ),
  2716. DecorateInfo(
  2717. skipCUDAVersionIn([(11, 7)]), "TestExpandedWeightModule", "test_module",
  2718. device_type='cuda'
  2719. ),
  2720. DecorateInfo(
  2721. skipCUDAVersionIn([(11, 7)]), "TestDecomp", "test_rnn_decomp_module",
  2722. device_type='cuda'
  2723. )
  2724. )
  2725. # Start of module error inputs functions.
  2726. def module_error_inputs_torch_nn_RNN_GRU_Cell(module_info, device, dtype, requires_grad, training, **kwargs):
  2727. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2728. samples = [
  2729. ErrorModuleInput(
  2730. ModuleInput(
  2731. constructor_input=FunctionInput(10, 20),
  2732. forward_input=FunctionInput(make_input(3, 11), make_input(3, 20)),
  2733. ),
  2734. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2735. error_type=RuntimeError,
  2736. error_regex="input has inconsistent input_size: got 11 expected 10"
  2737. ),
  2738. ErrorModuleInput(
  2739. ModuleInput(
  2740. constructor_input=FunctionInput(10, 20),
  2741. forward_input=FunctionInput(make_input(3, 10), make_input(3, 21)),
  2742. ),
  2743. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2744. error_type=RuntimeError,
  2745. error_regex="hidden0 has inconsistent hidden_size: got 21, expected 20"
  2746. ),
  2747. ErrorModuleInput(
  2748. ModuleInput(
  2749. constructor_input=FunctionInput(10, 20),
  2750. forward_input=FunctionInput(make_input(3, 10), make_input(5, 20)),
  2751. ),
  2752. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2753. error_type=RuntimeError,
  2754. error_regex="Input batch size 3 doesn't match hidden0 batch size 5"
  2755. ),
  2756. ErrorModuleInput(
  2757. ModuleInput(
  2758. constructor_input=FunctionInput(10, 20),
  2759. forward_input=FunctionInput(make_input(3, 10), make_input(3, 1, 1, 20)),
  2760. ),
  2761. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2762. error_type=ValueError,
  2763. error_regex="Expected hidden to be 1D or 2D, got 4D instead"
  2764. ),
  2765. ErrorModuleInput(
  2766. ModuleInput(
  2767. constructor_input=FunctionInput(10, 20, 'relu'),
  2768. forward_input=FunctionInput(make_input(3, 10), make_input(3, 21)),
  2769. ),
  2770. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2771. error_type=RuntimeError,
  2772. error_regex="hidden0 has inconsistent hidden_size: got 21, expected 20"
  2773. ),
  2774. ErrorModuleInput(
  2775. ModuleInput(
  2776. constructor_input=FunctionInput(10, 20, 'tanh'),
  2777. forward_input=FunctionInput(make_input(3, 10), make_input(3, 21)),
  2778. ),
  2779. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2780. error_type=RuntimeError,
  2781. error_regex="hidden0 has inconsistent hidden_size: got 21, expected 20"
  2782. ),
  2783. ]
  2784. return samples
  2785. def module_error_inputs_torch_nn_LSTMCell(module_info, device, dtype, requires_grad, training, **kwargs):
  2786. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2787. samples = [
  2788. ErrorModuleInput(
  2789. ModuleInput(
  2790. constructor_input=FunctionInput(10, 20),
  2791. forward_input=FunctionInput(make_input(3, 11), (make_input(3, 20), make_input(3, 20))),
  2792. ),
  2793. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2794. error_type=RuntimeError,
  2795. error_regex="input has inconsistent input_size: got 11 expected 10"
  2796. ),
  2797. ErrorModuleInput(
  2798. ModuleInput(
  2799. constructor_input=FunctionInput(10, 20),
  2800. forward_input=FunctionInput(make_input(3, 10), (make_input(3, 21), make_input(3, 21))),
  2801. ),
  2802. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2803. error_type=RuntimeError,
  2804. error_regex="hidden0 has inconsistent hidden_size: got 21, expected 20"
  2805. ),
  2806. ErrorModuleInput(
  2807. ModuleInput(
  2808. constructor_input=FunctionInput(10, 20),
  2809. forward_input=FunctionInput(make_input(3, 10), (make_input(5, 20), make_input(5, 20))),
  2810. ),
  2811. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2812. error_type=RuntimeError,
  2813. error_regex="Input batch size 3 doesn't match hidden0 batch size 5"
  2814. ),
  2815. ErrorModuleInput(
  2816. ModuleInput(
  2817. constructor_input=FunctionInput(10, 20),
  2818. forward_input=FunctionInput(make_input(3, 10), (make_input(3, 1, 1, 20), make_input(3, 1, 1, 20))),
  2819. ),
  2820. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2821. error_type=ValueError,
  2822. error_regex="Expected hx\\[0\\] to be 1D or 2D, got 4D instead"
  2823. ),
  2824. ]
  2825. return samples
  2826. def module_error_inputs_torch_nn_RNN_GRU(module_info, device, dtype, requires_grad, training, **kwargs):
  2827. samples = [
  2828. ErrorModuleInput(
  2829. ModuleInput(constructor_input=FunctionInput(10, 0, 1)),
  2830. error_on=ModuleErrorEnum.CONSTRUCTION_ERROR,
  2831. error_type=ValueError,
  2832. error_regex="hidden_size must be greater than zero"
  2833. ),
  2834. ErrorModuleInput(
  2835. ModuleInput(constructor_input=FunctionInput(10, 10, 0)),
  2836. error_on=ModuleErrorEnum.CONSTRUCTION_ERROR,
  2837. error_type=ValueError,
  2838. error_regex="num_layers must be greater than zero"
  2839. ),
  2840. ]
  2841. return samples
  2842. def module_error_inputs_torch_nn_Pad1d(module_info, device, dtype, requires_grad, training, **kwargs):
  2843. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2844. is_constant = kwargs.get('is_constant', False)
  2845. return [
  2846. ErrorModuleInput(
  2847. ModuleInput(
  2848. constructor_input=FunctionInput(1, 3) if is_constant else FunctionInput(3),
  2849. forward_input=FunctionInput(make_input((2, 3, 4, 5))),
  2850. ),
  2851. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2852. error_type=ValueError,
  2853. error_regex=r"expected 2D or 3D input \(got 4D input\)",
  2854. ),
  2855. ]
  2856. def module_error_inputs_torch_nn_Pad2d(module_info, device, dtype, requires_grad, training, **kwargs):
  2857. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2858. is_constant = kwargs.get('is_constant', False)
  2859. return [
  2860. ErrorModuleInput(
  2861. ModuleInput(
  2862. constructor_input=FunctionInput(1, 3) if is_constant else FunctionInput(3),
  2863. forward_input=FunctionInput(make_input((2, 3))),
  2864. ),
  2865. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2866. error_type=ValueError,
  2867. error_regex=r"expected 3D or 4D input \(got 2D input\)",
  2868. ),
  2869. ]
  2870. def module_error_inputs_torch_nn_Pad3d(module_info, device, dtype, requires_grad, training, **kwargs):
  2871. make_input = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
  2872. is_constant = kwargs.get('is_constant', False)
  2873. return [
  2874. ErrorModuleInput(
  2875. ModuleInput(
  2876. constructor_input=FunctionInput(1, 3) if is_constant else FunctionInput(3),
  2877. forward_input=FunctionInput(make_input((2, 3))),
  2878. ),
  2879. error_on=ModuleErrorEnum.FORWARD_ERROR,
  2880. error_type=ValueError,
  2881. error_regex=r"expected 4D or 5D input \(got 2D input\)",
  2882. ),
  2883. ]
  2884. # Database of ModuleInfo entries in alphabetical order.
  2885. module_db: List[ModuleInfo] = [
  2886. ModuleInfo(torch.nn.AdaptiveAvgPool1d,
  2887. module_inputs_func=module_inputs_torch_nn_AdaptiveAvgPool1d,
  2888. skips=(
  2889. # Fails on MPS backend if input/output sizes are not divisible
  2890. DecorateInfo(skipMPS),)
  2891. ),
  2892. ModuleInfo(torch.nn.AdaptiveAvgPool2d,
  2893. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  2894. module_inputs_func=module_inputs_torch_nn_AdaptiveAvgPool2d,
  2895. skips=(
  2896. # Fails on MPS backend if input/output sizes are not divisible
  2897. DecorateInfo(skipMPS),
  2898. # Fails on backward check if output size is 1x1
  2899. DecorateInfo(
  2900. unittest.expectedFailure,
  2901. 'TestModule',
  2902. 'test_memory_format',
  2903. active_if=operator.itemgetter('training'),
  2904. ),)
  2905. ),
  2906. ModuleInfo(torch.nn.AdaptiveAvgPool3d,
  2907. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  2908. module_inputs_func=module_inputs_torch_nn_AdaptiveAvgPool3d,
  2909. skips=(
  2910. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  2911. # not supported on MPS backend
  2912. DecorateInfo(skipMPS),)
  2913. ),
  2914. ModuleInfo(torch.nn.AdaptiveMaxPool1d,
  2915. module_inputs_func=module_inputs_torch_nn_AdaptiveMaxPool1d,
  2916. ),
  2917. ModuleInfo(torch.nn.AdaptiveMaxPool2d,
  2918. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  2919. module_inputs_func=module_inputs_torch_nn_AdaptiveMaxPool2d,
  2920. ),
  2921. ModuleInfo(torch.nn.AdaptiveMaxPool3d,
  2922. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  2923. module_inputs_func=module_inputs_torch_nn_AdaptiveMaxPool3d,
  2924. skips=(
  2925. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  2926. # not supported on MPS backend
  2927. DecorateInfo(skipMPS),)
  2928. ),
  2929. ModuleInfo(torch.nn.AvgPool1d,
  2930. module_inputs_func=module_inputs_torch_nn_AvgPool1d,
  2931. ),
  2932. ModuleInfo(torch.nn.AvgPool2d,
  2933. module_inputs_func=module_inputs_torch_nn_AvgPool2d,
  2934. skips=(
  2935. # The difference between channels last backward and
  2936. # channels first backward of AvgPool2d on CUDA is too large
  2937. # See https://github.com/pytorch/pytorch/issues/107201
  2938. DecorateInfo(
  2939. unittest.expectedFailure,
  2940. 'TestModule',
  2941. 'test_memory_format',
  2942. active_if=operator.itemgetter('training'),
  2943. device_type='cuda',
  2944. ),
  2945. # error: input types 'tensor<f32>' and 'tensor<15x10xf16>' are not broadcast compatible
  2946. DecorateInfo(skipIfMps, 'TestModule', dtypes=[torch.float16]),),
  2947. ),
  2948. ModuleInfo(torch.nn.AvgPool3d,
  2949. module_inputs_func=module_inputs_torch_nn_AvgPool3d,
  2950. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  2951. skips=(
  2952. # No channels_last support for AvgPool1d as it does not take 4D inputs
  2953. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  2954. # not supported on MPS backend
  2955. DecorateInfo(skipMPS),)
  2956. ),
  2957. ModuleInfo(torch.nn.BatchNorm1d,
  2958. train_and_eval_differ=True,
  2959. module_inputs_func=module_inputs_torch_nn_BatchNorm1d,
  2960. skips=(
  2961. # test fails on MPS backend and is being investigated.
  2962. # See https://github.com/pytorch/pytorch/issues/100914
  2963. DecorateInfo(skipMPS),
  2964. # tracking here rather than in the list in test_aotdispatch.py as eval mode passes
  2965. # RuntimeError: tried to get Double out of SymInt
  2966. DecorateInfo(
  2967. unittest.expectedFailure, 'TestEagerFusionModuleInfo',
  2968. 'test_aot_autograd_symbolic_module_exhaustive',
  2969. active_if=operator.itemgetter('training')
  2970. ),
  2971. # torch._subclasses.fake_tensor.DataDependentOutputException: aten._local_scalar_dense.default
  2972. DecorateInfo(
  2973. unittest.expectedFailure, 'TestEagerFusionModuleInfo',
  2974. 'test_aot_autograd_module_exhaustive',
  2975. active_if=operator.itemgetter('training')
  2976. ))
  2977. ),
  2978. ModuleInfo(torch.nn.BatchNorm2d,
  2979. train_and_eval_differ=True,
  2980. module_inputs_func=module_inputs_torch_nn_BatchNorm2d,
  2981. skips=(
  2982. # test fails on MPS backend and is being investigated.
  2983. # See https://github.com/pytorch/pytorch/issues/100914
  2984. DecorateInfo(skipMPS),
  2985. # tracking here rather than in the list in test_aotdispatch.py as eval mode passes
  2986. # RuntimeError: tried to get Double out of SymInt
  2987. DecorateInfo(
  2988. unittest.expectedFailure, 'TestEagerFusionModuleInfo',
  2989. 'test_aot_autograd_symbolic_module_exhaustive',
  2990. active_if=operator.itemgetter('training')
  2991. ),
  2992. # torch._subclasses.fake_tensor.DataDependentOutputException: aten._local_scalar_dense.default
  2993. DecorateInfo(
  2994. unittest.expectedFailure, 'TestEagerFusionModuleInfo',
  2995. 'test_aot_autograd_module_exhaustive',
  2996. active_if=operator.itemgetter('training')
  2997. ),)
  2998. ),
  2999. ModuleInfo(torch.nn.BatchNorm3d,
  3000. train_and_eval_differ=True,
  3001. module_inputs_func=module_inputs_torch_nn_BatchNorm3d,
  3002. skips=(
  3003. # not supported on MPS backend
  3004. DecorateInfo(skipMPS),
  3005. # tracking here rather than in the list in test_aotdispatch.py as eval mode passes
  3006. # RuntimeError: tried to get Double out of SymInt
  3007. DecorateInfo(
  3008. unittest.expectedFailure, 'TestEagerFusionModuleInfo',
  3009. 'test_aot_autograd_symbolic_module_exhaustive',
  3010. active_if=operator.itemgetter('training')
  3011. ),
  3012. # torch._subclasses.fake_tensor.DataDependentOutputException: aten._local_scalar_dense.default
  3013. DecorateInfo(
  3014. unittest.expectedFailure, 'TestEagerFusionModuleInfo',
  3015. 'test_aot_autograd_module_exhaustive',
  3016. active_if=operator.itemgetter('training')
  3017. ),)
  3018. ),
  3019. ModuleInfo(torch.nn.CELU,
  3020. module_inputs_func=module_inputs_torch_nn_CELU,
  3021. # not MPS specific, will be xfailed for all devices in next PR
  3022. skips=(
  3023. DecorateInfo(unittest.expectedFailure, 'TestModule', 'test_check_inplace',
  3024. device_type='mps', dtypes=[torch.float16]),)
  3025. ),
  3026. ModuleInfo(torch.nn.Conv1d,
  3027. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=1, lazy=False),
  3028. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3029. module_memformat_affects_out=True,
  3030. skips=(
  3031. # channels_last support on cuda requires cudnn >= 7603
  3032. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=7603), 'TestModule', 'test_memory_format'),
  3033. # Failure on ROCM for float32 issue #70125
  3034. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3035. # See #119108: MPSNDArrayConvolutionA14.mm:3976: failed assertion `destination datatype must be fp32'
  3036. # xfail does not work due to Fatal Python error: Aborted
  3037. DecorateInfo(skipIfMps, "TestModule", "test_memory_format",
  3038. device_type='mps', dtypes=[torch.float16]),
  3039. DecorateInfo(skipIfMps, "TestModule", "test_non_contiguous_tensors",
  3040. device_type='mps', dtypes=[torch.float16]),
  3041. ),
  3042. decorators=(
  3043. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3044. )),
  3045. ModuleInfo(torch.nn.Conv2d,
  3046. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=2, lazy=False),
  3047. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3048. module_memformat_affects_out=True,
  3049. skips=(
  3050. # channels_last support on cuda requires cudnn >= 7603
  3051. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=7603), 'TestModule', 'test_memory_format'),
  3052. # Failure on ROCM for float32 issue #70125
  3053. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3054. # This was wrongly being skipped before and needs investigation.
  3055. # See https://github.com/pytorch/pytorch/issues/80247
  3056. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format",
  3057. device_type='cuda', dtypes=[torch.float64]),
  3058. # Fails with channels last test on MPS backend
  3059. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format",
  3060. device_type='mps', dtypes=[torch.float32]),
  3061. # See #119108: MPSNDArrayConvolutionA14.mm:3976: failed assertion `destination datatype must be fp32'
  3062. # xfail does not work due to Fatal Python error: Aborted
  3063. DecorateInfo(skipIfMps, "TestModule", "test_memory_format",
  3064. device_type='mps', dtypes=[torch.float16]),
  3065. DecorateInfo(skipIfMps, "TestModule", "test_non_contiguous_tensors",
  3066. device_type='mps', dtypes=[torch.float16]),
  3067. ),
  3068. decorators=(
  3069. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3070. )),
  3071. ModuleInfo(torch.nn.Conv3d,
  3072. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=3, lazy=False),
  3073. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3074. module_memformat_affects_out=True,
  3075. skips=(
  3076. # channels_last support on cuda requires cudnn >= 8005
  3077. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=8005), 'TestModule', 'test_memory_format'),
  3078. # Failure on ROCM for float32 issue #70125
  3079. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3080. # Conv3d is not supported on MPS backend
  3081. DecorateInfo(skipMPS),
  3082. # This was wrongly being skipped before and needs investigation.
  3083. # See https://github.com/pytorch/pytorch/issues/80247
  3084. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format"),
  3085. ),
  3086. decorators=(
  3087. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3088. )),
  3089. ModuleInfo(torch.nn.ConvTranspose1d,
  3090. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=1, lazy=False, transposed=True),
  3091. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3092. module_memformat_affects_out=True,
  3093. dtypes=floating_and_complex_types_and(torch.chalf),
  3094. skips=(
  3095. # channels_last support on cuda requires cudnn >= 7603
  3096. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=7603), 'TestModule', 'test_memory_format'),
  3097. # Failure on ROCM for float32 issue #70125
  3098. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3099. # Not implmented for chalf on CPU
  3100. DecorateInfo(unittest.expectedFailure, 'TestModule', 'test_cpu_gpu_parity',
  3101. dtypes=(torch.chalf,), device_type='cuda'),
  3102. # See #119108: MPSNDArrayConvolutionA14.mm:3976: failed assertion `destination datatype must be fp32'
  3103. # xfail does not work due to Fatal Python error: Aborted
  3104. DecorateInfo(skipIfMps, "TestModule", "test_memory_format",
  3105. device_type='mps', dtypes=[torch.float16]),
  3106. DecorateInfo(skipIfMps, "TestModule", "test_non_contiguous_tensors",
  3107. device_type='mps', dtypes=[torch.float16]),),
  3108. decorators=(
  3109. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3110. DecorateInfo(precisionOverride({torch.chalf: 5e-03}), 'TestModule', 'test_memory_format'),
  3111. )),
  3112. ModuleInfo(torch.nn.ConvTranspose2d,
  3113. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=2, lazy=False, transposed=True),
  3114. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3115. module_memformat_affects_out=True,
  3116. dtypes=floating_and_complex_types_and(torch.chalf),
  3117. skips=(
  3118. # channels_last support on cuda requires cudnn >= 7603
  3119. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=7603), 'TestModule', 'test_memory_format'),
  3120. # Failure on ROCM for float32 issue #70125
  3121. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3122. # Fails on backward check because ViewAsRealBackward apply contiguous for grad
  3123. DecorateInfo(unittest.expectedFailure, 'TestModule', 'test_memory_format',
  3124. dtypes=(torch.complex32, torch.complex64, torch.complex128)),
  3125. # This was wrongly being skipped before and needs investigation.
  3126. # See https://github.com/pytorch/pytorch/issues/80247
  3127. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format", device_type='cuda',
  3128. dtypes=[torch.float64, torch.complex128]),
  3129. # Fails with channels last test on MPS backend
  3130. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format",
  3131. device_type='mps', dtypes=[torch.float32]),
  3132. # Not implemented for chalf on CPU
  3133. DecorateInfo(unittest.expectedFailure, 'TestModule', 'test_cpu_gpu_parity',
  3134. dtypes=(torch.chalf,), device_type='cuda'),
  3135. # See #119108: MPSNDArrayConvolutionA14.mm:3976: failed assertion `destination datatype must be fp32'
  3136. # xfail does not work due to Fatal Python error: Aborted
  3137. DecorateInfo(skipIfMps, "TestModule", "test_memory_format",
  3138. device_type='mps', dtypes=[torch.float16]),
  3139. DecorateInfo(skipIfMps, "TestModule", "test_non_contiguous_tensors",
  3140. device_type='mps', dtypes=[torch.float16]),
  3141. ),
  3142. decorators=(
  3143. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3144. DecorateInfo(precisionOverride({torch.chalf: 5e-03}), 'TestModule', 'test_memory_format'),
  3145. )),
  3146. ModuleInfo(torch.nn.ConvTranspose3d,
  3147. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=3, lazy=False, transposed=True),
  3148. dtypes=floating_and_complex_types_and(torch.chalf),
  3149. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3150. module_memformat_affects_out=True,
  3151. skips=(
  3152. # channels_last support on cuda requires cudnn >= 8005
  3153. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=8005), 'TestModule', 'test_memory_format'),
  3154. # Failure on ROCM for float32 issue #70125
  3155. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3156. # ConvTranspose3d is not supported on MPS backend
  3157. DecorateInfo(skipMPS),
  3158. # This was wrongly being skipped before and needs investigation.
  3159. # See https://github.com/pytorch/pytorch/issues/80247
  3160. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format"),
  3161. # These fail only on ROCm
  3162. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format", device_type='cuda',
  3163. dtypes=[torch.complex32, torch.complex64], active_if=TEST_WITH_ROCM),
  3164. # Not implmented for chalf on CPU
  3165. DecorateInfo(unittest.expectedFailure, 'TestModule', 'test_cpu_gpu_parity',
  3166. dtypes=(torch.chalf,), device_type='cuda'),
  3167. ),
  3168. decorators=(
  3169. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3170. DecorateInfo(precisionOverride({torch.complex64: 1e-04}), 'TestModule', 'test_cpu_gpu_parity'),
  3171. DecorateInfo(precisionOverride({torch.chalf: 5e-03}), 'TestModule', 'test_memory_format'),
  3172. )),
  3173. ModuleInfo(torch.nn.CosineEmbeddingLoss,
  3174. module_inputs_func=module_inputs_torch_nn_CosineEmbeddingLoss,
  3175. skips=(
  3176. # No channels_last support for loss functions.
  3177. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3178. ),
  3179. ModuleInfo(torch.nn.ELU,
  3180. module_inputs_func=module_inputs_torch_nn_ELU,
  3181. # not MPS specific, will be xfailed for all devices in next PR
  3182. skips=(
  3183. DecorateInfo(unittest.expectedFailure, 'TestModule', 'test_check_inplace',
  3184. device_type='mps', dtypes=[torch.float16]),)
  3185. ),
  3186. ModuleInfo(torch.nn.FractionalMaxPool2d,
  3187. module_inputs_func=module_inputs_torch_nn_FractionalMaxPool2d,
  3188. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3189. skips=(
  3190. # not supported on MPS backend
  3191. DecorateInfo(skipMPS),
  3192. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3193. ),
  3194. ModuleInfo(torch.nn.FractionalMaxPool3d,
  3195. module_inputs_func=module_inputs_torch_nn_FractionalMaxPool3d,
  3196. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3197. skips=(
  3198. # not supported on MPS backend
  3199. DecorateInfo(skipMPS),
  3200. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3201. ),
  3202. ModuleInfo(torch.nn.L1Loss,
  3203. module_inputs_func=module_inputs_torch_nn_L1Loss,
  3204. skips=(
  3205. # No channels_last support for loss functions.
  3206. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3207. ),
  3208. ModuleInfo(torch.nn.SmoothL1Loss,
  3209. module_inputs_func=module_inputs_torch_nn_SmoothL1Loss,
  3210. skips=(
  3211. # No channels_last support for loss functions.
  3212. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3213. # See #119108: input types 'tensor<f32>' and 'tensor<15x10xf16>' are not broadcast compatible
  3214. DecorateInfo(skipIfMps, 'TestModule', 'test_non_contiguous_tensors', dtypes=[torch.float16]),)
  3215. ),
  3216. ModuleInfo(torch.nn.LazyConv1d,
  3217. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=1, lazy=True),
  3218. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3219. module_memformat_affects_out=True,
  3220. skips=(
  3221. # channels_last support on cuda requires cudnn >= 7603
  3222. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=7603), 'TestModule', 'test_memory_format'),
  3223. # Failure on ROCM for float32 issue #70125
  3224. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3225. # Lazy modules don't currently play well with ModuleInfo tests on the meta device.
  3226. # See https://github.com/pytorch/pytorch/issues/70505 for more info.
  3227. DecorateInfo(skipMeta),
  3228. # See #119108: MPSNDArrayConvolutionA14.mm:3976: failed assertion `destination datatype must be fp32'
  3229. # xfail does not work due to Fatal Python error: Aborted
  3230. DecorateInfo(skipIfMps, "TestModule", "test_memory_format",
  3231. device_type='mps', dtypes=[torch.float16]),
  3232. DecorateInfo(skipIfMps, "TestModule", "test_non_contiguous_tensors",
  3233. device_type='mps', dtypes=[torch.float16]),
  3234. ),
  3235. decorators=(
  3236. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3237. )),
  3238. ModuleInfo(torch.nn.LazyConv2d,
  3239. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=2, lazy=True),
  3240. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3241. module_memformat_affects_out=True,
  3242. skips=(
  3243. # channels_last support on cuda requires cudnn >= 7603
  3244. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=7603), 'TestModule', 'test_memory_format'),
  3245. # Failure on ROCM for float32 issue #70125
  3246. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3247. # Lazy modules don't currently play well with ModuleInfo tests on the meta device.
  3248. # See https://github.com/pytorch/pytorch/issues/70505 for more info.
  3249. DecorateInfo(skipMeta),
  3250. # This was wrongly being skipped before and needs investigation.
  3251. # See https://github.com/pytorch/pytorch/issues/80247
  3252. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format",
  3253. device_type='cuda', dtypes=[torch.float64]),
  3254. # Fails with channels last test on MPS backend
  3255. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format",
  3256. device_type='mps', dtypes=[torch.float32]),
  3257. # See #119108: MPSNDArrayConvolutionA14.mm:3976: failed assertion `destination datatype must be fp32'
  3258. # xfail does not work due to Fatal Python error: Aborted
  3259. DecorateInfo(skipIfMps, "TestModule", "test_memory_format",
  3260. device_type='mps', dtypes=[torch.float16]),
  3261. DecorateInfo(skipIfMps, "TestModule", "test_non_contiguous_tensors",
  3262. device_type='mps', dtypes=[torch.float16]),
  3263. ),
  3264. decorators=(
  3265. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3266. )),
  3267. ModuleInfo(torch.nn.LazyConv3d,
  3268. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=3, lazy=True),
  3269. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3270. module_memformat_affects_out=True,
  3271. skips=(
  3272. # channels_last support on cuda requires cudnn >= 8005
  3273. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=8005), 'TestModule', 'test_memory_format'),
  3274. # Failure on ROCM for float32 issue #70125
  3275. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3276. # Lazy modules don't currently play well with ModuleInfo tests on the meta device.
  3277. # See https://github.com/pytorch/pytorch/issues/70505 for more info.
  3278. DecorateInfo(skipMeta),
  3279. # LazyConv3d is not supported on MPS backend
  3280. DecorateInfo(skipMPS),
  3281. # This was wrongly being skipped before and needs investigation.
  3282. # See https://github.com/pytorch/pytorch/issues/80247
  3283. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format"),
  3284. ),
  3285. decorators=(
  3286. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3287. )),
  3288. ModuleInfo(torch.nn.LazyConvTranspose1d,
  3289. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=1, lazy=True, transposed=True),
  3290. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3291. module_memformat_affects_out=True,
  3292. skips=(
  3293. # channels_last support on cuda requires cudnn >= 7603
  3294. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=7603), 'TestModule', 'test_memory_format'),
  3295. # Failure on ROCM for float32 issue #70125
  3296. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3297. # Lazy modules don't currently play well with ModuleInfo tests on the meta device.
  3298. # See https://github.com/pytorch/pytorch/issues/70505 for more info.
  3299. DecorateInfo(skipMeta),
  3300. # See #119108: MPSNDArrayConvolutionA14.mm:3976: failed assertion `destination datatype must be fp32'
  3301. # xfail does not work due to Fatal Python error: Aborted
  3302. DecorateInfo(skipIfMps, "TestModule", "test_memory_format",
  3303. device_type='mps', dtypes=[torch.float16]),
  3304. DecorateInfo(skipIfMps, "TestModule", "test_non_contiguous_tensors",
  3305. device_type='mps', dtypes=[torch.float16]),
  3306. ),
  3307. decorators=(
  3308. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3309. )),
  3310. ModuleInfo(torch.nn.LazyConvTranspose2d,
  3311. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=2, lazy=True, transposed=True),
  3312. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3313. module_memformat_affects_out=True,
  3314. skips=(
  3315. # channels_last support on cuda requires cudnn >= 7603
  3316. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=7603), 'TestModule', 'test_memory_format'),
  3317. # Failure on ROCM for float32 issue #70125
  3318. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3319. # Lazy modules don't currently play well with ModuleInfo tests on the meta device.
  3320. # See https://github.com/pytorch/pytorch/issues/70505 for more info.
  3321. DecorateInfo(skipMeta),
  3322. # This was wrongly being skipped before and needs investigation.
  3323. # See https://github.com/pytorch/pytorch/issues/80247
  3324. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format", device_type='cuda',
  3325. dtypes=[torch.float64]),
  3326. # Fails with channels last test on MPS backend
  3327. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format",
  3328. device_type='mps', dtypes=[torch.float32]),
  3329. # See #119108: MPSNDArrayConvolutionA14.mm:3976: failed assertion `destination datatype must be fp32'
  3330. # xfail does not work due to Fatal Python error: Aborted
  3331. DecorateInfo(skipIfMps, "TestModule", "test_memory_format",
  3332. device_type='mps', dtypes=[torch.float16]),
  3333. DecorateInfo(skipIfMps, "TestModule", "test_non_contiguous_tensors",
  3334. device_type='mps', dtypes=[torch.float16]),
  3335. ),
  3336. decorators=(
  3337. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3338. )),
  3339. ModuleInfo(torch.nn.LazyConvTranspose3d,
  3340. module_inputs_func=partial(module_inputs_torch_nn_ConvNd, N=3, lazy=True, transposed=True),
  3341. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3342. module_memformat_affects_out=True,
  3343. skips=(
  3344. # channels_last support on cuda requires cudnn >= 8005
  3345. DecorateInfo(skipCUDAIfCudnnVersionLessThan(version=8005), 'TestModule', 'test_memory_format'),
  3346. # Failure on ROCM for float32 issue #70125
  3347. DecorateInfo(skipCUDAIfRocm, 'TestModule', 'test_memory_format', dtypes=[torch.float32]),
  3348. # Lazy modules don't currently play well with ModuleInfo tests on the meta device.
  3349. # See https://github.com/pytorch/pytorch/issues/70505 for more info.
  3350. DecorateInfo(skipMeta),
  3351. # LazyConvTranspose3d is not supported on MPS backend
  3352. DecorateInfo(skipMPS),
  3353. # This was wrongly being skipped before and needs investigation.
  3354. # See https://github.com/pytorch/pytorch/issues/80247
  3355. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format"),
  3356. ),
  3357. decorators=(
  3358. DecorateInfo(precisionOverride({torch.float32: 1e-04}), 'TestModule', 'test_memory_format'),
  3359. )),
  3360. ModuleInfo(torch.nn.Linear,
  3361. module_inputs_func=module_inputs_torch_nn_Linear,
  3362. skips=(
  3363. # No channels_last support for Linear currently.
  3364. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3365. ),
  3366. ModuleInfo(torch.nn.Bilinear,
  3367. module_inputs_func=module_inputs_torch_nn_Bilinear,
  3368. decorators=[
  3369. DecorateInfo(
  3370. toleranceOverride({
  3371. torch.float32: tol(atol=1e-4, rtol=1e-4),
  3372. torch.float64: tol(atol=1e-4, rtol=1e-4)}),
  3373. 'TestModule', 'test_forward', device_type='cpu'),
  3374. ],
  3375. skips=(
  3376. # No channels_last support for Bilinear currently.
  3377. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3378. # See #119108: tolerance issue
  3379. DecorateInfo(unittest.expectedFailure, "TestModule", "test_forward",
  3380. device_type='mps', dtypes=[torch.float16]),)
  3381. ),
  3382. ModuleInfo(torch.nn.LPPool1d,
  3383. module_inputs_func=module_inputs_torch_nn_LPPool1d,
  3384. skips=(
  3385. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_grad'),
  3386. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_gradgrad'),)
  3387. ),
  3388. ModuleInfo(torch.nn.LPPool2d,
  3389. module_inputs_func=module_inputs_torch_nn_LPPool2d,
  3390. skips=(
  3391. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_grad'),
  3392. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_gradgrad'),
  3393. # Fails on backward check on MPS
  3394. # See https://github.com/pytorch/pytorch/issues/107214
  3395. DecorateInfo(
  3396. unittest.expectedFailure,
  3397. 'TestModule',
  3398. 'test_memory_format',
  3399. active_if=operator.itemgetter('training'),
  3400. device_type='mps',
  3401. ),)
  3402. ),
  3403. ModuleInfo(torch.nn.LPPool3d,
  3404. module_inputs_func=module_inputs_torch_nn_LPPool3d,
  3405. skips=(
  3406. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_grad'),
  3407. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_gradgrad'),
  3408. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3409. DecorateInfo(skipIfMps),)
  3410. ),
  3411. ModuleInfo(torch.nn.MaxPool1d,
  3412. module_inputs_func=module_inputs_torch_nn_MaxPool1d,
  3413. ),
  3414. ModuleInfo(torch.nn.MaxPool2d,
  3415. module_inputs_func=module_inputs_torch_nn_MaxPool2d,
  3416. ),
  3417. ModuleInfo(torch.nn.MaxPool3d,
  3418. module_inputs_func=module_inputs_torch_nn_MaxPool3d,
  3419. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3420. skips=(
  3421. # not supported on MPS backend
  3422. DecorateInfo(skipMPS),)
  3423. ),
  3424. ModuleInfo(torch.nn.KLDivLoss,
  3425. module_inputs_func=module_inputs_torch_nn_KLDivLoss,
  3426. skips=(
  3427. # No channels_last support for loss functions.
  3428. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3429. # https://github.com/pytorch/pytorch/issues/115588
  3430. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_cpu_gpu_parity'),
  3431. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_grad'),
  3432. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_gradgrad'),)
  3433. ),
  3434. ModuleInfo(torch.nn.MSELoss,
  3435. module_inputs_func=module_inputs_torch_nn_MSELoss,
  3436. skips=(
  3437. # No channels_last support for loss functions.
  3438. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3439. # See #119108: input types 'tensor<f32>' and 'tensor<15x10xf16>' are not broadcast compatible
  3440. DecorateInfo(skipIfMps, 'TestModule', 'test_non_contiguous_tensors', dtypes=[torch.float16]),
  3441. # See #119108: tolerance issue
  3442. DecorateInfo(unittest.expectedFailure, "TestModule", "test_forward",
  3443. device_type='mps', dtypes=[torch.float16]),)
  3444. ),
  3445. ModuleInfo(torch.nn.MarginRankingLoss,
  3446. module_inputs_func=module_inputs_torch_nn_MarginRankingLoss,
  3447. skips=(
  3448. # No channels_last support for loss functions.
  3449. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3450. ),
  3451. ModuleInfo(torch.nn.MultiLabelMarginLoss,
  3452. module_inputs_func=module_inputs_torch_nn_MultiLabelMarginLoss,
  3453. skips=(
  3454. # No channels_last support for loss functions.
  3455. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3456. # 'aten::multilabel_margin_loss_forward' is not currently implemented for the MPS device.
  3457. DecorateInfo(skipIfMps, 'TestModule'),
  3458. # derivative for aten::multilabel_margin_loss_backward is not implemented
  3459. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_gradgrad'),)
  3460. ),
  3461. ModuleInfo(torch.nn.MultiMarginLoss,
  3462. module_inputs_func=module_inputs_torch_nn_MultiMarginLoss,
  3463. skips=(
  3464. # No channels_last support for loss functions.
  3465. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3466. # 'aten::multi_margin_loss' is not currently implemented for the MPS device.
  3467. DecorateInfo(skipIfMps, 'TestModule'),
  3468. # RuntimeError: derivative for aten::multi_margin_loss_backward is not implemented
  3469. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_gradgrad'),)
  3470. ),
  3471. ModuleInfo(torch.nn.SoftMarginLoss,
  3472. module_inputs_func=module_inputs_torch_nn_SoftMarginLoss,
  3473. skips=(
  3474. # No channels_last support for loss functions.
  3475. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3476. # See #119108: tolerance issue
  3477. DecorateInfo(unittest.expectedFailure, "TestModule", "test_forward",
  3478. device_type='mps', dtypes=[torch.float16]),)
  3479. ),
  3480. ModuleInfo(torch.nn.MultiLabelSoftMarginLoss,
  3481. module_inputs_func=module_inputs_torch_nn_MultiLabelSoftMarginLoss,
  3482. skips=(
  3483. # No channels_last support for loss functions.
  3484. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3485. ),
  3486. ModuleInfo(torch.nn.NLLLoss,
  3487. module_inputs_func=module_inputs_torch_nn_NLLLoss,
  3488. skips=(
  3489. # No channels_last support for loss functions.
  3490. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3491. # See #119108: tolerance issue
  3492. DecorateInfo(unittest.expectedFailure, "TestModule", "test_forward",
  3493. device_type='mps', dtypes=[torch.float16]),)
  3494. ),
  3495. ModuleInfo(torch.nn.GaussianNLLLoss,
  3496. module_inputs_func=module_inputs_torch_nn_GaussianNLLLoss,
  3497. skips=(
  3498. # No channels_last support for loss functions.
  3499. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)),
  3500. ModuleInfo(torch.nn.PoissonNLLLoss,
  3501. module_inputs_func=module_inputs_torch_nn_PoissonNLLLoss,
  3502. skips=(
  3503. # No channels_last support for loss functions.
  3504. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)),
  3505. ModuleInfo(torch.nn.HingeEmbeddingLoss,
  3506. module_inputs_func=module_inputs_torch_nn_HingeEmbeddingLoss,
  3507. skips=(
  3508. # No channels_last support for loss functions.
  3509. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3510. ),
  3511. ModuleInfo(torch.nn.HuberLoss,
  3512. module_inputs_func=module_inputs_torch_nn_HuberLoss,
  3513. skips=(
  3514. # No channels_last support for loss functions.
  3515. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3516. # See #119108: seemingly incorrect output dtype
  3517. DecorateInfo(unittest.expectedFailure, "TestModule", "test_forward",
  3518. device_type='mps', dtypes=[torch.float16]),)
  3519. ),
  3520. ModuleInfo(torch.nn.BCELoss,
  3521. module_inputs_func=module_inputs_torch_nn_BCELoss,
  3522. skips=(
  3523. # No channels_last support for loss functions.
  3524. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3525. # error: input types 'tensor<f32>' and 'tensor<15x10xf16>' are not broadcast compatible
  3526. DecorateInfo(skipIfMps, 'TestModule', dtypes=[torch.float16]),)
  3527. ),
  3528. ModuleInfo(torch.nn.BCEWithLogitsLoss,
  3529. module_inputs_func=module_inputs_torch_nn_BCEWithLogitsLoss,
  3530. skips=(
  3531. # No channels_last support for loss functions.
  3532. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3533. # see #119108: tolerance issue
  3534. DecorateInfo(skipIfMps, 'TestModule', dtypes=[torch.float16]),)
  3535. ),
  3536. ModuleInfo(torch.nn.CrossEntropyLoss,
  3537. module_inputs_func=module_inputs_torch_nn_CrossEntropyLoss,
  3538. dtypes=get_all_fp_dtypes(include_half=True, include_bfloat16=False),
  3539. decorators=(
  3540. # No channels_last support for loss functions.
  3541. DecorateInfo(unittest.expectedFailure, 'TestModule', 'test_memory_format'),
  3542. DecorateInfo(toleranceOverride({torch.float16: tol(atol=3e-2, rtol=1e-3)}), "TestModule",
  3543. "test_forward", dtypes=[torch.float16], device_type='cpu'),
  3544. DecorateInfo(unittest.expectedFailure, "TestModule", "test_cpu_gpu_parity", dtypes=[torch.float16],
  3545. device_type='cuda'),),
  3546. ),
  3547. ModuleInfo(torch.nn.CTCLoss,
  3548. module_inputs_func=module_inputs_torch_nn_CTCLoss,
  3549. skips=(
  3550. # No channels_last support for loss functions.
  3551. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3552. # The operator aten::_ctc_loss is not currently implemented for the MPS device.
  3553. DecorateInfo(skipIfMps, 'TestModule'),
  3554. # derivative for aten::_ctc_loss_backward is not implemented
  3555. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_grad'),
  3556. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_gradgrad'),
  3557. # https://github.com/pytorch/pytorch/issues/115585
  3558. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_non_contiguous_tensors'),)
  3559. ),
  3560. ModuleInfo(torch.nn.GELU,
  3561. module_inputs_func=module_inputs_torch_nn_GELU,
  3562. skips=(
  3563. # See #119108: tolerance issue
  3564. DecorateInfo(unittest.expectedFailure, "TestModule", "test_forward",
  3565. device_type='mps', dtypes=[torch.float16]),)
  3566. ),
  3567. ModuleInfo(torch.nn.GLU,
  3568. module_inputs_func=module_inputs_torch_nn_GLU,
  3569. ),
  3570. ModuleInfo(torch.nn.GroupNorm,
  3571. module_inputs_func=module_inputs_torch_nn_GroupNorm,
  3572. dtypes=get_all_fp_dtypes(include_bfloat16=True, include_half=True),
  3573. skips=(
  3574. # Tracking at https://github.com/pytorch/pytorch/issues/98089
  3575. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_cpu_gpu_parity'),
  3576. DecorateInfo(toleranceOverride({torch.float32: tol(atol=1e-4, rtol=1e-4)}),
  3577. 'TestModule', 'test_memory_format', device_type='cpu'),
  3578. # No channels_last support for GroupNorm currently.
  3579. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format', device_type='cuda'),
  3580. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format', device_type='mps'),
  3581. DecorateInfo(unittest.skip("Skipped!"), "TestModule", "test_grad",
  3582. active_if=TEST_WITH_ROCM, device_type='cuda'),)
  3583. ),
  3584. ModuleInfo(torch.nn.Hardshrink,
  3585. module_inputs_func=module_inputs_torch_nn_Hardshrink,
  3586. skips=(
  3587. # not supported on MPS backend
  3588. DecorateInfo(skipMPS),),
  3589. ),
  3590. ModuleInfo(torch.nn.Hardswish,
  3591. module_inputs_func=module_inputs_torch_nn_Hardswish,
  3592. skips=(
  3593. # Fails on backward check on MPS
  3594. # See https://github.com/pytorch/pytorch/issues/107214
  3595. DecorateInfo(
  3596. unittest.expectedFailure,
  3597. 'TestModule',
  3598. 'test_memory_format',
  3599. active_if=operator.itemgetter('training'),
  3600. device_type='mps',
  3601. ),),
  3602. supports_gradgrad=False),
  3603. ModuleInfo(torch.nn.Hardtanh,
  3604. module_inputs_func=module_inputs_torch_nn_Hardtanh,
  3605. ),
  3606. ModuleInfo(torch.nn.InstanceNorm1d,
  3607. module_inputs_func=partial(module_inputs_torch_nn_InstanceNormNd, N=1),
  3608. train_and_eval_differ=True,
  3609. skips=(
  3610. # No channels_last support for InstanceNorm1d currently.
  3611. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3612. ),
  3613. ModuleInfo(torch.nn.InstanceNorm2d,
  3614. module_inputs_func=partial(module_inputs_torch_nn_InstanceNormNd, N=2),
  3615. train_and_eval_differ=True,
  3616. skips=(
  3617. # No channels_last support for InstanceNorm2d currently.
  3618. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3619. ),
  3620. ModuleInfo(torch.nn.InstanceNorm3d,
  3621. module_inputs_func=partial(module_inputs_torch_nn_InstanceNormNd, N=3),
  3622. train_and_eval_differ=True,
  3623. skips=(
  3624. # not supported on MPS backend
  3625. DecorateInfo(skipMPS),
  3626. # No channels_last support for InstanceNorm3d currently.
  3627. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3628. ),
  3629. ModuleInfo(torch.nn.LocalResponseNorm,
  3630. module_inputs_func=module_inputs_torch_nn_LocalResponseNorm,
  3631. skips=(
  3632. # uses avg_pool3d which is not supported on MPS backend
  3633. DecorateInfo(skipMPS),)
  3634. ),
  3635. ModuleInfo(torch.nn.LayerNorm,
  3636. module_inputs_func=module_inputs_torch_nn_LayerNorm,
  3637. skips=(
  3638. # No channels_last support for LayerNorm currently.
  3639. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3640. ),
  3641. ModuleInfo(torch.nn.RMSNorm,
  3642. module_inputs_func=module_inputs_torch_nn_RMSNorm,
  3643. ),
  3644. # TransformerEncoder takes the same inputs as TransformerEncoderLayer
  3645. ModuleInfo(torch.nn.TransformerEncoder,
  3646. train_and_eval_differ=True,
  3647. module_inputs_func=module_inputs_torch_nn_TransformerEncoder,
  3648. decorators=[
  3649. # Not implemented for SDPA backward derivative
  3650. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_gradgrad',
  3651. device_type='cpu'),
  3652. ],
  3653. skips=(
  3654. # No channels_last support for TransformerEncoderLayer currently.
  3655. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3656. # Doesn't support device / dtype kwargs directly because it is just a
  3657. # container of TransformerEncoderLayers.
  3658. DecorateInfo(unittest.expectedFailure, 'TestModule', 'test_factory_kwargs'),)
  3659. ),
  3660. ModuleInfo(torch.nn.TransformerEncoderLayer,
  3661. train_and_eval_differ=True,
  3662. module_inputs_func=module_inputs_torch_nn_TransformerEncoderLayer,
  3663. decorators=[
  3664. DecorateInfo(toleranceOverride({torch.float32: tol(atol=1e-4, rtol=1e-4)}),
  3665. 'TestModule', 'test_non_contiguous_tensors',
  3666. device_type='cpu', active_if=IS_WINDOWS),
  3667. # Not implemented for SDPA backward derivative
  3668. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_gradgrad',
  3669. device_type='cpu'),
  3670. ],
  3671. skips=(
  3672. # No channels_last support for TransformerEncoderLayer currently.
  3673. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3674. ),
  3675. ModuleInfo(torch.nn.TransformerDecoderLayer,
  3676. module_inputs_func=module_inputs_torch_nn_TransformerDecoderLayer,
  3677. decorators=[
  3678. # Not implemented for SDPA backward derivative
  3679. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_gradgrad',
  3680. device_type='cpu'),
  3681. ],
  3682. skips=(
  3683. # No channels_last support for TransformerDecoderLayer currently.
  3684. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3685. ),
  3686. ModuleInfo(torch.nn.Transformer,
  3687. module_inputs_func=module_inputs_torch_nn_Transformer,
  3688. decorators=[
  3689. # Not implemented for SDPA backward derivative
  3690. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_gradgrad',
  3691. device_type='cpu'),
  3692. ],
  3693. skips=(
  3694. # No channels_last support for Transformer currently.
  3695. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3696. ),
  3697. ModuleInfo(torch.nn.MultiheadAttention,
  3698. train_and_eval_differ=True,
  3699. module_inputs_func=module_inputs_torch_nn_MultiheadAttention,
  3700. skips=(
  3701. # No channels_last support for MultiheadAttention currently.
  3702. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3703. ),
  3704. ModuleInfo(torch.nn.Embedding,
  3705. module_inputs_func=module_inputs_torch_nn_Embedding,
  3706. decorators=[
  3707. DecorateInfo(toleranceOverride({torch.float32: tol(atol=1e-4, rtol=1e-4)}),
  3708. 'TestModule', 'test_non_contiguous_tensors',
  3709. device_type='mps')],
  3710. skips=(
  3711. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3712. ),
  3713. ModuleInfo(torch.nn.ReLU,
  3714. module_inputs_func=module_inputs_torch_nn_ReLU,
  3715. skips=(
  3716. # Fails on backward check on MPS
  3717. # See https://github.com/pytorch/pytorch/issues/107214
  3718. DecorateInfo(
  3719. unittest.expectedFailure,
  3720. 'TestModule',
  3721. 'test_memory_format',
  3722. active_if=operator.itemgetter('training'),
  3723. device_type='mps',
  3724. ),)
  3725. ),
  3726. ModuleInfo(torch.nn.LeakyReLU,
  3727. module_inputs_func=module_inputs_torch_nn_LeakyReLU,
  3728. ),
  3729. ModuleInfo(torch.nn.ReLU6,
  3730. module_inputs_func=module_inputs_torch_nn_ReLU6,
  3731. skips=(
  3732. # test fails on MPS backend and is being investigated.
  3733. # See https://github.com/pytorch/pytorch/issues/100914
  3734. DecorateInfo(skipMPS),)
  3735. ),
  3736. ModuleInfo(torch.nn.PReLU,
  3737. module_inputs_func=module_inputs_torch_nn_PReLU,
  3738. skips=(
  3739. # test fails on MPS backend and is being investigated.
  3740. # See https://github.com/pytorch/pytorch/issues/100914
  3741. DecorateInfo(skipMPS),)
  3742. ),
  3743. ModuleInfo(torch.nn.RNNCell,
  3744. module_inputs_func=partial(module_inputs_torch_nn_RNN_GRU_Cell, is_rnn=True),
  3745. module_error_inputs_func=module_error_inputs_torch_nn_RNN_GRU_Cell,
  3746. ),
  3747. ModuleInfo(torch.nn.GRUCell,
  3748. module_inputs_func=module_inputs_torch_nn_RNN_GRU_Cell,
  3749. module_error_inputs_func=module_error_inputs_torch_nn_RNN_GRU_Cell,
  3750. ),
  3751. ModuleInfo(torch.nn.LSTMCell,
  3752. module_inputs_func=module_inputs_torch_nn_LSTMCell,
  3753. module_error_inputs_func=module_error_inputs_torch_nn_LSTMCell,
  3754. ),
  3755. ModuleInfo(torch.nn.Sigmoid,
  3756. module_inputs_func=module_inputs_torch_nn_Sigmoid,
  3757. skips=(
  3758. # Fails on backward check on MPS
  3759. # See https://github.com/pytorch/pytorch/issues/107214
  3760. DecorateInfo(
  3761. unittest.expectedFailure,
  3762. 'TestModule',
  3763. 'test_memory_format',
  3764. active_if=operator.itemgetter('training'),
  3765. device_type='mps',
  3766. ),)
  3767. ),
  3768. ModuleInfo(torch.nn.LogSigmoid,
  3769. module_inputs_func=module_inputs_torch_nn_LogSigmoid,
  3770. skips=(
  3771. # See #119108: tolerance issue
  3772. DecorateInfo(unittest.expectedFailure, "TestModule", "test_forward", device_type='mps', dtypes=[torch.float16]),)
  3773. ),
  3774. ModuleInfo(torch.nn.SiLU,
  3775. module_inputs_func=module_inputs_torch_nn_SiLU,
  3776. ),
  3777. ModuleInfo(torch.nn.Softmax,
  3778. module_inputs_func=module_inputs_torch_nn_Softmax,
  3779. ),
  3780. ModuleInfo(torch.nn.Softmax2d,
  3781. module_inputs_func=module_inputs_torch_nn_Softmax2d,
  3782. skips=(
  3783. # no channels last support for Softmax2d currently
  3784. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3785. # See #119108: tolerance issue
  3786. DecorateInfo(unittest.expectedFailure, "TestModule", "test_forward", device_type='mps', dtypes=[torch.float16]),)
  3787. ),
  3788. ModuleInfo(torch.nn.LogSoftmax,
  3789. module_inputs_func=module_inputs_torch_nn_LogSoftmax,
  3790. skips=(
  3791. # no channels last support for LogSoftmax currently
  3792. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),
  3793. # See #119108: inf nan error
  3794. DecorateInfo(unittest.expectedFailure, "TestModule", "test_forward", device_type='mps', dtypes=[torch.float16]),)
  3795. ),
  3796. ModuleInfo(torch.nn.Softmin,
  3797. module_inputs_func=module_inputs_torch_nn_Softmin,
  3798. skips=(
  3799. # no channels last support for Softmin currently
  3800. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format'),)
  3801. ),
  3802. ModuleInfo(torch.nn.Softplus,
  3803. module_inputs_func=module_inputs_torch_nn_Softplus,
  3804. skips=(
  3805. # test fails on MPS backend and is being investigated.
  3806. # See https://github.com/pytorch/pytorch/issues/100914
  3807. DecorateInfo(skipMPS),)
  3808. ),
  3809. ModuleInfo(torch.nn.Softshrink,
  3810. module_inputs_func=module_inputs_torch_nn_Softshrink,
  3811. skips=(
  3812. # not supported on MPS backend
  3813. DecorateInfo(skipMPS),)
  3814. ),
  3815. ModuleInfo(torch.nn.Softsign,
  3816. module_inputs_func=module_inputs_torch_nn_Softsign,
  3817. ),
  3818. ModuleInfo(torch.nn.Tanh,
  3819. module_inputs_func=module_inputs_torch_nn_Tanh,
  3820. skips=(
  3821. # Fails on backward check on MPS
  3822. # See https://github.com/pytorch/pytorch/issues/107214
  3823. DecorateInfo(
  3824. unittest.expectedFailure,
  3825. 'TestModule',
  3826. 'test_memory_format',
  3827. active_if=operator.itemgetter('training'),
  3828. device_type='mps',
  3829. ),)
  3830. ),
  3831. ModuleInfo(torch.nn.Tanhshrink,
  3832. module_inputs_func=module_inputs_torch_nn_Tanhshrink,
  3833. skips=(
  3834. # Fails on backward check on MPS
  3835. # See https://github.com/pytorch/pytorch/issues/107214
  3836. DecorateInfo(
  3837. unittest.expectedFailure,
  3838. 'TestModule',
  3839. 'test_memory_format',
  3840. active_if=operator.itemgetter('training'),
  3841. device_type='mps',
  3842. ),)
  3843. ),
  3844. ModuleInfo(torch.nn.Threshold,
  3845. module_inputs_func=module_inputs_torch_nn_Threshold,
  3846. skips=(
  3847. # test fails on MPS backend and is being investigated.
  3848. # See https://github.com/pytorch/pytorch/issues/100914
  3849. DecorateInfo(skipMPS),)
  3850. ),
  3851. ModuleInfo(torch.nn.Mish,
  3852. module_inputs_func=module_inputs_torch_nn_Mish,
  3853. skips=(
  3854. # not supported on MPS backend
  3855. DecorateInfo(skipMPS),)
  3856. ),
  3857. ModuleInfo(torch.nn.RNN,
  3858. train_and_eval_differ=True,
  3859. module_inputs_func=partial(module_inputs_torch_nn_RNN_GRU, is_rnn=True),
  3860. module_error_inputs_func=module_error_inputs_torch_nn_RNN_GRU,
  3861. decorators=rnn_gru_lstm_module_info_decorators
  3862. ),
  3863. ModuleInfo(torch.nn.GRU,
  3864. train_and_eval_differ=True,
  3865. module_inputs_func=partial(module_inputs_torch_nn_RNN_GRU, is_rnn=False),
  3866. module_error_inputs_func=module_error_inputs_torch_nn_RNN_GRU,
  3867. decorators=rnn_gru_lstm_module_info_decorators),
  3868. ModuleInfo(torch.nn.LSTM,
  3869. train_and_eval_differ=True,
  3870. module_inputs_func=module_inputs_torch_nn_LSTM,
  3871. module_error_inputs_func=module_error_inputs_torch_nn_RNN_GRU,
  3872. skips=(
  3873. # LSTM with projections is not currently supported with MPS
  3874. DecorateInfo(skipMPS),),
  3875. decorators=rnn_gru_lstm_module_info_decorators),
  3876. ModuleInfo(torch.nn.ReflectionPad1d,
  3877. module_inputs_func=module_inputs_torch_nn_ReflectionPad1d,
  3878. ),
  3879. ModuleInfo(torch.nn.ReflectionPad2d,
  3880. module_inputs_func=module_inputs_torch_nn_ReflectionPad2d,
  3881. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3882. skips=(
  3883. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format',
  3884. device_type='cuda'),
  3885. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format',
  3886. device_type='mps'),)
  3887. ),
  3888. ModuleInfo(torch.nn.ReflectionPad3d,
  3889. module_inputs_func=module_inputs_torch_nn_ReflectionPad3d,
  3890. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3891. skips=(
  3892. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format',
  3893. device_type='cuda'),
  3894. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format',
  3895. device_type='mps'),)
  3896. ),
  3897. ModuleInfo(torch.nn.ReplicationPad1d,
  3898. module_inputs_func=module_inputs_torch_nn_ReplicationPad1d,
  3899. ),
  3900. ModuleInfo(torch.nn.ReplicationPad2d,
  3901. module_inputs_func=module_inputs_torch_nn_ReplicationPad2d,
  3902. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3903. skips=(
  3904. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format',
  3905. device_type='cuda'),
  3906. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format',
  3907. device_type='mps'),)
  3908. ),
  3909. ModuleInfo(torch.nn.ReplicationPad3d,
  3910. module_inputs_func=module_inputs_torch_nn_ReplicationPad3d,
  3911. gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
  3912. skips=(
  3913. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format',
  3914. device_type='cuda'),
  3915. DecorateInfo(unittest.skip("Skipped!"), 'TestModule', 'test_memory_format',
  3916. device_type='mps'),)
  3917. ),
  3918. ModuleInfo(torch.nn.SELU,
  3919. module_inputs_func=module_inputs_torch_nn_SELU,
  3920. skips=(
  3921. # test fails on MPS backend and is being investigated.
  3922. # See https://github.com/pytorch/pytorch/issues/100914
  3923. DecorateInfo(skipMPS),)
  3924. ),
  3925. ModuleInfo(torch.nn.ZeroPad1d,
  3926. module_inputs_func=module_inputs_torch_nn_ZeroPad1d,
  3927. ),
  3928. ModuleInfo(torch.nn.ZeroPad2d,
  3929. module_inputs_func=module_inputs_torch_nn_ZeroPad2d,
  3930. skips=(
  3931. # Fails with channels last test on MPS backend
  3932. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format", device_type='mps'),)
  3933. ),
  3934. ModuleInfo(torch.nn.ZeroPad3d,
  3935. module_inputs_func=module_inputs_torch_nn_ZeroPad3d,
  3936. skips=(
  3937. # Fails with channels last test on MPS backend
  3938. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format", device_type='mps'),)
  3939. ),
  3940. ModuleInfo(torch.nn.CircularPad1d,
  3941. module_inputs_func=module_inputs_torch_nn_CircularPad1d,
  3942. module_error_inputs_func=module_error_inputs_torch_nn_Pad1d,
  3943. ),
  3944. ModuleInfo(torch.nn.CircularPad2d,
  3945. module_inputs_func=module_inputs_torch_nn_CircularPad2d,
  3946. module_error_inputs_func=module_error_inputs_torch_nn_Pad2d,
  3947. ),
  3948. ModuleInfo(torch.nn.CircularPad3d,
  3949. module_inputs_func=module_inputs_torch_nn_CircularPad3d,
  3950. module_error_inputs_func=module_error_inputs_torch_nn_Pad3d,
  3951. skips=(
  3952. # Fails with channels last test on MPS backend
  3953. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format"),)
  3954. ),
  3955. ModuleInfo(torch.nn.ConstantPad1d,
  3956. module_inputs_func=module_inputs_torch_nn_ConstantPad1d,
  3957. ),
  3958. ModuleInfo(torch.nn.ConstantPad2d,
  3959. module_inputs_func=module_inputs_torch_nn_ConstantPad2d,
  3960. skips=(
  3961. # Fails with channels last test on MPS backend
  3962. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format", device_type='mps'),)
  3963. ),
  3964. ModuleInfo(torch.nn.ConstantPad3d,
  3965. module_inputs_func=module_inputs_torch_nn_ConstantPad3d,
  3966. skips=(
  3967. # Fails with channels last test on MPS backend
  3968. DecorateInfo(unittest.expectedFailure, "TestModule", "test_memory_format", device_type='mps'),)
  3969. )
  3970. ]