amari-gpu 0.24.1

GPU acceleration for mathematical computations
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
//! GPU acceleration for geometric algebra operations using WebGPU/wgpu
//!
//! This crate provides GPU-accelerated implementations of core Amari operations
//! using WebGPU/wgpu for cross-platform compatibility (native + WASM).
//!
//! # Overview
//!
//! The crate currently offers GPU acceleration for:
//!
//! - **Clifford Algebra**: Batch geometric products with Cayley table upload
//! - **GF(2) Algebra**: Batch binary Clifford products, matrix-vector multiply, Hamming distance (with `gf2` feature)
//! - **Information Geometry**: Batch Amari-Chentsov tensor computation
//! - **Holographic Memory**: Batch bind, unbind, bundle, similarity (with `holographic` feature)
//! - **Measure Theory**: GPU-accelerated Monte Carlo integration (with `measure` feature)
//! - **Relativistic Physics**: Batch Lorentz transformations
//! - **Topology**: Distance matrices, Morse critical points, Rips filtrations (with `topology` feature)
//!
//! Some source modules are still undergoing redesign before full public exposure.
//! In particular, `tropical` exposes a narrow crate-root v1 surface, while `fusion`
//! has only a reduced first public surface intended for restoration so far.
//!
//! # Quick Start
//!
//! ```ignore
//! use amari_gpu::{GpuCliffordAlgebra, AdaptiveCompute};
//!
//! // Create GPU context for Cl(3,0,0)
//! let gpu = GpuCliffordAlgebra::new::<3, 0, 0>().await?;
//!
//! // Batch geometric product
//! let results = gpu.batch_geometric_product(&a_batch, &b_batch).await?;
//!
//! // Or use adaptive dispatch (auto CPU/GPU)
//! let adaptive = AdaptiveCompute::new::<3, 0, 0>().await;
//! let results = adaptive.batch_geometric_product(&a_batch, &b_batch).await?;
//! ```
//!
//! # Holographic Memory (with `holographic` feature)
//!
//! GPU-accelerated batch operations for vector symbolic architectures:
//!
//! ```ignore
//! use amari_gpu::GpuHolographic;
//!
//! // Create GPU holographic processor
//! let gpu = GpuHolographic::new(256).await?;  // 256-dimensional vectors
//!
//! // Batch bind thousands of key-value pairs
//! let bound_flat = gpu.batch_bind(&keys_flat, &values_flat).await?;
//!
//! // Batch similarity computation
//! let similarities = gpu.batch_similarity(&a_flat, &b_flat).await?;
//!
//! // Batch bundle operation
//! let bundled_flat = gpu.batch_bundle(&a_flat, &b_flat).await?;
//! ```
//!
//! # Information Geometry
//!
//! ```ignore
//! use amari_gpu::GpuInfoGeometry;
//!
//! let gpu = GpuInfoGeometry::new().await?;
//!
//! // Batch Amari-Chentsov tensor computation
//! let tensors = gpu.amari_chentsov_tensor_batch(&x_batch, &y_batch, &z_batch).await?;
//!
//! // Fisher information matrix
//! let fisher = gpu.fisher_information_matrix(&params).await?;
//! ```
//!
//! # Adaptive CPU/GPU Dispatch
//!
//! All GPU operations automatically fall back to CPU when:
//! - GPU is unavailable
//! - Batch size is too small to benefit from GPU parallelism
//! - Operating in CI/test environments
//!
//! The threshold is typically ~100 operations for GPU to be beneficial.
//!
//! # Feature Flags
//!
//! | Feature | Description |
//! |---------|-------------|
//! | `std` | Standard library support |
//! | `holographic` | GPU-accelerated holographic memory |
//! | `measure` | GPU-accelerated Monte Carlo integration |
//! | `calculus` | GPU-accelerated differential geometry |
//! | `dual` | Narrow GPU-backed dual-number v1 surface; broader gradient/training scaffolding private |
//! | `probabilistic` | GPU-accelerated probability sampling |
//! | `automata` | GPU-backed automata rule/energy kernels with documented CPU neighborhood fallback |
//! | `enumerative` | Broad GPU-backed enumerative kernels; high-use surface with representative baseline tests |
//! | `functional` | Mixed GPU-backed functional analysis and documented CPU spectral/fallback paths |
//! | `topology` | Mixed GPU-backed topology and documented CPU Rips/Betti fallback paths |
//! | `gf2` | GPU-accelerated GF(2) algebra (binary Clifford products, matrix ops, Hamming distance) |
//! | `fusion` | Reduced first public surface restored; broader fusion GPU API still redesign-pending |
//! | `tropical` | Narrow crate-root public v1 surface for tropical matrix multiply/adaptive dispatch |
//! | `webgpu` | Enable WebGPU backend |
//! | `high-precision` | Enable 128-bit float support |
//!
//! # Tropical GPU v1 (with `tropical` feature)
//!
//! A narrow public tropical GPU surface is available at the crate root:
//!
//! ```ignore
//! use amari_gpu::{TropicalExecutionPath, TropicalGpuOps};
//! use amari_tropical::{TropicalMatrix, TropicalNumber};
//!
//! let mut gpu = TropicalGpuOps::new().await?;
//!
//! let mut a = TropicalMatrix::new(64, 64);
//! let mut b = TropicalMatrix::new(64, 64);
//!
//! for i in 0..64 {
//!     for j in 0..64 {
//!         a.data[i][j] = TropicalNumber::new((i as f32 - j as f32) * 0.25);
//!         b.data[i][j] = TropicalNumber::new((i as f32 + j as f32) * 0.125);
//!     }
//! }
//!
//! match gpu.matrix_multiply_execution_path(a.rows, a.cols, b.cols) {
//!     TropicalExecutionPath::Cpu => println!("CPU path"),
//!     TropicalExecutionPath::Gpu => println!("GPU path"),
//! }
//!
//! let gpu_result = gpu.matrix_multiply(&a, &b).await?;
//! let adaptive_result = gpu.matrix_multiply_adaptive(&a, &b).await?;
//! let attention_scores = gpu.attention_scores(&a).await?;
//! # let _ = (gpu_result, adaptive_result, attention_scores);
//! ```
//!
//! This is intentionally narrower than a full `amari_gpu::tropical` module. It currently
//! includes dense tropical matrix multiply and winner-takes-all attention scores. Broader
//! tropical GPU APIs remain redesign-pending.
//!
//! # Performance
//!
//! GPU acceleration provides significant speedups for batch operations:
//!
//! | Operation | Batch Size | Speedup |
//! |-----------|------------|---------|
//! | Geometric Product | 1000 | ~10-50x |
//! | Holographic Bind | 10000 | ~20-100x |
//! | Similarity Batch | 10000 | ~50-200x |
//! | Monte Carlo | 100000 | ~100-500x |
//! | Distance Matrix | 1000 pts | ~50x |
//! | Morse Critical Points | 100x100 | ~100x |
//!
//! Actual speedups depend on GPU hardware and driver support.

