Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include "core/framework/graph_partitioner.h"
 
#include <cassert>
#include <functional>
#include <limits>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
 
#include "core/common/inlined_containers.h"
#include "core/common/safeint.h"
#include "core/common/string_utils.h"
#include "core/framework/compute_capability.h"
#include "core/framework/ep_context_utils.h"
#include "core/framework/execution_providers.h"
#include "core/framework/func_kernel.h"
#include "core/framework/kernel_lookup.h"
#include "core/framework/kernel_registry_manager.h"
#include "core/framework/kernel_registry.h"
#include "core/framework/layering_annotations.h"
#include "core/framework/max_shape_inference.h"
#include "core/framework/resource_accountant.h"
#include "core/graph/function.h"
#include "core/graph/function_utils.h"
#include "core/graph/graph_utils.h"
#include "core/graph/graph_viewer.h"
#include "core/graph/model.h"
#include "core/session/onnxruntime_ep_device_ep_metadata_keys.h"
#include "core/session/onnxruntime_session_options_config_keys.h"
#include "core/util/protobuf_parsing_utils.h"
 
// uncomment this line to count non-CUDA ops in ONNX domain
// #define COUNT_NON_CUDA_OPS
 
#ifdef COUNT_NON_CUDA_OPS
class NonCudaOps {
 public:
  ~NonCudaOps() {
    printf("Non-CUDA ops:\n");
    for (auto i : map_) {
      printf("%s: %d\n", i.first.c_str(), i.second);
    }
  }
 
  void AddOp(const std::string& name) {
    if (map_.count(name))
      map_.at(name)++;
    else
      map_.insert({name, 1});
  }
 
 private:
  std::map<std::string, int> map_;
};
 
NonCudaOps non_cuda;
#endif
 
