trtx 0.7.0+rtx1.5

Safe Rust bindings to NVIDIA TensorRT-RTX (EXPERIMENTAL - NOT FOR PRODUCTION)
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
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
//! Network definition for building TensorRT engines.
//!
//! [`NetworkDefinition`] holds [`trtx_sys::nvinfer1::INetworkDefinition`] (C++ [`nvinfer1::INetworkDefinition`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_network_definition.html)).
//! [`Tensor`] wraps [`trtx_sys::nvinfer1::ITensor`] (C++ [`nvinfer1::ITensor`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_tensor.html)).
//! Layer handles implement [`trtx_sys::AsLayer`] / [`trtx_sys::AsLayerTyped`] over concrete `trtx_sys::nvinfer1::I*Layer` types; C++ index: [annotated](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/annotated.html).

use crate::interfaces::RecordError;
pub use crate::tensor::Tensor;
use cxx::UniquePtr;
use std::ffi::{CStr, CString};
use std::marker::PhantomData;
use std::pin::Pin;
use trtx_sys::nvinfer1::{IConcatenationLayer, IEinsumLayer, INetworkDefinition, ITensor};
use trtx_sys::{nvinfer1, LayerType, SampleMode, Weights};
use trtx_sys::{AsLayer, AsLayerTyped};
#[cfg(feature = "v_1_5")]
use trtx_sys::{AttentionIOForm, CausalMaskKind};
#[cfg(feature = "v_1_4")]
use trtx_sys::{CollectiveOperation, MoEActType, ReduceOperation};
use trtx_sys::{
    DataType, Dims64, FillOperation, GatherMode, MatrixOperation, ScaleMode, TopKOperation,
};
use trtx_sys::{InterpolationMode, KVCacheMode};

/// Panics if the layer or tensor was created from a different network.
macro_rules! check_network {
    ($network:ident, $this:ident) => {
        if $network.inner.as_ptr() != $this.network {
            panic!("Layer or tensor was created from different network")
        }
    };
    ($network:ident, $tensor:expr) => {
        if $network.inner.as_ptr() != $tensor.network {
            panic!("Layer or tensor was created from different network")
        }
    };
}
pub(crate) use check_network;

use crate::error::{Error, OkOrElseError, OkOrFailedSettingProperty, PropertySetAttempt, Result};
use crate::interfaces::ErrorRecorder;
use log::{debug, trace};

/// Kernel and optional bias weights for convolution and deconvolution layers.
#[derive(Debug)]
pub struct ConvWeights<'weights> {
    pub kernel_weights: &'weights [u8],
    pub kernel_dtype: crate::DataType,
    pub kernel_name: Option<&'weights str>,
    pub bias_weights: Option<&'weights [u8]>,
    pub bias_dtype: Option<crate::DataType>,
    pub bias_name: Option<&'weights str>,
}

#[derive(Debug)]
pub struct OwnedWeights {
    pub shape: Vec<i64>,
    pub data_type: DataType,
    pub values: Vec<u8>,
    pub name: Option<String>,
}

#[derive(Debug)]
pub struct OwnedConvWeights {
    pub kernel: OwnedWeights,
    pub bias: Option<OwnedWeights>,
}

impl OwnedConvWeights {
    pub fn as_weights(&self) -> ConvWeights<'_> {
        ConvWeights {
            kernel_weights: &self.kernel.values,
            kernel_dtype: self.kernel.data_type,
            kernel_name: self.kernel.name.as_deref(),
            bias_weights: self.bias.as_ref().map(|b| b.values.as_slice()),
            bias_dtype: self.bias.as_ref().map(|b| b.data_type),
            bias_name: self.bias.as_ref().and_then(|b| b.name.as_deref()),
        }
    }
}

/// `Inner` is a concrete [`trtx_sys::nvinfer1`] `I*Layer` (all implement [`trtx_sys::AsLayer`] toward [`trtx_sys::nvinfer1::ILayer`]); C++ base [`nvinfer1::ILayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_layer.html).
pub struct Layer<'network, Inner: AsLayer> {
    pub(crate) inner: Pin<&'network mut Inner>,
    pub(crate) network: *const nvinfer1::INetworkDefinition,
}

impl<Inner: AsLayer> std::fmt::Debug for Layer<'_, Inner> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Layer")
            .field("inner", &format!("{:x}", &*self.inner as *const _ as usize))
            .field(
                "layer_type",
                &Into::<LayerType>::into(self.inner.as_layer().getType()),
            )
            .finish_non_exhaustive()
    }
}

impl<'network, Inner: AsLayerTyped> Layer<'network, Inner> {
    /// See [nvinfer1::ILayer::getType] (compile time dispatch)
    pub const fn layer_type(&self) -> LayerType {
        Inner::TYPE
    }

    pub(crate) fn new(
        network: *const nvinfer1::INetworkDefinition,
        ptr: *mut Inner,
    ) -> Result<Self> {
        unsafe {
            let ptr = ptr
                .as_mut()
                .ok_or(Error::LayerCreationFailed(Inner::TYPE))?;
            Ok(Self {
                inner: Pin::new_unchecked(ptr),
                network,
            })
        }
    }
}
impl<'network> Layer<'network, nvinfer1::ILayer> {
    /// See [nvinfer1::ILayer::getType] (dynamic dispatch)
    pub fn layer_type_dynamic(&self) -> LayerType {
        self.inner.as_layer().getType().into()
    }

    /// Create a generic ILayer (of unknown type)
    pub(crate) fn new_dyn(
        network: *const nvinfer1::INetworkDefinition,
        ptr: *mut nvinfer1::ILayer,
    ) -> Result<Self> {
        unsafe {
            let ptr = ptr.as_mut().ok_or(Error::GetLayerFailed)?;
            Ok(Self {
                inner: Pin::new_unchecked(ptr),
                network,
            })
        }
    }
}

impl<'network, Inner: AsLayer> Layer<'network, Inner> {
    /// See [nvinfer1::ILayer::setInput]
    pub fn set_input(
        &mut self,
        network: &'_ mut NetworkDefinition,
        index: i32,
        tensor: &'_ Tensor,
    ) -> Result<()> {
        check_network!(network, self);
        debug!(
            "set_input layer={} index={index} tensor={}",
            layer_dbg(network, self),
            tensor_dbg(network, tensor)
        );
        unsafe { self.inner.as_mut().get_unchecked_mut() }
            .as_layer_pin_mut()
            .setInput(index, tensor.pin_mut());
        Ok(())
    }

    /// See [nvinfer1::ILayer::getInput]
    pub fn input(&self, network: &'_ NetworkDefinition, index: i32) -> Result<Tensor<'network>> {
        check_network!(network, self);
        let tensor = self.inner.as_layer().getInput(index);
        unsafe { Tensor::new(self.network, tensor) }
    }

    #[deprecated = "use input instead"]
    pub fn get_input(
        &self,
        network: &'_ NetworkDefinition,
        index: i32,
    ) -> Result<Tensor<'network>> {
        self.input(network, index)
    }

    /// See [nvinfer1::ILayer::getOutput]
    pub fn output(&self, network: &'_ NetworkDefinition, index: i32) -> Result<Tensor<'network>> {
        check_network!(network, self);
        let tensor = self.inner.as_layer().getOutput(index);
        unsafe { Tensor::new(self.network, tensor) }
    }

    #[deprecated = "use output instead"]
    pub fn get_output(
        &self,
        network: &'_ NetworkDefinition,
        index: i32,
    ) -> Result<Tensor<'network>> {
        self.output(network, index)
    }
    /// See [nvinfer1::ILayer::getNbInputs]
    pub fn num_inputs(&self, network: &'_ NetworkDefinition) -> i32 {
        check_network!(network, self);
        self.inner.as_layer().getNbInputs()
    }

    #[deprecated = "use num_inputs instead"]
    pub fn get_num_inputs(&self, network: &'_ NetworkDefinition) -> i32 {
        self.num_inputs(network)
    }

    /// See [nvinfer1::ILayer::getNbOutputs]
    pub fn num_outputs(&self, network: &'_ NetworkDefinition) -> i32 {
        check_network!(network, self);
        self.inner.as_layer().getNbOutputs()
    }

    #[deprecated = "use num_outputs instead"]
    pub fn get_num_outputs(&self, network: &'_ NetworkDefinition) -> i32 {
        self.num_outputs(network)
    }

    /// See [nvinfer1::ILayer::setName]
    pub fn set_name(&mut self, network: &'_ mut NetworkDefinition, name: &str) -> Result<()> {
        check_network!(network, self);
        let name = CString::new(name)?;
        unsafe {
            self.inner
                .as_mut()
                .get_unchecked_mut()
                .as_layer_pin_mut()
                .setName(name.as_ptr())
        };
        Ok(())
    }

    /// See [nvinfer1::ILayer::getName]
    pub fn name(&self, network: &NetworkDefinition) -> String {
        check_network!(network, self);
        let name = self.inner.as_layer().getName();
        // must clone since layer may change name at any time! Cow from to_string_lossy() only
        // possible if name immutable
        if name.is_null() {
            "(unamed)".to_string()
        } else {
            unsafe { CStr::from_ptr(name).to_string_lossy().to_string() }
        }
    }
}

/// [`trtx_sys::nvinfer1::IActivationLayer`] — C++ [`nvinfer1::IActivationLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_activation_layer.html).
pub type ActivationLayer<'layer> = Layer<'layer, nvinfer1::IActivationLayer>;
/// [`trtx_sys::nvinfer1::IAssertionLayer`] — C++ [`nvinfer1::IAssertionLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_assertion_layer.html).
pub type AssertionLayer<'layer> = Layer<'layer, nvinfer1::IAssertionLayer>;
/// [`trtx_sys::nvinfer1::ICastLayer`] — C++ [`nvinfer1::ICastLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_cast_layer.html).
pub type CastLayer<'layer> = Layer<'layer, nvinfer1::ICastLayer>;
/// [`trtx_sys::nvinfer1::IConcatenationLayer`] — C++ [`nvinfer1::IConcatenationLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_concatenation_layer.html).
pub type ConcatenationLayer<'layer> = Layer<'layer, nvinfer1::IConcatenationLayer>;
/// [`trtx_sys::nvinfer1::IConstantLayer`] — C++ [`nvinfer1::IConstantLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_constant_layer.html).
pub type ConstantLayer<'layer> = Layer<'layer, nvinfer1::IConstantLayer>;
/// [`trtx_sys::nvinfer1::IConvolutionLayer`] — C++ [`nvinfer1::IConvolutionLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_convolution_layer.html).
pub type ConvolutionLayer<'layer> = Layer<'layer, nvinfer1::IConvolutionLayer>;
/// [`trtx_sys::nvinfer1::ICumulativeLayer`] — C++ [`nvinfer1::ICumulativeLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_cumulative_layer.html).
pub type CumulativeLayer<'layer> = Layer<'layer, nvinfer1::ICumulativeLayer>;
/// [`trtx_sys::nvinfer1::IDeconvolutionLayer`] — C++ [`nvinfer1::IDeconvolutionLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_deconvolution_layer.html).
pub type DeconvolutionLayer<'layer> = Layer<'layer, nvinfer1::IDeconvolutionLayer>;
/// [`trtx_sys::nvinfer1::IDequantizeLayer`] — C++ [`nvinfer1::IDequantizeLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_dequantize_layer.html).
pub type DequantizeLayer<'layer> = Layer<'layer, nvinfer1::IDequantizeLayer>;
/// [`trtx_sys::nvinfer1::IDynamicQuantizeLayer`] — C++ [`nvinfer1::IDynamicQuantizeLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_dynamic_quantize_layer.html).
pub type DynamicQuantizeLayer<'layer> = Layer<'layer, nvinfer1::IDynamicQuantizeLayer>;
/// [`trtx_sys::nvinfer1::IElementWiseLayer`] — C++ [`nvinfer1::IElementWiseLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_element_wise_layer.html).
pub type ElementWiseLayer<'layer> = Layer<'layer, nvinfer1::IElementWiseLayer>;
/// [`trtx_sys::nvinfer1::IEinsumLayer`] — C++ [`nvinfer1::IEinsumLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_einsum_layer.html).
pub type EinsumLayer<'layer> = Layer<'layer, nvinfer1::IEinsumLayer>;
/// [`trtx_sys::nvinfer1::IFillLayer`] — C++ [`nvinfer1::IFillLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_fill_layer.html).
pub type FillLayer<'layer> = Layer<'layer, nvinfer1::IFillLayer>;
/// [`trtx_sys::nvinfer1::IGatherLayer`] — C++ [`nvinfer1::IGatherLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_gather_layer.html).
pub type GatherLayer<'layer> = Layer<'layer, nvinfer1::IGatherLayer>;
/// [`trtx_sys::nvinfer1::IGridSampleLayer`] — C++ [`nvinfer1::IGridSampleLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_grid_sample_layer.html).
pub type GridSampleLayer<'layer> = Layer<'layer, nvinfer1::IGridSampleLayer>;
/// [`trtx_sys::nvinfer1::IIdentityLayer`] — C++ [`nvinfer1::IIdentityLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_identity_layer.html).
pub type IdentityLayer<'layer> = Layer<'layer, nvinfer1::IIdentityLayer>;
/// [`trtx_sys::nvinfer1::IMatrixMultiplyLayer`] — C++ [`nvinfer1::IMatrixMultiplyLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_matrix_multiply_layer.html).
pub type MatrixMultiplyLayer<'layer> = Layer<'layer, nvinfer1::IMatrixMultiplyLayer>;
/// [`trtx_sys::nvinfer1::INMSLayer`] — C++ [`nvinfer1::INMSLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_n_m_s_layer.html).
pub type NMSLayer<'layer> = Layer<'layer, nvinfer1::INMSLayer>;
/// [`trtx_sys::nvinfer1::INonZeroLayer`] — C++ [`nvinfer1::INonZeroLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_non_zero_layer.html).
pub type NonZeroLayer<'layer> = Layer<'layer, nvinfer1::INonZeroLayer>;
/// [`trtx_sys::nvinfer1::INormalizationLayer`] — C++ [`nvinfer1::INormalizationLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_normalization_layer.html).
pub type NormalizationLayer<'layer> = Layer<'layer, nvinfer1::INormalizationLayer>;
/// [`trtx_sys::nvinfer1::IPaddingLayer`] — C++ [`nvinfer1::IPaddingLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_padding_layer.html).
pub type PaddingLayer<'layer> = Layer<'layer, nvinfer1::IPaddingLayer>;
/// [`trtx_sys::nvinfer1::IParametricReLULayer`] — C++ [`nvinfer1::IParametricReLULayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_parametric_re_l_u_layer.html).
pub type ParametricReLULayer<'layer> = Layer<'layer, nvinfer1::IParametricReLULayer>;
/// [`trtx_sys::nvinfer1::IPoolingLayer`] — C++ [`nvinfer1::IPoolingLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_pooling_layer.html).
pub type PoolingLayer<'layer> = Layer<'layer, nvinfer1::IPoolingLayer>;
/// [`trtx_sys::nvinfer1::IQuantizeLayer`] — C++ [`nvinfer1::IQuantizeLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_quantize_layer.html).
pub type QuantizeLayer<'layer> = Layer<'layer, nvinfer1::IQuantizeLayer>;
/// [`trtx_sys::nvinfer1::IRaggedSoftMaxLayer`] — C++ [`nvinfer1::IRaggedSoftMaxLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_ragged_soft_max_layer.html).
pub type RaggedSoftMaxLayer<'layer> = Layer<'layer, nvinfer1::IRaggedSoftMaxLayer>;
/// [`trtx_sys::nvinfer1::IReduceLayer`] — C++ [`nvinfer1::IReduceLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_reduce_layer.html).
pub type ReduceLayer<'layer> = Layer<'layer, nvinfer1::IReduceLayer>;
/// [`trtx_sys::nvinfer1::IResizeLayer`] — C++ [`nvinfer1::IResizeLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_resize_layer.html).
pub type ResizeLayer<'layer> = Layer<'layer, nvinfer1::IResizeLayer>;
/// [`trtx_sys::nvinfer1::IRotaryEmbeddingLayer`] — C++ [`nvinfer1::IRotaryEmbeddingLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_rotary_embedding_layer.html).
pub type RotaryEmbeddingLayer<'layer> = Layer<'layer, nvinfer1::IRotaryEmbeddingLayer>;
/// [`trtx_sys::nvinfer1::IScaleLayer`] — C++ [`nvinfer1::IScaleLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_scale_layer.html).
pub type ScaleLayer<'layer> = Layer<'layer, nvinfer1::IScaleLayer>;
/// [`trtx_sys::nvinfer1::IScatterLayer`] — C++ [`nvinfer1::IScatterLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_scatter_layer.html).
pub type ScatterLayer<'layer> = Layer<'layer, nvinfer1::IScatterLayer>;
/// [`trtx_sys::nvinfer1::ISelectLayer`] — C++ [`nvinfer1::ISelectLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_select_layer.html).
pub type SelectLayer<'layer> = Layer<'layer, nvinfer1::ISelectLayer>;
/// [`trtx_sys::nvinfer1::IShapeLayer`] — C++ [`nvinfer1::IShapeLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_shape_layer.html).
pub type ShapeLayer<'layer> = Layer<'layer, nvinfer1::IShapeLayer>;
/// [`trtx_sys::nvinfer1::IShuffleLayer`] — C++ [`nvinfer1::IShuffleLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_shuffle_layer.html).
pub type ShuffleLayer<'layer> = Layer<'layer, nvinfer1::IShuffleLayer>;
/// [`trtx_sys::nvinfer1::ISliceLayer`] — C++ [`nvinfer1::ISliceLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_slice_layer.html).
pub type SliceLayer<'layer> = Layer<'layer, nvinfer1::ISliceLayer>;
/// [`trtx_sys::nvinfer1::ISoftMaxLayer`] — C++ [`nvinfer1::ISoftMaxLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_soft_max_layer.html).
pub type SoftMaxLayer<'layer> = Layer<'layer, nvinfer1::ISoftMaxLayer>;
/// [`trtx_sys::nvinfer1::ISqueezeLayer`] — C++ [`nvinfer1::ISqueezeLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_squeeze_layer.html).
pub type SqueezeLayer<'layer> = Layer<'layer, nvinfer1::ISqueezeLayer>;
/// [`trtx_sys::nvinfer1::ITopKLayer`] — C++ [`nvinfer1::ITopKLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_top_k_layer.html).
pub type TopKLayer<'layer> = Layer<'layer, nvinfer1::ITopKLayer>;
/// [`trtx_sys::nvinfer1::IUnaryLayer`] — C++ [`nvinfer1::IUnaryLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_unary_layer.html).
pub type UnaryLayer<'layer> = Layer<'layer, nvinfer1::IUnaryLayer>;
/// [`trtx_sys::nvinfer1::IUnsqueezeLayer`] — C++ [`nvinfer1::IUnsqueezeLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_unsqueeze_layer.html).
pub type UnsqueezeLayer<'layer> = Layer<'layer, nvinfer1::IUnsqueezeLayer>;
/// [`trtx_sys::nvinfer1::IReverseSequenceLayer`] — C++ [`nvinfer1::IReverseSequenceLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_reverse_sequence_layer.html).
pub type ReverseSequenceLayer<'layer> = Layer<'layer, nvinfer1::IReverseSequenceLayer>;
/// [`trtx_sys::nvinfer1::IKVCacheUpdateLayer`] — C++ [`nvinfer1::IKVCacheUpdateLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_k_v_cache_update_layer.html).
pub type KVCacheUpdateLayer<'layer> = Layer<'layer, nvinfer1::IKVCacheUpdateLayer>;
/// [`trtx_sys::nvinfer1::ILRNLayer`] — C++ [`nvinfer1::ILRNLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_l_r_n_layer.html).
pub type LrnLayer<'layer> = Layer<'layer, nvinfer1::ILRNLayer>;
/// [`trtx_sys::nvinfer1::IOneHotLayer`] — C++ [`nvinfer1::IOneHotLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_one_hot_layer.html).
pub type OneHotLayer<'layer> = Layer<'layer, nvinfer1::IOneHotLayer>;
#[cfg(feature = "v_1_4")]
/// [`trtx_sys::nvinfer1::IMoELayer`] — C++ [`nvinfer1::IMoELayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_mo_e_layer.html).
#[cfg(feature = "v_1_4")]
pub type MoELayer<'layer> = Layer<'layer, nvinfer1::IMoELayer>;
#[cfg(feature = "v_1_4")]
/// [`trtx_sys::nvinfer1::IDistCollectiveLayer`] — C++ [`nvinfer1::IDistCollectiveLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_dist_collective_layer.html).
#[cfg(feature = "v_1_4")]
pub type DistCollectiveLayer<'layer> = Layer<'layer, nvinfer1::IDistCollectiveLayer>;