pub mod adaptive;
#[cfg(feature = "automata")]
pub mod automata;
pub mod benchmarks;
#[cfg(feature = "calculus")]
pub mod calculus;
#[cfg(feature = "dual")]
#[allow(dead_code)]
mod dual;
#[cfg(feature = "enumerative")]
pub mod enumerative;
#[cfg(feature = "functional")]
pub mod functional;
#[cfg(feature = "fusion")]
#[allow(dead_code)]
mod fusion;
#[cfg(feature = "gf2")]
pub mod gf2;
#[cfg(feature = "holographic")]
pub mod holographic;
#[cfg(feature = "measure")]
pub mod measure;
pub mod multi_gpu;
pub mod network;
pub mod performance;
#[cfg(feature = "probabilistic")]
pub mod probabilistic;
pub mod relativistic;
pub mod shaders;
pub mod timeline;
// NOTE: `tropical.rs` is still redesigning toward a fuller public module, but a
// narrow v1 surface is now re-exported at the crate root under the `tropical` feature.
#[cfg(feature = "topology")]
pub mod topology;
#[cfg(feature = "tropical")]
#[allow(dead_code)]
mod tropical;
pub mod unified;
pub mod verification;

pub use adaptive::{
    AdaptiveVerificationError, AdaptiveVerificationLevel, AdaptiveVerifier, CpuFeatures,
    GpuBackend, PlatformCapabilities, PlatformPerformanceProfile, VerificationPlatform,
    WasmEnvironment,
};
use amari_core::Multivector;
use amari_info_geom::amari_chentsov_tensor;
#[cfg(feature = "automata")]
pub use automata::{
    AutomataGpuConfig, AutomataGpuError, AutomataGpuOps, AutomataGpuResult, GpuCellData,
    GpuEvolutionParams, GpuRuleConfig,
};
pub use benchmarks::{
    AmariMultiGpuBenchmarks, BenchmarkConfig, BenchmarkResult, BenchmarkRunner,
    BenchmarkSuiteResults, BenchmarkSummary, ScalingAnalysis,
};
use bytemuck::{Pod, Zeroable};
#[cfg(feature = "calculus")]
pub use calculus::GpuCalculus;
#[cfg(feature = "dual")]
pub use dual::{DualGpuError, DualGpuOps, DualGpuResult, DualOperation, GpuDualNumber};
#[cfg(feature = "enumerative")]
pub use enumerative::{
    EnumerativeGpuConfig, EnumerativeGpuContext, EnumerativeGpuError, EnumerativeGpuOps,
    EnumerativeGpuResult, GpuCSMData, GpuGromovWittenData, GpuIntersectionData,
    GpuLittlewoodRichardsonData, GpuLocalizationData, GpuMatroidRankData, GpuMultiIntersectData,
    GpuNamespaceData, GpuOperadData, GpuSchubertClass, GpuStabilityData, GpuTropicalSchubertData,
    GpuWDVVData,
};
#[cfg(all(feature = "enumerative", feature = "gf2"))]
pub use enumerative::{
    GpuFiniteFieldPointData, GpuKLPolynomialData, GpuRepresentabilityData,
    GpuWeightDistributionData,
};
#[cfg(feature = "functional")]
pub use functional::{
    AdaptiveFunctionalCompute, GpuFunctionalError, GpuFunctionalResult, GpuHilbertSpace,
    GpuMatrixOperator, GpuSpectralDecomposition,
};
#[cfg(feature = "fusion")]
pub use fusion::{
    FusionGpuError, FusionGpuResult, GpuHolographicTDC, GpuResonatorOutput, HolographicGpuOps,
};
#[cfg(feature = "gf2")]
pub use gf2::{
    GF2GpuContext, GF2GpuError, GF2GpuOps, GF2GpuResult, GpuGF2CliffordPair, GpuGF2HammingPair,
    GpuGF2MatVecData,
};
#[cfg(feature = "holographic")]
pub use holographic::{
    GpuHolographic, GpuHolographicError, GpuHolographicMemory, GpuHolographicResult,
    GpuOpticalField,
};
#[cfg(feature = "measure")]
pub use measure::{
    GpuIntegrator, GpuMonteCarloIntegrator, GpuMultidimIntegrator, GpuParametricDensity,
    GpuTropicalMeasure,
};
pub use multi_gpu::{
    ComputeIntensity, DeviceCapabilities, DeviceId, DeviceWorkload, GpuArchitecture, GpuDevice,
    IntelligentLoadBalancer, LoadBalancingStrategy, MultiGpuBarrier, PerformanceRecord,
    PerformanceStats, SynchronizationManager, Workload, WorkloadCoordinator,
};
pub use network::{AdaptiveNetworkCompute, GpuGeometricNetwork, GpuNetworkError, GpuNetworkResult};
pub use performance::{
    AdaptiveDispatchPolicy, CalibrationResult, GpuProfile, GpuProfiler, WorkgroupConfig,
    WorkgroupOptimizer,
};
#[cfg(feature = "probabilistic")]
pub use probabilistic::{GpuProbabilistic, GpuProbabilisticError, GpuProbabilisticResult};
pub use relativistic::{
    GpuRelativisticParticle, GpuRelativisticPhysics, GpuSpacetimeVector, GpuTrajectoryParams,
};
pub use shaders::{
    ShaderLibrary, DUAL_SHADERS, FUSION_SHADERS, TOPOLOGY_SHADERS, TROPICAL_SHADERS,
};
use thiserror::Error;

#[cfg(test)]
#[allow(dead_code)]
pub(crate) static GPU_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
pub use timeline::{
    BottleneckAnalysis, DeviceUtilizationStats, GpuTimelineAnalyzer, MultiGpuPerformanceMonitor,
    OptimizationRecommendation, PerformanceAnalysisReport, PerformanceBottleneck,
    PerformanceSummary, RecommendationPriority, SynchronizationAnalysis, TimelineEvent,
    UtilizationAnalysis,
};
#[cfg(feature = "topology")]
pub use topology::{
    AdaptiveTopologyCompute, GpuCriticalPoint, GpuTopology, GpuTopologyError, GpuTopologyResult,
};
#[cfg(feature = "tropical")]
pub use tropical::{TropicalExecutionPath, TropicalGpuError, TropicalGpuOps, TropicalGpuResult};
pub use unified::{
    BufferPoolStats, EnhancedGpuBufferPool, GpuAccelerated, GpuContext, GpuDispatcher,
    GpuOperationParams, GpuParam, MultiGpuStats, PoolEntryStats, SharedGpuContext, UnifiedGpuError,
    UnifiedGpuResult,
};
pub use verification::{
    GpuBoundaryVerifier, GpuVerificationError, RelativisticVerifier, StatisticalGpuVerifier,
    VerificationConfig, VerificationStrategy, VerifiedMultivector,
};
use wgpu::util::DeviceExt;

#[derive(Error, Debug)]
pub enum GpuError {
    #[error("Failed to initialize GPU: {0}")]
    InitializationError(String),

    #[error("GPU buffer error: {0}")]
    BufferError(String),

    #[error("Shader compilation error: {0}")]
    ShaderError(String),
}

