treeboost 0.1.0

High-performance Gradient Boosted Decision Tree engine for large-scale tabular data
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
//! GPU kernel dispatch for histogram building.
//!
//! Manages compute pipelines, buffer allocation, and kernel execution
//! for GPU-accelerated GBDT histogram construction.
//!
//! # Fixed-Point Gradient Accumulation
//!
//! This module uses fixed-point i32 arithmetic for gradient/hessian accumulation
//! to avoid expensive CAS loops. The optimization works as follows:
//!
//! 1. CPU quantizes f32 gradients/hessians to i32 (multiply by FIXED_POINT_SCALE)
//! 2. GPU uses native i32 atomicAdd (no CAS loops!)
//! 3. CPU dequantizes results (divide by FIXED_POINT_SCALE)
//!
//! This gives ~2-3x faster histogram building vs CAS loops for f32 atomics.
//!
//! # Sparse Feature Support
//!
//! For features with >90% sparsity, uses specialized sparse kernel:
//! - Only processes non-default entries
//! - Uses default-bin subtraction trick for correctness
//! - Up to 10x faster than dense kernel on highly sparse data

use super::device::GpuDevice;
use crate::histogram::Histogram;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use wgpu::{BindGroupDescriptor, BindGroupEntry, BindGroupLayout, Buffer, ComputePipeline};

/// Fixed-point scale factor for gradient/hessian quantization.
/// Using 2^10 (1024) allows values up to ±31.99 with ~0.001 precision.
/// This fits in i16 range while maintaining sufficient accuracy for GBDT.
/// Gradients are packed as i16 pairs in u32 for 2x bandwidth reduction.
const FIXED_POINT_SCALE: f32 = 1024.0; // 2^10
const FIXED_POINT_SCALE_INV: f32 = 1.0 / 1024.0;

/// Detailed timing breakdown for GPU histogram building.
/// All times are in seconds.
#[derive(Debug, Clone, Default)]
pub struct GpuProfileData {
    /// CPU: Convert indices to u32
    pub indices_convert: Duration,
    /// CPU: Check bins alignment / pack to u32
    pub bins_pack: Duration,
    /// GPU: Ensure buffers are allocated (may include allocation)
    pub buffer_alloc: Duration,
    /// GPU: Upload params to uniform buffer
    pub upload_params: Duration,
    /// GPU: Upload bins (may be skipped if cached)
    pub upload_bins: Duration,
    /// Whether bins upload was skipped due to caching
    pub bins_cached: bool,
    /// GPU: Upload grad/hess
    pub upload_grad_hess: Duration,
    /// GPU: Upload indices
    pub upload_indices: Duration,
    /// GPU: Create bind groups
    pub bind_group_create: Duration,
    /// GPU: Encode zero pass + histogram pass + copy commands
    pub encode_commands: Duration,
    /// GPU: Submit and wait for completion
    pub gpu_execute: Duration,
    /// GPU: Read staging buffers back to CPU
    pub download_results: Duration,
    /// CPU: Convert raw u32 data to Histogram structs
    pub unpack_histograms: Duration,
    /// Total time for the entire operation
    pub total: Duration,
    /// Number of rows processed
    pub num_rows: usize,
    /// Number of features
    pub num_features: usize,
    /// Number of indices (subset size)
    pub num_indices: usize,
}

/// Parameters passed to histogram shader via uniform buffer.
#[repr(C)]
#[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct HistogramParams {
    pub num_rows: u32,
    pub num_features: u32,
    pub num_indices: u32, // 0 = use all rows (single batch mode)
    pub num_batches: u32, // 0 or 1 = single batch mode, >1 = batched mode
}

/// Batch descriptor for batched histogram building.
/// Describes a contiguous slice of the concatenated row_indices array.
#[repr(C)]
#[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct BatchInfo {
    pub start: u32, // Start offset in row_indices
    pub count: u32, // Number of rows in this batch
}

/// Pooled buffer that tracks capacity for reuse.
struct PooledBuffer {
    buffer: Buffer,
    capacity: u64,
}

/// Cache key for detecting if data has changed (pointer + length).
/// Uses raw pointer address as a fingerprint - if same pointer and length,
/// data hasn't changed and we can skip the upload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CacheKey {
    ptr: usize,
    len: usize,
}

impl CacheKey {
    fn from_slice<T>(slice: &[T]) -> Self {
        Self {
            ptr: slice.as_ptr() as usize,
            len: slice.len(),
        }
    }
}

/// Buffer pool for reusing GPU allocations.
struct BufferPool {
    // Input buffers
    params: Option<Buffer>,
    bins: Option<PooledBuffer>,
    bins_cache_key: Option<CacheKey>, // Track what bins are currently uploaded (stable across training)
    bins_4bit: Option<PooledBuffer>,  // 4-bit packed bins buffer
    bins_4bit_cache_key: Option<CacheKey>,
    grad_hess: Option<PooledBuffer>,
    indices: Option<PooledBuffer>,
    batch_info: Option<PooledBuffer>, // Batch descriptors for batched mode
    era_indices: Option<PooledBuffer>, // Era indices for DES
    era_indices_cache_key: Option<CacheKey>,
    // Output histogram buffers
    hist_grad: Option<PooledBuffer>,
    hist_hess: Option<PooledBuffer>,
    hist_count: Option<PooledBuffer>,
    // Staging buffers for readback
    staging_grad: Option<PooledBuffer>,
    staging_hess: Option<PooledBuffer>,
    staging_count: Option<PooledBuffer>,
}

impl BufferPool {
    fn new() -> Self {
        Self {
            params: None,
            bins: None,
            bins_cache_key: None,
            bins_4bit: None,
            bins_4bit_cache_key: None,
            grad_hess: None,
            indices: None,
            batch_info: None,
            era_indices: None,
            era_indices_cache_key: None,
            hist_grad: None,
            hist_hess: None,
            hist_count: None,
            staging_grad: None,
            staging_hess: None,
            staging_count: None,
        }
    }
}

/// GPU histogram kernel executor.
pub struct HistogramKernel {
    device: Arc<GpuDevice>,
    // Single-batch pipelines (8-bit)
    pipeline_dense: ComputePipeline,
    pipeline_zero: ComputePipeline,
    bind_group_layout_dense: BindGroupLayout,
    bind_group_layout_zero: BindGroupLayout,
    // Batched pipelines (8-bit)
    pipeline_batched: ComputePipeline,
    pipeline_zero_batched: ComputePipeline,
    bind_group_layout_batched: BindGroupLayout,
    // 4-bit bin pipelines (for datasets with max_bins <= 16)
    pipeline_dense_4bit: ComputePipeline,
    pipeline_zero_4bit: ComputePipeline,
    bind_group_layout_dense_4bit: BindGroupLayout,
    // Era histogram pipelines (for Directional Era Splitting)
    pipeline_era: ComputePipeline,
    pipeline_zero_era: ComputePipeline,
    bind_group_layout_era: BindGroupLayout,
    /// Buffer pool for reusing allocations (Mutex for thread safety)
    buffer_pool: Mutex<BufferPool>,
    /// Whether subgroup operations are available on hardware
    subgroups_supported: bool,
    /// Whether to use subgroup operations (default: false)
    /// Set via `set_use_subgroups()`. Only effective if `subgroups_supported` is true.
    use_subgroups: std::sync::atomic::AtomicBool,
    /// Subgroup-optimized pipelines (None if not supported)
    pipeline_dense_subgroups: Option<ComputePipeline>,
    pipeline_batched_subgroups: Option<ComputePipeline>,
    bind_group_layout_dense_subgroups: Option<BindGroupLayout>,
    bind_group_layout_batched_subgroups: Option<BindGroupLayout>,
}