// Loop and conditional boundary layers (created via Loop / IfConditional / add_attention)
/// [`trtx_sys::nvinfer1::IAttentionInputLayer`] — C++ [`nvinfer1::IAttentionInputLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_attention_input_layer.html).
pub type AttentionInputLayer<'layer> = Layer<'layer, nvinfer1::IAttentionInputLayer>;
/// [`trtx_sys::nvinfer1::IAttentionOutputLayer`] — C++ [`nvinfer1::IAttentionOutputLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_attention_output_layer.html).
pub type AttentionOutputLayer<'layer> = Layer<'layer, nvinfer1::IAttentionOutputLayer>;
/// [`trtx_sys::nvinfer1::IAttentionBoundaryLayer`] — C++ [`nvinfer1::IAttentionBoundaryLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_attention_boundary_layer.html).
pub type AttentionBoundaryLayer<'layer> = Layer<'layer, nvinfer1::IAttentionBoundaryLayer>;
/// [`trtx_sys::nvinfer1::ILoopBoundaryLayer`] — C++ [`nvinfer1::ILoopBoundaryLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_loop_boundary_layer.html).
pub type LoopBoundaryLayer<'layer> = Layer<'layer, nvinfer1::ILoopBoundaryLayer>;
/// [`trtx_sys::nvinfer1::IRecurrenceLayer`] — C++ [`nvinfer1::IRecurrenceLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_recurrence_layer.html).
pub type RecurrenceLayer<'layer> = Layer<'layer, nvinfer1::IRecurrenceLayer>;
/// [`trtx_sys::nvinfer1::ILoopOutputLayer`] — C++ [`nvinfer1::ILoopOutputLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_loop_output_layer.html).
pub type LoopOutputLayer<'layer> = Layer<'layer, nvinfer1::ILoopOutputLayer>;
/// [`trtx_sys::nvinfer1::ITripLimitLayer`] — C++ [`nvinfer1::ITripLimitLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_trip_limit_layer.html).
pub type TripLimitLayer<'layer> = Layer<'layer, nvinfer1::ITripLimitLayer>;
/// [`trtx_sys::nvinfer1::IIteratorLayer`] — C++ [`nvinfer1::IIteratorLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_iterator_layer.html).
pub type IteratorLayer<'layer> = Layer<'layer, nvinfer1::IIteratorLayer>;
/// [`trtx_sys::nvinfer1::IConditionLayer`] — C++ [`nvinfer1::IConditionLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_condition_layer.html).
pub type ConditionLayer<'layer> = Layer<'layer, nvinfer1::IConditionLayer>;
/// [`trtx_sys::nvinfer1::IIfConditionalOutputLayer`] — C++ [`nvinfer1::IIfConditionalOutputLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_if_conditional_output_layer.html).
pub type IfConditionalOutputLayer<'layer> = Layer<'layer, nvinfer1::IIfConditionalOutputLayer>;
/// [`trtx_sys::nvinfer1::IIfConditionalInputLayer`] — C++ [`nvinfer1::IIfConditionalInputLayer`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_if_conditional_input_layer.html).
pub type IfConditionalInputLayer<'layer> = Layer<'layer, nvinfer1::IIfConditionalInputLayer>;

pub type DynLayer<'layer> = Layer<'layer, nvinfer1::ILayer>;

/// Attention block (query, key, value → output). Created by [`NetworkDefinition::add_attention`].
/// Input/output layers are managed internally by TensorRT.
pub struct Attention<'network> {
    pub(crate) inner: Pin<&'network mut nvinfer1::IAttention>,
    pub(crate) network: *const nvinfer1::INetworkDefinition,
}

impl std::fmt::Debug for Attention<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Attention")
            .field("inner", &format!("{:x}", &*self.inner as *const _ as usize))
            .finish_non_exhaustive()
    }
}

/// Loop construct for recurrent subgraphs. Created by [`NetworkDefinition::add_loop`].
pub struct Loop<'network> {
    pub(crate) inner: Pin<&'network mut nvinfer1::ILoop>,
    pub(crate) network: *const nvinfer1::INetworkDefinition,
}

impl std::fmt::Debug for Loop<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Loop")
            .field("inner", &format!("{:x}", &*self.inner as *const _ as usize))
            .finish_non_exhaustive()
    }
}

/// If-conditional construct. Created by [`NetworkDefinition::add_if_conditional`].
pub struct IfConditional<'network> {
    pub(crate) inner: Pin<&'network mut nvinfer1::IIfConditional>,
    pub(crate) network: *const nvinfer1::INetworkDefinition,
}

impl std::fmt::Debug for IfConditional<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IfConditional")
            .field("inner", &format!("{:x}", &*self.inner as *const _ as usize))
            .finish_non_exhaustive()
    }
}
impl ShuffleLayer<'_> {
    /// See [nvinfer1::IShuffleLayer::setReshapeDimensions]
    pub fn set_reshape_dimensions(
        &mut self,
        network: &mut NetworkDefinition,
        dims: &[i64],
    ) -> Result<()> {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(dims);
        self.inner.as_mut().setReshapeDimensions(&dims_obj);
        Ok(())
    }

    /// See [nvinfer1::IShuffleLayer::setFirstTranspose]
    pub fn set_first_transpose(
        &mut self,
        network: &mut NetworkDefinition,
        order: &[i32],
    ) -> Result<()> {
        check_network!(network, self);
        let mut order_arr = [0i32; 8];
        let n = order.len().min(8);
        order_arr[..n].copy_from_slice(&order[..n]);
        let perm = trtx_sys::nvinfer1::Permutation { order: order_arr };
        self.inner.as_mut().setFirstTranspose(perm);
        Ok(())
    }

    /// See [nvinfer1::IShuffleLayer::setSecondTranspose]
    pub fn set_second_transpose(
        &mut self,
        network: &mut NetworkDefinition,
        order: &[i32],
    ) -> Result<()> {
        check_network!(network, self);
        let mut order_arr = [0i32; 8];
        let n = order.len().min(8);
        order_arr[..n].copy_from_slice(&order[..n]);
        let perm = trtx_sys::nvinfer1::Permutation { order: order_arr };
        self.inner.as_mut().setSecondTranspose(perm);
        Ok(())
    }
}

impl ResizeLayer<'_> {
    // --- IResizeLayer (full) ---
    // `setInput` / `getInput` / `getOutput` / `getNbInputs` / `getNbOutputs` / name accessors:
    // [`Layer::set_input`], [`Layer::get_input`], [`Layer::get_output`], etc.

    /// See [nvinfer1::IResizeLayer::setOutputDimensions]
    pub fn set_output_dimensions(&mut self, network: &mut NetworkDefinition, dims: &[i64]) {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(dims);
        self.inner.as_mut().setOutputDimensions(&dims_obj);
    }

    /// See [nvinfer1::IResizeLayer::getOutputDimensions]
    pub fn output_dimensions(&self, network: &NetworkDefinition) -> Vec<i64> {
        check_network!(network, self);
        let d = self.inner.as_ref().getOutputDimensions();
        d.d[..d.nbDims as usize].to_vec()
    }

    /// See [nvinfer1::IResizeLayer::setScales]
    pub fn set_scales(&mut self, network: &mut NetworkDefinition, scales: &[f32]) {
        check_network!(network, self);
        // SAFETY: `scales.as_ptr()` is valid for `scales.len()` elements. TensorRT copies scale values
        // into the layer definition during this call (same contract as other INetworkDefinition setters).
        unsafe {
            self.inner
                .as_mut()
                .setScales(scales.as_ptr(), scales.len() as i32);
        }
    }

    /// See [nvinfer1::IResizeLayer::getScales]
    ///
    /// Returns `None` if no scales were set or the resize layer is dynamic (per TensorRT).
    pub fn scales(&self, network: &NetworkDefinition) -> Option<Vec<f32>> {
        check_network!(network, self);
        // SAFETY: TensorRT API allows `size == 0` and `scales == nullptr` to return the scale count only.
        let n = unsafe { self.inner.as_ref().getScales(0, std::ptr::null_mut()) };
        if n <= 0 {
            return None;
        }
        let mut buf = vec![0.0_f32; n as usize];
        // SAFETY: `buf` has length `n` (from `getScales` above); pointer is valid for `n` writes.
        let n2 = unsafe { self.inner.as_ref().getScales(n, buf.as_mut_ptr()) };
        if n2 != n {
            return None;
        }
        Some(buf)
    }

    /// See [nvinfer1::IResizeLayer::setResizeMode]
    pub fn set_resize_mode(&mut self, network: &mut NetworkDefinition, mode: trtx_sys::ResizeMode) {
        check_network!(network, self);
        self.inner.as_mut().setResizeMode(mode.into());
    }

    /// See [nvinfer1::IResizeLayer::getResizeMode]
    pub fn resize_mode(&self, network: &NetworkDefinition) -> trtx_sys::ResizeMode {
        check_network!(network, self);
        self.inner.as_ref().getResizeMode().into()
    }

    /// See [nvinfer1::IResizeLayer::setCoordinateTransformation]
    pub fn set_coordinate_transformation(
        &mut self,
        network: &mut NetworkDefinition,
        transform: trtx_sys::ResizeCoordinateTransformation,
    ) {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setCoordinateTransformation(transform.into());
    }

    /// See [nvinfer1::IResizeLayer::getCoordinateTransformation]
    pub fn coordinate_transformation(
        &self,
        network: &NetworkDefinition,
    ) -> trtx_sys::ResizeCoordinateTransformation {
        check_network!(network, self);
        self.inner.as_ref().getCoordinateTransformation().into()
    }

    /// See [nvinfer1::IResizeLayer::setSelectorForSinglePixel]
    pub fn set_selector_for_single_pixel(
        &mut self,
        network: &mut NetworkDefinition,
        selector: trtx_sys::ResizeSelector,
    ) {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setSelectorForSinglePixel(selector.into());
    }

    /// See [nvinfer1::IResizeLayer::getSelectorForSinglePixel]
    pub fn selector_for_single_pixel(
        &self,
        network: &NetworkDefinition,
    ) -> trtx_sys::ResizeSelector {
        check_network!(network, self);
        self.inner.as_ref().getSelectorForSinglePixel().into()
    }

    /// See [nvinfer1::IResizeLayer::setNearestRounding]
    pub fn set_nearest_rounding(
        &mut self,
        network: &mut NetworkDefinition,
        mode: trtx_sys::ResizeRoundMode,
    ) {
        check_network!(network, self);
        self.inner.as_mut().setNearestRounding(mode.into());
    }

    /// See [nvinfer1::IResizeLayer::getNearestRounding]
    pub fn nearest_rounding(&self, network: &NetworkDefinition) -> trtx_sys::ResizeRoundMode {
        check_network!(network, self);
        self.inner.as_ref().getNearestRounding().into()
    }

    /// See [nvinfer1::IResizeLayer::setCubicCoeff]
    pub fn set_cubic_coeff(&mut self, network: &mut NetworkDefinition, a: f32) {
        check_network!(network, self);
        self.inner.as_mut().setCubicCoeff(a);
    }

    /// See [nvinfer1::IResizeLayer::getCubicCoeff]
    pub fn cubic_coeff(&self, network: &NetworkDefinition) -> f32 {
        check_network!(network, self);
        self.inner.as_ref().getCubicCoeff()
    }

    /// See [nvinfer1::IResizeLayer::setExcludeOutside]
    pub fn set_exclude_outside(&mut self, network: &mut NetworkDefinition, exclude: bool) {
        check_network!(network, self);
        self.inner.as_mut().setExcludeOutside(exclude);
    }

    /// See [nvinfer1::IResizeLayer::getExcludeOutside]
    pub fn exclude_outside(&self, network: &NetworkDefinition) -> bool {
        check_network!(network, self);
        self.inner.as_ref().getExcludeOutside()
    }
}

impl GatherLayer<'_> {
    /// See [nvinfer1::IGatherLayer::setMode]
    pub fn set_gather_mode(&mut self, network: &mut NetworkDefinition, mode: trtx_sys::GatherMode) {
        check_network!(network, self);
        self.inner.as_mut().setMode(mode.into());
    }
}

impl<'network> ScatterLayer<'network> {
    /// See [nvinfer1::IScatterLayer::setMode]
    pub fn set_scatter_mode(
        &mut self,
        network: &mut NetworkDefinition,
        mode: trtx_sys::ScatterMode,
    ) {
        check_network!(network, self);
        self.inner.as_mut().setMode(mode.into());
    }
    /// See [nvinfer1::IScatterLayer::setAxis]
    pub fn set_axis(&mut self, network: &'_ mut NetworkDefinition, axis: i32) {
        check_network!(network, self);
        self.inner.as_mut().setAxis(axis);
    }
}

impl<'network> ConvolutionLayer<'network> {
    /// See [nvinfer1::IConvolutionLayer::setStrideNd]
    pub fn set_stride(&mut self, network: &mut NetworkDefinition, stride: &[i64; 2]) {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(stride);
        self.inner.as_mut().setStrideNd(&dims_obj);
    }
    /// See [nvinfer1::IConvolutionLayer::setPaddingNd]
    pub fn set_padding(&mut self, network: &mut NetworkDefinition, padding: &[i64; 2]) {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(padding);
        self.inner.as_mut().setPaddingNd(&dims_obj);
    }
    /// See [nvinfer1::IConvolutionLayer::setDilationNd]
    pub fn set_dilation(&mut self, network: &mut NetworkDefinition, dilation: &[i64; 2]) {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(dilation);
        self.inner.as_mut().setDilationNd(&dims_obj);
    }
    /// See [nvinfer1::IConvolutionLayer::setNbGroups]
    pub fn set_num_groups(&mut self, network: &mut NetworkDefinition, num_groups: i64) {
        check_network!(network, self);
        self.inner.as_mut().setNbGroups(num_groups);
    }
}

impl<'network> DeconvolutionLayer<'network> {
    /// See [nvinfer1::IDeconvolutionLayer::setStrideNd]
    pub fn set_stride(&mut self, network: &mut NetworkDefinition, stride: &[i64; 2]) -> Result<()> {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(stride);
        self.inner.as_mut().setStrideNd(&dims_obj);
        Ok(())
    }

    /// Set pre-padding (trim this many elements at the start of each spatial dimension of the output).
    /// Pass [pre_h, pre_w] for 2D deconv; TensorRT applies to the spatial dimensions only.
    ///
    /// See [nvinfer1::IDeconvolutionLayer::setPrePadding]
    pub fn set_pre_padding(
        &mut self,
        network: &mut NetworkDefinition,
        padding: &[i64; 2],
    ) -> Result<()> {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(padding);
        self.inner.as_mut().setPrePadding(&dims_obj);
        Ok(())
    }
    /// Set post-padding (trim this many elements at the end of each spatial dimension of the output).
    /// Pass [post_h, post_w] for 2D deconv; TensorRT applies to the spatial dimensions only.
    ///
    /// See [nvinfer1::IDeconvolutionLayer::setPostPadding]
    pub fn set_post_padding(
        &mut self,
        network: &mut NetworkDefinition,
        padding: &[i64; 2],
    ) -> Result<()> {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(padding);
        self.inner.as_mut().setPostPadding(&dims_obj);
        Ok(())
    }

    /// See [nvinfer1::IDeconvolutionLayer::setDilationNd]
    pub fn set_dilation(
        &mut self,
        network: &mut NetworkDefinition,
        dilation: &[i64; 2],
    ) -> Result<()> {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(dilation);
        self.inner.as_mut().setDilationNd(&dims_obj);
        Ok(())
    }

    /// See [nvinfer1::IDeconvolutionLayer::setNbGroups]
    pub fn set_num_groups(
        &mut self,
        network: &mut NetworkDefinition,
        num_groups: i64,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner.as_mut().setNbGroups(num_groups);
        Ok(())
    }
}

impl<'network> PoolingLayer<'network> {
    /// See [nvinfer1::IPoolingLayer::setPoolingType]
    pub fn set_pooling_type(
        &mut self,
        network: &mut NetworkDefinition,
        pooling_type: trtx_sys::PoolingType,
    ) {
        check_network!(network, self);
        self.inner.as_mut().setPoolingType(pooling_type.into());
    }