namespace onnxruntime {
 
namespace {
 
// contains some common parameters used by the partitioning helper functions
struct PartitionParams {
  std::reference_wrapper<Graph> graph;
  std::reference_wrapper<const CheckLoadCancellationFn> check_load_cancellation_fn;
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
  std::reference_wrapper<FuncManager> func_mgr;
  std::reference_wrapper<KernelRegistry> fused_kernel_registry;
  std::reference_wrapper<int> fused_node_unique_id;
  std::reference_wrapper<const layout_transformation::TransformLayoutFunction> transform_layout_function;
  std::reference_wrapper<const layout_transformation::DebugGraphFn> debug_graph_fn;
  bool ep_context_data_write_callback_required;
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
  uint32_t registered_ep_context_data_callbacks;
  std::reference_wrapper<const OnPartitionAssignmentFunction> on_partition_assignment_fn;
  LayeringIndex* layering_index;
};
}  // namespace
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
 
// minimal KernelDef based on MetaDef instead of a Function based node
static void BuildFusedKernelDef(KernelDefBuilder& builder, const IndexedSubGraph::MetaDef& metadef,
                                const std::string& provider_type) {
  builder.SetName(metadef.name)
      .SetDomain(metadef.domain)
      .SinceVersion(metadef.since_version)
      .Provider(provider_type);
}
 
/// <summary>
/// Check if a node can be placed on a specific provider. If yes, then set the nodes execution provider.
/// Do nothing if the node is already assigned.
/// </summary>
/// <param name="graph">Graph in question.</param>
/// <param name="capability">Indexed subgraph which needs to be assigned</param>
/// <param name="provider_type">The EP to assign the Indexed subgraph to</param>
static bool TryAssignNodes(Graph& graph, const IndexedSubGraph& capability,
                           const std::string& provider_type,
                           InlinedVector<NodeIndex>* newly_assigned_nodes = nullptr) {
  // Before assigning the ep to any node, first walk through all the nodes and ensure
  // none of the nodes have already been assigned. If a node is assigned, simply return.
  for (auto node_index : capability.nodes) {
    const auto* node = graph.GetNode(node_index);
    if ((nullptr == node) ||
        (!node->GetExecutionProviderType().empty() && node->GetExecutionProviderType() != provider_type)) {
      return false;
    }
  }
 
  // When newly_assigned_nodes is provided, this call performs the tentative first-pass
  // tagging of the NHWC two-pass partitioning flow. Those tags only exist so the layout
  // transformer and the second GetCapability pass can recognize the candidate nodes; they
  // may be dropped again before any partition is committed. Tentative tags must therefore
  // not commit resource-accountant budget here. The budget for nodes that survive the
  // second pass is committed later (see the deferred-commit step in GetCapabilityForEP).
  const bool is_tentative_pass = (newly_assigned_nodes != nullptr);
  const bool acc_enabled = capability.IsAccountingEnabled();
  for (size_t i = 0, limit = capability.nodes.size(); i < limit; ++i) {
    auto* node = graph.GetNode(capability.nodes[i]);
    const bool was_unassigned = node->GetExecutionProviderType().empty();
    node->SetExecutionProviderType(provider_type);
    if (newly_assigned_nodes != nullptr && was_unassigned) {
      newly_assigned_nodes->push_back(node->Index());
    }
    if (acc_enabled && !is_tentative_pass) {
      capability.AccountForNode(i);
    }
  }
  return true;
}
 
static void ClearExecutionProviderAssignments(Graph& graph,
                                              const InlinedVector<NodeIndex>& node_indices,
                                              const std::string& provider_type) {
  for (NodeIndex node_index : node_indices) {
    auto* node = graph.GetNode(node_index);
    if (node != nullptr && node->GetExecutionProviderType() == provider_type) {
      node->SetExecutionProviderType("");
    }
  }
}
 
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
 
static bool TryAssignSingleNode(Graph& graph,
                                const IndexedSubGraph& indexed_sub_graph,
                                const std::string& provider_type) {
  // The provider can run a single node in the <graph> if not using meta-defs.
  // A fused kernel is not supported in this case.
  assert(indexed_sub_graph.GetMetaDef() == nullptr && indexed_sub_graph.nodes.size() == 1);
 
  auto* node = graph.GetNode(indexed_sub_graph.nodes[0]);
  if (nullptr != node && node->GetExecutionProviderType().empty()) {
    // The node was not fused or assigned. Assign it to <provider_type>.
    node->SetExecutionProviderType(provider_type);
    if (indexed_sub_graph.IsAccountingEnabled()) {
      indexed_sub_graph.AccountForNode(0);
    }
    return true;
  }
 
  return false;
}
 
static Status CheckEpContextDataSupport(const IExecutionProvider& ep, uint32_t required_flags) {
  if (required_flags == OrtEpContextDataCallbackSupportFlags_NONE) {
    return Status::OK();
  }
 
  uint32_t supported_flags = OrtEpContextDataCallbackSupportFlags_NONE;
  ORT_RETURN_IF_ERROR(ep.GetEpContextDataCallbackSupport(supported_flags));
  ORT_RETURN_IF((required_flags & OrtEpContextDataCallbackSupportFlags_READ) != 0 &&
                    (supported_flags & OrtEpContextDataCallbackSupportFlags_READ) == 0,
                "EP '", ep.Type(),
                "' does not support the registered EPContext data read callback.");
  ORT_RETURN_IF((required_flags & OrtEpContextDataCallbackSupportFlags_WRITE) != 0 &&
                    (supported_flags & OrtEpContextDataCallbackSupportFlags_WRITE) == 0,
                "EP '", ep.Type(),
                "' does not support the registered EPContext data write callback.");
 
  return Status::OK();
}
 
namespace {
struct GetCapabilityForEPParams {
  std::reference_wrapper<Graph> graph;
  std::reference_wrapper<const KernelRegistryManager> kernel_registry_mgr;
  std::reference_wrapper<IExecutionProvider> current_ep;
  std::reference_wrapper<std::vector<std::unique_ptr<ComputeCapability>>> capabilities;
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
  GraphPartitioner::Mode mode;
  std::reference_wrapper<const layout_transformation::TransformLayoutFunction> transform_layout;
  std::reference_wrapper<const layout_transformation::DebugGraphFn> debug_graph_fn;
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
  IResourceAccountant* resource_accountant;
  std::reference_wrapper<const GraphOptimizerRegistry> graph_optimizer_registry;
  std::reference_wrapper<const CheckLoadCancellationFn> check_load_cancellation_fn;
  LayeringIndex* layering_index;  // Added member
  uint32_t registered_ep_context_data_callbacks;
  InlinedHashSet<NodeIndex>* layout_assigned_nodes = nullptr;
};
 
auto get_capabilities = [](const IExecutionProvider& ep,
                           const GraphViewer& graph_viewer,
                           const IExecutionProvider::IKernelLookup& kernel_lookup,
                           IResourceAccountant* resource_accountant,
                           const GraphOptimizerRegistry& graph_optimizer_registry,
                           uint32_t registered_ep_context_data_callbacks,
                           std::vector<std::unique_ptr<ComputeCapability>>& capabilities) -> Status {
  if (registered_ep_context_data_callbacks != OrtEpContextDataCallbackSupportFlags_NONE) {
    ORT_RETURN_IF_ERROR(CheckEpContextDataSupport(
        ep, ep.GetEpContextDataCallbackRequirements(graph_viewer) & registered_ep_context_data_callbacks));
  }
  capabilities = ep.GetCapability(graph_viewer, kernel_lookup, graph_optimizer_registry, resource_accountant);
 
  // In theory an EP could return an empty capability. Remove those.
  capabilities.erase(std::remove_if(capabilities.begin(), capabilities.end(),
                                    [](const std::unique_ptr<ComputeCapability>& capability) {
                                      return !capability || !capability->sub_graph;
                                    }),
                     capabilities.end());
 
  return Status::OK();
};
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
Status RefreshMaxShapeInference(Graph& graph, IResourceAccountant& resource_accountant) {
  // Overrides are scoped to top-level inputs. Starting from the root also refreshes
  // recursively inferred shapes when a layout transformation modifies a subgraph.
  Graph* top_level_graph = &graph;
  while (Graph* parent_graph = top_level_graph->MutableParentGraph()) {
    top_level_graph = parent_graph;
  }
 
  MaxShapeInferenceResult result;
  ORT_RETURN_IF_ERROR(
      InferMaxShapes(*top_level_graph, resource_accountant.GetMaxShapeOverrides(), result));
  resource_accountant.SetMaxShapeInferenceResult(std::move(result));
  return Status::OK();
}
#endif
}  // namespace
 
static Status GetCapabilityForEP(const GetCapabilityForEPParams& params, const logging::Logger& logger) {
  auto& current_ep = params.current_ep.get();
  const auto& ep_type = current_ep.Type();
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
  if (current_ep.GetPreferredLayout() == DataLayout::NHWC && !params.transform_layout.get()) {
    LOGS(logger, WARNING) << ep_type << " cannot be used with this model due to its ONNX opset not being supported by "
                                        "the layout transformer.";
    return Status::OK();
  }
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
 
  const auto& kernel_registry_mgr = params.kernel_registry_mgr.get();
  const auto kernel_registries_for_ep = kernel_registry_mgr.GetKernelRegistriesByProviderType(ep_type);
  const KernelLookup kernel_lookup{ep_type,
                                   kernel_registries_for_ep,
                                   kernel_registry_mgr.GetKernelTypeStrResolver(),
                                   logger};
 
  auto& graph = params.graph.get();
  auto& capabilities = params.capabilities.get();
  const auto& graph_optimizer_registry = params.graph_optimizer_registry.get();
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
  InlinedVector<NodeIndex> assigned_filtered_in_nodes;
  InlinedVector<const Node*> filtered_in_nodes;
#endif
  // Helper to create a GraphViewer that filters nodes based on layering_index if present.
  auto create_graph_viewer = [&](std::unique_ptr<IndexedSubGraph>& out_sub_graph,
                                 std::unique_ptr<GraphViewer>& out_viewer) -> Status {
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
    if (params.layering_index) {
      assigned_filtered_in_nodes.clear();
      filtered_in_nodes.clear();
      filtered_in_nodes.reserve(graph.NumberOfNodes());
 
      auto rules_opt = params.layering_index->GetLayeringRulesForThisEp(ep_type);
      if (rules_opt) {
        assigned_filtered_in_nodes.reserve(rules_opt->get().size());
      }
 
      for (auto& node : graph.Nodes()) {
        auto rule_idx_opt = params.layering_index->GetNodeAssignment(graph, node.Index());
        bool include = true;
        if (rule_idx_opt) {
          // If node has an assignment, include it only if it is assigned to this EP
          if (!rules_opt || rules_opt->get().count(*rule_idx_opt) == 0) {
            include = false;
          } else {
            assigned_filtered_in_nodes.push_back(node.Index());
          }
        }
        // If node has no assignment, it is included (available to any EP)
 
        if (include) {
          filtered_in_nodes.push_back(&node);
        }
      }
      ORT_RETURN_IF_ERROR(graph_utils::CreateFilteredIndexedGraph(filtered_in_nodes, graph, out_sub_graph));
      out_viewer = std::make_unique<GraphViewer>(graph, *out_sub_graph);
      return Status::OK();
    }
#else
    ORT_UNUSED_PARAMETER(out_sub_graph);
#endif
    out_viewer = std::make_unique<GraphViewer>(graph);
    return Status::OK();
  };
  // Helper to un-assign nodes that were assigned to this EP but not claimed by updated capabilities.
  auto reset_assignment_unclaimed_nodes =
      [&](const InlinedHashSet<NodeIndex>* additionally_claimed_nodes = nullptr) {
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
        if (params.layering_index) {
          auto rules_opt = params.layering_index->GetLayeringRulesForThisEp(ep_type);
          if (rules_opt) {
            const auto& ep_rules = rules_opt->get();
            InlinedHashSet<NodeIndex> claimed;
            for (const auto& cap : capabilities) {
              if (cap && cap->sub_graph) {
                for (auto idx : cap->sub_graph->nodes) claimed.insert(idx);
              }
            }
            if (additionally_claimed_nodes != nullptr) {
              claimed.insert(additionally_claimed_nodes->begin(), additionally_claimed_nodes->end());
            }
 
            // Check if all assigned filtered-in nodes are claimed
            // and if not make them available for subsequent EPs
            for (auto& node_index : assigned_filtered_in_nodes) {
              if (claimed.count(node_index) == 0) {
                auto rule_idx_opt = params.layering_index->GetNodeAssignment(graph, node_index);
                if (rule_idx_opt && ep_rules.count(*rule_idx_opt) > 0) {
                  params.layering_index->MakeNodeUnassigned(graph, node_index);
                }
              }
            }
            assigned_filtered_in_nodes.clear();
          }
        }
#else
        ORT_UNUSED_PARAMETER(additionally_claimed_nodes);
#endif
      };
 
  {
    std::unique_ptr<IndexedSubGraph> sub_graph_holder;
    std::unique_ptr<GraphViewer> graph_viewer;
    ORT_RETURN_IF_ERROR(create_graph_viewer(sub_graph_holder, graph_viewer));
 
    if (params.resource_accountant) {
      params.resource_accountant->ResetForNewPass();
    }
    ORT_RETURN_IF_ERROR(get_capabilities(current_ep, *graph_viewer, kernel_lookup, params.resource_accountant,
                                         graph_optimizer_registry, params.registered_ep_context_data_callbacks,
                                         capabilities));
 
    reset_assignment_unclaimed_nodes();
 
    if (params.check_load_cancellation_fn()) {
      return ORT_MAKE_STATUS(ONNXRUNTIME, MODEL_LOAD_CANCELED,
                             "Graph partitioning was canceled by user request");
    }
 
    if (capabilities.empty()) {
      return Status::OK();
    }
  }
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
  // Run layout transformer for EPs with preferred layout of NHWC
  // CPU EP layout transformation happens later when level 3 transformers are run.
  if (params.mode != GraphPartitioner::Mode::kAssignOnly && params.transform_layout.get() &&
      current_ep.GetPreferredLayout() == DataLayout::NHWC) {
    InlinedVector<NodeIndex> nodes_temporarily_assigned_to_ep;
    for (auto& capability : capabilities) {
      TryAssignNodes(graph, *capability->sub_graph, ep_type, &nodes_temporarily_assigned_to_ep);
    }
    if (params.layout_assigned_nodes != nullptr) {
      params.layout_assigned_nodes->insert(nodes_temporarily_assigned_to_ep.begin(),
                                           nodes_temporarily_assigned_to_ep.end());
    }
 
    const NodeIndex first_new_node = graph.MaxNodeIndex();
 
    // Perform layout transformation on the specific EP assigned graph
    bool modified = false;
    auto transform_status = params.transform_layout(graph, modified, current_ep, params.debug_graph_fn);
    if (!transform_status.IsOK()) {
      ClearExecutionProviderAssignments(graph, nodes_temporarily_assigned_to_ep, ep_type);
      return transform_status;
    }
    if (params.check_load_cancellation_fn()) {
      ClearExecutionProviderAssignments(graph, nodes_temporarily_assigned_to_ep, ep_type);
      return ORT_MAKE_STATUS(ONNXRUNTIME, MODEL_LOAD_CANCELED,
                             "GetCapabilities was canceled by user request");
    }
 
    // It is possible some new nodes are introduced during transformation. These nodes can be either existing nodes
    // which are reconstructed to update domain or completely new nodes which are necessary for layout transformation.
    // we always give GetCapability the second call as long as capabilities is not empty. GetCapability have different
    // behaviors for first/second call, the first call only tag those nodes supported by this EP and then
    // assigned by `AssignNodes`, the second call will do some node processing and
    // node fusion whenever ops were layout-sensitive or not.
    // So we are calling GetCapability twice here to make things simple and finish the following procedures;
    // 1. To process new nodes introduced by transform_layout function.
    // 2. To do Op-fusion and graph optimization
    // 3. QDQ node-group fusion
 
    const NodeIndex end_node = graph.MaxNodeIndex();
 
    // Pass-1 tags were applied tentatively without committing any resource-accountant
    // budget (see TryAssignNodes). Capture the per-node costs computed during pass-1,
    // keyed by node index, so the budget for the nodes that survive the second pass can
    // be committed after the drop step below. The costs must be captured here because
    // capabilities.clear() destroys the pass-1 capabilities (and their costs) next.
    InlinedHashMap<NodeIndex, ResourceCount> pass1_node_costs;
    InlinedHashMap<NodeIndex, WorkspaceEstimateSelection> pass1_workspace_estimates;
    if (params.resource_accountant != nullptr) {
      const InlinedHashSet<NodeIndex> temporarily_assigned_nodes{
          nodes_temporarily_assigned_to_ep.begin(), nodes_temporarily_assigned_to_ep.end()};
      for (const auto& capability : capabilities) {
        const auto& sub_graph = *capability->sub_graph;
        if (sub_graph.IsAccountingEnabled()) {
          for (size_t i = 0, limit = sub_graph.nodes.size(); i < limit; ++i) {
            const NodeIndex node_index = sub_graph.nodes[i];
            if (!temporarily_assigned_nodes.contains(node_index)) {
              continue;
            }
 
            pass1_node_costs.insert_or_assign(node_index, sub_graph.GetNodeCost(i));
            pass1_workspace_estimates.insert_or_assign(
                node_index, params.resource_accountant->GetPendingWorkspaceEstimateSelection(node_index));
          }
        }
      }
 
      // Provisionally reserve costs only for nodes that were actually tagged in pass 1. Pass 2 may
      // introduce newly claimable nodes, and its admission decisions must include the cost of
      // pass-1 survivors. Nodes that do not survive pass 2 are rolled back below.
      for (NodeIndex node_index : nodes_temporarily_assigned_to_ep) {
        if (const auto cost_it = pass1_node_costs.find(node_index);
            cost_it != pass1_node_costs.end()) {
          params.resource_accountant->AddConsumedAmount(cost_it->second);
        }
      }
    }
 
    // Keep pass-1 EP assignments through the second GetCapability call so that EPs can
    // recognize already-tagged nodes (e.g. nodes transformed into kMSInternalNHWCDomain).
    capabilities.clear();
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
    if (params.layering_index && end_node > first_new_node) {
      // We need to update the LayeringIndex with newly created nodes
      // as the layout transformation may have created new nodes
      // with inherited annotations
      InlinedVector<NodeIndex> new_node_indices;
      for (NodeIndex idx = first_new_node; idx < end_node; ++idx) {
        if (graph.GetNode(idx) != nullptr) {
          new_node_indices.push_back(idx);
        }
      }
      params.layering_index->Update(graph, new_node_indices);
    }
#endif
 
    std::unique_ptr<IndexedSubGraph> sub_graph_holder;
    std::unique_ptr<GraphViewer> graph_viewer;
    ORT_RETURN_IF_ERROR(create_graph_viewer(sub_graph_holder, graph_viewer));
 
    auto collect_pass2_nodes = [&](const std::vector<std::unique_ptr<ComputeCapability>>& pass_capabilities) {
      std::pair<InlinedHashSet<NodeIndex>, InlinedHashSet<NodeIndex>> result;
      auto& [pass2_nodes, new_nodes] = result;
      for (const auto& capability : pass_capabilities) {
        for (auto node_index : capability->sub_graph->nodes) {
          pass2_nodes.insert(node_index);
          if (node_index >= first_new_node) {
            new_nodes.insert(node_index);
          }
        }
      }
      return result;
    };
 
    InlinedHashSet<NodeIndex> confirmed_pass1_survivors;
    InlinedHashSet<NodeIndex> independently_runnable_survivors;
    InlinedHashSet<NodeIndex> pass1_nodes_to_reprobe;
    InlinedHashSet<NodeIndex> reserved_pass1_survivors;
    std::vector<std::unique_ptr<ComputeCapability>> confirmed_survivor_capabilities;
    if (params.resource_accountant) {
      if (modified) {
        ORT_RETURN_IF_ERROR(RefreshMaxShapeInference(graph, *params.resource_accountant));
      }
 
      // Discover the complete second-pass support set without budget gating. A budgeted
      // GetCapability call can stop before visiting later pass-1 survivors, so absence from
      // a truncated result does not prove that a provisional reservation should be removed.
      params.resource_accountant->ResetForNewPass();
      ORT_RETURN_IF_ERROR(get_capabilities(current_ep, *graph_viewer, kernel_lookup, nullptr, graph_optimizer_registry,
                                           params.registered_ep_context_data_callbacks, capabilities));
 
      if (params.check_load_cancellation_fn()) {
        ClearExecutionProviderAssignments(graph, nodes_temporarily_assigned_to_ep, ep_type);
        return ORT_MAKE_STATUS(ONNXRUNTIME, MODEL_LOAD_CANCELED,
                               "GetCapabilities was canceled by user request");
      }
 
      const auto [discovered_pass2_nodes, unused_discovered_new_nodes] =
          collect_pass2_nodes(capabilities);
      ORT_UNUSED_PARAMETER(unused_discovered_new_nodes);
      for (NodeIndex node_index : nodes_temporarily_assigned_to_ep) {
        if (discovered_pass2_nodes.contains(node_index)) {
          confirmed_pass1_survivors.insert(node_index);
        }
      }
 
      // Re-probe a survivor when it is grouped with a pass-2-only node, or when its
      // capability has optimization work but no MetaDef. In both cases the pass-1 tag
      // would either hide its cost or prevent the capability from being processed.
      for (auto& capability : capabilities) {
        const auto& nodes = capability->sub_graph->nodes;
        const size_t confirmed_survivor_count =
            static_cast<size_t>(std::count_if(
                nodes.begin(), nodes.end(),
                [&](NodeIndex node_index) {
                  return confirmed_pass1_survivors.contains(node_index);
                }));
        if (confirmed_survivor_count == 0) {
          continue;
        }
 
        if (confirmed_survivor_count != nodes.size()) {
          for (NodeIndex node_index : nodes) {
            if (confirmed_pass1_survivors.contains(node_index)) {
              pass1_nodes_to_reprobe.insert(node_index);
            }
          }
          continue;
        }
 
        if (capability->sub_graph->GetMetaDef() != nullptr) {
          confirmed_survivor_capabilities.push_back(std::move(capability));
        } else if (nodes.size() == 1 && capability->nodes_to_optimize.empty()) {
          independently_runnable_survivors.insert(nodes.front());
        } else {
          pass1_nodes_to_reprobe.insert(nodes.begin(), nodes.end());
        }
      }
 
      // Remove the original provisional reservations. The exact retained survivor set is
      // determined below using an accountant-aware capability pass without budget truncation.
      for (NodeIndex node_index : nodes_temporarily_assigned_to_ep) {
        const auto cost_it = pass1_node_costs.find(node_index);
        if (cost_it != pass1_node_costs.end()) {
          params.resource_accountant->RemoveConsumedAmount(cost_it->second);
        }
      }
      params.resource_accountant->ResetForNewPass();
 
      for (NodeIndex node_index : pass1_nodes_to_reprobe) {
        if (auto* node = graph.GetNode(node_index);
            node != nullptr && node->GetExecutionProviderType() == ep_type) {
          node->SetExecutionProviderType("");
        }
        pass1_workspace_estimates.erase(node_index);
        pass1_node_costs.erase(node_index);
      }
 
      auto get_reconciled_capabilities =
          [&](const std::vector<std::unique_ptr<ComputeCapability>>& pass_capabilities) {
            InlinedVector<const ComputeCapability*> reconciled_capabilities;
            reconciled_capabilities.reserve(
                pass_capabilities.size() + confirmed_survivor_capabilities.size());
            for (const auto& capability : pass_capabilities) {
              reconciled_capabilities.push_back(capability.get());
            }
 
            for (const auto& survivor_capability : confirmed_survivor_capabilities) {
              const auto& survivor_nodes = survivor_capability->sub_graph->nodes;
              const InlinedHashSet<NodeIndex> survivor_node_set{
                  survivor_nodes.begin(), survivor_nodes.end()};
              const bool covered_by_final_capability =
                  std::any_of(
                      reconciled_capabilities.begin(), reconciled_capabilities.end(),
                      [&](const ComputeCapability* capability) {
                        const auto& final_nodes = capability->sub_graph->nodes;
                        return std::all_of(
                            survivor_nodes.begin(), survivor_nodes.end(),
                            [&](NodeIndex survivor_node_index) {
                              return std::find(final_nodes.begin(), final_nodes.end(),
                                               survivor_node_index) != final_nodes.end();
                            });
                      });
              if (covered_by_final_capability) {
                continue;
              }
 
              const bool overlaps_final_capabilities =
                  std::any_of(
                      reconciled_capabilities.begin(), reconciled_capabilities.end(),
                      [&](const ComputeCapability* capability) {
                        const auto& nodes = capability->sub_graph->nodes;
                        return std::any_of(
                            nodes.begin(), nodes.end(),
                            [&](NodeIndex node_index) {
                              return survivor_node_set.contains(node_index);
                            });
                      });
              if (overlaps_final_capabilities) {
                const bool can_replace_overlapping_capabilities =
                    std::all_of(
                        reconciled_capabilities.begin(), reconciled_capabilities.end(),
                        [&](const ComputeCapability* capability) {
                          const auto& nodes = capability->sub_graph->nodes;
                          const bool overlaps_survivor =
                              std::any_of(
                                  nodes.begin(), nodes.end(),
                                  [&](NodeIndex node_index) {
                                    return survivor_node_set.contains(node_index);
                                  });
                          return !overlaps_survivor ||
                                 (!capability->sub_graph->IsAccountingEnabled() &&
                                  std::all_of(nodes.begin(), nodes.end(),
                                              [&](NodeIndex node_index) {
                                                return confirmed_pass1_survivors.contains(node_index);
                                              }));
                        });
                if (!can_replace_overlapping_capabilities) {
                  continue;
                }
 
                reconciled_capabilities.erase(
                    std::remove_if(
                        reconciled_capabilities.begin(), reconciled_capabilities.end(),
                        [&](const ComputeCapability* capability) {
                          const auto& nodes = capability->sub_graph->nodes;
                          return std::any_of(
                              nodes.begin(), nodes.end(),
                              [&](NodeIndex node_index) {
                                return survivor_node_set.contains(node_index);
                              });
                        }),
                    reconciled_capabilities.end());
              }
 
              reconciled_capabilities.push_back(survivor_capability.get());
            }
 
            return reconciled_capabilities;
          };
 
      auto collect_reconciled_pass2_nodes =
          [&](const InlinedVector<const ComputeCapability*>& reconciled_capabilities) {
            InlinedHashSet<NodeIndex> reconciled_nodes;
            for (const ComputeCapability* capability : reconciled_capabilities) {
              reconciled_nodes.insert(
                  capability->sub_graph->nodes.begin(), capability->sub_graph->nodes.end());
            }
            reconciled_nodes.insert(independently_runnable_survivors.begin(),
                                    independently_runnable_survivors.end());
            return reconciled_nodes;
          };
 
      auto rebuild_survivor_reservations =
          [&](const InlinedHashSet<NodeIndex>& retained_pass1_survivors) -> Status {
        for (NodeIndex node_index : reserved_pass1_survivors) {
          const auto cost_it = pass1_node_costs.find(node_index);
          if (cost_it != pass1_node_costs.end()) {
            params.resource_accountant->RemoveConsumedAmount(cost_it->second);
          }
        }
        reserved_pass1_survivors.clear();
        params.resource_accountant->ResetForNewPass();
 
        // Recompute retained survivor costs together so shared initializers are charged
        // exactly once to the finalized survivor set.
        for (NodeIndex node_index : nodes_temporarily_assigned_to_ep) {
          if (!retained_pass1_survivors.contains(node_index) ||
              pass1_nodes_to_reprobe.contains(node_index)) {
            continue;
          }
 
          const Node* node = graph.GetNode(node_index);
          ORT_RETURN_IF_NOT(node != nullptr, "Pass-1 survivor node ", node_index, " no longer exists.");
 
          std::optional<Level1MemoryEstimate> level1_memory_estimate;
          const auto workspace_it = pass1_workspace_estimates.find(node_index);
          if (workspace_it != pass1_workspace_estimates.end() &&
              workspace_it->second.source != WorkspaceEstimateSource::kNone) {
            const auto& selection = workspace_it->second;
            Level1MemoryEstimate estimate;
            if (selection.source == WorkspaceEstimateSource::kEstimator ||
                selection.source == WorkspaceEstimateSource::kProfileAndEstimator) {
              estimate.runtime_workspace_bytes = selection.level1_estimated_bytes;
            } else {
              estimate.runtime_transient_bytes = selection.level1_estimated_bytes;
            }
            estimate.persistent_prepack_bytes = selection.persistent_prepack_bytes;
            estimate.initialization_scratch_bytes = selection.initialization_scratch_bytes;
            level1_memory_estimate = estimate;
          }
 
          const ResourceCount recomputed_cost =
              params.resource_accountant->ComputeResourceCount(*node, level1_memory_estimate);
          pass1_node_costs.insert_or_assign(node_index, recomputed_cost);
          params.resource_accountant->AddConsumedAmount(recomputed_cost);
          reserved_pass1_survivors.insert(node_index);
        }
        return Status::OK();
      };
 
      if (confirmed_survivor_capabilities.empty()) {
        ORT_RETURN_IF_ERROR(rebuild_survivor_reservations(confirmed_pass1_survivors));
        capabilities.clear();
        ORT_RETURN_IF_ERROR(get_capabilities(current_ep, *graph_viewer, kernel_lookup,
                                             params.resource_accountant, graph_optimizer_registry,
                                             params.registered_ep_context_data_callbacks, capabilities));
      } else {
        // First obtain the complete accountant-aware capability grouping. This identifies
        // survivor capabilities displaced by newly accounted overlaps without allowing stale
        // survivor reservations to truncate the result.
        const auto original_threshold = params.resource_accountant->GetThreshold();
        params.resource_accountant->SetThreshold(
            ResourceCount{std::numeric_limits<size_t>::max()});
        capabilities.clear();
        const auto capability_status = get_capabilities(current_ep, *graph_viewer, kernel_lookup,
                                                        params.resource_accountant, graph_optimizer_registry,
                                                        params.registered_ep_context_data_callbacks, capabilities);
        params.resource_accountant->SetThreshold(original_threshold);
        ORT_RETURN_IF_ERROR(capability_status);
 
        if (params.check_load_cancellation_fn()) {
          ClearExecutionProviderAssignments(graph, nodes_temporarily_assigned_to_ep, ep_type);
          return ORT_MAKE_STATUS(ONNXRUNTIME, MODEL_LOAD_CANCELED,
                                 "GetCapabilities was canceled by user request");
        }
 
        auto expected_retained_nodes =
            collect_reconciled_pass2_nodes(get_reconciled_capabilities(capabilities));
        const size_t max_reconciliation_attempts = confirmed_pass1_survivors.size() + 2;
        bool reconciliation_stable = false;
        for (size_t attempt = 0; attempt < max_reconciliation_attempts; ++attempt) {
          ORT_RETURN_IF_ERROR(rebuild_survivor_reservations(expected_retained_nodes));
 
          capabilities.clear();
          ORT_RETURN_IF_ERROR(get_capabilities(current_ep, *graph_viewer, kernel_lookup,
                                               params.resource_accountant, graph_optimizer_registry,
                                               params.registered_ep_context_data_callbacks, capabilities));
 
          if (params.check_load_cancellation_fn()) {
            ClearExecutionProviderAssignments(graph, nodes_temporarily_assigned_to_ep, ep_type);
            return ORT_MAKE_STATUS(ONNXRUNTIME, MODEL_LOAD_CANCELED,
                                   "GetCapabilities was canceled by user request");
          }
 
          auto actual_retained_nodes =
              collect_reconciled_pass2_nodes(get_reconciled_capabilities(capabilities));
          const bool retained_set_matches =
              actual_retained_nodes.size() == expected_retained_nodes.size() &&
              std::all_of(actual_retained_nodes.begin(), actual_retained_nodes.end(),
                          [&](NodeIndex node_index) {
                            return expected_retained_nodes.contains(node_index);
                          });
          if (retained_set_matches) {
            reconciliation_stable = true;
            break;
          }
 
          expected_retained_nodes = std::move(actual_retained_nodes);
        }
 
        ORT_RETURN_IF_NOT(
            reconciliation_stable,
            "NHWC capability/resource reconciliation did not converge for execution provider ",
            ep_type, ".");
 
        const auto reconciled_capabilities = get_reconciled_capabilities(capabilities);
        const InlinedHashSet<const ComputeCapability*> retained_capabilities{
            reconciled_capabilities.begin(), reconciled_capabilities.end()};
        capabilities.erase(
            std::remove_if(
                capabilities.begin(), capabilities.end(),
                [&](const std::unique_ptr<ComputeCapability>& capability) {
                  return !retained_capabilities.contains(capability.get());
                }),
            capabilities.end());
        for (auto& survivor_capability : confirmed_survivor_capabilities) {
          if (retained_capabilities.contains(survivor_capability.get())) {
            capabilities.push_back(std::move(survivor_capability));
          }
        }
      }
    } else {
      ORT_RETURN_IF_ERROR(get_capabilities(current_ep, *graph_viewer, kernel_lookup, nullptr, graph_optimizer_registry,
                                           params.registered_ep_context_data_callbacks, capabilities));
    }
 
    if (params.check_load_cancellation_fn()) {
      ClearExecutionProviderAssignments(graph, nodes_temporarily_assigned_to_ep, ep_type);
      return ORT_MAKE_STATUS(ONNXRUNTIME, MODEL_LOAD_CANCELED,
                             "GetCapabilities was canceled by user request");
    }
 
    auto [pass2_node_indices, new_nodes_in_capabilities] = collect_pass2_nodes(capabilities);
    pass2_node_indices.insert(independently_runnable_survivors.begin(),
                              independently_runnable_survivors.end());
    reset_assignment_unclaimed_nodes(&pass2_node_indices);
 
    // Clear temporary assignments that were not reclaimed by the complete discovery pass.
    for (NodeIndex node_index : nodes_temporarily_assigned_to_ep) {
      if (pass2_node_indices.count(node_index) != 0) continue;
 
      auto* node = graph.GetNode(node_index);
      if (node != nullptr && node->GetExecutionProviderType() == ep_type) {
        node->SetExecutionProviderType("");
      }
    }
 
    // Finalize the rebuilt pass-1 survivor reservations. New nodes introduced for pass 2
    // carry their own costs and are accounted normally when their partitions are placed.
    if (params.resource_accountant != nullptr) {
      for (NodeIndex node_index : nodes_temporarily_assigned_to_ep) {
        if (!reserved_pass1_survivors.contains(node_index)) {
          continue;
        }
 
        auto cost_it = pass1_node_costs.find(node_index);
        if (cost_it == pass1_node_costs.end()) {
          continue;
        }
 
        const auto* node = graph.GetNode(node_index);
        if (node == nullptr || node->GetExecutionProviderType() != ep_type) {
          params.resource_accountant->RemoveConsumedAmount(cost_it->second);
          continue;
        }
 
        params.resource_accountant->CommitResourcesForNode(node_index);
      }
    }
 
    for (NodeIndex idx = first_new_node; idx < end_node; ++idx) {
      const Node* node = graph.GetNode(idx);
      if (params.layout_assigned_nodes != nullptr && node != nullptr &&
          node->GetExecutionProviderType() == ep_type) {
        params.layout_assigned_nodes->insert(idx);
      }
      if (node != nullptr && node->Domain() == kMSInternalNHWCDomain) {
        if (new_nodes_in_capabilities.count(node->Index()) == 0) {
          return ORT_MAKE_STATUS(
              ONNXRUNTIME, FAIL,
              "Node '", node->Name(), "' OpType:", node->OpType(), " with domain:", kMSInternalNHWCDomain,
              " was inserted using the NHWC format as requested by ", ep_type, ", but was not selected",
              " by that EP. This means the graph is now invalid as there will not be an EP able to run the node."
              " This could be a bug in layout transformer, or in the GetCapability implementation of the EP.");
        }
      }
    }
  }
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
 
  return Status::OK();
}
 
#if !defined(ORT_MINIMAL_BUILD)
 
// This function queries the capabilities for a given EP, but it does not assign the nodes.
// It also does not perform layout transformation. This will be done during normal partitioning.
static Status GetCapabilityForEPForAotInlining(const GraphViewer& graph_viewer,
                                               const KernelRegistryManager& kernel_registry_mgr,
                                               const IExecutionProvider& current_ep,
                                               const GraphOptimizerRegistry& graph_optimizer_registry,
                                               const logging::Logger& logger,
                                               uint32_t registered_ep_context_data_callbacks,
                                               std::vector<std::unique_ptr<ComputeCapability>>& capabilities) {
  const auto& ep_type = current_ep.Type();
 
  const auto kernel_registries_for_ep = kernel_registry_mgr.GetKernelRegistriesByProviderType(ep_type);
  const KernelLookup kernel_lookup{ep_type,
                                   kernel_registries_for_ep,
                                   kernel_registry_mgr.GetKernelTypeStrResolver(),
                                   logger};
 
  // TODO: Provide EP with a capability to look inside the functions.
  ORT_RETURN_IF_ERROR(get_capabilities(current_ep, graph_viewer, kernel_lookup, nullptr, graph_optimizer_registry,
                                       registered_ep_context_data_callbacks, capabilities));
 
  return Status::OK();
}
 
#endif  // !defined(ORT_MINIMAL_BUILD)
 
/**
 * Check whether the given IndexedSubGraph is available for assigning to a specific provider.
 *
 */
static bool IsIndexedSubGraphAvailableForAssignment(Graph& graph,
                                                    const IndexedSubGraph& capability,
                                                    GraphPartitioner::Mode mode,
                                                    const std::string& provider_type,
                                                    const InlinedHashSet<NodeIndex>* layout_assigned_nodes = nullptr) {
  // The provider can run a single node in the <graph> if not using meta-defs.
  if (capability.GetMetaDef() == nullptr && capability.nodes.size() == 1) {
    auto* node = graph.GetNode(capability.nodes[0]);
    if (nullptr != node &&
        (node->GetExecutionProviderType().empty() ||
         (node->GetExecutionProviderType() == provider_type && layout_assigned_nodes != nullptr &&
          layout_assigned_nodes->contains(node->Index())))) {
      // Accept provisional NHWC tags, but do not reprocess assignments from an earlier partitioning round.
      return true;
    }
    return false;
  }
 
  // if mode is kAssignOnly we want all nodes that can _potentially_ be taken by compiling EPs to be assigned,
  // so that we aggregate the nodes covered and ensure the original nodes remain in the ORT format model by
  // preventing level 2 and 3 optimizers from changing them. optimizers check the EP the node is assigned to
  // and only make changes if the EP is on the optimizer's list of supported EPs. an EP that compiles nodes
  // should never be on those lists.
  //
  // when the ORT format model is loaded we will process it normally with EP priority being applied for
  // whichever EPs are enabled at the time.
  //
  // e.g. an Android NNAPI EP may take different/overlapping nodes to a iOS CoreML EP.
  // We want the ORT format model to be able to be run as efficiently as possible on either platform,
  // so we want all the nodes that either may take to be preserved. If we did not do this we would
  // need to create one ORT format model for Android and one for iOS.
  if (mode == GraphPartitioner::Mode::kAssignOnly) {
    return true;
  }
 
  for (auto node_index : capability.nodes) {
    const auto* node = graph.GetNode(node_index);
    if ((nullptr == node) ||
        (!node->GetExecutionProviderType().empty() && node->GetExecutionProviderType() != provider_type)) {
      // The node was fused or assigned, so that the whole sub-graph will not be assigned to this <provider>
      // The assumption is that this <provider> can only run the sub-graph as a whole unit.
      return false;
    }
  }
 
  return true;
}
 
static bool IsExternalEpContextNode(const Node& node) {
  if (node.Domain() != kMSDomain || node.OpType() != "EPContext") {
    return false;
  }
 
  const auto& attributes = node.GetAttributes();
  const auto embed_mode = attributes.find("embed_mode");
  return embed_mode != attributes.end() && embed_mode->second.i() == 0;
}
 
static bool IndexedSubGraphHasExternalEpContextNode(const Graph& graph,
                                                    const IndexedSubGraph& indexed_sub_graph) {
  return std::any_of(indexed_sub_graph.nodes.cbegin(), indexed_sub_graph.nodes.cend(),
                     [&graph](NodeIndex node_index) {
                       const auto* node = graph.GetNode(node_index);
                       return node != nullptr && IsExternalEpContextNode(*node);
                     });
}
 
static bool GraphHasAssignedExternalEpContextNode(const Graph& graph, std::string_view provider_type) {
  // NHWC survivors can remain assigned without a returned capability after resource-accountant reconciliation.
  for (const auto& node : graph.Nodes()) {
    if (node.GetExecutionProviderType() == provider_type && IsExternalEpContextNode(node)) {
      return true;
    }
  }
 
  return false;
}
 
#if !defined(ORT_MINIMAL_BUILD)
 
/**
 * Return a fused node or assign the nodes in the indexed subgraph to the current EP.
 *
 * \param graph
 * \param capability
 * \param kernel_registry_mgr
 * \param provider_type name of the provider to test
 * \param mode
 * \param fused_node_unique_id A counter for generating fused node names. Unique across the entire model.
 * \return Fused node. Return nullptr if there is no fuse
 */
static Node* PlaceNode(Graph& graph, const IndexedSubGraph& capability,
                       IExecutionProvider::FusionStyle fusion_style,
                       const std::string& provider_type,
                       GraphPartitioner::Mode mode,
                       int& fused_node_unique_id) {
  Node* result = nullptr;
 
  if (nullptr == capability.GetMetaDef()) {
    TryAssignSingleNode(graph, capability, provider_type);
  } else {
    const bool acc_enabled = capability.IsAccountingEnabled();
    if (mode == GraphPartitioner::Mode::kNormal) {
      std::ostringstream oss;
      oss << provider_type << "_" << capability.GetMetaDef()->name << "_" << fused_node_unique_id++;
      std::string node_name = oss.str();
 
      Node* fused_node = nullptr;
      if (fusion_style == IExecutionProvider::FusionStyle::Function) {
        fused_node = &graph.FuseSubGraph(capability, node_name);
      } else {
        // create a fused node without copying everything to a Function body. The IndexedSubGraph will be passed
        // through to Compile via a filtered GraphViewer.
        fused_node = &graph.BeginFuseSubGraph(capability, node_name);
      }
 
      fused_node->SetExecutionProviderType(provider_type);
      if (acc_enabled) {
        // Account for all constituent nodes using the per-node costs computed
        // during GetCapability() (which already includes within-pass weight dedup).
        // Computing the cost for the newly created fused node would undercount
        // because the fused node often doesn't expose all original initializers,
        // and would commit weights for the wrong node index.
        capability.AccountForAllNodes(fused_node->GetContainingGraph(), fused_node->Index());
      }
      result = fused_node;
    } else {
      // assign the nodes in the indexed subgraph to the current EP so that level 2+ optimizers will not change them.
      // This is used when exporting an ORT format model to maintain the original nodes and re-do the fusion
      // at runtime. The original nodes provide a fallback if fewer nodes can be fused at runtime due to device
      // capabilities.
      for (size_t i = 0, limit = capability.nodes.size(); i < limit; ++i) {
        auto* node = graph.GetNode(capability.nodes[i]);
        if (node != nullptr) {
          node->SetExecutionProviderType(provider_type);
          if (acc_enabled) {
            capability.AccountForNode(i);
          }
        }
      }
    }
  }
 
  return result;
}
 
// for the current EP, recursively iterate through the Graph and any nested subgraphs (recursion is bottom-up).
// assign any nodes to the EP that are currently unassigned, and that the EP can handle.
static Status PartitionOnnxFormatModelImpl(Graph& graph, FuncManager& func_mgr,
                                           KernelRegistryManager& kernel_registry_mgr,
                                           KernelRegistry& fused_kernel_registry,
                                           IExecutionProvider& current_ep,
                                           GraphPartitioner::Mode mode,
                                           int& fused_node_unique_id,
                                           const layout_transformation::TransformLayoutFunction& transform_layout_fn,
                                           const layout_transformation::DebugGraphFn& debug_graph_fn,
                                           const CheckLoadCancellationFn& check_load_cancellation_fn,
                                           const OnPartitionAssignmentFunction& on_partition_assignment_fn,
                                           const logging::Logger& logger, IResourceAccountant* resource_accountant,
                                           const GraphOptimizerRegistry& graph_optimizer_registry,
                                           bool disable_model_compile,
                                           uint32_t registered_ep_context_data_callbacks,
                                           bool ep_context_data_write_callback_required,
                                           LayeringIndex* layering_index) {  // Added arg
  // handle testing edge case where optimizers or constant lifting results in graph with no nodes.
  // doing it here saves all providers checking for this in GetCapability
  if (graph.NumberOfNodes() == 0) {
    return Status::OK();
  }
 
  // recurse into nested graphs first to partition bottom up.
  for (auto& node : graph.Nodes()) {
    for (auto& entry : node.GetAttributeNameToMutableSubgraphMap()) {
      Graph* subgraph = entry.second;
      // we pass through the FuncManager from the top level graph
      ORT_RETURN_IF_ERROR(PartitionOnnxFormatModelImpl(*subgraph, func_mgr, kernel_registry_mgr,
                                                       fused_kernel_registry, current_ep, mode, fused_node_unique_id,
                                                       transform_layout_fn, debug_graph_fn,
                                                       check_load_cancellation_fn,
                                                       on_partition_assignment_fn,
                                                       logger, resource_accountant,
                                                       graph_optimizer_registry, disable_model_compile,
                                                       registered_ep_context_data_callbacks,
                                                       ep_context_data_write_callback_required,
                                                       layering_index));  // Pass through
    }
  }
 
  // If an execution provider returns the capability that it can run a sub-graph,
  // onnxruntime will fuse the sub-graph into a function node. For compilation
  // based execution providers (one which needs to compile graph at runtime.
  // Indicated by need_compile flag), onnxruntime will invoke the "Compile" method
  // to get compiled binary. There are two mode of compile, one is return the entry
  // point to the compiled binary directly, another is export the compiled binary to
  // shared library for future reuse.
 
  // TODO: when the graph contains a function node, and user passes in the dll which could
  // run the function by SessionOption, we should create a function kernel for it and
  // delegate the compute to the functions inside the dlls.
  std::vector<std::unique_ptr<ComputeCapability>> capabilities;
  InlinedHashSet<NodeIndex> layout_assigned_nodes;
  const auto get_capability_params = GetCapabilityForEPParams{
      std::ref(graph),
      std::cref(kernel_registry_mgr),
      std::ref(current_ep),
      std::ref(capabilities),
      mode,
      std::cref(transform_layout_fn),
      std::cref(debug_graph_fn),
      resource_accountant,
      std::ref(graph_optimizer_registry),
      std::cref(check_load_cancellation_fn),
      layering_index,
      registered_ep_context_data_callbacks,
      &layout_assigned_nodes};
 
  ORT_RETURN_IF_ERROR(GetCapabilityForEP(get_capability_params, logger));
 
  const std::string& type = current_ep.Type();
  auto fusion_style = current_ep.GetFusionStyle();
  std::vector<Node*> nodes_to_compile;
 
  // The fused node may map to an existing kernel, so it is fused but doesn't need to be compiled
  // But we still need to finalize the graph fusion for those nodes.
  std::vector<Node*> nodes_to_complete_fuse;
  std::vector<std::unique_ptr<ComputeCapability>> capabilities_to_complete_fuse;
 
  // filter out the ComputeCapability instances that do not need compiling so we have a std::vector that's 1:1 with
  // nodes_to_compile.
  std::vector<std::unique_ptr<ComputeCapability>> capabilities_to_compile;
  bool accepted_external_ep_context_capability = false;
  capabilities_to_compile.reserve(std::count_if(capabilities.cbegin(), capabilities.cend(),
                                                [](const std::unique_ptr<ComputeCapability>& entry) {
                                                  return entry != nullptr &&
                                                         entry->sub_graph != nullptr &&
                                                         entry->sub_graph->GetMetaDef() != nullptr;
                                                }));
 
  for (auto& capability : capabilities) {
    // The <provider> can run a fused <sub_graph> in the <graph>.
    // Check whether any node in the <sub_graph> was already assigned. If so it cannot be stolen as assignment is done
    // in order of EP priority
    bool sub_graph_available_for_assignment =
        IsIndexedSubGraphAvailableForAssignment(graph, *capability->sub_graph, mode, type, &layout_assigned_nodes);
 
    // If the <sub_graph> is available to be assigned to the EP and the ComputeCapability has nodes_to_optimize,
    // run EP related optimizations and update ComputeCapability.
    if (sub_graph_available_for_assignment && !capability->nodes_to_optimize.empty()) {
      for (auto& optimization_cc : capability->nodes_to_optimize) {
        if (optimization_cc->optimization_func) {
          auto status = optimization_cc->optimization_func(graph, *optimization_cc, *capability, graph_optimizer_registry);
          if (status != Status::OK()) {
            return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, type, "The optimization function failed to finish.");
          }
          // #TODO: Handle nested optimization ComputeCapability
        }
      }
    }
 
    Node* n = nullptr;
    if (sub_graph_available_for_assignment) {
      accepted_external_ep_context_capability |=
          IndexedSubGraphHasExternalEpContextNode(graph, *capability->sub_graph);
 
      if (on_partition_assignment_fn) {
        // Call custom function provided by owner of GraphPartitioner whenever a subgraph is assigned to an EP.
        // This can be used, for example, to collect partitioning information.
        on_partition_assignment_fn(graph, *capability, type);
      }
 
      n = PlaceNode(graph, *capability->sub_graph, fusion_style, type, mode, fused_node_unique_id);
    }
    if (n != nullptr) {
      // searching in kernel registries, if no kernel registered for the fused_node, use compile approach
      if (!KernelRegistryManager::HasImplementationOf(kernel_registry_mgr, *n, type, logger)) {
        nodes_to_compile.push_back(n);
        capabilities_to_compile.push_back(std::move(capability));
      } else {
        // there is a predefined kernel for the fused node. doesn't need compile, but need to complete the fusing.
        nodes_to_complete_fuse.push_back(n);
        capabilities_to_complete_fuse.push_back(std::move(capability));
      }
    }
  }
 