/// GPU-accelerated Clifford algebra operations.
///
/// Public v1 exposes batch geometric products for flat multivector coefficient
/// arrays. Inputs must contain complete multivectors of length `2^(P+Q+R)` and
/// are computed on the GPU in `f32`, then converted back to `f64` for API
/// compatibility.
///
/// `AdaptiveCompute::batch_geometric_product` is a separate Cl(3,0,0) helper;
/// use `GpuCliffordAlgebra::new::<P,Q,R>()` directly for other signatures.
pub struct GpuCliffordAlgebra {
    device: wgpu::Device,
    queue: wgpu::Queue,
    compute_pipeline: wgpu::ComputePipeline,
    cayley_buffer: wgpu::Buffer,
    #[allow(dead_code)]
    dim: usize,
    basis_count: usize,
}

impl GpuCliffordAlgebra {
    /// Initialize GPU context and compile shaders
    pub async fn new<const P: usize, const Q: usize, const R: usize>() -> Result<Self, GpuError> {
        let instance = wgpu::Instance::default();

        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: None,
                force_fallback_adapter: false,
            })
            .await
            .ok_or_else(|| GpuError::InitializationError("No GPU adapter found".to_string()))?;

        let (device, queue) = adapter
            .request_device(
                &wgpu::DeviceDescriptor {
                    label: Some("Amari GPU Device"),
                    required_features: wgpu::Features::empty(),
                    required_limits: wgpu::Limits::default(),
                },
                None,
            )
            .await
            .map_err(|e| GpuError::InitializationError(e.to_string()))?;

        let dim = P + Q + R;
        let basis_count = 1 << dim;

        // Generate and upload Cayley table
        let cayley_table = Self::generate_cayley_table::<P, Q, R>();
        let cayley_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Cayley Table"),
            contents: bytemuck::cast_slice(&cayley_table),
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
        });

        // Create compute shader with a signature-specific basis count.
        let shader_source = GEOMETRIC_PRODUCT_SHADER.replace(
            "const BASIS_COUNT: u32 = 8u; // For 3D Clifford algebra",
            &format!("const BASIS_COUNT: u32 = {basis_count}u;"),
        );
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("Geometric Product Shader"),
            source: wgpu::ShaderSource::Wgsl(shader_source.into()),
        });

        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("Compute Bind Group Layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: false },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Compute Pipeline Layout"),
            bind_group_layouts: &[&bind_group_layout],
            push_constant_ranges: &[],
        });

        let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("Geometric Product Pipeline"),
            layout: Some(&pipeline_layout),
            module: &shader,
            entry_point: "main",
        });

        Ok(Self {
            device,
            queue,
            compute_pipeline,
            cayley_buffer,
            dim,
            basis_count,
        })
    }

    /// Generate Cayley table as flat array for GPU
    fn generate_cayley_table<const P: usize, const Q: usize, const R: usize>() -> Vec<CayleyEntry> {
        use amari_core::cayley::CayleyTable;

        let table = CayleyTable::<P, Q, R>::get();
        let basis_count = 1 << (P + Q + R);
        let mut flat_table = Vec::with_capacity(basis_count * basis_count);

        for i in 0..basis_count {
            for j in 0..basis_count {
                let (sign, index) = table.get_product(i, j);
                flat_table.push(CayleyEntry {
                    sign: sign as f32,
                    index: index as u32,
                });
            }
        }

        flat_table
    }

    /// Perform batch geometric product on GPU.
    pub async fn batch_geometric_product(
        &self,
        a_batch: &[f64],
        b_batch: &[f64],
    ) -> Result<Vec<f64>, GpuError> {
        let batch_size = self.validate_flat_batches(a_batch, b_batch)?;
        if batch_size == 0 {
            return Ok(Vec::new());
        }

        // Convert to f32 for GPU
        let a_f32: Vec<f32> = a_batch.iter().map(|&x| x as f32).collect();
        let b_f32: Vec<f32> = b_batch.iter().map(|&x| x as f32).collect();

        // Create GPU buffers
        let a_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("A Buffer"),
                contents: bytemuck::cast_slice(&a_f32),
                usage: wgpu::BufferUsages::STORAGE,
            });

        let b_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("B Buffer"),
                contents: bytemuck::cast_slice(&b_f32),
                usage: wgpu::BufferUsages::STORAGE,
            });

        let output_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Output Buffer"),
            size: (a_batch.len() * std::mem::size_of::<f32>()) as u64,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
            mapped_at_creation: false,
        });

        let staging_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Staging Buffer"),
            size: (a_batch.len() * std::mem::size_of::<f32>()) as u64,
            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        // Create bind group
        let bind_group_layout = self.compute_pipeline.get_bind_group_layout(0);
        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Compute Bind Group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: self.cayley_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: a_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: b_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: output_buffer.as_entire_binding(),
                },
            ],
        });

        // Dispatch compute shader
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Compute Encoder"),
            });

        {
            let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("Compute Pass"),
                timestamp_writes: None,
            });

            compute_pass.set_pipeline(&self.compute_pipeline);
            compute_pass.set_bind_group(0, &bind_group, &[]);
            compute_pass.dispatch_workgroups(batch_size as u32, 1, 1);
        }

        encoder.copy_buffer_to_buffer(
            &output_buffer,
            0,
            &staging_buffer,
            0,
            (a_batch.len() * std::mem::size_of::<f32>()) as u64,
        );

        self.queue.submit(Some(encoder.finish()));

        // Read back results
        let buffer_slice = staging_buffer.slice(..);
        let (sender, receiver) = futures::channel::oneshot::channel();
        buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
            let _ = sender.send(result);
        });

        self.device.poll(wgpu::Maintain::Wait);
        receiver
            .await
            .map_err(|_| GpuError::BufferError("Failed to receive buffer map result".to_string()))?
            .map_err(|e| GpuError::BufferError(e.to_string()))?;

        let data = buffer_slice.get_mapped_range();
        let result_f32: &[f32] = bytemuck::cast_slice(&data);
        let result: Vec<f64> = result_f32.iter().map(|&x| x as f64).collect();

        drop(data);
        staging_buffer.unmap();

        Ok(result)
    }

    /// Heuristic to determine if GPU should be used
    pub fn should_use_gpu(operation_count: usize) -> bool {
        // GPU is beneficial for batch operations with many multivectors
        operation_count >= 100
    }

    /// Number of basis blades for this signature.
    pub fn basis_count(&self) -> usize {
        self.basis_count
    }

    /// Algebra dimension `P + Q + R` for this GPU context.
    pub fn dimension(&self) -> usize {
        self.dim
    }

    fn validate_flat_batches(&self, a_batch: &[f64], b_batch: &[f64]) -> Result<usize, GpuError> {
        if a_batch.len() != b_batch.len() {
            return Err(GpuError::BufferError(
                "input batches must have the same coefficient count".to_string(),
            ));
        }
        if !a_batch.len().is_multiple_of(self.basis_count) {
            return Err(GpuError::BufferError(format!(
                "coefficient count {} is not a multiple of basis_count {}",
                a_batch.len(),
                self.basis_count
            )));
        }
        for (name, batch) in [("a", a_batch), ("b", b_batch)] {
            if let Some((index, _)) = batch
                .iter()
                .enumerate()
                .find(|(_, value)| !value.is_finite())
            {
                return Err(GpuError::BufferError(format!(
                    "{name}_batch coefficient {index} is not finite"
                )));
            }
        }
        Ok(a_batch.len() / self.basis_count)
    }
}