    /// See [nvinfer1::IPoolingLayer::getPoolingType]
    pub fn pooling_type(&self, network: &NetworkDefinition) -> trtx_sys::PoolingType {
        check_network!(network, self);
        self.inner.as_ref().getPoolingType().into()
    }

    /// See [nvinfer1::IPoolingLayer::setBlendFactor]
    pub fn set_blend_factor(&mut self, network: &mut NetworkDefinition, blend_factor: f32) {
        check_network!(network, self);
        self.inner.as_mut().setBlendFactor(blend_factor);
    }

    /// See [nvinfer1::IPoolingLayer::getBlendFactor]
    pub fn blend_factor(&self, network: &NetworkDefinition) -> f32 {
        check_network!(network, self);
        self.inner.as_ref().getBlendFactor()
    }

    /// See [nvinfer1::IPoolingLayer::setAverageCountExcludesPadding]
    pub fn set_average_count_excludes_padding(
        &mut self,
        network: &mut NetworkDefinition,
        exclusive: bool,
    ) {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setAverageCountExcludesPadding(exclusive);
    }

    /// See [nvinfer1::IPoolingLayer::getAverageCountExcludesPadding]
    pub fn average_count_excludes_padding(&self, network: &NetworkDefinition) -> bool {
        check_network!(network, self);
        self.inner.as_ref().getAverageCountExcludesPadding()
    }

    /// See [nvinfer1::IPoolingLayer::setPrePadding]
    pub fn set_pre_padding(&mut self, network: &mut NetworkDefinition, padding: &[i64]) {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(padding);
        self.inner.as_mut().setPrePadding(&dims_obj);
    }

    /// See [nvinfer1::IPoolingLayer::getPrePadding]
    pub fn pre_padding(&self, network: &NetworkDefinition) -> Vec<i64> {
        check_network!(network, self);
        let d = self.inner.as_ref().getPrePadding();
        d.d[..d.nbDims as usize].to_vec()
    }

    /// See [nvinfer1::IPoolingLayer::setPostPadding]
    pub fn set_post_padding(&mut self, network: &mut NetworkDefinition, padding: &[i64]) {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(padding);
        self.inner.as_mut().setPostPadding(&dims_obj);
    }

    /// See [nvinfer1::IPoolingLayer::getPostPadding]
    pub fn post_padding(&self, network: &NetworkDefinition) -> Vec<i64> {
        check_network!(network, self);
        let d = self.inner.as_ref().getPostPadding();
        d.d[..d.nbDims as usize].to_vec()
    }

    /// See [nvinfer1::IPoolingLayer::setPaddingMode]
    pub fn set_padding_mode(
        &mut self,
        network: &mut NetworkDefinition,
        padding_mode: trtx_sys::PaddingMode,
    ) {
        check_network!(network, self);
        self.inner.as_mut().setPaddingMode(padding_mode.into());
    }

    /// See [nvinfer1::IPoolingLayer::getPaddingMode]
    pub fn padding_mode(&self, network: &NetworkDefinition) -> trtx_sys::PaddingMode {
        check_network!(network, self);
        self.inner.as_ref().getPaddingMode().into()
    }

    /// See [nvinfer1::IPoolingLayer::setWindowSizeNd]
    pub fn set_window_size_nd(&mut self, network: &mut NetworkDefinition, window_size: &[i64]) {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(window_size);
        self.inner.as_mut().setWindowSizeNd(&dims_obj);
    }

    /// See [nvinfer1::IPoolingLayer::getWindowSizeNd]
    pub fn window_size_nd(&self, network: &NetworkDefinition) -> Vec<i64> {
        check_network!(network, self);
        let d = self.inner.as_ref().getWindowSizeNd();
        d.d[..d.nbDims as usize].to_vec()
    }

    /// See [nvinfer1::IPoolingLayer::setStrideNd]
    pub fn set_stride_nd(&mut self, network: &mut NetworkDefinition, stride: &[i64]) {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(stride);
        self.inner.as_mut().setStrideNd(&dims_obj);
    }

    /// See [nvinfer1::IPoolingLayer::getStrideNd]
    pub fn stride_nd(&self, network: &NetworkDefinition) -> Vec<i64> {
        check_network!(network, self);
        let d = self.inner.as_ref().getStrideNd();
        d.d[..d.nbDims as usize].to_vec()
    }

    /// See [nvinfer1::IPoolingLayer::setPaddingNd]
    pub fn set_padding_nd(&mut self, network: &mut NetworkDefinition, padding: &[i64]) {
        check_network!(network, self);
        let dims_obj = trtx_sys::Dims::from_slice(padding);
        self.inner.as_mut().setPaddingNd(&dims_obj);
    }

    /// See [nvinfer1::IPoolingLayer::getPaddingNd]
    pub fn padding_nd(&self, network: &NetworkDefinition) -> Vec<i64> {
        check_network!(network, self);
        let d = self.inner.as_ref().getPaddingNd();
        d.d[..d.nbDims as usize].to_vec()
    }
}

impl<'network> DynamicQuantizeLayer<'network> {
    /// See [nvinfer1::IDynamicQuantizeLayer::setAxis]
    pub fn set_axis(&mut self, network: &mut NetworkDefinition, axis: i32) {
        check_network!(network, self);
        self.inner.as_mut().setAxis(axis);
    }

    /// See [nvinfer1::IDynamicQuantizeLayer::getAxis]
    pub fn axis(&self, network: &NetworkDefinition) -> i32 {
        check_network!(network, self);
        self.inner.getAxis()
    }

    /// See [nvinfer1::IDynamicQuantizeLayer::setBlockShape]
    pub fn set_block_shape(&mut self, network: &mut NetworkDefinition, block_shape: &[i64]) {
        check_network!(network, self);
        let dims = Dims64::from_slice(block_shape);
        self.inner.as_mut().setBlockShape(&dims);
    }

    /// See [nvinfer1::IDynamicQuantizeLayer::getBlockShape]
    pub fn block_shape(&self, network: &NetworkDefinition) -> Dims64 {
        check_network!(network, self);
        self.inner.getBlockShape()
    }

    /// See [nvinfer1::IDynamicQuantizeLayer::setBlockSize]
    pub fn set_block_size(&mut self, network: &mut NetworkDefinition, size: i32) {
        check_network!(network, self);
        self.inner.as_mut().setBlockSize(size);
    }

    /// See [nvinfer1::IDynamicQuantizeLayer::getBlockSize]
    pub fn block_size(&self, network: &NetworkDefinition) -> i32 {
        check_network!(network, self);
        self.inner.getBlockSize()
    }

    /// See [nvinfer1::IDynamicQuantizeLayer::setToType]
    pub fn set_to_type(&mut self, network: &mut NetworkDefinition, to_type: DataType) {
        check_network!(network, self);
        self.inner.as_mut().setToType(to_type.into());
    }

    /// See [nvinfer1::IDynamicQuantizeLayer::getToType]
    pub fn to_type(&self, network: &NetworkDefinition) -> DataType {
        check_network!(network, self);
        self.inner.getToType().into()
    }

    /// See [nvinfer1::IDynamicQuantizeLayer::setScaleType]
    pub fn set_scale_type(&mut self, network: &mut NetworkDefinition, scale_type: DataType) {
        check_network!(network, self);
        self.inner.as_mut().setScaleType(scale_type.into());
    }

    /// See [nvinfer1::IDynamicQuantizeLayer::getScaleType]
    pub fn scale_type(&self, network: &NetworkDefinition) -> DataType {
        check_network!(network, self);
        self.inner.getScaleType().into()
    }
}

impl<'network> QuantizeLayer<'network> {
    /// See [nvinfer1::IQuantizeLayer::setAxis]
    pub fn set_axis(&mut self, network: &mut NetworkDefinition, axis: i32) {
        check_network!(network, self);
        self.inner.as_mut().setAxis(axis);
    }

    /// See [nvinfer1::IQuantizeLayer::getAxis]
    pub fn axis(&self, network: &NetworkDefinition) -> i32 {
        check_network!(network, self);
        self.inner.getAxis()
    }

    /// See [nvinfer1::IQuantizeLayer::setBlockShape]
    pub fn set_block_shape(
        &mut self,
        network: &mut NetworkDefinition,
        block_shape: &[i64],
    ) -> Result<()> {
        check_network!(network, self);
        let dims = Dims64::from_slice(block_shape);
        self.inner
            .as_mut()
            .setBlockShape(&dims)
            .ok_or_err(PropertySetAttempt::QuantizeLayerBlockShape)
    }

    /// See [nvinfer1::IQuantizeLayer::getBlockShape]
    pub fn block_shape(&self, network: &NetworkDefinition) -> Dims64 {
        check_network!(network, self);
        self.inner.getBlockShape()
    }

    /// See [nvinfer1::IQuantizeLayer::setToType]
    pub fn set_to_type(&mut self, network: &mut NetworkDefinition, to_type: DataType) {
        check_network!(network, self);
        self.inner.as_mut().setToType(to_type.into());
    }

    /// See [nvinfer1::IQuantizeLayer::getToType]
    pub fn to_type(&self, network: &NetworkDefinition) -> DataType {
        check_network!(network, self);
        self.inner.getToType().into()
    }
}

impl<'network> DequantizeLayer<'network> {
    /// See [nvinfer1::IDequantizeLayer::setAxis]
    pub fn set_axis(&mut self, network: &mut NetworkDefinition, axis: i32) {
        check_network!(network, self);
        self.inner.as_mut().setAxis(axis);
    }

    /// See [nvinfer1::IDequantizeLayer::getAxis]
    pub fn axis(&self, network: &NetworkDefinition) -> i32 {
        check_network!(network, self);
        self.inner.getAxis()
    }

    /// See [nvinfer1::IDequantizeLayer::setBlockShape]
    pub fn set_block_shape(
        &mut self,
        network: &mut NetworkDefinition,
        block_shape: &[i64],
    ) -> Result<()> {
        check_network!(network, self);
        let dims = Dims64::from_slice(block_shape);
        self.inner
            .as_mut()
            .setBlockShape(&dims)
            .ok_or_err(PropertySetAttempt::DequantizeLayerBlockShape)
    }

    /// See [nvinfer1::IDequantizeLayer::getBlockShape]
    pub fn block_shape(&self, network: &NetworkDefinition) -> Dims64 {
        check_network!(network, self);
        self.inner.getBlockShape()
    }

    /// See [nvinfer1::IDequantizeLayer::setToType]
    pub fn set_to_type(&mut self, network: &mut NetworkDefinition, to_type: DataType) {
        check_network!(network, self);
        self.inner.as_mut().setToType(to_type.into());
    }

    /// See [nvinfer1::IDequantizeLayer::getToType]
    pub fn to_type(&self, network: &NetworkDefinition) -> DataType {
        check_network!(network, self);
        self.inner.getToType().into()
    }
}

impl ConcatenationLayer<'_> {
    /// See [nvinfer1::IConcatenationLayer::setAxis]
    pub fn set_axis(&mut self, network: &mut NetworkDefinition, axis: i32) {
        check_network!(network, self);
        self.inner.as_mut().setAxis(axis);
    }
}

impl RotaryEmbeddingLayer<'_> {
    /// See [`trtx_sys::nvinfer1::IRotaryEmbeddingLayer::setInterleaved`].
    pub fn set_interleaved(&mut self, network: &mut NetworkDefinition, interleaved: bool) {
        check_network!(network, self);
        self.inner.as_mut().setInterleaved(interleaved);
    }

    /// See [`trtx_sys::nvinfer1::IRotaryEmbeddingLayer::getInterleaved`].
    pub fn interleaved(&self, network: &NetworkDefinition) -> bool {
        check_network!(network, self);
        self.inner.as_ref().getInterleaved()
    }

    /// See [`trtx_sys::nvinfer1::IRotaryEmbeddingLayer::setRotaryEmbeddingDim`].
    pub fn set_rotary_embedding_dim(
        &mut self,
        network: &mut NetworkDefinition,
        rotary_embedding_dim: i32,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setRotaryEmbeddingDim(rotary_embedding_dim)
            .ok_or_err(PropertySetAttempt::RotaryEmbeddingLayerRotaryEmbeddingDim)
    }

    /// See [`trtx_sys::nvinfer1::IRotaryEmbeddingLayer::getRotaryEmbeddingDim`].
    pub fn rotary_embedding_dim(&self, network: &NetworkDefinition) -> i32 {
        check_network!(network, self);
        self.inner.as_ref().getRotaryEmbeddingDim()
    }
}

impl NormalizationLayer<'_> {
    /// See [nvinfer1::INormalizationLayer::setEpsilon]
    pub fn set_epsilon(&mut self, network: &mut NetworkDefinition, eps: f32) {
        check_network!(network, self);
        self.inner.as_mut().setEpsilon(eps);
    }
    /// See [nvinfer1::INormalizationLayer::getEpsilon]
    pub fn epsilon(&self, network: &NetworkDefinition) -> f32 {
        check_network!(network, self);
        self.inner.as_ref().getEpsilon()
    }

    #[deprecated = "use epsilon instead"]
    pub fn get_epsilon(&self, network: &NetworkDefinition) -> f32 {
        self.epsilon(network)
    }
    /// See [nvinfer1::INormalizationLayer::setAxes]
    pub fn set_axes(&mut self, network: &mut NetworkDefinition, axes: crate::Axes) {
        check_network!(network, self);
        self.inner.as_mut().setAxes(axes.to_bits());
    }
    /// See [nvinfer1::INormalizationLayer::getAxes]
    pub fn axes(&self, network: &NetworkDefinition) -> crate::Axes {
        check_network!(network, self);
        crate::Axes::from_bits(self.inner.as_ref().getAxes())
    }

    #[deprecated = "use axes instead"]
    pub fn get_axes(&self, network: &NetworkDefinition) -> crate::Axes {
        self.axes(network)
    }
    /// See [nvinfer1::INormalizationLayer::setNbGroups]
    pub fn set_num_groups(&mut self, network: &mut NetworkDefinition, groups: i64) {
        check_network!(network, self);
        self.inner.as_mut().setNbGroups(groups);
    }
    /// See [nvinfer1::INormalizationLayer::getNbGroups]
    pub fn num_groups(&self, network: &NetworkDefinition) -> i64 {
        check_network!(network, self);
        self.inner.as_ref().getNbGroups()
    }

    #[deprecated = "use num_groups instead"]
    pub fn get_num_groups(&self, network: &NetworkDefinition) -> i64 {
        self.num_groups(network)
    }

    // is removed because deprecated in TRT
    //pub fn set_compute_precision(&mut self, network: &mut NetworkDefinition, data_type: DataType) {
    //pub fn get_compute_precision(&self, network: &NetworkDefinition) -> DataType {

    pub fn is_v2(&self, network: &NetworkDefinition) -> bool {
        check_network!(network, self);
        self.inner.as_ref().isV2()
    }
}