  uint32_t required_ep_context_data_support = OrtEpContextDataCallbackSupportFlags_NONE;
  if (ep_context_data_write_callback_required && !nodes_to_compile.empty()) {
    required_ep_context_data_support |= OrtEpContextDataCallbackSupportFlags_WRITE;
  }
 
  if ((registered_ep_context_data_callbacks & OrtEpContextDataCallbackSupportFlags_READ) != 0 &&
      (accepted_external_ep_context_capability || GraphHasAssignedExternalEpContextNode(graph, type))) {
    required_ep_context_data_support |= OrtEpContextDataCallbackSupportFlags_READ;
  }
 
  ORT_RETURN_IF_ERROR(CheckEpContextDataSupport(current_ep, required_ep_context_data_support));
 
  if (capabilities.empty()) {
    return Status::OK();
  }
 
  // Helper function that returns true if any of the nodes assigned to a compiling EP is not already compiled.
  auto graph_viewer_has_non_compiled_node = [](const GraphViewer& graph_viewer) -> bool {
    for (const auto& node : graph_viewer.Nodes()) {
      if (node.OpType() != "EPContext") {
        return true;
      }
    }
    return false;
  };
 
  // NOTE: if mode_ is kAssignOnly, nodes_to_compile will be empty at this point due to logic in PlaceNode
  // even with single node, EP might still want to compile it.
  // for example, it want to JIT an optimized kernel for LSTM with a given shape.
  if (!nodes_to_compile.empty()) {
    std::vector<NodeComputeInfo> node_compute_funcs;
    // !!! The Function style fusion is deprecated.
    if (fusion_style == IExecutionProvider::FusionStyle::Function) {
      // Create a Function based node where the fused nodes have a new Graph instance.
      return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, type, "The Function Style fusion is deprecated.");
    } else {
      // temporary storage for the GraphViewer for each IndexedSubGraph
      std::vector<std::unique_ptr<GraphViewer>> viewers;
      viewers.reserve(nodes_to_compile.size());
      std::vector<IExecutionProvider::FusedNodeAndGraph> nodes_and_viewers;
      nodes_and_viewers.reserve(nodes_to_compile.size());
 
      for (size_t j = 0, end = nodes_to_compile.size(); j < end; j++) {
        auto* node = nodes_to_compile[j];
        const auto& cur_capability = *capabilities_to_compile[j];
        auto graph_viewer = std::make_unique<GraphViewer>(graph, *cur_capability.sub_graph);
 
        if (disable_model_compile && graph_viewer_has_non_compiled_node(*graph_viewer)) {
          return ORT_MAKE_STATUS(ONNXRUNTIME, MODEL_REQUIRES_COMPILATION, "User disabled EP compilation but EP '",
                                 type, "' needs to compile one or more nodes.");
        }
 
        viewers.push_back(std::move(graph_viewer));
        nodes_and_viewers.push_back(IExecutionProvider::FusedNodeAndGraph{*node, *viewers.back()});
      }
 
      ORT_RETURN_IF_ERROR(current_ep.Compile(nodes_and_viewers, node_compute_funcs));
      ORT_RETURN_IF(check_load_cancellation_fn(),
                    "Graph partitioning is canceled due to user request.");
 
      if (node_compute_funcs.size() != nodes_to_compile.size()) {
        return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, type, " did not return correct number of compiled functions");
      }
 