/// Cayley table entry for GPU
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
struct CayleyEntry {
    sign: f32,
    index: u32,
}

/// WGSL compute shader for geometric product
const GEOMETRIC_PRODUCT_SHADER: &str = r#"
struct CayleyEntry {
    sign: f32,
    index: u32,
}

@group(0) @binding(0)
var<storage, read> cayley_table: array<CayleyEntry>;

@group(0) @binding(1)
var<storage, read> a_batch: array<f32>;

@group(0) @binding(2)
var<storage, read> b_batch: array<f32>;

@group(0) @binding(3)
var<storage, read_write> output: array<f32>;

const BASIS_COUNT: u32 = 8u; // For 3D Clifford algebra

@compute @workgroup_size(1)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let batch_idx = global_id.x;
    let offset = batch_idx * BASIS_COUNT;
    
    // Clear output
    for (var k = 0u; k < BASIS_COUNT; k = k + 1u) {
        output[offset + k] = 0.0;
    }
    
    // Compute geometric product
    for (var i = 0u; i < BASIS_COUNT; i = i + 1u) {
        let a_coeff = a_batch[offset + i];
        if (abs(a_coeff) < 1e-14) {
            continue;
        }
        
        for (var j = 0u; j < BASIS_COUNT; j = j + 1u) {
            let b_coeff = b_batch[offset + j];
            if (abs(b_coeff) < 1e-14) {
                continue;
            }
            
            let table_idx = i * BASIS_COUNT + j;
            let entry = cayley_table[table_idx];
            output[offset + entry.index] += entry.sign * a_coeff * b_coeff;
        }
    }
}
"#;

/// Adaptive GPU/CPU dispatcher for the legacy Cl(3,0,0) flat-batch helper.
///
/// Single multivector products always use the CPU `amari-core` baseline.
/// `batch_geometric_product` accepts flat Cl(3,0,0) batches with 8 coefficients
/// per multivector and uses GPU only when a context is available and the batch
/// crosses `GpuCliffordAlgebra::should_use_gpu`.
pub struct AdaptiveCompute {
    gpu: Option<GpuCliffordAlgebra>,
}

impl AdaptiveCompute {
    /// Create with optional GPU acceleration
    pub async fn new<const P: usize, const Q: usize, const R: usize>() -> Self {
        let gpu = GpuCliffordAlgebra::new::<P, Q, R>().await.ok();
        Self { gpu }
    }

    /// Perform geometric product, automatically choosing CPU or GPU
    pub async fn geometric_product<const P: usize, const Q: usize, const R: usize>(
        &self,
        a: &Multivector<P, Q, R>,
        b: &Multivector<P, Q, R>,
    ) -> Multivector<P, Q, R> {
        // For single operations, always use CPU
        a.geometric_product(b)
    }

    /// Batch geometric product with adaptive dispatch for flat Cl(3,0,0) inputs.
    pub async fn batch_geometric_product(
        &self,
        a_batch: &[f64],
        b_batch: &[f64],
    ) -> Result<Vec<f64>, GpuError> {
        let batch_size = validate_cl3_flat_batches(a_batch, b_batch)?;
        if batch_size == 0 {
            return Ok(Vec::new());
        }

        if let Some(gpu) = &self.gpu {
            if GpuCliffordAlgebra::should_use_gpu(batch_size) {
                return gpu.batch_geometric_product(a_batch, b_batch).await;
            }
        }

        // Fallback to CPU
        let mut result = Vec::with_capacity(a_batch.len());
        for i in 0..batch_size {
            let start = i * 8;
            let end = start + 8;

            let a = Multivector::<3, 0, 0>::from_coefficients(a_batch[start..end].to_vec());
            let b = Multivector::<3, 0, 0>::from_coefficients(b_batch[start..end].to_vec());
            let product = a.geometric_product(&b);

            for j in 0..8 {
                result.push(product.get(j));
            }
        }

        Ok(result)
    }
}

fn validate_probability_like_vector(name: &str, values: &[f64]) -> Result<(), GpuError> {
    for (index, value) in values.iter().enumerate() {
        if !value.is_finite() {
            return Err(GpuError::BufferError(format!(
                "{name}[{index}] is not finite"
            )));
        }
        if *value < 0.0 {
            return Err(GpuError::BufferError(format!(
                "{name}[{index}] is negative"
            )));
        }
    }
    Ok(())
}

fn validate_kl_pair(index: usize, p: &[f64], q: &[f64]) -> Result<(), GpuError> {
    if p.len() != q.len() {
        return Err(GpuError::BufferError(format!(
            "divergence pair {index} length mismatch: p={}, q={}",
            p.len(),
            q.len()
        )));
    }
    validate_probability_like_vector("p", p)?;
    validate_probability_like_vector("q", q)?;
    for (coord, (pi, qi)) in p.iter().zip(q.iter()).enumerate() {
        if *pi > 0.0 && *qi <= 0.0 {
            return Err(GpuError::BufferError(format!(
                "divergence pair {index} has q[{coord}] <= 0 while p[{coord}] > 0"
            )));
        }
    }
    Ok(())
}

fn validate_cl3_flat_batches(a_batch: &[f64], b_batch: &[f64]) -> Result<usize, GpuError> {
    const CL3_BASIS_COUNT: usize = 8;
    if a_batch.len() != b_batch.len() {
        return Err(GpuError::BufferError(
            "input batches must have the same coefficient count".to_string(),
        ));
    }
    if !a_batch.len().is_multiple_of(CL3_BASIS_COUNT) {
        return Err(GpuError::BufferError(format!(
            "coefficient count {} is not a multiple of 8 for Cl(3,0,0)",
            a_batch.len()
        )));
    }
    for (name, batch) in [("a", a_batch), ("b", b_batch)] {
        if let Some((index, _)) = batch
            .iter()
            .enumerate()
            .find(|(_, value)| !value.is_finite())
        {
            return Err(GpuError::BufferError(format!(
                "{name}_batch coefficient {index} is not finite"
            )));
        }
    }
    Ok(a_batch.len() / CL3_BASIS_COUNT)
}

/// Information-geometry operations with GPU-ready infrastructure.
///
/// The public 0.20 surface is a correctness-first CPU baseline after WebGPU
/// context creation. Amari-Chentsov batches, Fisher metrics, and Bregman/KL-style
/// divergences are validated and computed with `amari-info-geom` semantics while
/// shader-backed tensor/fisher/divergence pipelines remain private restoration
/// candidates.
///
/// This preserves public API stability without claiming unvalidated GPU kernels.
pub struct GpuInfoGeometry {
    device: wgpu::Device,
    queue: wgpu::Queue,
    tensor_pipeline: wgpu::ComputePipeline,
    #[allow(dead_code)]
    fisher_pipeline: wgpu::ComputePipeline,
    #[allow(dead_code)]
    divergence_pipeline: wgpu::ComputePipeline,
}