#[cfg(feature = "v_1_4")]
impl MoELayer<'_> {
    /// See [`trtx_sys::nvinfer1::IMoELayer::setGatedWeights`].
    pub fn set_gated_weights(
        &mut self,
        network: &mut NetworkDefinition,
        fc_gate_weights: &Tensor,
        fc_up_weights: &Tensor,
        fc_down_weights: &Tensor,
        activation_type: MoEActType,
    ) -> Result<()> {
        check_network!(network, self);
        check_network!(network, fc_gate_weights);
        check_network!(network, fc_up_weights);
        check_network!(network, fc_down_weights);
        self.inner.as_mut().setGatedWeights(
            fc_gate_weights.pin_mut(),
            fc_up_weights.pin_mut(),
            fc_down_weights.pin_mut(),
            activation_type.into(),
        );
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::setGatedBiases`].
    pub fn set_gated_biases(
        &mut self,
        network: &mut NetworkDefinition,
        fc_gate_biases: &Tensor,
        fc_up_biases: &Tensor,
        fc_down_biases: &Tensor,
    ) -> Result<()> {
        check_network!(network, self);
        check_network!(network, fc_gate_biases);
        check_network!(network, fc_up_biases);
        check_network!(network, fc_down_biases);
        self.inner.as_mut().setGatedBiases(
            fc_gate_biases.pin_mut(),
            fc_up_biases.pin_mut(),
            fc_down_biases.pin_mut(),
        );
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::setActivationType`].
    pub fn set_activation_type(
        &mut self,
        network: &mut NetworkDefinition,
        activation_type: MoEActType,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setActivationType(activation_type.into());
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::getActivationType`].
    pub fn activation_type(&self, network: &NetworkDefinition) -> MoEActType {
        check_network!(network, self);
        self.inner.as_ref().getActivationType().into()
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::setQuantizationStatic`].
    pub fn set_quantization_static(
        &mut self,
        network: &mut NetworkDefinition,
        fc_down_activation_scale: &Tensor,
        data_type: DataType,
    ) -> Result<()> {
        check_network!(network, self);
        check_network!(network, fc_down_activation_scale);
        self.inner
            .as_mut()
            .setQuantizationStatic(fc_down_activation_scale.pin_mut(), data_type.into());
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::setQuantizationDynamicDblQ`].
    pub fn set_quantization_dynamic_dbl_q(
        &mut self,
        network: &mut NetworkDefinition,
        fc_down_activation_dbl_q_scale: &Tensor,
        data_type: DataType,
        block_shape: &[i64],
        dyn_q_output_scale_type: DataType,
    ) -> Result<()> {
        check_network!(network, self);
        check_network!(network, fc_down_activation_dbl_q_scale);
        let block = trtx_sys::Dims::from_slice(block_shape);
        self.inner.as_mut().setQuantizationDynamicDblQ(
            fc_down_activation_dbl_q_scale.pin_mut(),
            data_type.into(),
            &block,
            dyn_q_output_scale_type.into(),
        );
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::setQuantizationToType`].
    pub fn set_quantization_to_type(
        &mut self,
        network: &mut NetworkDefinition,
        type_: DataType,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner.as_mut().setQuantizationToType(type_.into());
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::getQuantizationToType`].
    pub fn quantization_to_type(&self, network: &NetworkDefinition) -> DataType {
        check_network!(network, self);
        self.inner.as_ref().getQuantizationToType().into()
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::setQuantizationBlockShape`].
    pub fn set_quantization_block_shape(
        &mut self,
        network: &mut NetworkDefinition,
        block_shape: &[i64],
    ) -> Result<()> {
        check_network!(network, self);
        let block = trtx_sys::Dims::from_slice(block_shape);
        self.inner.as_mut().setQuantizationBlockShape(&block);
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::getQuantizationBlockShape`].
    pub fn quantization_block_shape(&self, network: &NetworkDefinition) -> Vec<i64> {
        check_network!(network, self);
        let d = self.inner.as_ref().getQuantizationBlockShape();
        d.d[..d.nbDims as usize].to_vec()
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::setDynQOutputScaleType`].
    pub fn set_dyn_q_output_scale_type(
        &mut self,
        network: &mut NetworkDefinition,
        type_: DataType,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner.as_mut().setDynQOutputScaleType(type_.into());
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::getDynQOutputScaleType`].
    pub fn dyn_q_output_scale_type(&self, network: &NetworkDefinition) -> DataType {
        check_network!(network, self);
        self.inner.as_ref().getDynQOutputScaleType().into()
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::setSwigluParams`].
    pub fn set_swiglu_params(
        &mut self,
        network: &mut NetworkDefinition,
        limit: f32,
        alpha: f32,
        beta: f32,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner.as_mut().setSwigluParams(limit, alpha, beta);
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::setSwigluParamLimit`].
    pub fn set_swiglu_param_limit(
        &mut self,
        network: &mut NetworkDefinition,
        limit: f32,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner.as_mut().setSwigluParamLimit(limit);
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::getSwigluParamLimit`].
    pub fn swiglu_param_limit(&self, network: &NetworkDefinition) -> f32 {
        check_network!(network, self);
        self.inner.as_ref().getSwigluParamLimit()
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::setSwigluParamAlpha`].
    pub fn set_swiglu_param_alpha(
        &mut self,
        network: &mut NetworkDefinition,
        alpha: f32,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner.as_mut().setSwigluParamAlpha(alpha);
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::getSwigluParamAlpha`].
    pub fn swiglu_param_alpha(&self, network: &NetworkDefinition) -> f32 {
        check_network!(network, self);
        self.inner.as_ref().getSwigluParamAlpha()
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::setSwigluParamBeta`].
    pub fn set_swiglu_param_beta(
        &mut self,
        network: &mut NetworkDefinition,
        beta: f32,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner.as_mut().setSwigluParamBeta(beta);
        Ok(())
    }

    /// See [`trtx_sys::nvinfer1::IMoELayer::getSwigluParamBeta`].
    pub fn swiglu_param_beta(&self, network: &NetworkDefinition) -> f32 {
        check_network!(network, self);
        self.inner.as_ref().getSwigluParamBeta()
    }
}

#[cfg(feature = "v_1_4")]
/// `IDistCollectiveLayer` adds no methods beyond [`ILayer`](trtx_sys::nvinfer1::ILayer); use [`Layer`] helpers.
impl DistCollectiveLayer<'_> {}

/// [`trtx_sys::nvinfer1::INetworkDefinition`] — C++ [`nvinfer1::INetworkDefinition`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_network_definition.html).
pub struct NetworkDefinition<'builder> {
    //pub(crate) inner: Mutex<Pin<&'builder mut INetworkDefinition>>,
    pub(crate) inner: UniquePtr<INetworkDefinition>,
    //error_recorder: Option<Rc<RefCell<ErrorRecorder>>>,
    _builder: PhantomData<&'builder trtx_sys::nvinfer1::IBuilder>,
    small_copied_weights: Vec<Vec<u8>>, // for convenience we hold pointers to scalars here
    error_recorder: Option<Pin<Box<ErrorRecorder>>>,
}

impl std::fmt::Debug for NetworkDefinition<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NetworkDefinition")
            .field("inner", &format!("{:x}", self.inner.as_ptr() as usize))
            .finish_non_exhaustive()
    }
}

fn tensor_dbg(network: &NetworkDefinition<'_>, tensor: &Tensor<'_>) -> String {
    tensor
        .name(network)
        .unwrap_or_else(|_| "(unnamed)".to_string())
}
fn layer_dbg<Inner: AsLayer>(network: &NetworkDefinition<'_>, layer: &Layer<'_, Inner>) -> String {
    layer.name(network)
}

impl<'network> NetworkDefinition<'network> {
    pub(crate) fn from_ptr(ptr: *mut INetworkDefinition) -> Self {
        Self {
            inner: unsafe { UniquePtr::from_raw(ptr) },
            error_recorder: None,
            _builder: Default::default(),
            small_copied_weights: Default::default(),
        }
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addInput`].
    pub fn add_input(
        &mut self,
        name: &str,
        data_type: trtx_sys::DataType,
        dims: &[i64],
    ) -> Result<Tensor<'network>> {
        debug!("add_input name={name:?} data_type={data_type:?} dims={dims:?}");
        let name_cstr = std::ffi::CString::new(name)?;
        let dims_struct = trtx_sys::Dims::from_slice(dims);
        let tensor_ptr = unsafe {
            self.inner
                .pin_mut()
                .addInput(name_cstr.as_ptr(), data_type.into(), &dims_struct)
        };
        unsafe { Tensor::new(self.inner.as_ptr(), tensor_ptr) }
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::markOutput`].
    pub fn mark_output(&mut self, tensor: &'_ Tensor) {
        check_network!(self, tensor);
        debug!("mark_input tensor={}", tensor_dbg(self, tensor));
        self.inner.pin_mut().markOutput(tensor.pin_mut());
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::markDebug`].
    /// Mark a tensor for debugging; at runtime use [`crate::ExecutionContext`] ([`trtx_sys::nvinfer1::IExecutionContext`]) — C++ [`setDebugListener`](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_execution_context.html).
    pub fn mark_tensor_debug(&mut self, tensor: &'_ Tensor) -> Result<()> {
        check_network!(self, tensor);
        let success = self.inner.pin_mut().markDebug(tensor.pin_mut());
        if success {
            Ok(())
        } else {
            Err(Error::Runtime("markDebug failed".to_string()))
        }
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::markWeightsRefittable`].
    pub fn mark_weights_refittable(&mut self, name: &str) -> Result<()> {
        debug!("mark_weights_refittable: {name:?}");
        let name_cstr = std::ffi::CString::new(name)?;
        unsafe {
            self.inner
                .pin_mut()
                .markWeightsRefittable(name_cstr.as_ptr())
                .ok_or_else_err(|| Error::FailedToMarkWeightsRefittable {
                    weight_name: name.to_string(),
                })
        }
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::unmarkWeightsRefittable`].
    pub fn unmark_weights_refittable(&mut self, name: &str) -> Result<()> {
        debug!("unmark_weights_refittable: {name:?}");
        let name_cstr = std::ffi::CString::new(name)?;
        unsafe {
            self.inner
                .pin_mut()
                .unmarkWeightsRefittable(name_cstr.as_ptr())
                .ok_or_else_err(|| Error::FailedToUnmarkWeightsRefittable {
                    weight_name: name.to_string(),
                })
        }
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::areWeightsMarkedRefittable`].
    pub fn are_weights_marked_refittable(&self, name: &str) -> Result<bool> {
        let name_cstr = std::ffi::CString::new(name)?;
        unsafe { Ok(self.inner.areWeightsMarkedRefittable(name_cstr.as_ptr())) }
    }

    /// See [nvinfer1::INetworkDefinition::setWeightsName]
    ///
    /// Used by internal methods
    ///
    /// # Safety
    ///
    /// Weights needs to be in a valid state, and Weights must be valid until the engine build is finished
    unsafe fn set_weights_name(&mut self, weights: nvinfer1::Weights, name: &str) -> Result<()> {
        let cname = CString::new(name)?;
        self.inner
            .pin_mut()
            .setWeightsName(weights, cname.as_ptr())
            .ok_or_else_err(|| Error::FailedToSetWeightsName {
                weight_name: name.to_string(),
            })
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::isDebugTensor`].
    /// See [`trtx_sys::nvinfer1::IExecutionContext`] debug APIs (C++ [docs](https://docs.nvidia.com/deeplearning/tensorrt-rtx/latest/_static/cpp-api/classnvinfer1_1_1_i_execution_context.html)).
    pub fn is_debug_tensor(&self, tensor: &'_ Tensor) -> bool {
        check_network!(self, tensor);
        self.inner.isDebugTensor(tensor.as_ref())
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::getNbInputs`].
    pub fn nb_inputs(&self) -> i32 {
        self.inner.getNbInputs()
    }

    #[deprecated = "use nb_inputs instead"]
    pub fn get_nb_inputs(&self) -> i32 {
        self.nb_inputs()
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::getNbOutputs`].
    pub fn nb_outputs(&self) -> i32 {
        self.inner.getNbOutputs()
    }

    #[deprecated = "use nb_outputs instead"]
    pub fn get_nb_outputs(&self) -> i32 {
        self.nb_outputs()
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::getInput`].
    pub fn input(&self, index: i32) -> Result<Tensor<'network>> {
        let tensor_ptr = self.inner.getInput(index);
        if tensor_ptr.is_null() {
            return Err(Error::Runtime(format!(
                "Failed to get input at index {}",
                index
            )));
        }
        unsafe { Tensor::new(self.inner.as_ptr(), tensor_ptr) }
    }

    #[deprecated = "use input instead"]
    pub fn get_input(&self, index: i32) -> Result<Tensor<'network>> {
        self.input(index)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::getOutput`].
    pub fn output(&self, index: i32) -> Result<Tensor<'network>> {
        let tensor_ptr = self.inner.getOutput(index);
        if tensor_ptr.is_null() {
            return Err(Error::Runtime(format!(
                "Failed to get output at index {}",
                index
            )));
        }
        unsafe { Tensor::new(self.inner.as_ptr(), tensor_ptr) }
    }

    #[deprecated = "use output instead"]
    pub fn get_output(&self, index: i32) -> Result<Tensor<'network>> {
        self.output(index)
    }

    /// Returns an iterator over the network's input tensors.
    pub fn inputs(&self) -> NetworkInputIter<'_, 'network> {
        NetworkInputIter {
            network: self,
            index: 0,
            count: self.nb_inputs(),
        }
    }

    /// Returns an iterator over the network's output tensors.
    pub fn outputs(&self) -> NetworkOutputIter<'_, 'network> {
        NetworkOutputIter {
            network: self,
            index: 0,
            count: self.nb_outputs(),
        }
    }

    /// Number of layers in the network (for introspection/dumping).
    /// See [INetworkDefinition::getNbLayers]
    pub fn nb_layers(&self) -> i32 {
        self.inner.getNbLayers()
    }

    #[deprecated = "use nb_layers instead"]
    pub fn get_nb_layers(&self) -> i32 {
        self.nb_layers()
    }

    pub fn layer(&self, layer_index: i32) -> Result<DynLayer<'network>> {
        let layer_ptr = self.inner.getLayer(layer_index);
        DynLayer::new_dyn(self.inner.as_ptr(), layer_ptr)
    }

    /// Returns an iterator over the network's layers.
    pub fn layers(&self) -> NetworkLayerIter<'_, 'network> {
        NetworkLayerIter {
            network: self,
            index: 0,
            count: self.nb_layers(),
        }
    }

    #[deprecated = "use layer instead"]
    pub fn get_layer(&self, layer_index: i32) -> Result<DynLayer<'network>> {
        self.layer(layer_index)
    }

    /// Layer name at index (for introspection/dumping). Returns "(Unnamed)" if null.
    pub fn layer_name(&self, layer_index: i32) -> Result<String> {
        Ok(self.layer(layer_index)?.name(self))
    }

    #[deprecated = "use layer_name instead"]
    pub fn get_layer_name(&self, layer_index: i32) -> Result<String> {
        self.layer_name(layer_index)
    }

    /// Layer type enum value at index (for introspection/dumping). See TensorRT LayerType.
    pub fn layer_type(&self, layer_index: i32) -> Result<LayerType> {
        Ok(self.layer(layer_index)?.layer_type_dynamic())
    }

    #[deprecated = "use layer_type instead"]
    pub fn get_layer_type(&self, layer_index: i32) -> Result<LayerType> {
        self.layer_type(layer_index)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addActivation`].
    pub fn add_activation(
        &mut self,
        input: &'_ Tensor,
        activation_type: trtx_sys::ActivationType,
    ) -> Result<ActivationLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_activation input={} activation_type={activation_type:?}",
            tensor_dbg(self, input)
        );
        let layer_ptr = self
            .inner
            .pin_mut()
            .addActivation(input.pin_mut(), activation_type.into());
        ActivationLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addParametricReLU`].
    pub fn add_parametric_relu(
        &mut self,
        input: &'_ Tensor,
        slope: &'_ Tensor,
    ) -> Result<ParametricReLULayer<'network>> {
        check_network!(self, input);
        check_network!(self, slope);
        debug!(
            "add_parametric_relu input={} slope={}",
            tensor_dbg(self, input),
            tensor_dbg(self, slope)
        );
        let layer_ptr = self
            .inner
            .pin_mut()
            .addParametricReLU(input.pin_mut(), slope.pin_mut());
        ParametricReLULayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addLRN`].
    pub fn add_lrn(
        &mut self,
        input: &'_ Tensor,
        window: i64,
        alpha: f32,
        beta: f32,
        k: f32,
    ) -> Result<LrnLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_lrn input={} window={window} alpha={alpha} beta={beta} k={k}",
            tensor_dbg(self, input)
        );
        let layer_ptr = self
            .inner
            .pin_mut()
            .addLRN(input.pin_mut(), window, alpha, beta, k);
        LrnLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addUnary`].
    pub fn add_unary(
        &mut self,
        input: &'_ Tensor,
        op: trtx_sys::UnaryOperation,
    ) -> Result<UnaryLayer<'network>> {
        check_network!(self, input);
        debug!("add_unary input={} op={op:?}", tensor_dbg(self, input));
        let layer_ptr = self.inner.pin_mut().addUnary(input.pin_mut(), op.into());
        UnaryLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addIdentity`].
    pub fn add_identity(&mut self, input: &'_ Tensor) -> Result<IdentityLayer<'network>> {
        check_network!(self, input);
        debug!("add_identity input={}", tensor_dbg(self, input));
        let layer_ptr = self.inner.pin_mut().addIdentity(input.pin_mut());

        IdentityLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addShape`].
    pub fn add_shape(&mut self, input: &'_ Tensor) -> Result<ShapeLayer<'network>> {
        check_network!(self, input);
        debug!("add_shape input={}", tensor_dbg(self, input));
        let layer_ptr = self.inner.pin_mut().addShape(input.pin_mut());
        ShapeLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addCast`].
    pub fn add_cast(
        &mut self,
        input: &'_ Tensor,
        to_type: trtx_sys::DataType,
    ) -> Result<CastLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_cast input={} to_type={to_type:?}",
            tensor_dbg(self, input)
        );
        let layer_ptr = self
            .inner
            .pin_mut()
            .addCast(input.pin_mut(), to_type.into());
        CastLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addElementWise`].
    pub fn add_elementwise(
        &mut self,
        input1: &'_ Tensor,
        input2: &'_ Tensor,
        op: trtx_sys::ElementWiseOperation,
    ) -> Result<ElementWiseLayer<'network>> {
        check_network!(self, input1);
        check_network!(self, input2);
        debug!(
            "add_elementwise input1={} input2={} op={op:?}",
            tensor_dbg(self, input1),
            tensor_dbg(self, input2)
        );
        let layer_ptr =
            self.inner
                .pin_mut()
                .addElementWise(input1.pin_mut(), input2.pin_mut(), op.into());
        ElementWiseLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addPoolingNd`].
    pub fn add_pooling(
        &'_ mut self,
        input: &'_ Tensor,
        pooling_type: trtx_sys::PoolingType,
        window_size: &[i64; 2],
    ) -> Result<PoolingLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_pooling input={} pooling_type={pooling_type:?} window_size={window_size:?}",
            tensor_dbg(self, input)
        );
        let window_dims = trtx_sys::Dims::new_2d(window_size[0], window_size[1]);
        let layer_ptr =
            self.inner
                .pin_mut()
                .addPoolingNd(input.pin_mut(), pooling_type.into(), &window_dims);
        PoolingLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addShuffle`].
    pub fn add_shuffle(&'_ mut self, input: &'_ Tensor) -> Result<ShuffleLayer<'network>> {
        check_network!(self, input);
        debug!("add_shuffle input={}", tensor_dbg(self, input));
        let layer_ptr = self.inner.pin_mut().addShuffle(input.pin_mut());
        ShuffleLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addMatrixMultiply`].
    pub fn add_matrix_multiply(
        &'_ mut self,
        input0: &'_ Tensor,
        op0: MatrixOperation,
        input1: &'_ Tensor,
        op1: MatrixOperation,
    ) -> Result<MatrixMultiplyLayer<'network>> {
        check_network!(self, input0);
        check_network!(self, input1);
        debug!(
            "add_matrix_multiply input0={} op0={op0:?} input1={} op1={op1:?}",
            tensor_dbg(self, input0),
            tensor_dbg(self, input1)
        );
        let layer_ptr = self.inner.pin_mut().addMatrixMultiply(
            input0.pin_mut(),
            op0.into(),
            input1.pin_mut(),
            op1.into(),
        );
        MatrixMultiplyLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// Same as [`Self::add_convolution`] but allows to set weights later (e.g. dynamic kernel and bias)
    ///
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addConvolutionNd`].
    pub fn add_convolution_deferrred_weights(
        &'_ mut self,
        input: &'_ Tensor,
        nb_output_maps: i32,
        kernel_size: &[i32; 2],
    ) -> Result<ConvolutionLayer<'network>> {
        debug!(
            "add_convolution_deferrred_weights input={} nb_output_maps={nb_output_maps} kernel_size={kernel_size:?}",
            tensor_dbg(self, input)
        );
        let kernel_dims = trtx_sys::Dims::new_2d(kernel_size[0] as i64, kernel_size[1] as i64);
        let layer_ptr = self.inner.pin_mut().addConvolutionNd(
            input.pin_mut(),
            nb_output_maps as i64,
            &kernel_dims,
            Weights {
                type_: nvinfer1::DataType::kFLOAT,
                values: std::ptr::null(),
                count: 0,
            },
            Weights {
                type_: nvinfer1::DataType::kFLOAT,
                values: std::ptr::null(),
                count: 0,
            },
        );
        ConvolutionLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// Same as [`Self::add_convolution`] but takes ownership of weights
    ///
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addConvolutionNd`].
    pub fn add_convolution_owned_weights(
        &'_ mut self,
        input: &'_ Tensor,
        nb_output_maps: i32,
        kernel_size: &[i32; 2],
        weights: OwnedConvWeights,
    ) -> Result<ConvolutionLayer<'network>> {
        debug!(
            "add_convolution_owned_weights input={} nb_output_maps={nb_output_maps} kernel_size={kernel_size:?}",
            tensor_dbg(self, input)
        );
        let mut layer =
            self.add_convolution_deferrred_weights(input, nb_output_maps, kernel_size)?;
        let kernel = self
            .add_constant_owned(
                &weights.kernel.shape,
                weights.kernel.values,
                weights.kernel.data_type,
                weights.kernel.name.as_deref(),
            )?
            .output(self, 0)?;
        layer.set_input(self, 1, &kernel)?;

        if let Some(bias) = weights.bias {
            let bias = self
                .add_constant_owned(
                    &bias.shape,
                    bias.values,
                    bias.data_type,
                    bias.name.as_deref(),
                )?
                .output(self, 0)?;
            layer.set_input(self, 2, &bias)?;
        }

        Ok(layer)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addConvolutionNd`].
    pub fn add_convolution(
        &'_ mut self,
        input: &'_ Tensor,
        nb_output_maps: i32,
        kernel_size: &[i32; 2],
        weights: &ConvWeights<'network>,
    ) -> Result<ConvolutionLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_convolution input={} nb_output_maps={nb_output_maps} kernel_size={kernel_size:?}",
            tensor_dbg(self, input)
        );
        let kernel_dtype = weights.kernel_dtype;
        let kernel_weights = weights.kernel_weights;
        let bias_weights = weights.bias_weights;
        let bias_dtype = weights.bias_dtype;
        let kernel_bpe = kernel_dtype.size_bits() / 8;
        let weight_count = (kernel_weights.len() / kernel_bpe) as i64;
        let bias_dtype_val = bias_dtype.unwrap_or(kernel_dtype);
        let bias_bpe = bias_dtype_val.size_bits() / 8;
        let bias_count = bias_weights
            .map(|b| (b.len() / bias_bpe) as i64)
            .unwrap_or(0);
        let kernel_ptr = if weight_count > 0 {
            kernel_weights.as_ptr() as *const std::ffi::c_void
        } else {
            std::ptr::null()
        };
        let bias_ptr = if bias_count > 0 {
            bias_weights
                .map(|b| b.as_ptr() as *const std::ffi::c_void)
                .unwrap_or(std::ptr::null())
        } else {
            std::ptr::null()
        };
        let kernel_dims = trtx_sys::Dims::new_2d(kernel_size[0] as i64, kernel_size[1] as i64);
        let kernel_w = trtx_sys::nvinfer1::Weights::new_with_type(
            kernel_dtype.into(),
            kernel_ptr,
            weight_count,
        );
        let bias_w =
            trtx_sys::nvinfer1::Weights::new_with_type(bias_dtype_val.into(), bias_ptr, bias_count);
        let layer_ptr = self.inner.pin_mut().addConvolutionNd(
            input.pin_mut(),
            nb_output_maps as i64,
            &kernel_dims,
            kernel_w,
            bias_w,
        );
        ConvolutionLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// Add a 2D deconvolution layer. Same input semantics as convolution: input 0 = activation,
    /// input 1 = kernel tensor (use set_input(1, tensor) when kernel_weights is empty),
    /// input 2 = bias tensor (use set_input(2, tensor) when bias_weights is None/empty).
    ///
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addDeconvolutionNd`].
    pub fn add_deconvolution(
        &mut self,
        input: &'_ Tensor,
        nb_output_maps: i64,
        kernel_size: &[i64; 2],
        weights: &ConvWeights<'network>,
    ) -> Result<DeconvolutionLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_deconvolution input={} nb_output_maps={nb_output_maps} kernel_size={kernel_size:?}",
            tensor_dbg(self, input)
        );
        let kernel_dtype = weights.kernel_dtype;
        let kernel_weights = weights.kernel_weights;
        let bias_weights = weights.bias_weights;
        let bias_dtype = weights.bias_dtype;
        let kernel_bpe = kernel_dtype.size_bits() / 8;
        let weight_count = (kernel_weights.len() / kernel_bpe) as i64;
        let bias_dtype_val = bias_dtype.unwrap_or(kernel_dtype);
        let bias_bpe = bias_dtype_val.size_bits() / 8;
        let bias_count = bias_weights
            .map(|b| (b.len() / bias_bpe) as i64)
            .unwrap_or(0);
        let kernel_ptr = if weight_count > 0 {
            kernel_weights.as_ptr() as *const std::ffi::c_void
        } else {
            std::ptr::null()
        };
        let bias_ptr = if bias_count > 0 {
            bias_weights
                .map(|b| b.as_ptr() as *const std::ffi::c_void)
                .unwrap_or(std::ptr::null())
        } else {
            std::ptr::null()
        };
        let kernel_dims = trtx_sys::Dims::new_2d(kernel_size[0], kernel_size[1]);
        let kernel_w = trtx_sys::nvinfer1::Weights::new_with_type(
            kernel_dtype.into(),
            kernel_ptr,
            weight_count,
        );
        let bias_w =
            trtx_sys::nvinfer1::Weights::new_with_type(bias_dtype_val.into(), bias_ptr, bias_count);
        let layer_ptr = self.inner.pin_mut().addDeconvolutionNd(
            input.pin_mut(),
            nb_output_maps,
            kernel_dims,
            kernel_w,
            bias_w,
        );
        DeconvolutionLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// Add a 2D deconvolution layer. Same input semantics as convolution: input 0 = activation,
    /// input 1 = kernel tensor (use set_input(1, tensor) when kernel_weights is empty),
    /// input 2 = bias tensor (use set_input(2, tensor) when bias_weights is None/empty).
    ///
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addDeconvolutionNd`].
    pub fn add_deconvolution_deferred_weights(
        &mut self,
        input: &'_ Tensor,
        nb_output_maps: i64,
        kernel_size: &[i64; 2],
    ) -> Result<DeconvolutionLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_deconvolution_deferred_weights input={} nb_output_maps={nb_output_maps} kernel_size={kernel_size:?}",
            tensor_dbg(self, input)
        );
        let kernel_dims = trtx_sys::Dims::new_2d(kernel_size[0], kernel_size[1]);
        let layer_ptr = self.inner.pin_mut().addDeconvolutionNd(
            input.pin_mut(),
            nb_output_maps,
            kernel_dims,
            Weights {
                type_: nvinfer1::DataType::kFLOAT,
                values: std::ptr::null(),
                count: 0,
            },
            Weights {
                type_: nvinfer1::DataType::kFLOAT,
                values: std::ptr::null(),
                count: 0,
            },
        );
        DeconvolutionLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// Same as [`Self::add_deconvolution`] but takes ownership of weights
    ///
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addDeconvolutionNd`].
    pub fn add_deconvolution_owned_weights(
        &'_ mut self,
        input: &'_ Tensor,
        nb_output_maps: i64,
        kernel_size: &[i64; 2],
        weights: OwnedConvWeights,
    ) -> Result<DeconvolutionLayer<'network>> {
        debug!(
            "add_deconvolution_owned_weights input={} nb_output_maps={nb_output_maps} kernel_size={kernel_size:?}",
            tensor_dbg(self, input)
        );
        let mut layer =
            self.add_deconvolution_deferred_weights(input, nb_output_maps, kernel_size)?;
        let kernel = self
            .add_constant_owned(
                &weights.kernel.shape,
                weights.kernel.values,
                weights.kernel.data_type,
                weights.kernel.name.as_deref(),
            )?
            .output(self, 0)?;
        layer.set_input(self, 1, &kernel)?;

        if let Some(bias) = weights.bias {
            let bias = self
                .add_constant_owned(
                    &bias.shape,
                    bias.values,
                    bias.data_type,
                    bias.name.as_deref(),
                )?
                .output(self, 0)?;
            layer.set_input(self, 2, &bias)?;
        }

        Ok(layer)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addConcatenation`].
    pub fn add_concatenation(
        &'_ mut self,
        inputs: &[&'_ Tensor],
    ) -> Result<ConcatenationLayer<'network>> {
        for t in inputs.iter() {
            check_network!(self, t);
        }
        let input_names: Vec<String> = inputs.iter().map(|t| tensor_dbg(self, t)).collect();
        debug!("add_concatenation inputs={input_names:?}");
        let mut input_ptrs: Vec<*mut std::ffi::c_void> = inputs
            .iter()
            .map(|t| t.as_mut() as *mut ITensor as *mut _)
            .collect();
        let layer_ptr = unsafe {
            trtx_sys::network_add_concatenation(
                self.inner.as_mut_ptr() as *mut std::ffi::c_void,
                input_ptrs.as_mut_ptr(),
                inputs.len() as i32,
            )
        } as *mut IConcatenationLayer;
        ConcatenationLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addEinsum`].
    pub fn add_einsum(
        &'_ mut self,
        inputs: &[&'_ Tensor],
        equation: &str,
    ) -> Result<EinsumLayer<'network>> {
        for t in inputs.iter() {
            check_network!(self, t);
        }
        let input_names: Vec<String> = inputs.iter().map(|t| tensor_dbg(self, t)).collect();
        debug!("add_einsum inputs={input_names:?} equation={equation:?}");
        let equation_cstr = CString::new(equation)?;
        let mut input_ptrs: Vec<*mut std::ffi::c_void> = inputs
            .iter()
            .map(|t| t.as_mut() as *mut ITensor as *mut _)
            .collect();
        let layer_ptr = unsafe {
            trtx_sys::network_add_einsum(
                self.inner.as_mut_ptr() as *mut std::ffi::c_void,
                input_ptrs.as_mut_ptr(),
                inputs.len() as i32,
                equation_cstr.as_ptr(),
            )
        } as *mut IEinsumLayer;
        EinsumLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addConstant`].
    /// Same as [`Self::add_constant`] just copying the provided weights for small weights like scalars
    pub fn add_small_constant_copied(
        &mut self,
        dims: &[i64],
        weights: &[u8],
        data_type: trtx_sys::DataType,
        name: Option<&str>,
    ) -> Result<ConstantLayer<'network>> {
        trace!(
            "add_small_constant_copied dims={dims:?} data_type={data_type:?} weights_len={} name={name:?}",
            weights.len()
        );
        unsafe { self.add_constant_unsafe(dims, weights, data_type, true, name) }
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addConstant`].
    /// Same as [`Self::add_constant`] but takes ownership of weights
    pub fn add_constant_owned(
        &mut self,
        dims: &[i64],
        weights: Vec<u8>,
        data_type: trtx_sys::DataType,
        name: Option<&str>,
    ) -> Result<ConstantLayer<'network>> {
        trace!(
            "add_constant_owned dims={dims:?} data_type={data_type:?} weights_len={} name={name:?}",
            weights.len()
        );
        let element_count: i64 = dims.iter().product();
        let expected_bytes = element_count * data_type.size_bits() as i64 / 8;
        if weights.len() as i64 != expected_bytes {
            panic!(
                "Weight size mismatch: expected {expected_bytes} bytes, got {} bytes",
                weights.len()
            );
        }
        let dims_struct = trtx_sys::Dims::from_slice(dims);
        let weights_struct = trtx_sys::nvinfer1::Weights::new_with_type(
            data_type.into(),
            {
                self.small_copied_weights.push(weights);
                self.small_copied_weights
                    .last()
                    .expect("can't be empty. we just pushed")
                    .as_ptr()
            } as *const std::ffi::c_void,
            element_count,
        );
        let ptr = weights_struct.values;
        let layer_ptr = self
            .inner
            .pin_mut()
            .addConstant(&dims_struct, weights_struct);
        let layer = ConstantLayer::new(self.inner.as_ptr(), layer_ptr)?;
        if let Some(name) = name {
            unsafe {
                self.set_weights_name(
                    Weights {
                        type_: data_type.into(),
                        values: ptr,
                        count: element_count,
                    },
                    name,
                )?
            };
        }

        Ok(layer)
    }

    unsafe fn add_constant_unsafe(
        &mut self,
        dims: &[i64],
        weights: &[u8],
        data_type: trtx_sys::DataType,
        copy: bool,
        name: Option<&str>,
    ) -> Result<ConstantLayer<'network>> {
        let element_count: i64 = dims.iter().product();
        let expected_bytes = element_count * data_type.size_bits() as i64 / 8;
        if weights.len() as i64 != expected_bytes {
            panic!(
                "Weight size mismatch: expected {expected_bytes} bytes, got {} bytes",
                weights.len()
            );
        }
        let dims_struct = trtx_sys::Dims::from_slice(dims);
        let weights_struct = trtx_sys::nvinfer1::Weights::new_with_type(
            data_type.into(),
            if copy {
                self.small_copied_weights.push(weights.to_vec());
                self.small_copied_weights
                    .last()
                    .expect("can't be empty. we just pushed")
                    .as_ptr()
            } else {
                weights.as_ptr()
            } as *const std::ffi::c_void,
            element_count,
        );
        let ptr = weights_struct.values;
        let layer_ptr = self
            .inner
            .pin_mut()
            .addConstant(&dims_struct, weights_struct);
        let layer = ConstantLayer::new(self.inner.as_ptr(), layer_ptr)?;
        if let Some(name) = name {
            self.set_weights_name(
                Weights {
                    type_: data_type.into(),
                    values: ptr,
                    count: element_count,
                },
                name,
            )?;
        }

        Ok(layer)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addConstant`].
    pub fn add_constant(
        &mut self,
        dims: &[i64],
        weights: &'network [u8],
        data_type: trtx_sys::DataType,
        name: Option<&str>,
    ) -> Result<ConstantLayer<'network>> {
        trace!(
            "add_constant dims={dims:?} data_type={data_type:?} weights_len={} name={name:?}",
            weights.len()
        );
        unsafe { self.add_constant_unsafe(dims, weights, data_type, false, name) }
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addSoftMax`].
    pub fn add_softmax(
        &mut self,
        input: &'_ Tensor,
        axes: crate::Axes,
    ) -> Result<SoftMaxLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_softmax input={} axes={axes:?}",
            tensor_dbg(self, input)
        );
        let layer_ptr = self.inner.pin_mut().addSoftMax(input.pin_mut());
        let mut rtn = SoftMaxLayer::new(self.inner.as_ptr(), layer_ptr)?;
        rtn.inner.as_mut().setAxes(axes.to_bits());
        Ok(rtn)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addRaggedSoftMax`].
    pub fn add_ragged_softmax(
        &mut self,
        input: &'_ Tensor,
        bounds: &'_ Tensor,
    ) -> Result<RaggedSoftMaxLayer<'network>> {
        check_network!(self, input);
        check_network!(self, bounds);
        debug!(
            "add_ragged_softmax input={} bounds={}",
            tensor_dbg(self, input),
            tensor_dbg(self, bounds)
        );
        let layer_ptr = self
            .inner
            .pin_mut()
            .addRaggedSoftMax(input.pin_mut(), bounds.pin_mut());
        RaggedSoftMaxLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addScale`].
    pub fn add_scale(
        &mut self,
        input: &'_ Tensor,
        mode: ScaleMode,
        shift: &[u8],
        scale: &[u8],
        power: &[u8],
    ) -> Result<ScaleLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_scale input={} mode={mode:?} shift_len={} scale_len={} power_len={}",
            tensor_dbg(self, input),
            shift.len(),
            scale.len(),
            power.len()
        );
        let weight_count = match mode {
            ScaleMode::kUNIFORM => 1i64,
            ScaleMode::kCHANNEL => {
                let input_dims = input.dimensions(self)?;
                if input_dims.len() >= 4 {
                    input_dims[1]
                } else if !input_dims.is_empty() {
                    input_dims[0]
                } else {
                    1i64
                }
            }
            ScaleMode::kELEMENTWISE => {
                let input_dims = input.dimensions(self)?;
                input_dims.iter().product::<i64>()
            }
        };

        let shift_w = trtx_sys::nvinfer1::Weights::new_float(
            shift.as_ptr() as *const std::ffi::c_void,
            weight_count,
        );
        let scale_w = trtx_sys::nvinfer1::Weights::new_float(
            scale.as_ptr() as *const std::ffi::c_void,
            weight_count,
        );
        let power_w = trtx_sys::nvinfer1::Weights::new_float(
            power.as_ptr() as *const std::ffi::c_void,
            weight_count,
        );
        let layer_ptr =
            self.inner
                .pin_mut()
                .addScale(input.pin_mut(), mode.into(), shift_w, scale_w, power_w);
        ScaleLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addScaleNd`].
    pub fn add_scale_nd(
        &mut self,
        input: &'_ Tensor,
        mode: ScaleMode,
        shift: &[u8],
        scale: &[u8],
        power: &[u8],
        channel_axis: i32,
    ) -> Result<ScaleLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_scale_nd input={} mode={mode:?} channel_axis={channel_axis} shift_len={} scale_len={} power_len={}",
            tensor_dbg(self, input),
            shift.len(),
            scale.len(),
            power.len()
        );
        let weight_count = match mode {
            ScaleMode::kUNIFORM => 1i64,
            ScaleMode::kCHANNEL => {
                let input_dims = input.dimensions(self)?;
                if input_dims.len() >= 4 {
                    input_dims[1]
                } else if !input_dims.is_empty() {
                    input_dims[0]
                } else {
                    1i64
                }
            }
            ScaleMode::kELEMENTWISE => {
                let input_dims = input.dimensions(self)?;
                input_dims.iter().product::<i64>()
            }
        };
        let shift_w = trtx_sys::nvinfer1::Weights::new_float(
            shift.as_ptr() as *const std::ffi::c_void,
            weight_count,
        );
        let scale_w = trtx_sys::nvinfer1::Weights::new_float(
            scale.as_ptr() as *const std::ffi::c_void,
            weight_count,
        );
        let power_w = trtx_sys::nvinfer1::Weights::new_float(
            power.as_ptr() as *const std::ffi::c_void,
            weight_count,
        );
        let layer_ptr = self.inner.pin_mut().addScaleNd(
            input.pin_mut(),
            mode.into(),
            shift_w,
            scale_w,
            power_w,
            channel_axis,
        );
        ScaleLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addReduce`].
    pub fn add_reduce(
        &mut self,
        input: &'_ Tensor,
        op: trtx_sys::ReduceOperation,
        axes: crate::Axes,
        keep_dims: bool,
    ) -> Result<ReduceLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_reduce input={} op={op:?} axes={axes:?} keep_dims={keep_dims}",
            tensor_dbg(self, input)
        );
        let axes_bits = axes.to_bits();
        let layer_ptr =
            self.inner
                .pin_mut()
                .addReduce(input.pin_mut(), op.into(), axes_bits, keep_dims);
        ReduceLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addCumulative`].
    pub fn add_cumulative(
        &mut self,
        input: &'_ Tensor,
        axis: i32,
        op: trtx_sys::CumulativeOperation,
        exclusive: bool,
        reverse: bool,
    ) -> Result<CumulativeLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_cumulative input={} axis={axis} op={op:?} exclusive={exclusive} reverse={reverse}",
            tensor_dbg(self, input)
        );
        let axis_bytes = axis.to_le_bytes();
        let axis_constant =
            self.add_small_constant_copied(&[], &axis_bytes, trtx_sys::DataType::kINT32, None)?;
        let axis_tensor = axis_constant.output(self, 0)?;
        self.add_cumulative_with_axis_tensor(input, &axis_tensor, op, exclusive, reverse)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addCumulative`].
    pub fn add_cumulative_with_axis_tensor(
        &mut self,
        input: &'_ Tensor,
        axis_tensor: &'_ Tensor,
        op: trtx_sys::CumulativeOperation,
        exclusive: bool,
        reverse: bool,
    ) -> Result<CumulativeLayer<'network>> {
        check_network!(self, input);
        check_network!(self, axis_tensor);
        debug!(
            "add_cumulative_with_axis_tensor input={} axis_tensor={} op={op:?} exclusive={exclusive} reverse={reverse}",
            tensor_dbg(self, input),
            tensor_dbg(self, axis_tensor)
        );
        let layer_ptr = self.inner.pin_mut().addCumulative(
            input.pin_mut(),
            axis_tensor.pin_mut(),
            op.into(),
            exclusive,
            reverse,
        );
        CumulativeLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addSlice`].
    pub fn add_slice(
        &mut self,
        input: &'_ Tensor,
        start: &[i64],
        size: &[i64],
        stride: &[i64],
    ) -> Result<SliceLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_slice input={} start={start:?} size={size:?} stride={stride:?}",
            tensor_dbg(self, input)
        );
        if start.len() != size.len() || start.len() != stride.len() {
            return Err(Error::Runtime(
                "start, size, and stride must have the same length".to_string(),
            ));
        }
        let start_dims = trtx_sys::Dims::from_slice(start);
        let size_dims = trtx_sys::Dims::from_slice(size);
        let stride_dims = trtx_sys::Dims::from_slice(stride);
        let layer_ptr =
            self.inner
                .pin_mut()
                .addSlice(input.pin_mut(), &start_dims, &size_dims, &stride_dims);
        SliceLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addTopK1`].
    pub fn add_topk_with_indices(
        &mut self,
        input: &'_ Tensor,
        op: TopKOperation,
        k: i32,
        axes: crate::Axes,
        indices_type: DataType,
    ) -> Result<TopKLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_topk input={} op={op:?} k={k} axes={axes:?} indices_type={indices_type:?}",
            tensor_dbg(self, input)
        );
        let axes_bits = axes.to_bits();
        let layer_ptr = self.inner.pin_mut().addTopK1(
            input.pin_mut(),
            op.into(),
            k,
            axes_bits,
            indices_type.into(),
        );
        TopKLayer::new(self.inner.as_ptr(), layer_ptr)
    }
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addTopK`].
    pub fn add_topk(
        &mut self,
        input: &'_ Tensor,
        op: TopKOperation,
        k: i32,
        axes: crate::Axes,
    ) -> Result<TopKLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_topk input={} op={op:?} k={k} axes={axes:?}",
            tensor_dbg(self, input)
        );
        let axes_bits = axes.to_bits();
        let layer_ptr = self
            .inner
            .pin_mut()
            .addTopK(input.pin_mut(), op.into(), k, axes_bits);
        TopKLayer::new(self.inner.as_ptr(), layer_ptr)
    }
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addResize`].
    pub fn add_resize(&mut self, input: &'_ Tensor) -> Result<ResizeLayer<'network>> {
        check_network!(self, input);
        debug!("add_resize input={}", tensor_dbg(self, input));
        let layer_ptr = self.inner.pin_mut().addResize(input.pin_mut());
        ResizeLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addRotaryEmbedding`].
    pub fn add_rotary_embedding(
        &mut self,
        input: &'_ Tensor,
        cos_cache: &'_ Tensor,
        sin_cache: &'_ Tensor,
        interleaved: bool,
        rotary_embedding_dim: i32,
    ) -> Result<RotaryEmbeddingLayer<'network>> {
        check_network!(self, input);
        check_network!(self, cos_cache);
        check_network!(self, sin_cache);
        debug!(
            "add_rotary_embedding input={} cos_cache={} sin_cache={} interleaved={interleaved} rotary_embedding_dim={rotary_embedding_dim}",
            tensor_dbg(self, input),
            tensor_dbg(self, cos_cache),
            tensor_dbg(self, sin_cache)
        );
        let layer_ptr = self.inner.pin_mut().addRotaryEmbedding(
            input.pin_mut(),
            cos_cache.pin_mut(),
            sin_cache.pin_mut(),
            interleaved,
            rotary_embedding_dim,
        );
        RotaryEmbeddingLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addGather`].
    pub fn add_gather(
        &'_ mut self,
        data: &'_ Tensor,
        indices: &'_ Tensor,
        axis: i32,
    ) -> Result<GatherLayer<'network>> {
        check_network!(self, data);
        check_network!(self, indices);
        debug!(
            "add_gather data={} indices={} axis={axis}",
            tensor_dbg(self, data),
            tensor_dbg(self, indices)
        );
        let layer_ptr = self
            .inner
            .pin_mut()
            .addGather(data.pin_mut(), indices.pin_mut(), axis);
        GatherLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addGatherV2`].
    pub fn add_gather_v2(
        &mut self,
        data: &'_ Tensor,
        indices: &'_ Tensor,
        mode: GatherMode,
    ) -> Result<GatherLayer<'network>> {
        check_network!(self, data);
        check_network!(self, indices);
        debug!(
            "add_gather_v2 data={} indices={} mode={mode:?}",
            tensor_dbg(self, data),
            tensor_dbg(self, indices)
        );
        let layer_ptr =
            self.inner
                .pin_mut()
                .addGatherV2(data.pin_mut(), indices.pin_mut(), mode.into());
        GatherLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addScatter`].
    pub fn add_scatter(
        &mut self,
        data: &'_ Tensor,
        indices: &'_ Tensor,
        updates: &'_ Tensor,
        mode: trtx_sys::ScatterMode,
    ) -> Result<ScatterLayer<'network>> {
        check_network!(self, data);
        check_network!(self, indices);
        check_network!(self, updates);
        debug!(
            "add_scatter data={} indices={} updates={} mode={mode:?}",
            tensor_dbg(self, data),
            tensor_dbg(self, indices),
            tensor_dbg(self, updates)
        );
        let layer_ptr = self.inner.pin_mut().addScatter(
            data.pin_mut(),
            indices.pin_mut(),
            updates.pin_mut(),
            mode.into(),
        );
        ScatterLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addQuantize`].
    pub fn add_quantize(
        &'_ mut self,
        input: &'_ Tensor,
        scale: &'_ Tensor,
        output_type: trtx_sys::DataType,
    ) -> Result<QuantizeLayer<'network>> {
        check_network!(self, input);
        check_network!(self, scale);
        debug!(
            "add_quantize input={} scale={} output_type={output_type:?}",
            tensor_dbg(self, input),
            tensor_dbg(self, scale)
        );
        #[cfg(not(all(feature = "enterprise", not(feature = "v_1_5"))))]
        let layer_ptr =
            self.inner
                .pin_mut()
                .addQuantize(input.pin_mut(), scale.pin_mut(), output_type.into());
        #[cfg(all(feature = "enterprise", not(feature = "v_1_5")))]
        let layer_ptr =
            self.inner
                .pin_mut()
                .addQuantize1(input.pin_mut(), scale.pin_mut(), output_type.into());
        QuantizeLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addDequantize`].
    pub fn add_dequantize(
        &mut self,
        input: &'_ Tensor,
        scale: &'_ Tensor,
        output_type: trtx_sys::DataType,
    ) -> Result<DequantizeLayer<'network>> {
        check_network!(self, input);
        check_network!(self, scale);
        debug!(
            "add_dequantize input={} scale={} output_type={output_type:?}",
            tensor_dbg(self, input),
            tensor_dbg(self, scale)
        );
        #[cfg(not(all(feature = "enterprise", not(feature = "v_1_5"))))]
        let layer_ptr = self.inner.pin_mut().addDequantize(
            input.pin_mut(),
            scale.pin_mut(),
            output_type.into(),
        );
        #[cfg(all(feature = "enterprise", not(feature = "v_1_5")))]
        let layer_ptr = self.inner.pin_mut().addDequantize1(
            input.pin_mut(),
            scale.pin_mut(),
            output_type.into(),
        );
        DequantizeLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addDynamicQuantize`].
    #[deprecated(note = "use add_dynamic_quantize_v2 instead")]
    pub fn add_dynamic_quantize(
        &mut self,
        input: &'_ Tensor,
        axis: i32,
        block_size: i32,
        output_type: DataType,
        scale_type: DataType,
    ) -> Result<DynamicQuantizeLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_dynamic_quantize input={} axis={axis} block_size={block_size} output_type={output_type:?} scale_type={scale_type:?}",
            tensor_dbg(self, input)
        );
        #[allow(deprecated)]
        let layer_ptr = self.inner.pin_mut().addDynamicQuantize(
            input.pin_mut(),
            axis,
            block_size,
            output_type.into(),
            scale_type.into(),
        );
        DynamicQuantizeLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addDynamicQuantizeV2`].
    pub fn add_dynamic_quantize_v2(
        &mut self,
        input: &'_ Tensor,
        block_shape: &[i64],
        output_type: DataType,
        scale_type: DataType,
    ) -> Result<DynamicQuantizeLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_dynamic_quantize_v2 input={} block_shape={block_shape:?} output_type={output_type:?} scale_type={scale_type:?}",
            tensor_dbg(self, input)
        );
        let block_shape_dims = Dims64::from_slice(block_shape);
        let layer_ptr = self.inner.pin_mut().addDynamicQuantizeV2(
            input.pin_mut(),
            &block_shape_dims,
            output_type.into(),
            scale_type.into(),
        );
        DynamicQuantizeLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addSelect`].
    pub fn add_select(
        &mut self,
        condition: &'_ Tensor,
        then_input: &'_ Tensor,
        else_input: &'_ Tensor,
    ) -> Result<SelectLayer<'network>> {
        check_network!(self, condition);
        check_network!(self, then_input);
        check_network!(self, else_input);
        debug!(
            "add_select condition={} then_input={} else_input={}",
            tensor_dbg(self, condition),
            tensor_dbg(self, then_input),
            tensor_dbg(self, else_input)
        );
        let layer_ptr = self.inner.pin_mut().addSelect(
            condition.pin_mut(),
            then_input.pin_mut(),
            else_input.pin_mut(),
        );
        SelectLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addPaddingNd`].
    pub fn add_padding(
        &mut self,
        input: &'_ Tensor,
        pre_padding: &[i64],
        post_padding: &[i64],
    ) -> Result<PaddingLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_padding input={} pre_padding={pre_padding:?} post_padding={post_padding:?}",
            tensor_dbg(self, input)
        );
        if pre_padding.len() != post_padding.len() {
            return Err(Error::Runtime(
                "pre_padding and post_padding must have the same length".to_string(),
            ));
        }
        let pre_dims = trtx_sys::Dims::from_slice(pre_padding);
        let post_dims = trtx_sys::Dims::from_slice(post_padding);
        let layer_ptr = self
            .inner
            .pin_mut()
            .addPaddingNd(input.pin_mut(), &pre_dims, &post_dims);
        PaddingLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addFill`].
    pub fn add_fill(
        &mut self,
        dimensions: &[i64],
        op: FillOperation,
        output_type: DataType,
    ) -> Result<FillLayer<'network>> {
        debug!("add_fill dimensions={dimensions:?} op={op:?} output_type={output_type:?}");
        let dims = Dims64::from_slice(dimensions);
        let layer_ptr = self
            .inner
            .pin_mut()
            .addFill(&dims, op.into(), output_type.into());
        FillLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addOneHot`].
    pub fn add_one_hot(
        &mut self,
        indices: &'_ Tensor,
        values: &'_ Tensor,
        depth: &'_ Tensor,
        axis: i32,
    ) -> Result<OneHotLayer<'network>> {
        check_network!(self, indices);
        check_network!(self, values);
        check_network!(self, depth);
        debug!(
            "add_one_hot indices={} values={} depth={} axis={axis}",
            tensor_dbg(self, indices),
            tensor_dbg(self, values),
            tensor_dbg(self, depth)
        );
        let layer_ptr = self.inner.pin_mut().addOneHot(
            indices.pin_mut(),
            values.pin_mut(),
            depth.pin_mut(),
            axis,
        );
        OneHotLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addNonZero`].
    pub fn add_non_zero(
        &mut self,
        input: &'_ Tensor,
        indices_type: DataType,
    ) -> Result<NonZeroLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_non_zero input={} indices_type={indices_type:?}",
            tensor_dbg(self, input)
        );
        let layer_ptr = self
            .inner
            .pin_mut()
            .addNonZero1(input.pin_mut(), indices_type.into());
        NonZeroLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addNMS`].
    pub fn add_nms(
        &mut self,
        boxes: &'_ Tensor,
        scores: &'_ Tensor,
        max_output_boxes_per_class: &'_ Tensor,
        indices_type: DataType,
    ) -> Result<NMSLayer<'network>> {
        check_network!(self, boxes);
        check_network!(self, scores);
        check_network!(self, max_output_boxes_per_class);
        debug!(
            "add_nms boxes={} scores={} max_output_boxes_per_class={} indices_type={indices_type:?}",
            tensor_dbg(self, boxes),
            tensor_dbg(self, scores),
            tensor_dbg(self, max_output_boxes_per_class)
        );
        let layer_ptr = self.inner.pin_mut().addNMS1(
            boxes.pin_mut(),
            scores.pin_mut(),
            max_output_boxes_per_class.pin_mut(),
            indices_type.into(),
        );
        NMSLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addReverseSequence`].
    pub fn add_reverse_sequence(
        &mut self,
        input: &'_ Tensor,
        sequence_lens: &'_ Tensor,
    ) -> Result<ReverseSequenceLayer<'network>> {
        check_network!(self, input);
        check_network!(self, sequence_lens);
        debug!(
            "add_reverse_sequence input={} sequence_lens={}",
            tensor_dbg(self, input),
            tensor_dbg(self, sequence_lens)
        );
        let layer_ptr = self
            .inner
            .pin_mut()
            .addReverseSequence(input.pin_mut(), sequence_lens.pin_mut());
        ReverseSequenceLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addSqueeze`].
    pub fn add_squeeze(
        &mut self,
        input: &'_ Tensor,
        axes: &'_ Tensor,
    ) -> Result<SqueezeLayer<'network>> {
        check_network!(self, input);
        check_network!(self, axes);
        debug!(
            "add_squeeze input={} axes={}",
            tensor_dbg(self, input),
            tensor_dbg(self, axes)
        );
        let layer_ptr = self
            .inner
            .pin_mut()
            .addSqueeze(input.pin_mut(), axes.pin_mut());
        SqueezeLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addUnsqueeze`].
    pub fn add_unsqueeze(
        &mut self,
        input: &'_ Tensor,
        axes: &'_ Tensor,
    ) -> Result<UnsqueezeLayer<'network>> {
        check_network!(self, input);
        check_network!(self, axes);
        debug!(
            "add_unsqueeze input={} axes={}",
            tensor_dbg(self, input),
            tensor_dbg(self, axes)
        );
        let layer_ptr = self
            .inner
            .pin_mut()
            .addUnsqueeze(input.pin_mut(), axes.pin_mut());
        UnsqueezeLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addKVCacheUpdate`].
    pub fn add_kv_cache_update(
        &mut self,
        cache: &'_ Tensor,
        update: &'_ Tensor,
        write_indices: &'_ Tensor,
        cache_mode: KVCacheMode,
    ) -> Result<KVCacheUpdateLayer<'network>> {
        check_network!(self, cache);
        check_network!(self, update);
        check_network!(self, write_indices);
        debug!(
            "add_kv_cache_update cache={} update={} write_indices={} cache_mode={cache_mode:?}",
            tensor_dbg(self, cache),
            tensor_dbg(self, update),
            tensor_dbg(self, write_indices)
        );
        let layer_ptr = self.inner.pin_mut().addKVCacheUpdate(
            cache.pin_mut(),
            update.pin_mut(),
            write_indices.pin_mut(),
            cache_mode.into(),
        );
        KVCacheUpdateLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addAssertion`].
    pub fn add_assertion(
        &mut self,
        condition: &'_ Tensor,
        message: &str,
    ) -> Result<AssertionLayer<'network>> {
        check_network!(self, condition);
        debug!(
            "add_assertion condition={} message={message:?}",
            tensor_dbg(self, condition)
        );
        let message_cstr = std::ffi::CString::new(message)?;
        let layer_ptr = unsafe {
            self.inner
                .pin_mut()
                .addAssertion(condition.pin_mut(), message_cstr.as_ptr())
        };
        AssertionLayer::new(self.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addLoop`].
    pub fn add_loop(&mut self) -> Result<Loop<'network>> {
        debug!("add_loop");
        let loop_ptr = self.inner.pin_mut().addLoop();
        let loop_ptr = unsafe { loop_ptr.as_mut() }
            .ok_or_else(|| Error::Runtime("Failed to add loop".to_string()))?;
        Ok(Loop {
            inner: unsafe { Pin::new_unchecked(loop_ptr) },
            network: self.inner.as_ptr(),
        })
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addIfConditional`].
    pub fn add_if_conditional(&mut self) -> Result<IfConditional<'network>> {
        debug!("add_if_conditional");
        let if_ptr = self.inner.pin_mut().addIfConditional();
        let if_ptr = unsafe { if_ptr.as_mut() }
            .ok_or_else(|| Error::Runtime("Failed to add if conditional".to_string()))?;
        Ok(IfConditional {
            inner: unsafe { Pin::new_unchecked(if_ptr) },
            network: self.inner.as_ptr(),
        })
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addAttentionV2`].
    pub fn add_attention_v2(
        &mut self,
        query: &'_ Tensor,
        key: &'_ Tensor,
        value: &'_ Tensor,
        norm_op: trtx_sys::AttentionNormalizationOp,
        causal_kind: CausalMaskKind,
    ) -> Result<Attention<'network>> {
        check_network!(self, query);
        check_network!(self, key);
        check_network!(self, value);
        debug!(
            "add_attention_v2 query={} key={} value={} norm_op={norm_op:?} causal_kind={causal_kind:?}",
            tensor_dbg(self, query),
            tensor_dbg(self, key),
            tensor_dbg(self, value)
        );
        let attn_ptr = self.inner.pin_mut().addAttentionV2(
            query.pin_mut(),
            key.pin_mut(),
            value.pin_mut(),
            norm_op.into(),
            causal_kind.into(),
        );
        let attn = unsafe { attn_ptr.as_mut() }
            .ok_or_else(|| Error::Runtime("Failed to add attention".to_string()))?;
        Ok(Attention {
            inner: unsafe { Pin::new_unchecked(attn) },
            network: self.inner.as_ptr(),
        })
    }

    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addAttention`].
    /// Creates an attention block (internally creates [`AttentionInputLayer`] and [`AttentionOutputLayer`]).
    pub fn add_attention(
        &mut self,
        query: &'_ Tensor,
        key: &'_ Tensor,
        value: &'_ Tensor,
        norm_op: trtx_sys::AttentionNormalizationOp,
        causal: bool,
    ) -> Result<Attention<'network>> {
        check_network!(self, query);
        check_network!(self, key);
        check_network!(self, value);
        debug!(
            "add_attention query={} key={} value={} norm_op={norm_op:?} causal={causal}",
            tensor_dbg(self, query),
            tensor_dbg(self, key),
            tensor_dbg(self, value)
        );
        let attn_ptr = self.inner.pin_mut().addAttention(
            query.pin_mut(),
            key.pin_mut(),
            value.pin_mut(),
            norm_op.into(),
            causal,
        );
        let attn = unsafe { attn_ptr.as_mut() }
            .ok_or_else(|| Error::Runtime("Failed to add attention".to_string()))?;
        Ok(Attention {
            inner: unsafe { Pin::new_unchecked(attn) },
            network: self.inner.as_ptr(),
        })
    }

    #[cfg(feature = "v_1_4")]
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addMoE`].
    pub fn add_moe(
        &mut self,
        hidden_states: &Tensor,
        selected_experts_for_tokens: &Tensor,
        scores_for_selected_experts: &Tensor,
    ) -> Result<MoELayer<'network>> {
        check_network!(self, hidden_states);
        check_network!(self, selected_experts_for_tokens);
        check_network!(self, scores_for_selected_experts);
        debug!(
            "add_moe hidden_states={} selected_experts_for_tokens={} scores_for_selected_experts={}",
            tensor_dbg(self, hidden_states),
            tensor_dbg(self, selected_experts_for_tokens),
            tensor_dbg(self, scores_for_selected_experts)
        );
        let layer_ptr = self.inner.pin_mut().addMoE(
            hidden_states.pin_mut(),
            selected_experts_for_tokens.pin_mut(),
            scores_for_selected_experts.pin_mut(),
        );
        MoELayer::new(self.inner.as_ptr(), layer_ptr)
    }

    #[cfg(feature = "v_1_4")]
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addDistCollective`].
    ///
    /// Pass an empty `groups` slice so all ranks participate (`groups == nullptr`, `groupSize == 0` in C++).
    pub fn add_dist_collective(
        &mut self,
        input: &Tensor,
        dist_collective_op: CollectiveOperation,
        reduce_op: ReduceOperation,
        root: i64,
        groups: &[i64],
    ) -> Result<DistCollectiveLayer<'network>> {
        check_network!(self, input);
        debug!(
            "add_dist_collective input={} dist_collective_op={dist_collective_op:?} reduce_op={reduce_op:?} root={root} groups={groups:?}",
            tensor_dbg(self, input)
        );
        let (groups_ptr, group_size) = if groups.is_empty() {
            (std::ptr::null_mut(), 0i64)
        } else {
            (groups.as_ptr() as *mut i64, groups.len() as i64)
        };
        let layer_ptr = unsafe {
            self.inner.pin_mut().addDistCollective(
                input.pin_mut(),
                dist_collective_op.into(),
                reduce_op.into(),
                root,
                groups_ptr,
                group_size,
            )
        };
        DistCollectiveLayer::new(self.inner.as_ptr(), layer_ptr)
    }
}