      for (size_t j = 0, end = nodes_to_compile.size(); j < end; j++) {
        auto* node = nodes_to_compile[j];
 
        ORT_RETURN_IF_ERROR(func_mgr.AddFuncInfo(node->Name(), std::move(node_compute_funcs[j])));
 
        const auto& cur_capability = capabilities_to_compile[j];
        const IndexedSubGraph& indexed_sub_graph = *cur_capability->sub_graph;
        const IndexedSubGraph::MetaDef& metadef = *indexed_sub_graph.GetMetaDef();
 
        // create the func kernel for the name in the MetaDef. this is also the node name and that name that will
        // used as the key in the FuncManager entry. We need the registry to own the KernelCreateInfo that is
        // used by SessionState
        KernelDefBuilder builder;
        BuildFusedKernelDef(builder, metadef, type);
        ORT_RETURN_IF_ERROR(fused_kernel_registry.Register(
            builder,
            [](FuncManager& func_mgr, const OpKernelInfo& info, std::unique_ptr<OpKernel>& out) -> Status {
              return FunctionKernel::Create(func_mgr, info, out);
            }));
 
        // now that we're done compiling we can remove the original nodes from the Graph and wire in the new one
        graph.FinalizeFuseSubGraph(indexed_sub_graph, *node);
      }
    }
  }
 
  if (!nodes_to_complete_fuse.empty()) {
    for (size_t j = 0, end = nodes_to_complete_fuse.size(); j < end; j++) {
      auto* node = nodes_to_complete_fuse[j];
 
      const auto& cur_capability = capabilities_to_complete_fuse[j];
      const IndexedSubGraph& indexed_sub_graph = *cur_capability->sub_graph;
 
      // now that we're done compiling we can remove the original nodes from the Graph and wire in the new one
      graph.FinalizeFuseSubGraph(indexed_sub_graph, *node);
    }
  }
 
  // if this is the main graph call Resolve to put the Graph back into a guaranteed good state
  // TODO: Graph::FuseSubGraph and Graph::FinalizeFuseSubGraph should now create valid edges so this call to
  // Graph::Resolve should not be required. Need to test to validate that, especially if node being fused
  // was a control flow node with its own subgraph as more than just the edges may need updating.
  if (!graph.IsSubgraph()) {
    ORT_RETURN_IF_ERROR(graph.Resolve());
  }
 
  // For some cases, like fp16 on cpu, right now we don't have any kernel support that.
  // But we will insert cast op to run the model, so skip the error checking here.
  // If after graph transform phase, the node still not assigned, we will report error
  // during kernel creation phase.