impl HistogramKernel {
    /// Create histogram kernel with compiled shaders.
    pub fn new(device: Arc<GpuDevice>) -> Self {
        // Load shader source
        let shader_source = include_str!("shaders/histogram.wgsl");

        // Create pipelines for each entry point
        let pipeline_dense = device.create_compute_pipeline(
            "histogram_dense_pipeline",
            shader_source,
            "histogram_dense",
        );

        let pipeline_zero = device.create_compute_pipeline(
            "zero_histograms_pipeline",
            shader_source,
            "zero_histograms",
        );

        // Batched pipelines
        let pipeline_batched = device.create_compute_pipeline(
            "histogram_batched_pipeline",
            shader_source,
            "histogram_batched",
        );

        let pipeline_zero_batched = device.create_compute_pipeline(
            "zero_histograms_batched_pipeline",
            shader_source,
            "zero_histograms_batched",
        );

        // Get bind group layouts from each pipeline (they differ in which bindings are used)
        let bind_group_layout_dense = pipeline_dense.get_bind_group_layout(0);
        let bind_group_layout_zero = pipeline_zero.get_bind_group_layout(0);
        let bind_group_layout_batched = pipeline_batched.get_bind_group_layout(0);

        // Create 4-bit pipelines for datasets with small bin counts
        let shader_source_4bit = include_str!("shaders/histogram_4bit.wgsl");

        let pipeline_dense_4bit = device.create_compute_pipeline(
            "histogram_dense_4bit_pipeline",
            shader_source_4bit,
            "histogram_dense_4bit",
        );

        let pipeline_zero_4bit = device.create_compute_pipeline(
            "zero_histograms_4bit_pipeline",
            shader_source_4bit,
            "zero_histograms_4bit",
        );

        let bind_group_layout_dense_4bit = pipeline_dense_4bit.get_bind_group_layout(0);

        // Create era histogram pipelines (for Directional Era Splitting)
        let shader_source_era = include_str!("shaders/histogram_era.wgsl");

        let pipeline_era = device.create_compute_pipeline(
            "histogram_era_pipeline",
            shader_source_era,
            "histogram_era",
        );

        let pipeline_zero_era = device.create_compute_pipeline(
            "zero_histograms_era_pipeline",
            shader_source_era,
            "zero_histograms_era",
        );

        let bind_group_layout_era = pipeline_era.get_bind_group_layout(0);

        // Check for subgroup support and create optimized pipelines if available
        // Note: Even if the device reports SUBGROUP support, the WGSL compiler may not
        // support the `enable subgroups;` extension yet (depends on wgpu/naga version).
        // We try to compile and fall back gracefully if it fails.
        let subgroups_supported = device.subgroups_supported;
        let (
            pipeline_dense_subgroups,
            pipeline_batched_subgroups,
            bind_group_layout_dense_subgroups,
            bind_group_layout_batched_subgroups,
        ) = if subgroups_supported {
            // Try to create subgroup pipelines - may fail if WGSL extension not supported
            let subgroup_shader = include_str!("shaders/histogram_subgroups.wgsl");

            // Use try_create_compute_pipeline which returns Option instead of panicking
            match device.try_create_compute_pipeline(
                "histogram_dense_subgroups_pipeline",
                subgroup_shader,
                "histogram_dense_subgroups",
            ) {
                Some(dense_sg) => {
                    // Dense succeeded, try batched
                    match device.try_create_compute_pipeline(
                        "histogram_batched_subgroups_pipeline",
                        subgroup_shader,
                        "histogram_batched_subgroups",
                    ) {
                        Some(batched_sg) => {
                            let layout_dense_sg = dense_sg.get_bind_group_layout(0);
                            let layout_batched_sg = batched_sg.get_bind_group_layout(0);
                            (
                                Some(dense_sg),
                                Some(batched_sg),
                                Some(layout_dense_sg),
                                Some(layout_batched_sg),
                            )
                        }
                        None => (None, None, None, None),
                    }
                }
                None => (None, None, None, None),
            }
        } else {
            (None, None, None, None)
        };

        // Update subgroups_supported based on whether we actually got working pipelines
        let subgroups_supported = pipeline_dense_subgroups.is_some();

        Self {
            device,
            pipeline_dense,
            pipeline_zero,
            bind_group_layout_dense,
            bind_group_layout_zero,
            pipeline_batched,
            pipeline_zero_batched,
            bind_group_layout_batched,
            pipeline_dense_4bit,
            pipeline_zero_4bit,
            bind_group_layout_dense_4bit,
            pipeline_era,
            pipeline_zero_era,
            bind_group_layout_era,
            buffer_pool: Mutex::new(BufferPool::new()),
            subgroups_supported,
            use_subgroups: std::sync::atomic::AtomicBool::new(false), // Disabled by default
            pipeline_dense_subgroups,
            pipeline_batched_subgroups,
            bind_group_layout_dense_subgroups,
            bind_group_layout_batched_subgroups,
        }
    }

    /// Returns true if subgroup operations are supported by the hardware.
    pub fn subgroups_available(&self) -> bool {
        self.subgroups_supported
    }

    /// Returns true if subgroup operations are enabled and will be used.
    pub fn has_subgroups(&self) -> bool {
        self.subgroups_supported
            && self
                .use_subgroups
                .load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Enable or disable subgroup operations.
    ///
    /// Subgroups are disabled by default. Enable them if you want to test
    /// whether they provide benefit on your hardware.
    ///
    /// Note: Has no effect if hardware doesn't support subgroups.
    pub fn set_use_subgroups(&self, enabled: bool) {
        self.use_subgroups
            .store(enabled, std::sync::atomic::Ordering::Relaxed);
    }

    /// Build histograms using the base shader (no subgroups).
    ///
    /// This is primarily for benchmarking to compare subgroup vs non-subgroup performance.
    /// The implementation duplicates `build_histograms` but forces the base pipeline.
    pub fn build_histograms_base_shader(
        &self,
        bins_row_major: &[u8],
        grad_hess: &[(f32, f32)],
        row_indices: &[usize],
        num_rows: usize,
        num_features: usize,
    ) -> Vec<Histogram> {
        // This is a copy of build_histograms but forces the base pipeline
        // (Could be refactored to share code, but keeping separate for clarity)
        let dev = &self.device;

        let grad_hess_packed: Vec<u32> = grad_hess
            .iter()
            .map(|(g, h)| {
                let grad_i16 = ((*g * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                let hess_i16 = ((*h * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                (grad_i16 as u16 as u32) | ((hess_i16 as u16 as u32) << 16)
            })
            .collect();

        let indices_u32: Vec<u32> = row_indices.iter().map(|&i| i as u32).collect();

        let bins_aligned = bins_row_major.len() % 4 == 0;
        let bins_packed_owned: Vec<u32>;
        let bins_packed: &[u32] = if bins_aligned {
            bytemuck::cast_slice(bins_row_major)
        } else {
            bins_packed_owned = pack_bins_u32(bins_row_major);
            &bins_packed_owned
        };

        let bins_size = (bins_packed.len() * 4) as u64;
        let grad_hess_size = (grad_hess_packed.len() * 4) as u64;
        let indices_size = if indices_u32.is_empty() {
            4u64
        } else {
            (indices_u32.len() * 4) as u64
        };
        let hist_size = (num_features * 256 * 4) as u64;

        let params = HistogramParams {
            num_rows: num_rows as u32,
            num_features: num_features as u32,
            num_indices: indices_u32.len() as u32,
            num_batches: 0,
        };

        let mut pool = self.buffer_pool.lock().unwrap();

        if pool.params.is_none() {
            pool.params = Some(dev.create_uniform_buffer(
                "params_buffer",
                std::mem::size_of::<HistogramParams>() as u64,
            ));
        }

        if Self::ensure_storage_buffer(dev, &mut pool.bins, "bins_buffer", bins_size, false) {
            pool.bins_cache_key = None;
        }
        Self::ensure_storage_buffer(
            dev,
            &mut pool.grad_hess,
            "grad_hess_buffer",
            grad_hess_size,
            false,
        );
        Self::ensure_storage_buffer(
            dev,
            &mut pool.indices,
            "indices_buffer",
            indices_size,
            false,
        );
        Self::ensure_storage_buffer(dev, &mut pool.hist_grad, "hist_grad", hist_size, true);
        Self::ensure_storage_buffer(dev, &mut pool.hist_hess, "hist_hess", hist_size, true);
        Self::ensure_storage_buffer(dev, &mut pool.hist_count, "hist_count", hist_size, true);
        Self::ensure_staging_buffer(dev, &mut pool.staging_grad, "staging_grad", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_hess, "staging_hess", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_count, "staging_count", hist_size);

        dev.write_buffer(pool.params.as_ref().unwrap(), &[params]);

        let bins_key = CacheKey::from_slice(bins_row_major);
        if pool.bins_cache_key != Some(bins_key) {
            dev.write_buffer(&pool.bins.as_ref().unwrap().buffer, bins_packed);
            pool.bins_cache_key = Some(bins_key);
        }

        dev.write_buffer(&pool.grad_hess.as_ref().unwrap().buffer, &grad_hess_packed);

        if !indices_u32.is_empty() {
            dev.write_buffer(&pool.indices.as_ref().unwrap().buffer, &indices_u32);
        }

        let bind_group_zero = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("zero_bind_group"),
            layout: &self.bind_group_layout_zero,
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
            ],
        });

        // FORCE base layout (not subgroup layout)
        let bind_group_dense = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("histogram_bind_group_base"),
            layout: &self.bind_group_layout_dense,
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: pool.bins.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 2,
                    resource: pool.grad_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 3,
                    resource: pool.indices.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
            ],
        });