// --- Network input/output iterators ---

/// Iterator over a [`NetworkDefinition`]'s input tensors. Created by [`NetworkDefinition::inputs`].
#[derive(Debug)]
pub struct NetworkInputIter<'a, 'network> {
    network: &'a NetworkDefinition<'network>,
    index: i32,
    count: i32,
}

impl<'network> Iterator for NetworkInputIter<'_, 'network> {
    type Item = Tensor<'network>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.count {
            return None;
        }
        let tensor = self.network.input(self.index).expect("valid input index");
        self.index += 1;
        Some(tensor)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = (self.count - self.index).max(0) as usize;
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for NetworkInputIter<'_, '_> {}

/// Iterator over a [`NetworkDefinition`]'s output tensors. Created by [`NetworkDefinition::outputs`].
#[derive(Debug)]
pub struct NetworkOutputIter<'a, 'network> {
    network: &'a NetworkDefinition<'network>,
    index: i32,
    count: i32,
}

impl<'network> Iterator for NetworkOutputIter<'_, 'network> {
    type Item = Tensor<'network>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.count {
            return None;
        }
        let tensor = self.network.output(self.index).expect("valid output index");
        self.index += 1;
        Some(tensor)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = (self.count - self.index).max(0) as usize;
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for NetworkOutputIter<'_, '_> {}