impl GpuInfoGeometry {
    /// Initialize GPU context for information geometry operations
    pub async fn new() -> Result<Self, GpuError> {
        let instance = wgpu::Instance::default();

        // Try different adapter options, starting with high performance, then fallback
        let adapter = if let Some(adapter) = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: None,
                force_fallback_adapter: false,
            })
            .await
        {
            adapter
        } else if let Some(adapter) = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::LowPower,
                compatible_surface: None,
                force_fallback_adapter: false,
            })
            .await
        {
            adapter
        } else if let Some(adapter) = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::None,
                compatible_surface: None,
                force_fallback_adapter: true,
            })
            .await
        {
            adapter
        } else {
            return Err(GpuError::InitializationError(
                "No GPU adapter found".to_string(),
            ));
        };

        let (device, queue) = adapter
            .request_device(
                &wgpu::DeviceDescriptor {
                    label: Some("Amari GPU Info Geometry Device"),
                    required_features: wgpu::Features::empty(),
                    required_limits: wgpu::Limits::default(),
                },
                None,
            )
            .await
            .map_err(|e| GpuError::InitializationError(format!("Device request failed: {}", e)))?;

        // Create compute pipelines for different operations
        let tensor_pipeline = Self::create_tensor_pipeline(&device)?;
        let fisher_pipeline = Self::create_fisher_pipeline(&device)?;
        let divergence_pipeline = Self::create_divergence_pipeline(&device)?;

        Ok(Self {
            device,
            queue,
            tensor_pipeline,
            fisher_pipeline,
            divergence_pipeline,
        })
    }

    /// Create with specific device preference for edge computing
    pub async fn new_with_device_preference(device_type: &str) -> Result<Self, GpuError> {
        let (power_preference, force_fallback) = match device_type {
            "high-performance" => (wgpu::PowerPreference::HighPerformance, false),
            "low-power" => (wgpu::PowerPreference::LowPower, false),
            "fallback" => (wgpu::PowerPreference::None, true),
            _ => {
                return Err(GpuError::InitializationError(
                    "Invalid device type".to_string(),
                ))
            }
        };

        let instance = wgpu::Instance::default();

        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference,
                compatible_surface: None,
                force_fallback_adapter: force_fallback,
            })
            .await
            .ok_or_else(|| {
                GpuError::InitializationError("No suitable adapter found".to_string())
            })?;

        let (device, queue) = adapter
            .request_device(
                &wgpu::DeviceDescriptor {
                    label: Some("Amari GPU Info Geometry Device"),
                    required_features: wgpu::Features::empty(),
                    required_limits: wgpu::Limits::default(),
                },
                None,
            )
            .await
            .map_err(|e| GpuError::InitializationError(format!("Device request failed: {}", e)))?;

        let tensor_pipeline = Self::create_tensor_pipeline(&device)?;
        let fisher_pipeline = Self::create_fisher_pipeline(&device)?;
        let divergence_pipeline = Self::create_divergence_pipeline(&device)?;

        Ok(Self {
            device,
            queue,
            tensor_pipeline,
            fisher_pipeline,
            divergence_pipeline,
        })
    }

    /// Compute single Amari-Chentsov tensor (CPU fallback for small operations)
    pub async fn amari_chentsov_tensor(
        &self,
        x: &Multivector<3, 0, 0>,
        y: &Multivector<3, 0, 0>,
        z: &Multivector<3, 0, 0>,
    ) -> Result<f64, GpuError> {
        // For single computations, use CPU
        Ok(amari_chentsov_tensor(x, y, z))
    }

    /// Batch compute Amari-Chentsov tensors with CPU-baseline semantics.
    ///
    /// All three batches must have equal length. The current public path uses
    /// `amari-info-geom::amari_chentsov_tensor` for correctness; the shader path
    /// remains private until hardware parity is validated.
    pub async fn amari_chentsov_tensor_batch(
        &self,
        x_batch: &[Multivector<3, 0, 0>],
        y_batch: &[Multivector<3, 0, 0>],
        z_batch: &[Multivector<3, 0, 0>],
    ) -> Result<Vec<f64>, GpuError> {
        if x_batch.len() != y_batch.len() || x_batch.len() != z_batch.len() {
            return Err(GpuError::BufferError(format!(
                "batch length mismatch: x={}, y={}, z={}",
                x_batch.len(),
                y_batch.len(),
                z_batch.len()
            )));
        }
        if x_batch.is_empty() {
            return Ok(Vec::new());
        }

        let results = x_batch
            .iter()
            .zip(y_batch.iter())
            .zip(z_batch.iter())
            .map(|((x, y), z)| amari_chentsov_tensor(x, y, z))
            .collect();
        Ok(results)
    }

    /// Compute tensor batch from TypedArray-style flat data.
    ///
    /// Each item is `[x0,x1,x2, y0,y1,y2, z0,z1,z2]` for Cl(3,0,0) vector
    /// components. All values must be finite.
    pub async fn amari_chentsov_tensor_from_typed_arrays(
        &self,
        flat_data: &[f64],
        batch_size: usize,
    ) -> Result<Vec<f64>, GpuError> {
        let expected = batch_size.checked_mul(9).ok_or_else(|| {
            GpuError::BufferError("batch size overflows flat data shape".to_string())
        })?;
        if flat_data.len() != expected {
            return Err(GpuError::BufferError(format!(
                "invalid flat data size: expected {expected}, got {}",
                flat_data.len()
            )));
        }
        if let Some((index, _)) = flat_data
            .iter()
            .enumerate()
            .find(|(_, value)| !value.is_finite())
        {
            return Err(GpuError::BufferError(format!(
                "flat tensor coefficient {index} is not finite"
            )));
        }

        // Convert flat data to multivector batches
        let mut x_batch = Vec::with_capacity(batch_size);
        let mut y_batch = Vec::with_capacity(batch_size);
        let mut z_batch = Vec::with_capacity(batch_size);

        for i in 0..batch_size {
            let base = i * 9;
            let mut x = Multivector::zero();
            let mut y = Multivector::zero();
            let mut z = Multivector::zero();

            // Extract vector components
            x.set_vector_component(0, flat_data[base]);
            x.set_vector_component(1, flat_data[base + 1]);
            x.set_vector_component(2, flat_data[base + 2]);

            y.set_vector_component(0, flat_data[base + 3]);
            y.set_vector_component(1, flat_data[base + 4]);
            y.set_vector_component(2, flat_data[base + 5]);

            z.set_vector_component(0, flat_data[base + 6]);
            z.set_vector_component(1, flat_data[base + 7]);
            z.set_vector_component(2, flat_data[base + 8]);

            x_batch.push(x);
            y_batch.push(y);
            z_batch.push(z);
        }

        self.amari_chentsov_tensor_batch(&x_batch, &y_batch, &z_batch)
            .await
    }

    /// Get device information for edge computing
    pub async fn device_info(&self) -> Result<GpuDeviceInfo, GpuError> {
        Ok(GpuDeviceInfo::new(true, "WebGPU Device"))
    }

    /// Get current memory usage if the backend exposes it.
    ///
    /// Portable WebGPU does not expose allocator usage through `wgpu`, so this
    /// returns `0` rather than a fabricated placeholder value.
    pub async fn memory_usage(&self) -> Result<u64, GpuError> {
        Ok(0)
    }

    /// Compute a Fisher Information Matrix CPU baseline.
    ///
    /// Interprets `parameters` as coordinates of a probability-simplex style
    /// point and delegates to `amari-info-geom::DuallyFlatManifold`'s Fisher
    /// metric implementation. Values must be finite and non-negative.
    pub async fn fisher_information_matrix(
        &self,
        parameters: &[f64],
    ) -> Result<GpuFisherMatrix, GpuError> {
        validate_probability_like_vector("parameters", parameters)?;
        if parameters.is_empty() {
            return Ok(GpuFisherMatrix::new(Vec::new()));
        }
        let matrix = parameters
            .iter()
            .enumerate()
            .map(|(row, _)| {
                parameters
                    .iter()
                    .enumerate()
                    .map(|(col, value)| {
                        if row == col {
                            if *value > 1e-12 {
                                1.0 / value
                            } else {
                                1e12
                            }
                        } else {
                            0.0
                        }
                    })
                    .collect()
            })
            .collect();
        Ok(GpuFisherMatrix::new(matrix))
    }

    /// Batch compute KL-style Bregman divergences on the CPU correctness path.
    pub async fn bregman_divergence_batch(
        &self,
        p_batch: &[Vec<f64>],
        q_batch: &[Vec<f64>],
    ) -> Result<Vec<f64>, GpuError> {
        if p_batch.len() != q_batch.len() {
            return Err(GpuError::BufferError(format!(
                "batch length mismatch: p={}, q={}",
                p_batch.len(),
                q_batch.len()
            )));
        }
        for (index, (p, q)) in p_batch.iter().zip(q_batch.iter()).enumerate() {
            validate_kl_pair(index, p, q)?;
        }

        let results = p_batch
            .iter()
            .zip(q_batch.iter())
            .map(|(p, q)| {
                // Simple KL divergence implementation
                p.iter()
                    .zip(q.iter())
                    .map(|(pi, qi)| {
                        if *pi > 0.0 && *qi > 0.0 {
                            pi * (pi / qi).ln()
                        } else {
                            0.0
                        }
                    })
                    .sum()
            })
            .collect();
        Ok(results)
    }

    // Private implementation methods

    /// GPU tensor batch computation implementation
    ///
    /// This method contains the full WebGPU implementation for GPU-accelerated
    /// tensor computation using WGSL compute shaders. Currently not used in the
    /// public API due to GPU access restrictions in test environments.
    ///
    /// In production environments with proper GPU access, this method would be
    /// called from `amari_chentsov_tensor_batch()` for large batch sizes.
    #[allow(dead_code)] // Currently unused due to CPU fallback
    async fn compute_tensor_batch_gpu(
        &self,
        x_batch: &[Multivector<3, 0, 0>],
        y_batch: &[Multivector<3, 0, 0>],
        z_batch: &[Multivector<3, 0, 0>],
    ) -> Result<Vec<f64>, GpuError> {
        let batch_size = x_batch.len();

        // Create input buffers
        let x_data: Vec<f32> = x_batch
            .iter()
            .flat_map(|mv| {
                vec![
                    mv.vector_component(0) as f32,
                    mv.vector_component(1) as f32,
                    mv.vector_component(2) as f32,
                ]
            })
            .collect();

        let y_data: Vec<f32> = y_batch
            .iter()
            .flat_map(|mv| {
                vec![
                    mv.vector_component(0) as f32,
                    mv.vector_component(1) as f32,
                    mv.vector_component(2) as f32,
                ]
            })
            .collect();

        let z_data: Vec<f32> = z_batch
            .iter()
            .flat_map(|mv| {
                vec![
                    mv.vector_component(0) as f32,
                    mv.vector_component(1) as f32,
                    mv.vector_component(2) as f32,
                ]
            })
            .collect();

        // Create GPU buffers
        let x_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("X Batch Buffer"),
                contents: bytemuck::cast_slice(&x_data),
                usage: wgpu::BufferUsages::STORAGE,
            });

        let y_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("Y Batch Buffer"),
                contents: bytemuck::cast_slice(&y_data),
                usage: wgpu::BufferUsages::STORAGE,
            });

        let z_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("Z Batch Buffer"),
                contents: bytemuck::cast_slice(&z_data),
                usage: wgpu::BufferUsages::STORAGE,
            });

        let output_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Output Buffer"),
            size: (batch_size * 4) as u64, // f32 results
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
            mapped_at_creation: false,
        });

        let staging_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Staging Buffer"),
            size: (batch_size * 4) as u64,
            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        // Create bind group
        let bind_group_layout = self.tensor_pipeline.get_bind_group_layout(0);
        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Tensor Compute Bind Group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: x_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: y_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: z_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: output_buffer.as_entire_binding(),
                },
            ],
        });

        // Dispatch compute shader
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Tensor Compute Encoder"),
            });

        {
            let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("Tensor Compute Pass"),
                timestamp_writes: None,
            });
            compute_pass.set_pipeline(&self.tensor_pipeline);
            compute_pass.set_bind_group(0, &bind_group, &[]);
            let workgroup_count = batch_size.div_ceil(64); // 64 threads per workgroup
            compute_pass.dispatch_workgroups(workgroup_count as u32, 1, 1);
        }

        encoder.copy_buffer_to_buffer(
            &output_buffer,
            0,
            &staging_buffer,
            0,
            (batch_size * 4) as u64,
        );

        self.queue.submit(std::iter::once(encoder.finish()));

        // Read back results
        let buffer_slice = staging_buffer.slice(..);
        let (sender, receiver) = futures::channel::oneshot::channel();
        buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
            let _ = sender.send(result);
        });

        self.device.poll(wgpu::Maintain::Wait);

        receiver
            .await
            .map_err(|_| GpuError::BufferError("Failed to receive buffer map result".to_string()))?
            .map_err(|e| GpuError::BufferError(format!("Buffer mapping failed: {:?}", e)))?;

        let data = buffer_slice.get_mapped_range();
        let result_f32: &[f32] = bytemuck::cast_slice(&data);
        let results: Vec<f64> = result_f32.iter().map(|&x| x as f64).collect();

        drop(data);
        staging_buffer.unmap();

        Ok(results)
    }

    fn create_tensor_pipeline(device: &wgpu::Device) -> Result<wgpu::ComputePipeline, GpuError> {
        let shader_source = TENSOR_COMPUTE_SHADER;
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("Tensor Compute Shader"),
            source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(shader_source)),
        });

        let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("Tensor Compute Pipeline"),
            layout: None,
            module: &shader,
            entry_point: "main",
        });

        Ok(compute_pipeline)
    }

    fn create_fisher_pipeline(device: &wgpu::Device) -> Result<wgpu::ComputePipeline, GpuError> {
        // Placeholder - would implement Fisher matrix computation shader
        Self::create_tensor_pipeline(device)
    }

    fn create_divergence_pipeline(
        device: &wgpu::Device,
    ) -> Result<wgpu::ComputePipeline, GpuError> {
        // Placeholder - would implement Bregman divergence computation shader
        Self::create_tensor_pipeline(device)
    }
}

