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

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