tritonserver-rs 0.4.0

Pefrorm easy and efficient ML models inference
Documentation
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
// Copyright 2018-2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "model_config_utils.h"

#include <google/protobuf/util/json_util.h>
#include <google/protobuf/util/message_differencer.h>

#include <deque>
#include <mutex>
#include <set>

#include "constants.h"
#include "cuda_utils.h"
#include "filesystem/api.h"
#include "triton/common/logging.h"

#define TRITONJSON_STATUSTYPE triton::core::Status
#define TRITONJSON_STATUSRETURN(M) \
  return triton::core::Status(triton::core::Status::Code::INTERNAL, (M))
#define TRITONJSON_STATUSSUCCESS triton::core::Status::Success
#include "triton/common/triton_json.h"

#ifdef TRITON_ENABLE_GPU
#include <cuda_runtime_api.h>
#endif  // TRITON_ENABLE_GPU

namespace triton { namespace core {

namespace {

#ifdef TRITON_ENABLE_ENSEMBLE

struct EnsembleTensor {
  EnsembleTensor(const std::string& name, bool isOutput)
      : name{name}, isOutput(isOutput)
  {
  }
  const std::string name;

  bool isOutput{false};
  bool ready{false};
  std::vector<EnsembleTensor*> prev_nodes;
  std::vector<EnsembleTensor*> next_nodes;
};

/// Build a graph that represents the data flow in the ensemble specified in
/// given model config. the node (ensemble tensor) in the graph can be looked
/// up using its name as key.
/// \param ensemble_config The model configuration that specifies
/// ensemble_scheduling field.
/// \param keyed_ensemble_graph Returned the ensemble graph.
/// \return The error status. A non-OK status indicates the build fails because
/// the ensemble configuration is not valid.
Status
BuildEnsembleGraph(
    const inference::ModelConfig& config,
    std::unordered_map<std::string, EnsembleTensor>& keyed_ensemble_graph)
{
  keyed_ensemble_graph.clear();
  size_t step_idx = 0;
  for (const auto& element : config.ensemble_scheduling().step()) {
    if (element.model_name().empty()) {
      return Status(
          Status::Code::INVALID_ARG,
          "must specify 'model_name' in step " + std::to_string(step_idx) +
              " of ensemble '" + config.name() + "'");
    }
    if (element.input_map().size() == 0) {
      return Status(
          Status::Code::INVALID_ARG,
          "must specify 'input_map' in step " + std::to_string(step_idx) +
              " of ensemble '" + config.name() + "'");
    }
    if (element.output_map().size() == 0) {
      return Status(
          Status::Code::INVALID_ARG,
          "must specify 'output_map' in step " + std::to_string(step_idx) +
              " of ensemble '" + config.name() + "'");
    }

    // Link ensemble tensors
    std::vector<EnsembleTensor*> tensor_as_output;
    for (const auto& output_map : element.output_map()) {
      auto it = keyed_ensemble_graph.find(output_map.second);
      if (it != keyed_ensemble_graph.end()) {
        if (it->second.isOutput) {
          return Status(
              Status::Code::INVALID_ARG,
              "ensemble tensor '" + it->first +
                  "' can appear in an output map only once for ensemble '" +
                  config.name() + "' step " + std::to_string(step_idx));
        } else {
          it->second.isOutput = true;
        }
      } else {
        it =
            keyed_ensemble_graph
                .emplace(std::make_pair(
                    output_map.second, EnsembleTensor(output_map.second, true)))
                .first;
      }
      tensor_as_output.push_back(&(it->second));
    }

    std::set<std::string> model_inputs;
    for (const auto& input_map : element.input_map()) {
      if (model_inputs.find(input_map.first) != model_inputs.end()) {
        return Status(
            Status::Code::INVALID_ARG,
            "input '" + input_map.first + "' in model '" +
                element.model_name() +
                "' is mapped to multiple ensemble tensors for ensemble '" +
                config.name() + "' step " + std::to_string(step_idx));
      } else {
        model_inputs.emplace(input_map.first);
      }
      auto it = keyed_ensemble_graph.find(input_map.second);
      if (it == keyed_ensemble_graph.end()) {
        it = keyed_ensemble_graph
                 .emplace(std::make_pair(
                     input_map.second, EnsembleTensor(input_map.second, false)))
                 .first;
      }
      for (auto output : tensor_as_output) {
        output->prev_nodes.push_back(&(it->second));
        it->second.next_nodes.push_back(output);
      }
    }

    step_idx++;
  }

  return Status::Success;
}

Status
ValidateEnsembleSchedulingConfig(const inference::ModelConfig& config)
{
  if (config.platform() != kEnsemblePlatform) {
    return Status(
        Status::Code::INVALID_ARG,
        "ensemble scheduling cannot be set for model '" + config.name() +
            "' whose platform is not " + kEnsemblePlatform);
  }
  if (config.instance_group().size() != 0) {
    return Status(
        Status::Code::INVALID_ARG,
        "instance group should not be specified for ensemble '" +
            config.name() + "'");
  }
  if (config.has_optimization()) {
    return Status(
        Status::Code::INVALID_ARG,
        "optimization should not be specified for ensemble '" + config.name() +
            "'");
  }
  if (config.model_warmup_size() != 0) {
    return Status(
        Status::Code::INVALID_ARG,
        "model_warmup can not be specified for ensemble '" + config.name() +
            "'");
  }

  // Make sure step is not empty and all fields are set
  if (config.ensemble_scheduling().step_size() == 0) {
    return Status(
        Status::Code::INVALID_ARG,
        "must specify 'step' for ensemble '" + config.name() + "'");
  }

  std::unordered_map<std::string, EnsembleTensor> tensors;

  RETURN_IF_ERROR(BuildEnsembleGraph(config, tensors));

  // check data flow
  std::deque<EnsembleTensor*> ready_queue;
  for (const auto& input : config.input()) {
    auto it = tensors.find(input.name());
    if (it == tensors.end()) {
      return Status(
          Status::Code::INVALID_ARG, "ensemble input '" + input.name() +
                                         "' for ensemble " + config.name() +
                                         "' is not used");
    }
    it->second.ready = true;
    ready_queue.push_back(&(it->second));
  }
  while (!ready_queue.empty()) {
    auto& ready_node = ready_queue.front();
    for (auto& next_node : ready_node->next_nodes) {
      if (next_node->ready) {
        continue;
      }
      bool next_node_ready = true;
      for (auto& prev_node : next_node->prev_nodes) {
        if (!prev_node->ready) {
          next_node_ready = false;
          break;
        }
      }
      next_node->ready = next_node_ready;
      if (next_node_ready) {
        ready_queue.push_back(next_node);
      }
    }
    ready_queue.pop_front();
  }
  std::set<std::string> outputs;
  for (const auto& output : config.output()) {
    auto it = tensors.find(output.name());
    if (it == tensors.end()) {
      return Status(
          Status::Code::INVALID_ARG, "ensemble output '" + output.name() +
                                         "' for ensemble " + config.name() +
                                         "' is not used");
    }
    if (!it->second.ready) {
      std::string error_message = "output '" + output.name() +
                                  "' for ensemble '" + config.name() +
                                  "' is not written";

      // recurrsively check 'prev_nodes' for the source of not-ready state
      std::vector<EnsembleTensor*>* prev_nodes = &it->second.prev_nodes;
      auto last_not_ready_node = &it->second;
      // there can be circular dependency so remember seen names to break it
      std::set<std::string> seen_names;
      while ((prev_nodes != nullptr) && (!prev_nodes->empty())) {
        const auto& nodes = *prev_nodes;
        // make sure while loop will terminate if no not-ready source is seen
        prev_nodes = nullptr;
        for (const auto& node : nodes) {
          if ((!node->ready) &&
              (seen_names.find(node->name) == seen_names.end())) {
            seen_names.emplace(node->name);
            last_not_ready_node = node;
            prev_nodes = &node->prev_nodes;
            break;
          }
        }
      }
      // there is not-ready source
      if (last_not_ready_node->name != it->second.name) {
        error_message += ": at least one of its depending tensors, '" +
                         last_not_ready_node->name + "', is not connected";
      }
      return Status(Status::Code::INVALID_ARG, error_message);
    } else {
      outputs.insert(it->first);
    }
  }
  // Check redundant ensemble tensors
  for (const auto& tensor : tensors) {
    // skip ensemble outputs as they have been checked and can have no
    // next nodes
    if (outputs.find(tensor.first) != outputs.end()) {
      continue;
    }
    if (!tensor.second.ready || (tensor.second.next_nodes.size() == 0)) {
      return Status(
          Status::Code::INVALID_ARG, "ensemble tensor '" + tensor.first +
                                         "' is unused in ensemble '" +
                                         config.name() + "'");
    }
  }
  return Status::Success;
}

#endif  // TRITON_ENABLE_ENSEMBLE

template <class ModelIO>
Status
ValidateIOShape(
    const ModelIO& io, int32_t max_batch_size,
    const std::string& message_prefix = "")
{
  if (io.name().empty()) {
    return Status(
        Status::Code::INVALID_ARG, message_prefix + "must specify 'name'");
  }

  std::string message_prefix_with_name =
      message_prefix + std::string("'" + io.name() + "' ");

  if (io.data_type() == inference::DataType::TYPE_INVALID) {
    return Status(
        Status::Code::INVALID_ARG,
        message_prefix_with_name + "must specify 'data_type'");
  }

  if (io.dims_size() == 0) {
    return Status(
        Status::Code::INVALID_ARG,
        message_prefix_with_name + "must specify 'dims'");
  }

  // If the configuration is non-batching, then no input or output
  // reshape can be empty as that would mean that input or output was
  // always empty (no data).
  if (io.has_reshape() && (io.reshape().shape_size() == 0) &&
      (max_batch_size == 0)) {
    return Status(
        Status::Code::INVALID_ARG,
        message_prefix_with_name +
            "cannot have empty reshape for non-batching model as scalar "
            "tensors are not supported");
  }

  for (auto dim : io.dims()) {
    // Dimension cannot be 0.
    if ((dim < 1) && (dim != triton::common::WILDCARD_DIM)) {
      return Status(
          Status::Code::INVALID_ARG,
          message_prefix_with_name + "dimension must be integer >= 1, or " +
              std::to_string(triton::common::WILDCARD_DIM) +
              " to indicate a variable-size dimension");
    }
  }

  if (io.has_reshape()) {
    // Zeros are not allowed in reshape.
    for (auto dim : io.reshape().shape()) {
      if ((dim < 1) && (dim != triton::common::WILDCARD_DIM)) {
        return Status(
            Status::Code::INVALID_ARG,
            message_prefix_with_name +
                "reshape dimensions must be integer >= 1, or " +
                std::to_string(triton::common::WILDCARD_DIM) +
                " to indicate a variable-size dimension");
      }
    }

    const int64_t dims_size = triton::common::GetElementCount(io.dims());
    const int64_t reshape_size =
        triton::common::GetElementCount(io.reshape().shape());

    // dims and reshape must both have same element count
    // or both have variable-size dimension.
    // Special case for empty reshape... expect dims to have element
    // count of 1.
    if ((dims_size != reshape_size) &&
        ((reshape_size != 0) || (dims_size != 1))) {
      return Status(
          Status::Code::INVALID_ARG,
          message_prefix_with_name + "has different size for dims and reshape");
    }

    // shape contains variable-size dimension, in this case we compare if
    // each pair of the trunks separated by variable-size dimension has
    // the same element count. For instance, from [2, 4, -1, 6] to [8, -1, 1, 6]
    // is valid reshape as 2 * 4 = 8 and 6 = 1 * 6.
    if (dims_size == -1) {
      std::vector<int64_t> dim_element_cnts;
      std::vector<int64_t> reshape_element_cnts;
      int64_t current_cnt = 1;
      for (const auto& dim : io.dims()) {
        if (dim != -1) {
          current_cnt *= dim;
        } else {
          dim_element_cnts.push_back(current_cnt);
          current_cnt = 1;
        }
      }
      dim_element_cnts.push_back(current_cnt);

      current_cnt = 1;
      for (const auto& dim : io.reshape().shape()) {
        if (dim != -1) {
          current_cnt *= dim;
        } else {
          reshape_element_cnts.push_back(current_cnt);
          current_cnt = 1;
        }
      }
      reshape_element_cnts.push_back(current_cnt);

      if (dim_element_cnts.size() != reshape_element_cnts.size()) {
        return Status(
            Status::Code::INVALID_ARG,
            message_prefix_with_name +
                "has different number of variable-size dimensions for dims "
                "and reshape");
      }
      for (size_t idx = 0; idx < dim_element_cnts.size(); idx++) {
        if (dim_element_cnts[idx] != reshape_element_cnts[idx]) {
          return Status(
              Status::Code::INVALID_ARG,
              message_prefix_with_name +
                  "has different size for dims and reshape");
        }
      }
    }
  }

  return Status::Success;
}

/// Validate that Non-linear format inputs or outputs are specified correctly
/// in a model configuration.
template <class ModelIO>
Status
ValidateNonLinearFormatIO(
    const ModelIO& io, const std::string& platform, bool is_input)
{
  if (!io.is_non_linear_format_io()) {
    // Nothing to validate as the tensor is not non-linear format.
    return Status::Success;
  }

  if (platform != kTensorRTPlanPlatform) {
    return Status(
        Status::Code::INVALID_ARG,
        "Non-linear IO format is only supported for the TensorRT platform");
  }

  if (io.dims_size() != 3) {
    std::string io_type = is_input ? "input" : "output";
    return Status(
        Status::Code::INVALID_ARG,
        "Non-linear IO format " + io_type + " requires 3 dims");
  }

  return Status::Success;
}

}  // namespace

Status
GetModelVersionFromPath(const std::string& path, int64_t* version)
{
  auto version_dir = BaseName(path);

  // Determine the version from the last segment of 'path'
  try {
    *version = std::atoll(version_dir.c_str());
  }
  catch (...) {
    return Status(
        Status::Code::INTERNAL,
        "unable to determine model version from " + path);
  }

  return Status::Success;
}

Status
GetBooleanSequenceControlProperties(
    const inference::ModelSequenceBatching& batcher,
    const std::string& model_name,
    const inference::ModelSequenceBatching::Control::Kind control_kind,
    const bool required, std::string* tensor_name,
    inference::DataType* tensor_datatype, float* fp32_false_value,
    float* fp32_true_value, int32_t* int32_false_value,
    int32_t* int32_true_value, bool* bool_false_value, bool* bool_true_value)
{
  // Make sure same tensor is not configured for multiple controls
  std::set<std::string> seen_tensors;

  // Make sure the control kind is not mentioned multiple times.
  bool seen_control = false;

  for (const auto& control_input : batcher.control_input()) {
    if (control_input.name().empty()) {
      return Status(
          Status::Code::INVALID_ARG,
          "sequence batching control tensor must have a name for " +
              model_name);
    }

    if (seen_tensors.find(control_input.name()) != seen_tensors.end()) {
      return Status(
          Status::Code::INVALID_ARG,
          "sequence batching control tensor '" + control_input.name() +
              "' is specified for multiple control kinds for " + model_name);
    }

    seen_tensors.insert(control_input.name());

    for (const auto& c : control_input.control()) {
      if (c.kind() == control_kind) {
        if (seen_control) {
          return Status(
              Status::Code::INVALID_ARG,
              "sequence batching specifies multiple " +
                  inference::ModelSequenceBatching_Control_Kind_Name(
                      control_kind) +
                  " tensors for " + model_name);
        }

        *tensor_name = control_input.name();
        seen_control = true;

        // Make sure only one of int, float, or bool type is specified.
        if (!((c.int32_false_true_size() != 0) ||
              (c.fp32_false_true_size() != 0) ||
              (c.bool_false_true_size() != 0))) {
          return Status(
              Status::Code::INVALID_ARG,
              "sequence batching must specify either 'int32_false_true', "
              "'fp32_false_true' or 'bool_false_true' for " +
                  inference::ModelSequenceBatching_Control_Kind_Name(
                      control_kind) +
                  " for " + model_name);
        } else if (
            ((c.int32_false_true_size() != 0) &&
             (c.fp32_false_true_size() != 0)) ||
            ((c.int32_false_true_size() != 0) &&
             (c.bool_false_true_size() != 0)) ||
            ((c.fp32_false_true_size() != 0) &&
             (c.bool_false_true_size() != 0))) {
          return Status(
              Status::Code::INVALID_ARG,
              "sequence batching specifies more than one from "
              "'int32_false_true', 'fp32_false_true' and 'bool_false_true' "
              "for " +
                  inference::ModelSequenceBatching_Control_Kind_Name(
                      control_kind) +
                  " for " + model_name);
        }

        if (c.int32_false_true_size() > 0) {
          if (c.int32_false_true_size() != 2) {
            return Status(
                Status::Code::INVALID_ARG,
                "sequence batching control 'int32_false_true' must have "
                "exactly 2 entries for " +
                    inference::ModelSequenceBatching_Control_Kind_Name(
                        control_kind) +
                    " for " + model_name);
          }

          if (tensor_datatype != nullptr) {
            *tensor_datatype = inference::DataType::TYPE_INT32;
          }
          if (int32_false_value != nullptr) {
            *int32_false_value = c.int32_false_true(0);
          }
          if (int32_true_value != nullptr) {
            *int32_true_value = c.int32_false_true(1);
          }
        } else if (c.fp32_false_true_size() > 0) {
          if (c.fp32_false_true_size() != 2) {
            return Status(
                Status::Code::INVALID_ARG,
                "sequence batching control 'fp32_false_true' must have exactly "
                "2 entries for " +
                    inference::ModelSequenceBatching_Control_Kind_Name(
                        control_kind) +
                    " for " + model_name);
          }

          if (tensor_datatype != nullptr) {
            *tensor_datatype = inference::DataType::TYPE_FP32;
          }
          if (fp32_false_value != nullptr) {
            *fp32_false_value = c.fp32_false_true(0);
          }
          if (fp32_true_value != nullptr) {
            *fp32_true_value = c.fp32_false_true(1);
          }
        } else {
          if (c.bool_false_true_size() != 2) {
            return Status(
                Status::Code::INVALID_ARG,
                "sequence batching control 'bool_false_true' must have exactly "
                "2 entries for " +
                    inference::ModelSequenceBatching_Control_Kind_Name(
                        control_kind) +
                    " for " + model_name);
          }

          if (tensor_datatype != nullptr) {
            *tensor_datatype = inference::DataType::TYPE_BOOL;
          }
          if (bool_false_value != nullptr) {
            *bool_false_value = c.bool_false_true(0);
          }
          if (bool_true_value != nullptr) {
            *bool_true_value = c.bool_false_true(1);
          }
        }
      }
    }
  }

  if (!seen_control) {
    if (required) {
      return Status(
          Status::Code::INVALID_ARG,
          "sequence batching control tensor must specify a " +
              inference::ModelSequenceBatching_Control_Kind_Name(control_kind) +
              " value for " + model_name);
    }

    tensor_name->clear();
  }

  return Status::Success;
}

Status
GetTypedSequenceControlProperties(
    const inference::ModelSequenceBatching& batcher,
    const std::string& model_name,
    const inference::ModelSequenceBatching::Control::Kind control_kind,
    const bool required, std::string* tensor_name,
    inference::DataType* tensor_datatype)
{
  // Make sure same tensor is not configured for multiple controls
  std::set<std::string> seen_tensors;

  // Make sure the control kind is not mentioned multiple times.
  bool seen_control = false;

  for (const auto& control_input : batcher.control_input()) {
    if (control_input.name().empty()) {
      return Status(
          Status::Code::INVALID_ARG,
          "sequence batching control tensor must have a name for " +
              model_name);
    }

    if (seen_tensors.find(control_input.name()) != seen_tensors.end()) {
      return Status(
          Status::Code::INVALID_ARG,
          "sequence batching control tensor '" + control_input.name() +
              "' is specified for multiple control kinds for " + model_name);
    }

    seen_tensors.insert(control_input.name());

    for (const auto& c : control_input.control()) {
      if (c.kind() == control_kind) {
        if (seen_control) {
          return Status(
              Status::Code::INVALID_ARG,
              "sequence batching specifies multiple " +
                  inference::ModelSequenceBatching_Control_Kind_Name(
                      control_kind) +
                  " tensors for " + model_name);
        }

        *tensor_name = control_input.name();
        if (tensor_datatype != nullptr) {
          *tensor_datatype = c.data_type();
        }

        seen_control = true;

        if ((c.int32_false_true_size() > 0) || (c.fp32_false_true_size() > 0) ||
            (c.bool_false_true_size() > 0)) {
          return Status(
              Status::Code::INVALID_ARG,
              "sequence batching must not specify either 'int32_false_true', "
              "'fp32_false_true' or 'bool_false_true' for " +
                  inference::ModelSequenceBatching_Control_Kind_Name(
                      control_kind) +
                  " for " + model_name);
        }
      }
    }
  }

  if (!seen_control) {
    if (required) {
      return Status(
          Status::Code::INVALID_ARG,
          "sequence batching control tensor must specify a " +
              inference::ModelSequenceBatching_Control_Kind_Name(control_kind) +
              " value for " + model_name);
    }

    tensor_name->clear();
  }

  return Status::Success;
}

Status
GetNormalizedModelConfig(
    const std::string& model_name, const std::string& path,
    const double min_compute_capability, inference::ModelConfig* config)
{
  // Server-side autofill only sets certain backend fields for the models that
  // belong to limited backends for backwards-compatibility. See TensorRT
  // backend, ONNX Runtime backend, OpenVINO backend, TensorFLow backend, and
  // PyTorch backend.
  // Extracting detailed information is delegated to the backend implementation
  // to auto-complete.
  RETURN_IF_ERROR(
      AutoCompleteBackendFields(model_name, std::string(path), config));

  LOG_PROTOBUF_VERBOSE(1, "Server side auto-completed config: ", (*config));

  RETURN_IF_ERROR(NormalizeModelConfig(min_compute_capability, config));

  return Status::Success;
}

Status
NormalizeModelConfig(
    const double min_compute_capability, inference::ModelConfig* config)
{
  // If version_policy is not specified, default to Latest 1 version.
  if (!config->has_version_policy()) {
    inference::ModelVersionPolicy::Latest latest;
    latest.set_num_versions(1);
    config->mutable_version_policy()->mutable_latest()->CopyFrom(latest);
  }

  // If dynamic batching is specified...
  if (config->has_dynamic_batching()) {
    // If preferred batch size is not specified set it to
    // max-batch-size.
    if (config->dynamic_batching().preferred_batch_size().size() == 0) {
      auto mutable_preferred_batch_size =
          config->mutable_dynamic_batching()->mutable_preferred_batch_size();
      if (config->max_batch_size() > 0) {
        mutable_preferred_batch_size->Add(config->max_batch_size());
      }
    }
  }

  // If sequence batching is specified...
  if (config->has_sequence_batching()) {
    // Set default idle is not specified.
    if (config->sequence_batching().max_sequence_idle_microseconds() == 0) {
      config->mutable_sequence_batching()->set_max_sequence_idle_microseconds(
          SEQUENCE_IDLE_DEFAULT_MICROSECONDS);
    }

    if (config->sequence_batching().has_oldest()) {
      // If preferred batch size is not specified set it to
      // max-batch-size.
      if (config->sequence_batching().oldest().preferred_batch_size().size() ==
          0) {
        auto mutable_preferred_batch_size =
            config->mutable_sequence_batching()
                ->mutable_oldest()
                ->mutable_preferred_batch_size();
        if (config->max_batch_size() > 0) {
          mutable_preferred_batch_size->Add(config->max_batch_size());
        }
      }
    }
  }

  // If model ensembling is specified, don't attempt to normalize instance_group
  // as it is not allowed in ensemble scheduling
  if (!config->has_ensemble_scheduling()) {
    auto optimization = config->mutable_optimization();
    if (!optimization->has_input_pinned_memory()) {
      optimization->mutable_input_pinned_memory()->set_enable(true);
    }
    if (!optimization->has_output_pinned_memory()) {
      optimization->mutable_output_pinned_memory()->set_enable(true);
    }
  }

  return Status::Success;
}

Status
NormalizeInstanceGroup(
    const double min_compute_capability,
    const std::vector<inference::ModelInstanceGroup>& preferred_groups,
    inference::ModelConfig* config)
{
  // Instance group setting doesn't apply to ensemble
  if (config->has_ensemble_scheduling()) {
    return Status::Success;
  }

  // Creates a set of supported GPU device ids
  std::set<int> supported_gpus;
#ifdef TRITON_ENABLE_GPU
  // Get the total number of GPUs from the runtime library.
  Status status = GetSupportedGPUs(&supported_gpus, min_compute_capability);
  if (!status.IsOk()) {
    return status;
  }

#endif  // TRITON_ENABLE_GPU

  // Make sure there is at least one instance_group.
  if (config->instance_group().empty()) {
    inference::ModelInstanceGroup* group = config->add_instance_group();
    group->set_name(config->name());

    for (const auto& pg : preferred_groups) {
      // handle preferred GPU setting differently based on kind
      if (pg.kind() == inference::ModelInstanceGroup::KIND_GPU) {
        // Don't use preferred group with KIND_GPU if there is no GPU.
        if (supported_gpus.empty()) {
          continue;
        }
        // If preferred group sets GPUs, limit deployment onto those that
        // are also listed in supported gpus
        if (!pg.gpus().empty()) {
          for (const int32_t gid : pg.gpus()) {
            if (supported_gpus.find(gid) != supported_gpus.end()) {
              group->add_gpus(gid);
            }
          }
        }
      } else if (pg.kind() == inference::ModelInstanceGroup::KIND_AUTO) {
        // if AUTO, then set preferred GPU as is, to align with KIND_AUTO
        // deduction specified below
        for (const int32_t gid : pg.gpus()) {
          group->add_gpus(gid);
        }
      }
      group->set_kind(pg.kind());
      group->set_count(pg.count());

      // Found a valid preferred group.
      break;
    }
  }

  // Assign default name, kind and count to each instance group that
  // doesn't give those values explicitly. For KIND_GPU, set GPUs to
  // all available if not specified explicitly.
  size_t cnt = 0;
  for (auto& group : *config->mutable_instance_group()) {
    // Name
    if (group.name().empty()) {
      group.set_name(config->name() + "_" + std::to_string(cnt));
    }
    cnt++;

    // For KIND_AUTO... if there are no GPUs or if any of the listed
    // 'gpu's are not present, then use KIND_CPU.
    if (group.kind() == inference::ModelInstanceGroup::KIND_AUTO) {
      if (supported_gpus.empty()) {
        group.set_kind(inference::ModelInstanceGroup::KIND_CPU);
      } else {
        for (const int32_t gid : group.gpus()) {
          if (supported_gpus.find(gid) == supported_gpus.end()) {
            group.set_kind(inference::ModelInstanceGroup::KIND_CPU);
            break;
          }
        }
      }

      if (group.kind() == inference::ModelInstanceGroup::KIND_AUTO) {
        group.set_kind(inference::ModelInstanceGroup::KIND_GPU);
      }
    }

    // KIND is resolved at this point
    for (const auto& pg : preferred_groups) {
      if (group.kind() != pg.kind()) {
        continue;
      }

      // Limit the GPU setting within what is specified in the preferred group,
      // if no available GPU then skip to next preferred group
      if ((group.kind() == inference::ModelInstanceGroup::KIND_GPU) &&
          group.gpus().empty() && !pg.gpus().empty()) {
        for (const int32_t gid : pg.gpus()) {
          if (supported_gpus.find(gid) != supported_gpus.end()) {
            group.add_gpus(gid);
          }
        }
        if (group.gpus().empty()) {
          continue;
        }
      }
      if ((group.count() < 1) && (pg.count() > 0)) {
        group.set_count(pg.count());
      }
    }

    // Set Triton default if the fields are not set from preferred group
    // Count
    if (group.count() < 1) {
      RETURN_IF_ERROR(SetDefaultInstanceCount(&group, config->backend()));
    }

    // GPUs
    if ((group.kind() == inference::ModelInstanceGroup::KIND_GPU) &&
        (group.gpus().size() == 0)) {
      for (auto d : supported_gpus) {
        group.add_gpus(d);
      }
    }
  }

  return Status::Success;
}

Status
LocalizePythonBackendExecutionEnvironmentPath(
    const std::string& model_path, inference::ModelConfig* config,
    std::shared_ptr<LocalizedPath>* localized_model_dir)
{
  if (config->backend() == kPythonBackend) {
    if (config->parameters().contains("EXECUTION_ENV_PATH")) {
      // Read EXECUTION_ENV_PATH
      std::string exec_env_path =
          config->parameters().at("EXECUTION_ENV_PATH").string_value();
      // Replace model directory variable with model_path
      std::string model_dir_var = "$$TRITON_MODEL_DIRECTORY";
      if (exec_env_path.substr(0, model_dir_var.size()) == model_dir_var) {
        exec_env_path.replace(0, model_dir_var.size(), model_path);
      }
      // Collapse any .. in the path
      std::string abs_exec_env_path;
      std::size_t prev_pos = exec_env_path.size();
      std::size_t pos = exec_env_path.find_last_of('/', prev_pos - 1);
      int skip = 0;
      while (pos != std::string::npos && prev_pos > 0) {
        if (!skip) {
          abs_exec_env_path =
              exec_env_path.substr(pos, prev_pos - pos) + abs_exec_env_path;
        }
        skip = skip > 0 ? skip - 1 : skip;
        if (pos >= 3 && exec_env_path.substr(pos - 3, 3) == "/..") {
          skip += 2;
        }
        prev_pos = pos;
        pos = exec_env_path.find_last_of('/', prev_pos - 1);
      }
      abs_exec_env_path = exec_env_path.substr(0, prev_pos) + abs_exec_env_path;
      // Localize iff abs_exec_env_path is outside the model directory
      std::string model_path_slash =
          model_path.back() == '/' ? model_path : model_path + "/";
      if (abs_exec_env_path.substr(0, model_path_slash.size()) !=
          model_path_slash) {
        // Localize the file
        std::shared_ptr<LocalizedPath> localized_exec_env_path;
        RETURN_IF_ERROR(
            LocalizePath(abs_exec_env_path, &localized_exec_env_path));
        // Persist the localized temporary path
        (*localized_model_dir)
            ->other_localized_path.push_back(localized_exec_env_path);
        // Rewrite EXECUTION_ENV_PATH
        config->mutable_parameters()
            ->at("EXECUTION_ENV_PATH")
            .set_string_value(localized_exec_env_path->Path());
      }
    }
  }
  return Status::Success;
}

Status
SetPythonBasedBackendExecutionEnvironment(
    const std::string& backend_libdir, inference::ModelConfig* model_config)
{
  if (!model_config->parameters().contains("EXECUTION_ENV_PATH")) {
    std::string env_name = "pb_exec_env_" + model_config->runtime() + ".tar.gz";
    std::string env_path = JoinPath({backend_libdir, std::move(env_name)});
    bool env_path_exist;
    RETURN_IF_ERROR(FileExists(env_path, &env_path_exist));
    if (env_path_exist) {
      inference::ModelParameter model_param;
      model_param.set_string_value(env_path);
      (*model_config->mutable_parameters())["EXECUTION_ENV_PATH"] =
          std::move(model_param);
    }
  }
  return Status::Success;
}

Status
SetDefaultInstanceCount(
    inference::ModelInstanceGroup* group, const std::string& backend)
{
  group->set_count(1);

  // Backends opt into the default_cpu_instance_count since
  // some backends (pytorch, OpenVINO) don't perform well/have high overhead
  // when using multiple instances.
  const int default_cpu_instance_count = 2;
  bool use_default_cpu_instance_count =
      (backend == kTensorFlowBackend) || (backend == kOnnxRuntimeBackend);
  if (group->kind() == inference::ModelInstanceGroup::KIND_CPU &&
      use_default_cpu_instance_count) {
    group->set_count(default_cpu_instance_count);
  }

  return Status::Success;
}

Status
AutoCompleteBackendFields(
    const std::string& model_name, const std::string& model_path,
    inference::ModelConfig* config)
{
  std::set<std::string> version_dirs;
  RETURN_IF_ERROR(GetDirectorySubdirs(model_path, &version_dirs));

  // There must be at least one version directory that we can inspect to
  // attempt to determine the platform. If not, we skip autofill with file name.
  // For now we allow multiple versions and only inspect the first version
  // directory to ensure it is valid. We can add more aggressive checks later.
  const bool has_version = (version_dirs.size() != 0);
  const auto version_path =
      has_version ? JoinPath({model_path, *(version_dirs.begin())}) : "";
  std::set<std::string> version_dir_content;
  if (has_version) {
    RETURN_IF_ERROR(GetDirectoryContents(version_path, &version_dir_content));
  }

  // If the model name is not given in the configuration, set if based
  // on the model path.
  if (config->name().empty()) {
    config->set_name(model_name);
  }

  // Trying to fill the 'backend', 'default_model_filename' field.

  // TensorFlow
  // For TF backend, the platform is required
  if (config->platform().empty()) {
    // Check 'backend', 'default_model_filename', and the actual directory
    // to determine the platform
    if (config->backend().empty() ||
        (config->backend() == kTensorFlowBackend)) {
      if (config->default_model_filename() == kTensorFlowSavedModelFilename) {
        config->set_platform(kTensorFlowSavedModelPlatform);
      } else if (
          config->default_model_filename() == kTensorFlowGraphDefFilename) {
        config->set_platform(kTensorFlowGraphDefPlatform);
      } else if (config->default_model_filename().empty() && has_version) {
        bool is_dir = false;
        if (version_dir_content.find(kTensorFlowSavedModelFilename) !=
            version_dir_content.end()) {
          RETURN_IF_ERROR(IsDirectory(
              JoinPath({version_path, kTensorFlowSavedModelFilename}),
              &is_dir));
          if (is_dir) {
            config->set_platform(kTensorFlowSavedModelPlatform);
          }
        }
        if (version_dir_content.find(kTensorFlowGraphDefFilename) !=
            version_dir_content.end()) {
          RETURN_IF_ERROR(IsDirectory(
              JoinPath({version_path, kTensorFlowGraphDefFilename}), &is_dir));
          if (!is_dir) {
            config->set_platform(kTensorFlowGraphDefPlatform);
          }
        }
      }
    }
  }

  // Fill 'backend' and 'default_model_filename' if missing
  if ((config->platform() == kTensorFlowSavedModelPlatform) ||
      (config->platform() == kTensorFlowGraphDefPlatform)) {
    if (config->backend().empty()) {
      config->set_backend(kTensorFlowBackend);
    }
    if (config->default_model_filename().empty()) {
      if (config->platform() == kTensorFlowSavedModelPlatform) {
        config->set_default_model_filename(kTensorFlowSavedModelFilename);
      } else {
        config->set_default_model_filename(kTensorFlowGraphDefFilename);
      }
    }
    return Status::Success;
  }

  // TensorRT
  if (config->backend().empty()) {
    if ((config->platform() == kTensorRTPlanPlatform) ||
        (config->default_model_filename() == kTensorRTPlanFilename)) {
      config->set_backend(kTensorRTBackend);
    } else if (
        config->platform().empty() &&
        config->default_model_filename().empty() && has_version) {
      bool is_dir = false;
      if (version_dir_content.find(kTensorRTPlanFilename) !=
          version_dir_content.end()) {
        RETURN_IF_ERROR(IsDirectory(
            JoinPath({version_path, kTensorRTPlanFilename}), &is_dir));
        if (!is_dir) {
          config->set_backend(kTensorRTBackend);
        }
      }
    }
  }
  if (config->backend() == kTensorRTBackend) {
    if (config->platform().empty()) {
      config->set_platform(kTensorRTPlanPlatform);
    }
    if (config->default_model_filename().empty()) {
      config->set_default_model_filename(kTensorRTPlanFilename);
    }
    return Status::Success;
  }

  // ONNXRuntime
  if (config->backend().empty()) {
    if ((config->platform() == kOnnxRuntimeOnnxPlatform) ||
        (config->default_model_filename() == kOnnxRuntimeOnnxFilename)) {
      config->set_backend(kOnnxRuntimeBackend);
    } else if (
        config->platform().empty() &&
        config->default_model_filename().empty() && has_version) {
      if (version_dir_content.find(kOnnxRuntimeOnnxFilename) !=
          version_dir_content.end()) {
        // ONNX model can be a file or a directory in the case of large model
        config->set_backend(kOnnxRuntimeBackend);
      }
    }
  }
  if (config->backend() == kOnnxRuntimeBackend) {
    if (config->platform().empty()) {
      config->set_platform(kOnnxRuntimeOnnxPlatform);
    }
    if (config->default_model_filename().empty()) {
      config->set_default_model_filename(kOnnxRuntimeOnnxFilename);
    }
    return Status::Success;
  }

  // OpenVINO
  if (config->backend().empty()) {
    if (config->default_model_filename() == kOpenVINORuntimeOpenVINOFilename) {
      config->set_backend(kOpenVINORuntimeBackend);
    } else if (
        config->platform().empty() &&
        config->default_model_filename().empty() && has_version) {
      if (version_dir_content.find(kOpenVINORuntimeOpenVINOFilename) !=
          version_dir_content.end()) {
        config->set_backend(kOpenVINORuntimeBackend);
      }
    }
  }
  if (config->backend() == kOpenVINORuntimeBackend) {
    if (config->default_model_filename().empty()) {
      config->set_default_model_filename(kOpenVINORuntimeOpenVINOFilename);
    }
    return Status::Success;
  }

  // PyTorch
  if (config->backend().empty()) {
    if ((config->platform() == kPyTorchLibTorchPlatform) ||
        (config->default_model_filename() == kPyTorchLibTorchFilename)) {
      config->set_backend(kPyTorchBackend);
    } else if (
        config->platform().empty() &&
        config->default_model_filename().empty() && has_version) {
      bool is_dir = false;
      if (version_dir_content.find(kPyTorchLibTorchFilename) !=
          version_dir_content.end()) {
        RETURN_IF_ERROR(IsDirectory(
            JoinPath({version_path, kPyTorchLibTorchFilename}), &is_dir));
        if (!is_dir) {
          config->set_backend(kPyTorchBackend);
        }
      }
    }
  }
  if (config->backend() == kPyTorchBackend) {
    if (config->platform().empty()) {
      // do not introduce new platforms, new runtimes may ignore this field.
      config->set_platform(kPyTorchLibTorchPlatform);
    }
    if (config->runtime() != kPythonFilename &&
        config->default_model_filename().empty()) {
      config->set_default_model_filename(kPyTorchLibTorchFilename);
    }
    return Status::Success;
  }

  // Python
  if (config->backend().empty()) {
    if (config->default_model_filename() == kPythonFilename) {
      config->set_backend(kPythonBackend);
    } else if (
        config->platform().empty() &&
        config->default_model_filename().empty() && has_version) {
      if (version_dir_content.find(kPythonFilename) !=
          version_dir_content.end()) {
        config->set_backend(kPythonBackend);
      }
    }
  }
  if (config->backend() == kPythonBackend) {
    if (config->default_model_filename().empty()) {
      config->set_default_model_filename(kPythonFilename);
    }
    return Status::Success;
  }

  // Custom Backend
  // For now, only do the narrowest case, where no info is given in the config.
  if (config->backend().empty() && config->platform().empty() &&
      config->default_model_filename().empty()) {
    LOG_VERBOSE(1) << "Could not infer supported backend, so attempting "
                      "autofill of custom backend.";
    // Since we lazily load the backends, we let the model tell us what backend
    // to load. We must assume that if the model name conforms to the required
    // shape, we parse the backend name out of the model file name. i.e.
    // model.identity will set the backend to "identity".
    const std::string delimiter = ".";
    size_t pos = model_name.find(delimiter, 0);
    if (pos == std::string::npos) {
      return Status(
          triton::common::Error::Code::INVALID_ARG,
          ("Invalid model name: Could not determine backend for model '" +
           model_name +
           "' with no backend in model configuration. Expected model name of "
           "the form 'model.<backend_name>'."));
    }
    const std::string backend_name =
        model_name.substr(pos + 1, std::string::npos);
    config->set_backend(backend_name);
    config->set_default_model_filename(
        (std::string("model.") + backend_name).c_str());
    return Status::Success;
  }

  return Status::Success;
}

Status
ValidateModelIOConfig(const inference::ModelConfig& config)
{
  Status status;
  for (const auto& io : config.input()) {
    status = ValidateModelInput(io, config.max_batch_size(), config.platform());
    if (!status.IsOk()) {
      return Status(
          status.StatusCode(), status.Message() + " for " + config.name());
    }
  }
  for (const auto& io : config.output()) {
    status =
        ValidateModelOutput(io, config.max_batch_size(), config.platform());
    if (!status.IsOk()) {
      return Status(
          status.StatusCode(), status.Message() + " for " + config.name());
    }
  }
  status = ValidateBatchIO(config);
  if (!status.IsOk()) {
    return Status(
        status.StatusCode(), status.Message() + " for " + config.name());
  }
  return Status::Success;
}

Status
ValidateBatchIO(const inference::ModelConfig& config)
{
  std::set<std::string> input_names;
  std::set<std::string> output_names;
  for (const auto& io : config.input()) {
    input_names.emplace(io.name());
  }
  for (const auto& io : config.output()) {
    output_names.emplace(io.name());
  }
  for (const auto& batch_io : config.batch_input()) {
    switch (batch_io.kind()) {
      case inference::BatchInput::BATCH_ELEMENT_COUNT:
      case inference::BatchInput::BATCH_ACCUMULATED_ELEMENT_COUNT:
      case inference::BatchInput::BATCH_ACCUMULATED_ELEMENT_COUNT_WITH_ZERO:
      case inference::BatchInput::BATCH_MAX_ELEMENT_COUNT_AS_SHAPE:
      case inference::BatchInput::BATCH_ITEM_SHAPE:
      case inference::BatchInput::BATCH_ITEM_SHAPE_FLATTEN: {
        if (batch_io.source_input_size() != 1) {
          return Status(
              Status::Code::INVALID_ARG,
              "batch input kind '" +
                  inference::BatchInput::Kind_Name(batch_io.kind()) +
                  "' expects 1 source input, got " +
                  std::to_string(batch_io.source_input_size()));
        }
        break;
      }
      default:
        return Status(
            Status::Code::INVALID_ARG,
            "unknown batch input kind '" +
                inference::BatchInput::Kind_Name(batch_io.kind()) + "'");
    }
    if ((batch_io.data_type() != inference::DataType::TYPE_INT32) &&
        (batch_io.data_type() != inference::DataType::TYPE_FP32)) {
      return Status(
          Status::Code::INVALID_ARG,
          "batch input data type must be TYPE_INT32 or TYPE_FP32");
    }
    for (const auto& source_name : batch_io.source_input()) {
      if (input_names.find(source_name) == input_names.end()) {
        return Status(
            Status::Code::INVALID_ARG,
            "unknown source input name '" + source_name + "'");
      }
    }
  }

  for (const auto& batch_io : config.batch_output()) {
    switch (batch_io.kind()) {
      case inference::BatchOutput::BATCH_SCATTER_WITH_INPUT_SHAPE: {
        if (batch_io.source_input_size() != 1) {
          return Status(
              Status::Code::INVALID_ARG,
              "batch output kind '" +
                  inference::BatchOutput::Kind_Name(batch_io.kind()) +
                  "' expects 1 source input, got " +
                  std::to_string(batch_io.source_input_size()));
        }
        break;
      }
      default:
        return Status(
            Status::Code::INVALID_ARG,
            "unknown batch output kind '" +
                inference::BatchOutput::Kind_Name(batch_io.kind()) + "'");
    }
    for (const auto& source_name : batch_io.source_input()) {
      if (input_names.find(source_name) == input_names.end()) {
        return Status(
            Status::Code::INVALID_ARG,
            "unknown source input name '" + source_name + "'");
      }
    }
    std::set<std::string> target_names;
    for (const auto& target_name : batch_io.target_name()) {
      if (output_names.find(target_name) == output_names.end()) {
        return Status(
            Status::Code::INVALID_ARG,
            "unknown target output name '" + target_name + "'");
      }
      if (target_names.emplace(target_name).second == false) {
        return Status(
            Status::Code::INVALID_ARG, "target output name '" + target_name +
                                           "' can only be specified once");
      }
    }
  }
  return Status::Success;
}

Status
ValidateModelConfig(
    const inference::ModelConfig& config, const double min_compute_capability)
{
  if (config.name().empty()) {
    return Status(
        Status::Code::INVALID_ARG, "model configuration must specify 'name'");
  }

  if (config.backend().empty()) {
    // Expect backend is not empty unless it is ensemble platform.
#ifdef TRITON_ENABLE_ENSEMBLE
    if (config.platform() != kEnsemblePlatform)
#endif  // TRITON_ENABLE_ENSEMBLE
      return Status(
          Status::Code::INVALID_ARG, "unexpected platform type '" +
                                         config.platform() + "' for " +
                                         config.name());
  }
#ifdef TRITON_ENABLE_ENSEMBLE
  else if (config.platform() == kEnsemblePlatform) {
    return Status(
        Status::Code::INVALID_ARG,
        "Ensemble model '" + config.name() + "' must have platform type '" +
            config.platform() + "' and empty backend type");
  }
#endif  // TRITON_ENABLE_ENSEMBLE

  if (config.platform().empty() && config.backend().empty()) {
    return Status(
        Status::Code::INVALID_ARG,
        "must specify 'platform' or 'backend' for '" + config.name() + "'");
  }

  // Ensure both platform and backend are referring to known backend,
  // and allow all platforms for a user-provided unknown backend.
  auto backend_type = GetBackendType(config.backend());
  if ((backend_type != BackendType::BACKEND_TYPE_UNKNOWN) &&
      (backend_type != GetBackendTypeFromPlatform(config.platform()))) {
    return Status(
        Status::Code::INVALID_ARG,
        "unexpected 'platform' and 'backend' pair, got:" + config.platform() +
            ", " + config.backend());
  }

  if (config.max_batch_size() < 0) {
    return Status(
        Status::Code::INVALID_ARG,
        "'max_batch_size' must be non-negative value for " + config.name());
  }

  if (!config.has_version_policy()) {
    return Status(
        Status::Code::INVALID_ARG,
        "must specify 'version policy' for " + config.name());
  }

  // If dynamic batching is specified make sure the preferred batch
  // sizes are positive and don't exceed maximum batch size.
  if (config.has_dynamic_batching()) {
    for (const auto size : config.dynamic_batching().preferred_batch_size()) {
      if (size <= 0) {
        return Status(
            Status::Code::INVALID_ARG,
            "dynamic batching preferred size must be positive for " +
                config.name());
      }
      if (size > config.max_batch_size()) {
        return Status(
            Status::Code::INVALID_ARG,
            "dynamic batching preferred size must be <= max batch size for " +
                config.name());
      }
    }

    // Priority queue is specified
    const auto priority_levels = config.dynamic_batching().priority_levels();
    if (priority_levels != 0) {
      if ((config.dynamic_batching().default_priority_level() == 0) ||
          (config.dynamic_batching().default_priority_level() >
           priority_levels)) {
        return Status(
            Status::Code::INVALID_ARG,
            "default priority level must be in range [1, " +
                std::to_string(priority_levels) + "] for " + config.name());
      }
      for (const auto& queue_policy :
           config.dynamic_batching().priority_queue_policy()) {
        if ((queue_policy.first == 0) ||
            (queue_policy.first > priority_levels)) {
          return Status(
              Status::Code::INVALID_ARG,
              "priority queue policy must have priority level in range [1, " +
                  std::to_string(priority_levels) + "] for " + config.name());
        }
      }
    }

    // preserve ordering option will conflict with priorities and delay policy
    if (config.dynamic_batching().preserve_ordering()) {
      if (priority_levels > 1) {
        return Status(
            Status::Code::INVALID_ARG,
            "Only one priority level is allowed when 'preserve_ordering' is "
            "true for " +
                config.name());
      }
      const auto& default_policy =
          config.dynamic_batching().default_queue_policy();
      if ((default_policy.default_timeout_microseconds() != 0) &&
          (default_policy.timeout_action() ==
           inference::ModelQueuePolicy::DELAY)) {
        return Status(
            Status::Code::INVALID_ARG,
            "Queue policy can not have DELAY as timeout action when "
            "'preserve_ordering' is true for " +
                config.name());
      }
      // Also need to check policy in 'priority_queue_policy'
      // for single priority case
      for (const auto& policy :
           config.dynamic_batching().priority_queue_policy()) {
        if ((policy.second.default_timeout_microseconds() != 0) &&
            (policy.second.timeout_action() ==
             inference::ModelQueuePolicy::DELAY)) {
          return Status(
              Status::Code::INVALID_ARG,
              "Queue policy can not have DELAY as timeout action when "
              "'preserve_ordering' is true for " +
                  config.name());
        }
      }
    }
  }

  // If sequence batching is specified make sure the control is
  // specified correctly.
  if (config.has_sequence_batching()) {
    // FIXME: DLIS-4034 - Response Cache does not yet support sequence batcher.
    if (config.response_cache().enable()) {
      return Status(
          Status::Code::INVALID_ARG,
          "Response Cache does not currently support model " + config.name() +
              " with sequence batching scheduler. Please disable the response "
              "cache.");
    }

    const auto& batcher = config.sequence_batching();

    // Check boolean controls...
    std::string tensor_name;
    RETURN_IF_ERROR(GetBooleanSequenceControlProperties(
        batcher, config.name(),
        inference::ModelSequenceBatching::Control::CONTROL_SEQUENCE_START,
        false /* required */, &tensor_name, nullptr, nullptr, nullptr, nullptr,
        nullptr, nullptr, nullptr));
    RETURN_IF_ERROR(GetBooleanSequenceControlProperties(
        batcher, config.name(),
        inference::ModelSequenceBatching::Control::CONTROL_SEQUENCE_END,
        false /* required */, &tensor_name, nullptr, nullptr, nullptr, nullptr,
        nullptr, nullptr, nullptr));
    RETURN_IF_ERROR(GetBooleanSequenceControlProperties(
        batcher, config.name(),
        inference::ModelSequenceBatching::Control::CONTROL_SEQUENCE_READY,
        false /* required */, &tensor_name, nullptr, nullptr, nullptr, nullptr,
        nullptr, nullptr, nullptr));

    // Check CORRID control and make sure it is one of the allowed types.
    inference::DataType tensor_datatype;
    RETURN_IF_ERROR(GetTypedSequenceControlProperties(
        batcher, config.name(),
        inference::ModelSequenceBatching::Control::CONTROL_SEQUENCE_CORRID,
        false /* required */, &tensor_name, &tensor_datatype));
    if (!tensor_name.empty()) {
      if ((tensor_datatype != inference::DataType::TYPE_UINT64) &&
          (tensor_datatype != inference::DataType::TYPE_INT64) &&
          (tensor_datatype != inference::DataType::TYPE_UINT32) &&
          (tensor_datatype != inference::DataType::TYPE_INT32) &&
          (tensor_datatype != inference::DataType::TYPE_STRING)) {
        return Status(
            Status::Code::INVALID_ARG,
            "unexpected data type for control " +
                inference::ModelSequenceBatching_Control_Kind_Name(
                    inference::ModelSequenceBatching::Control::
                        CONTROL_SEQUENCE_CORRID) +
                " for " + config.name() +
                ". Allowed data types are TYPE_UINT64, TYPE_INT64, "
                "TYPE_UINT32, "
                "TYPE_INT32 and TYPE_STRING");
      }
    }

    // If oldest-first strategy is enabled make sure the preferred
    // batch sizes are positive and don't exceed maximum batch size.
    if (config.sequence_batching().has_oldest()) {
      for (const auto size :
           config.sequence_batching().oldest().preferred_batch_size()) {
        if (size <= 0) {
          return Status(
              Status::Code::INVALID_ARG,
              "sequence batching preferred batch size must be positive for " +
                  config.name());
        }
        if (size > config.max_batch_size()) {
          return Status(
              Status::Code::INVALID_ARG,
              "sequence batching preferred batch size must be <= max batch "
              "size for " +
                  config.name());
        }
      }
    }

    // If direct strategy is enabled make sure the minimum slot utilization is
    // in range (0.0, 1.0]
    if (config.sequence_batching().has_direct()) {
      if ((config.sequence_batching().direct().minimum_slot_utilization() <
           0.0) ||
          (config.sequence_batching().direct().minimum_slot_utilization() >
           1.0)) {
        return Status(
            Status::Code::INVALID_ARG,
            "sequence batching minimum slot utilization must be in range "
            "(0.0, 1.0] for " +
                config.name());
      }
    }
  }

  // If ensemble scheduling is specified, validate it.  Otherwise,
  // must validate platform and instance_group
  if (config.has_ensemble_scheduling()) {
#ifdef TRITON_ENABLE_ENSEMBLE
    RETURN_IF_ERROR(ValidateEnsembleSchedulingConfig(config));
#else
    return Status(
        Status::Code::INVALID_ARG, "ensemble scheduling not supported");
#endif  // TRITON_ENABLE_ENSEMBLE
  }
#ifdef TRITON_ENABLE_ENSEMBLE
  else if (config.platform() == kEnsemblePlatform) {
    return Status(
        Status::Code::INVALID_ARG,
        "ensemble scheduling must be set for ensemble " + config.name() +
            " whose platform is " + kEnsemblePlatform);
  }
#endif  // TRITON_ENABLE_ENSEMBLE

  // FIXME: DLIS-3916 - Response Cache does not yet support decoupled models
  if (config.model_transaction_policy().decoupled() &&
      config.response_cache().enable()) {
    return Status(
        Status::Code::INVALID_ARG,
        "Response Cache does not currently support model " + config.name() +
            " with 'decoupled' transaction policy. Please disable the response"
            " cache.");
  }

  return Status::Success;
}

Status
ValidateInstanceGroup(
    const inference::ModelConfig& config, const double min_compute_capability)
{
  // Instance group setting doesn't apply to ensemble
  if (config.has_ensemble_scheduling()) {
    return Status::Success;
  }

  if (config.instance_group().size() == 0) {
    return Status(
        Status::Code::INVALID_ARG,
        "must specify one or more 'instance group's for " + config.name());
  }

  // Make sure KIND_GPU instance group specifies at least one GPU and
  // doesn't specify a non-existent GPU. Make sure non-KIND_GPU does
  // not specify any GPUs.
#ifdef TRITON_ENABLE_GPU
  std::set<int> supported_gpus;
  Status status = GetSupportedGPUs(&supported_gpus, min_compute_capability);
  if (!status.IsOk()) {
    return status;
  }
#endif  // TRITON_ENABLE_GPU

  for (const auto& group : config.instance_group()) {
    if (group.kind() == inference::ModelInstanceGroup::KIND_MODEL) {
      if (group.gpus().size() > 0) {
        return Status(
            Status::Code::INVALID_ARG,
            "instance group " + group.name() + " of model " + config.name() +
                " has kind KIND_MODEL but specifies one or more GPUs");
      }
    } else if (group.kind() == inference::ModelInstanceGroup::KIND_GPU) {
#if !defined(TRITON_ENABLE_GPU) && !defined(TRITON_ENABLE_MALI_GPU)
      return Status(
          Status::Code::INVALID_ARG,
          "instance group " + group.name() + " of model " + config.name() +
              " has kind KIND_GPU but server does not support GPUs");
#elif defined(TRITON_ENABLE_GPU)
      if (group.gpus().size() == 0) {
        if (supported_gpus.size() == 0) {
          return Status(
              Status::Code::INVALID_ARG,
              "instance group " + group.name() + " of model " + config.name() +
                  " has kind KIND_GPU but no GPUs are available");
        } else {
          return Status(
              Status::Code::INVALID_ARG,
              "instance group " + group.name() + " of model " + config.name() +
                  " has kind KIND_GPU but specifies no GPUs");
        }
      }

      for (const int32_t gid : group.gpus()) {
        if (supported_gpus.find(gid) == supported_gpus.end()) {
          std::string supported_gpus_str;
          for (const auto& cc : supported_gpus) {
            if (!supported_gpus_str.empty()) {
              supported_gpus_str += ", ";
            }
            supported_gpus_str += std::to_string(cc);
          }
          return Status(
              Status::Code::INVALID_ARG,
              "instance group " + group.name() + " of model " + config.name() +
                  " specifies invalid or unsupported gpu id " +
                  std::to_string(gid) +
                  ". GPUs with at least the minimum required CUDA compute "
                  "compatibility of " +
                  std::to_string(min_compute_capability) +
                  " are: " + supported_gpus_str);
        }
      }
#endif  // ! TRITON_ENABLE_GPU && ! TRITON_ENABLE_MALI_GPU
    } else if (group.kind() == inference::ModelInstanceGroup::KIND_CPU) {
      if (group.gpus().size() > 0) {
        return Status(
            Status::Code::INVALID_ARG,
            "instance group " + group.name() + " of model " + config.name() +
                " has kind KIND_CPU but specifies one or more GPUs");
      }
    } else {
      return Status(
          Status::Code::INTERNAL, "instance group " + group.name() +
                                      " of model " + config.name() +
                                      " has unexpected kind KIND_AUTO");
    }

    if ((config.platform() != kTensorRTPlanPlatform) &&
        !group.profile().empty()) {
      return Status(
          Status::Code::INVALID_ARG,
          "instance group " + group.name() + " of model " + config.name() +
              " and platform " + config.platform() +
              "specifies profile field which is only supported for "
              "TensorRT models");
    } else if (!group.profile().empty()) {
      for (const auto& profile : group.profile()) {
        int profile_index;
        RETURN_IF_ERROR(GetProfileIndex(profile, &profile_index));
        if (profile_index < 0) {
          return Status(
              Status::Code::INVALID_ARG,
              "instance group " + group.name() + " of model " + config.name() +
                  " and platform " + config.platform() +
                  " specifies invalid profile " + profile +
                  ". The field should contain the string representation of a "
                  "non-negative integer.");
        }
      }
    }
  }
  return Status::Success;
}

Status
ValidateModelInput(
    const inference::ModelInput& io, int32_t max_batch_size,
    const std::string& platform)
{
  RETURN_IF_ERROR(ValidateIOShape(io, max_batch_size, "model input "));

  if (((io.format() == inference::ModelInput::FORMAT_NHWC) ||
       (io.format() == inference::ModelInput::FORMAT_NCHW)) &&
      (io.dims_size() != 3)) {
    return Status(
        Status::Code::INVALID_ARG, "model input NHWC/NCHW require 3 dims");
  }

  if ((platform != kTensorRTPlanPlatform) && io.is_shape_tensor()) {
    return Status(
        Status::Code::INVALID_ARG,
        "shape tensors are only supported for TensorRT platform");
  }

  RETURN_IF_ERROR(ValidateNonLinearFormatIO(io, platform, true /* is_input*/));

  return Status::Success;
}

Status
CheckAllowedModelInput(
    const inference::ModelInput& io, const std::set<std::string>& allowed)
{
  if (allowed.find(io.name()) == allowed.end()) {
    std::string astr;
    for (const auto& a : allowed) {
      if (!astr.empty()) {
        astr.append(", ");
      }
      astr.append(a);
    }

    return Status(
        Status::Code::INVALID_ARG, "unexpected inference input '" + io.name() +
                                       "', allowed inputs are: " + astr);
  }
  return Status::Success;
}

Status
ValidateModelOutput(
    const inference::ModelOutput& io, int32_t max_batch_size,
    const std::string& platform)
{
  RETURN_IF_ERROR(ValidateIOShape(io, max_batch_size, "model output "));

  if ((platform != kTensorRTPlanPlatform) && io.is_shape_tensor()) {
    return Status(
        Status::Code::INVALID_ARG,
        "shape tensors are only supported for TensorRT platform");
  }

  RETURN_IF_ERROR(ValidateNonLinearFormatIO(io, platform, false /* is_input*/));

  return Status::Success;
}

Status
CheckAllowedModelOutput(
    const inference::ModelOutput& io, const std::set<std::string>& allowed)
{
  if (allowed.find(io.name()) == allowed.end()) {
    std::string astr;
    for (const auto& a : allowed) {
      if (!astr.empty()) {
        astr.append(", ");
      }
      astr.append(a);
    }

    return Status(
        Status::Code::INVALID_ARG, "unexpected inference output '" + io.name() +
                                       "', allowed outputs are: " + astr);
  }

  return Status::Success;
}

Status
ParseBoolParameter(
    const std::string& key, std::string value, bool* parsed_value)
{
  std::transform(
      value.begin(), value.end(), value.begin(),
      [](unsigned char c) { return std::tolower(c); });

  if ((value == "true") || (value == "1")) {
    *parsed_value = true;
  } else if ((value == "false") || (value == "0")) {
    *parsed_value = false;
  } else {
    return Status(
        Status::Code::INVALID_ARG,
        "failed to convert " + key + " '" + value + "' to boolean value");
  }

  return Status::Success;
}

Status
ParseLongLongParameter(
    const std::string& key, const std::string& value, int64_t* parsed_value)
{
  try {
    *parsed_value = std::stoll(value);
  }
  catch (const std::invalid_argument& ia) {
    return Status(
        Status::Code::INVALID_ARG,
        "failed to convert " + key + " '" + value + "' to integral number");
  }

  return Status::Success;
}

Status
GetProfileIndex(const std::string& profile_name, int* profile_index)
{
  if (profile_name.empty()) {
    return Status(Status::Code::INVALID_ARG, "profile name must not be empty");
  }

  try {
    *profile_index = stoi(profile_name);
  }
  catch (const std::invalid_argument& ia) {
    return Status(
        Status::Code::INVALID_ARG,
        "unable to parse '" + profile_name + "': " + ia.what());
  }

  return Status::Success;
}

namespace {

Status
CollectInt64Fields(
    google::protobuf::Message* message, const std::string& prefix,
    std::set<std::string>* int64_fields)
{
  const google::protobuf::Descriptor* desc = message->GetDescriptor();
  const google::protobuf::Reflection* refl = message->GetReflection();
  for (int i = 0; i < desc->field_count(); ++i) {
    const google::protobuf::FieldDescriptor* field = desc->field(i);
    const std::string fullname = prefix + "::" + field->name();
    switch (field->type()) {
      case google::protobuf::FieldDescriptor::TYPE_MESSAGE: {
        if (field->is_repeated()) {
          int rsize = refl->FieldSize(*message, field);
          if (rsize == 0) {
            refl->AddMessage(message, field);
          }

          rsize = refl->FieldSize(*message, field);
          for (int r = 0; r < rsize; ++r) {
            RETURN_IF_ERROR(CollectInt64Fields(
                refl->MutableRepeatedMessage(message, field, r), fullname,
                int64_fields));
          }
        } else {
          RETURN_IF_ERROR(CollectInt64Fields(
              refl->MutableMessage(message, field), fullname, int64_fields));
        }
      } break;

      case google::protobuf::FieldDescriptor::TYPE_INT64:
      case google::protobuf::FieldDescriptor::TYPE_UINT64:
      case google::protobuf::FieldDescriptor::TYPE_SINT64:
      case google::protobuf::FieldDescriptor::TYPE_FIXED64:
      case google::protobuf::FieldDescriptor::TYPE_SFIXED64:
        int64_fields->insert(fullname);
        break;

      default:
        break;
    }
  }

  return Status::Success;
}

Status
ValidateModelConfigInt64()
{
  // Must initialize a dummy ModelConfig so that all fields are
  // visited.
  inference::ModelConfig config;

  std::set<std::string> int64_fields;
  RETURN_IF_ERROR(CollectInt64Fields(&config, "ModelConfig", &int64_fields));

  LOG_VERBOSE(1) << "ModelConfig 64-bit fields:";
  for (const auto& f : int64_fields) {
    LOG_VERBOSE(1) << "\t" << f;
  }

  // We expect to find exactly the following fields. If we get an
  // error from this code ModelConfig has added or removed a 64-bit
  // field and we need to adjust here and in ModelConfigToJson below.
  std::set<std::string> expected{
      "ModelConfig::input::dims",
      "ModelConfig::input::reshape::shape",
      "ModelConfig::output::dims",
      "ModelConfig::output::reshape::shape",
      "ModelConfig::version_policy::specific::versions",
      "ModelConfig::dynamic_batching::max_queue_delay_microseconds",
      "ModelConfig::dynamic_batching::default_queue_policy::default_timeout_"
      "microseconds",
      "ModelConfig::dynamic_batching::priority_queue_policy::value::default_"
      "timeout_microseconds",
      "ModelConfig::dynamic_batching::priority_levels",
      "ModelConfig::dynamic_batching::priority_queue_policy::key",
      "ModelConfig::dynamic_batching::default_priority_level",
      "ModelConfig::sequence_batching::direct::max_queue_delay_microseconds",
      "ModelConfig::sequence_batching::state::dims",
      "ModelConfig::sequence_batching::state::initial_state::dims",
      "ModelConfig::sequence_batching::oldest::max_queue_delay_microseconds",
      "ModelConfig::sequence_batching::max_sequence_idle_microseconds",
      "ModelConfig::ensemble_scheduling::step::model_version",
      "ModelConfig::model_warmup::inputs::value::dims",
      "ModelConfig::optimization::cuda::graph_spec::input::value::dim",
      "ModelConfig::optimization::cuda::graph_spec::graph_lower_bound::input::"
      "value::dim",
      "ModelConfig::instance_group::secondary_devices::device_id"};

  if (int64_fields != expected) {
    return Status(
        Status::Code::INTERNAL, "ModelConfig 64-bit field needs update");
  }

  return Status::Success;
}

Status
FixUInt(
    triton::common::TritonJson::Value& document,
    triton::common::TritonJson::Value& io, const std::string& name)
{
  triton::common::TritonJson::Value str_value;
  if (!io.Find(name.c_str(), &str_value)) {
    return Status::Success;
  }

  std::string str;
  RETURN_IF_ERROR(str_value.AsString(&str));

  uint64_t d;
  try {
    d = std::strtoull(str.c_str(), nullptr, 10);
  }
  catch (...) {
    return Status(
        Status::Code::INTERNAL,
        (std::string("unable to convert '") + str + "' to unsigned integer"));
  }

  str_value.SetUInt(d);

  return Status::Success;
}

Status
FixInt(
    triton::common::TritonJson::Value& document,
    triton::common::TritonJson::Value& io, const std::string& name)
{
  triton::common::TritonJson::Value str_value;
  if (!io.Find(name.c_str(), &str_value)) {
    return Status::Success;
  }

  std::string str;
  RETURN_IF_ERROR(str_value.AsString(&str));

  int64_t d;
  try {
    d = std::atoll(str.c_str());
  }
  catch (...) {
    return Status(
        Status::Code::INTERNAL,
        (std::string("unable to convert '") + str + "' to integer"));
  }

  str_value.SetInt(d);

  return Status::Success;
}

Status
FixIntArray(
    triton::common::TritonJson::Value& document,
    triton::common::TritonJson::Value& io, const std::string& name)
{
  triton::common::TritonJson::Value fixed_shape_array(
      document, triton::common::TritonJson::ValueType::ARRAY);

  if (!io.Find(name.c_str())) {
    return Status::Success;
  }

  triton::common::TritonJson::Value shape_array;
  RETURN_IF_ERROR(io.MemberAsArray(name.c_str(), &shape_array));
  for (size_t i = 0; i < shape_array.ArraySize(); ++i) {
    std::string str;
    RETURN_IF_ERROR(shape_array.IndexAsString(i, &str));

    int64_t d;
    try {
      d = std::atoll(str.c_str());
    }
    catch (...) {
      return Status(
          Status::Code::INTERNAL,
          (std::string("unable to convert '") + str + "' to integer"));
    }

    RETURN_IF_ERROR(fixed_shape_array.AppendInt(d));
  }

  shape_array.Swap(fixed_shape_array);
  fixed_shape_array.Release();

  return Status::Success;
}

Status
FixObjectArray(
    triton::common::TritonJson::Value& document,
    triton::common::TritonJson::Value& arr, const std::string& name)
{
  for (size_t i = 0; i < arr.ArraySize(); ++i) {
    triton::common::TritonJson::Value obj;
    RETURN_IF_ERROR(arr.IndexAsObject(i, &obj));
    RETURN_IF_ERROR(FixInt(document, obj, name));
  }

  return Status::Success;
}

}  // namespace

Status
ModelConfigToJson(
    const inference::ModelConfig& config, const uint32_t config_version,
    std::string* json_str)
{
  // Currently only support 'config_version' 1, which is the json
  // representation of the ModelConfig protobuf with the int64 fields
  // fixes to be actual numbers instead of the string madness done by
  // protobuf.
  if (config_version != 1) {
    return Status(
        Status::Code::INVALID_ARG,
        std::string("model configuration version ") +
            std::to_string(config_version) +
            " not supported, supported versions are: 1");
  }

  // Config will have 0 byte size if all fields are with default value,
  // in other word the config is empty.
  if (config.ByteSizeLong() == 0) {
    json_str->clear();
    return Status::Success;
  }

  std::string config_json_str;
  ::google::protobuf::util::JsonPrintOptions options;
  options.preserve_proto_field_names = true;
  options.always_print_primitive_fields = true;
  ::google::protobuf::util::MessageToJsonString(
      config, &config_json_str, options);

  // We need to verify that every field 64-bit field in the
  // ModelConfig protobuf is being handled. We hardcode the known
  // fields and check just once to make sure everything has been
  // handled. We could have this check in a separately compiled CI
  // test but it is convenient to keep it here close to the code below
  // that actually fixes the 64-bit fields.
  {
    static std::once_flag fonce;
    Status status = Status::Success;
    std::call_once(fonce, [&status] { status = ValidateModelConfigInt64(); });
    RETURN_IF_ERROR(status);
  }

  // In the json produced by protobuf, int64 and uint64 values are
  // represented as strings. Protobuf doesn't provide an option to
  // disable this (sigh) so we need to fix it up here as we want the
  // json representation of the config to be reasonable json...
  triton::common::TritonJson::Value config_json;
  config_json.Parse(config_json_str);

  // Fix input::dims, input::reshape::shape, output::dims,
  // output::reshape::shape
  for (std::string name : {"input", "output"}) {
    triton::common::TritonJson::Value ios;
    RETURN_IF_ERROR(config_json.MemberAsArray(name.c_str(), &ios));
    for (size_t i = 0; i < ios.ArraySize(); ++i) {
      triton::common::TritonJson::Value io;
      RETURN_IF_ERROR(ios.IndexAsObject(i, &io));
      RETURN_IF_ERROR(FixIntArray(config_json, io, "dims"));

      triton::common::TritonJson::Value reshape;
      if (io.Find("reshape", &reshape)) {
        RETURN_IF_ERROR(FixIntArray(config_json, reshape, "shape"));
      }
    }
  }

  // Fix version_policy::specific::versions
  {
    triton::common::TritonJson::Value vp;
    if (config_json.Find("version_policy", &vp)) {
      triton::common::TritonJson::Value specific;
      if (vp.Find("specific", &specific)) {
        RETURN_IF_ERROR(FixIntArray(config_json, specific, "versions"));
      }
    }
  }

  // Fix dynamic_batching::max_queue_delay_microseconds,
  // dynamic_batching::default_queue_policy::default_timeout_microseconds,
  // dynamic_batching::priority_queue_policy::value::default_timeout_microseconds
  // dynamic_batching::priority_levels
  // dynamic_batching::default_priority_level
  // dynamic_batching::priority_queue_policy::key is left as JSON only allows
  // strings for keys
  {
    triton::common::TritonJson::Value db;
    if (config_json.Find("dynamic_batching", &db)) {
      RETURN_IF_ERROR(FixUInt(config_json, db, "max_queue_delay_microseconds"));
      RETURN_IF_ERROR(FixUInt(config_json, db, "priority_levels"));
      RETURN_IF_ERROR(FixUInt(config_json, db, "default_priority_level"));
      triton::common::TritonJson::Value dqp;
      if (db.Find("default_queue_policy", &dqp)) {
        RETURN_IF_ERROR(
            FixUInt(config_json, dqp, "default_timeout_microseconds"));
      }
      triton::common::TritonJson::Value pqp;
      if (db.Find("priority_queue_policy", &pqp)) {
        // Iterate over each member in 'pqp' and fix...
        std::vector<std::string> members;
        RETURN_IF_ERROR(pqp.Members(&members));
        for (const auto& m : members) {
          triton::common::TritonJson::Value el;
          RETURN_IF_ERROR(pqp.MemberAsObject(m.c_str(), &el));
          RETURN_IF_ERROR(
              FixUInt(config_json, el, "default_timeout_microseconds"));
        }
      }
    }
  }

  // Fix sequence_batching::oldest::max_queue_delay_microseconds,
  // sequence_batching::direct::max_queue_delay_microseconds,
  // sequence_batching::max_sequence_idle_microseconds
  {
    triton::common::TritonJson::Value sb;
    if (config_json.Find("sequence_batching", &sb)) {
      RETURN_IF_ERROR(
          FixUInt(config_json, sb, "max_sequence_idle_microseconds"));
      triton::common::TritonJson::Value oldest;
      if (sb.Find("oldest", &oldest)) {
        RETURN_IF_ERROR(
            FixUInt(config_json, oldest, "max_queue_delay_microseconds"));
      }
      triton::common::TritonJson::Value direct;
      if (sb.Find("direct", &direct)) {
        RETURN_IF_ERROR(
            FixUInt(config_json, direct, "max_queue_delay_microseconds"));
      }

      triton::common::TritonJson::Value states;
      if (sb.Find("state", &states)) {
        for (size_t i = 0; i < states.ArraySize(); ++i) {
          triton::common::TritonJson::Value state;
          RETURN_IF_ERROR(states.IndexAsObject(i, &state));
          RETURN_IF_ERROR(FixIntArray(config_json, state, "dims"));

          triton::common::TritonJson::Value initial_state;
          if (sb.Find("initial_state", &initial_state)) {
            RETURN_IF_ERROR(FixIntArray(config_json, initial_state, "dims"));
          }
        }
      }
    }
  }

  // Fix ensemble_scheduling::step::model_version.
  {
    triton::common::TritonJson::Value ens;
    if (config_json.Find("ensemble_scheduling", &ens)) {
      triton::common::TritonJson::Value step;
      if (ens.Find("step", &step)) {
        RETURN_IF_ERROR(FixObjectArray(config_json, step, "model_version"));
      }
    }
  }

  // Fix model_warmup::inputs::value::dims.
  {
    triton::common::TritonJson::Value warmups;
    if (config_json.Find("model_warmup", &warmups)) {
      for (size_t i = 0; i < warmups.ArraySize(); ++i) {
        triton::common::TritonJson::Value warmup;
        RETURN_IF_ERROR(warmups.IndexAsObject(i, &warmup));
        triton::common::TritonJson::Value inputs;
        if (warmup.Find("inputs", &inputs)) {
          std::vector<std::string> members;
          RETURN_IF_ERROR(inputs.Members(&members));
          for (const auto& m : members) {
            triton::common::TritonJson::Value input;
            RETURN_IF_ERROR(inputs.MemberAsObject(m.c_str(), &input));
            RETURN_IF_ERROR(FixIntArray(config_json, input, "dims"));
          }
        }
      }
    }
  }

  // Convert fixed json back the string...
  triton::common::TritonJson::WriteBuffer buffer;
  RETURN_IF_ERROR(config_json.Write(&buffer));
  *json_str = std::move(buffer.MutableContents());

  return Status::Success;
}

Status
JsonToModelConfig(
    const std::string& json_config, const uint32_t config_version,
    inference::ModelConfig* protobuf_config)
{
  // Currently only support 'config_version' 1, which is the json
  // representation of the ModelConfig protobuf matches the representation in
  // ModelConfigToJson().
  if (config_version != 1) {
    return Status(
        Status::Code::INVALID_ARG,
        std::string("model configuration version ") +
            std::to_string(config_version) +
            " not supported, supported versions are: 1");
  }

  ::google::protobuf::util::JsonParseOptions options;
  options.case_insensitive_enum_parsing = true;
  options.ignore_unknown_fields = false;
  auto err = ::google::protobuf::util::JsonStringToMessage(
      json_config, protobuf_config, options);
  if (!err.ok()) {
    return Status(Status::Code::INVALID_ARG, std::string(err.message()));
  }

  return Status::Success;
}

BackendType
GetBackendTypeFromPlatform(const std::string& platform_name)
{
  if ((platform_name == kTensorFlowGraphDefPlatform) ||
      (platform_name == kTensorFlowSavedModelPlatform)) {
    return BackendType::BACKEND_TYPE_TENSORFLOW;
  }

  if (platform_name == kTensorRTPlanPlatform) {
    return BackendType::BACKEND_TYPE_TENSORRT;
  }

  if (platform_name == kOnnxRuntimeOnnxPlatform) {
    return BackendType::BACKEND_TYPE_ONNXRUNTIME;
  }

  if (platform_name == kPyTorchLibTorchPlatform) {
    return BackendType::BACKEND_TYPE_PYTORCH;
  }

  return BackendType::BACKEND_TYPE_UNKNOWN;
}

/// Get the BackendType value for a backend name.
/// \param backend_name The backend name.
/// \return The BackendType or BackendType::UNKNOWN if the platform string
/// is not recognized.
BackendType
GetBackendType(const std::string& backend_name)
{
  if (backend_name == kTensorFlowBackend) {
    return BackendType::BACKEND_TYPE_TENSORFLOW;
  }

  if (backend_name == kTensorRTBackend) {
    return BackendType::BACKEND_TYPE_TENSORRT;
  }

  if (backend_name == kOnnxRuntimeBackend) {
    return BackendType::BACKEND_TYPE_ONNXRUNTIME;
  }

  if (backend_name == kPyTorchBackend) {
    return BackendType::BACKEND_TYPE_PYTORCH;
  }

  return BackendType::BACKEND_TYPE_UNKNOWN;
}

TRITONSERVER_DataType
DataTypeToTriton(const inference::DataType dtype)
{
  switch (dtype) {
    case inference::DataType::TYPE_BOOL:
      return TRITONSERVER_TYPE_BOOL;
    case inference::DataType::TYPE_UINT8:
      return TRITONSERVER_TYPE_UINT8;
    case inference::DataType::TYPE_UINT16:
      return TRITONSERVER_TYPE_UINT16;
    case inference::DataType::TYPE_UINT32:
      return TRITONSERVER_TYPE_UINT32;
    case inference::DataType::TYPE_UINT64:
      return TRITONSERVER_TYPE_UINT64;
    case inference::DataType::TYPE_INT8:
      return TRITONSERVER_TYPE_INT8;
    case inference::DataType::TYPE_INT16:
      return TRITONSERVER_TYPE_INT16;
    case inference::DataType::TYPE_INT32:
      return TRITONSERVER_TYPE_INT32;
    case inference::DataType::TYPE_INT64:
      return TRITONSERVER_TYPE_INT64;
    case inference::DataType::TYPE_FP16:
      return TRITONSERVER_TYPE_FP16;
    case inference::DataType::TYPE_FP32:
      return TRITONSERVER_TYPE_FP32;
    case inference::DataType::TYPE_FP64:
      return TRITONSERVER_TYPE_FP64;
    case inference::DataType::TYPE_STRING:
      return TRITONSERVER_TYPE_BYTES;
    case inference::DataType::TYPE_BF16:
      return TRITONSERVER_TYPE_BF16;
    default:
      break;
  }

  return TRITONSERVER_TYPE_INVALID;
}

inference::DataType
TritonToDataType(const TRITONSERVER_DataType dtype)
{
  switch (dtype) {
    case TRITONSERVER_TYPE_BOOL:
      return inference::DataType::TYPE_BOOL;
    case TRITONSERVER_TYPE_UINT8:
      return inference::DataType::TYPE_UINT8;
    case TRITONSERVER_TYPE_UINT16:
      return inference::DataType::TYPE_UINT16;
    case TRITONSERVER_TYPE_UINT32:
      return inference::DataType::TYPE_UINT32;
    case TRITONSERVER_TYPE_UINT64:
      return inference::DataType::TYPE_UINT64;
    case TRITONSERVER_TYPE_INT8:
      return inference::DataType::TYPE_INT8;
    case TRITONSERVER_TYPE_INT16:
      return inference::DataType::TYPE_INT16;
    case TRITONSERVER_TYPE_INT32:
      return inference::DataType::TYPE_INT32;
    case TRITONSERVER_TYPE_INT64:
      return inference::DataType::TYPE_INT64;
    case TRITONSERVER_TYPE_FP16:
      return inference::DataType::TYPE_FP16;
    case TRITONSERVER_TYPE_FP32:
      return inference::DataType::TYPE_FP32;
    case TRITONSERVER_TYPE_FP64:
      return inference::DataType::TYPE_FP64;
    case TRITONSERVER_TYPE_BYTES:
      return inference::DataType::TYPE_STRING;
    case TRITONSERVER_TYPE_BF16:
      return inference::DataType::TYPE_BF16;
    default:
      break;
  }

  return inference::DataType::TYPE_INVALID;
}

bool
ConfigChangeRequiresReload(
    const inference::ModelConfig& old_config,
    const inference::ModelConfig& new_config)
{
  ::google::protobuf::util::MessageDifferencer pb_diff;
  pb_diff.IgnoreField(
      old_config.descriptor()->FindFieldByLowercaseName("instance_group"));
  pb_diff.IgnoreField(
      old_config.descriptor()->FindFieldByLowercaseName("version_policy"));
  return !pb_diff.Compare(old_config, new_config);
}

bool
EquivalentInInstanceConfig(
    const inference::ModelInstanceGroup& instance_config_lhs,
    const inference::ModelInstanceGroup& instance_config_rhs)
{
  ::google::protobuf::util::MessageDifferencer pb_diff;
  pb_diff.IgnoreField(
      instance_config_lhs.descriptor()->FindFieldByLowercaseName("name"));
  pb_diff.IgnoreField(
      instance_config_lhs.descriptor()->FindFieldByLowercaseName("count"));
  return pb_diff.Compare(instance_config_lhs, instance_config_rhs);
}

std::string
InstanceConfigSignature(const inference::ModelInstanceGroup& instance_config)
{
  inference::ModelInstanceGroup config = instance_config;
  *config.mutable_name() = "[Normalized]";
  config.set_count(1);
  return config.SerializeAsString();
}

}}  // namespace triton::core