/// Iterator over a [`NetworkDefinition`]'s layers. Created by [`NetworkDefinition::layers`].
#[derive(Debug)]
pub struct NetworkLayerIter<'a, 'network> {
    network: &'a NetworkDefinition<'network>,
    index: i32,
    count: i32,
}

impl<'network> Iterator for NetworkLayerIter<'_, 'network> {
    type Item = DynLayer<'network>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.count {
            return None;
        }
        let layer = self.network.layer(self.index).expect("valid layer index");
        self.index += 1;
        Some(layer)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = (self.count - self.index).max(0) as usize;
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for NetworkLayerIter<'_, '_> {}

// --- IAttention ---

impl<'network> Attention<'network> {
    /// See [`trtx_sys::nvinfer1::IAttention::setNormalizationOperation`].
    pub fn set_normalization_operation(
        &mut self,
        network: &mut NetworkDefinition,
        op: trtx_sys::AttentionNormalizationOp,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setNormalizationOperation(op.into())
            .ok_or_err(PropertySetAttempt::AttentionLayerNormalizationOp)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getNormalizationOperation`].
    pub fn normalization_operation(
        &self,
        network: &NetworkDefinition,
    ) -> trtx_sys::AttentionNormalizationOp {
        check_network!(network, self);
        self.inner.getNormalizationOperation().into()
    }

    /// See [`trtx_sys::nvinfer1::IAttention::setMask`].
    pub fn set_mask(&mut self, network: &mut NetworkDefinition, mask: &Tensor) -> Result<()> {
        check_network!(network, self);
        check_network!(network, mask);
        self.inner
            .as_mut()
            .setMask(mask.pin_mut())
            .ok_or_err(PropertySetAttempt::AttentionLayerMask)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getMask`]. Returns [`None`] if no mask is set.
    ///
    /// Note: C++ exposes `getMask` as a non-`const` method; this wrapper takes `&mut self` accordingly.
    pub fn mask(&mut self, network: &mut NetworkDefinition) -> Option<Tensor<'network>> {
        check_network!(network, self);
        let p = self.inner.as_mut().getMask();
        if p.is_null() {
            None
        } else {
            unsafe { Tensor::new(self.network, p).ok() }
        }
    }

    /// See [`trtx_sys::nvinfer1::IAttention::setCausal`].
    pub fn set_causal(&mut self, network: &mut NetworkDefinition, is_causal: bool) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setCausal(is_causal)
            .ok_or_err(PropertySetAttempt::AttentionLayerCausal)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getCausal`].
    pub fn causal(&self, network: &NetworkDefinition) -> bool {
        check_network!(network, self);
        self.inner.getCausal()
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IAttention::setCausalKind`].
    pub fn set_causal_kind(
        &mut self,
        network: &mut NetworkDefinition,
        kind: CausalMaskKind,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setCausalKind(kind.into())
            .ok_or_err(PropertySetAttempt::AttentionLayerCausalKind)
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IAttention::getCausalKind`].
    pub fn causal_kind(&self, network: &NetworkDefinition) -> CausalMaskKind {
        check_network!(network, self);
        self.inner.getCausalKind().into()
    }

    /// See [`trtx_sys::nvinfer1::IAttention::setDecomposable`].
    pub fn set_decomposable(
        &mut self,
        network: &mut NetworkDefinition,
        decomposable: bool,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setDecomposable(decomposable)
            .ok_or_err(PropertySetAttempt::AttentionLayerDecomposable)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getDecomposable`].
    pub fn decomposable(&self, network: &NetworkDefinition) -> bool {
        check_network!(network, self);
        self.inner.getDecomposable()
    }

    /// See [`trtx_sys::nvinfer1::IAttention::setInput`].
    pub fn set_input(
        &mut self,
        network: &mut NetworkDefinition,
        index: i32,
        input: &Tensor,
    ) -> Result<()> {
        check_network!(network, self);
        check_network!(network, input);
        self.inner
            .as_mut()
            .setInput(index, input.pin_mut())
            .ok_or_err(PropertySetAttempt::AttentionLayerInput)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getNbInputs`].
    pub fn num_inputs(&self, network: &NetworkDefinition) -> i32 {
        check_network!(network, self);
        self.inner.getNbInputs()
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getInput`].
    pub fn input(&self, network: &NetworkDefinition, index: i32) -> Result<Tensor<'network>> {
        check_network!(network, self);
        let tensor_ptr = self.inner.getInput(index);
        unsafe { Tensor::new(self.network, tensor_ptr) }
    }

    #[deprecated = "use input instead"]
    pub fn get_input(&self, network: &NetworkDefinition, index: i32) -> Result<Tensor<'network>> {
        self.input(network, index)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getNbOutputs`].
    pub fn num_outputs(&self, network: &NetworkDefinition) -> i32 {
        check_network!(network, self);
        self.inner.getNbOutputs()
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getOutput`]. IAttention has one output (index 0).
    pub fn output(&self, network: &NetworkDefinition, index: i32) -> Result<Tensor<'network>> {
        check_network!(network, self);
        let tensor_ptr = self.inner.getOutput(index);
        unsafe { Tensor::new(self.network, tensor_ptr) }
    }

    #[deprecated = "use output instead"]
    pub fn get_output(&self, network: &NetworkDefinition, index: i32) -> Result<Tensor<'network>> {
        self.output(network, index)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::setName`].
    ///
    /// The C++ API requires a null-terminated name of at most 4096 bytes including the terminator.
    pub fn set_name(&mut self, network: &mut NetworkDefinition, name: &str) -> Result<()> {
        check_network!(network, self);
        let name = CString::new(name)?;
        unsafe { self.inner.as_mut().setName(name.as_ptr()) }
            .ok_or_err(PropertySetAttempt::AttentionLayerName)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getName`].
    pub fn name(&self, network: &NetworkDefinition) -> String {
        check_network!(network, self);
        let name = self.inner.getName();
        if name.is_null() {
            "(unamed)".to_string()
        } else {
            unsafe { CStr::from_ptr(name).to_string_lossy().to_string() }
        }
    }

    /// See [`trtx_sys::nvinfer1::IAttention::setNormalizationQuantizeScale`].
    pub fn set_normalization_quantize_scale(
        &mut self,
        network: &mut NetworkDefinition,
        tensor: &Tensor,
    ) -> Result<()> {
        check_network!(network, self);
        check_network!(network, tensor);
        self.inner
            .as_mut()
            .setNormalizationQuantizeScale(tensor.pin_mut())
            .ok_or_err(PropertySetAttempt::AttentionLayerQuantizeScale)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getNormalizationQuantizeScale`].
    pub fn normalization_quantize_scale(
        &self,
        network: &NetworkDefinition,
    ) -> Option<Tensor<'network>> {
        check_network!(network, self);
        let p = self.inner.getNormalizationQuantizeScale();
        if p.is_null() {
            None
        } else {
            unsafe { Tensor::new(self.network, p).ok() }
        }
    }

    /// See [`trtx_sys::nvinfer1::IAttention::setNormalizationQuantizeToType`].
    pub fn set_normalization_quantize_to_type(
        &mut self,
        network: &mut NetworkDefinition,
        type_: DataType,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setNormalizationQuantizeToType(type_.into())
            .ok_or_err(PropertySetAttempt::AttentionLayerQuantizeToType)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getNormalizationQuantizeToType`].
    pub fn normalization_quantize_to_type(&self, network: &NetworkDefinition) -> DataType {
        check_network!(network, self);
        self.inner.getNormalizationQuantizeToType().into()
    }

    #[deprecated = "use normalization_quantize_to_type instead"]
    pub fn get_normalization_quantize_to_type(&self, network: &NetworkDefinition) -> DataType {
        self.normalization_quantize_to_type(network)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::setMetadata`].
    pub fn set_metadata(&mut self, network: &mut NetworkDefinition, metadata: &str) -> Result<()> {
        check_network!(network, self);
        let metadata_cstr = CString::new(metadata)?;
        unsafe { self.inner.as_mut().setMetadata(metadata_cstr.as_ptr()) }
            .ok_or_err(PropertySetAttempt::AttentionLayerMetadata)
    }

    /// See [`trtx_sys::nvinfer1::IAttention::getMetadata`].
    pub fn metadata(&self, network: &NetworkDefinition) -> String {
        check_network!(network, self);
        let p = self.inner.getMetadata();
        if p.is_null() {
            String::new()
        } else {
            unsafe { CStr::from_ptr(p).to_string_lossy().to_string() }
        }
    }

    #[cfg(feature = "v_1_4")]
    /// See [`trtx_sys::nvinfer1::IAttention::setNbRanks`].
    pub fn set_nb_ranks(&mut self, network: &mut NetworkDefinition, nb_ranks: i32) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setNbRanks(nb_ranks)
            .ok_or_err(PropertySetAttempt::AttentionLayerNumRanks)
    }

    #[cfg(feature = "v_1_4")]
    /// See [`trtx_sys::nvinfer1::IAttention::getNbRanks`].
    pub fn nb_ranks(&self, network: &NetworkDefinition) -> i32 {
        check_network!(network, self);
        self.inner.getNbRanks()
    }

    #[deprecated = "use nb_ranks instead"]
    pub fn get_nb_ranks(&self, network: &NetworkDefinition) -> i32 {
        self.nb_ranks(network)
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IAttention::setQueryForm`].
    pub fn set_query_form(
        &mut self,
        network: &mut NetworkDefinition,
        form: AttentionIOForm,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setQueryForm(form.into())
            .ok_or_err(PropertySetAttempt::AttentionLayerQueryForm)
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IAttention::setKeyValueForm`].
    pub fn set_key_value_form(
        &mut self,
        network: &mut NetworkDefinition,
        form: AttentionIOForm,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setKeyValueForm(form.into())
            .ok_or_err(PropertySetAttempt::AttentionLayerKeyValueForm)
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IAttention::getQueryForm`].
    pub fn query_form(&self, network: &NetworkDefinition) -> AttentionIOForm {
        check_network!(network, self);
        self.inner.getQueryForm().into()
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IAttention::setKeyValueForm`].
    pub fn key_value_form(&self, network: &NetworkDefinition) -> AttentionIOForm {
        check_network!(network, self);
        self.inner.getQueryForm().into()
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IAttention::getQueryLengths`].
    pub fn query_lengths(&self, network: &NetworkDefinition) -> Result<Tensor<'network>> {
        check_network!(network, self);
        unsafe { Tensor::new(self.network, self.inner.getQueryLengths()) }
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IAttention::getKeyValueLengths`].
    pub fn key_value_lengths(&self, network: &NetworkDefinition) -> Result<Tensor<'network>> {
        check_network!(network, self);
        unsafe { Tensor::new(self.network, self.inner.getKeyValueLengths()) }
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IAttention::setQueryLengths`].
    pub fn set_query_lengths(
        &mut self,
        network: &mut NetworkDefinition,
        lengths: &'_ Tensor,
    ) -> Result<()> {
        check_network!(network, self);
        check_network!(network, lengths);
        unsafe {
            self.inner
                .as_mut()
                .setQueryLengths(lengths.inner)
                .ok_or_err(PropertySetAttempt::AttentionLayerQueryLengths)
        }
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IAttention::setKeyValueLengths`].
    pub fn set_key_value_lengths(
        &mut self,
        network: &mut NetworkDefinition,
        lengths: &'_ Tensor,
    ) -> Result<()> {
        check_network!(network, self);
        check_network!(network, lengths);
        unsafe {
            self.inner
                .as_mut()
                .setKeyValueLengths(lengths.inner)
                .ok_or_err(PropertySetAttempt::AttentionLayerKeyValueLengths)
        }
    }
}

impl<'network> KVCacheUpdateLayer<'network> {
    /// See [`trtx_sys::nvinfer1::IKVCacheUpdateLayer::setCacheMode`].
    pub fn set_cache_mode(
        &mut self,
        network: &mut NetworkDefinition,
        mode: KVCacheMode,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setCacheMode(mode.into())
            .ok_or_err(PropertySetAttempt::KVCacheUpdateMode)
    }

    /// See [`trtx_sys::nvinfer1::IKVCacheUpdateLayer::getCacheMode`].
    pub fn cache_mode(&self, network: &NetworkDefinition) -> KVCacheMode {
        check_network!(network, self);
        self.inner.getCacheMode().into()
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IKVCacheUpdateLayer::setUpdateForm`].
    pub fn set_update_form(
        &mut self,
        network: &mut NetworkDefinition,
        form: AttentionIOForm,
    ) -> Result<()> {
        check_network!(network, self);
        self.inner
            .as_mut()
            .setUpdateForm(form.into())
            .ok_or_err(PropertySetAttempt::KVCacheUpdateUpdateForm)
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IKVCacheUpdateLayer::setUpdateForm`].
    pub fn update_form(&self, network: &NetworkDefinition) -> AttentionIOForm {
        check_network!(network, self);
        self.inner.getUpdateForm().into()
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IKVCacheUpdateLayer::setUpdateLengths`].
    pub fn set_update_lengths(
        &mut self,
        network: &mut NetworkDefinition,
        lengths: &Tensor,
    ) -> Result<()> {
        check_network!(network, self);
        check_network!(network, lengths);
        unsafe {
            self.inner
                .as_mut()
                .setUpdateLengths(lengths.inner)
                .ok_or_err(PropertySetAttempt::KVCacheUpdateLayerUpdateLengths)
        }
    }

    #[cfg(feature = "v_1_5")]
    /// See [`trtx_sys::nvinfer1::IKVCacheUpdateLayer::getUpdateLengths`].
    pub fn update_lengths(&self, network: &NetworkDefinition) -> Result<Tensor<'network>> {
        check_network!(network, self);
        unsafe { Tensor::new(self.network, self.inner.getUpdateLengths()) }
    }
}

