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 114 kB

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