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