/// GPU device information for edge computing
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GpuDeviceInfo {
    is_gpu: bool,
    description: String,
}

impl GpuDeviceInfo {
    fn new(is_gpu: bool, description: &str) -> Self {
        Self {
            is_gpu,
            description: description.to_string(),
        }
    }

    pub fn is_gpu(&self) -> bool {
        self.is_gpu
    }

    pub fn supports_webgpu(&self) -> bool {
        self.is_gpu
    }

    pub fn is_initialized(&self) -> bool {
        true
    }

    /// Human-readable device/backend description.
    pub fn description(&self) -> &str {
        &self.description
    }
}

/// Fisher Information Matrix returned by `GpuInfoGeometry`.
#[derive(Clone, Debug, PartialEq)]
pub struct GpuFisherMatrix {
    matrix: Vec<Vec<f64>>,
}

impl GpuFisherMatrix {
    fn new(matrix: Vec<Vec<f64>>) -> Self {
        Self { matrix }
    }

    /// Borrow the matrix rows.
    pub fn matrix(&self) -> &[Vec<f64>] {
        &self.matrix
    }

    /// Matrix dimension, assuming the validated square matrices produced by this crate.
    pub fn dimension(&self) -> usize {
        self.matrix.len()
    }

    pub async fn eigenvalues(&self) -> Result<Vec<f64>, GpuError> {
        // Simplified eigenvalue computation
        let mut eigenvals = Vec::new();
        for i in 0..self.matrix.len() {
            if i < self.matrix[i].len() {
                eigenvals.push(self.matrix[i][i]);
            }
        }
        Ok(eigenvals)
    }
}

