You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

session_basic.cc 108 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
adapte to remove inline merge me commit for remove inline deal witch multiple cases of switch in ConstructKernelGraph deal with switch and call cases in ConstructKernelGraph fix bug and rebase master ConstructKernelGraph adapte to remove inline fix InsertMultipleAssignToGraph bug add graph input to new graph which is created for switch input replace CreateNewParameterFromCNode to NewParameter in order to set new parameter's abstract and kernel_info avoids create a new switch repeatedly when the cnode is a call switch without real input null pointer check update frontend code Revert "update frontend code" This reverts commit ce1f600d1e9b4b47d9b81122f981bbbe505dd250. update frontend code PR_2948 fix bug of CheckLabalIndex handle switch_layer in ConstructKernelGraph add attr for assign node to avoid erasing by cse pass cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem rebase master Revert "cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem" This reverts commit 74c258f94260ca0769a1ef69c6ef8e831c301dbf. Revert "handle switch_layer in ConstructKernelGraph" This reverts commit cb5367f02d69facbca8d39e9234c501608aee27f. Revert "update frontend code PR_2948" This reverts commit 234ac583400a96a8ddd641f7a722e1ccd5e056c6. Revert "merge me commit for remove inline" This reverts commit 55c0ebd42b6699c7686f5ce585e745f87dd42280. fix diff after rebase master doing remove inline in me overwrite FindNodePrimitive Revert "doing remove inline in me" This reverts commit b42e893125bc624d323e855ac6ae615333c06e65.
5 years ago
adapte to remove inline merge me commit for remove inline deal witch multiple cases of switch in ConstructKernelGraph deal with switch and call cases in ConstructKernelGraph fix bug and rebase master ConstructKernelGraph adapte to remove inline fix InsertMultipleAssignToGraph bug add graph input to new graph which is created for switch input replace CreateNewParameterFromCNode to NewParameter in order to set new parameter's abstract and kernel_info avoids create a new switch repeatedly when the cnode is a call switch without real input null pointer check update frontend code Revert "update frontend code" This reverts commit ce1f600d1e9b4b47d9b81122f981bbbe505dd250. update frontend code PR_2948 fix bug of CheckLabalIndex handle switch_layer in ConstructKernelGraph add attr for assign node to avoid erasing by cse pass cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem rebase master Revert "cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem" This reverts commit 74c258f94260ca0769a1ef69c6ef8e831c301dbf. Revert "handle switch_layer in ConstructKernelGraph" This reverts commit cb5367f02d69facbca8d39e9234c501608aee27f. Revert "update frontend code PR_2948" This reverts commit 234ac583400a96a8ddd641f7a722e1ccd5e056c6. Revert "merge me commit for remove inline" This reverts commit 55c0ebd42b6699c7686f5ce585e745f87dd42280. fix diff after rebase master doing remove inline in me overwrite FindNodePrimitive Revert "doing remove inline in me" This reverts commit b42e893125bc624d323e855ac6ae615333c06e65.
5 years ago
adapte to remove inline merge me commit for remove inline deal witch multiple cases of switch in ConstructKernelGraph deal with switch and call cases in ConstructKernelGraph fix bug and rebase master ConstructKernelGraph adapte to remove inline fix InsertMultipleAssignToGraph bug add graph input to new graph which is created for switch input replace CreateNewParameterFromCNode to NewParameter in order to set new parameter's abstract and kernel_info avoids create a new switch repeatedly when the cnode is a call switch without real input null pointer check update frontend code Revert "update frontend code" This reverts commit ce1f600d1e9b4b47d9b81122f981bbbe505dd250. update frontend code PR_2948 fix bug of CheckLabalIndex handle switch_layer in ConstructKernelGraph add attr for assign node to avoid erasing by cse pass cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem rebase master Revert "cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem" This reverts commit 74c258f94260ca0769a1ef69c6ef8e831c301dbf. Revert "handle switch_layer in ConstructKernelGraph" This reverts commit cb5367f02d69facbca8d39e9234c501608aee27f. Revert "update frontend code PR_2948" This reverts commit 234ac583400a96a8ddd641f7a722e1ccd5e056c6. Revert "merge me commit for remove inline" This reverts commit 55c0ebd42b6699c7686f5ce585e745f87dd42280. fix diff after rebase master doing remove inline in me overwrite FindNodePrimitive Revert "doing remove inline in me" This reverts commit b42e893125bc624d323e855ac6ae615333c06e65.
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
adapte to remove inline merge me commit for remove inline deal witch multiple cases of switch in ConstructKernelGraph deal with switch and call cases in ConstructKernelGraph fix bug and rebase master ConstructKernelGraph adapte to remove inline fix InsertMultipleAssignToGraph bug add graph input to new graph which is created for switch input replace CreateNewParameterFromCNode to NewParameter in order to set new parameter's abstract and kernel_info avoids create a new switch repeatedly when the cnode is a call switch without real input null pointer check update frontend code Revert "update frontend code" This reverts commit ce1f600d1e9b4b47d9b81122f981bbbe505dd250. update frontend code PR_2948 fix bug of CheckLabalIndex handle switch_layer in ConstructKernelGraph add attr for assign node to avoid erasing by cse pass cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem rebase master Revert "cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem" This reverts commit 74c258f94260ca0769a1ef69c6ef8e831c301dbf. Revert "handle switch_layer in ConstructKernelGraph" This reverts commit cb5367f02d69facbca8d39e9234c501608aee27f. Revert "update frontend code PR_2948" This reverts commit 234ac583400a96a8ddd641f7a722e1ccd5e056c6. Revert "merge me commit for remove inline" This reverts commit 55c0ebd42b6699c7686f5ce585e745f87dd42280. fix diff after rebase master doing remove inline in me overwrite FindNodePrimitive Revert "doing remove inline in me" This reverts commit b42e893125bc624d323e855ac6ae615333c06e65.
5 years ago
adapte to remove inline merge me commit for remove inline deal witch multiple cases of switch in ConstructKernelGraph deal with switch and call cases in ConstructKernelGraph fix bug and rebase master ConstructKernelGraph adapte to remove inline fix InsertMultipleAssignToGraph bug add graph input to new graph which is created for switch input replace CreateNewParameterFromCNode to NewParameter in order to set new parameter's abstract and kernel_info avoids create a new switch repeatedly when the cnode is a call switch without real input null pointer check update frontend code Revert "update frontend code" This reverts commit ce1f600d1e9b4b47d9b81122f981bbbe505dd250. update frontend code PR_2948 fix bug of CheckLabalIndex handle switch_layer in ConstructKernelGraph add attr for assign node to avoid erasing by cse pass cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem rebase master Revert "cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem" This reverts commit 74c258f94260ca0769a1ef69c6ef8e831c301dbf. Revert "handle switch_layer in ConstructKernelGraph" This reverts commit cb5367f02d69facbca8d39e9234c501608aee27f. Revert "update frontend code PR_2948" This reverts commit 234ac583400a96a8ddd641f7a722e1ccd5e056c6. Revert "merge me commit for remove inline" This reverts commit 55c0ebd42b6699c7686f5ce585e745f87dd42280. fix diff after rebase master doing remove inline in me overwrite FindNodePrimitive Revert "doing remove inline in me" This reverts commit b42e893125bc624d323e855ac6ae615333c06e65.
5 years ago
adapte to remove inline merge me commit for remove inline deal witch multiple cases of switch in ConstructKernelGraph deal with switch and call cases in ConstructKernelGraph fix bug and rebase master ConstructKernelGraph adapte to remove inline fix InsertMultipleAssignToGraph bug add graph input to new graph which is created for switch input replace CreateNewParameterFromCNode to NewParameter in order to set new parameter's abstract and kernel_info avoids create a new switch repeatedly when the cnode is a call switch without real input null pointer check update frontend code Revert "update frontend code" This reverts commit ce1f600d1e9b4b47d9b81122f981bbbe505dd250. update frontend code PR_2948 fix bug of CheckLabalIndex handle switch_layer in ConstructKernelGraph add attr for assign node to avoid erasing by cse pass cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem rebase master Revert "cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem" This reverts commit 74c258f94260ca0769a1ef69c6ef8e831c301dbf. Revert "handle switch_layer in ConstructKernelGraph" This reverts commit cb5367f02d69facbca8d39e9234c501608aee27f. Revert "update frontend code PR_2948" This reverts commit 234ac583400a96a8ddd641f7a722e1ccd5e056c6. Revert "merge me commit for remove inline" This reverts commit 55c0ebd42b6699c7686f5ce585e745f87dd42280. fix diff after rebase master doing remove inline in me overwrite FindNodePrimitive Revert "doing remove inline in me" This reverts commit b42e893125bc624d323e855ac6ae615333c06e65.
5 years ago
adapte to remove inline merge me commit for remove inline deal witch multiple cases of switch in ConstructKernelGraph deal with switch and call cases in ConstructKernelGraph fix bug and rebase master ConstructKernelGraph adapte to remove inline fix InsertMultipleAssignToGraph bug add graph input to new graph which is created for switch input replace CreateNewParameterFromCNode to NewParameter in order to set new parameter's abstract and kernel_info avoids create a new switch repeatedly when the cnode is a call switch without real input null pointer check update frontend code Revert "update frontend code" This reverts commit ce1f600d1e9b4b47d9b81122f981bbbe505dd250. update frontend code PR_2948 fix bug of CheckLabalIndex handle switch_layer in ConstructKernelGraph add attr for assign node to avoid erasing by cse pass cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem rebase master Revert "cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem" This reverts commit 74c258f94260ca0769a1ef69c6ef8e831c301dbf. Revert "handle switch_layer in ConstructKernelGraph" This reverts commit cb5367f02d69facbca8d39e9234c501608aee27f. Revert "update frontend code PR_2948" This reverts commit 234ac583400a96a8ddd641f7a722e1ccd5e056c6. Revert "merge me commit for remove inline" This reverts commit 55c0ebd42b6699c7686f5ce585e745f87dd42280. fix diff after rebase master doing remove inline in me overwrite FindNodePrimitive Revert "doing remove inline in me" This reverts commit b42e893125bc624d323e855ac6ae615333c06e65.
5 years ago
adapte to remove inline merge me commit for remove inline deal witch multiple cases of switch in ConstructKernelGraph deal with switch and call cases in ConstructKernelGraph fix bug and rebase master ConstructKernelGraph adapte to remove inline fix InsertMultipleAssignToGraph bug add graph input to new graph which is created for switch input replace CreateNewParameterFromCNode to NewParameter in order to set new parameter's abstract and kernel_info avoids create a new switch repeatedly when the cnode is a call switch without real input null pointer check update frontend code Revert "update frontend code" This reverts commit ce1f600d1e9b4b47d9b81122f981bbbe505dd250. update frontend code PR_2948 fix bug of CheckLabalIndex handle switch_layer in ConstructKernelGraph add attr for assign node to avoid erasing by cse pass cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem rebase master Revert "cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem" This reverts commit 74c258f94260ca0769a1ef69c6ef8e831c301dbf. Revert "handle switch_layer in ConstructKernelGraph" This reverts commit cb5367f02d69facbca8d39e9234c501608aee27f. Revert "update frontend code PR_2948" This reverts commit 234ac583400a96a8ddd641f7a722e1ccd5e056c6. Revert "merge me commit for remove inline" This reverts commit 55c0ebd42b6699c7686f5ce585e745f87dd42280. fix diff after rebase master doing remove inline in me overwrite FindNodePrimitive Revert "doing remove inline in me" This reverts commit b42e893125bc624d323e855ac6ae615333c06e65.
5 years ago
adapte to remove inline merge me commit for remove inline deal witch multiple cases of switch in ConstructKernelGraph deal with switch and call cases in ConstructKernelGraph fix bug and rebase master ConstructKernelGraph adapte to remove inline fix InsertMultipleAssignToGraph bug add graph input to new graph which is created for switch input replace CreateNewParameterFromCNode to NewParameter in order to set new parameter's abstract and kernel_info avoids create a new switch repeatedly when the cnode is a call switch without real input null pointer check update frontend code Revert "update frontend code" This reverts commit ce1f600d1e9b4b47d9b81122f981bbbe505dd250. update frontend code PR_2948 fix bug of CheckLabalIndex handle switch_layer in ConstructKernelGraph add attr for assign node to avoid erasing by cse pass cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem rebase master Revert "cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem" This reverts commit 74c258f94260ca0769a1ef69c6ef8e831c301dbf. Revert "handle switch_layer in ConstructKernelGraph" This reverts commit cb5367f02d69facbca8d39e9234c501608aee27f. Revert "update frontend code PR_2948" This reverts commit 234ac583400a96a8ddd641f7a722e1ccd5e056c6. Revert "merge me commit for remove inline" This reverts commit 55c0ebd42b6699c7686f5ce585e745f87dd42280. fix diff after rebase master doing remove inline in me overwrite FindNodePrimitive Revert "doing remove inline in me" This reverts commit b42e893125bc624d323e855ac6ae615333c06e65.
5 years ago
adapte to remove inline merge me commit for remove inline deal witch multiple cases of switch in ConstructKernelGraph deal with switch and call cases in ConstructKernelGraph fix bug and rebase master ConstructKernelGraph adapte to remove inline fix InsertMultipleAssignToGraph bug add graph input to new graph which is created for switch input replace CreateNewParameterFromCNode to NewParameter in order to set new parameter's abstract and kernel_info avoids create a new switch repeatedly when the cnode is a call switch without real input null pointer check update frontend code Revert "update frontend code" This reverts commit ce1f600d1e9b4b47d9b81122f981bbbe505dd250. update frontend code PR_2948 fix bug of CheckLabalIndex handle switch_layer in ConstructKernelGraph add attr for assign node to avoid erasing by cse pass cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem rebase master Revert "cherry-pick ms commit[59b35f690ddcc94ff35a4f4eaf3816121b32235b]:temporary avoid list getitem problem" This reverts commit 74c258f94260ca0769a1ef69c6ef8e831c301dbf. Revert "handle switch_layer in ConstructKernelGraph" This reverts commit cb5367f02d69facbca8d39e9234c501608aee27f. Revert "update frontend code PR_2948" This reverts commit 234ac583400a96a8ddd641f7a722e1ccd5e056c6. Revert "merge me commit for remove inline" This reverts commit 55c0ebd42b6699c7686f5ce585e745f87dd42280. fix diff after rebase master doing remove inline in me overwrite FindNodePrimitive Revert "doing remove inline in me" This reverts commit b42e893125bc624d323e855ac6ae615333c06e65.
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582
  1. /**
  2. * Copyright 2019-2021 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "backend/session/session_basic.h"
  17. #include <algorithm>
  18. #include <set>
  19. #include <queue>
  20. #include <unordered_map>
  21. #include <utility>
  22. #include "ops/primitive_c.h"
  23. #include "ir/manager.h"
  24. #include "abstract/utils.h"
  25. #include "backend/kernel_compiler/common_utils.h"
  26. #include "base/core_ops.h"
  27. #include "base/base_ref_utils.h"
  28. #include "common/trans.h"
  29. #include "utils/config_manager.h"
  30. #include "backend/session/anf_runtime_algorithm.h"
  31. #include "backend/session/executor_manager.h"
  32. #include "backend/optimizer/common/common_backend_optimization.h"
  33. #include "backend/optimizer/common/helper.h"
  34. #include "runtime/device/kernel_runtime_manager.h"
  35. #include "utils/ms_utils.h"
  36. #include "ir/anf.h"
  37. #include "ir/func_graph_cloner.h"
  38. #include "utils/utils.h"
  39. #include "debug/anf_ir_dump.h"
  40. #include "debug/dump_proto.h"
  41. #include "debug/common.h"
  42. #include "utils/trace_base.h"
  43. #include "frontend/parallel/context.h"
  44. #if (ENABLE_CPU && !_WIN32)
  45. #include "ps/ps_cache/ps_cache_manager.h"
  46. #include "ps/constants.h"
  47. #include "ps/util.h"
  48. #include "ps/ps_context.h"
  49. #include "abstract/abstract_value.h"
  50. #endif
  51. namespace mindspore {
  52. namespace session {
  53. namespace {
  54. const int kSummaryGetItem = 2;
  55. const size_t max_depth = 128;
  56. bool IsShapeDynamic(const abstract::ShapePtr &shape) {
  57. if (shape == nullptr) {
  58. return false;
  59. }
  60. return std::any_of(shape->shape().begin(), shape->shape().end(), [](int64_t s) { return s < 0; });
  61. }
  62. bool RecursiveCheck(const FuncGraphManagerPtr &manager, const AnfNodePtr &node, size_t *idx) {
  63. MS_EXCEPTION_IF_NULL(manager);
  64. MS_EXCEPTION_IF_NULL(node);
  65. if (AnfAlgo::IsRealKernel(node)) {
  66. return true;
  67. }
  68. (*idx) += 1;
  69. // max recursion depth
  70. if (*idx <= max_depth) {
  71. auto users = manager->node_users()[node];
  72. if (std::any_of(users.begin(), users.end(), [&](const std::pair<AnfNodePtr, int64_t> &kernel) {
  73. return RecursiveCheck(manager, kernel.first, idx);
  74. })) {
  75. return true;
  76. }
  77. }
  78. return false;
  79. }
  80. bool IsUsedByRealKernel(const FuncGraphManagerPtr &manager, const AnfNodePtr &node) {
  81. MS_EXCEPTION_IF_NULL(manager);
  82. MS_EXCEPTION_IF_NULL(node);
  83. auto node_users = manager->node_users()[node];
  84. size_t idx = 0;
  85. if (std::any_of(node_users.begin(), node_users.end(), [&](const std::pair<AnfNodePtr, int64_t> &kernel) {
  86. return RecursiveCheck(manager, kernel.first, &idx);
  87. })) {
  88. return true;
  89. }
  90. return false;
  91. }
  92. bool CheckIfNeedCreateOutputTensor(const AnfNodePtr &node) {
  93. MS_EXCEPTION_IF_NULL(node);
  94. if (node->isa<Parameter>()) {
  95. auto node_ptr = node->cast<ParameterPtr>();
  96. MS_EXCEPTION_IF_NULL(node_ptr);
  97. if (!node_ptr->is_used_by_real_kernel()) {
  98. return true;
  99. }
  100. }
  101. return false;
  102. }
  103. ParamInfoPtr GetParamDefaultValue(const AnfNodePtr &node) {
  104. if (node == nullptr) {
  105. return nullptr;
  106. }
  107. auto parameter = node->cast<ParameterPtr>();
  108. if (parameter == nullptr || !parameter->has_default()) {
  109. return nullptr;
  110. }
  111. return parameter->param_info();
  112. }
  113. static bool IsPynativeMode() {
  114. auto ms_context = MsContext::GetInstance();
  115. MS_EXCEPTION_IF_NULL(ms_context);
  116. return ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) == kPynativeMode;
  117. }
  118. BaseRef GetNodeOutputTensorFromInputs(const session::KernelWithIndex &node_output_pair, const KernelGraphPtr &graph,
  119. const std::vector<tensor::TensorPtr> &input_tensors) {
  120. auto &node = node_output_pair.first;
  121. MS_EXCEPTION_IF_NULL(node);
  122. if (HasAbstractMonad(node)) {
  123. return std::make_shared<tensor::Tensor>(int64_t(0), kBool);
  124. }
  125. // if node is a value node, no need sync addr from device to host
  126. if (node->isa<ValueNode>()) {
  127. auto value_node = node->cast<ValueNodePtr>();
  128. MS_EXCEPTION_IF_NULL(value_node);
  129. return value_node->value();
  130. }
  131. MS_EXCEPTION_IF_NULL(graph);
  132. bool output_addr_exist = AnfAlgo::OutputAddrExist(node, node_output_pair.second);
  133. if (!output_addr_exist || (CheckIfNeedCreateOutputTensor(node) && !IsPynativeMode())) {
  134. if (node->isa<Parameter>()) {
  135. for (size_t input_idx = 0; input_idx < graph->inputs().size(); input_idx++) {
  136. if (input_idx >= input_tensors.size()) {
  137. MS_LOG(EXCEPTION) << "Input idx:" << input_idx << "out of range:" << input_tensors.size();
  138. }
  139. if (graph->inputs()[input_idx] == node) {
  140. return input_tensors[input_idx];
  141. }
  142. }
  143. if (!output_addr_exist) {
  144. MS_LOG(EXCEPTION) << "Parameter : " << node->DebugString() << " has no output addr";
  145. }
  146. }
  147. }
  148. return nullptr;
  149. }
  150. BaseRef CreateNodeOutputTensor(const session::KernelWithIndex &node_output_pair, const KernelGraphPtr &graph,
  151. const std::vector<tensor::TensorPtr> &input_tensors,
  152. std::map<tensor::TensorPtr, session::KernelWithIndex> *tensor_to_node) {
  153. auto &node = node_output_pair.first;
  154. int output_index = SizeToInt(node_output_pair.second);
  155. MS_EXCEPTION_IF_NULL(node);
  156. MS_EXCEPTION_IF_NULL(graph);
  157. MS_LOG(INFO) << "Create tensor for output[" << node->DebugString() << "] index[" << output_index << "]";
  158. auto tensor_from_input = GetNodeOutputTensorFromInputs(node_output_pair, graph, input_tensors);
  159. if (tensor_from_input != nullptr) {
  160. return tensor_from_input;
  161. }
  162. TypeId type_id = AnfAlgo::GetOutputDeviceDataType(node, output_index);
  163. if (type_id == kTypeUnknown) {
  164. type_id = AnfAlgo::GetOutputInferDataType(node, output_index);
  165. }
  166. std::vector<int64_t> temp_shape;
  167. auto shape = AnfAlgo::GetOutputInferShape(node, output_index);
  168. (void)std::copy(shape.begin(), shape.end(), std::back_inserter(temp_shape));
  169. tensor::TensorPtr tensor;
  170. bool is_internal_output = graph->IsInternalOutput(node, output_index);
  171. if (is_internal_output) {
  172. tensor = graph->GetInternalOutputTensor(node, output_index);
  173. if (tensor == nullptr) {
  174. tensor = std::make_shared<tensor::Tensor>(type_id, temp_shape);
  175. graph->AddInternalOutputTensor(node, output_index, tensor);
  176. }
  177. } else {
  178. tensor = std::make_shared<tensor::Tensor>(type_id, temp_shape);
  179. }
  180. tensor->set_padding_type(AnfAlgo::GetOutputReshapeType(node, output_index));
  181. if (is_internal_output) {
  182. tensor->set_sync_status(kNoNeedSync);
  183. } else {
  184. // if in pynative mode,data only copied to host when user want to print data
  185. auto ms_context = MsContext::GetInstance();
  186. MS_EXCEPTION_IF_NULL(ms_context);
  187. if (ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) != kPynativeMode &&
  188. ms_context->get_param<std::string>(MS_CTX_DEVICE_TARGET) != kGPUDevice) {
  189. tensor->set_sync_status(kNeedSyncDeviceToHostImmediately);
  190. } else {
  191. tensor->set_sync_status(kNeedSyncDeviceToHost);
  192. }
  193. }
  194. tensor->SetNeedWait(true);
  195. tensor->SetIsGraphOutput();
  196. (*tensor_to_node)[tensor] = node_output_pair;
  197. return tensor;
  198. }
  199. BaseRef CreateNodeOutputTensors(const AnfNodePtr &anf, const KernelGraphPtr &graph,
  200. const std::vector<tensor::TensorPtr> &input_tensors,
  201. std::map<tensor::TensorPtr, session::KernelWithIndex> *tensor_to_node,
  202. KernelMapTensor *node_to_tensor) {
  203. MS_EXCEPTION_IF_NULL(anf);
  204. MS_EXCEPTION_IF_NULL(tensor_to_node);
  205. MS_EXCEPTION_IF_NULL(node_to_tensor);
  206. MS_LOG(INFO) << "Create tensor for output[" << anf->DebugString() << "]";
  207. auto item_with_index = AnfAlgo::VisitKernelWithReturnType(anf, 0);
  208. MS_EXCEPTION_IF_NULL(item_with_index.first);
  209. MS_LOG(INFO) << "Create tensor for output after visit:" << item_with_index.first->DebugString();
  210. // special handle for maketuple
  211. if (AnfAlgo::CheckPrimitiveType(item_with_index.first, prim::kPrimMakeTuple)) {
  212. auto cnode = item_with_index.first->cast<CNodePtr>();
  213. MS_EXCEPTION_IF_NULL(cnode);
  214. VectorRef ret;
  215. for (size_t i = 1; i < cnode->inputs().size(); ++i) {
  216. auto out = CreateNodeOutputTensors(cnode->input(i), graph, input_tensors, tensor_to_node, node_to_tensor);
  217. ret.push_back(out);
  218. }
  219. return ret;
  220. }
  221. // if is graph return nothing ,the function should return a null anylist
  222. size_t size = AnfAlgo::GetOutputTensorNum(item_with_index.first);
  223. if (size == 0) {
  224. return VectorRef();
  225. }
  226. // The outputs of graph may have the same kernel node, no need to create new tensor.
  227. const auto &iter = node_to_tensor->find(item_with_index);
  228. if (iter != node_to_tensor->end()) {
  229. return iter->second;
  230. }
  231. const auto &tensor = CreateNodeOutputTensor(item_with_index, graph, input_tensors, tensor_to_node);
  232. (*node_to_tensor)[item_with_index] = tensor;
  233. return tensor;
  234. }
  235. ValueNodePtr CreateNewValueNode(const AnfNodePtr &anf, KernelGraph *graph) {
  236. MS_EXCEPTION_IF_NULL(anf);
  237. MS_EXCEPTION_IF_NULL(graph);
  238. auto value_node = anf->cast<ValueNodePtr>();
  239. MS_EXCEPTION_IF_NULL(value_node);
  240. auto value = value_node->value();
  241. MS_EXCEPTION_IF_NULL(value);
  242. if (value->isa<None>()) {
  243. return nullptr;
  244. }
  245. auto new_value_node = graph->NewValueNode(value_node);
  246. graph->FrontBackendlMapAdd(anf, new_value_node);
  247. graph->AddValueNodeToGraph(new_value_node);
  248. return new_value_node;
  249. }
  250. ValueNodePtr ConstructRunOpValueNode(const std::shared_ptr<KernelGraph> &graph, const tensor::TensorPtr &input_tensor) {
  251. MS_EXCEPTION_IF_NULL(graph);
  252. MS_EXCEPTION_IF_NULL(input_tensor);
  253. auto value_node = std::make_shared<ValueNode>(input_tensor);
  254. MS_EXCEPTION_IF_NULL(value_node);
  255. // construct abstract of value node
  256. auto type_of_tensor = input_tensor->Dtype();
  257. auto shape_of_tensor = input_tensor->shape();
  258. auto abstract = std::make_shared<abstract::AbstractTensor>(type_of_tensor, shape_of_tensor);
  259. value_node->set_abstract(abstract);
  260. // add value node to graph
  261. auto input_value_node = graph->NewValueNode(value_node);
  262. graph->AddValueNodeToGraph(input_value_node);
  263. return input_value_node;
  264. }
  265. ParameterPtr ConstructRunOpParameter(const std::shared_ptr<KernelGraph> &graph, const tensor::TensorPtr &input_tensor,
  266. int64_t tensor_mask) {
  267. MS_EXCEPTION_IF_NULL(graph);
  268. auto param = graph->NewParameter();
  269. MS_EXCEPTION_IF_NULL(param);
  270. if (tensor_mask == kParameterWeightTensorMask) {
  271. param->set_default_param(input_tensor);
  272. }
  273. // set the kernel info of parameter
  274. auto kernel_build_info_builder = std::make_shared<kernel::KernelBuildInfo::KernelBuildInfoBuilder>();
  275. MS_EXCEPTION_IF_NULL(input_tensor);
  276. auto device_address = std::dynamic_pointer_cast<device::DeviceAddress>(input_tensor->device_address());
  277. if (device_address == nullptr) {
  278. kernel_build_info_builder->SetOutputsFormat(std::vector<std::string>{kOpFormat_DEFAULT});
  279. TypeId param_init_data_type = AnfAlgo::IsParameterWeight(param) ? kTypeUnknown : input_tensor->data_type();
  280. kernel_build_info_builder->SetOutputsDeviceType(std::vector<TypeId>{param_init_data_type});
  281. } else {
  282. kernel_build_info_builder->SetOutputsFormat(std::vector<std::string>{device_address->format()});
  283. kernel_build_info_builder->SetOutputsDeviceType(std::vector<TypeId>{device_address->type_id()});
  284. kernel_build_info_builder->SetOutputsReshapeType({input_tensor->padding_type()});
  285. AnfAlgo::SetOutputAddr(device_address, 0, param.get());
  286. }
  287. AnfAlgo::SetSelectKernelBuildInfo(kernel_build_info_builder->Build(), param.get());
  288. // construct abstract of parameter
  289. auto type_of_tensor = input_tensor->Dtype();
  290. auto shape_of_tensor = input_tensor->shape();
  291. auto abstract = std::make_shared<abstract::AbstractTensor>(type_of_tensor, shape_of_tensor);
  292. param->set_abstract(abstract);
  293. return param;
  294. }
  295. void DumpGraphOutput(const Any &any, size_t recurse_level = 0) {
  296. MS_LOG(INFO) << "Graph outputs:";
  297. const size_t max_deep = 10;
  298. if (recurse_level > max_deep) {
  299. MS_LOG(INFO) << "Recurse too deep";
  300. return;
  301. }
  302. std::string tab_str;
  303. for (size_t i = 0; i < recurse_level; i++) {
  304. tab_str = tab_str.append(" ");
  305. }
  306. if (any.is<AnyList>()) {
  307. (void)tab_str.append("{");
  308. MS_LOG(INFO) << tab_str;
  309. auto any_list = any.cast<AnyList>();
  310. for (auto &it : any_list) {
  311. DumpGraphOutput(it, recurse_level + 1);
  312. }
  313. (void)tab_str.append("}");
  314. MS_LOG(INFO) << tab_str;
  315. }
  316. (void)tab_str.append(any.ToString());
  317. MS_LOG(INFO) << tab_str;
  318. }
  319. bool ExistSummaryNode(const KernelGraph *graph) {
  320. MS_EXCEPTION_IF_NULL(graph);
  321. auto ret = graph->get_return();
  322. MS_EXCEPTION_IF_NULL(ret);
  323. auto all_nodes = DeepLinkedGraphSearch(ret);
  324. for (auto &n : all_nodes) {
  325. if (IsPrimitiveCNode(n, prim::kPrimScalarSummary) || IsPrimitiveCNode(n, prim::kPrimTensorSummary) ||
  326. IsPrimitiveCNode(n, prim::kPrimImageSummary) || IsPrimitiveCNode(n, prim::kPrimHistogramSummary)) {
  327. return true;
  328. }
  329. }
  330. return false;
  331. }
  332. void GetParameterIndex(const KernelGraph *graph, const std::vector<tensor::TensorPtr> &inputs,
  333. std::map<AnfNodePtr, size_t> *parameter_index) {
  334. size_t index = 0;
  335. for (const auto &input_node : graph->inputs()) {
  336. auto params = AnfAlgo::GetAllOutput(input_node);
  337. for (const auto &param : params) {
  338. if (index >= inputs.size()) {
  339. MS_LOG(EXCEPTION) << "Parameter size out of range. Parameter index: " << index
  340. << ", input size: " << inputs.size();
  341. }
  342. const auto &input = inputs[index];
  343. // Check shape of input and parameter
  344. const auto &input_shape = input->shape();
  345. const auto &param_shape = AnfAlgo::GetOutputInferShape(param, 0);
  346. if (input_shape.size() != param_shape.size()) {
  347. MS_LOG(EXCEPTION) << "Shapes of input and parameter are different, input index: " << index
  348. << ", parameter: " << param->fullname_with_scope();
  349. }
  350. for (size_t i = 0; i < input_shape.size(); i += 1) {
  351. if (input_shape[i] < 0 || static_cast<size_t>(input_shape[i]) != param_shape[i]) {
  352. MS_LOG(EXCEPTION) << "Shapes of input and parameter are different, input index: " << index
  353. << ", parameter: " << param->fullname_with_scope();
  354. }
  355. }
  356. parameter_index->emplace(param, index++);
  357. }
  358. }
  359. }
  360. BaseRef CreateNodeOutputPlaceholder(const session::KernelWithIndex &node_output_pair, const KernelGraphPtr &graph,
  361. const std::vector<tensor::TensorPtr> &input_tensors,
  362. const std::vector<size_t> &indexes,
  363. std::map<KernelWithIndex, std::vector<std::vector<size_t>>> *output_indexes) {
  364. auto &node = node_output_pair.first;
  365. MS_EXCEPTION_IF_NULL(node);
  366. MS_EXCEPTION_IF_NULL(graph);
  367. MS_EXCEPTION_IF_NULL(output_indexes);
  368. MS_LOG(INFO) << "Create placeholder for output[" << node->DebugString() << "] index[" << node_output_pair.second
  369. << "]";
  370. // if node is a value node, no need sync addr from device to host
  371. if (node->isa<ValueNode>()) {
  372. auto value_node = node->cast<ValueNodePtr>();
  373. MS_EXCEPTION_IF_NULL(value_node);
  374. return value_node->value();
  375. }
  376. if (node->isa<Parameter>()) {
  377. for (size_t input_idx = 0; input_idx < graph->inputs().size(); input_idx++) {
  378. if (input_idx >= input_tensors.size()) {
  379. MS_LOG(EXCEPTION) << "Input idx:" << input_idx << "out of range:" << input_tensors.size();
  380. }
  381. if (graph->inputs()[input_idx] == node) {
  382. return input_tensors[input_idx];
  383. }
  384. }
  385. MS_LOG(EXCEPTION) << "Parameter: " << node->DebugString() << " has no output addr";
  386. }
  387. (*output_indexes)[node_output_pair].emplace_back(indexes);
  388. BaseRef output_placeholder = std::make_shared<BaseRef>();
  389. return output_placeholder;
  390. }
  391. BaseRef CreateNodeOutputPlaceholder(const AnfNodePtr &anf, const KernelGraphPtr &graph,
  392. const std::vector<tensor::TensorPtr> &input_tensors,
  393. const std::vector<size_t> &indexes,
  394. std::map<KernelWithIndex, std::vector<std::vector<size_t>>> *output_indexes) {
  395. MS_EXCEPTION_IF_NULL(anf);
  396. MS_EXCEPTION_IF_NULL(output_indexes);
  397. MS_LOG(INFO) << "Create placeholder for output[" << anf->DebugString() << "]";
  398. auto item_with_index = AnfAlgo::VisitKernelWithReturnType(anf, 0);
  399. MS_EXCEPTION_IF_NULL(item_with_index.first);
  400. MS_LOG(INFO) << "Create placeholder for output after visit:" << item_with_index.first->DebugString();
  401. // special handle for maketuple
  402. if (AnfAlgo::CheckPrimitiveType(item_with_index.first, prim::kPrimMakeTuple)) {
  403. auto cnode = item_with_index.first->cast<CNodePtr>();
  404. MS_EXCEPTION_IF_NULL(cnode);
  405. VectorRef ret;
  406. for (size_t i = 1; i < cnode->inputs().size(); ++i) {
  407. std::vector<size_t> cur_index = indexes;
  408. cur_index.emplace_back(i - 1);
  409. auto out = CreateNodeOutputPlaceholder(cnode->input(i), graph, input_tensors, cur_index, output_indexes);
  410. ret.push_back(out);
  411. }
  412. return ret;
  413. }
  414. // if is graph return nothing ,the function should return a null anylist
  415. size_t size = AnfAlgo::GetOutputTensorNum(item_with_index.first);
  416. if (size == 0) {
  417. return VectorRef();
  418. }
  419. return CreateNodeOutputPlaceholder(item_with_index, graph, input_tensors, indexes, output_indexes);
  420. }
  421. void CreateOutputPlaceholder(const KernelGraphPtr &kernel_graph, const std::vector<tensor::TensorPtr> &input_tensors,
  422. VectorRef *outputs,
  423. std::map<KernelWithIndex, std::vector<std::vector<size_t>>> *output_indexes) {
  424. MS_EXCEPTION_IF_NULL(kernel_graph);
  425. MS_EXCEPTION_IF_NULL(outputs);
  426. MS_EXCEPTION_IF_NULL(output_indexes);
  427. auto anf_outputs = kernel_graph->outputs();
  428. size_t index = 0;
  429. for (auto &item : anf_outputs) {
  430. MS_EXCEPTION_IF_NULL(item);
  431. MS_LOG(INFO) << "Create node output placeholder[" << item->DebugString() << "]";
  432. std::vector<size_t> indexes{index++};
  433. outputs->emplace_back(CreateNodeOutputPlaceholder(item, kernel_graph, input_tensors, indexes, output_indexes));
  434. }
  435. }
  436. void GetRefCount(const KernelGraph *graph, std::map<KernelWithIndex, size_t> *ref_count) {
  437. MS_EXCEPTION_IF_NULL(graph);
  438. for (const auto &kernel : graph->execution_order()) {
  439. for (size_t i = 1; i < kernel->inputs().size(); i += 1) {
  440. const auto &input = kernel->input(i);
  441. auto kernel_with_index = AnfAlgo::VisitKernel(input, 0);
  442. const auto &node = kernel_with_index.first;
  443. if (node->isa<CNode>()) {
  444. (*ref_count)[kernel_with_index] += 1;
  445. }
  446. }
  447. }
  448. }
  449. void HandleOpInputs(const std::set<KernelWithIndex> &input_kernel, std::map<KernelWithIndex, size_t> *ref_count,
  450. std::map<KernelWithIndex, tensor::TensorPtr> *op_output_map) {
  451. MS_EXCEPTION_IF_NULL(ref_count);
  452. MS_EXCEPTION_IF_NULL(op_output_map);
  453. for (auto &kernel_with_index : input_kernel) {
  454. MS_EXCEPTION_IF_NULL(kernel_with_index.first);
  455. if (!kernel_with_index.first->isa<CNode>()) {
  456. continue;
  457. }
  458. auto ref_iter = ref_count->find(kernel_with_index);
  459. if (ref_iter == ref_count->end()) {
  460. MS_LOG(EXCEPTION) << "Can not find input KernelWithIndex in cnode reference count map, input cnode = "
  461. << kernel_with_index.first->DebugString() << ", index = " << kernel_with_index.second;
  462. }
  463. // Reduce reference count number, when it was reduced to zero, release the useless output of pre node.
  464. ref_iter->second -= 1;
  465. if (ref_iter->second != 0) {
  466. continue;
  467. }
  468. ref_count->erase(ref_iter);
  469. auto output_iter = op_output_map->find(kernel_with_index);
  470. if (output_iter == op_output_map->end()) {
  471. MS_LOG(EXCEPTION) << "Can not find input KernelWithIndex in op_output map, input cnode = "
  472. << kernel_with_index.first->DebugString() << ", index = " << kernel_with_index.second;
  473. }
  474. op_output_map->erase(output_iter);
  475. }
  476. }
  477. void HandleOpOutputs(const AnfNodePtr &kernel, const VectorRef &op_outputs,
  478. const std::map<KernelWithIndex, std::vector<std::vector<size_t>>> &output_indexes,
  479. const std::map<KernelWithIndex, size_t> &ref_count,
  480. std::map<KernelWithIndex, tensor::TensorPtr> *op_output_map, VectorRef *outputs,
  481. std::vector<TensorPtr> *runop_output_tensors) {
  482. MS_EXCEPTION_IF_NULL(kernel);
  483. MS_EXCEPTION_IF_NULL(op_output_map);
  484. MS_EXCEPTION_IF_NULL(outputs);
  485. MS_EXCEPTION_IF_NULL(runop_output_tensors);
  486. auto output_tensors = TransformVectorRefToMultiTensor(op_outputs);
  487. if (output_tensors.size() > op_outputs.size()) {
  488. MS_LOG(EXCEPTION) << "Op output contains tuple, node = " << kernel->DebugString();
  489. }
  490. size_t out_index = 0;
  491. for (const auto &output_tensor : output_tensors) {
  492. auto kernel_with_index = make_pair(kernel, out_index++);
  493. if (ref_count.find(kernel_with_index) != ref_count.end()) {
  494. (*op_output_map)[kernel_with_index] = output_tensor;
  495. }
  496. const auto &iter = output_indexes.find(kernel_with_index);
  497. if (iter == output_indexes.end()) {
  498. continue;
  499. }
  500. const std::vector<std::vector<size_t>> &multiple_ref_indexes = iter->second;
  501. for (const auto &ref_indexes : multiple_ref_indexes) {
  502. size_t n = 0;
  503. const VectorRef *cur_vector_ref = outputs;
  504. for (; n < ref_indexes.size() - 1; n += 1) {
  505. size_t index = ref_indexes.at(n);
  506. if (index >= cur_vector_ref->size()) {
  507. MS_LOG(EXCEPTION) << "Get invalid output ref index: " << index << ", size of vertor ref is "
  508. << cur_vector_ref->size();
  509. }
  510. const BaseRef &base_ref = (*cur_vector_ref)[index];
  511. if (!utils::isa<VectorRef>(base_ref)) {
  512. MS_LOG(EXCEPTION) << "Get none VectorRef by ref index, index: " << index << "cur n: " << n;
  513. }
  514. cur_vector_ref = &utils::cast<VectorRef>(base_ref);
  515. }
  516. BaseRef &tensor_ref = (*const_cast<VectorRef *>(cur_vector_ref))[ref_indexes.at(n)];
  517. tensor_ref = output_tensor;
  518. runop_output_tensors->emplace_back(output_tensor);
  519. }
  520. }
  521. }
  522. } // namespace
  523. GraphId SessionBasic::graph_sum_ = 0;
  524. void SessionBasic::InitExecutor(const std::string &device_name, uint32_t device_id) {
  525. device_id_ = device_id;
  526. context_ = std::make_shared<Context>(device_name, device_id);
  527. executor_ = ExecutorManager::Instance().GetExecutor(device_name, device_id);
  528. }
  529. GraphId SessionBasic::GetGraphIdByNode(const AnfNodePtr &front_anf) const {
  530. for (const auto &graph_item : graphs_) {
  531. auto graph = graph_item.second;
  532. MS_EXCEPTION_IF_NULL(graph);
  533. // if front_anf is a parameter,the backend parameter may have two
  534. if (graph->GetBackendAnfByFrontAnf(front_anf) != nullptr) {
  535. return graph_item.first;
  536. }
  537. }
  538. MS_EXCEPTION_IF_NULL(front_anf);
  539. MS_LOG(DEBUG) << "Front_anf " << front_anf->DebugString() << " is not exist in any graph";
  540. return kInvalidGraphId;
  541. }
  542. KernelGraphPtr SessionBasic::GetGraph(mindspore::GraphId graph_id) const {
  543. auto it = graphs_.find(graph_id);
  544. if (it == graphs_.end()) {
  545. MS_LOG(INFO) << "Can't find graph " << graph_id;
  546. return nullptr;
  547. }
  548. return it->second;
  549. }
  550. void SessionBasic::ClearGraph() {
  551. auto graph_iter = graphs_.begin();
  552. while (graph_iter != graphs_.end()) {
  553. graph_iter->second.reset();
  554. graphs_.erase(graph_iter++);
  555. }
  556. graph_sum_ = 0;
  557. }
  558. void SessionBasic::InitInternalOutputParameter(const AnfNodePtr &out_node, const AnfNodePtr &parameter) {
  559. auto graph_id = GetGraphIdByNode(out_node);
  560. if (graph_id == kInvalidGraphId) {
  561. return;
  562. }
  563. auto node_graph = GetGraph(graph_id);
  564. if (node_graph == nullptr) {
  565. return;
  566. }
  567. MS_LOG(INFO) << "Init parameter with pre graph output node: " << out_node->DebugString();
  568. auto ref_node = node_graph->GetInternalOutputByFrontNode(out_node);
  569. if (ref_node == nullptr) {
  570. MS_LOG(INFO) << "No corresponding internal output for output node";
  571. return;
  572. }
  573. size_t output_idx = 0;
  574. if (AnfAlgo::CheckPrimitiveType(out_node, prim::kPrimTupleGetItem)) {
  575. output_idx = AnfAlgo::GetTupleGetItemOutIndex(out_node->cast<CNodePtr>());
  576. }
  577. auto real_kernel = AnfAlgo::VisitKernel(ref_node, output_idx);
  578. auto ref_real_node = real_kernel.first;
  579. auto ref_real_node_index = real_kernel.second;
  580. if (ref_real_node->isa<CNode>() && node_graph->IsUniqueTargetInternalOutput(ref_real_node, ref_real_node_index)) {
  581. auto kernel_info = ref_real_node->kernel_info();
  582. if (kernel_info == nullptr || !kernel_info->has_build_info()) {
  583. MS_LOG(INFO) << "No kernel info";
  584. return;
  585. }
  586. if (!opt::IsNopNode(ref_real_node) && !AnfAlgo::OutputAddrExist(ref_real_node, ref_real_node_index)) {
  587. MS_LOG(INFO) << "No kernel address";
  588. return;
  589. }
  590. auto address = AnfAlgo::GetMutableOutputAddr(ref_real_node, ref_real_node_index);
  591. auto format = AnfAlgo::GetOutputFormat(ref_real_node, ref_real_node_index);
  592. auto type = AnfAlgo::GetOutputDeviceDataType(ref_real_node, ref_real_node_index);
  593. auto d_kernel_info = std::make_shared<device::KernelInfo>();
  594. MS_EXCEPTION_IF_NULL(d_kernel_info);
  595. parameter->set_kernel_info(d_kernel_info);
  596. kernel::KernelBuildInfo::KernelBuildInfoBuilder builder;
  597. builder.SetOutputsDeviceType({type});
  598. builder.SetOutputsFormat({format});
  599. d_kernel_info->set_select_kernel_build_info(builder.Build());
  600. AnfAlgo::SetOutputAddr(address, 0, parameter.get());
  601. auto abstract = std::make_shared<abstract::AbstractTensor>(TypeIdToType(type),
  602. parameter->Shape()->cast<abstract::BaseShapePtr>());
  603. parameter->set_abstract(abstract);
  604. }
  605. }
  606. AnfNodePtr SessionBasic::CreateParameterFromTuple(const AnfNodePtr &node, KernelGraph *graph) {
  607. MS_EXCEPTION_IF_NULL(node);
  608. MS_EXCEPTION_IF_NULL(graph);
  609. auto new_parameter = graph->TransTupleToMakeTuple(graph->NewParameter(node->abstract()));
  610. auto parameters = AnfAlgo::GetAllOutput(new_parameter);
  611. std::vector<AnfNodePtr> pre_graph_out = {node};
  612. // If a cnode is a call, it's input0 is a cnode too, so it doesn't have primitive
  613. if (!pre_graph_out.empty() && !AnfAlgo::IsRealKernel(node)) {
  614. pre_graph_out = AnfAlgo::GetAllOutput(node, {prim::kPrimTupleGetItem, prim::kPrimUpdateState});
  615. }
  616. for (const auto &parameter : parameters) {
  617. auto valid_inputs = graph->MutableValidInputs();
  618. MS_EXCEPTION_IF_NULL(valid_inputs);
  619. auto graph_inputs = graph->MutableInputs();
  620. MS_EXCEPTION_IF_NULL(graph_inputs);
  621. valid_inputs->push_back(true);
  622. graph_inputs->push_back(parameter);
  623. }
  624. size_t param_index = 0;
  625. for (const auto &out_node : pre_graph_out) {
  626. size_t output_size = AnfAlgo::GetOutputTensorNum(out_node);
  627. for (size_t i = 0; i < output_size; i++) {
  628. if (param_index >= parameters.size()) {
  629. MS_LOG(EXCEPTION) << "Parameters size:" << parameters.size() << "out of range.Node:" << node->DebugString()
  630. << ",out_node:" << out_node->DebugString();
  631. }
  632. InitInternalOutputParameter(out_node, parameters[param_index++]);
  633. }
  634. }
  635. return new_parameter;
  636. }
  637. ParameterPtr SessionBasic::CreateNewParameterFromParameter(const AnfNodePtr &anf, KernelGraph *graph) {
  638. MS_EXCEPTION_IF_NULL(anf);
  639. if (!anf->isa<Parameter>()) {
  640. MS_LOG(EXCEPTION) << "Anf[" << anf->DebugString() << "] is not a parameter";
  641. }
  642. MS_EXCEPTION_IF_NULL(graph);
  643. auto param_value = GetParamDefaultValue(anf);
  644. auto valid_inputs = graph->MutableValidInputs();
  645. MS_EXCEPTION_IF_NULL(valid_inputs);
  646. auto graph_inputs = graph->MutableInputs();
  647. MS_EXCEPTION_IF_NULL(graph_inputs);
  648. ParameterPtr new_parameter = nullptr;
  649. // if parameter's python parameter has been exist a backend parameter, reuse the exist parameter
  650. if (param_value != nullptr) {
  651. new_parameter = param_value->parameter();
  652. }
  653. if (new_parameter == nullptr) {
  654. TraceGuard trace_guard(std::make_shared<TraceCopy>(anf->debug_info()));
  655. new_parameter = graph->NewParameter(anf->cast<ParameterPtr>());
  656. auto input_node_iter = partial_parameters_map_.find(anf);
  657. if (input_node_iter != partial_parameters_map_.end()) {
  658. InitInternalOutputParameter(input_node_iter->second, new_parameter);
  659. }
  660. if (param_value != nullptr) {
  661. param_value->set_parameter(new_parameter);
  662. }
  663. }
  664. new_parameter->IncreaseUsedGraphCount();
  665. graph_inputs->push_back(new_parameter);
  666. valid_inputs->push_back(true);
  667. return new_parameter;
  668. }
  669. AnfNodePtr SessionBasic::CreateNewParameterFromCNode(const AnfNodePtr &anf, KernelGraph *graph) {
  670. MS_EXCEPTION_IF_NULL(anf);
  671. MS_EXCEPTION_IF_NULL(graph);
  672. MS_LOG(INFO) << "Create a new parameter from cnode[" << anf->DebugString() << "]";
  673. return CreateParameterFromTuple(anf, graph);
  674. }
  675. void SessionBasic::GetCNodeInfo(const CNodePtr &cnode, std::vector<AnfNodePtr> *cnode_inputs) const {
  676. MS_EXCEPTION_IF_NULL(cnode);
  677. MS_EXCEPTION_IF_NULL(cnode_inputs);
  678. auto prim = AnfAlgo::GetCNodePrimitive(cnode);
  679. if (prim != nullptr) {
  680. // push attr to inputs[0] of new cnode
  681. cnode_inputs->push_back(std::make_shared<ValueNode>(std::make_shared<Primitive>(*prim)));
  682. } else {
  683. auto fg = AnfAlgo::GetCNodeFuncGraphPtr(cnode);
  684. MS_EXCEPTION_IF_NULL(fg);
  685. auto new_fg = BasicClone(fg);
  686. cnode_inputs->push_back(std::make_shared<ValueNode>(new_fg));
  687. }
  688. }
  689. void SessionBasic::GetNewCNodeInputs(const CNodePtr &cnode, KernelGraph *graph, std::vector<AnfNodePtr> *cnode_inputs,
  690. std::unordered_map<AnfNodePtr, AnfNodePtr> *other_graph_cnode) {
  691. MS_EXCEPTION_IF_NULL(cnode);
  692. MS_EXCEPTION_IF_NULL(graph);
  693. MS_EXCEPTION_IF_NULL(other_graph_cnode);
  694. MS_EXCEPTION_IF_NULL(cnode_inputs);
  695. auto origin_inputs = cnode->inputs();
  696. const bool is_depend = IsPrimitiveCNode(cnode, prim::kPrimDepend);
  697. const bool is_updatestate = IsPrimitiveCNode(cnode, prim::kPrimUpdateState);
  698. // if has multiple depends,only select first depend as parameter
  699. for (size_t input_idx = 1; input_idx < origin_inputs.size(); input_idx++) {
  700. auto anf = origin_inputs[input_idx];
  701. MS_EXCEPTION_IF_NULL(anf);
  702. // anf has been created before
  703. if (graph->GetBackendAnfByFrontAnf(anf) != nullptr) {
  704. (void)cnode_inputs->emplace_back(graph->GetBackendAnfByFrontAnf(anf));
  705. continue;
  706. } else if ((is_depend && input_idx > 1) || (is_updatestate && input_idx > 2)) {
  707. cnode_inputs->push_back(NewValueNode(MakeValue(SizeToInt(input_idx))));
  708. continue;
  709. } else if (other_graph_cnode->find(anf) != other_graph_cnode->end()) {
  710. cnode_inputs->push_back((*other_graph_cnode)[anf]);
  711. continue;
  712. } else if (anf->isa<ValueNode>() && !IsValueNode<FuncGraph>(anf)) {
  713. // if input is a value node,
  714. auto new_value_node = CreateNewValueNode(anf, graph);
  715. if (new_value_node != nullptr) {
  716. (void)cnode_inputs->emplace_back(new_value_node);
  717. }
  718. continue;
  719. } else if (anf->isa<Parameter>()) {
  720. auto new_parameter = CreateNewParameterFromParameter(anf, graph);
  721. cnode_inputs->push_back(new_parameter);
  722. if (GetGraphIdByNode(anf) == kInvalidGraphId) {
  723. graph->FrontBackendlMapAdd(anf, new_parameter);
  724. } else {
  725. (*other_graph_cnode)[anf] = new_parameter;
  726. }
  727. continue;
  728. } else {
  729. // the input node is a cnode from other graph
  730. auto parameter_from_cnode = CreateNewParameterFromCNode(anf, graph);
  731. if (parameter_from_cnode == nullptr) {
  732. parameter_from_cnode = NewValueNode(MakeValue(SizeToLong(input_idx)));
  733. }
  734. if (parameter_from_cnode->isa<Parameter>() && IsPrimitiveCNode(anf, prim::kPrimLoad)) {
  735. auto para = parameter_from_cnode->cast<ParameterPtr>();
  736. auto load_cnode = anf->cast<CNodePtr>();
  737. para->set_name(load_cnode->input(kFirstDataInputIndex)->fullname_with_scope());
  738. }
  739. cnode_inputs->push_back(parameter_from_cnode);
  740. (*other_graph_cnode)[anf] = parameter_from_cnode;
  741. }
  742. }
  743. }
  744. CNodePtr SessionBasic::CreateNewCNode(const CNodePtr &cnode, KernelGraph *graph,
  745. std::unordered_map<AnfNodePtr, AnfNodePtr> *other_graph_cnode) {
  746. MS_EXCEPTION_IF_NULL(cnode);
  747. MS_EXCEPTION_IF_NULL(graph);
  748. MS_EXCEPTION_IF_NULL(other_graph_cnode);
  749. // get primitive of old node
  750. std::vector<AnfNodePtr> cnode_inputs;
  751. GetCNodeInfo(cnode, &cnode_inputs);
  752. GetNewCNodeInputs(cnode, graph, &cnode_inputs, other_graph_cnode);
  753. TraceGuard trace_guard(std::make_shared<TraceCopy>(cnode->debug_info()));
  754. auto new_cnode = graph->NewCNode(cnode_inputs);
  755. return new_cnode;
  756. }
  757. CNodePtr SessionBasic::CreateSwitchInput(const CNodePtr &cnode, const AnfNodePtr &node_input, KernelGraph *graph) {
  758. MS_EXCEPTION_IF_NULL(node_input);
  759. MS_EXCEPTION_IF_NULL(graph);
  760. // switch input generalizes partial
  761. std::vector<AnfNodePtr> partial_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimPartial->name()))};
  762. if (AnfAlgo::CheckPrimitiveType(node_input, prim::kPrimPartial)) {
  763. auto partial_node = graph->GetBackendAnfByFrontAnf(node_input);
  764. return partial_node->cast<CNodePtr>();
  765. } else if (node_input->isa<ValueNode>() && IsValueNode<FuncGraph>(node_input)) {
  766. partial_inputs.emplace_back(graph->GetBackendAnfByFrontAnf(node_input));
  767. } else {
  768. KernelGraphPtr kernel_graph = NewKernelGraph();
  769. MS_EXCEPTION_IF_NULL(kernel_graph);
  770. auto parameter = CreateNewParameterFromCNode(cnode, kernel_graph.get());
  771. MS_EXCEPTION_IF_NULL(parameter);
  772. parameter->set_abstract(cnode->abstract());
  773. auto primitive = NewValueNode(std::make_shared<Primitive>(prim::kPrimReturn->name()));
  774. auto return_node = kernel_graph->NewCNode({primitive, parameter});
  775. return_node->set_abstract(cnode->abstract());
  776. kernel_graph->set_return(return_node);
  777. partial_inputs.emplace_back(std::make_shared<ValueNode>(kernel_graph));
  778. partial_inputs.emplace_back(graph->GetBackendAnfByFrontAnf(node_input));
  779. }
  780. auto partial_node = graph->NewCNode(partial_inputs);
  781. return partial_node;
  782. }
  783. std::vector<AnfNodePtr> SessionBasic::CreateCallSwitchInputs(const CNodePtr &cnode, KernelGraph *graph) {
  784. MS_EXCEPTION_IF_NULL(cnode);
  785. MS_EXCEPTION_IF_NULL(graph);
  786. std::vector<AnfNodePtr> cnode_inputs = {
  787. graph->NewValueNode(NewValueNode(std::make_shared<Primitive>(prim::kPrimCall->name())))};
  788. auto attr_input = cnode->input(kAnfPrimitiveIndex);
  789. MS_EXCEPTION_IF_NULL(attr_input);
  790. auto cnode_input = graph->GetBackendAnfByFrontAnf(attr_input);
  791. auto switch_cnode = cnode_input->cast<CNodePtr>();
  792. MS_EXCEPTION_IF_NULL(switch_cnode);
  793. if (cnode->inputs().size() < 2) {
  794. cnode_inputs = switch_cnode->inputs();
  795. return cnode_inputs;
  796. }
  797. std::vector<AnfNodePtr> switch_inputs = {switch_cnode->input(kAnfPrimitiveIndex),
  798. switch_cnode->input(kFirstDataInputIndex)};
  799. for (size_t index = kFirstBranchInSwitch; index < switch_cnode->inputs().size(); index++) {
  800. auto node = switch_cnode->input(index);
  801. // there is real input in call, should put it to true and false branch in switch
  802. if (AnfAlgo::CheckPrimitiveType(node, prim::kPrimPartial)) {
  803. auto partial_node = node->cast<CNodePtr>();
  804. MS_EXCEPTION_IF_NULL(partial_node);
  805. std::vector<AnfNodePtr> partial_inputs = partial_node->inputs();
  806. // Put all call args at the end of partial inputs.
  807. for (size_t i = kFirstDataInputIndex; i < cnode->size(); ++i) {
  808. (void)partial_inputs.emplace_back(graph->GetBackendAnfByFrontAnf(cnode->input(i)));
  809. }
  810. auto new_partial = graph->NewCNode(partial_inputs);
  811. (void)switch_inputs.emplace_back(new_partial);
  812. }
  813. }
  814. if (switch_inputs.size() < kSwitchInputSize) {
  815. MS_LOG(EXCEPTION) << "Switch inputs size: " << switch_inputs.size() << "less than " << kSwitchInputSize;
  816. }
  817. auto switch_node = graph->NewCNode(switch_inputs);
  818. (void)cnode_inputs.emplace_back(switch_node);
  819. return cnode_inputs;
  820. }
  821. void SessionBasic::ProcessNodeRetFunc(const CNodePtr &cnode, KernelGraph *graph,
  822. const std::vector<AnfNodePtr> &real_inputs) {
  823. MS_EXCEPTION_IF_NULL(cnode);
  824. // func1 =switch(branch1, branch2)
  825. // func2 = func1(param1)
  826. // out = func2(param2)
  827. // process the last cnode(func2), not func1 which abstract is AbstractFunction
  828. if (cnode->abstract()->isa<abstract::AbstractFunction>()) {
  829. return;
  830. }
  831. MS_EXCEPTION_IF_NULL(graph);
  832. auto ret = graph->get_return();
  833. MS_EXCEPTION_IF_NULL(ret);
  834. auto return_input = ret->input(kFirstDataInputIndex);
  835. // return node is a function
  836. std::vector<AnfNodePtr> call_inputs = {
  837. graph->NewValueNode(NewValueNode(std::make_shared<Primitive>(prim::kPrimCall->name())))};
  838. if (AnfAlgo::CheckPrimitiveType(return_input, prim::kPrimPartial)) {
  839. auto return_input_cnode = return_input->cast<CNodePtr>();
  840. auto partial_inputs = return_input_cnode->inputs();
  841. call_inputs.insert(call_inputs.end(), partial_inputs.begin() + kFirstDataInputIndex, partial_inputs.end());
  842. } else if (IsValueNode<KernelGraph>(return_input)) { // return node is kernel graph
  843. call_inputs.emplace_back(return_input);
  844. } else { // return node is value node
  845. KernelGraphPtr kernel_graph = NewKernelGraph();
  846. auto valid_inputs = kernel_graph->MutableValidInputs();
  847. MS_EXCEPTION_IF_NULL(valid_inputs);
  848. auto graph_inputs = kernel_graph->MutableInputs();
  849. MS_EXCEPTION_IF_NULL(graph_inputs);
  850. std::vector<AnfNodePtr> cnode_inputs = {return_input};
  851. for (auto real_input : real_inputs) {
  852. auto new_parameter = kernel_graph->NewParameter(real_input->abstract());
  853. valid_inputs->push_back(true);
  854. graph_inputs->push_back(new_parameter);
  855. cnode_inputs.push_back(new_parameter);
  856. }
  857. auto new_cnode = kernel_graph->NewCNode(cnode_inputs);
  858. new_cnode->set_abstract(cnode->abstract());
  859. std::vector<AnfNodePtr> return_inputs = {
  860. kernel_graph->NewValueNode(NewValueNode(std::make_shared<Primitive>(prim::kPrimReturn->name()))), new_cnode};
  861. auto return_node = kernel_graph->NewCNode(return_inputs);
  862. return_node->set_abstract(cnode->abstract());
  863. kernel_graph->set_return(return_node);
  864. call_inputs.push_back(std::make_shared<ValueNode>(kernel_graph));
  865. }
  866. // new call node inputs
  867. for (auto real_input : real_inputs) {
  868. auto parameter_for_input = CreateNewParameterFromCNode(real_input, graph);
  869. call_inputs.emplace_back(parameter_for_input);
  870. }
  871. auto call_node = graph->NewCNode(call_inputs);
  872. call_node->set_abstract(cnode->abstract());
  873. // update return input
  874. ret->set_input(kFirstDataInputIndex, call_node);
  875. }
  876. std::vector<AnfNodePtr> SessionBasic::CreateCallSwitchLayerInputs(const CNodePtr &cnode, KernelGraph *graph) {
  877. MS_EXCEPTION_IF_NULL(cnode);
  878. MS_EXCEPTION_IF_NULL(graph);
  879. std::vector<AnfNodePtr> cnode_inputs = {
  880. graph->NewValueNode(NewValueNode(std::make_shared<Primitive>(prim::kPrimCall->name())))};
  881. auto attr_input = cnode->input(kAnfPrimitiveIndex);
  882. MS_EXCEPTION_IF_NULL(attr_input);
  883. auto cnode_input = graph->GetBackendAnfByFrontAnf(attr_input);
  884. auto switch_layer_cnode = cnode_input->cast<CNodePtr>();
  885. MS_EXCEPTION_IF_NULL(switch_layer_cnode);
  886. std::vector<AnfNodePtr> switch_layer_inputs = {switch_layer_cnode->input(kAnfPrimitiveIndex),
  887. switch_layer_cnode->input(kFirstDataInputIndex)};
  888. auto make_tuple_node = switch_layer_cnode->input(kMakeTupleInSwitchLayerIndex);
  889. MS_EXCEPTION_IF_NULL(make_tuple_node);
  890. auto node = make_tuple_node->cast<CNodePtr>();
  891. MS_EXCEPTION_IF_NULL(node);
  892. auto make_tuple_inputs = node->inputs();
  893. // there are real inputs in call, should put it to make_tuple in switch_layer
  894. std::vector<AnfNodePtr> real_inputs;
  895. for (size_t idx = kFirstDataInputIndex; idx < cnode->inputs().size(); ++idx) {
  896. real_inputs.emplace_back(graph->GetBackendAnfByFrontAnf(cnode->input(idx)));
  897. }
  898. std::vector<AnfNodePtr> new_make_tuple_inputs = {
  899. graph->NewValueNode(NewValueNode(std::make_shared<Primitive>(prim::kPrimMakeTuple->name())))};
  900. for (size_t idx = kFirstDataInputIndex; idx < make_tuple_inputs.size(); idx++) {
  901. auto partial_idx = make_tuple_inputs[idx];
  902. MS_EXCEPTION_IF_NULL(cnode->abstract());
  903. std::vector<AnfNodePtr> new_partial_inputs;
  904. KernelGraphPtr partial_kernel_graph;
  905. // switch_layer node input is partial cnode
  906. if (AnfAlgo::CheckPrimitiveType(partial_idx, prim::kPrimPartial)) {
  907. auto partial_node = partial_idx->cast<CNodePtr>();
  908. MS_EXCEPTION_IF_NULL(partial_node);
  909. auto partial_input = partial_node->input(kFirstDataInputIndex);
  910. partial_kernel_graph = GetValueNode<KernelGraphPtr>(partial_input);
  911. new_partial_inputs = partial_node->inputs();
  912. } else if (IsValueNode<KernelGraph>(partial_idx)) { // switch_layer node input is kernel graph value node
  913. new_partial_inputs.emplace_back(NewValueNode(std::make_shared<Primitive>(prim::kPrimPartial->name())));
  914. new_partial_inputs.emplace_back(partial_idx);
  915. partial_kernel_graph = GetValueNode<KernelGraphPtr>(partial_idx);
  916. }
  917. // when branch in swich_layer return function
  918. MS_EXCEPTION_IF_NULL(partial_kernel_graph);
  919. auto ret = partial_kernel_graph->get_return();
  920. MS_EXCEPTION_IF_NULL(ret);
  921. auto return_input = ret->input(kFirstDataInputIndex);
  922. if (AnfAlgo::CheckPrimitiveType(return_input, prim::kPrimPartial) || return_input->isa<ValueNode>()) {
  923. ProcessNodeRetFunc(cnode, partial_kernel_graph.get(), real_inputs);
  924. }
  925. // partial node add input args
  926. new_partial_inputs.insert(new_partial_inputs.end(), real_inputs.begin(), real_inputs.end());
  927. // create new partial node
  928. auto new_partial = graph->NewCNode(new_partial_inputs);
  929. new_make_tuple_inputs.emplace_back(new_partial);
  930. }
  931. auto new_make_tuple = graph->NewCNode(new_make_tuple_inputs);
  932. auto abstract = make_tuple_node->abstract();
  933. if (abstract == nullptr) {
  934. abstract = std::make_shared<abstract::AbstractTuple>(AbstractBasePtrList());
  935. }
  936. new_make_tuple->set_abstract(abstract);
  937. switch_layer_inputs.emplace_back(new_make_tuple);
  938. auto new_switch_layer = graph->NewCNode(switch_layer_inputs);
  939. cnode_inputs.emplace_back(new_switch_layer);
  940. return cnode_inputs;
  941. }
  942. std::vector<AnfNodePtr> SessionBasic::CreateSwitchOrPartialNode(const CNodePtr &cnode, KernelGraph *graph) {
  943. MS_EXCEPTION_IF_NULL(cnode);
  944. MS_EXCEPTION_IF_NULL(graph);
  945. // create primitive of cnode:call(partial or switch or switch_layer)
  946. std::vector<AnfNodePtr> cnode_inputs = {
  947. graph->NewValueNode(NewValueNode(std::make_shared<Primitive>(prim::kPrimCall->name())))};
  948. auto attr_input = cnode->input(kAnfPrimitiveIndex);
  949. MS_EXCEPTION_IF_NULL(attr_input);
  950. auto cnode_input = graph->GetBackendAnfByFrontAnf(attr_input);
  951. if (cnode_input == nullptr) {
  952. MS_LOG(ERROR) << "CNode input[0] is CNode:" << attr_input->DebugString() << ", but input[0] has not been created.";
  953. return {};
  954. }
  955. // if the node is partial, insert the inputs of partial to the call
  956. if (AnfAlgo::CheckPrimitiveType(cnode_input, prim::kPrimPartial)) {
  957. auto partial_node = attr_input->cast<CNodePtr>();
  958. MS_EXCEPTION_IF_NULL(partial_node);
  959. auto partial_inputs = partial_node->inputs();
  960. (void)std::transform(partial_inputs.begin() + kFirstDataInputIndex, partial_inputs.end(),
  961. std::back_inserter(cnode_inputs), [&graph](const AnfNodePtr &node) {
  962. MS_EXCEPTION_IF_NULL(graph->GetBackendAnfByFrontAnf(node));
  963. return graph->GetBackendAnfByFrontAnf(node);
  964. });
  965. return cnode_inputs;
  966. } else if (AnfAlgo::CheckPrimitiveType(cnode_input, prim::kPrimSwitch)) {
  967. return CreateCallSwitchInputs(cnode, graph);
  968. } else if (AnfAlgo::CheckPrimitiveType(cnode_input, prim::kPrimSwitchLayer)) {
  969. return CreateCallSwitchLayerInputs(cnode, graph);
  970. }
  971. MS_LOG(ERROR) << "CNode:" << cnode->DebugString() << " input[0]" << cnode_input->DebugString()
  972. << "must be partial or switch or switch_layer.";
  973. return {};
  974. }
  975. std::vector<AnfNodePtr> SessionBasic::CreateValueNode(const CNodePtr &cnode, KernelGraph *graph) {
  976. MS_EXCEPTION_IF_NULL(cnode);
  977. MS_EXCEPTION_IF_NULL(graph);
  978. std::vector<AnfNodePtr> cnode_inputs;
  979. auto attr_input = cnode->input(kAnfPrimitiveIndex);
  980. MS_EXCEPTION_IF_NULL(attr_input);
  981. if (AnfAlgo::IsGraphKernel(cnode)) {
  982. auto fg = AnfAlgo::GetCNodeFuncGraphPtr(cnode);
  983. MS_EXCEPTION_IF_NULL(fg);
  984. auto new_fg = BasicClone(fg);
  985. cnode_inputs.push_back(std::make_shared<ValueNode>(new_fg));
  986. } else {
  987. // create primitive of cnode:call
  988. cnode_inputs = {graph->NewValueNode(NewValueNode(std::make_shared<Primitive>(prim::kPrimCall->name())))};
  989. // create a ValueNode<KernelGraph> as input of cnode:call
  990. if (graph->GetBackendAnfByFrontAnf(attr_input) != nullptr) {
  991. cnode_inputs.emplace_back(graph->GetBackendAnfByFrontAnf(attr_input));
  992. } else {
  993. auto new_value_node = CreateValueNodeKernelGraph(attr_input, graph);
  994. if (new_value_node != nullptr) {
  995. cnode_inputs.emplace_back(new_value_node);
  996. }
  997. }
  998. }
  999. return cnode_inputs;
  1000. }
  1001. void SessionBasic::CreateCNodeInputs(const CNodePtr &cnode, KernelGraph *graph, std::vector<AnfNodePtr> *cnode_inputs) {
  1002. MS_EXCEPTION_IF_NULL(cnode);
  1003. MS_EXCEPTION_IF_NULL(graph);
  1004. if (AnfAlgo::CheckPrimitiveType(cnode, prim::kPrimSwitch)) {
  1005. (void)cnode_inputs->emplace_back(graph->GetBackendAnfByFrontAnf(cnode->input(kFirstDataInputIndex)));
  1006. for (size_t index = kFirstBranchInSwitch; index < cnode->inputs().size(); index++) {
  1007. auto node_input = cnode->input(index);
  1008. auto switch_input = CreateSwitchInput(cnode, node_input, graph);
  1009. (void)cnode_inputs->emplace_back(switch_input);
  1010. }
  1011. } else {
  1012. for (size_t input_idx = kFirstDataInputIndex; input_idx < cnode->inputs().size(); input_idx++) {
  1013. auto anf = cnode->input(input_idx);
  1014. MS_EXCEPTION_IF_NULL(anf);
  1015. // anf has been created before
  1016. if (graph->GetBackendAnfByFrontAnf(anf) != nullptr) {
  1017. (void)cnode_inputs->emplace_back(graph->GetBackendAnfByFrontAnf(anf));
  1018. continue;
  1019. } else if (IsValueNode<None>(anf)) {
  1020. continue;
  1021. }
  1022. MS_LOG(EXCEPTION) << "Unexpected input[" << anf->DebugString() << "]";
  1023. }
  1024. }
  1025. }
  1026. CNodePtr SessionBasic::CreateNewCNode(const CNodePtr &cnode, KernelGraph *graph) {
  1027. MS_EXCEPTION_IF_NULL(cnode);
  1028. MS_EXCEPTION_IF_NULL(graph);
  1029. std::vector<AnfNodePtr> cnode_inputs;
  1030. auto attr_input = cnode->input(kAnfPrimitiveIndex);
  1031. MS_EXCEPTION_IF_NULL(attr_input);
  1032. if (IsValueNode<FuncGraph>(attr_input)) {
  1033. // cnode is a graph or a call
  1034. cnode_inputs = CreateValueNode(cnode, graph);
  1035. } else if (attr_input->isa<CNode>()) {
  1036. // cnode ia a call (partial/switch/switch_layer)
  1037. // 1. take the args of call to the partial node, as the real_args to call switch's or switch_layer's child graph
  1038. // 2. the call in frontend is map to the partial/switch/switch_layer in backend and haven't been created
  1039. cnode_inputs = CreateSwitchOrPartialNode(cnode, graph);
  1040. if (cnode_inputs.empty()) {
  1041. MS_LOG_ERROR << "Create switch or partial failed, cnode:" << cnode->DebugString();
  1042. return nullptr;
  1043. }
  1044. } else {
  1045. // get primitive of old node
  1046. auto prim = AnfAlgo::GetCNodePrimitive(cnode);
  1047. MS_EXCEPTION_IF_NULL(prim);
  1048. // push attr to inputs[0] of new cnode
  1049. cnode_inputs = {graph->NewValueNode(NewValueNode(std::make_shared<Primitive>(*prim)))};
  1050. }
  1051. // handle inputs of cnode except primitive
  1052. CreateCNodeInputs(cnode, graph, &cnode_inputs);
  1053. TraceGuard trace_guard(std::make_shared<TraceCopy>(cnode->debug_info()));
  1054. auto new_cnode = graph->NewCNode(cnode_inputs);
  1055. // if the cnode is call switch, remove call
  1056. if (new_cnode->inputs().size() > 1) {
  1057. auto first_input = new_cnode->input(kFirstDataInputIndex);
  1058. MS_EXCEPTION_IF_NULL(first_input);
  1059. if (AnfAlgo::CheckPrimitiveType(new_cnode, prim::kPrimCall) &&
  1060. AnfAlgo::CheckPrimitiveType(first_input, prim::kPrimSwitch)) {
  1061. new_cnode = first_input->cast<CNodePtr>();
  1062. }
  1063. if (AnfAlgo::CheckPrimitiveType(new_cnode, prim::kPrimCall) &&
  1064. AnfAlgo::CheckPrimitiveType(first_input, prim::kPrimSwitchLayer)) {
  1065. auto abstract = cnode->abstract();
  1066. new_cnode = first_input->cast<CNodePtr>();
  1067. new_cnode->set_abstract(abstract);
  1068. }
  1069. }
  1070. return new_cnode;
  1071. }
  1072. ValueNodePtr SessionBasic::CreateValueNodeKernelGraph(const AnfNodePtr &anf, KernelGraph *graph) {
  1073. MS_EXCEPTION_IF_NULL(anf);
  1074. MS_EXCEPTION_IF_NULL(graph);
  1075. auto value_node = anf->cast<ValueNodePtr>();
  1076. MS_EXCEPTION_IF_NULL(value_node);
  1077. auto sub_func_graph = AnfAlgo::GetValueNodeFuncGraph(anf);
  1078. MS_EXCEPTION_IF_NULL(sub_func_graph);
  1079. if (front_backend_graph_map_.find(sub_func_graph.get()) == front_backend_graph_map_.end()) {
  1080. MS_LOG(EXCEPTION) << "FuncGraph: " << sub_func_graph->ToString() << " has not been transformed to KernelGraph.";
  1081. }
  1082. auto sub_kernel_graph = front_backend_graph_map_[sub_func_graph.get()];
  1083. ValueNodePtr new_value_node = std::make_shared<ValueNode>(sub_kernel_graph);
  1084. new_value_node->set_abstract(value_node->abstract());
  1085. // create new kernel_info of new value_node
  1086. auto kernel_info = std::make_shared<device::KernelInfo>();
  1087. new_value_node->set_kernel_info(kernel_info);
  1088. // create kernel_build_info for new value node
  1089. auto kernel_build_info_builder = std::make_shared<kernel::KernelBuildInfo::KernelBuildInfoBuilder>();
  1090. AnfAlgo::SetSelectKernelBuildInfo(kernel_build_info_builder->Build(), new_value_node.get());
  1091. AnfAlgo::SetGraphId(graph->graph_id(), new_value_node.get());
  1092. graph->FrontBackendlMapAdd(anf, new_value_node);
  1093. return new_value_node;
  1094. }
  1095. ParameterPtr SessionBasic::CreateNewParameter(const AnfNodePtr &anf, KernelGraph *graph) {
  1096. MS_EXCEPTION_IF_NULL(anf);
  1097. MS_EXCEPTION_IF_NULL(graph);
  1098. if (!anf->isa<Parameter>()) {
  1099. MS_LOG(EXCEPTION) << "Anf[" << anf->DebugString() << "] is not a parameter";
  1100. }
  1101. auto param_value = GetParamDefaultValue(anf);
  1102. ParameterPtr new_parameter = nullptr;
  1103. // if parameter's python parameter has been exist a backend parameter, reuse the exist parameter
  1104. if (param_value != nullptr) {
  1105. new_parameter = param_value->parameter();
  1106. if (new_parameter == nullptr) {
  1107. TraceGuard trace_guard(std::make_shared<TraceCopy>(anf->debug_info()));
  1108. new_parameter = graph->NewParameter(anf->cast<ParameterPtr>());
  1109. param_value->set_parameter(new_parameter);
  1110. }
  1111. } else {
  1112. TraceGuard trace_guard(std::make_shared<TraceCopy>(anf->debug_info()));
  1113. new_parameter = graph->NewParameter(anf->cast<ParameterPtr>());
  1114. }
  1115. new_parameter->IncreaseUsedGraphCount();
  1116. return new_parameter;
  1117. }
  1118. KernelGraphPtr SessionBasic::ConstructKernelGraph(const AnfNodePtrList &lst, const AnfNodePtrList &outputs) {
  1119. std::unordered_map<AnfNodePtr, AnfNodePtr> other_graph_cnode;
  1120. auto graph = NewKernelGraph();
  1121. MS_EXCEPTION_IF_NULL(graph);
  1122. MS_LOG(INFO) << "Create graph: " << graph->graph_id();
  1123. for (const auto &node : lst) {
  1124. MS_EXCEPTION_IF_NULL(node);
  1125. MS_LOG(DEBUG) << "Start create new cnode, node = " << node->DebugString();
  1126. if (!node->isa<CNode>()) {
  1127. MS_LOG(EXCEPTION) << "Node " << node->DebugString() << " is not CNode";
  1128. }
  1129. auto cnode = node->cast<CNodePtr>();
  1130. MS_EXCEPTION_IF_NULL(cnode);
  1131. // create a new cnode object
  1132. auto new_cnode = CreateNewCNode(cnode, graph.get(), &other_graph_cnode);
  1133. MS_EXCEPTION_IF_NULL(new_cnode);
  1134. new_cnode->set_abstract(cnode->abstract());
  1135. new_cnode->set_scope(cnode->scope());
  1136. if (IsPrimitiveCNode(cnode, prim::kPrimLoad)) {
  1137. new_cnode->set_fullname_with_scope(cnode->input(kFirstDataInputIndex)->fullname_with_scope());
  1138. }
  1139. // record map relations between anf from ME and new anf node used in backend
  1140. graph->FrontBackendlMapAdd(node, new_cnode);
  1141. }
  1142. // add a make_tuple at the end of graph as output
  1143. graph->set_output(ConstructOutput(outputs, graph));
  1144. MS_EXCEPTION_IF_NULL(context_);
  1145. FuncGraphManagerPtr manager = MakeManager({graph});
  1146. if (manager) {
  1147. manager->AddFuncGraph(graph);
  1148. graph->set_manager(manager);
  1149. }
  1150. graph->SetExecOrderByDefault();
  1151. if (ExistSummaryNode(graph.get())) {
  1152. graph->set_summary_node_exist(true);
  1153. }
  1154. // Update Graph Dynamic Shape Attr
  1155. UpdateGraphDynamicShapeAttr(NOT_NULL(graph));
  1156. UnifyMindIR(graph);
  1157. opt::BackendCommonOptimization(graph);
  1158. graph->SetInputNodes();
  1159. auto input_nodes = graph->input_nodes();
  1160. for (auto input_node : input_nodes) {
  1161. if (input_node->isa<Parameter>()) {
  1162. auto node_ptr = input_node->cast<ParameterPtr>();
  1163. MS_EXCEPTION_IF_NULL(node_ptr);
  1164. if (!IsUsedByRealKernel(manager, input_node)) {
  1165. node_ptr->set_used_by_real_kernel(false);
  1166. }
  1167. auto shape = node_ptr->Shape();
  1168. if (IsShapeDynamic(shape->cast<abstract::ShapePtr>())) {
  1169. node_ptr->set_used_by_dynamic_kernel(true);
  1170. }
  1171. }
  1172. }
  1173. graph->SetOptimizerFlag();
  1174. return graph;
  1175. }
  1176. GraphInfo SessionBasic::GetSingleOpGraphInfo(const CNodePtr &kernel,
  1177. const std::vector<tensor::TensorPtr> &input_tensors) {
  1178. MS_EXCEPTION_IF_NULL(kernel);
  1179. auto prim = AnfAlgo::GetCNodePrimitive(kernel);
  1180. MS_EXCEPTION_IF_NULL(prim);
  1181. const AbstractBasePtr &abstract = kernel->abstract();
  1182. MS_EXCEPTION_IF_NULL(abstract);
  1183. size_t output_num = AnfAlgo::GetOutputTensorNum(kernel);
  1184. GraphInfo graph_info;
  1185. // get input tensor info
  1186. for (const auto &tensor : input_tensors) {
  1187. MS_EXCEPTION_IF_NULL(tensor);
  1188. auto tensor_shape = tensor->shape();
  1189. (void)std::for_each(tensor_shape.begin(), tensor_shape.end(),
  1190. [&](const auto &dim) { (void)graph_info.append(std::to_string(dim) + "_"); });
  1191. (void)graph_info.append(std::to_string(tensor->data_type()) + "_");
  1192. if (tensor->device_address() != nullptr) {
  1193. const auto type_id = std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address())->type_id();
  1194. (void)graph_info.append(std::to_string(type_id) + "_");
  1195. const auto format = std::dynamic_pointer_cast<device::DeviceAddress>(tensor->device_address())->format();
  1196. (void)graph_info.append(format + "_");
  1197. }
  1198. for (const auto &padding_type : tensor->padding_type()) {
  1199. (void)graph_info.append(std::to_string(padding_type) + "_");
  1200. }
  1201. }
  1202. // get attr info
  1203. const auto &attr_map = prim->attrs();
  1204. (void)std::for_each(attr_map.begin(), attr_map.end(), [&](const auto &element) {
  1205. if (element.second->ToString().empty()) {
  1206. return;
  1207. }
  1208. (void)graph_info.append(element.second->ToString() + "_");
  1209. });
  1210. auto build_shape = abstract->BuildShape();
  1211. MS_EXCEPTION_IF_NULL(build_shape);
  1212. (void)graph_info.append(build_shape->ToString() + "_");
  1213. for (size_t output_index = 0; output_index < output_num; output_index += 1) {
  1214. const auto output_type = AnfAlgo::GetOutputInferDataType(kernel, output_index);
  1215. (void)graph_info.append(std::to_string(output_type) + "_");
  1216. }
  1217. graph_info.append(prim->id());
  1218. return graph_info;
  1219. }
  1220. void SessionBasic::GetSingleOpRunInfo(const CNodePtr cnode, OpRunInfo *run_info) {
  1221. MS_EXCEPTION_IF_NULL(cnode);
  1222. MS_EXCEPTION_IF_NULL(run_info);
  1223. auto primitive = AnfAlgo::GetCNodePrimitive(cnode);
  1224. run_info->primitive = primitive;
  1225. run_info->op_name = primitive->name();
  1226. const auto &abstract = cnode->abstract();
  1227. if (abstract == nullptr) {
  1228. MS_LOG(EXCEPTION) << "Abstract is nullptr, node = " << cnode->DebugString();
  1229. }
  1230. run_info->abstract = abstract;
  1231. const auto &shape = abstract->BuildShape();
  1232. MS_EXCEPTION_IF_NULL(shape);
  1233. const auto &shape_info = shape->ToString();
  1234. if (shape_info.find("-1") != string::npos) {
  1235. run_info->is_dynamic_shape = true;
  1236. }
  1237. }
  1238. TensorPtr SessionBasic::GetValueNodeOutputTensor(const AnfNodePtr &node, size_t output_index) {
  1239. MS_EXCEPTION_IF_NULL(node);
  1240. if (!node->isa<ValueNode>()) {
  1241. return nullptr;
  1242. }
  1243. auto value_node = node->cast<ValueNodePtr>();
  1244. MS_EXCEPTION_IF_NULL(value_node);
  1245. auto value = GetValueNode(value_node);
  1246. MS_EXCEPTION_IF_NULL(value);
  1247. if (value->isa<ValueTuple>()) {
  1248. auto value_tuple = value->cast<ValueTuplePtr>();
  1249. MS_EXCEPTION_IF_NULL(value_tuple);
  1250. if (output_index >= value_tuple->size()) {
  1251. MS_LOG(EXCEPTION) << "Index " << output_index << "is out of value tuple range";
  1252. }
  1253. auto tensor_value = value_tuple->value()[output_index];
  1254. if (tensor_value->isa<tensor::Tensor>()) {
  1255. return tensor_value->cast<tensor::TensorPtr>();
  1256. }
  1257. } else if (value->isa<tensor::Tensor>()) {
  1258. if (output_index != 0) {
  1259. MS_LOG(EXCEPTION) << "Index should be 0 for Tensor ValueNode, but is " << output_index;
  1260. }
  1261. return value->cast<TensorPtr>();
  1262. }
  1263. return nullptr;
  1264. }
  1265. TensorPtr SessionBasic::GetParameterOutputTensor(const AnfNodePtr &node,
  1266. const std::map<AnfNodePtr, size_t> &parameter_index,
  1267. const std::vector<tensor::TensorPtr> &graph_inputs) {
  1268. MS_EXCEPTION_IF_NULL(node);
  1269. if (!node->isa<Parameter>()) {
  1270. return nullptr;
  1271. }
  1272. const auto &iter = parameter_index.find(node);
  1273. if (iter == parameter_index.end()) {
  1274. MS_LOG(EXCEPTION) << "Can not find parameter input of cnode, parameter = " << node->DebugString();
  1275. }
  1276. const size_t index = iter->second;
  1277. if (index >= graph_inputs.size()) {
  1278. MS_LOG(EXCEPTION) << "Parameter index is greater than size of graph's input tensor, parameter index = " << index
  1279. << ", input tensor size = " << graph_inputs.size();
  1280. }
  1281. return graph_inputs[index];
  1282. }
  1283. TensorPtr SessionBasic::GetCNodeOutputTensor(const KernelWithIndex &kernel_with_index,
  1284. const std::map<KernelWithIndex, tensor::TensorPtr> &op_output) {
  1285. const auto &iter = op_output.find(kernel_with_index);
  1286. if (iter == op_output.end()) {
  1287. MS_LOG(EXCEPTION) << "Can not find output tensor of cnode, node = " << kernel_with_index.first->DebugString();
  1288. }
  1289. return iter->second;
  1290. }
  1291. void SessionBasic::GetOpInputTensors(const CNodePtr &cnode,
  1292. const std::map<KernelWithIndex, tensor::TensorPtr> &op_output,
  1293. const std::map<AnfNodePtr, size_t> &parameter_index,
  1294. const std::vector<tensor::TensorPtr> &graph_inputs,
  1295. InputTensorInfo *input_tensor_info) {
  1296. MS_EXCEPTION_IF_NULL(cnode);
  1297. MS_EXCEPTION_IF_NULL(input_tensor_info);
  1298. for (size_t i = 1; i < cnode->inputs().size(); i += 1) {
  1299. const auto &input = cnode->input(i);
  1300. auto kernel_with_index = AnfAlgo::VisitKernel(input, 0);
  1301. auto real_input = kernel_with_index.first;
  1302. MS_EXCEPTION_IF_NULL(real_input);
  1303. tensor::TensorPtr tensor = nullptr;
  1304. if (real_input->isa<ValueNode>()) {
  1305. if (HasAbstractMonad(real_input)) {
  1306. continue;
  1307. }
  1308. tensor = GetValueNodeOutputTensor(real_input, kernel_with_index.second);
  1309. } else if (real_input->isa<Parameter>()) {
  1310. tensor = GetParameterOutputTensor(real_input, parameter_index, graph_inputs);
  1311. } else if (real_input->isa<CNode>()) {
  1312. tensor = GetCNodeOutputTensor(kernel_with_index, op_output);
  1313. input_tensor_info->input_kernel.insert(kernel_with_index);
  1314. } else {
  1315. MS_LOG(EXCEPTION) << "Invalid input node, node = " << real_input->DebugString();
  1316. }
  1317. MS_EXCEPTION_IF_NULL(tensor);
  1318. MS_LOG(DEBUG) << "Get" << i << "th input tensor of " << cnode->fullname_with_scope() << " from "
  1319. << real_input->fullname_with_scope() << "-" << kernel_with_index.second;
  1320. input_tensor_info->input_tensors_mask.emplace_back(tensor->is_parameter() ? kParameterWeightTensorMask
  1321. : kParameterDataTensorMask);
  1322. input_tensor_info->input_tensors.emplace_back(tensor);
  1323. }
  1324. }
  1325. bool SessionBasic::CreateCNodeOfKernelGraph(const AnfNodePtr &node, KernelGraph *graph) {
  1326. MS_EXCEPTION_IF_NULL(node);
  1327. MS_EXCEPTION_IF_NULL(graph);
  1328. auto cnode = node->cast<CNodePtr>();
  1329. MS_EXCEPTION_IF_NULL(cnode);
  1330. // create a new cnode object
  1331. auto new_cnode = CreateNewCNode(cnode, graph);
  1332. if (new_cnode == nullptr) {
  1333. return false;
  1334. }
  1335. new_cnode->set_abstract(cnode->abstract());
  1336. std::string fullname;
  1337. if (cnode->input(kAnfPrimitiveIndex)->isa<CNode>()) {
  1338. fullname = cnode->input(kAnfPrimitiveIndex)->fullname_with_scope();
  1339. } else if (IsPrimitiveCNode(cnode, prim::kPrimLoad)) {
  1340. fullname = cnode->input(kFirstDataInputIndex)->fullname_with_scope();
  1341. } else {
  1342. fullname = cnode->fullname_with_scope();
  1343. }
  1344. new_cnode->set_fullname_with_scope(fullname);
  1345. new_cnode->set_scope(cnode->scope());
  1346. graph->FrontBackendlMapAdd(node, new_cnode);
  1347. if (AnfAlgo::CheckPrimitiveType(new_cnode, prim::kPrimReturn)) {
  1348. graph->set_return(new_cnode);
  1349. }
  1350. return true;
  1351. }
  1352. std::shared_ptr<KernelGraph> SessionBasic::ConstructKernelGraph(const FuncGraphPtr &func_graph,
  1353. std::vector<KernelGraphPtr> *all_out_graph) {
  1354. MS_EXCEPTION_IF_NULL(func_graph);
  1355. MS_EXCEPTION_IF_NULL(all_out_graph);
  1356. auto node_list = TopoSort(func_graph->get_return());
  1357. auto graph = NewKernelGraph();
  1358. MS_EXCEPTION_IF_NULL(graph);
  1359. front_backend_graph_map_[func_graph.get()] = graph;
  1360. MS_LOG(INFO) << "Create graph: " << graph->graph_id();
  1361. for (const auto &node : node_list) {
  1362. MS_EXCEPTION_IF_NULL(node);
  1363. MS_LOG(DEBUG) << "Start create new cnode, node = " << node->DebugString();
  1364. // Create parameter
  1365. if (node->isa<Parameter>()) {
  1366. auto graph_inputs = graph->MutableInputs();
  1367. MS_EXCEPTION_IF_NULL(graph_inputs);
  1368. auto new_parameter = CreateNewParameter(node, graph.get());
  1369. graph_inputs->push_back(new_parameter);
  1370. graph->FrontBackendlMapAdd(node, new_parameter);
  1371. continue;
  1372. }
  1373. // Create value node
  1374. if (node->isa<ValueNode>()) {
  1375. // Create common value node
  1376. if (!IsValueNode<FuncGraph>(node)) {
  1377. (void)CreateNewValueNode(node, graph.get());
  1378. continue;
  1379. }
  1380. // Create child kernel graph according ValueNode<FuncGraph>
  1381. FuncGraphPtr child_graph = AnfAlgo::GetValueNodeFuncGraph(node);
  1382. if (front_backend_graph_map_.find(child_graph.get()) == front_backend_graph_map_.end()) {
  1383. (void)ConstructKernelGraph(child_graph, all_out_graph);
  1384. }
  1385. (void)CreateValueNodeKernelGraph(node, graph.get());
  1386. continue;
  1387. }
  1388. // Create cnode
  1389. if (!CreateCNodeOfKernelGraph(node, graph.get())) {
  1390. DumpIR("construct_kernel_graph_fail.ir", func_graph);
  1391. MS_LOG(EXCEPTION) << "Construct func graph " << func_graph->ToString() << " failed."
  1392. << trace::DumpSourceLines(node);
  1393. }
  1394. }
  1395. AddParameterToGraphInputs(func_graph->parameters(), graph.get());
  1396. FuncGraphManagerPtr manager = MakeManager({graph});
  1397. auto input_nodes = graph->inputs();
  1398. for (auto input_node : input_nodes) {
  1399. if (input_node->isa<Parameter>()) {
  1400. auto node_ptr = input_node->cast<ParameterPtr>();
  1401. MS_EXCEPTION_IF_NULL(node_ptr);
  1402. if (!IsUsedByRealKernel(manager, input_node)) {
  1403. node_ptr->set_used_by_real_kernel(false);
  1404. }
  1405. auto shape = node_ptr->Shape();
  1406. if (IsShapeDynamic(shape->cast<abstract::ShapePtr>())) {
  1407. node_ptr->set_used_by_dynamic_kernel(true);
  1408. }
  1409. }
  1410. }
  1411. graph->SetExecOrderByDefault();
  1412. if (ExistSummaryNode(graph.get())) {
  1413. graph->set_summary_node_exist(true);
  1414. }
  1415. all_out_graph->push_back(graph);
  1416. return graph;
  1417. }
  1418. void SessionBasic::AddParameterToGraphInputs(const std::vector<AnfNodePtr> &parameters, KernelGraph *graph) {
  1419. MS_EXCEPTION_IF_NULL(graph);
  1420. auto graph_inputs = graph->MutableInputs();
  1421. MS_EXCEPTION_IF_NULL(graph_inputs);
  1422. graph_inputs->clear();
  1423. for (auto &parameter : parameters) {
  1424. MS_EXCEPTION_IF_NULL(parameter);
  1425. auto backend_parameter = graph->GetBackendAnfByFrontAnf(parameter);
  1426. if (backend_parameter == nullptr) {
  1427. // for example "def f(x,y,z) {return x + y}", parameter z in unused
  1428. auto new_parameter = CreateNewParameter(parameter, graph);
  1429. graph_inputs->push_back(new_parameter);
  1430. MS_LOG(INFO) << "Can't find parameter:" << parameter->DebugString();
  1431. continue;
  1432. }
  1433. graph_inputs->push_back(backend_parameter);
  1434. }
  1435. }
  1436. void SessionBasic::UpdateOutputs(const std::shared_ptr<KernelGraph> &kernel_graph, VectorRef *const outputs,
  1437. const std::vector<tensor::TensorPtr> &input_tensors) const {
  1438. MS_EXCEPTION_IF_NULL(kernel_graph);
  1439. MS_EXCEPTION_IF_NULL(outputs);
  1440. std::map<tensor::TensorPtr, session::KernelWithIndex> tensor_to_node;
  1441. KernelMapTensor node_to_tensor;
  1442. auto anf_outputs = kernel_graph->outputs();
  1443. for (auto &item : anf_outputs) {
  1444. MS_EXCEPTION_IF_NULL(item);
  1445. MS_LOG(INFO) << "Update output[" << item->DebugString() << "]";
  1446. outputs->emplace_back(CreateNodeOutputTensors(item, kernel_graph, input_tensors, &tensor_to_node, &node_to_tensor));
  1447. }
  1448. auto ms_context = MsContext::GetInstance();
  1449. MS_EXCEPTION_IF_NULL(ms_context);
  1450. for (auto &item : tensor_to_node) {
  1451. auto &tensor = item.first;
  1452. auto &node = item.second.first;
  1453. auto &output_index = item.second.second;
  1454. DeviceAddressPtr address = nullptr;
  1455. if (ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) == kPynativeMode &&
  1456. ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER)) {
  1457. address = AnfAlgo::GetMutableOutputAddr(node, output_index, false);
  1458. } else {
  1459. address = AnfAlgo::GetMutableOutputAddr(node, output_index);
  1460. }
  1461. MS_EXCEPTION_IF_NULL(tensor);
  1462. tensor->set_device_address(address);
  1463. tensor->SetNeedWait(false);
  1464. MS_LOG(DEBUG) << "Debug address: Output tensor obj " << tensor.get() << ", tensor id " << tensor->id()
  1465. << ", device address " << tensor->device_address().get();
  1466. if (ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) != kPynativeMode) {
  1467. tensor->data_sync(false);
  1468. tensor->set_sync_status(kNeedSyncHostToDevice);
  1469. }
  1470. }
  1471. }
  1472. void SessionBasic::UpdateOutputAbstract(const std::shared_ptr<KernelGraph> &kernel_graph,
  1473. OpRunInfo *op_run_info) const {
  1474. MS_EXCEPTION_IF_NULL(kernel_graph);
  1475. MS_EXCEPTION_IF_NULL(op_run_info);
  1476. const auto &kernels = kernel_graph->execution_order();
  1477. for (const auto &kernel : kernels) {
  1478. MS_EXCEPTION_IF_NULL(kernel);
  1479. if (AnfAlgo::GetCNodeName(kernel) == op_run_info->op_name) {
  1480. op_run_info->abstract = kernel->abstract();
  1481. }
  1482. }
  1483. }
  1484. std::vector<tensor::TensorPtr> SessionBasic::GetInputNeedLockTensors(const GraphId &graph_id,
  1485. const std::vector<tensor::TensorPtr> &inputs) {
  1486. auto graph = GetGraph(graph_id);
  1487. MS_EXCEPTION_IF_NULL(graph);
  1488. if (!graph->has_optimizer()) {
  1489. return {};
  1490. }
  1491. std::vector<tensor::TensorPtr> result;
  1492. for (auto &tensor : inputs) {
  1493. if (!tensor->IsGraphOutput()) {
  1494. result.emplace_back(tensor);
  1495. }
  1496. }
  1497. return result;
  1498. }
  1499. void SessionBasic::CreateOutputTensors(const GraphId &graph_id, const std::vector<tensor::TensorPtr> &input_tensors,
  1500. VectorRef *outputs,
  1501. std::map<tensor::TensorPtr, session::KernelWithIndex> *tensor_to_node) {
  1502. auto kernel_graph = GetGraph(graph_id);
  1503. MS_EXCEPTION_IF_NULL(kernel_graph);
  1504. MS_EXCEPTION_IF_NULL(outputs);
  1505. MS_EXCEPTION_IF_NULL(tensor_to_node);
  1506. auto anf_outputs = kernel_graph->outputs();
  1507. KernelMapTensor node_to_tensor;
  1508. for (auto &item : anf_outputs) {
  1509. MS_EXCEPTION_IF_NULL(item);
  1510. MS_LOG(INFO) << "Create node output[" << item->DebugString() << "]";
  1511. outputs->emplace_back(CreateNodeOutputTensors(item, kernel_graph, input_tensors, tensor_to_node, &node_to_tensor));
  1512. }
  1513. }
  1514. void SessionBasic::UpdateOutputTensors(const VectorRef *outputs,
  1515. const std::map<tensor::TensorPtr, session::KernelWithIndex> &tensor_to_node) {
  1516. MS_EXCEPTION_IF_NULL(outputs);
  1517. for (const auto &item : *outputs) {
  1518. if (utils::isa<VectorRefPtr>(item)) {
  1519. const auto &vector_ref = utils::cast<VectorRef>(item);
  1520. UpdateOutputTensors(&vector_ref, tensor_to_node);
  1521. } else if (utils::isa<tensor::TensorPtr>(item)) {
  1522. const auto &tensor = utils::cast<tensor::TensorPtr>(item);
  1523. MS_EXCEPTION_IF_NULL(tensor);
  1524. const auto &iter = tensor_to_node.find(tensor);
  1525. if (iter != tensor_to_node.end()) {
  1526. const auto &node = iter->second.first;
  1527. const auto &output_index = iter->second.second;
  1528. const auto &address = AnfAlgo::GetMutableOutputAddr(node, output_index);
  1529. tensor->set_device_address(address);
  1530. if (AnfAlgo::IsDynamicShape(node)) {
  1531. const auto &updated_shape = AnfAlgo::GetOutputInferShape(node, output_index);
  1532. ShapeVector int_shape;
  1533. std::transform(updated_shape.begin(), updated_shape.end(), std::back_inserter(int_shape), SizeToInt);
  1534. tensor->set_shape(int_shape);
  1535. }
  1536. }
  1537. if (tensor->NeedSyncDeviceToHostImmediately()) {
  1538. tensor->data_sync(false);
  1539. tensor->set_device_address(nullptr);
  1540. tensor->set_sync_status(kNeedSyncHostToDevice);
  1541. }
  1542. }
  1543. }
  1544. }
  1545. void SessionBasic::GetModelInputsInfo(uint32_t graph_id, std::vector<tensor::TensorPtr> *inputs,
  1546. std::vector<std::string> *inputs_name) const {
  1547. MS_LOG(INFO) << "Start get model inputs, graph id : " << graph_id;
  1548. auto kernel_graph = GetGraph(graph_id);
  1549. MS_EXCEPTION_IF_NULL(kernel_graph);
  1550. MS_EXCEPTION_IF_NULL(inputs);
  1551. MS_EXCEPTION_IF_NULL(inputs_name);
  1552. auto kernel_graph_inputs = kernel_graph->inputs();
  1553. vector<ParameterPtr> paras;
  1554. // find parameters of graph inputs
  1555. for (size_t i = 0; i < kernel_graph_inputs.size(); ++i) {
  1556. if (!kernel_graph_inputs[i]->isa<Parameter>()) {
  1557. MS_LOG(ERROR) << "Kernel graph inputs have anfnode which is not Parameter.";
  1558. continue;
  1559. }
  1560. auto parameter = kernel_graph_inputs[i]->cast<ParameterPtr>();
  1561. if (!AnfAlgo::IsParameterWeight(parameter)) {
  1562. vector<int64_t> input_shape;
  1563. auto parameter_shape = AnfAlgo::GetOutputDeviceShape(parameter, 0);
  1564. (void)std::transform(parameter_shape.begin(), parameter_shape.end(), std::back_inserter(input_shape),
  1565. [](const size_t dim) { return SizeToLong(dim); });
  1566. auto kernel_build_info = AnfAlgo::GetSelectKernelBuildInfo(parameter);
  1567. auto data_type = kernel_build_info->GetOutputDeviceType(0);
  1568. auto ms_tensor = std::make_shared<tensor::Tensor>(data_type, input_shape);
  1569. inputs->push_back(ms_tensor);
  1570. inputs_name->push_back(parameter->name());
  1571. }
  1572. }
  1573. }
  1574. void SessionBasic::GetModelOutputsInfo(uint32_t graph_id, std::vector<tensor::TensorPtr> *outputs,
  1575. std::vector<std::string> *output_names) const {
  1576. std::vector<tensor::TensorPtr> inputs;
  1577. std::vector<std::string> input_names;
  1578. GetModelInputsInfo(graph_id, &inputs, &input_names);
  1579. auto kernel_graph = GetGraph(graph_id);
  1580. MS_EXCEPTION_IF_NULL(kernel_graph);
  1581. MS_EXCEPTION_IF_NULL(outputs);
  1582. MS_EXCEPTION_IF_NULL(output_names);
  1583. VectorRef vector_outputs;
  1584. std::map<tensor::TensorPtr, session::KernelWithIndex> tensor_to_node;
  1585. KernelMapTensor node_to_tensor;
  1586. auto anf_outputs = kernel_graph->outputs();
  1587. for (auto &item : anf_outputs) {
  1588. MS_EXCEPTION_IF_NULL(item);
  1589. MS_LOG(INFO) << "Create node output[" << item->DebugString() << "]";
  1590. vector_outputs.emplace_back(CreateNodeOutputTensors(item, kernel_graph, inputs, &tensor_to_node, &node_to_tensor));
  1591. }
  1592. *outputs = TransformVectorRefToMultiTensor(vector_outputs);
  1593. for (size_t i = 0; i < outputs->size(); i++) {
  1594. output_names->push_back("output" + std::to_string(i));
  1595. }
  1596. }
  1597. void SessionBasic::RegisterSummaryCallBackFunc(const CallBackFunc &callback) {
  1598. MS_EXCEPTION_IF_NULL(callback);
  1599. summary_callback_ = callback;
  1600. }
  1601. void SessionBasic::SetSummaryNodes(KernelGraph *graph) {
  1602. MS_LOG(DEBUG) << "Update summary Start";
  1603. MS_EXCEPTION_IF_NULL(graph);
  1604. if (!graph->summary_node_exist()) {
  1605. return;
  1606. }
  1607. auto summary = graph->summary_nodes();
  1608. auto apply_list = TopoSort(graph->get_return());
  1609. for (auto &n : apply_list) {
  1610. MS_EXCEPTION_IF_NULL(n);
  1611. if (IsPrimitiveCNode(n, prim::kPrimScalarSummary) || IsPrimitiveCNode(n, prim::kPrimTensorSummary) ||
  1612. IsPrimitiveCNode(n, prim::kPrimImageSummary) || IsPrimitiveCNode(n, prim::kPrimHistogramSummary)) {
  1613. auto cnode = n->cast<CNodePtr>();
  1614. MS_EXCEPTION_IF_NULL(cnode);
  1615. if (cnode->inputs().size() <= kSummaryGetItem) {
  1616. MS_LOG(EXCEPTION) << "The node Summary should have 2 inputs at least!";
  1617. }
  1618. auto node = cnode->input(kSummaryGetItem);
  1619. MS_EXCEPTION_IF_NULL(node);
  1620. auto item_with_index = AnfAlgo::VisitKernelWithReturnType(node, 0, true);
  1621. MS_EXCEPTION_IF_NULL(item_with_index.first);
  1622. if (!AnfAlgo::IsRealKernel(item_with_index.first)) {
  1623. MS_LOG(EXCEPTION) << "Unexpected node:" << item_with_index.first->DebugString();
  1624. }
  1625. summary[n->fullname_with_scope()] = item_with_index;
  1626. }
  1627. }
  1628. graph->set_summary_nodes(summary);
  1629. MS_LOG(DEBUG) << "Update summary end size: " << summary.size();
  1630. }
  1631. void SessionBasic::Summary(KernelGraph *graph) {
  1632. if (summary_callback_ == nullptr) {
  1633. return;
  1634. }
  1635. MS_EXCEPTION_IF_NULL(graph);
  1636. bool exist_summary = graph->summary_node_exist();
  1637. if (!exist_summary) {
  1638. return;
  1639. }
  1640. static bool is_first = true;
  1641. if (is_first && !IsSupportSummary()) {
  1642. is_first = false;
  1643. MS_LOG(ERROR) << "The Summary operator can not collect data correctly. Detail: the data sink mode is used and the"
  1644. " sink size(in model.train() python api) is not equal to 1.";
  1645. }
  1646. SetSummaryNodes(graph);
  1647. auto summary_outputs = graph->summary_nodes();
  1648. std::map<std::string, tensor::TensorPtr> params_list;
  1649. // fetch outputs apply kernel in session & run callback functions
  1650. for (auto &output_item : summary_outputs) {
  1651. auto node = output_item.second.first;
  1652. size_t index = IntToSize(output_item.second.second);
  1653. auto address = AnfAlgo::GetOutputAddr(node, index);
  1654. auto shape = AnfAlgo::GetOutputInferShape(node, index);
  1655. TypeId type_id = AnfAlgo::GetOutputInferDataType(node, index);
  1656. std::vector<int64_t> temp_shape;
  1657. (void)std::copy(shape.begin(), shape.end(), std::back_inserter(temp_shape));
  1658. tensor::TensorPtr tensor = std::make_shared<tensor::Tensor>(type_id, temp_shape);
  1659. MS_EXCEPTION_IF_NULL(address);
  1660. if (!address->GetPtr()) {
  1661. continue;
  1662. }
  1663. if (!address->SyncDeviceToHost(trans::GetRuntimePaddingShape(node, index), LongToSize(tensor->data().nbytes()),
  1664. tensor->data_type(), tensor->data_c())) {
  1665. MS_LOG(ERROR) << "Failed to sync output from device to host.";
  1666. }
  1667. tensor->set_sync_status(kNoNeedSync);
  1668. params_list[output_item.first] = tensor;
  1669. }
  1670. // call callback function here
  1671. summary_callback_(0, params_list);
  1672. }
  1673. namespace {
  1674. bool CNodeFirstInputIsPrimitive(const AnfNodePtr &node) {
  1675. if (node == nullptr) {
  1676. return false;
  1677. }
  1678. auto cnode = node->cast<CNodePtr>();
  1679. if (cnode == nullptr) {
  1680. return false;
  1681. }
  1682. auto prim = cnode->input(kAnfPrimitiveIndex);
  1683. if (prim == nullptr || !IsValueNode<Primitive>(prim)) {
  1684. return false;
  1685. }
  1686. return true;
  1687. }
  1688. std::vector<AnfNodePtr> ExtendNodeUsers(const FuncGraphManagerPtr &front_func_graph_manager,
  1689. const AnfNodePtr &front_node) {
  1690. MS_EXCEPTION_IF_NULL(front_func_graph_manager);
  1691. auto &users = front_func_graph_manager->node_users()[front_node];
  1692. std::vector<AnfNodePtr> result;
  1693. for (auto &user : users) {
  1694. if (AnfAlgo::CheckPrimitiveType(user.first, prim::kPrimDepend)) {
  1695. auto depend_cnode = user.first->cast<CNodePtr>();
  1696. if (depend_cnode == nullptr) {
  1697. continue;
  1698. }
  1699. if (front_node != depend_cnode->input(1)) {
  1700. continue;
  1701. }
  1702. auto res = ExtendNodeUsers(front_func_graph_manager, user.first);
  1703. result.insert(result.end(), res.begin(), res.end());
  1704. } else if (AnfAlgo::CheckPrimitiveType(user.first, prim::kPrimMakeTuple)) {
  1705. auto res = ExtendNodeUsers(front_func_graph_manager, user.first);
  1706. (void)result.insert(result.end(), res.begin(), res.end());
  1707. } else {
  1708. (void)result.emplace_back(user.first);
  1709. }
  1710. }
  1711. return result;
  1712. }
  1713. AnfNodePtr GetSupportedInternalNode(const AnfNodePtr &front_node) {
  1714. MS_EXCEPTION_IF_NULL(front_node);
  1715. if (!front_node->isa<CNode>()) {
  1716. return nullptr;
  1717. }
  1718. if (AnfAlgo::IsRealKernel(front_node)) {
  1719. return front_node;
  1720. }
  1721. if (AnfAlgo::CheckPrimitiveType(front_node, prim::kPrimTupleGetItem)) {
  1722. return front_node;
  1723. }
  1724. if (AnfAlgo::CheckPrimitiveType(front_node, prim::kPrimDepend)) {
  1725. auto cnode = front_node->cast<CNodePtr>();
  1726. MS_EXCEPTION_IF_NULL(cnode);
  1727. auto &inputs = cnode->inputs();
  1728. if (inputs.size() > 2) {
  1729. return GetSupportedInternalNode(inputs[1]);
  1730. }
  1731. }
  1732. return nullptr;
  1733. }
  1734. } // namespace
  1735. constexpr auto kMixTarget = "MixTarget";
  1736. constexpr auto kNoTarget = "NoTarget";
  1737. std::string SessionBasic::AddPartialParametersMap(const FuncGraphManagerPtr &front_func_graph_manager,
  1738. const AnfNodePtr &partial_node) {
  1739. MS_EXCEPTION_IF_NULL(partial_node);
  1740. auto iter = partial_target_map_.find(partial_node);
  1741. if (iter != partial_target_map_.end()) {
  1742. return iter->second;
  1743. }
  1744. auto partial_cnode = partial_node->cast<CNodePtr>();
  1745. MS_EXCEPTION_IF_NULL(partial_cnode);
  1746. auto partial_graph = GetValueNode<FuncGraphPtr>(partial_cnode->input(kFirstDataInputIndex));
  1747. MS_EXCEPTION_IF_NULL(partial_graph);
  1748. auto parameters = partial_graph->parameters();
  1749. auto partial_inputs = partial_cnode->inputs();
  1750. if (parameters.size() + 2 != partial_inputs.size()) {
  1751. return kMixTarget;
  1752. }
  1753. for (size_t i = 0; i < parameters.size(); ++i) {
  1754. partial_parameters_map_[parameters[i]] = partial_inputs[2 + i];
  1755. }
  1756. auto graph_nodes = TopoSort(partial_graph->get_return());
  1757. std::string graph_target = kNoTarget;
  1758. for (auto &node : graph_nodes) {
  1759. if (!node->isa<CNode>()) {
  1760. continue;
  1761. }
  1762. if (!AnfAlgo::IsRealKernel(node)) {
  1763. continue;
  1764. }
  1765. std::string cur_target = GetCNodeTarget(node);
  1766. if (graph_target == kNoTarget) {
  1767. graph_target = cur_target;
  1768. }
  1769. if (graph_target != cur_target) {
  1770. graph_target = kMixTarget;
  1771. break;
  1772. }
  1773. }
  1774. (void)partial_target_map_.insert({partial_node, graph_target});
  1775. return graph_target;
  1776. }
  1777. void SessionBasic::HandleInternalOutput(const AnfNodePtr &input_front_node, const AnfNodePtr &backend_node,
  1778. const FuncGraphManagerPtr &front_func_graph_manager,
  1779. const std::shared_ptr<KernelGraph> &backend_graph) {
  1780. auto front_node = GetSupportedInternalNode(input_front_node);
  1781. if (front_node == nullptr) {
  1782. return;
  1783. }
  1784. auto front_real_kernel_pair = AnfAlgo::VisitKernel(front_node, 0);
  1785. auto backend_real_kernel_pair = AnfAlgo::VisitKernel(backend_node, 0);
  1786. auto backend_real_kernel = backend_real_kernel_pair.first;
  1787. if (backend_real_kernel == nullptr || !backend_real_kernel->isa<CNode>()) {
  1788. return;
  1789. }
  1790. auto front_real_kernel = front_real_kernel_pair.first;
  1791. std::string kernel_target = GetCNodeTarget(front_real_kernel);
  1792. bool internal_output = CNodeFirstInputIsPrimitive(front_real_kernel);
  1793. bool unique_target = true;
  1794. if (internal_output && opt::IsNopNode(front_real_kernel)) {
  1795. auto pre_node_pair = AnfAlgo::GetPrevNodeOutput(front_real_kernel, 0);
  1796. auto pre_node_target = GetCNodeTarget(pre_node_pair.first);
  1797. if (pre_node_target != kernel_target) {
  1798. unique_target = false;
  1799. }
  1800. }
  1801. if (internal_output) {
  1802. auto users = ExtendNodeUsers(front_func_graph_manager, front_node);
  1803. for (auto &user : users) {
  1804. if (AnfAlgo::CheckPrimitiveType(user, prim::kPrimPartial)) {
  1805. auto partial_target = AddPartialParametersMap(front_func_graph_manager, user);
  1806. if (partial_target != kNoTarget && partial_target != kernel_target) {
  1807. unique_target = false;
  1808. }
  1809. continue;
  1810. }
  1811. if (!CNodeFirstInputIsPrimitive(user)) {
  1812. internal_output = false;
  1813. break;
  1814. }
  1815. if (!AnfAlgo::IsRealKernel(user)) {
  1816. internal_output = false;
  1817. break;
  1818. }
  1819. if (kernel_target != GetCNodeTarget(user)) {
  1820. unique_target = false;
  1821. }
  1822. }
  1823. }
  1824. if (internal_output) {
  1825. MS_LOG(INFO) << "AddInternalOutput: " << front_node->DebugString() << " To " << backend_real_kernel->DebugString()
  1826. << ", unique_target: " << unique_target;
  1827. backend_graph->AddInternalOutput(front_node, backend_real_kernel, backend_real_kernel_pair.second, unique_target);
  1828. }
  1829. }
  1830. CNodePtr SessionBasic::ConstructOutput(const AnfNodePtrList &outputs, const std::shared_ptr<KernelGraph> &graph) {
  1831. MS_EXCEPTION_IF_NULL(graph);
  1832. std::vector<AnfNodePtr> output_args;
  1833. for (const auto &output : outputs) {
  1834. MS_EXCEPTION_IF_NULL(output);
  1835. MS_LOG(INFO) << "Output:" << output->DebugString();
  1836. }
  1837. auto FindEqu = [graph, outputs, this](const AnfNodePtr &out) -> AnfNodePtr {
  1838. auto backend_anf = graph->GetBackendAnfByFrontAnf(out);
  1839. if (backend_anf != nullptr) {
  1840. auto context_ptr = MsContext::GetInstance();
  1841. MS_EXCEPTION_IF_NULL(context_ptr);
  1842. if (context_ptr->get_param<int>(MS_CTX_EXECUTION_MODE) == kPynativeMode) {
  1843. return backend_anf;
  1844. }
  1845. MS_EXCEPTION_IF_NULL(out);
  1846. auto out_func_graph = out->func_graph();
  1847. MS_EXCEPTION_IF_NULL(out_func_graph);
  1848. auto out_func_graph_manager = out_func_graph->manager();
  1849. if (out_func_graph_manager == nullptr) {
  1850. return backend_anf;
  1851. }
  1852. HandleInternalOutput(out, backend_anf, out_func_graph_manager, graph);
  1853. return backend_anf;
  1854. }
  1855. MS_LOG(EXCEPTION) << "Can't find the node in the equiv map!";
  1856. };
  1857. output_args.push_back(NewValueNode(prim::kPrimMakeTuple));
  1858. (void)std::transform(outputs.begin(), outputs.end(), std::back_inserter(output_args),
  1859. [&](const AnfNodePtr &out) -> AnfNodePtr { return FindEqu(out); });
  1860. return graph->NewCNode(output_args);
  1861. }
  1862. void SessionBasic::CreateOutputNode(const CNodePtr &cnode, const std::shared_ptr<KernelGraph> &graph) {
  1863. MS_LOG(INFO) << "Start!";
  1864. std::vector<AnfNodePtr> make_tuple_inputs;
  1865. make_tuple_inputs.push_back(NewValueNode(prim::kPrimMakeTuple));
  1866. MS_EXCEPTION_IF_NULL(graph);
  1867. if (AnfRuntimeAlgorithm::GetOutputTensorNum(cnode) > 1) {
  1868. for (size_t output_index = 0; output_index < AnfRuntimeAlgorithm::GetOutputTensorNum(cnode); output_index++) {
  1869. auto idx = NewValueNode(SizeToLong(output_index));
  1870. MS_EXCEPTION_IF_NULL(idx);
  1871. auto imm = std::make_shared<Int64Imm>(output_index);
  1872. idx->set_abstract(std::make_shared<abstract::AbstractScalar>(imm));
  1873. auto getitem = graph->NewCNode({NewValueNode(prim::kPrimTupleGetItem), cnode, idx});
  1874. std::vector<TypeId> types = {AnfAlgo::GetOutputInferDataType(cnode, output_index)};
  1875. std::vector<std::vector<size_t>> shapes = {AnfAlgo::GetOutputInferShape(cnode, output_index)};
  1876. AnfAlgo::SetOutputInferTypeAndShape(types, shapes, getitem.get());
  1877. make_tuple_inputs.push_back(getitem);
  1878. }
  1879. } else {
  1880. make_tuple_inputs.push_back(cnode);
  1881. }
  1882. // create output
  1883. auto g_output = graph->NewCNode(make_tuple_inputs);
  1884. graph->set_output(g_output);
  1885. MS_LOG(INFO) << "Finish!";
  1886. }
  1887. std::shared_ptr<KernelGraph> SessionBasic::ConstructSingleOpGraph(const OpRunInfo &op_run_info,
  1888. const std::vector<tensor::TensorPtr> &input_tensors,
  1889. const std::vector<int64_t> &tensors_mask,
  1890. bool is_ascend) {
  1891. auto graph = std::make_shared<KernelGraph>();
  1892. graph->set_graph_id(graph_sum_);
  1893. graph_sum_++;
  1894. std::vector<AnfNodePtr> inputs;
  1895. // set input[0]
  1896. PrimitivePtr op_prim = op_run_info.primitive;
  1897. MS_EXCEPTION_IF_NULL(op_prim);
  1898. inputs.push_back(std::make_shared<ValueNode>(op_prim));
  1899. // set input parameter
  1900. MS_LOG(INFO) << "Input tensor size: " << input_tensors.size();
  1901. if (input_tensors.size() != tensors_mask.size()) {
  1902. MS_LOG(EXCEPTION) << "Input tensors size " << input_tensors.size() << " should be equal to tensors mask size "
  1903. << tensors_mask.size();
  1904. }
  1905. for (size_t i = 0; i < input_tensors.size(); ++i) {
  1906. if (tensors_mask[i] == kValueNodeTensorMask) {
  1907. auto value_node = ConstructRunOpValueNode(graph, input_tensors[i]);
  1908. inputs.push_back(value_node);
  1909. continue;
  1910. }
  1911. auto parameter = ConstructRunOpParameter(graph, input_tensors[i], tensors_mask[i]);
  1912. inputs.push_back(parameter);
  1913. auto mutable_inputs = graph->MutableInputs();
  1914. MS_EXCEPTION_IF_NULL(mutable_inputs);
  1915. mutable_inputs->push_back(parameter);
  1916. }
  1917. // set execution order
  1918. auto cnode = graph->NewCNode(inputs);
  1919. MS_EXCEPTION_IF_NULL(cnode);
  1920. // set abstract,which include inferred shapes and types
  1921. cnode->set_abstract(op_run_info.abstract);
  1922. // get output dynamic shape info
  1923. AnfAlgo::SetNodeAttr(kAttrOutputIsDynamicShape, MakeValue(op_run_info.is_dynamic_shape), cnode);
  1924. if (op_run_info.is_auto_mixed_precision) {
  1925. AnfAlgo::SetNodeAttr(kAttrPynativeNextOpName, MakeValue(op_run_info.next_op_name), cnode);
  1926. AnfAlgo::SetNodeAttr(kAttrPynativeNextIndex, MakeValue(op_run_info.next_input_index), cnode);
  1927. }
  1928. // set execution order
  1929. std::vector<CNodePtr> exe_order = {cnode};
  1930. graph->set_execution_order(exe_order);
  1931. graph->UpdateGraphDynamicAttr();
  1932. // set output
  1933. if (is_ascend) {
  1934. graph->set_output(cnode);
  1935. } else {
  1936. CreateOutputNode(cnode, graph);
  1937. }
  1938. graph->SetInputNodes();
  1939. auto manager = MakeManager({graph});
  1940. if (manager != nullptr) {
  1941. manager->AddFuncGraph(graph);
  1942. graph->set_manager(manager);
  1943. }
  1944. auto ms_context = MsContext::GetInstance();
  1945. MS_EXCEPTION_IF_NULL(ms_context);
  1946. if (ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER)) {
  1947. UnifyMindIR(graph);
  1948. }
  1949. return graph;
  1950. }
  1951. KernelGraphPtr SessionBasic::NewKernelGraph() {
  1952. auto graph = std::make_shared<KernelGraph>();
  1953. graph->set_graph_id(graph_sum_);
  1954. graphs_[graph_sum_++] = graph;
  1955. return graph;
  1956. }
  1957. AnfNodePtr SessionBasic::FindPullNode(const AnfNodePtr &push_node, const std::vector<AnfNodePtr> &node_list) {
  1958. MS_EXCEPTION_IF_NULL(push_node);
  1959. for (auto &node : node_list) {
  1960. if (node != nullptr && node->isa<CNode>()) {
  1961. for (auto input : node->cast<CNodePtr>()->inputs()) {
  1962. if (push_node == AnfAlgo::VisitKernel(input, 0).first) {
  1963. if (AnfAlgo::GetCNodeName(node) != kPullOpName) {
  1964. MS_LOG(EXCEPTION) << "The edge between Push and Pull node is invalid.";
  1965. }
  1966. return node;
  1967. }
  1968. }
  1969. }
  1970. }
  1971. return nullptr;
  1972. }
  1973. GraphId SessionBasic::CompileGraph(const GraphSegmentPtr &segment, const AnfNodePtrList &outputs) {
  1974. MS_EXCEPTION_IF_NULL(executor_);
  1975. return executor_->CompileGraph(shared_from_this(), segment, outputs);
  1976. }
  1977. GraphId SessionBasic::CompileGraph(NotNull<FuncGraphPtr> func_graph) {
  1978. MS_EXCEPTION_IF_NULL(executor_);
  1979. return executor_->CompileGraph(shared_from_this(), func_graph);
  1980. }
  1981. void SessionBasic::BuildGraph(GraphId graph_id) {
  1982. MS_EXCEPTION_IF_NULL(executor_);
  1983. executor_->BuildGraph(shared_from_this(), graph_id);
  1984. }
  1985. void SessionBasic::RunOp(OpRunInfo *op_run_info, const GraphInfo &graph_info,
  1986. std::vector<tensor::TensorPtr> *input_tensors, VectorRef *outputs,
  1987. const std::vector<int64_t> &tensors_mask) {
  1988. MS_EXCEPTION_IF_NULL(executor_);
  1989. executor_->RunOp(shared_from_this(), op_run_info, graph_info, input_tensors, outputs, tensors_mask);
  1990. }
  1991. void SessionBasic::RunOpsInGraph(const GraphId &graph_id, const std::vector<tensor::TensorPtr> &inputs,
  1992. VectorRef *outputs) {
  1993. MS_EXCEPTION_IF_NULL(executor_);
  1994. executor_->RunOpsInGraph(shared_from_this(), graph_id, inputs, outputs);
  1995. }
  1996. void SessionBasic::RunGraph(const GraphId &graph_id, const std::vector<tensor::TensorPtr> &inputs, VectorRef *outputs) {
  1997. MS_EXCEPTION_IF_NULL(executor_);
  1998. executor_->RunGraph(shared_from_this(), graph_id, inputs, outputs);
  1999. }
  2000. void SessionBasic::RunGraphAsync(const GraphId &graph_id, const std::vector<tensor::TensorPtr> &inputs,
  2001. VectorRef *outputs) {
  2002. MS_EXCEPTION_IF_NULL(executor_);
  2003. executor_->RunGraphAsync(shared_from_this(), graph_id, inputs, outputs);
  2004. }
  2005. void SessionBasic::RunGraphImpl(const GraphId &graph_id, const std::vector<tensor::TensorPtr> &inputs,
  2006. VectorRef *const outputs) {
  2007. MS_LOG(INFO) << "Run graph start, graph id: " << graph_id;
  2008. auto kernel_graph = GetGraph(graph_id);
  2009. MS_EXCEPTION_IF_NULL(kernel_graph);
  2010. // if none of child graph and no anf output exists
  2011. if (!kernel_graph->executable()) {
  2012. MS_LOG(INFO) << "No child graph has anf output";
  2013. return;
  2014. }
  2015. PreExecuteGraph(kernel_graph, inputs, outputs);
  2016. ExecuteGraph(kernel_graph);
  2017. PostExecuteGraph(kernel_graph, inputs, outputs);
  2018. MS_LOG(INFO) << "Run graph end, graph id: " << graph_id;
  2019. }
  2020. void SessionBasic::RunOpsInGraphImpl(const GraphId &graph_id, const std::vector<tensor::TensorPtr> &inputs,
  2021. VectorRef *outputs) {
  2022. MS_LOG(INFO) << "Start!";
  2023. auto kernel_graph = GetGraph(graph_id);
  2024. MS_EXCEPTION_IF_NULL(kernel_graph);
  2025. std::map<AnfNodePtr, size_t> parameter_index;
  2026. GetParameterIndex(kernel_graph.get(), inputs, &parameter_index);
  2027. std::map<KernelWithIndex, std::vector<std::vector<size_t>>> output_indexes;
  2028. CreateOutputPlaceholder(kernel_graph, inputs, outputs, &output_indexes);
  2029. std::map<KernelWithIndex, size_t> cnode_refcount;
  2030. GetRefCount(kernel_graph.get(), &cnode_refcount);
  2031. BuildOpsInGraph(graph_id, parameter_index, inputs, cnode_refcount);
  2032. // Clear bucket resources every step
  2033. if (kernel_graph->is_bprop()) {
  2034. ClearAllBucket(graph_id);
  2035. }
  2036. std::map<KernelWithIndex, tensor::TensorPtr> op_output_map;
  2037. for (const auto &kernel : kernel_graph->execution_order()) {
  2038. // Generate input tensors, tensor masks and input kernel with index
  2039. InputTensorInfo input_tensor_info;
  2040. GetOpInputTensors(kernel, op_output_map, parameter_index, inputs, &input_tensor_info);
  2041. // Get OpRunInfo and GraphInfo
  2042. OpRunInfo run_info;
  2043. GetSingleOpRunInfo(kernel, &run_info);
  2044. GraphInfo graph_info = GetSingleOpGraphInfo(kernel, input_tensor_info.input_tensors);
  2045. // Build and run current single op
  2046. VectorRef op_outputs;
  2047. RunOpImpl(graph_info, &run_info, &input_tensor_info.input_tensors, &op_outputs,
  2048. input_tensor_info.input_tensors_mask);
  2049. std::vector<tensor::TensorPtr> new_output_tensors;
  2050. // Handle inputs and outputs of current op
  2051. HandleOpInputs(input_tensor_info.input_kernel, &cnode_refcount, &op_output_map);
  2052. HandleOpOutputs(kernel, op_outputs, output_indexes, cnode_refcount, &op_output_map, outputs, &new_output_tensors);
  2053. // Save grad node to Bucket
  2054. if (kernel_graph->is_bprop()) {
  2055. AddGradAddrToBucket(graph_id, new_output_tensors);
  2056. }
  2057. }
  2058. MS_LOG(INFO) << "Finish!";
  2059. }
  2060. void SessionBasic::EraseValueNodeTensor(const std::vector<int64_t> &tensors_mask,
  2061. std::vector<tensor::TensorPtr> *input_tensors) {
  2062. MS_EXCEPTION_IF_NULL(input_tensors);
  2063. if (input_tensors->size() != tensors_mask.size()) {
  2064. MS_LOG(EXCEPTION) << "Input tensors size " << input_tensors->size() << " should be equal to tensors mask size "
  2065. << tensors_mask.size();
  2066. }
  2067. std::vector<tensor::TensorPtr> new_input_tensors;
  2068. for (size_t index = 0; index < tensors_mask.size(); ++index) {
  2069. if (tensors_mask[index] != kValueNodeTensorMask) {
  2070. new_input_tensors.emplace_back(input_tensors->at(index));
  2071. }
  2072. }
  2073. *input_tensors = new_input_tensors;
  2074. }
  2075. void SessionBasic::UpdateAllGraphDynamicShapeAttr(const std::vector<KernelGraphPtr> &all_graphs) {
  2076. bool is_dynamic = false;
  2077. for (const auto &graph : all_graphs) {
  2078. UpdateGraphDynamicShapeAttr(NOT_NULL(graph));
  2079. is_dynamic = graph->is_dynamic_shape() || is_dynamic;
  2080. }
  2081. if (is_dynamic && all_graphs.size() > 1) {
  2082. MS_LOG(EXCEPTION) << "Dynamic shape is not supported with control flow.";
  2083. }
  2084. }
  2085. void SessionBasic::UpdateGraphDynamicShapeAttr(const NotNull<KernelGraphPtr> &root_graph) {
  2086. for (const auto &cnode : root_graph->execution_order()) {
  2087. if (AnfAlgo::IsNodeDynamicShape(cnode)) {
  2088. AnfAlgo::SetNodeAttr(kAttrIsDynamicShape, MakeValue(true), cnode);
  2089. MS_LOG(INFO) << "Set Dynamic Shape Attr to Node:" << cnode->fullname_with_scope();
  2090. }
  2091. }
  2092. root_graph->UpdateGraphDynamicAttr();
  2093. }
  2094. bool SessionBasic::IsGetNextGraph(const std::shared_ptr<KernelGraph> &kernel_graph, std::string *channel_name) {
  2095. MS_EXCEPTION_IF_NULL(kernel_graph);
  2096. for (const auto &kernel_node : kernel_graph->execution_order()) {
  2097. auto kernel_name = AnfAlgo::GetCNodeName(kernel_node);
  2098. if (kernel_name == kGetNextOpName) {
  2099. auto prim = AnfAlgo::GetCNodePrimitive(kernel_node);
  2100. MS_EXCEPTION_IF_NULL(prim);
  2101. *channel_name = GetValue<std::string>(prim->GetAttr("shared_name"));
  2102. return true;
  2103. }
  2104. }
  2105. return false;
  2106. }
  2107. void SessionBasic::RunOpRemoveNopNode(const KernelGraphPtr &kernel_graph) const {
  2108. auto ms_context = MsContext::GetInstance();
  2109. MS_EXCEPTION_IF_NULL(ms_context);
  2110. if (!ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER)) {
  2111. opt::RemoveNopNode(kernel_graph.get());
  2112. }
  2113. }
  2114. void SessionBasic::RunOpHideNopNode(const KernelGraphPtr &kernel_graph) const {
  2115. auto ms_context = MsContext::GetInstance();
  2116. MS_EXCEPTION_IF_NULL(ms_context);
  2117. if (!ms_context->get_param<bool>(MS_CTX_ENABLE_PYNATIVE_INFER)) {
  2118. opt::HideNopNode(kernel_graph.get());
  2119. }
  2120. }
  2121. std::vector<uint32_t> SessionBasic::GetAllReduceSplitIndex() {
  2122. auto ms_context = MsContext::GetInstance();
  2123. MS_EXCEPTION_IF_NULL(ms_context);
  2124. std::string group = GetCommWorldGroup();
  2125. auto parallel_context = parallel::ParallelContext::GetInstance();
  2126. MS_EXCEPTION_IF_NULL(parallel_context);
  2127. // PyNative not support multi group allreduce
  2128. group += "sum1";
  2129. return parallel_context->GetAllReduceFusionSplitIndices(group);
  2130. }
  2131. uint32_t GetBpropGraphGradsCount(const KernelGraphPtr &graph) {
  2132. return AnfAlgo::GetAllOutput(graph->output(), {prim::kPrimTupleGetItem}).size();
  2133. }
  2134. void SetGraphBpropAttr(const KernelGraphPtr &graph) {
  2135. auto &execution_orders = graph->execution_order();
  2136. if (std::any_of(execution_orders.begin(), execution_orders.end(),
  2137. [](const AnfNodePtr &node) { return node->scope()->name().rfind("Gradient", 0) == 0; })) {
  2138. graph->set_is_bprop(true);
  2139. MS_LOG(INFO) << "Match bprop graph";
  2140. } else {
  2141. graph->set_is_bprop(false);
  2142. }
  2143. }
  2144. std::vector<uint32_t> GenerateBucketSizeList(const KernelGraphPtr &graph, const std::vector<uint32_t> &split_index) {
  2145. if (split_index.empty()) {
  2146. auto grads_count = GetBpropGraphGradsCount(graph);
  2147. if (grads_count == 0) {
  2148. MS_LOG(EXCEPTION) << "Bprop graph has no grad";
  2149. }
  2150. return {grads_count};
  2151. }
  2152. std::vector<uint32_t> bucket_size_list;
  2153. uint32_t old_index = 0;
  2154. for (auto &index : split_index) {
  2155. if (old_index == 0) {
  2156. bucket_size_list.emplace_back(index - old_index + 1);
  2157. } else {
  2158. bucket_size_list.emplace_back(index - old_index);
  2159. }
  2160. old_index = index;
  2161. }
  2162. return bucket_size_list;
  2163. }
  2164. void PreProcessOnSplitIndex(const KernelGraphPtr &graph, vector<uint32_t> *split_index) {
  2165. MS_EXCEPTION_IF_NULL(split_index);
  2166. if (split_index->empty()) {
  2167. return;
  2168. }
  2169. // calculate split index num
  2170. auto split_index_len = split_index->size();
  2171. uint32_t split_index_num = (*split_index)[split_index_len - 1];
  2172. // obtain graph output tensor num
  2173. auto grads_count = GetBpropGraphGradsCount(graph);
  2174. if (split_index_num >= grads_count) {
  2175. MS_LOG(WARNING) << "Invalid all_reduce_fusion_config:" << *split_index << " total grads count:" << grads_count
  2176. << ". AllReduces are fused into one AllReduce.";
  2177. split_index->clear();
  2178. split_index->push_back(grads_count);
  2179. } else if (split_index_num < grads_count - 1) {
  2180. split_index->push_back(grads_count - 1);
  2181. }
  2182. }
  2183. void SessionBasic::InitAllBucket(const KernelGraphPtr &graph) {
  2184. MS_EXCEPTION_IF_NULL(graph);
  2185. MS_LOG(INFO) << "Init Bucket start, graph_id:" << graph->graph_id();
  2186. auto ms_context = MsContext::GetInstance();
  2187. MS_EXCEPTION_IF_NULL(ms_context);
  2188. const bool pynative_mode = (ms_context->get_param<int>(MS_CTX_EXECUTION_MODE) == kPynativeMode);
  2189. auto parallel_context = parallel::ParallelContext::GetInstance();
  2190. MS_EXCEPTION_IF_NULL(parallel_context);
  2191. auto parallel_mode = parallel_context->parallel_mode();
  2192. if (!pynative_mode || parallel_mode != parallel::DATA_PARALLEL) {
  2193. return;
  2194. }
  2195. SetGraphBpropAttr(graph);
  2196. if (!graph->is_bprop()) {
  2197. return;
  2198. }
  2199. std::vector<std::shared_ptr<device::Bucket>> bucket_list;
  2200. // Create bucket for every split allreduce ops
  2201. auto split_index = GetAllReduceSplitIndex();
  2202. PreProcessOnSplitIndex(graph, &split_index);
  2203. auto bucket_size_list = GenerateBucketSizeList(graph, split_index);
  2204. uint32_t bucket_id = 0;
  2205. for (auto bucket_size : bucket_size_list) {
  2206. MS_LOG(INFO) << "Create new bucket:" << bucket_id;
  2207. auto bucket = CreateBucket(bucket_id++, bucket_size);
  2208. bucket->Init();
  2209. bucket_list.emplace_back(bucket);
  2210. }
  2211. auto bucket_ret = bucket_map_.try_emplace(graph->graph_id(), bucket_list);
  2212. if (!bucket_ret.second) {
  2213. MS_LOG(EXCEPTION) << "Duplicate bucket_map_ graph key:" << graph->graph_id();
  2214. }
  2215. // set all free bucket index to 0
  2216. auto free_bucket_ret = free_bucket_id_map_.try_emplace(graph->graph_id(), 0);
  2217. if (!free_bucket_ret.second) {
  2218. MS_LOG(EXCEPTION) << "Duplicate free_bucket_id_map_ graph key:" << graph->graph_id();
  2219. }
  2220. MS_LOG(INFO) << "Init Bucket finish";
  2221. }
  2222. void SessionBasic::AddGradAddrToBucket(const GraphId &graph_id, const std::vector<tensor::TensorPtr> &grad_tensor) {
  2223. auto parallel_context = parallel::ParallelContext::GetInstance();
  2224. MS_EXCEPTION_IF_NULL(parallel_context);
  2225. auto parallel_mode = parallel_context->parallel_mode();
  2226. if (parallel_mode != parallel::DATA_PARALLEL) {
  2227. return;
  2228. }
  2229. auto iter = bucket_map_.find(graph_id);
  2230. if (iter == bucket_map_.end()) {
  2231. MS_LOG(EXCEPTION) << "unknown graph id:" << graph_id;
  2232. }
  2233. auto &bucket_list = iter->second;
  2234. auto free_bucket_iter = free_bucket_id_map_.find(graph_id);
  2235. if (free_bucket_iter == free_bucket_id_map_.end()) {
  2236. MS_LOG(EXCEPTION) << "unknown free graph id:" << graph_id;
  2237. }
  2238. auto free_bucket_index = free_bucket_iter->second;
  2239. for (auto &tensor : grad_tensor) {
  2240. if (free_bucket_index >= bucket_list.size()) {
  2241. MS_LOG(EXCEPTION) << "Invalid free bucket id:" << free_bucket_iter->second
  2242. << " total bucket num:" << bucket_list.size();
  2243. }
  2244. auto &free_bucket = bucket_list[free_bucket_index];
  2245. free_bucket->AddGradTensor(tensor);
  2246. if (free_bucket->full()) {
  2247. MS_LOG(INFO) << "bucket is full";
  2248. free_bucket->Launch();
  2249. free_bucket_index = ++free_bucket_iter->second;
  2250. MS_LOG(INFO) << "new free bucket:" << free_bucket_index;
  2251. }
  2252. }
  2253. }
  2254. void SessionBasic::ClearAllBucket(const GraphId &graph_id) {
  2255. auto iter = bucket_map_.find(graph_id);
  2256. if (iter != bucket_map_.end()) {
  2257. auto bucket_list = iter->second;
  2258. for (auto &bucket : bucket_list) {
  2259. MS_LOG(INFO) << "Clear bucket:" << bucket->id();
  2260. bucket->Release();
  2261. }
  2262. }
  2263. auto free_iter = free_bucket_id_map_.find(graph_id);
  2264. if (free_iter != free_bucket_id_map_.end()) {
  2265. free_iter->second = 0;
  2266. }
  2267. }
  2268. void SessionBasic::FinalOptimize(const KernelGraphPtr &graph) const {
  2269. MS_LOG(INFO) << "Start FinalOptimize for graph: " << graph->graph_id();
  2270. opt::CommonFinalOptimization(graph);
  2271. MS_LOG(INFO) << "End FinalOptimize for graph: " << graph->graph_id();
  2272. }
  2273. void SessionBasic::DumpGraph(const std::shared_ptr<KernelGraph> &kernel_graph) {
  2274. #ifdef ENABLE_DUMP_IR
  2275. auto context_ptr = MsContext::GetInstance();
  2276. MS_EXCEPTION_IF_NULL(context_ptr);
  2277. bool save_graphs = context_ptr->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG);
  2278. if (save_graphs) {
  2279. DumpIR("graph_build_" + std::to_string(kernel_graph->graph_id()) + ".ir", kernel_graph, true, kWholeStack);
  2280. DumpIRProto(kernel_graph, "vm_build_" + std::to_string(kernel_graph->graph_id()));
  2281. DumpIR("trace_code_graph", kernel_graph, true, kWholeStack);
  2282. }
  2283. #endif
  2284. }
  2285. #if (ENABLE_CPU && !_WIN32)
  2286. void SessionBasic::InitPsWorker(const KernelGraphPtr &kernel_graph) {
  2287. if (!ps::PSContext::instance()->is_worker()) {
  2288. return;
  2289. }
  2290. CheckPSModeConsistence(kernel_graph);
  2291. if (ps::PsDataPrefetch::GetInstance().cache_enable()) {
  2292. if (!ps::ps_cache_instance.initialized_ps_cache()) {
  2293. auto context_ptr = MsContext::GetInstance();
  2294. MS_EXCEPTION_IF_NULL(context_ptr);
  2295. auto devcie_target = context_ptr->get_param<std::string>(MS_CTX_DEVICE_TARGET);
  2296. auto runtime_instance = device::KernelRuntimeManager::Instance().GetKernelRuntime(devcie_target, device_id_);
  2297. MS_EXCEPTION_IF_NULL(runtime_instance);
  2298. auto context = runtime_instance->context();
  2299. const auto &kernels = kernel_graph->execution_order();
  2300. if (kernels.size() > 0 && AnfAlgo::GetCNodeName(kernels[0]) == "InitDataSetQueue") {
  2301. GetBatchElements(kernels[0]);
  2302. ps::ps_cache_instance.Initialize();
  2303. }
  2304. ps::ps_cache_instance.DoProcessData(device_id_, context);
  2305. }
  2306. } else {
  2307. // Assign parameter keys.
  2308. AssignParamKey(kernel_graph);
  2309. }
  2310. }
  2311. void SessionBasic::GetBatchElements(const AnfNodePtr &kernel_node) const {
  2312. auto shapes = AnfAlgo::GetNodeAttr<std::vector<std::vector<int64_t>>>(kernel_node, "shapes");
  2313. auto types = AnfAlgo::GetNodeAttr<std::vector<TypePtr>>(kernel_node, "types");
  2314. if (shapes.size() != types.size() || shapes.size() == 0 || types.size() == 0) {
  2315. MS_LOG(EXCEPTION) << "Invalid shapes of op[InitDataSetQueue]: shapes size " << shapes.size() << ", types size "
  2316. << types;
  2317. }
  2318. size_t batch_elements = 1;
  2319. const auto &shape = shapes[0];
  2320. for (size_t i = 0; i < shape.size(); ++i) {
  2321. batch_elements *= shape[i];
  2322. }
  2323. ps::ps_cache_instance.set_batch_elements(batch_elements);
  2324. }
  2325. void SessionBasic::CheckPSModeConsistence(const KernelGraphPtr &kernel_graph) const {
  2326. auto input_nodes = kernel_graph->inputs();
  2327. for (const auto &input_node : input_nodes) {
  2328. if (!input_node->isa<Parameter>()) {
  2329. continue;
  2330. }
  2331. auto pk_node = input_node->cast<ParameterPtr>();
  2332. MS_EXCEPTION_IF_NULL(pk_node);
  2333. auto param_info_ptr = pk_node->param_info();
  2334. const std::string &param_name = pk_node->fullname_with_scope();
  2335. if (param_info_ptr != nullptr && param_info_ptr->init_in_server() &&
  2336. !ps::ps_cache_instance.IsHashTable(param_name)) {
  2337. MS_LOG(EXCEPTION) << "Can not initialize the parameter[" << param_name
  2338. << "] in server, this parameter is used by kernel which executes in device";
  2339. }
  2340. }
  2341. }
  2342. void SessionBasic::AssignParamKey(const KernelGraphPtr &kernel_graph) {
  2343. MS_EXCEPTION_IF_NULL(kernel_graph);
  2344. // PS embeddingLookup cache check.
  2345. if (ps::PsDataPrefetch::GetInstance().cache_enable()) {
  2346. MS_LOG(EXCEPTION) << "The other parameter can't set ps mode when the embeddingLookup cache is enabled in "
  2347. "parameter server training mode.";
  2348. }
  2349. std::vector<AnfNodePtr> node_list = TopoSort(kernel_graph->get_return());
  2350. for (auto &node : node_list) {
  2351. if (node != nullptr && node->isa<CNode>()) {
  2352. // Assign key for forward kernel EmbeddingLookup.
  2353. // The key will be assigned to embedding table ande Push kernel as well.
  2354. if (AnfAlgo::GetCNodeName(node) == kEmbeddingLookupOpName) {
  2355. size_t embedding_table_idx = 0;
  2356. auto embedding_table = AnfAlgo::GetInputNode(node->cast<CNodePtr>(), embedding_table_idx);
  2357. size_t key = ps::Worker::GetInstance().SetParamKey(embedding_table->fullname_with_scope());
  2358. AnfAlgo::SetNodeAttr(kAttrPsKey, MakeValue(key), node);
  2359. } else if (AnfAlgo::GetCNodeName(node) == kPushOpName) {
  2360. auto pull_node = FindPullNode(node, node_list);
  2361. if (!pull_node) {
  2362. MS_LOG(EXCEPTION) << "Assigning parameter key failed: can't find Pull node of the Push node.";
  2363. }
  2364. // Second input of Pull node is the trainable parameter.
  2365. size_t parameter_index = 1;
  2366. auto parameter_node = AnfAlgo::GetInputNode(pull_node->cast<CNodePtr>(), parameter_index);
  2367. size_t key = ps::Worker::GetInstance().SetParamKey(parameter_node->fullname_with_scope());
  2368. AnfAlgo::SetNodeAttr(kAttrPsKey, MakeValue(key), node);
  2369. AnfAlgo::SetNodeAttr(kAttrPsKey, MakeValue(key), pull_node);
  2370. std::string optimizer_name = AnfAlgo::GetNodeAttr<std::string>(node, kAttrOptimizerType);
  2371. ps::Worker::GetInstance().SetKeyOptimId(key, optimizer_name);
  2372. }
  2373. }
  2374. }
  2375. }
  2376. void SessionBasic::InitPSParamAndOptim(const KernelGraphPtr &kernel_graph,
  2377. const std::vector<tensor::TensorPtr> &inputs_const) {
  2378. if (!ps::PSContext::instance()->is_worker()) {
  2379. return;
  2380. }
  2381. std::vector<tensor::TensorPtr> inputs(inputs_const);
  2382. MS_EXCEPTION_IF_NULL(kernel_graph);
  2383. auto input_nodes = kernel_graph->inputs();
  2384. auto ms_context = MsContext::GetInstance();
  2385. MS_EXCEPTION_IF_NULL(ms_context);
  2386. for (size_t i = 0; i < inputs.size(); ++i) {
  2387. auto tensor = inputs[i];
  2388. MS_EXCEPTION_IF_NULL(tensor);
  2389. auto input_node = input_nodes[i];
  2390. MS_EXCEPTION_IF_NULL(input_node);
  2391. if (input_node->isa<Parameter>() && AnfAlgo::OutputAddrExist(input_node, 0)) {
  2392. ps::Worker::GetInstance().InitPSParamAndOptim(input_node, tensor);
  2393. }
  2394. }
  2395. }
  2396. #endif
  2397. } // namespace session
  2398. void DumpGraphExeOrder(const std::string &file_name, const std::string &target_dir,
  2399. const std::vector<CNodePtr> &execution_order) {
  2400. bool status = Common::CreateNotExistDirs(target_dir + "/execution_order/");
  2401. std::string file_path = target_dir + "/execution_order/" + file_name;
  2402. if (!status) {
  2403. MS_LOG(ERROR) << "Failed at CreateNotExistDirs in DumpGraphExeOrder";
  2404. return;
  2405. }
  2406. if (file_path.size() > PATH_MAX) {
  2407. MS_LOG(ERROR) << "File path " << file_path << " is too long.";
  2408. return;
  2409. }
  2410. char real_path[PATH_MAX] = {0};
  2411. char *real_path_ret = nullptr;
  2412. #if defined(_WIN32) || defined(_WIN64)
  2413. real_path_ret = _fullpath(real_path, file_path.c_str(), PATH_MAX);
  2414. #else
  2415. real_path_ret = realpath(file_path.c_str(), real_path);
  2416. #endif
  2417. if (nullptr == real_path_ret) {
  2418. MS_LOG(DEBUG) << "dir " << file_path << " does not exit.";
  2419. } else {
  2420. std::string path_string = real_path;
  2421. if (chmod(common::SafeCStr(path_string), S_IRUSR | S_IWUSR) == -1) {
  2422. MS_LOG(ERROR) << "Modify file:" << real_path << " to rw fail.";
  2423. return;
  2424. }
  2425. }
  2426. // write to csv file
  2427. std::ofstream ofs(real_path);
  2428. if (!ofs.is_open()) {
  2429. MS_LOG(ERROR) << "Open file '" << real_path << "' failed!";
  2430. return;
  2431. }
  2432. ofs << "NodeExecutionOrder-FullNameWithScope\n";
  2433. for (const CNodePtr &node : execution_order) {
  2434. ofs << node->fullname_with_scope() << "\n";
  2435. }
  2436. ofs.close();
  2437. // set file mode to read only by user
  2438. ChangeFileMode(file_path, S_IRUSR);
  2439. }
  2440. } // namespace mindspore