#ifdef COUNT_NON_CUDA_OPS
  for (auto& node : graph.Nodes()) {
    if (node.GetExecutionProviderType() != kCudaExecutionProvider &&
        node.Domain() != kMLDomain &&
        node.Domain() != kMSDomain)
      non_cuda.AddOp(node.OpType());
  }
#endif
 
  return Status::OK();
}
 
struct FunctionExpansionCost {
  size_t node_count;
  size_t proto_bytes;
};
 
enum class FunctionExpansionLimit {
  kNone,
  kNodes,
  kProtoBytes,
};
 
static Status GetFunctionExpansionCost(const Node& node,
                                       size_t remaining_node_budget,
                                       size_t remaining_byte_budget,
                                       FunctionExpansionCost& cost);
 
static FunctionExpansionLimit TryChargeFunctionExpansion(const FunctionExpansionCost& cost,
                                                         size_t node_limit,
                                                         size_t& expanded_node_count,
                                                         size_t byte_limit,
                                                         size_t& expanded_proto_bytes);
 
// expand any nodes that have an ONNX function definition but no matching ORT kernel
static Status InlineNodes(Graph& graph,
                          bool& modified_graph,
                          LayeringIndex* layering_index,
                          const logging::Logger& logger,
                          size_t expansion_node_limit,
                          size_t& expanded_node_count,
                          size_t expansion_byte_limit,
                          size_t& expanded_proto_bytes) {
  // recurse into nested graphs first so we process from bottom up
  for (auto& node : graph.Nodes()) {
    for (auto& entry : node.GetAttributeNameToMutableSubgraphMap()) {
      Graph* subgraph = entry.second;
      ORT_RETURN_IF_ERROR(InlineNodes(*subgraph, modified_graph, layering_index, logger,
                                      expansion_node_limit, expanded_node_count,
                                      expansion_byte_limit, expanded_proto_bytes));
    }
  }
 
  // See if the node with no provider can be inlined. If one such nodes can be successfully inlined,
  // we re-run the partitioner on the modified graph.
  // NOTE: Inlining the function will change the nodes in the Graph instance, so we can't do that while iterating
  // using graph.Nodes().
  InlinedVector<Node*> nodes_to_inline;
  for (auto& node : graph.Nodes()) {
    if (node.GetExecutionProviderType().empty() && node.CanBeInlined()) {
      nodes_to_inline.push_back(&node);
    }
  }
 
  // Collect new node indices for nodes inlined from annotated parents so we can
  // update the LayeringIndex in one batch.
  InlinedVector<NodeIndex> new_node_indices;
 
  for (auto* node : nodes_to_inline) {
    FunctionExpansionCost expansion_cost{};
    ORT_RETURN_IF_ERROR(GetFunctionExpansionCost(
        *node, expansion_node_limit - expanded_node_count,
        expansion_byte_limit - expanded_proto_bytes, expansion_cost));
    const auto limit_exceeded = TryChargeFunctionExpansion(expansion_cost,
                                                           expansion_node_limit,
                                                           expanded_node_count,
                                                           expansion_byte_limit,
                                                           expanded_proto_bytes);
    if (limit_exceeded != FunctionExpansionLimit::kNone) {
      const auto function_id =
          function_utils::GetFunctionIdentifier(node->Domain(), node->OpType(), node->Overload());
      return ORT_MAKE_STATUS(
          ONNXRUNTIME, FAIL,
          "Function inlining exceeded the configured cumulative ",
          limit_exceeded == FunctionExpansionLimit::kNodes ? "node" : "protobuf",
          " expansion limit while expanding '", function_id, "'.");
    }
 
    // Check for an effective layering assignment: either from an explicit annotation
    // on the node, or from an inherited assignment via the LayeringIndex (e.g., a function
    // call node inside an annotated If/Loop subgraph that inherited its parent's rule).
    const bool has_explicit_annotation = !node->GetLayeringAnnotation().empty();
    bool has_effective_assignment = has_explicit_annotation;
 
    if (layering_index != nullptr && !has_explicit_annotation) {
      // The node may have an inherited-only assignment with no stored annotation string.
      // Materialize the annotation on the node so Graph::InlineFunction propagates it
      // to the newly created inlined nodes.
      auto rule_idx = layering_index->GetNodeAssignment(graph, node->Index());
      if (rule_idx) {
        has_effective_assignment = true;
        const auto& rules = layering_index->GetRules();
        if (*rule_idx < rules.rules.size()) {
          node->SetLayeringAnnotation(rules.rules[*rule_idx].annotation);
        }
      }
    }
 
    const int max_before = has_effective_assignment ? graph.MaxNodeIndex() : 0;
 
    ORT_RETURN_IF_ERROR(graph.InlineFunction(*node));
    modified_graph = true;
 
    if (has_effective_assignment) {
      const int max_after = graph.MaxNodeIndex();
      for (int i = max_before; i < max_after; ++i) {
        if (graph.GetNode(static_cast<NodeIndex>(i)) != nullptr) {
          new_node_indices.push_back(static_cast<NodeIndex>(i));
        }
      }
    }
  }
 
  // Update the LayeringIndex so the next partitioning round filters correctly
  // for the newly inlined nodes that inherited their parent's annotation.
  if (layering_index != nullptr && !new_node_indices.empty()) {
    layering_index->Update(graph, new_node_indices);
  }
 
  return Status::OK();
}
 
constexpr size_t kDefaultFunctionExpansionNodeLimit = 1'000'000;
constexpr size_t kDefaultFunctionExpansionByteLimit = 1024ULL * 1024ULL * 1024ULL;
 
static size_t CountNodesIncludingSubgraphs(const ONNX_NAMESPACE::GraphProto& graph);
 
static size_t CountNodesIncludingSubgraphs(const ONNX_NAMESPACE::AttributeProto& attribute) {
  SafeInt<size_t> node_count = 0;
  if (attribute.has_g()) {
    node_count += CountNodesIncludingSubgraphs(attribute.g());
  }
  for (const auto& attribute_graph : attribute.graphs()) {
    node_count += CountNodesIncludingSubgraphs(attribute_graph);
  }
 
  return node_count;
}
 
static size_t CountNodesIncludingSubgraphs(const ONNX_NAMESPACE::GraphProto& graph) {
  SafeInt<size_t> node_count = graph.node_size();
  for (const auto& node : graph.node()) {
    for (const auto& attribute : node.attribute()) {
      node_count += CountNodesIncludingSubgraphs(attribute);
    }
  }
 
  return node_count;
}
 
static size_t EstimateNodeProtoBytes(const Node& node) {
  constexpr size_t kFieldOverhead = 11;
  SafeInt<size_t> proto_bytes = 0;
  const auto add_string = [&proto_bytes](const std::string& value) {
    proto_bytes += value.size() + kFieldOverhead;
  };
 
  add_string(node.Name());
  add_string(node.OpType());
  add_string(node.Description());
  add_string(node.Domain());
  for (const auto* input : node.InputDefs()) {
    if (input != nullptr) {
      add_string(input->Name());
    }
  }
  for (const auto* output : node.OutputDefs()) {
    if (output != nullptr) {
      add_string(output->Name());
    }
  }
  for (const auto& [name, attribute] : node.GetAttributes()) {
    proto_bytes += name.size() + kFieldOverhead;
    proto_bytes += attribute.ByteSizeLong() + kFieldOverhead;
  }
 
  return proto_bytes;
}
 
using FunctionNameBindings = InlinedHashMap<std::string_view, size_t>;
 
static size_t SpecializedNameFieldCost(std::string_view name,
                                       const FunctionNameBindings& name_bindings,
                                       size_t prefix_overhead) {
  constexpr size_t kFieldOverhead = 11;
  const auto binding = name_bindings.find(name);
  return SafeInt<size_t>(binding == name_bindings.end() ? name.size() + prefix_overhead
                                                        : binding->second) +
         kFieldOverhead;
}
 
static void AddSpecializedGraphNameCost(const ONNX_NAMESPACE::GraphProto& graph,
                                        const FunctionNameBindings& name_bindings,
                                        size_t prefix_overhead,
                                        SafeInt<size_t>& proto_bytes);
 
static FunctionNameBindings MakeScopedGraphNameBindings(const ONNX_NAMESPACE::GraphProto& graph,
                                                        const FunctionNameBindings& name_bindings,
                                                        size_t prefix_overhead) {
  FunctionNameBindings scoped_name_bindings = name_bindings;
  const auto add_local_binding = [&scoped_name_bindings, prefix_overhead](const std::string& name) {
    scoped_name_bindings.insert_or_assign(name, SafeInt<size_t>(name.size()) + prefix_overhead);
  };
  for (const auto& input : graph.input()) {
    add_local_binding(input.name());
  }
  for (const auto& output : graph.output()) {
    add_local_binding(output.name());
  }
  for (const auto& initializer : graph.initializer()) {
    add_local_binding(initializer.name());
  }
  for (const auto& initializer : graph.sparse_initializer()) {
    add_local_binding(initializer.values().name());
  }
  return scoped_name_bindings;
}
 
static void AddSpecializedAttributeNameCost(const ONNX_NAMESPACE::AttributeProto& attribute,
                                            const FunctionNameBindings& name_bindings,
                                            size_t prefix_overhead,
                                            SafeInt<size_t>& proto_bytes) {
  if (attribute.has_g()) {
    AddSpecializedGraphNameCost(attribute.g(), name_bindings, prefix_overhead, proto_bytes);
  }
  for (const auto& graph : attribute.graphs()) {
    AddSpecializedGraphNameCost(graph, name_bindings, prefix_overhead, proto_bytes);
  }
}
 
static void AddSpecializedNodeNameCost(const ONNX_NAMESPACE::NodeProto& node,
                                       const FunctionNameBindings& name_bindings,
                                       size_t prefix_overhead,
                                       SafeInt<size_t>& proto_bytes) {
  if (!node.name().empty()) {
    proto_bytes += SafeInt<size_t>(node.name().size()) + prefix_overhead + 11;
  }
  for (const auto& input : node.input()) {
    proto_bytes += SpecializedNameFieldCost(input, name_bindings, prefix_overhead);
  }
  for (const auto& output : node.output()) {
    proto_bytes += SpecializedNameFieldCost(output, name_bindings, prefix_overhead);
  }
  for (const auto& attribute : node.attribute()) {
    AddSpecializedAttributeNameCost(attribute, name_bindings, prefix_overhead, proto_bytes);
  }
}
 
static void AddSpecializedGraphNameCost(const ONNX_NAMESPACE::GraphProto& graph,
                                        const FunctionNameBindings& name_bindings,
                                        size_t prefix_overhead,
                                        SafeInt<size_t>& proto_bytes) {
  const auto scoped_name_bindings = MakeScopedGraphNameBindings(graph, name_bindings, prefix_overhead);
  for (const auto& input : graph.input()) {
    proto_bytes += SpecializedNameFieldCost(input.name(), scoped_name_bindings, prefix_overhead);
  }
  for (const auto& output : graph.output()) {
    proto_bytes += SpecializedNameFieldCost(output.name(), scoped_name_bindings, prefix_overhead);
  }
  for (const auto& initializer : graph.initializer()) {
    proto_bytes += SpecializedNameFieldCost(initializer.name(), scoped_name_bindings, prefix_overhead);
  }
  for (const auto& initializer : graph.sparse_initializer()) {
    proto_bytes += SpecializedNameFieldCost(initializer.values().name(), scoped_name_bindings, prefix_overhead);
  }
  for (const auto& node : graph.node()) {
    AddSpecializedNodeNameCost(node, scoped_name_bindings, prefix_overhead, proto_bytes);
  }
}
 