/// WGSL compute shader for batch Amari-Chentsov tensor computation
const TENSOR_COMPUTE_SHADER: &str = r#"
@group(0) @binding(0)
var<storage, read> x_batch: array<vec3<f32>>;

@group(0) @binding(1)
var<storage, read> y_batch: array<vec3<f32>>;

@group(0) @binding(2)
var<storage, read> z_batch: array<vec3<f32>>;

@group(0) @binding(3)
var<storage, read_write> output: array<f32>;

@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let idx = global_id.x;
    if (idx >= arrayLength(&x_batch)) {
        return;
    }

    let x = x_batch[idx];
    let y = y_batch[idx];
    let z = z_batch[idx];

    // Compute scalar triple product: x · (y × z)
    let cross_yz = cross(y, z);
    let scalar_triple = dot(x, cross_yz);

    output[idx] = scalar_triple;
}
"#;

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

    #[test]
    fn test_should_use_gpu() {
        assert!(!GpuCliffordAlgebra::should_use_gpu(10));
        assert!(GpuCliffordAlgebra::should_use_gpu(1000));
    }

    #[test]
    fn test_should_use_gpu_threshold() {
        // Test boundary conditions around the threshold
        assert!(!GpuCliffordAlgebra::should_use_gpu(99));
        assert!(GpuCliffordAlgebra::should_use_gpu(100));
        assert!(GpuCliffordAlgebra::should_use_gpu(101));
    }

    #[test]
    fn test_should_use_gpu_zero_batch() {
        assert!(!GpuCliffordAlgebra::should_use_gpu(0));
    }

    #[test]
    fn test_should_use_gpu_single_element() {
        assert!(!GpuCliffordAlgebra::should_use_gpu(1));
    }

    #[test]
    fn test_gpu_error_display() {
        let init_err = GpuError::InitializationError("No GPU found".to_string());
        assert!(init_err.to_string().contains("Failed to initialize GPU"));

        let buffer_err = GpuError::BufferError("Buffer too small".to_string());
        assert!(buffer_err.to_string().contains("buffer error"));

        let shader_err = GpuError::ShaderError("Invalid syntax".to_string());
        assert!(shader_err.to_string().contains("Shader compilation"));
    }

    #[test]
    fn test_gpu_error_debug() {
        let err = GpuError::InitializationError("test".to_string());
        let debug_str = format!("{:?}", err);
        assert!(debug_str.contains("InitializationError"));
    }

    #[test]
    fn test_gpu_error_variants() {
        // Test all error variants can be created and display correctly
        let errors = vec![
            GpuError::InitializationError("init failed".to_string()),
            GpuError::BufferError("buffer failed".to_string()),
            GpuError::ShaderError("shader failed".to_string()),
        ];

        for err in errors {
            // Ensure Display trait works
            let _ = err.to_string();
            // Ensure Debug trait works
            let _ = format!("{:?}", err);
        }
    }

    #[tokio::test]
    #[ignore = "GPU hardware required, may fail in CI/CD environments"]
    async fn test_adaptive_compute_geometric_product() {
        // Test AdaptiveCompute which has CPU fallback
        let adaptive = AdaptiveCompute::new::<3, 0, 0>().await;

        let e1 = Multivector::<3, 0, 0>::basis_vector(0);
        let e2 = Multivector::<3, 0, 0>::basis_vector(1);

        // Single product - always uses CPU, returns Multivector directly
        let result = adaptive.geometric_product(&e1, &e2).await;
        // e1 * e2 = e12 (bivector)
        assert!(result.magnitude() > 0.0);
    }

    #[tokio::test]
    #[ignore = "GPU hardware required, may fail in CI/CD environments"]
    async fn test_adaptive_compute_batch_small() {
        // Test AdaptiveCompute with small batch (should use CPU)
        // Skip if GPU initialization fails (expected in CI)
        let adaptive = AdaptiveCompute::new::<3, 0, 0>().await;

        // Create flat coefficient arrays (8 elements per Cl(3,0,0) multivector)
        let e1_coeffs = vec![0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; // e1
        let e2_coeffs = vec![0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]; // e2

        // 2 multivectors in batch
        let mut a_batch = Vec::new();
        let mut b_batch = Vec::new();
        a_batch.extend_from_slice(&e1_coeffs);
        a_batch.extend_from_slice(&e1_coeffs);
        b_batch.extend_from_slice(&e2_coeffs);
        b_batch.extend_from_slice(&e2_coeffs);

        let result = adaptive.batch_geometric_product(&a_batch, &b_batch).await;
        assert!(result.is_ok());
        // 2 multivectors * 8 coefficients = 16
        assert_eq!(result.unwrap().len(), 16);
    }

    #[test]
    fn test_gpu_device_info_methods() {
        let info = GpuDeviceInfo::new(true, "Test GPU");

        assert!(info.is_gpu());
        // supports_webgpu returns is_gpu
        assert!(info.supports_webgpu());
        assert!(info.is_initialized());
    }

    #[test]
    fn test_gpu_device_info_cpu() {
        let info = GpuDeviceInfo::new(false, "CPU Fallback");

        assert!(!info.is_gpu());
        assert!(!info.supports_webgpu());
        assert!(info.is_initialized());
    }

    #[tokio::test]
    async fn test_gpu_info_geometry_creation() {
        // Skip GPU tests in CI environments where GPU is not available
        if std::env::var("CI").is_ok()
            || std::env::var("GITHUB_ACTIONS").is_ok()
            || std::env::var("DISPLAY").is_err()
        {
            println!("Skipping GPU test in CI environment");
            return;
        }

        // This test will fail if no GPU is available, which is expected in CI
        match GpuInfoGeometry::new().await {
            Ok(_) => {
                // GPU available - test basic functionality
                println!("GPU initialization successful");
            }
            Err(GpuError::InitializationError(_)) => {
                // No GPU available - this is fine
                println!("GPU initialization failed - no GPU available");
            }
            Err(e) => panic!("Unexpected error: {:?}", e),
        }
    }

    #[tokio::test]
    async fn test_gpu_fisher_matrix_eigenvalues() {
        let matrix = GpuFisherMatrix::new(vec![
            vec![1.0, 0.0, 0.0],
            vec![0.0, 2.0, 0.0],
            vec![0.0, 0.0, 3.0],
        ]);
        let eigenvalues = matrix.eigenvalues().await.unwrap();
        assert_eq!(eigenvalues.len(), 3);
        assert_eq!(eigenvalues[0], 1.0);
        assert_eq!(eigenvalues[1], 2.0);
        assert_eq!(eigenvalues[2], 3.0);
    }

    #[tokio::test]
    async fn test_gpu_fisher_matrix_empty() {
        let matrix = GpuFisherMatrix::new(vec![]);
        let eigenvalues = matrix.eigenvalues().await.unwrap();
        assert!(eigenvalues.is_empty());
    }

    #[tokio::test]
    async fn test_gpu_fisher_matrix_single_element() {
        let matrix = GpuFisherMatrix::new(vec![vec![5.0]]);
        let eigenvalues = matrix.eigenvalues().await.unwrap();
        assert_eq!(eigenvalues.len(), 1);
        assert_eq!(eigenvalues[0], 5.0);
    }

    #[test]
    fn test_cayley_entry_struct() {
        // Test that CayleyEntry can be created and is Pod-compatible
        let entry = CayleyEntry {
            sign: 1.0,
            index: 5,
        };
        assert_eq!(entry.sign, 1.0);
        assert_eq!(entry.index, 5);

        // Test bytemuck cast works (verifies Pod + Zeroable traits)
        let entries = vec![
            entry,
            CayleyEntry {
                sign: -1.0,
                index: 3,
            },
        ];
        let bytes: &[u8] = bytemuck::cast_slice(&entries);
        assert_eq!(bytes.len(), 16); // 2 entries * 8 bytes each (f32 + u32)
    }

    #[test]
    fn test_cayley_entry_zero() {
        // Test that CayleyEntry implements Zeroable
        let zeroed: CayleyEntry = bytemuck::Zeroable::zeroed();
        assert_eq!(zeroed.sign, 0.0);
        assert_eq!(zeroed.index, 0);
    }

    #[test]
    fn test_geometric_product_shader_not_empty() {
        // Verify shader constant is properly defined
        assert!(!GEOMETRIC_PRODUCT_SHADER.is_empty());
        assert!(GEOMETRIC_PRODUCT_SHADER.contains("@compute"));
        assert!(GEOMETRIC_PRODUCT_SHADER.contains("@workgroup_size"));
        assert!(GEOMETRIC_PRODUCT_SHADER.contains("CayleyEntry"));
    }

    #[test]
    fn test_tensor_compute_shader_not_empty() {
        // Verify tensor shader constant is properly defined
        assert!(!TENSOR_COMPUTE_SHADER.is_empty());
        assert!(TENSOR_COMPUTE_SHADER.contains("@compute"));
        assert!(TENSOR_COMPUTE_SHADER.contains("@workgroup_size"));
        assert!(TENSOR_COMPUTE_SHADER.contains("cross"));
        assert!(TENSOR_COMPUTE_SHADER.contains("dot"));
    }

    #[test]
    fn test_gpu_error_from_string() {
        // Test error messages contain the original message
        let msg = "Custom error message";
        let err = GpuError::InitializationError(msg.to_string());
        assert!(err.to_string().contains(msg));

        let err = GpuError::BufferError(msg.to_string());
        assert!(err.to_string().contains(msg));

        let err = GpuError::ShaderError(msg.to_string());
        assert!(err.to_string().contains(msg));
    }

    #[test]
    fn test_should_use_gpu_large_batch() {
        // Test with large batch sizes
        assert!(GpuCliffordAlgebra::should_use_gpu(1000));
        assert!(GpuCliffordAlgebra::should_use_gpu(10000));
        assert!(GpuCliffordAlgebra::should_use_gpu(100000));
    }

    #[test]
    fn test_should_use_gpu_near_threshold() {
        // Test values near the threshold
        for i in 0..100 {
            assert!(!GpuCliffordAlgebra::should_use_gpu(i));
        }
        for i in 100..200 {
            assert!(GpuCliffordAlgebra::should_use_gpu(i));
        }
    }

    #[test]
    fn test_gpu_device_info_initialized_always_true() {
        // is_initialized always returns true
        let gpu_info = GpuDeviceInfo::new(true, "GPU");
        let cpu_info = GpuDeviceInfo::new(false, "CPU");
        assert!(gpu_info.is_initialized());
        assert!(cpu_info.is_initialized());
    }

    #[tokio::test]
    async fn test_adaptive_compute_cpu_fallback_small_batch() {
        // Test that small batches use CPU (doesn't require GPU)
        let adaptive = AdaptiveCompute { gpu: None };

        let e1_coeffs = vec![0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
        let e2_coeffs = vec![0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0];

        let result = adaptive
            .batch_geometric_product(&e1_coeffs, &e2_coeffs)
            .await;
        assert!(result.is_ok());
        let coeffs = result.unwrap();
        assert_eq!(coeffs.len(), 8);
        // e1 * e2 = e12 (bivector) - verify a non-zero coefficient exists
        let has_nonzero = coeffs.iter().any(|&c| c.abs() > 0.5);
        assert!(has_nonzero, "Product should have non-zero coefficients");
    }

    #[tokio::test]
    async fn test_adaptive_compute_cpu_fallback_multiple_elements() {
        // Test CPU fallback with multiple multivectors
        let adaptive = AdaptiveCompute { gpu: None };

        let mut a_batch = Vec::new();
        let mut b_batch = Vec::new();

        // 5 multivectors
        for _ in 0..5 {
            a_batch.extend_from_slice(&[0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
            b_batch.extend_from_slice(&[0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
        }

        let result = adaptive.batch_geometric_product(&a_batch, &b_batch).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 40); // 5 * 8
    }

    #[tokio::test]
    async fn test_adaptive_compute_geometric_product_cpu() {
        // Test single geometric product (always uses CPU)
        let adaptive = AdaptiveCompute { gpu: None };

        let a = Multivector::<3, 0, 0>::scalar(2.0);
        let b = Multivector::<3, 0, 0>::scalar(3.0);

        let result = adaptive.geometric_product(&a, &b).await;
        assert!((result.scalar_part() - 6.0).abs() < 1e-10);
    }

    #[tokio::test]
    async fn test_adaptive_compute_geometric_product_basis_vectors() {
        // Test basis vector products
        let adaptive = AdaptiveCompute { gpu: None };

        let e1 = Multivector::<3, 0, 0>::basis_vector(0);
        let e1_clone = Multivector::<3, 0, 0>::basis_vector(0);

        // e1 * e1 = 1 in Cl(3,0,0)
        let result = adaptive.geometric_product(&e1, &e1_clone).await;
        assert!((result.scalar_part() - 1.0).abs() < 1e-10);
    }
}