        let mut encoder = dev.create_encoder("histogram_encoder_base");

        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("zero_pass"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&self.pipeline_zero);
            pass.set_bind_group(0, &bind_group_zero, &[]);
            let total_bins = (num_features * 256) as u32;
            let workgroups = (total_bins + 255) / 256;
            pass.dispatch_workgroups(workgroups, 1, 1);
        }

        // FORCE base pipeline (not subgroup pipeline)
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("histogram_pass_base"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&self.pipeline_dense);
            pass.set_bind_group(0, &bind_group_dense, &[]);
            pass.dispatch_workgroups(num_features as u32, 1, 1);
        }

        encoder.copy_buffer_to_buffer(
            &pool.hist_grad.as_ref().unwrap().buffer,
            0,
            &pool.staging_grad.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_hess.as_ref().unwrap().buffer,
            0,
            &pool.staging_hess.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_count.as_ref().unwrap().buffer,
            0,
            &pool.staging_count.as_ref().unwrap().buffer,
            0,
            hist_size,
        );

        dev.submit_and_wait(encoder);

        let mut grad_data = vec![0i32; num_features * 256];
        let mut hess_data = vec![0i32; num_features * 256];
        let mut count_data = vec![0u32; num_features * 256];

        dev.read_buffer(&pool.staging_grad.as_ref().unwrap().buffer, &mut grad_data);
        dev.read_buffer(&pool.staging_hess.as_ref().unwrap().buffer, &mut hess_data);
        dev.read_buffer(
            &pool.staging_count.as_ref().unwrap().buffer,
            &mut count_data,
        );

        drop(pool);

        let mut histograms = Vec::with_capacity(num_features);
        for f in 0..num_features {
            let mut hist = Histogram::new();
            let offset = f * 256;

            for bin in 0..256 {
                let idx = offset + bin;
                let sum_grad = grad_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                let sum_hess = hess_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                let count = count_data[idx];

                if count > 0 {
                    hist.accumulate(bin as u8, sum_grad, sum_hess);
                    let entry = hist.get_mut(bin as u8);
                    entry.count = count;
                }
            }

            histograms.push(hist);
        }

        histograms
    }

    /// Execute histogram building on GPU.
    ///
    /// # Arguments
    /// * `bins_row_major` - Bin values in row-major order [row][feature], packed as u32
    /// * `grad_hess` - Interleaved gradients and hessians [(g0,h0), (g1,h1), ...]
    /// * `row_indices` - Optional row indices (empty = use all rows)
    /// * `num_rows` - Total number of rows
    /// * `num_features` - Number of features
    ///
    /// # Returns
    /// Vector of histograms, one per feature
    pub fn build_histograms(
        &self,
        bins_row_major: &[u8],
        grad_hess: &[(f32, f32)],
        row_indices: &[usize],
        num_rows: usize,
        num_features: usize,
    ) -> Vec<Histogram> {
        let dev = &self.device;

        // Quantize gradients/hessians to fixed-point i16 and pack into u32
        // This halves upload bandwidth while using native atomicAdd
        let grad_hess_packed: Vec<u32> = grad_hess
            .iter()
            .map(|(g, h)| {
                // Scale and clamp to i16 range
                let grad_i16 = ((*g * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                let hess_i16 = ((*h * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                // Pack: gradient in low 16 bits, hessian in high 16 bits
                (grad_i16 as u16 as u32) | ((hess_i16 as u16 as u32) << 16)
            })
            .collect();

        // Convert row indices to u32 (still needs allocation, but small)
        let indices_u32: Vec<u32> = row_indices.iter().map(|&i| i as u32).collect();

        // For bins, try zero-copy cast if aligned, else pack
        let bins_aligned = bins_row_major.len() % 4 == 0;
        let bins_packed_owned: Vec<u32>;
        let bins_packed: &[u32] = if bins_aligned {
            // Zero-copy: interpret bytes directly as u32s
            bytemuck::cast_slice(bins_row_major)
        } else {
            // Fallback: pack with padding (rare case)
            bins_packed_owned = pack_bins_u32(bins_row_major);
            &bins_packed_owned
        };

        // Calculate required buffer sizes
        let bins_size = (bins_packed.len() * 4) as u64;
        let grad_hess_size = (grad_hess_packed.len() * 4) as u64; // 1 u32 per row (packed i16 pair)
        let indices_size = if indices_u32.is_empty() {
            4u64
        } else {
            (indices_u32.len() * 4) as u64
        };
        let hist_size = (num_features * 256 * 4) as u64;

        // Create uniform buffer with parameters
        let params = HistogramParams {
            num_rows: num_rows as u32,
            num_features: num_features as u32,
            num_indices: indices_u32.len() as u32,
            num_batches: 0, // Single batch mode
        };

        // Lock buffer pool and ensure all buffers exist with sufficient capacity
        let mut pool = self.buffer_pool.lock().unwrap();

        // Params buffer (fixed size, create once)
        if pool.params.is_none() {
            pool.params = Some(dev.create_uniform_buffer(
                "params_buffer",
                std::mem::size_of::<HistogramParams>() as u64,
            ));
        }

        // Ensure input buffers have sufficient capacity (invalidate cache if reallocated)
        if Self::ensure_storage_buffer(dev, &mut pool.bins, "bins_buffer", bins_size, false) {
            pool.bins_cache_key = None; // Buffer was reallocated, must re-upload
        }
        Self::ensure_storage_buffer(
            dev,
            &mut pool.grad_hess,
            "grad_hess_buffer",
            grad_hess_size,
            false,
        );
        Self::ensure_storage_buffer(
            dev,
            &mut pool.indices,
            "indices_buffer",
            indices_size,
            false,
        );

        // Ensure output histogram buffers
        Self::ensure_storage_buffer(dev, &mut pool.hist_grad, "hist_grad", hist_size, true);
        Self::ensure_storage_buffer(dev, &mut pool.hist_hess, "hist_hess", hist_size, true);
        Self::ensure_storage_buffer(dev, &mut pool.hist_count, "hist_count", hist_size, true);

        // Ensure staging buffers
        Self::ensure_staging_buffer(dev, &mut pool.staging_grad, "staging_grad", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_hess, "staging_hess", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_count, "staging_count", hist_size);

        // Write data to buffers (with caching to skip redundant uploads)
        // Params always need updating (num_indices changes per call)
        dev.write_buffer(pool.params.as_ref().unwrap(), &[params]);

        // Bins: only upload if data changed (same dataset = same pointer)
        // This works because dataset bins never change during training
        let bins_key = CacheKey::from_slice(bins_row_major);
        if pool.bins_cache_key != Some(bins_key) {
            dev.write_buffer(&pool.bins.as_ref().unwrap().buffer, bins_packed);
            pool.bins_cache_key = Some(bins_key);
        }

        // Grad/Hess: always upload - values change every round even though the
        // slice pointer may stay the same (pointer-based caching would be incorrect)
        dev.write_buffer(&pool.grad_hess.as_ref().unwrap().buffer, &grad_hess_packed);

        // Indices: always upload (different subset each call)
        if !indices_u32.is_empty() {
            dev.write_buffer(&pool.indices.as_ref().unwrap().buffer, &indices_u32);
        }

        // Create bind groups using pooled buffers
        let bind_group_zero = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("zero_bind_group"),
            layout: &self.bind_group_layout_zero,
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
            ],
        });

        // Select the appropriate layout based on whether we're using subgroups
        let dense_layout = if self.has_subgroups() {
            self.bind_group_layout_dense_subgroups.as_ref().unwrap()
        } else {
            &self.bind_group_layout_dense
        };

        let bind_group_dense = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("histogram_bind_group"),
            layout: dense_layout,
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: pool.bins.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 2,
                    resource: pool.grad_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 3,
                    resource: pool.indices.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
            ],
        });

        // Execute kernels
        let mut encoder = dev.create_encoder("histogram_encoder");

        // Zero histograms first
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("zero_pass"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&self.pipeline_zero);
            pass.set_bind_group(0, &bind_group_zero, &[]);
            let total_bins = (num_features * 256) as u32;
            let workgroups = (total_bins + 255) / 256;
            pass.dispatch_workgroups(workgroups, 1, 1);
        }

        // Run histogram kernel (use subgroup-optimized version if available)
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("histogram_pass"),
                timestamp_writes: None,
            });
            if self.has_subgroups() {
                pass.set_pipeline(self.pipeline_dense_subgroups.as_ref().unwrap());
            } else {
                pass.set_pipeline(&self.pipeline_dense);
            }
            pass.set_bind_group(0, &bind_group_dense, &[]);
            pass.dispatch_workgroups(num_features as u32, 1, 1);
        }

        // Copy results to staging buffers
        encoder.copy_buffer_to_buffer(
            &pool.hist_grad.as_ref().unwrap().buffer,
            0,
            &pool.staging_grad.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_hess.as_ref().unwrap().buffer,
            0,
            &pool.staging_hess.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_count.as_ref().unwrap().buffer,
            0,
            &pool.staging_count.as_ref().unwrap().buffer,
            0,
            hist_size,
        );

        // Submit and wait
        dev.submit_and_wait(encoder);

        // Read back results (as i32 fixed-point)
        let mut grad_data = vec![0i32; num_features * 256];
        let mut hess_data = vec![0i32; num_features * 256];
        let mut count_data = vec![0u32; num_features * 256];

        dev.read_buffer(&pool.staging_grad.as_ref().unwrap().buffer, &mut grad_data);
        dev.read_buffer(&pool.staging_hess.as_ref().unwrap().buffer, &mut hess_data);
        dev.read_buffer(
            &pool.staging_count.as_ref().unwrap().buffer,
            &mut count_data,
        );

        // Drop pool borrow before building histograms
        drop(pool);

        // Convert to Histogram structs with dequantization
        let mut histograms = Vec::with_capacity(num_features);
        for f in 0..num_features {
            let mut hist = Histogram::new();
            let offset = f * 256;

            for bin in 0..256 {
                let idx = offset + bin;
                // Dequantize from fixed-point i32 back to f32
                let sum_grad = grad_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                let sum_hess = hess_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                let count = count_data[idx];

                if count > 0 {
                    hist.accumulate(bin as u8, sum_grad, sum_hess);
                    // Adjust count (accumulate adds 1, we want the actual count)
                    let entry = hist.get_mut(bin as u8);
                    entry.count = count;
                }
            }

            histograms.push(hist);
        }

        histograms
    }

    /// Build histograms using 4-bit packed bins.
    ///
    /// This is optimized for datasets where all features have ≤16 bins.
    /// Uses nibble-packed bin data for 50% memory bandwidth reduction.
    ///
    /// # Arguments
    /// * `bins_4bit` - 4-bit packed bins in row-major order (2 features per byte)
    /// * `grad_hess` - Interleaved gradients and hessians [(g0,h0), (g1,h1), ...]
    /// * `row_indices` - Optional row indices (empty = use all rows)
    /// * `num_rows` - Total number of rows
    /// * `num_features` - Number of features
    ///
    /// # Returns
    /// Vector of histograms, one per feature
    pub fn build_histograms_4bit(
        &self,
        bins_4bit: &[u8],
        grad_hess: &[(f32, f32)],
        row_indices: &[usize],
        num_rows: usize,
        num_features: usize,
    ) -> Vec<Histogram> {
        let dev = &self.device;

        // Quantize gradients/hessians to fixed-point i16 and pack into u32
        let grad_hess_packed: Vec<u32> = grad_hess
            .iter()
            .map(|(g, h)| {
                let grad_i16 = ((*g * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                let hess_i16 = ((*h * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                (grad_i16 as u16 as u32) | ((hess_i16 as u16 as u32) << 16)
            })
            .collect();

        // Convert row indices to u32
        let indices_u32: Vec<u32> = row_indices.iter().map(|&i| i as u32).collect();

        // Pack 4-bit bins for GPU (already nibble-packed, just need u32 alignment)
        let bins_aligned = bins_4bit.len() % 4 == 0;
        let bins_packed_owned: Vec<u32>;
        let bins_packed: &[u32] = if bins_aligned {
            bytemuck::cast_slice(bins_4bit)
        } else {
            bins_packed_owned = pack_bins_u32(bins_4bit);
            &bins_packed_owned
        };

        // Calculate required buffer sizes
        let bins_size = (bins_packed.len() * 4) as u64;
        let grad_hess_size = (grad_hess_packed.len() * 4) as u64;
        let indices_size = if indices_u32.is_empty() {
            4u64
        } else {
            (indices_u32.len() * 4) as u64
        };
        let hist_size = (num_features * 256 * 4) as u64;

        // Create uniform buffer with parameters
        let params = HistogramParams {
            num_rows: num_rows as u32,
            num_features: num_features as u32,
            num_indices: indices_u32.len() as u32,
            num_batches: 0, // Single batch mode
        };

        // Lock buffer pool and ensure all buffers exist
        let mut pool = self.buffer_pool.lock().unwrap();

        // Params buffer (fixed size, create once)
        if pool.params.is_none() {
            pool.params = Some(dev.create_uniform_buffer(
                "params_buffer",
                std::mem::size_of::<HistogramParams>() as u64,
            ));
        }

        // Ensure 4-bit bins buffer (separate from 8-bit)
        if Self::ensure_storage_buffer(
            dev,
            &mut pool.bins_4bit,
            "bins_4bit_buffer",
            bins_size,
            false,
        ) {
            pool.bins_4bit_cache_key = None;
        }
        Self::ensure_storage_buffer(
            dev,
            &mut pool.grad_hess,
            "grad_hess_buffer",
            grad_hess_size,
            false,
        );
        Self::ensure_storage_buffer(
            dev,
            &mut pool.indices,
            "indices_buffer",
            indices_size,
            false,
        );

        // Ensure output histogram buffers
        Self::ensure_storage_buffer(dev, &mut pool.hist_grad, "hist_grad", hist_size, true);
        Self::ensure_storage_buffer(dev, &mut pool.hist_hess, "hist_hess", hist_size, true);
        Self::ensure_storage_buffer(dev, &mut pool.hist_count, "hist_count", hist_size, true);

        // Ensure staging buffers
        Self::ensure_staging_buffer(dev, &mut pool.staging_grad, "staging_grad", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_hess, "staging_hess", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_count, "staging_count", hist_size);

        // Write data to buffers with caching
        dev.write_buffer(pool.params.as_ref().unwrap(), &[params]);

        // 4-bit bins: check cache
        let bins_key = CacheKey::from_slice(bins_4bit);
        if pool.bins_4bit_cache_key != Some(bins_key) {
            dev.write_buffer(&pool.bins_4bit.as_ref().unwrap().buffer, bins_packed);
            pool.bins_4bit_cache_key = Some(bins_key);
        }

        dev.write_buffer(&pool.grad_hess.as_ref().unwrap().buffer, &grad_hess_packed);

        if !indices_u32.is_empty() {
            dev.write_buffer(&pool.indices.as_ref().unwrap().buffer, &indices_u32);
        }

        // Create bind groups using 4-bit layouts
        let bind_group_zero = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("zero_bind_group_4bit"),
            layout: &self.pipeline_zero_4bit.get_bind_group_layout(0),
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
            ],
        });

        let bind_group_dense = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("histogram_bind_group_4bit"),
            layout: &self.bind_group_layout_dense_4bit,
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: pool.bins_4bit.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 2,
                    resource: pool.grad_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 3,
                    resource: pool.indices.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
            ],
        });

        // Execute kernels
        let mut encoder = dev.create_encoder("histogram_encoder_4bit");

        // Zero histograms first
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("zero_pass_4bit"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&self.pipeline_zero_4bit);
            pass.set_bind_group(0, &bind_group_zero, &[]);
            let total_bins = (num_features * 256) as u32;
            let workgroups = (total_bins + 255) / 256;
            pass.dispatch_workgroups(workgroups, 1, 1);
        }

        // Run 4-bit histogram kernel
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("histogram_pass_4bit"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&self.pipeline_dense_4bit);
            pass.set_bind_group(0, &bind_group_dense, &[]);
            pass.dispatch_workgroups(num_features as u32, 1, 1);
        }

        // Copy results to staging buffers
        encoder.copy_buffer_to_buffer(
            &pool.hist_grad.as_ref().unwrap().buffer,
            0,
            &pool.staging_grad.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_hess.as_ref().unwrap().buffer,
            0,
            &pool.staging_hess.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_count.as_ref().unwrap().buffer,
            0,
            &pool.staging_count.as_ref().unwrap().buffer,
            0,
            hist_size,
        );

        // Submit and wait
        dev.submit_and_wait(encoder);

        // Read back results (as i32 fixed-point)
        let mut grad_data = vec![0i32; num_features * 256];
        let mut hess_data = vec![0i32; num_features * 256];
        let mut count_data = vec![0u32; num_features * 256];

        dev.read_buffer(&pool.staging_grad.as_ref().unwrap().buffer, &mut grad_data);
        dev.read_buffer(&pool.staging_hess.as_ref().unwrap().buffer, &mut hess_data);
        dev.read_buffer(
            &pool.staging_count.as_ref().unwrap().buffer,
            &mut count_data,
        );

        // Drop pool borrow
        drop(pool);

        // Convert to Histogram structs with dequantization
        let mut histograms = Vec::with_capacity(num_features);
        for f in 0..num_features {
            let mut hist = Histogram::new();
            let offset = f * 256;

            // Only check first 16 bins for 4-bit mode
            for bin in 0..16 {
                let idx = offset + bin;
                let sum_grad = grad_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                let sum_hess = hess_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                let count = count_data[idx];

                if count > 0 {
                    hist.accumulate(bin as u8, sum_grad, sum_hess);
                    let entry = hist.get_mut(bin as u8);
                    entry.count = count;
                }
            }

            histograms.push(hist);
        }

        histograms
    }

    /// Build histograms with detailed profiling.
    ///
    /// Returns both the histograms and detailed timing breakdown for each step.
    /// Use this to understand GPU overhead and identify optimization opportunities.
    pub fn build_histograms_profiled(
        &self,
        bins_row_major: &[u8],
        grad_hess: &[(f32, f32)],
        row_indices: &[usize],
        num_rows: usize,
        num_features: usize,
    ) -> (Vec<Histogram>, GpuProfileData) {
        let total_start = Instant::now();
        let mut profile = GpuProfileData {
            num_rows,
            num_features,
            num_indices: row_indices.len(),
            ..Default::default()
        };

        let dev = &self.device;

        // Quantize gradients/hessians to fixed-point i16 and pack into u32
        let grad_hess_packed: Vec<u32> = grad_hess
            .iter()
            .map(|(g, h)| {
                let grad_i16 = ((*g * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                let hess_i16 = ((*h * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                (grad_i16 as u16 as u32) | ((hess_i16 as u16 as u32) << 16)
            })
            .collect();

        // Convert row indices to u32
        let t = Instant::now();
        let indices_u32: Vec<u32> = row_indices.iter().map(|&i| i as u32).collect();
        profile.indices_convert = t.elapsed();

        // Pack bins
        let t = Instant::now();
        let bins_aligned = bins_row_major.len() % 4 == 0;
        let bins_packed_owned: Vec<u32>;
        let bins_packed: &[u32] = if bins_aligned {
            bytemuck::cast_slice(bins_row_major)
        } else {
            bins_packed_owned = pack_bins_u32(bins_row_major);
            &bins_packed_owned
        };
        profile.bins_pack = t.elapsed();

        // Calculate sizes
        let bins_size = (bins_packed.len() * 4) as u64;
        let grad_hess_size = (grad_hess_packed.len() * 4) as u64; // 1 u32 per row (packed i16 pair)
        let indices_size = if indices_u32.is_empty() {
            4u64
        } else {
            (indices_u32.len() * 4) as u64
        };
        let hist_size = (num_features * 256 * 4) as u64;

        let params = HistogramParams {
            num_rows: num_rows as u32,
            num_features: num_features as u32,
            num_indices: indices_u32.len() as u32,
            num_batches: 0, // Single batch mode
        };

        // Buffer allocation
        let t = Instant::now();
        let mut pool = self.buffer_pool.lock().unwrap();

        if pool.params.is_none() {
            pool.params = Some(dev.create_uniform_buffer(
                "params_buffer",
                std::mem::size_of::<HistogramParams>() as u64,
            ));
        }

        if Self::ensure_storage_buffer(dev, &mut pool.bins, "bins_buffer", bins_size, false) {
            pool.bins_cache_key = None;
        }
        Self::ensure_storage_buffer(
            dev,
            &mut pool.grad_hess,
            "grad_hess_buffer",
            grad_hess_size,
            false,
        );
        Self::ensure_storage_buffer(
            dev,
            &mut pool.indices,
            "indices_buffer",
            indices_size,
            false,
        );
        Self::ensure_storage_buffer(dev, &mut pool.hist_grad, "hist_grad", hist_size, true);
        Self::ensure_storage_buffer(dev, &mut pool.hist_hess, "hist_hess", hist_size, true);
        Self::ensure_storage_buffer(dev, &mut pool.hist_count, "hist_count", hist_size, true);
        Self::ensure_staging_buffer(dev, &mut pool.staging_grad, "staging_grad", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_hess, "staging_hess", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_count, "staging_count", hist_size);
        profile.buffer_alloc = t.elapsed();

        // Upload params
        let t = Instant::now();
        dev.write_buffer(pool.params.as_ref().unwrap(), &[params]);
        profile.upload_params = t.elapsed();

        // Upload bins (check cache)
        let t = Instant::now();
        let bins_key = CacheKey::from_slice(bins_row_major);
        if pool.bins_cache_key != Some(bins_key) {
            dev.write_buffer(&pool.bins.as_ref().unwrap().buffer, bins_packed);
            pool.bins_cache_key = Some(bins_key);
            profile.bins_cached = false;
        } else {
            profile.bins_cached = true;
        }
        profile.upload_bins = t.elapsed();

        // Upload grad/hess (packed i16 pairs)
        let t = Instant::now();
        dev.write_buffer(&pool.grad_hess.as_ref().unwrap().buffer, &grad_hess_packed);
        profile.upload_grad_hess = t.elapsed();

        // Upload indices
        let t = Instant::now();
        if !indices_u32.is_empty() {
            dev.write_buffer(&pool.indices.as_ref().unwrap().buffer, &indices_u32);
        }
        profile.upload_indices = t.elapsed();

        // Create bind groups
        let t = Instant::now();
        let bind_group_zero = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("zero_bind_group"),
            layout: &self.bind_group_layout_zero,
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
            ],
        });

        // Select the appropriate layout based on whether we're using subgroups
        let dense_layout = if self.has_subgroups() {
            self.bind_group_layout_dense_subgroups.as_ref().unwrap()
        } else {
            &self.bind_group_layout_dense
        };

        let bind_group_dense = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("histogram_bind_group"),
            layout: dense_layout,
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: pool.bins.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 2,
                    resource: pool.grad_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 3,
                    resource: pool.indices.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
            ],
        });
        profile.bind_group_create = t.elapsed();

        // Encode commands
        let t = Instant::now();
        let mut encoder = dev.create_encoder("histogram_encoder");

        // Zero histograms
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("zero_pass"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&self.pipeline_zero);
            pass.set_bind_group(0, &bind_group_zero, &[]);
            let total_bins = (num_features * 256) as u32;
            let workgroups = (total_bins + 255) / 256;
            pass.dispatch_workgroups(workgroups, 1, 1);
        }

        // Histogram kernel (use subgroup-optimized version if available)
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("histogram_pass"),
                timestamp_writes: None,
            });
            if self.has_subgroups() {
                pass.set_pipeline(self.pipeline_dense_subgroups.as_ref().unwrap());
            } else {
                pass.set_pipeline(&self.pipeline_dense);
            }
            pass.set_bind_group(0, &bind_group_dense, &[]);
            pass.dispatch_workgroups(num_features as u32, 1, 1);
        }

        // Copy to staging
        encoder.copy_buffer_to_buffer(
            &pool.hist_grad.as_ref().unwrap().buffer,
            0,
            &pool.staging_grad.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_hess.as_ref().unwrap().buffer,
            0,
            &pool.staging_hess.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_count.as_ref().unwrap().buffer,
            0,
            &pool.staging_count.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        profile.encode_commands = t.elapsed();

        // Submit and wait
        let t = Instant::now();
        dev.submit_and_wait(encoder);
        profile.gpu_execute = t.elapsed();

        // Download results (as i32 fixed-point)
        let t = Instant::now();
        let mut grad_data = vec![0i32; num_features * 256];
        let mut hess_data = vec![0i32; num_features * 256];
        let mut count_data = vec![0u32; num_features * 256];

        dev.read_buffer(&pool.staging_grad.as_ref().unwrap().buffer, &mut grad_data);
        dev.read_buffer(&pool.staging_hess.as_ref().unwrap().buffer, &mut hess_data);
        dev.read_buffer(
            &pool.staging_count.as_ref().unwrap().buffer,
            &mut count_data,
        );
        profile.download_results = t.elapsed();

        drop(pool);

        // Unpack histograms with dequantization
        let t = Instant::now();
        let mut histograms = Vec::with_capacity(num_features);
        for f in 0..num_features {
            let mut hist = Histogram::new();
            let offset = f * 256;

            for bin in 0..256 {
                let idx = offset + bin;
                // Dequantize from fixed-point i32 back to f32
                let sum_grad = grad_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                let sum_hess = hess_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                let count = count_data[idx];

                if count > 0 {
                    hist.accumulate(bin as u8, sum_grad, sum_hess);
                    let entry = hist.get_mut(bin as u8);
                    entry.count = count;
                }
            }

            histograms.push(hist);
        }
        profile.unpack_histograms = t.elapsed();

        profile.total = total_start.elapsed();

        (histograms, profile)
    }

    /// Ensure a storage buffer exists with sufficient capacity.
    /// Returns true if buffer was (re)allocated (cache should be invalidated).
    fn ensure_storage_buffer(
        dev: &GpuDevice,
        pool: &mut Option<PooledBuffer>,
        label: &str,
        required_size: u64,
        read_write: bool,
    ) -> bool {
        let needs_new = match pool {
            Some(ref pb) => pb.capacity < required_size,
            None => true,
        };

        if needs_new {
            // Allocate with 20% headroom, aligned to 4 bytes
            let capacity = ((required_size as f64 * 1.2) as u64 + 3) & !3;
            let buffer = dev.create_storage_buffer(label, capacity, read_write);
            *pool = Some(PooledBuffer { buffer, capacity });
            true
        } else {
            false
        }
    }

    /// Ensure a staging buffer exists with sufficient capacity.
    fn ensure_staging_buffer(
        dev: &GpuDevice,
        pool: &mut Option<PooledBuffer>,
        label: &str,
        required_size: u64,
    ) {
        let needs_new = match pool {
            Some(ref pb) => pb.capacity < required_size,
            None => true,
        };

        if needs_new {
            // Allocate with 20% headroom, aligned to 4 bytes
            let capacity = ((required_size as f64 * 1.2) as u64 + 3) & !3;
            let buffer = dev.create_staging_buffer(label, capacity);
            *pool = Some(PooledBuffer { buffer, capacity });
        }
    }

    /// Build histograms for multiple batches in a single GPU dispatch.
    ///
    /// This is significantly more efficient than calling `build_histograms` multiple times
    /// because it amortizes GPU dispatch overhead across all batches.
    ///
    /// # Arguments
    ///
    /// * `bins_row_major` - Row-major bin data for entire dataset
    /// * `grad_hess` - Gradient/hessian pairs for entire dataset
    /// * `batches` - Slice of row index arrays, one per batch
    /// * `num_rows` - Total number of rows in dataset
    /// * `num_features` - Number of features
    ///
    /// # Returns
    ///
    /// Vector of histogram vectors, one per batch. Each inner vector contains
    /// `num_features` histograms.
    pub fn build_histograms_batched(
        &self,
        bins_row_major: &[u8],
        grad_hess: &[(f32, f32)],
        batches: &[&[usize]],
        num_rows: usize,
        num_features: usize,
    ) -> Vec<Vec<Histogram>> {
        let num_batches = batches.len();
        if num_batches == 0 {
            return Vec::new();
        }

        // For single batch, use the optimized single-batch path
        if num_batches == 1 {
            return vec![self.build_histograms(
                bins_row_major,
                grad_hess,
                batches[0],
                num_rows,
                num_features,
            )];
        }

        let dev = &self.device;

        // Quantize gradients/hessians to fixed-point i16 and pack into u32
        let grad_hess_packed: Vec<u32> = grad_hess
            .iter()
            .map(|(g, h)| {
                let grad_i16 = ((*g * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                let hess_i16 = ((*h * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                (grad_i16 as u16 as u32) | ((hess_i16 as u16 as u32) << 16)
            })
            .collect();

        // Concatenate all batch row indices and create batch info
        let mut all_indices: Vec<u32> = Vec::new();
        let mut batch_info_data: Vec<BatchInfo> = Vec::with_capacity(num_batches);

        for batch_indices in batches {
            let start = all_indices.len() as u32;
            let count = batch_indices.len() as u32;
            batch_info_data.push(BatchInfo { start, count });
            all_indices.extend(batch_indices.iter().map(|&i| i as u32));
        }

        // For bins, try zero-copy cast if aligned, else pack
        let bins_aligned = bins_row_major.len() % 4 == 0;
        let bins_packed_owned: Vec<u32>;
        let bins_packed: &[u32] = if bins_aligned {
            bytemuck::cast_slice(bins_row_major)
        } else {
            bins_packed_owned = pack_bins_u32(bins_row_major);
            &bins_packed_owned
        };

        // Calculate buffer sizes
        let bins_size = (bins_packed.len() * 4) as u64;
        let grad_hess_size = (grad_hess_packed.len() * 4) as u64; // 1 u32 per row (packed i16 pair)
        let indices_size = if all_indices.is_empty() {
            4u64
        } else {
            (all_indices.len() * 4) as u64
        };
        let batch_info_size = (batch_info_data.len() * std::mem::size_of::<BatchInfo>()) as u64;
        let hist_size = (num_batches * num_features * 256 * 4) as u64;

        // Create uniform buffer with parameters
        let params = HistogramParams {
            num_rows: num_rows as u32,
            num_features: num_features as u32,
            num_indices: all_indices.len() as u32,
            num_batches: num_batches as u32,
        };

        // Lock buffer pool and ensure all buffers exist
        let mut pool = self.buffer_pool.lock().unwrap();

        // Ensure params buffer
        if pool.params.is_none() {
            pool.params = Some(dev.create_uniform_buffer(
                "params_buffer",
                std::mem::size_of::<HistogramParams>() as u64,
            ));
        }

        // Ensure input buffers
        Self::ensure_storage_buffer(dev, &mut pool.bins, "bins_buffer", bins_size, false);
        Self::ensure_storage_buffer(
            dev,
            &mut pool.grad_hess,
            "grad_hess_buffer",
            grad_hess_size,
            false,
        );
        Self::ensure_storage_buffer(
            dev,
            &mut pool.indices,
            "indices_buffer",
            indices_size,
            false,
        );
        Self::ensure_storage_buffer(
            dev,
            &mut pool.batch_info,
            "batch_info_buffer",
            batch_info_size,
            false,
        );

        // Ensure output buffers (sized for all batches)
        Self::ensure_storage_buffer(
            dev,
            &mut pool.hist_grad,
            "hist_grad_buffer",
            hist_size,
            true,
        );
        Self::ensure_storage_buffer(
            dev,
            &mut pool.hist_hess,
            "hist_hess_buffer",
            hist_size,
            true,
        );
        Self::ensure_storage_buffer(
            dev,
            &mut pool.hist_count,
            "hist_count_buffer",
            hist_size,
            true,
        );

        // Ensure staging buffers
        Self::ensure_staging_buffer(dev, &mut pool.staging_grad, "staging_grad", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_hess, "staging_hess", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_count, "staging_count", hist_size);

        // Upload data
        dev.write_buffer(pool.params.as_ref().unwrap(), &[params]);
        dev.write_buffer(&pool.bins.as_ref().unwrap().buffer, bins_packed);
        dev.write_buffer(&pool.grad_hess.as_ref().unwrap().buffer, &grad_hess_packed);
        dev.write_buffer(&pool.indices.as_ref().unwrap().buffer, &all_indices);
        dev.write_buffer(&pool.batch_info.as_ref().unwrap().buffer, &batch_info_data);

        // Select the appropriate layout based on whether we're using subgroups
        let batched_layout = if self.pipeline_batched_subgroups.is_some() {
            self.bind_group_layout_batched_subgroups.as_ref().unwrap()
        } else {
            &self.bind_group_layout_batched
        };

        // Create bind groups for batched kernel
        let bind_group_batched = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("batched_bind_group"),
            layout: batched_layout,
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: pool.bins.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 2,
                    resource: pool.grad_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 3,
                    resource: pool.indices.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 11,
                    resource: pool.batch_info.as_ref().unwrap().buffer.as_entire_binding(),
                },
            ],
        });

        // Zero bind group for batched kernel (use batched zero pipeline's layout)
        let bind_group_layout_zero_batched = self.pipeline_zero_batched.get_bind_group_layout(0);
        let bind_group_zero = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("zero_bind_group_batched"),
            layout: &bind_group_layout_zero_batched,
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
            ],
        });

        // Execute kernels
        let mut encoder = dev.create_encoder("histogram_batched_encoder");

        // Zero histograms first (for all batches)
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("zero_pass_batched"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&self.pipeline_zero_batched);
            pass.set_bind_group(0, &bind_group_zero, &[]);
            let total_bins = (num_batches * num_features * 256) as u32;
            let workgroups = (total_bins + 255) / 256;
            pass.dispatch_workgroups(workgroups, 1, 1);
        }

        // Run batched histogram kernel (use subgroup-optimized version if available)
        // Dispatch: (num_features, num_batches, 1)
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("histogram_batched_pass"),
                timestamp_writes: None,
            });
            if let Some(ref sg_pipeline) = self.pipeline_batched_subgroups {
                pass.set_pipeline(sg_pipeline);
            } else {
                pass.set_pipeline(&self.pipeline_batched);
            }
            pass.set_bind_group(0, &bind_group_batched, &[]);
            pass.dispatch_workgroups(num_features as u32, num_batches as u32, 1);
        }

        // Copy results to staging buffers
        encoder.copy_buffer_to_buffer(
            &pool.hist_grad.as_ref().unwrap().buffer,
            0,
            &pool.staging_grad.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_hess.as_ref().unwrap().buffer,
            0,
            &pool.staging_hess.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_count.as_ref().unwrap().buffer,
            0,
            &pool.staging_count.as_ref().unwrap().buffer,
            0,
            hist_size,
        );

        // Submit and wait
        dev.submit_and_wait(encoder);

        // Read back results (as i32 fixed-point)
        let total_hist_entries = num_batches * num_features * 256;
        let mut grad_data = vec![0i32; total_hist_entries];
        let mut hess_data = vec![0i32; total_hist_entries];
        let mut count_data = vec![0u32; total_hist_entries];

        dev.read_buffer(&pool.staging_grad.as_ref().unwrap().buffer, &mut grad_data);
        dev.read_buffer(&pool.staging_hess.as_ref().unwrap().buffer, &mut hess_data);
        dev.read_buffer(
            &pool.staging_count.as_ref().unwrap().buffer,
            &mut count_data,
        );

        // Drop pool borrow
        drop(pool);

        // Convert to Histogram structs with dequantization - one Vec<Histogram> per batch
        // Output layout: [batch * num_features * 256 + feature * 256 + bin]
        let hist_stride = num_features * 256;
        let mut all_histograms = Vec::with_capacity(num_batches);

        for batch in 0..num_batches {
            let batch_offset = batch * hist_stride;
            let mut batch_histograms = Vec::with_capacity(num_features);

            for f in 0..num_features {
                let mut hist = Histogram::new();
                let feature_offset = batch_offset + f * 256;

                for bin in 0..256 {
                    let idx = feature_offset + bin;
                    // Dequantize from fixed-point i32 back to f32
                    let sum_grad = grad_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                    let sum_hess = hess_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                    let count = count_data[idx];

                    if count > 0 {
                        hist.accumulate(bin as u8, sum_grad, sum_hess);
                        let entry = hist.get_mut(bin as u8);
                        entry.count = count;
                    }
                }

                batch_histograms.push(hist);
            }

            all_histograms.push(batch_histograms);
        }

        all_histograms
    }

    /// Build era-stratified histograms for Directional Era Splitting (DES).
    ///
    /// Returns histograms indexed as `[era][feature]`.
    ///
    /// # Arguments
    /// * `bins_row_major` - Bin values in row-major order [row][feature]
    /// * `grad_hess` - Interleaved gradients and hessians [(g0,h0), (g1,h1), ...]
    /// * `row_indices` - Row indices to process (empty = use all rows)
    /// * `era_indices` - Era index for each row in the full dataset
    /// * `num_rows` - Total number of rows
    /// * `num_features` - Number of features
    /// * `num_eras` - Number of unique eras
    ///
    /// # Returns
    /// 2D vector of histograms: `[num_eras][num_features]`
    pub fn build_era_histograms(
        &self,
        bins_row_major: &[u8],
        grad_hess: &[(f32, f32)],
        row_indices: &[usize],
        era_indices: &[u16],
        num_rows: usize,
        num_features: usize,
        num_eras: usize,
    ) -> Vec<Vec<Histogram>> {
        let dev = &self.device;

        // Quantize gradients/hessians to fixed-point i16 and pack into u32
        let grad_hess_packed: Vec<u32> = grad_hess
            .iter()
            .map(|(g, h)| {
                let grad_i16 = ((*g * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                let hess_i16 = ((*h * FIXED_POINT_SCALE).clamp(-32767.0, 32767.0)) as i16;
                (grad_i16 as u16 as u32) | ((hess_i16 as u16 as u32) << 16)
            })
            .collect();

        // Convert row indices to u32
        let indices_u32: Vec<u32> = row_indices.iter().map(|&i| i as u32).collect();

        // Pack era indices (u16) into u32 (2 per u32)
        let era_packed: Vec<u32> = era_indices
            .chunks(2)
            .map(|chunk| {
                let e0 = chunk[0] as u32;
                let e1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
                e0 | (e1 << 16)
            })
            .collect();

        // Pack bins
        let bins_aligned = bins_row_major.len() % 4 == 0;
        let bins_packed_owned: Vec<u32>;
        let bins_packed: &[u32] = if bins_aligned {
            bytemuck::cast_slice(bins_row_major)
        } else {
            bins_packed_owned = pack_bins_u32(bins_row_major);
            &bins_packed_owned
        };

        // Calculate buffer sizes
        let bins_size = (bins_packed.len() * 4) as u64;
        let grad_hess_size = (grad_hess_packed.len() * 4) as u64;
        let indices_size = if indices_u32.is_empty() {
            4u64
        } else {
            (indices_u32.len() * 4) as u64
        };
        let era_size = (era_packed.len() * 4) as u64;
        let hist_size = (num_eras * num_features * 256 * 4) as u64;

        // Create uniform buffer with parameters (reusing HistogramParams with num_eras in num_batches field)
        let params = HistogramParams {
            num_rows: num_rows as u32,
            num_features: num_features as u32,
            num_indices: indices_u32.len() as u32,
            num_batches: num_eras as u32, // Repurposed as num_eras for era shader
        };

        // Lock buffer pool and ensure all buffers exist
        let mut pool = self.buffer_pool.lock().unwrap();

        // Params buffer
        if pool.params.is_none() {
            pool.params = Some(dev.create_uniform_buffer(
                "params_buffer",
                std::mem::size_of::<HistogramParams>() as u64,
            ));
        }

        // Ensure input buffers
        if Self::ensure_storage_buffer(dev, &mut pool.bins, "bins_buffer", bins_size, false) {
            pool.bins_cache_key = None;
        }
        Self::ensure_storage_buffer(
            dev,
            &mut pool.grad_hess,
            "grad_hess_buffer",
            grad_hess_size,
            false,
        );
        Self::ensure_storage_buffer(
            dev,
            &mut pool.indices,
            "indices_buffer",
            indices_size,
            false,
        );
        if Self::ensure_storage_buffer(
            dev,
            &mut pool.era_indices,
            "era_indices_buffer",
            era_size,
            false,
        ) {
            pool.era_indices_cache_key = None;
        }

        // Ensure output histogram buffers (sized for all eras)
        Self::ensure_storage_buffer(dev, &mut pool.hist_grad, "hist_grad", hist_size, true);
        Self::ensure_storage_buffer(dev, &mut pool.hist_hess, "hist_hess", hist_size, true);
        Self::ensure_storage_buffer(dev, &mut pool.hist_count, "hist_count", hist_size, true);

        // Ensure staging buffers
        Self::ensure_staging_buffer(dev, &mut pool.staging_grad, "staging_grad", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_hess, "staging_hess", hist_size);
        Self::ensure_staging_buffer(dev, &mut pool.staging_count, "staging_count", hist_size);

        // Upload data
        dev.write_buffer(pool.params.as_ref().unwrap(), &[params]);

        // Bins: check cache
        let bins_key = CacheKey::from_slice(bins_row_major);
        if pool.bins_cache_key != Some(bins_key) {
            dev.write_buffer(&pool.bins.as_ref().unwrap().buffer, bins_packed);
            pool.bins_cache_key = Some(bins_key);
        }

        dev.write_buffer(&pool.grad_hess.as_ref().unwrap().buffer, &grad_hess_packed);

        if !indices_u32.is_empty() {
            dev.write_buffer(&pool.indices.as_ref().unwrap().buffer, &indices_u32);
        }

        // Era indices: check cache
        let era_key = CacheKey::from_slice(era_indices);
        if pool.era_indices_cache_key != Some(era_key) {
            dev.write_buffer(&pool.era_indices.as_ref().unwrap().buffer, &era_packed);
            pool.era_indices_cache_key = Some(era_key);
        }

        // Create bind groups for era histogram kernel
        let bind_group_zero = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("zero_bind_group_era"),
            layout: &self.pipeline_zero_era.get_bind_group_layout(0),
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
            ],
        });

        let bind_group_era = dev.device.create_bind_group(&BindGroupDescriptor {
            label: Some("histogram_bind_group_era"),
            layout: &self.bind_group_layout_era,
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: pool.params.as_ref().unwrap().as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: pool.bins.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 2,
                    resource: pool.grad_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 3,
                    resource: pool.indices.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 4,
                    resource: pool.hist_grad.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 5,
                    resource: pool.hist_hess.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 6,
                    resource: pool.hist_count.as_ref().unwrap().buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 7,
                    resource: pool
                        .era_indices
                        .as_ref()
                        .unwrap()
                        .buffer
                        .as_entire_binding(),
                },
            ],
        });

        // Execute kernels
        let mut encoder = dev.create_encoder("histogram_era_encoder");

        // Zero histograms first (for all eras)
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("zero_pass_era"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&self.pipeline_zero_era);
            pass.set_bind_group(0, &bind_group_zero, &[]);
            let total_bins = (num_eras * num_features * 256) as u32;
            let workgroups = (total_bins + 255) / 256;
            pass.dispatch_workgroups(workgroups, 1, 1);
        }

        // Run era histogram kernel
        // Dispatch: (num_features, num_eras, 1)
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("histogram_era_pass"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&self.pipeline_era);
            pass.set_bind_group(0, &bind_group_era, &[]);
            pass.dispatch_workgroups(num_features as u32, num_eras as u32, 1);
        }

        // Copy results to staging buffers
        encoder.copy_buffer_to_buffer(
            &pool.hist_grad.as_ref().unwrap().buffer,
            0,
            &pool.staging_grad.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_hess.as_ref().unwrap().buffer,
            0,
            &pool.staging_hess.as_ref().unwrap().buffer,
            0,
            hist_size,
        );
        encoder.copy_buffer_to_buffer(
            &pool.hist_count.as_ref().unwrap().buffer,
            0,
            &pool.staging_count.as_ref().unwrap().buffer,
            0,
            hist_size,
        );

        // Submit and wait
        dev.submit_and_wait(encoder);

        // Read back results (as i32 fixed-point)
        let total_hist_entries = num_eras * num_features * 256;
        let mut grad_data = vec![0i32; total_hist_entries];
        let mut hess_data = vec![0i32; total_hist_entries];
        let mut count_data = vec![0u32; total_hist_entries];

        dev.read_buffer(&pool.staging_grad.as_ref().unwrap().buffer, &mut grad_data);
        dev.read_buffer(&pool.staging_hess.as_ref().unwrap().buffer, &mut hess_data);
        dev.read_buffer(
            &pool.staging_count.as_ref().unwrap().buffer,
            &mut count_data,
        );

        // Drop pool borrow
        drop(pool);

        // Convert to Histogram structs with dequantization - [era][feature]
        // Output layout: [era * num_features * 256 + feature * 256 + bin]
        let hist_stride = num_features * 256;
        let mut all_histograms = Vec::with_capacity(num_eras);

        for era in 0..num_eras {
            let era_offset = era * hist_stride;
            let mut era_histograms = Vec::with_capacity(num_features);

            for f in 0..num_features {
                let mut hist = Histogram::new();
                let feature_offset = era_offset + f * 256;

                for bin in 0..256 {
                    let idx = feature_offset + bin;
                    // Dequantize from fixed-point i32 back to f32
                    let sum_grad = grad_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                    let sum_hess = hess_data[idx] as f32 * FIXED_POINT_SCALE_INV;
                    let count = count_data[idx];

                    if count > 0 {
                        hist.accumulate(bin as u8, sum_grad, sum_hess);
                        let entry = hist.get_mut(bin as u8);
                        entry.count = count;
                    }
                }

                era_histograms.push(hist);
            }

            all_histograms.push(era_histograms);
        }

        all_histograms
    }
}

/// Pack u8 bins into u32 array (4 bytes per u32).
fn pack_bins_u32(bins: &[u8]) -> Vec<u32> {
    let mut packed = vec![0u32; (bins.len() + 3) / 4];
    for (i, &bin) in bins.iter().enumerate() {
        let word_idx = i / 4;
        let byte_idx = i % 4;
        packed[word_idx] |= (bin as u32) << (byte_idx * 8);
    }
    packed
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pack_bins_u32() {
        let bins = vec![0u8, 1, 2, 3, 4, 5];
        let packed = pack_bins_u32(&bins);

        assert_eq!(packed.len(), 2);
        assert_eq!(packed[0], 0x03020100); // Little-endian: [0,1,2,3]
        assert_eq!(packed[1] & 0xFFFF, 0x0504); // [4,5,0,0]
    }
}