static Status AddBoundAttributeCost(
    const ONNX_NAMESPACE::AttributeProto& attribute,
    const InlinedHashMap<std::string_view, const ONNX_NAMESPACE::AttributeProto*>& attribute_bindings,
    const FunctionNameBindings& name_bindings,
    size_t prefix_overhead,
    InlinedHashSet<std::string_view>& resolving_attribute_bindings,
    size_t remaining_node_budget,
    size_t remaining_byte_budget,
    SafeInt<size_t>& node_count,
    SafeInt<size_t>& proto_bytes) {
  if (node_count > remaining_node_budget || proto_bytes > remaining_byte_budget) {
    return Status::OK();
  }
  const ONNX_NAMESPACE::AttributeProto* effective_attribute = &attribute;
  bool bound_attribute = false;
  if (!attribute.ref_attr_name().empty()) {
    const auto binding = attribute_bindings.find(attribute.ref_attr_name());
    if (binding != attribute_bindings.end()) {
      ORT_RETURN_IF_NOT(resolving_attribute_bindings.insert(binding->first).second,
                        "Recursive function attribute binding '", binding->first, "' is not supported.");
      node_count += CountNodesIncludingSubgraphs(*binding->second);
      proto_bytes += binding->second->ByteSizeLong();
      effective_attribute = binding->second;
      bound_attribute = true;
    }
  }
 
  if (bound_attribute) {
    AddSpecializedAttributeNameCost(*effective_attribute, name_bindings, prefix_overhead, proto_bytes);
  }
 
  const auto process_graph = [&](const ONNX_NAMESPACE::GraphProto& graph) -> Status {
    const auto scoped_name_bindings = MakeScopedGraphNameBindings(graph, name_bindings, prefix_overhead);
    for (const auto& node : graph.node()) {
      for (const auto& nested_attribute : node.attribute()) {
        ORT_RETURN_IF_ERROR(AddBoundAttributeCost(
            nested_attribute, attribute_bindings, scoped_name_bindings, prefix_overhead,
            resolving_attribute_bindings, remaining_node_budget, remaining_byte_budget,
            node_count, proto_bytes));
        if (node_count > remaining_node_budget || proto_bytes > remaining_byte_budget) {
          return Status::OK();
        }
      }
    }
    return Status::OK();
  };
 
  if (effective_attribute->has_g()) {
    ORT_RETURN_IF_ERROR(process_graph(effective_attribute->g()));
  }
  for (const auto& graph : effective_attribute->graphs()) {
    ORT_RETURN_IF_ERROR(process_graph(graph));
  }
 
  if (bound_attribute) {
    resolving_attribute_bindings.erase(attribute.ref_attr_name());
  }
  return Status::OK();
}
 
static Status GetFunctionExpansionCost(const Node& node,
                                       size_t remaining_node_budget,
                                       size_t remaining_byte_budget,
                                       FunctionExpansionCost& cost) {
  if (const auto* function_body = node.GetFunctionBody()) {
    const auto& body = function_body->Body();
    SafeInt<size_t> proto_bytes = 0;
    SafeInt<size_t> node_count = 0;
    constexpr size_t kRenamedFieldOverhead = 64;
    for (const auto& function_node : body.Nodes()) {
      ++node_count;
      proto_bytes += EstimateNodeProtoBytes(function_node);
      if (!function_node.Name().empty()) {
        proto_bytes += kRenamedFieldOverhead;
      }
      for (const auto& [name, attribute] : function_node.GetAttributes()) {
        ORT_UNUSED_PARAMETER(name);
        node_count += CountNodesIncludingSubgraphs(attribute);
      }
    }
    for (const auto& [name, initializer] : body.GetAllInitializedTensors()) {
      proto_bytes += initializer->ByteSizeLong();
      proto_bytes += name.size() + kRenamedFieldOverhead;
    }
    cost = {node_count, proto_bytes};
    return Status::OK();
  }
 
  ONNX_NAMESPACE::FunctionProto function_proto;
  ORT_RETURN_IF_NOT(node.TryGetFunctionProto(function_proto),
                    "Unable to get function body for node '", node.Name(), "'.");
 
  InlinedHashMap<std::string_view, const ONNX_NAMESPACE::AttributeProto*> attribute_bindings;
  attribute_bindings.reserve(node.GetAttributes().size() + function_proto.attribute_proto_size());
  for (const auto& [name, attribute] : node.GetAttributes()) {
    attribute_bindings.emplace(name, &attribute);
  }
  for (const auto& attribute : function_proto.attribute_proto()) {
    attribute_bindings.emplace(attribute.name(), &attribute);
  }
 
  FunctionNameBindings name_bindings;
  const auto add_name_bindings = [&name_bindings](const auto& formal_names, const auto& actual_defs) {
    const size_t binding_count = std::min(static_cast<size_t>(formal_names.size()), actual_defs.size());
    for (size_t i = 0; i < binding_count; ++i) {
      if (actual_defs[i] != nullptr) {
        name_bindings.emplace(formal_names.Get(static_cast<int>(i)), actual_defs[i]->Name().size());
      }
    }
  };
  add_name_bindings(function_proto.input(), node.InputDefs());
  add_name_bindings(function_proto.output(), node.OutputDefs());
 
  const size_t prefix_overhead = SafeInt<size_t>(node.OpType().size()) + 42;
  SafeInt<size_t> node_count = function_proto.node_size();
  SafeInt<size_t> proto_bytes = 0;
  InlinedHashSet<std::string_view> resolving_attribute_bindings;
  for (const auto& function_node : function_proto.node()) {
    proto_bytes += function_node.ByteSizeLong();
    AddSpecializedNodeNameCost(function_node, name_bindings, prefix_overhead, proto_bytes);
    for (const auto& attribute : function_node.attribute()) {
      node_count += CountNodesIncludingSubgraphs(attribute);
      ORT_RETURN_IF_ERROR(AddBoundAttributeCost(
          attribute, attribute_bindings, name_bindings, prefix_overhead,
          resolving_attribute_bindings, remaining_node_budget, remaining_byte_budget,
          node_count, proto_bytes));
      if (node_count > remaining_node_budget || proto_bytes > remaining_byte_budget) {
        break;
      }
    }
  }
  cost = {node_count, proto_bytes};
  return Status::OK();
}
 
static FunctionExpansionLimit TryChargeFunctionExpansion(const FunctionExpansionCost& cost,
                                                         size_t node_limit,
                                                         size_t& expanded_node_count,
                                                         size_t byte_limit,
                                                         size_t& expanded_proto_bytes) {
  if (cost.node_count > node_limit - expanded_node_count) {
    return FunctionExpansionLimit::kNodes;
  }
  if (cost.proto_bytes > byte_limit - expanded_proto_bytes) {
    return FunctionExpansionLimit::kProtoBytes;
  }
 
  expanded_node_count += cost.node_count;
  expanded_proto_bytes += cost.proto_bytes;
  return FunctionExpansionLimit::kNone;
}
 
static Status InitializeFunctionExpansionLimits(const ConfigOptions& config_options,
                                                bool& initialized,
                                                size_t& node_limit,
                                                size_t& byte_limit) {
  if (initialized) {
    return Status::OK();
  }
 
  const auto parse_limit = [&config_options](const char* config_key,
                                             size_t default_value,
                                             size_t& value) -> Status {
    const auto config_value = config_options.GetConfigOrDefault(config_key, std::to_string(default_value));
    if (!TryParseStringWithClassicLocale<size_t>(config_value, value) || value == 0) {
      return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
                             "Invalid positive integer value '", config_value,
                             "' for session configuration '", config_key, "'.");
    }
    return Status::OK();
  };
 
  ORT_RETURN_IF_ERROR(parse_limit(kOrtSessionOptionsFunctionExpansionNodeLimit,
                                  kDefaultFunctionExpansionNodeLimit, node_limit));
  ORT_RETURN_IF_ERROR(parse_limit(kOrtSessionOptionsFunctionExpansionByteLimit,
                                  kDefaultFunctionExpansionByteLimit, byte_limit));
  initialized = true;
  return Status::OK();
}
 
static Status InlineFunctionsAOTImpl(const ExecutionProviders& execution_providers,
                                     const KernelRegistryManager& kernel_registry_mgr,
                                     Graph& graph,
                                     const GraphOptimizerRegistry& graph_optimizer_registry,
                                     const logging::Logger& logger,
                                     const CheckLoadCancellationFn& check_load_cancellation_fn,
                                     uint32_t registered_ep_context_data_callbacks,
                                     InlinedHashSet<std::string>& not_inlined,
                                     size_t& inlined_count,
                                     size_t expansion_node_limit,
                                     size_t& expanded_node_count,
                                     size_t expansion_byte_limit,
                                     size_t& expanded_proto_bytes) {
  // handle testing edge case where optimizers or constant lifting results in graph with no nodes.
  // doing it here saves all providers checking for this in GetCapability
  if (graph.NumberOfNodes() == 0) {
    return Status::OK();
  }
 
  for (auto& node : graph.Nodes()) {
    for (auto& entry : node.GetAttributeNameToMutableSubgraphMap()) {
      Graph* subgraph = entry.second;
      // we pass through the FuncManager from the top level graph
      ORT_RETURN_IF_ERROR(InlineFunctionsAOTImpl(execution_providers,
                                                 kernel_registry_mgr,
                                                 *subgraph,
                                                 graph_optimizer_registry,
                                                 logger,
                                                 check_load_cancellation_fn,
                                                 registered_ep_context_data_callbacks,
                                                 not_inlined,
                                                 inlined_count,
                                                 expansion_node_limit,
                                                 expanded_node_count,
                                                 expansion_byte_limit,
                                                 expanded_proto_bytes));
    }
  }
 
  // Gather the candidates
  InlinedVector<NodeIndex> inline_candidates;
  for (auto& node : graph.Nodes()) {
    if (node.CanBeInlined()) {
      inline_candidates.push_back(node.Index());
    }
  }
 
  if (inline_candidates.empty()) {
    return Status::OK();
  }
 
  // Find out all the nodes that are already taken
  const GraphViewer graph_viewer(graph);
 
  InlinedHashSet<NodeIndex> claimed_by_ep;
  for (const auto& ep : execution_providers) {
    std::vector<std::unique_ptr<ComputeCapability>> capabilities;
    ORT_RETURN_IF_ERROR(GetCapabilityForEPForAotInlining(graph_viewer, kernel_registry_mgr, *ep,
                                                         graph_optimizer_registry, logger,
                                                         registered_ep_context_data_callbacks,
                                                         capabilities));
    if (check_load_cancellation_fn()) {
      return ORT_MAKE_STATUS(ONNXRUNTIME, MODEL_LOAD_CANCELED, "AOT inlining is canceled due to user request.");
    }
 
    for (auto& capability : capabilities) {
      const auto& nodes = capability->sub_graph->nodes;
      if (nodes.size() == 1) {
        // Single node capability.
        ORT_IGNORE_RETURN_VALUE(claimed_by_ep.insert(nodes[0]));
      } else {
        // Make sure none is claimed by other EPs mirroring the logic in PartitionOnnxFormatModelImpl.
        if (std::all_of(nodes.cbegin(), nodes.cend(), [&claimed_by_ep](NodeIndex node_index) {
              return claimed_by_ep.count(node_index) == 0;
            })) {
          claimed_by_ep.insert(nodes.cbegin(), nodes.cend());
        }
      }
    }
  }
 
  // TODO: Insert version check. We need to collect all the versions
  // that imported by the model. If the version is not supported by
  // the model, we can not inline it.
 
  for (auto node_index : inline_candidates) {
    auto* node = graph.GetNode(node_index);
    if (node != nullptr) {
      if (claimed_by_ep.count(node_index) == 0) {
        auto function_id = function_utils::GetFunctionIdentifier(node->Domain(), node->OpType(), node->Overload());
        FunctionExpansionCost expansion_cost{};
        ORT_RETURN_IF_ERROR(GetFunctionExpansionCost(
            *node, expansion_node_limit - expanded_node_count,
            expansion_byte_limit - expanded_proto_bytes, expansion_cost));
        const auto limit_exceeded = TryChargeFunctionExpansion(expansion_cost,
                                                               expansion_node_limit,
                                                               expanded_node_count,
                                                               expansion_byte_limit,
                                                               expanded_proto_bytes);
        if (limit_exceeded != FunctionExpansionLimit::kNone) {
          LOGS(logger, WARNING) << "AOT function inlining reached the cumulative "
                                << (limit_exceeded == FunctionExpansionLimit::kNodes ? "node" : "protobuf")
                                << " expansion limit. "
                                << "Retaining function call '" << function_id
                                << "' for execution-provider partitioning.";
          ORT_IGNORE_RETURN_VALUE(not_inlined.insert(function_id));
          continue;
        }
        ORT_RETURN_IF_ERROR(graph.InlineFunction(*node));
        ++inlined_count;
      } else {
        // OpType is the same as function name.
        auto function_id = function_utils::GetFunctionIdentifier(node->Domain(), node->OpType(), node->Overload());
        ORT_IGNORE_RETURN_VALUE(not_inlined.insert(std::move(function_id)));
      }
    }
    if (check_load_cancellation_fn()) {
      return ORT_MAKE_STATUS(ONNXRUNTIME, MODEL_LOAD_CANCELED, "AOT inlining is canceled due to user request.");
    }
  }
 
  return Status::OK();
}
 