// --- Loop boundary layers (ILoop::addRecurrence, addTripLimit, addIterator, addLoopOutput) ---

impl<'network> Loop<'network> {
    /// See [`trtx_sys::nvinfer1::ILoop::addRecurrence`].
    pub fn add_recurrence(
        &mut self,
        network: &mut NetworkDefinition,
        initial_value: &'_ Tensor,
    ) -> Result<RecurrenceLayer<'network>> {
        check_network!(network, self);
        check_network!(network, initial_value);
        debug!(
            "Loop::add_recurrence initial_value={}",
            tensor_dbg(network, initial_value)
        );
        let layer_ptr = { self.inner.as_mut().addRecurrence(initial_value.pin_mut()) };
        RecurrenceLayer::new(network.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::ILoop::addTripLimit`].
    pub fn add_trip_limit(
        &mut self,
        network: &mut NetworkDefinition,
        tensor: &'_ Tensor,
        limit: trtx_sys::TripLimit,
    ) -> Result<TripLimitLayer<'network>> {
        check_network!(network, self);
        check_network!(network, tensor);
        debug!(
            "Loop::add_trip_limit tensor={} limit={limit:?}",
            tensor_dbg(network, tensor)
        );
        let layer_ptr = {
            self.inner
                .as_mut()
                .addTripLimit(tensor.pin_mut(), limit.into())
        };
        TripLimitLayer::new(network.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::ILoop::addIterator`].
    pub fn add_iterator(
        &mut self,
        network: &mut NetworkDefinition,
        tensor: &'_ Tensor,
        axis: i32,
        reverse: bool,
    ) -> Result<IteratorLayer<'network>> {
        check_network!(network, self);
        check_network!(network, tensor);
        debug!(
            "Loop::add_iterator tensor={} axis={axis} reverse={reverse}",
            tensor_dbg(network, tensor)
        );
        let layer_ptr = {
            self.inner
                .as_mut()
                .addIterator(tensor.pin_mut(), axis, reverse)
        };
        IteratorLayer::new(network.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::ILoop::addLoopOutput`].
    pub fn add_loop_output(
        &mut self,
        network: &mut NetworkDefinition,
        tensor: &'_ Tensor,
        output_kind: trtx_sys::LoopOutput,
        axis: i32,
    ) -> Result<LoopOutputLayer<'network>> {
        check_network!(network, self);
        check_network!(network, tensor);
        debug!(
            "Loop::add_loop_output tensor={} output_kind={output_kind:?} axis={axis}",
            tensor_dbg(network, tensor)
        );
        let layer_ptr =
            self.inner
                .as_mut()
                .addLoopOutput(tensor.pin_mut(), output_kind.into(), axis);
        LoopOutputLayer::new(network.inner.as_ptr(), layer_ptr)
    }
}

// --- IfConditional boundary layers (IIfConditional::setCondition, addInput, addOutput) ---

impl<'network> IfConditional<'network> {
    /// See [`trtx_sys::nvinfer1::IIfConditional::setCondition`].
    pub fn set_condition(
        &mut self,
        network: &mut NetworkDefinition,
        condition: &'_ Tensor,
    ) -> Result<ConditionLayer<'network>> {
        check_network!(network, self);
        check_network!(network, condition);
        let layer_ptr = self.inner.as_mut().setCondition(condition.pin_mut());
        ConditionLayer::new(network.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::IIfConditional::addInput`].
    pub fn add_input(
        &mut self,
        network: &mut NetworkDefinition,
        input: &'_ Tensor,
    ) -> Result<IfConditionalInputLayer<'network>> {
        check_network!(network, self);
        check_network!(network, input);
        debug!(
            "IfConditional::add_input input={}",
            tensor_dbg(network, input)
        );
        let layer_ptr = self.inner.as_mut().addInput(input.pin_mut());
        IfConditionalInputLayer::new(network.inner.as_ptr(), layer_ptr)
    }

    /// See [`trtx_sys::nvinfer1::IIfConditional::addOutput`].
    pub fn add_output(
        &mut self,
        network: &mut NetworkDefinition,
        true_output: &'_ Tensor,
        false_output: &'_ Tensor,
    ) -> Result<IfConditionalOutputLayer<'network>> {
        check_network!(network, self);
        check_network!(network, true_output);
        check_network!(network, false_output);
        debug!(
            "IfConditional::add_output true_output={} false_output={}",
            tensor_dbg(network, true_output),
            tensor_dbg(network, false_output)
        );
        let layer_ptr = self
            .inner
            .as_mut()
            .addOutput(true_output.pin_mut(), false_output.pin_mut());
        IfConditionalOutputLayer::new(network.inner.as_ptr(), layer_ptr)
    }
}