// TODO: Move function to ep_context_utils.h/cc
static Status CreateEpContextModel(const ExecutionProviders& execution_providers,
                                   const Graph& graph,
                                   const epctx::ModelGenOptions& ep_context_gen_options,
                                   const logging::Logger& logger) {
  InlinedVector<const Node*> all_ep_context_nodes;
  for (const auto& ep : execution_providers) {
    const InlinedVector<const Node*> ep_context_nodes = ep->GetEpContextNodes();
    all_ep_context_nodes.insert(all_ep_context_nodes.begin(), ep_context_nodes.begin(), ep_context_nodes.end());
  }
 
  // This function serializes the EPContext form only; the sole caller (GraphPartitioner::Partition) invokes
  // it just when AnyEpContextNodesProduced() is true, so at least one EPContext node is guaranteed here. The
  // no-compiled-nodes policy (kReturnError / kGenerateModel) is handled by InferenceSession instead.
  assert(!all_ep_context_nodes.empty());
 
  auto get_ep_context_node = [&all_ep_context_nodes](const std::string& node_name) -> std::pair<bool, const Node*> {
    for (auto& node : all_ep_context_nodes) {
      if (node_name == node->Name()) {
        return std::make_pair(true, node);
      }
    }
    return std::make_pair(false, static_cast<const Node*>(nullptr));
  };
 
  const epctx::BufferHolder* output_buffer_holder = ep_context_gen_options.TryGetOutputModelBuffer();
  const epctx::BufferWriteFuncHolder* output_write_func_holder = ep_context_gen_options.TryGetOutputModelWriteFunc();
  const std::filesystem::path* output_model_path_ptr = ep_context_gen_options.TryGetOutputModelPath();
 
  // Determine whether we need to resolve/validate a file system path for the output model.
  // A path is needed when:
  //   - Writing the output model to a file (not to a buffer or write function)
  //   - Writing initializers to an external file (needs the model path to compute the external file location)
  const bool output_is_to_file = (output_buffer_holder == nullptr && output_write_func_holder == nullptr);
  const bool needs_path_for_external_initializers =
      (ep_context_gen_options.TryGetExternalInitializerFileInfo() != nullptr);
 
  std::filesystem::path valid_output_model_path;
  if ((output_is_to_file || needs_path_for_external_initializers) &&
      (output_model_path_ptr != nullptr || !graph.ModelPath().empty())) {
    std::filesystem::path output_model_path = (output_model_path_ptr != nullptr) ? *output_model_path_ptr
                                                                                 : std::filesystem::path("");
    ORT_RETURN_IF_ERROR(epctx::GetValidatedEpContextPath(output_model_path,
                                                         graph.ModelPath(),
                                                         valid_output_model_path,
                                                         ep_context_gen_options.error_if_output_file_exists));
  }
 
  // Utility function to detect a fused node with an unsupported domain.
  // Ex: when compiling an already compiled model, an EPContext node in the input model would be wrapped
  // into a fused node with a domain like "QNN". Such fused nodes do not pass ONNX correctness checks, so
  // we should detect them here and return a better error message. Otherwise, an ORT_INVALID_GRAPH error is raised
  // with a confusing error message *after* the invalid model has been saved/generated.
  // Note: This only applies to the explicit compile API. The original compilation approach (via session options),
  // early exits above (without error) if the model is already compiled.
  auto is_invalid_fused_node = [&graph](const Node& node) {
    const std::unordered_map<std::string, int>& supported_domains = graph.DomainToVersionMap();
    return (node.NodeType() == Node::Type::Fused) && (supported_domains.find(node.Domain()) == supported_domains.end());
  };
 
  Model ep_context_model(graph.Name(), false, graph.GetModel().MetaData(),
                         graph.GetModel().ModelPath(),  // use source model path so that external initializers can find the data file path
                         IOnnxRuntimeOpSchemaRegistryList{graph.GetSchemaRegistry()},
                         graph.DomainToVersionMap(), {}, logger);
  auto& ep_graph = ep_context_model.MainGraph();
  ep_graph.SetDescription(graph.Description());
 
  // Set inputs outputs explicitly to make sure the order is same as the user model.
  auto inputs = graph.GetInputs();
  auto outputs = graph.GetOutputs();
 
  InlinedVector<const NodeArg*> ep_graph_inputs;
  ep_graph_inputs.reserve(inputs.size());
  for (auto& input : inputs) {
    auto input_arg = graph.GetNodeArg(input->Name());
    auto& ep_graph_input_arg = ep_graph.GetOrCreateNodeArg(input_arg->Name(), input_arg->TypeAsProto());
    ep_graph_inputs.push_back(&ep_graph_input_arg);
  }
 
  InlinedVector<const NodeArg*> ep_graph_outputs;
  ep_graph_outputs.reserve(outputs.size());
  for (auto& output : outputs) {
    auto output_arg = graph.GetNodeArg(output->Name());
    auto& ep_graph_output_arg = ep_graph.GetOrCreateNodeArg(output_arg->Name(), output_arg->TypeAsProto());
    ep_graph_outputs.push_back(&ep_graph_output_arg);
  }
 
  ep_graph.SetInputs(ep_graph_inputs);
  ep_graph.SetOutputs(ep_graph_outputs);
 
  for (const auto& node : graph.Nodes()) {
    // the fused node and EPContext node has same node name
    auto ep_context_node = get_ep_context_node(node.Name());
    // Use EpContext node created by the EPs if name matched, otherwise use node from original model
    if (ep_context_node.first) {
      ep_graph.AddNode(*ep_context_node.second);
    } else if (is_invalid_fused_node(node)) {
      return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_GRAPH, "Encountered an invalid node while compiling a model. ",
                             "Please ensure the input model is not already compiled.");
    } else {
      ep_graph.AddNode(node);
    }
  }
 
  // handle initializers
  for (const auto& [name, _] : graph.GetAllInitializedTensors()) {
    if (ep_graph.GetNodeArg(name) != nullptr) {
      graph_utils::MakeInitializerCopyIfNotExist(graph, ep_graph, name);
    }
  }
 
  ORT_RETURN_IF_ERROR(ep_graph.Resolve());
 
  // Generate EP compatibility strings for OrtEp types and add to model metadata
  // At this point, the graph has been populated with all the EPContext nodes
  {
    const GraphViewer graph_viewer(ep_graph);
    for (const auto& ep : execution_providers) {
      ORT_TRY {
        // Generate the compatibility string for this EP
        std::string compatibility_string = ep->GetCompiledModelCompatibilityInfo(graph_viewer);
        if (!compatibility_string.empty()) {
          // Create a unique key for this EP's compatibility info
          // Use format: "ep_compatibility_info.<EP_TYPE>"
          // All EPs in a session must have a unique Type() value, so this will be unique for the generated model
          std::string metadata_key = std::string(kOrtModelMetadata_EpCompatibilityInfoPrefix) + ep->Type();
          auto& model_metadata = ep_context_model.MetaData();
          auto [it, was_inserted] =
              model_metadata.insert_or_assign(metadata_key, compatibility_string);
          if (!was_inserted) {
            LOGS(logger, WARNING) << "Overwriting existing EP compatibility info for key: " << metadata_key << " (EP: " << ep->Type() << ")";
          }
          LOGS(logger, VERBOSE) << "Added EP compatibility info for " << ep->Type() << " with key: " << metadata_key;
        }
      }
      ORT_CATCH(const std::exception& ex) {
        ORT_HANDLE_EXCEPTION([&]() {
          LOGS(logger, WARNING) << "Failed to generate compatibility string for EP " << ep->Type() << ": " << ex.what();
        });
      }
    }
  }
 
  ONNX_NAMESPACE::ModelProto model_proto;
  ORT_RETURN_IF_ERROR(EpContextModelToProto(ep_context_model, valid_output_model_path, ep_context_gen_options,
                                            /*out*/ model_proto));
 
  return epctx::SaveModelProtoToLocation(model_proto, ep_context_gen_options, valid_output_model_path, logger);
}
 
static Status PartitionOnnxFormatModel(const PartitionParams& partition_params, GraphPartitioner::Mode mode,
                                       const ExecutionProviders& execution_providers,
                                       KernelRegistryManager& kernel_registry_manager,
                                       const std::optional<ResourceAccountantMap>& acc_map,
                                       const GraphOptimizerRegistry& graph_optimizer_registry,
                                       const logging::Logger& logger, bool disable_model_compile,
                                       size_t expansion_node_limit,
                                       size_t& expanded_node_count,
                                       size_t expansion_byte_limit,
                                       size_t& expanded_proto_bytes) {  // Added arg
  bool modified_graph = false;
 
  auto& graph = partition_params.graph.get();
  auto& func_mgr = partition_params.func_mgr.get();
  auto& fused_kernel_registry = partition_params.fused_kernel_registry.get();
  auto& fused_node_unique_id = partition_params.fused_node_unique_id.get();
  const auto& transform_layout_function = partition_params.transform_layout_function;
  const CheckLoadCancellationFn& check_load_cancellation_fn = partition_params.check_load_cancellation_fn;
  const OnPartitionAssignmentFunction& on_partition_assignment_fn = partition_params.on_partition_assignment_fn;
 
  do {
    // process full graph with each EP
    for (const auto& ep : execution_providers) {
      IResourceAccountant* resource_accountant = nullptr;
      if (acc_map.has_value()) {
        // Plugin EPs can share the in-tree EP name they replace. Translate the
        // CUDA plugin alias so it continues to find the CUDA accountant.
        const auto& ep_type = ep->Type();
        const auto accountant_key = ep_type == kCudaExecutionProviderPluginAlias
                                        ? std::string{kCudaExecutionProvider}
                                        : ep_type;
        auto hit = acc_map->find(accountant_key);
        if (hit != acc_map->end()) {
          resource_accountant = hit->second.get();
        }
      }
      if (resource_accountant != nullptr) {
        // A preceding EP or function-inlining iteration may have changed the graph.
        // Results cannot be shared across those mutations because fused/generated NodeArgs
        // and subgraph identities may differ. The second GetCapability pass reuses this
        // result unless its layout transformation reports a modification.
        ORT_RETURN_IF_ERROR(RefreshMaxShapeInference(graph, *resource_accountant));
      }
      ORT_RETURN_IF_ERROR(PartitionOnnxFormatModelImpl(graph, func_mgr, kernel_registry_manager,
                                                       fused_kernel_registry, *ep, mode, fused_node_unique_id,
                                                       transform_layout_function,
                                                       partition_params.debug_graph_fn,
                                                       check_load_cancellation_fn,
                                                       on_partition_assignment_fn,
                                                       logger, resource_accountant, graph_optimizer_registry,
                                                       disable_model_compile,
                                                       partition_params.registered_ep_context_data_callbacks,
                                                       partition_params.ep_context_data_write_callback_required,
                                                       partition_params.layering_index));  // Pass param
    }
 
    // expand any nodes that have an ONNX function definition but no matching ORT kernel.
    modified_graph = false;
    ORT_RETURN_IF_ERROR(InlineNodes(graph, modified_graph, partition_params.layering_index, logger,
                                    expansion_node_limit, expanded_node_count,
                                    expansion_byte_limit, expanded_proto_bytes));
 
    // Resolve and rerun graph partitioning and inlining if there was a change
    if (modified_graph) {
      ORT_RETURN_IF_ERROR(graph.Resolve());
    }
  } while (modified_graph);
 
  return Status::OK();
}
 
#endif  // !defined(ORT_MINIMAL_BUILD)
 
static Status PartitionOrtFormatModelImpl(const PartitionParams& partition_params,
                                          KernelRegistryManager& kernel_registry_mgr,
                                          IExecutionProvider& current_ep,
                                          const GraphOptimizerRegistry& graph_optimizer_registry,
                                          const logging::Logger& logger) {
  // handle testing edge case where optimizers or constant lifting results in graph with no nodes.
  // doing it here saves all providers checking for this in GetCapability
  auto& graph = partition_params.graph.get();
  if (graph.NumberOfNodes() == 0) {
    return Status::OK();
  }
 
  // recurse into nested graphs first to partition bottom up.
  for (auto& node : graph.Nodes()) {
    for (auto& entry : node.GetAttributeNameToMutableSubgraphMap()) {
      auto& subgraph = *entry.second;
      PartitionParams subgraph_partition_params = partition_params;
      subgraph_partition_params.graph = std::ref(subgraph);
      ORT_RETURN_IF_ERROR(PartitionOrtFormatModelImpl(subgraph_partition_params, kernel_registry_mgr,
                                                      current_ep, graph_optimizer_registry, logger));
    }
  }
 
  std::vector<std::unique_ptr<ComputeCapability>> capabilities;
  // clang-format off
  const auto get_capability_params = GetCapabilityForEPParams{
      std::ref(graph),
      std::cref(kernel_registry_mgr),
      std::ref(current_ep),
      std::ref(capabilities),
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
      GraphPartitioner::Mode::kOrtFormatLoad,
      std::cref(partition_params.transform_layout_function),
      std::cref(partition_params.debug_graph_fn),
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
      nullptr,
      std::ref(graph_optimizer_registry),
      partition_params.check_load_cancellation_fn,
      partition_params.layering_index,
      partition_params.registered_ep_context_data_callbacks
  };
  // clang-format on
 
  ORT_RETURN_IF_ERROR(GetCapabilityForEP(get_capability_params, logger));
 
  const std::string& type = current_ep.Type();
  if ((partition_params.registered_ep_context_data_callbacks & OrtEpContextDataCallbackSupportFlags_READ) != 0) {
    const bool accepted_external_ep_context_capability =
        GraphHasAssignedExternalEpContextNode(graph, type) ||
        std::any_of(capabilities.cbegin(), capabilities.cend(),
                    [&](const std::unique_ptr<ComputeCapability>& capability) {
                      return IsIndexedSubGraphAvailableForAssignment(
                                 graph, *capability->sub_graph,
                                 GraphPartitioner::Mode::kOrtFormatLoad, type) &&
                             IndexedSubGraphHasExternalEpContextNode(graph, *capability->sub_graph);
                    });
    if (accepted_external_ep_context_capability) {
      ORT_RETURN_IF_ERROR(CheckEpContextDataSupport(current_ep, OrtEpContextDataCallbackSupportFlags_READ));
    }
  }
 
  if (capabilities.empty()) {
    return Status::OK();
  }
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
  struct CompilationEntry {
    std::unique_ptr<GraphViewer> viewer;
    std::reference_wrapper<Node> fused_node;
    std::reference_wrapper<const ComputeCapability> capability;
  };
  std::vector<CompilationEntry> compilation_entries;
  compilation_entries.reserve(capabilities.size());
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
 
  for (const auto& capability : capabilities) {
    const IndexedSubGraph& indexed_sub_graph = *capability->sub_graph;
    const IndexedSubGraph::MetaDef* metadef = indexed_sub_graph.GetMetaDef();
    if (!metadef) {
      TryAssignSingleNode(graph, indexed_sub_graph, type);
    } else {
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
      std::ostringstream oss;
      oss << type << "_" << metadef->name << "_" << partition_params.fused_node_unique_id++;
      const std::string node_name = oss.str();
 
      Node& fused_node = graph.BeginFuseSubGraph(indexed_sub_graph, node_name);
      fused_node.SetExecutionProviderType(type);
      if (indexed_sub_graph.IsAccountingEnabled()) {
        indexed_sub_graph.AccountForAllNodes(fused_node.GetContainingGraph(), fused_node.Index());
      }
 
      // create filtered graph viewer for this set of nodes
      //
      // TODO: Could avoid the topological sort in the GraphViewer ctor by constructing from an existing
      // GraphViewer instance instead of the Graph (copying the topological order instead of recalculating).
      auto viewer = std::make_unique<GraphViewer>(graph, indexed_sub_graph);
 
      compilation_entries.push_back(CompilationEntry{std::move(viewer), fused_node, *capability});
#else   // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
      return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Compiling capabilities is not supported in this build.");
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
    }
  }
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
  // We will compile the fused nodes one by one, and fuse the subgraph if successful.
  for (const auto& compilation_entry : compilation_entries) {
    Node& node = compilation_entry.fused_node;
    std::vector<NodeComputeInfo> single_node_compute_func;
    ORT_RETURN_IF_ERROR(current_ep.Compile({IExecutionProvider::FusedNodeAndGraph{node, *compilation_entry.viewer}},
                                           single_node_compute_func));
    if (partition_params.check_load_cancellation_fn()) {
      return ORT_MAKE_STATUS(ONNXRUNTIME, MODEL_LOAD_CANCELED, "Graph partitioning is canceled due to user request.");
    }
 
    ORT_RETURN_IF(single_node_compute_func.empty(), "single_node_compute_func should have 1 element.");
    auto& func_mgr = partition_params.func_mgr.get();
    ORT_RETURN_IF_ERROR(func_mgr.AddFuncInfo(node.Name(), std::move(single_node_compute_func[0])));
 
    const ComputeCapability& cur_capability = compilation_entry.capability;
    const IndexedSubGraph& indexed_sub_graph = *cur_capability.sub_graph;
    const IndexedSubGraph::MetaDef& metadef = *indexed_sub_graph.GetMetaDef();
 
    KernelDefBuilder builder;
    BuildFusedKernelDef(builder, metadef, type);
    auto kernel_def = builder.Build();
 
    auto& fused_kernel_registry = partition_params.fused_kernel_registry.get();
    ORT_RETURN_IF_ERROR(fused_kernel_registry.Register(
        KernelCreateInfo(
            std::move(kernel_def),
            [](FuncManager& func_mgr, const OpKernelInfo& info, std::unique_ptr<OpKernel>& out) -> Status {
              return FunctionKernel::Create(func_mgr, info, out);
            })));
 
    // now that we're done compiling we can remove the original nodes from the Graph and wire in the new one
    graph.FinalizeFuseSubGraph(indexed_sub_graph, node);
    // accounting was already done via AccountForAllNodes() when the fused node was created above.
  }
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
 
  return Status::OK();
}
 
// Simplified partitioning where custom EPs may produce compiled nodes.
static Status PartitionOrtFormatModel(const PartitionParams& partition_params,
                                      const ExecutionProviders& execution_providers,
                                      KernelRegistryManager& kernel_registry_manager,
                                      const GraphOptimizerRegistry& graph_optimizer_registry,
                                      const logging::Logger& logger) {
  // process full graph with each EP
  for (const auto& ep : execution_providers) {
    ORT_RETURN_IF_ERROR(PartitionOrtFormatModelImpl(partition_params, kernel_registry_manager, *ep, graph_optimizer_registry, logger));
  }
 
  return Status::OK();
}
 
#ifndef ORT_MINIMAL_BUILD
 
Status GraphPartitioner::InlineFunctionsAOT(Model& model,
                                            const ExecutionProviders& execution_providers,
                                            const KernelRegistryManager& kernel_registry_manager,
                                            const ConfigOptions& config_options,
                                            const logging::Logger& logger,
                                            uint32_t registered_ep_context_data_callbacks) const {
  const auto local_functions_num = model.GetModelLocalFunctionTemplates().size();
  const bool is_there_local_functions = local_functions_num > 0;
 
  if (!is_there_local_functions) {
    LOGS(logger, INFO) << "This model does not have any local functions defined. AOT Inlining is not performed";
    return Status::OK();
  }
 
  auto check_load_cancellation_fn = [this]() -> bool { return IsLoadCancellationFlagSet(); };
  ORT_RETURN_IF_ERROR(InitializeFunctionExpansionLimits(
      config_options,
      function_expansion_limits_initialized_,
      function_expansion_node_limit_,
      function_expansion_byte_limit_));
 
  auto& graph = model.MainGraph();
  InlinedHashSet<std::string> not_inlined;
  do {
    size_t inlined_count = 0;
    ORT_RETURN_IF_ERROR(InlineFunctionsAOTImpl(execution_providers,
                                               kernel_registry_manager,
                                               graph,
                                               *graph_optimizer_registry_,
                                               logger,
                                               check_load_cancellation_fn,
                                               registered_ep_context_data_callbacks,
                                               not_inlined,
                                               inlined_count,
                                               function_expansion_node_limit_,
                                               expanded_function_node_count_,
                                               function_expansion_byte_limit_,
                                               expanded_function_proto_bytes_));
 
    if (inlined_count == 0) {
      break;
    }
    ORT_RETURN_IF_ERROR(graph.Resolve());
  } while (true);
 
  model.RemoveLocalFunctionsProtos(not_inlined);
 
  LOGS(logger, INFO)
      << "AOT inlining completed. (" << (local_functions_num - model.GetModelLocalFunctionTemplates().size())
      << ") functions of ("
      << local_functions_num
      << ") pruned.";
 
  return Status::OK();
}
 
#endif
 
Status GraphPartitioner::Partition(Graph& graph, FuncManager& func_mgr,
                                   const layout_transformation::TransformLayoutFunction& transform_layout_function,
                                   const ConfigOptions& config_options,
                                   const logging::Logger& logger,
                                   LayeringIndex* layering_index,
                                   Mode mode,
                                   const epctx::ModelGenOptions& ep_context_gen_options,
                                   bool ep_context_data_read_callback_registered,
                                   const layout_transformation::DebugGraphFn& debug_graph_fn,
                                   WorkspaceReservationMap* workspace_reservations) const {
  // It is a greedy partitioning algorithm per provider preferences user provided when calling ONNX RUNTIME right now.
  // 1. Execution providers' capabilities are checked one by one.
  // 2. All sub-graphs that an execution provider returns will be assigned to it if it's not assigned yet.
  //    NOTE: A 'sub-graph' is a subset of nodes within the current Graph instance.
  //          The control flow nodes have nested Graph instance/s which are also called subgraphs,
  //          but are completely separate Graph instances and not a subset of nodes within a single Graph instance.
  // 3. CPU execution provider is expected to be able to run any node and is the last one in execution provider
  //    preference.
  if (providers_.Empty()) {
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "No provider specified.");
  }
  if (workspace_reservations != nullptr) {
    workspace_reservations->clear();
  }
 
  CheckLoadCancellationFn check_load_cancellation_fn = [this]() -> bool { return IsLoadCancellationFlagSet(); };
  uint32_t registered_ep_context_data_callbacks = ep_context_data_read_callback_registered
                                                      ? OrtEpContextDataCallbackSupportFlags_READ
                                                      : OrtEpContextDataCallbackSupportFlags_NONE;
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
  // fused_kernel_registry is preparing the kernels created on the fly for fused sub graph.
  // It is only visible for current session.
  std::shared_ptr<KernelRegistry> fused_kernel_registry = std::make_shared<KernelRegistry>();
 
  // we make sure each fused node name is unique across the entire model for clarity
  int fused_node_unique_id = 0;
  const bool ep_context_data_write_callback_registered = ep_context_gen_options.TryGetEpContextDataWriteFunc() != nullptr;
  if (ep_context_data_write_callback_registered) {
    registered_ep_context_data_callbacks |= OrtEpContextDataCallbackSupportFlags_WRITE;
    // Some EPs may produce external EPContext data as a side effect of GetCapability() itself (e.g. a
    // direct-assignment path that compiles before Compile() is ever called), so this WRITE-support check must
    // happen before GetCapability() is invoked on any provider.
    const GraphViewer graph_viewer(graph);
    for (const auto& ep : providers_) {
      ORT_RETURN_IF_ERROR(CheckEpContextDataSupport(
          *ep, ep->GetEpContextDataCallbackRequirements(graph_viewer) & OrtEpContextDataCallbackSupportFlags_WRITE));
    }
  }
  const bool ep_context_data_write_callback_required =
      ep_context_data_write_callback_registered && ep_context_gen_options.enable &&
      !ep_context_gen_options.embed_ep_context_in_model;
 
  PartitionParams partition_params{
      std::ref(graph),
      std::cref(check_load_cancellation_fn),
      std::ref(func_mgr),
      std::ref(*fused_kernel_registry),
      std::ref(fused_node_unique_id),
      std::cref(transform_layout_function),
      std::cref(debug_graph_fn),
      ep_context_data_write_callback_required,
      registered_ep_context_data_callbacks,
      std::cref(on_partition_assignment_fn_),
      layering_index};
 
#else  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
 
  ORT_UNUSED_PARAMETER(func_mgr);
  ORT_UNUSED_PARAMETER(transform_layout_function);
  ORT_UNUSED_PARAMETER(debug_graph_fn);
  PartitionParams partition_params{
      std::ref(graph),
      std::cref(check_load_cancellation_fn),
      registered_ep_context_data_callbacks,
      std::cref(on_partition_assignment_fn_),
      layering_index};
 
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
 
  if (mode == Mode::kNormal || mode == Mode::kAssignOnly) {
#if !defined(ORT_MINIMAL_BUILD)
    if (ep_context_gen_options.enable) {
      if (const std::filesystem::path* output_model_path_ptr = ep_context_gen_options.TryGetOutputModelPath();
          output_model_path_ptr != nullptr) {
        // Check before EP compile graphs
        std::filesystem::path context_cache_path;
        ORT_RETURN_IF_ERROR(epctx::GetValidatedEpContextPath(*output_model_path_ptr, graph.ModelPath(),
                                                             context_cache_path,
                                                             ep_context_gen_options.error_if_output_file_exists));
      }
    }
 
    // We use this only if Resource Aware Partitioning is enabled for any of the EPs
    // The map is empty if not created if not enabled
    std::optional<ResourceAccountantMap> ep_acc_map;
    ORT_RETURN_IF_ERROR(CreateAccountants(config_options, graph.ModelPath(), ep_acc_map));
    ORT_RETURN_IF_ERROR(InitializeFunctionExpansionLimits(
        config_options,
        function_expansion_limits_initialized_,
        function_expansion_node_limit_,
        function_expansion_byte_limit_));
 
    bool disable_model_compile = config_options.GetConfigOrDefault(kOrtSessionOptionsDisableModelCompile, "0") == "1";
    ORT_RETURN_IF_ERROR(PartitionOnnxFormatModel(partition_params, mode, providers_, kernel_registry_mgr_,
                                                 ep_acc_map, *graph_optimizer_registry_, logger,
                                                 disable_model_compile,
                                                 function_expansion_node_limit_,
                                                 expanded_function_node_count_,
                                                 function_expansion_byte_limit_,
                                                 expanded_function_proto_bytes_));  // Pass param
 
    if (ep_acc_map.has_value()) {
      for (const auto& [ep_type, accountant] : *ep_acc_map) {
        const auto consumed = accountant->GetConsumedAmount();
        if (!std::holds_alternative<size_t>(consumed)) {
          continue;
        }
 
        const size_t total_estimate = std::get<size_t>(consumed);
        const size_t workspace_estimate = accountant->GetCommittedWorkspaceEstimate();
        const size_t persistent_prepack_estimate =
            accountant->GetCommittedPersistentPrepackEstimate();
        const size_t initialization_scratch_estimate =
            accountant->GetCommittedInitializationScratchEstimate();
        const auto source_counts = accountant->GetWorkspaceEstimateSourceCounts();
        const auto comparison = accountant->GetWorkspaceEstimateComparisonSummary();
        const size_t categorized_estimate =
            static_cast<size_t>(SafeInt<size_t>(workspace_estimate) +
                                persistent_prepack_estimate);
        const size_t non_workspace_estimate =
            total_estimate >= categorized_estimate
                ? total_estimate - categorized_estimate
                : 0;
        LOGS(logger, INFO) << "Resource estimation for EP '" << ep_type << "': "
                           << "non-workspace memory: " << non_workspace_estimate << " bytes, "
                           << "workspace memory: " << workspace_estimate << " bytes, "
                           << "persistent prepack memory: " << persistent_prepack_estimate << " bytes, "
                           << "peak initialization scratch memory (not included in budget): "
                           << initialization_scratch_estimate << " bytes, "
                           << "total estimated memory: " << total_estimate << " bytes, "
                           << "workspace sources: fallback=" << source_counts.fallback
                           << ", profile=" << source_counts.profile
                           << ", estimator=" << source_counts.estimator
                           << ", profile+estimator=" << source_counts.profile_and_estimator;
        if (comparison.node_count > 0) {
          LOGS(logger, INFO) << "Workspace profile-estimator comparison for EP '" << ep_type << "': "
                             << comparison.node_count << " accepted node(s), "
                             << "profile larger=" << comparison.profile_larger
                             << ", estimator larger=" << comparison.estimator_larger
                             << ", equal=" << comparison.equal
                             << ", profiled workspace=" << comparison.profiled_bytes << " bytes"
                             << ", Level-1 estimated workspace="
                             << comparison.level1_estimated_bytes << " bytes";
        }
        if (workspace_reservations != nullptr) {
          auto reservations = accountant->GetCommittedWorkspaceReservations();
          for (auto& [graph_identity, node_reservations] : reservations) {
            auto& destination = (*workspace_reservations)[graph_identity];
            for (auto& [node_index, selection] : node_reservations) {
              destination.insert_or_assign(node_index, selection);
            }
          }
        }
      }
    }
 
    // Serialize here only when the output is EPContext-based (some EP produced EPContext nodes). The plain
    // form (no nodes compiled) is instead emitted by InferenceSession (epctx::BuildAndSaveOptimizedModel);
    // see there for how its serialization point is chosen.
    if (ep_context_gen_options.enable && AnyEpContextNodesProduced()) {
      ORT_RETURN_IF_ERROR(CreateEpContextModel(providers_, graph, ep_context_gen_options, logger));
    }
#else
    ORT_UNUSED_PARAMETER(config_options);
    ORT_UNUSED_PARAMETER(logger);
    ORT_UNUSED_PARAMETER(ep_context_gen_options);
    return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "ONNX models are not supported in this build.");
#endif  //! defined(ORT_MINIMAL_BUILD)
  } else {
    ORT_RETURN_IF_ERROR(PartitionOrtFormatModel(partition_params, providers_, kernel_registry_mgr_, *graph_optimizer_registry_, logger));
  }
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
  if (!fused_kernel_registry->IsEmpty()) {
    kernel_registry_mgr_.RegisterKernelRegistry(fused_kernel_registry);
  }
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
 
  return Status::OK();
}
 
#ifndef ORT_MINIMAL_BUILD
bool GraphPartitioner::AnyEpContextNodesProduced() const {
  for (const auto& ep : providers_) {
    if (!ep->GetEpContextNodes().empty()) {
      return true;
    }
  }
  return false;
}
#endif  // !defined(ORT_MINIMAL_BUILD)
 
}  // namespace onnxruntime