// --- RecurrenceLayer: set_input(1, tensor) for value from inside loop ---

/// See [`trtx_sys::nvinfer1::IRecurrenceLayer`]. Input 0 = initial value (set at creation); input 1 = value from previous iteration (from inside loop).
impl<'network> RecurrenceLayer<'network> {}

// --- IteratorLayer: set_axis, set_reverse ---

impl IteratorLayer<'_> {
    /// See [`trtx_sys::nvinfer1::IIteratorLayer::setAxis`].
    pub fn set_axis(&mut self, network: &mut NetworkDefinition, axis: i32) {
        check_network!(network, self);
        self.inner.as_mut().setAxis(axis);
    }
    /// See [`trtx_sys::nvinfer1::IIteratorLayer::setReverse`].
    pub fn set_reverse(&mut self, network: &mut NetworkDefinition, reverse: bool) {
        check_network!(network, self);
        self.inner.as_mut().setReverse(reverse);
    }
}

// --- LoopOutputLayer: get_loop_output, set_axis (for concatenation), set_input for index 1 ---

impl LoopOutputLayer<'_> {
    /// See [`trtx_sys::nvinfer1::ILoopOutputLayer::getLoopOutput`].
    pub fn loop_output(&self, network: &NetworkDefinition) -> trtx_sys::nvinfer1::LoopOutput {
        check_network!(network, self);
        self.inner.as_ref().getLoopOutput()
    }

    #[deprecated = "use loop_output instead"]
    pub fn get_loop_output(&self, network: &NetworkDefinition) -> trtx_sys::nvinfer1::LoopOutput {
        self.loop_output(network)
    }
    /// See [`trtx_sys::nvinfer1::ILoopOutputLayer::setAxis`]. Ignored if output kind is kLAST_VALUE.
    pub fn set_axis(&mut self, network: &mut NetworkDefinition, axis: i32) {
        check_network!(network, self);
        self.inner.as_mut().setAxis(axis);
    }
}

// --- TripLimitLayer: get_trip_limit (getter only) ---

impl TripLimitLayer<'_> {
    /// See [`trtx_sys::nvinfer1::ITripLimitLayer::getTripLimit`].
    pub fn trip_limit(&self, network: &NetworkDefinition) -> trtx_sys::nvinfer1::TripLimit {
        check_network!(network, self);
        self.inner.as_ref().getTripLimit()
    }

    #[deprecated = "use trip_limit instead"]
    pub fn get_trip_limit(&self, network: &NetworkDefinition) -> trtx_sys::nvinfer1::TripLimit {
        self.trip_limit(network)
    }
}

impl<'builder> NetworkDefinition<'builder> {
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addNormalization`].
    pub fn add_normalization(
        &mut self,
        input: &'_ Tensor,
        scale: &'_ Tensor,
        bias: &'_ Tensor,
        axes_mask: crate::Axes,
    ) -> Result<NormalizationLayer<'builder>> {
        check_network!(self, input);
        check_network!(self, scale);
        check_network!(self, bias);
        debug!(
            "add_normalization input={} scale={} bias={} axes_mask={axes_mask:?}",
            tensor_dbg(self, input),
            tensor_dbg(self, scale),
            tensor_dbg(self, bias)
        );
        let axes_bits = axes_mask.to_bits();
        let ptr = self.inner.pin_mut().addNormalization(
            input.pin_mut(),
            scale.pin_mut(),
            bias.pin_mut(),
            axes_bits,
        );
        NormalizationLayer::new(self.inner.as_ptr(), ptr)
    }
    /// See [`trtx_sys::nvinfer1::INetworkDefinition::addNormalizationV2`].
    pub fn add_normalization_v2(
        &mut self,
        input: &'_ Tensor,
        scale: &'_ Tensor,
        bias: &'_ Tensor,
        axes_mask: crate::Axes,
    ) -> Result<NormalizationLayer<'builder>> {
        check_network!(self, input);
        check_network!(self, scale);
        check_network!(self, bias);
        debug!(
            "add_normalization_v2 input={} scale={} bias={} axes_mask={axes_mask:?}",
            tensor_dbg(self, input),
            tensor_dbg(self, scale),
            tensor_dbg(self, bias)
        );
        let axes_bits = axes_mask.to_bits();
        let ptr = self.inner.pin_mut().addNormalizationV2(
            input.pin_mut(),
            scale.pin_mut(),
            bias.pin_mut(),
            axes_bits,
        );
        NormalizationLayer::new(self.inner.as_ptr(), ptr)
    }

    /// See [y nvinfer1::INetworkDefinition::setErrorRecorder]
    ///
    /// The Rust bindings only allow setting the error recorder once
    pub fn set_error_recorder(&mut self, error_recorder: Box<dyn RecordError>) -> Result<()> {
        let error_recorder = ErrorRecorder::new(error_recorder)?;
        if self.error_recorder.is_some() {
            // would need to make sure that we don't destroy a monitor still in use
            // could offer this as an unsafe method for users who only set this when there is no
            // build process active. Or we only accept a ref to progress monitor and force user
            // via lifetimes to keep this alive for builder config lifetime
            panic!("Setting a progress monitor more than once not supported at the moment");
        }
        self.error_recorder = Some(error_recorder);
        let rec = self
            .error_recorder
            .as_mut()
            .unwrap()
            .as_trt_error_recorder();
        #[cfg(not(feature = "mock"))]
        unsafe {
            self.inner.pin_mut().setErrorRecorder(rec)
        };
        Ok(())
    }

    pub fn add_grid_sample(
        &mut self,
        input: &'_ Tensor,
        grid: &'_ Tensor,
    ) -> Result<GridSampleLayer<'builder>> {
        check_network!(self, input);
        check_network!(self, grid);

        let ptr = self
            .inner
            .pin_mut()
            .addGridSample(input.pin_mut(), grid.pin_mut());
        GridSampleLayer::new(self.inner.as_ptr(), ptr)
    }
}

impl<'network> GridSampleLayer<'network> {
    /// See [nvinfer1::IGridSampleLayer::setInterpolationMode]
    pub fn set_interpolation_mode(
        &mut self,
        network: &mut NetworkDefinition,
        mode: InterpolationMode,
    ) {
        check_network!(network, self);
        self.inner.as_mut().setInterpolationMode(mode.into());
    }
    /// See [nvinfer1::IGridSampleLayer::getInterpolationMode]
    pub fn interpolation_mode(&self, network: &NetworkDefinition) -> InterpolationMode {
        check_network!(network, self);
        self.inner.getInterpolationMode().into()
    }
    /// See [nvinfer1::IGridSampleLayer::setSampleMode]
    pub fn set_sample_mode(&mut self, network: &mut NetworkDefinition, mode: SampleMode) {
        check_network!(network, self);
        self.inner.as_mut().setSampleMode(mode.into());
    }
    /// See [nvinfer1::IGridSampleLayer::getSampleMode]
    pub fn sample_mode(&self, network: &NetworkDefinition) -> SampleMode {
        check_network!(network, self);
        self.inner.getSampleMode().into()
    }
    /// See [nvinfer1::IGridSampleLayer::setAlignCorners]
    pub fn set_align_corners(&mut self, network: &mut NetworkDefinition, align_corners: bool) {
        check_network!(network, self);
        self.inner.as_mut().setAlignCorners(align_corners);
    }
    /// See [nvinfer1::IGridSampleLayer::getAlignCorners]
    pub fn align_corners(&self, network: &NetworkDefinition) -> bool {
        check_network!(network, self);
        self.inner.getAlignCorners()
    }
}

impl<'network> CastLayer<'network> {
    /// See [nvinfer1::ICastLayer::setToType]
    pub fn set_to_type(&mut self, network: &mut NetworkDefinition<'_>, data_type: DataType) {
        check_network!(network, self);
        self.inner.as_mut().setToType(data_type.into())
    }

    /// See [nvinfer1::ICastLayer::getToType]
    pub fn to_type(&self, network: &NetworkDefinition<'_>) -> DataType {
        check_network!(network, self);
        self.inner.getToType().into()
    }
}

#[cfg(test)]
mod test {
    use trtx_sys::LayerType;

    use crate::{Builder, Logger};

    #[test]
    #[cfg(not(feature = "mock"))]
    fn test_get_layer() {
        let logger = Logger::stderr().unwrap();
        let mut builder = Builder::new(&logger).unwrap();
        let mut network = builder.create_network(0).unwrap();
        let input = network
            .add_input("a", trtx_sys::DataType::kFLOAT, &[1])
            .unwrap();
        let a = network
            .add_activation(&input, trtx_sys::ActivationType::kRELU)
            .unwrap()
            .output(&network, 0)
            .unwrap();
        let b = network
            .add_activation(&a, trtx_sys::ActivationType::kRELU)
            .unwrap()
            .output(&network, 0)
            .unwrap();
        let c = network
            .add_activation(&b, trtx_sys::ActivationType::kRELU)
            .unwrap()
            .output(&network, 0)
            .unwrap();
        a.set_name(&mut network, "Fritz").unwrap();
        b.set_name(&mut network, "Adam").unwrap();
        c.set_name(&mut network, "James").unwrap();

        assert_eq!(
            &network
                .layer(0)
                .unwrap()
                .output(&network, 0)
                .unwrap()
                .name(&network)
                .unwrap(),
            "Fritz"
        );
        assert_eq!(
            &network
                .layer(1)
                .unwrap()
                .output(&network, 0)
                .unwrap()
                .name(&network)
                .unwrap(),
            "Adam"
        );
        assert_eq!(
            &network
                .layer(2)
                .unwrap()
                .output(&network, 0)
                .unwrap()
                .name(&network)
                .unwrap(),
            "James"
        );
        assert_eq!(
            network.layer(2).unwrap().layer_type_dynamic(),
            LayerType::kACTIVATION
        );
        network
            .layer(1)
            .unwrap()
            .set_name(&mut network, "Eva")
            .unwrap();
        assert_eq!(
            &network
                .layer(1)
                .unwrap()
                .output(&network, 0)
                .unwrap()
                .name(&network)
                .unwrap(),
            &network
                .layer(2)
                .unwrap()
                .input(&network, 0)
                .unwrap()
                .name(&network)
                .unwrap(),
        );
        assert_eq!(
            "Adam",
            &network
                .layer(2)
                .unwrap()
                .input(&network, 0)
                .unwrap()
                .name(&network)
                .unwrap()
        );
        assert_eq!(&network.layer(1).unwrap().name(&network), "Eva");
    }

    #[test]
    #[cfg(not(feature = "mock"))]
    fn test_inputs_outputs_iter() {
        let logger = Logger::stderr().unwrap();
        let mut builder = Builder::new(&logger).unwrap();
        let mut network = builder.create_network(0).unwrap();
        let a = network
            .add_input("input_a", trtx_sys::DataType::kFLOAT, &[1])
            .unwrap();
        let b = network
            .add_input("input_b", trtx_sys::DataType::kFLOAT, &[1])
            .unwrap();
        let out = network
            .add_elementwise(&a, &b, trtx_sys::ElementWiseOperation::kSUM)
            .unwrap()
            .output(&network, 0)
            .unwrap();
        out.set_name(&mut network, "output_c").unwrap();
        network.mark_output(&out);

        let input_names: Vec<_> = network
            .inputs()
            .map(|t| t.name(&network).unwrap())
            .collect();
        assert_eq!(input_names, ["input_a", "input_b"]);
        assert_eq!(network.inputs().len(), 2);

        let output_names: Vec<_> = network
            .outputs()
            .map(|t| t.name(&network).unwrap())
            .collect();
        assert_eq!(output_names, ["output_c"]);
        assert_eq!(network.outputs().len(), 1);

        // equivalent to the old loop pattern
        let mut old_style = Vec::new();
        for i in 0..network.nb_inputs() {
            old_style.push(network.input(i).unwrap().name(&network).unwrap());
        }
        assert_eq!(input_names, old_style);
    }

    #[test]
    #[cfg(not(feature = "mock"))]
    fn test_layers_iter() {
        use trtx_sys::LayerType;

        let logger = Logger::stderr().unwrap();
        let mut builder = Builder::new(&logger).unwrap();
        let mut network = builder.create_network(0).unwrap();
        let input = network
            .add_input("a", trtx_sys::DataType::kFLOAT, &[1])
            .unwrap();
        network
            .add_activation(&input, trtx_sys::ActivationType::kRELU)
            .unwrap();
        network
            .add_activation(&input, trtx_sys::ActivationType::kSIGMOID)
            .unwrap();

        assert_eq!(network.layers().len(), 2);
        let types: Vec<_> = network.layers().map(|l| l.layer_type_dynamic()).collect();
        assert_eq!(types, [LayerType::kACTIVATION, LayerType::kACTIVATION]);
    }
}