Spaces:
Paused

File size: 88,203 Bytes
bc9f3e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

hardware.py β€” GPU/device detection and the "Fix Environment" self-repair

helper (installs a hardware-matched PyTorch build at runtime).

"""

import os
import re
import subprocess
import sys
from pathlib import Path
from typing import Optional

import torch
import warnings

# Windows flag to suppress creating a console window for spawned subprocesses
CREATE_NO_WINDOW: int = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if sys.platform == "win32" else 0

# ── Frozen-build pip helpers ───────────────────────────────────────────────
# In the PyInstaller/Store build sys.executable is the app exe (not Python),
# so we ship a minimal bundled Python+pip alongside the app and use it for
# all runtime pip installs (GPU PyTorch, llama-cpp-python, agent packages).
# Packages install into user_data/packages/ (writable, isolated from the
# frozen bundle) and the startup hook (pyi_rth_smolagents_source.py) adds
# that directory to sys.path + torch/lib to os.environ["PATH"].

FROZEN_PYTHON_EXE: Optional[str] = None  # resolved once, cached

def _find_frozen_python() -> Optional[str]:
    """Locate the bundled Python interpreter shipped with the frozen app.



    The build pipeline (build_standalone.py) downloads the Python embeddable

    package, adds pip, and places it in <app>/python/.  This function finds

    that interpreter so pip-based installs work in the packaged build.

    Returns the path to python.exe or None when unavailable.

    """
    global FROZEN_PYTHON_EXE
    if FROZEN_PYTHON_EXE is not None:
        return FROZEN_PYTHON_EXE

    if not getattr(sys, "frozen", False):
        return None

    # APP_ROOT = parent of internal/ (the PyInstaller contents_directory).
    app_root = Path(sys._MEIPASS).parent
    candidate = app_root / "python" / "python.exe"
    if candidate.is_file():
        FROZEN_PYTHON_EXE = str(candidate)
        return FROZEN_PYTHON_EXE
    return None


def _frozen_pip_target() -> str:
    """Return the --target directory for pip installs in the frozen build.



    Packages land in user_data/packages/ which the startup hook adds to

    sys.path (and torch/lib to os.environ["PATH"]).

    """
    from backend.paths import user_data_dir
    return str(user_data_dir() / "packages")


def _pip_base_args() -> list:
    """Return the base pip-install command prefix.



    In the frozen build the bundled Python+pip is used and every install

    targets user_data/packages/ (--target) for isolation.  In dev/venv

    builds the normal sys.executable is used.

    """
    frozen_py = _find_frozen_python()
    if frozen_py:
        return [frozen_py, "-m", "pip", "install", "--target", _frozen_pip_target()]
    return [sys.executable, "-m", "pip", "install"]

# Canonical GPU-detection helpers live in llama_health (which never imports
# backend modules, so there is no import cycle). Reuse them here instead of
# maintaining a second copy β€” the compute-capability signal decides whether
# any CUDA wheel can actually run on this machine.
from backend.llama_health import _gpu_compute_capability, _gpu_name


def _llama_cpp_cpu_wheel_url() -> Optional[str]:
    """Prebuilt CPU wheel for llama-cpp-python on Windows (any Python 3.x).



    `pip install llama-cpp-python` without an explicit wheel URL resolves to

    the sdist and builds from source β€” which needs a C/C++ toolchain that most

    end-user PCs (and always the packaged Microsoft Store build) don't have,

    so the install fails out of the box. Every CPU fallback must therefore

    install this prebuilt wheel instead. Returns None on non-Windows, where

    the plain PyPI package remains the fallback."""
    if sys.platform != "win32":
        return None
    return (
        "https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34/"
        "llama_cpp_python-0.3.34-py3-none-win_amd64.whl"
    )


def _llama_cpp_vulkan_wheel_url() -> Optional[str]:
    """Prebuilt Vulkan wheel for llama-cpp-python on Windows β€” hardware

    offload for AMD/Intel GPUs via the Vulkan backend. Like the CPU wheel it

    is built WITHOUT AVX-512 code paths, so it loads on the same Intel

    consumer CPUs the CUDA wheels crash on (see _cpu_supports_avx512)."""
    if sys.platform != "win32":
        return None
    return (
        "https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34-vulkan/"
        "llama_cpp_python-0.3.34-py3-none-win_amd64.whl"
    )


def _cpu_supports_avx512() -> bool:
    """True when this CPU can actually execute AVX-512 instructions.



    The abetlen llama-cpp-python CUDA wheels (v0.3.34-cu124 / -cu130 β€” the

    ones the installer picks for a modern NVIDIA GPU with a matching CUDA

    runtime) are compiled WITH AVX-512 code paths. On CPUs without AVX-512

    β€” every Intel consumer chip since Alder Lake, e.g. i7-14700F (Raptor

    Lake) β€” model LOADING crashes with STATUS_ILLEGAL_INSTRUCTION

    (0xc000001d / WinError -1073741795) inside llama.cpp's native code

    because some quantize/load paths are not runtime-dispatched: the app

    showed "Failed to load GGUF model … Windows Error 0xc000001d" for EVERY

    local GGUF on such a machine. The CPU wheel (and the vulkan wheel) are

    built WITHOUT AVX-512 and load fine, so the installer must pick them on

    such CPUs β€” GPU offload still works via the external llama-server

    backend, whose release binaries ship per-architecture CPU DLLs.



    Detected via Windows' documented IsProcessorFeaturePresent(

    PF_AVX512F_INSTRUCTIONS_AVAILABLE). Non-Windows / unknown OS verdicts

    return True so a capable machine is never denied the CUDA wheel.

    """
    if sys.platform != "win32":
        return True
    try:
        import ctypes

        return bool(ctypes.windll.kernel32.IsProcessorFeaturePresent(41))
    except Exception:
        # OS can't tell us β€” assume AVX-512 capable (the historical default).
        return True


def _cpu_name() -> str:
    """The CPU's model name (e.g. 'Intel(R) Core(TM) i7-14700F') for

    installer messages β€” read from the registry, never raising."""
    try:
        import winreg

        with winreg.OpenKey(
            winreg.HKEY_LOCAL_MACHINE,
            r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
        ) as key:
            value, _ = winreg.QueryValueEx(key, "ProcessorNameString")
            return str(value).strip() or "unknown CPU"
    except Exception:
        return "this CPU"


def is_illegal_instruction_error(exc) -> bool:
    """True when an exception (or any exception in its chain) is Windows'

    STATUS_ILLEGAL_INSTRUCTION (0xc000001d / WinError -1073741795) β€” the

    signature of a native binary executing a CPU instruction this CPU does

    not support, e.g. an AVX-512 llama-cpp-python CUDA wheel on an Intel

    consumer CPU (see _cpu_supports_avx512). Used to route around a broken

    wheel (auto-fallback to llama-server) and to surface the REAL cause in

    GGUF load errors instead of "corrupted file" guesses."""
    seen = set()
    while exc is not None and id(exc) not in seen:
        seen.add(id(exc))
        msg = f"{exc!r} {exc}".lower()
        if any(tok in msg for tok in ("0xc000001d", "-1073741795",
                                      "illegal instruction",
                                      "status_illegal_instruction")):
            return True
        exc = getattr(exc, "__cause__", None) or getattr(exc, "__context__", None)
    return False


class HardwareManager:
    PYTORCH_AUTO = "auto"
    PYTORCH_CPU = "cpu"
    PYTORCH_CUDA = "cuda"
    PYTORCH_XPU = "xpu"
    PYTORCH_ROCM = "rocm"

    LLAMA_CPP_AUTO = "auto"
    LLAMA_CPP_CPU = "cpu"
    LLAMA_CPP_CUDA = "cuda"
    LLAMA_CPP_VULKAN = "vulkan"

    @staticmethod
    def _normalize_gpu_brand(name: str) -> str:
        lowered = (name or "").lower()
        if any(token in lowered for token in ("nvidia", "geforce", "rtx", "gtx", "quadro")):
            return "nvidia"
        if any(token in lowered for token in ("amd", "radeon", "rx ", "vega", "firepro")):
            return "amd"
        if "intel" in lowered:
            return "intel"
        return "unknown"

    @staticmethod
    def detect_video_controllers() -> list[dict]:
        """Return display adapters visible to the OS.



        This intentionally does not depend on torch. Store/customer machines

        often start with CPU-only torch, which means torch cannot see Intel,

        AMD, or even NVIDIA hardware yet. Windows CIM is the most reliable

        low-friction signal for recommending an install path.



        VRAM note: Win32_VideoController.AdapterRAM is a 32-bit DWORD, so it

        caps at ~4 GB and returns the 0xFFFFFFFF "unknown" sentinel when

        unavailable β€” on any NVIDIA GPU with more VRAM than that it is

        garbage (a 24 GB card reports ~4.0 GB). NVIDIA controllers therefore

        get their true total VRAM from nvidia-smi (memory.total), matched by

        GPU name with an index-order fallback; non-NVIDIA cards keep the CIM

        value (their VRAM fits in a DWORD).

        """
        controllers = []
        if sys.platform == "win32":
            ps = (
                "Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue | "
                "Select-Object Name,AdapterRAM,DriverVersion,DriverDate | ConvertTo-Json -Compress"
            )
            try:
                result = subprocess.run(
                    ["powershell", "-NoProfile", "-Command", ps],
                    capture_output=True, text=True, check=False, timeout=10,
                    creationflags=CREATE_NO_WINDOW,
                )
                if result.returncode == 0 and result.stdout.strip():
                    import json
                    data = json.loads(result.stdout)
                    if isinstance(data, dict):
                        data = [data]
                    for item in data or []:
                        name = str(item.get("Name") or "").strip()
                        if not name:
                            continue
                        controllers.append({
                            "name": name,
                            "brand": HardwareManager._normalize_gpu_brand(name),
                            "adapter_ram": item.get("AdapterRAM"),
                            "driver_version": item.get("DriverVersion") or "",
                            "driver_date": item.get("DriverDate") or "",
                        })
            except Exception:
                pass
            # Only NVIDIA VRAM is untrustworthy (DWORD cap), so only then is
            # an nvidia-smi probe worth spawning β€” pure Intel/AMD machines
            # never pay for it.
            nvidia_controllers = [c for c in controllers if c["brand"] == "nvidia"]
            if nvidia_controllers:
                smi_gpus = HardwareManager._nvidia_smi_gpus()
                used = set()
                for c in nvidia_controllers:
                    # Prefer a name match β€” CIM and nvidia-smi can order GPUs
                    # differently on multi-GPU machines β€” then fall back to
                    # the first unmatched GPU (index order).
                    target = None
                    for i, g in enumerate(smi_gpus):
                        if i not in used and HardwareManager._gpu_names_match(c["name"], g["name"]):
                            target = i
                            break
                    if target is None:
                        for i in range(len(smi_gpus)):
                            if i not in used:
                                target = i
                                break
                    if target is not None:
                        used.add(target)
                        c["adapter_ram"] = HardwareManager._vram_bytes(smi_gpus[target]["vram_mib"])
        if controllers:
            return controllers

        # Fallbacks for machines where CIM is unavailable.
        for g in HardwareManager._nvidia_smi_gpus():
            controllers.append({
                "name": g["name"],
                "brand": "nvidia",
                "adapter_ram": HardwareManager._vram_bytes(g["vram_mib"]),
                "driver_version": g.get("driver_version") or "",
                "driver_date": "",
            })
        return controllers

    @staticmethod
    def _nvidia_smi_gpus() -> list[dict]:
        """Name + total VRAM (MiB) + driver version of each NVIDIA GPU, from

        nvidia-smi. Returns [] when nvidia-smi is unavailable β€” callers must

        treat that as "unknown VRAM", never as zero. Win32_VideoController.

        AdapterRAM cannot be trusted for VRAM: it is a 32-bit DWORD that caps

        at ~4 GB (see detect_video_controllers).

        """
        try:
            result = subprocess.run(
                ["nvidia-smi", "--query-gpu=name,memory.total,driver_version",
                 "--format=csv,noheader,nounits"],
                capture_output=True, text=True, check=False, timeout=10,
                creationflags=CREATE_NO_WINDOW,
            )
            if result.returncode != 0:
                return []
            gpus = []
            for line in result.stdout.splitlines():
                parts = [p.strip() for p in line.split(",")]
                if not parts or not parts[0] or parts[0].lower() == "n/a":
                    continue
                mib = 0
                m = re.search(r"\d+", parts[1] if len(parts) > 1 else "")
                if m:
                    mib = int(m.group(0))
                gpus.append({
                    "name": parts[0],
                    "vram_mib": mib,
                    "driver_version": parts[2] if len(parts) > 2 else "",
                })
            return gpus
        except Exception:
            return []

    @staticmethod
    def _gpu_names_match(a: str, b: str) -> bool:
        """True if two GPU names refer to the same card β€” normalized substring

        match (either direction). CIM and nvidia-smi usually agree exactly on

        NVIDIA names but can differ in spacing/case."""
        na = re.sub(r"[^a-z0-9]+", "", (a or "").lower())
        nb = re.sub(r"[^a-z0-9]+", "", (b or "").lower())
        return bool(na and nb and (na in nb or nb in na))

    @staticmethod
    def _vram_bytes(mib: int) -> int:
        """Convert nvidia-smi MiB to bytes (stored in adapter_ram so existing

        consumers keep working)."""
        return int(mib) * 1024 * 1024

    @staticmethod
    def _intel_xpu_likely_supported(gpu_name: str) -> bool:
        lowered = (gpu_name or "").lower()
        # Arc / Xe / Core Ultra iGPUs are the realistic Windows XPU target.
        # Older UHD/HD iGPUs usually expose graphics/Vulkan but not a usable
        # PyTorch XPU runtime, so recommending XPU there creates huge downloads
        # followed by a failed kernel test.
        return any(token in lowered for token in (" arc", "intel(r) arc", " iris xe", " xe graphics", "core ultra"))

    @staticmethod
    def _amd_rocm_likely_supported(gpu_name: str) -> bool:
        lowered = (gpu_name or "").lower()
        # Windows ROCm support is much narrower than "any Radeon". Keep this
        # conservative; CPU/Vulkan remain the broad compatibility path.
        return any(token in lowered for token in ("7900", "7800", "7700", "7600", "w7900", "w7800"))

    @staticmethod
    def _adapter_ram_gb(gpu: dict) -> Optional[float]:
        """Best-effort VRAM (GB). None/0 are unknown, and the exact

        0xFFFFFFFF value is Win32_VideoController.AdapterRAM's documented

        "unknown" sentinel β€” never rendered as a number.



        The sentinel is the only DWORD value that can be reliably detected: a

        >4 GB card's raw AdapterRAM wraps to an arbitrary-looking number

        (e.g. 4293918720 for a 24 GB card), which this check alone cannot

        distinguish from a legit ~4 GB value. Those cases are handled by the

        nvidia-smi enrichment in detect_video_controllers (available on any

        NVIDIA machine with a working driver); a machine without nvidia-smi

        and without the exact sentinel keeps the raw DWORD β€” a known residual

        limitation.

        """
        try:
            ram = gpu.get("adapter_ram")
            if not ram:
                return None
            ram = int(ram)
            # Exactly 0xFFFFFFFF is the documented "unknown" sentinel of the
            # 32-bit DWORD β€” a raw AdapterRAM can never exceed it, while a
            # real byte count (e.g. the nvidia-smi enrichment) legitimately
            # can, so the comparison must be exact equality, not >=.
            if ram == 0xFFFFFFFF:
                return None
            return ram / (1024 ** 3)
        except Exception:
            return None

    @staticmethod
    def _nvidia_generation_from_cc(cc: Optional[str]) -> str:
        try:
            major = int(str(cc).split(".")[0])
        except Exception:
            return "unknown generation"
        return {
            5: "Maxwell-class or older",
            6: "Pascal-class",
            7: "Turing/Volta-class",
            8: "Ampere/Ada-class",
            9: "Hopper/Ada/Blackwell-class",
        }.get(major, "new NVIDIA generation" if major > 9 else "legacy NVIDIA generation")

    @staticmethod
    def _intel_generation_hint(name: str) -> str:
        lowered = (name or "").lower()
        if "arc" in lowered:
            return "Intel Arc discrete GPU"
        if "core ultra" in lowered:
            return "Core Ultra / modern Xe iGPU"
        if "iris xe" in lowered or " xe graphics" in lowered:
            return "Iris Xe / Xe-class iGPU"
        if "uhd" in lowered or " hd graphics" in lowered:
            return "older Intel UHD/HD iGPU"
        return "Intel graphics"

    @staticmethod
    def get_acceleration_decision_tree() -> dict:
        """Detailed hardware decision tree for the Settings tab.



        The installer intentionally lays down a CPU baseline only. This

        method explains what the user can optionally install afterward and

        why, using hardware signals that matter for native AI packages:

        GPU family/generation, NVIDIA compute capability, installed CUDA

        runtime DLLs, driver hint, and VRAM.

        """
        gpus = HardwareManager.detect_video_controllers()
        cc = _gpu_compute_capability()
        cuda_driver = HardwareManager.detect_nvidia_cuda_version()
        cuda_runtime = HardwareManager.detect_installed_cuda_runtime_major()

        lines = ["Install baseline: CPU PyTorch first. Optional accelerators can be installed from Settings."]
        adapter_details = []
        for idx, gpu in enumerate(gpus):
            name = gpu.get("name", "Unknown GPU")
            brand = gpu.get("brand", "unknown")
            ram_gb = HardwareManager._adapter_ram_gb(gpu)
            ram_text = f"{ram_gb:.1f} GB" if ram_gb is not None else "unknown VRAM"
            detail = f"{idx}: {name} | brand={brand} | VRAM={ram_text} | driver={gpu.get('driver_version') or 'unknown'}"
            if brand == "nvidia":
                detail += f" | compute capability={cc or 'unknown'} | {HardwareManager._nvidia_generation_from_cc(cc)}"
            elif brand == "intel":
                detail += f" | {HardwareManager._intel_generation_hint(name)}"
            adapter_details.append(detail)
        if adapter_details:
            lines.extend(["", "Detected adapters:"] + [f"- {d}" for d in adapter_details])
        else:
            lines.extend(["", "Detected adapters:", "- none reported by the OS"])

        pytorch_choice = HardwareManager.PYTORCH_CPU
        pytorch_reason = "CPU PyTorch is the safe default and works on the widest range of PCs."
        llama_choice = HardwareManager.LLAMA_CPP_CPU
        llama_reason = "CPU llama.cpp is the safest GGUF baseline."

        brands = {g.get("brand") for g in gpus}
        if "nvidia" in brands:
            try:
                cc_f = float(cc) if cc else 0.0
            except (TypeError, ValueError):
                cc_f = 0.0
            lines.append("")
            lines.append("NVIDIA decision:")
            lines.append(f"- Driver CUDA hint: {cuda_driver or 'not reported'}")
            lines.append(f"- Installed CUDA runtime DLL family: cublas64_{cuda_runtime}.dll" if cuda_runtime else "- Installed CUDA runtime DLL family: not found")
            lines.append(f"- Compute capability: {cc or 'unknown'} ({HardwareManager._nvidia_generation_from_cc(cc)})")
            if cc_f >= 7.0:
                pytorch_choice = HardwareManager.PYTORCH_CUDA
                pytorch_reason = "NVIDIA compute capability is new enough for current CUDA PyTorch; install CUDA PyTorch only if you want GPU speed."
                if cuda_runtime in (12, 13):
                    llama_choice = HardwareManager.LLAMA_CPP_CUDA
                    llama_reason = f"CUDA runtime {cuda_runtime} DLLs are installed, so a matching llama-cpp-python CUDA wheel can load."
                else:
                    llama_reason = "GPU is modern, but CUDA runtime DLLs were not found; use CPU llama.cpp or install CUDA runtime before CUDA llama.cpp."
            elif cc_f:
                pytorch_reason = f"NVIDIA compute capability {cc} is too old for current CUDA AI wheels; CPU is recommended."
                llama_reason = f"NVIDIA compute capability {cc} is too old for current llama.cpp CUDA kernels; CPU is recommended."
                if "intel" in brands or "amd" in brands:
                    llama_choice = HardwareManager.LLAMA_CPP_VULKAN
                    llama_reason += " Vulkan can be tried for Intel/AMD graphics, but keep CPU as fallback."
            else:
                pytorch_reason = "NVIDIA GPU was detected but compute capability could not be verified; CPU is the safe default."
                llama_reason = "Do not install CUDA llama.cpp blindly without compute capability and runtime verification."
        elif "amd" in brands:
            amd_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "amd")
            if HardwareManager._amd_rocm_likely_supported(amd_names):
                pytorch_choice = HardwareManager.PYTORCH_ROCM
                pytorch_reason = "Recent AMD GPU detected; Windows ROCm can be tried from Settings, but it is a large optional install."
            else:
                pytorch_reason = "AMD GPU detected, but Windows ROCm support is narrow; CPU PyTorch is safer."
            llama_choice = HardwareManager.LLAMA_CPP_VULKAN
            llama_reason = "AMD graphics can try the Vulkan llama.cpp wheel; CPU remains the compatibility fallback."
        elif "intel" in brands:
            intel_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "intel")
            if HardwareManager._intel_xpu_likely_supported(intel_names):
                pytorch_choice = HardwareManager.PYTORCH_XPU
                pytorch_reason = "Modern Intel Arc/Xe-class GPU detected; PyTorch XPU can be tried from Settings."
                llama_choice = HardwareManager.LLAMA_CPP_VULKAN
                llama_reason = "Intel graphics can try Vulkan llama.cpp; CPU remains the fallback."
            else:
                pytorch_reason = "Older Intel UHD/HD graphics detected; PyTorch XPU is not recommended. Use CPU."
                llama_reason = "Older Intel UHD/HD graphics may expose Vulkan, but acceleration is often limited; CPU is recommended."

        lines.extend([
            "",
            f"Recommended PyTorch path: {pytorch_choice.upper()} - {pytorch_reason}",
            f"Recommended GGUF/llama.cpp path: {llama_choice.upper()} - {llama_reason}",
            "",
            "Rule: install GPU packages only from Settings after the app launches, and only after a real kernel/load test passes.",
        ])
        return {
            "gpus": gpus,
            "nvidia_compute_capability": cc,
            "nvidia_generation": HardwareManager._nvidia_generation_from_cc(cc),
            "cuda_driver": cuda_driver,
            "cuda_runtime_major": cuda_runtime,
            "pytorch": {"choice": pytorch_choice, "reason": pytorch_reason},
            "llama_cpp": {"choice": llama_choice, "reason": llama_reason},
            "report": "\n".join(lines),
        }

    @staticmethod
    def _format_gpu_list(gpus: list[dict]) -> str:
        if not gpus:
            return "No discrete/integrated GPU reported by the OS."
        rows = []
        for idx, gpu in enumerate(gpus):
            ram_gb = HardwareManager._adapter_ram_gb(gpu)
            ram_text = f"{ram_gb:.1f} GB" if ram_gb is not None else "unknown VRAM"
            rows.append(
                f"{idx}: {gpu.get('name', 'Unknown GPU')} "
                f"({gpu.get('brand', 'unknown')}, {ram_text}, driver {gpu.get('driver_version') or 'unknown'})"
            )
        return "\n".join(rows)

    @staticmethod
    def get_backend_recommendations() -> dict:
        """Recommend install choices for PyTorch and llama.cpp separately."""
        tree = HardwareManager.get_acceleration_decision_tree()
        return {
            "gpus": tree["gpus"],
            "pytorch": tree["pytorch"],
            "llama_cpp": tree["llama_cpp"],
        }

    @staticmethod
    def get_pytorch_install_options() -> list[str]:
        return [
            "Auto recommended",
            "CPU PyTorch (works on every PC)",
            "NVIDIA CUDA PyTorch",
            "Intel XPU PyTorch",
            "AMD ROCm PyTorch",
        ]

    @staticmethod
    def parse_pytorch_install_choice(label: str) -> str:
        text = (label or "").lower()
        if "nvidia" in text or "cuda" in text:
            return HardwareManager.PYTORCH_CUDA
        if "intel" in text or "xpu" in text:
            return HardwareManager.PYTORCH_XPU
        if "amd" in text or "rocm" in text:
            return HardwareManager.PYTORCH_ROCM
        if "cpu" in text:
            return HardwareManager.PYTORCH_CPU
        return HardwareManager.PYTORCH_AUTO

    @staticmethod
    def get_llama_cpp_install_options() -> list[str]:
        return [
            "Auto recommended",
            "CPU llama.cpp",
            "NVIDIA CUDA llama.cpp",
            "Vulkan llama.cpp (Intel/AMD)",
        ]

    @staticmethod
    def parse_llama_cpp_install_choice(label: str) -> str:
        text = (label or "").lower()
        if "nvidia" in text or "cuda" in text:
            return HardwareManager.LLAMA_CPP_CUDA
        if "vulkan" in text or "intel" in text or "amd" in text:
            return HardwareManager.LLAMA_CPP_VULKAN
        if "cpu" in text:
            return HardwareManager.LLAMA_CPP_CPU
        return HardwareManager.LLAMA_CPP_AUTO

    @staticmethod
    def format_backend_recommendations() -> str:
        return HardwareManager.get_acceleration_decision_tree()["report"]

    @staticmethod
    def detect_vram_gb() -> Optional[float]:
        """Best-effort total VRAM (in GB) of the primary CUDA GPU, if any.



        Returns None if there's no CUDA GPU, or detection fails for any

        reason β€” callers should treat None as "unknown", not "zero", since

        a failed *detection* is not the same as genuinely having no GPU.

        """
        try:
            if torch.cuda.is_available():
                props = torch.cuda.get_device_properties(0)
                return props.total_memory / (1024 ** 3)
            if hasattr(torch, "xpu") and torch.xpu.is_available():
                props = torch.xpu.get_device_properties(0)
                return props.total_memory / (1024 ** 3)
        except Exception:
            pass
        return None

    @staticmethod
    def detect_system_ram_gb() -> Optional[float]:
        """Best-effort total system RAM (in GB).



        Prefers `psutil` (not a hard requirement of this app β€” see

        requirements.txt) since it's cross-platform; falls back to

        reading /proc/meminfo directly on Linux if psutil isn't

        installed. Returns None if neither approach works (e.g. Windows

        without psutil) β€” callers should treat this the same as an

        unknown GPU: fall back to a conservative default tier rather than

        guessing a number that could be wildly wrong.

        """
        try:
            import psutil
            return psutil.virtual_memory().total / (1024 ** 3)
        except Exception:
            pass
        try:
            with open("/proc/meminfo") as f:
                for line in f:
                    if line.startswith("MemTotal:"):
                        kb = int(line.split()[1])
                        return kb / (1024 ** 2)
        except Exception:
            pass
        return None

    @staticmethod
    def get_memory_usage() -> dict:
        """Current live CPU + RAM + VRAM usage β€” the numbers shown next to

        the "Free All VRAM" buttons (Settings tab + sidebar) so users can see

        how much of their machine is in use (and how much freeing VRAM

        actually recovered). Never raises: every probe is individually

        guarded and degrades to None ("unknown") instead of crashing the

        Settings tab.



        Returns {

          "cpu":  {"pct": float|None},

          "ram":  {"used_gb": float|None, "total_gb": float|None, "pct": float|None},

          "vram": {"used_gb": float|None, "total_gb": float|None, "pct": float|None},

        }

        - CPU comes from psutil.cpu_percent() (system-wide, the same

          percentage Task Manager shows).

        - RAM comes from psutil.virtual_memory() (used = total - available,

          pct = the same percentage Task Manager shows).

        - VRAM prefers nvidia-smi `memory.used`/`memory.total` (works even

          when torch is a CPU-only build), falling back to torch CUDA

          stats, and stays all-None on machines with no usable GPU.

        """
        usage = {
            "cpu": {"pct": None},
            "ram": {"used_gb": None, "total_gb": None, "pct": None},
            "vram": {"used_gb": None, "total_gb": None, "pct": None},
        }
        try:
            import psutil
            # A short real sampling interval (not None): cpu_percent(interval=None)
            # returns 0.0 on the FIRST call because it has no baseline to compare
            # against β€” the sidebar would show a bogus 0% on first render. A
            # 100ms sample returns a real number every time, negligible against
            # the 5s UI poll cadence.
            usage["cpu"]["pct"] = round(psutil.cpu_percent(interval=0.1), 1)
        except Exception:
            pass
        try:
            import psutil
            vm = psutil.virtual_memory()
            usage["ram"]["used_gb"] = round((vm.total - vm.available) / (1024 ** 3), 1)
            usage["ram"]["total_gb"] = round(vm.total / (1024 ** 3), 1)
            usage["ram"]["pct"] = round(vm.percent, 1)
        except Exception:
            pass

        # VRAM β€” nvidia-smi first (real used/total regardless of which torch
        # build is installed), then torch CUDA as the fallback.
        try:
            result = subprocess.run(
                ["nvidia-smi", "--query-gpu=memory.used,memory.total",
                 "--format=csv,noheader,nounits"],
                capture_output=True, text=True, check=False, timeout=10,
                creationflags=CREATE_NO_WINDOW,
            )
            if result.returncode == 0 and result.stdout.strip():
                used, total = None, None
                for line in result.stdout.splitlines():
                    parts = [p.strip() for p in line.split(",")]
                    m_used = re.search(r"\d+", parts[0]) if parts else None
                    m_total = re.search(r"\d+", parts[1]) if len(parts) > 1 else None
                    if m_used and m_total:
                        used = float(m_used.group(0)) / 1024.0  # MiB -> GiB
                        total = float(m_total.group(0)) / 1024.0
                        break
                if used is not None and total is not None:
                    usage["vram"]["used_gb"] = round(used, 1)
                    usage["vram"]["total_gb"] = round(total, 1)
                    usage["vram"]["pct"] = round(used / total * 100, 1) if total else None
        except Exception:
            pass

        if usage["vram"]["total_gb"] is None:
            try:
                if torch.cuda.is_available():
                    props = torch.cuda.get_device_properties(0)
                    total = props.total_memory / (1024 ** 3)
                    used = torch.cuda.memory_allocated(0) / (1024 ** 3)
                    usage["vram"]["used_gb"] = round(used, 1)
                    usage["vram"]["total_gb"] = round(total, 1)
                    usage["vram"]["pct"] = round(used / total * 100, 1) if total else None
                elif hasattr(torch, "xpu") and torch.xpu.is_available():
                    props = torch.xpu.get_device_properties(0)
                    total = props.total_memory / (1024 ** 3)
                    used = torch.xpu.memory_allocated(0) / (1024 ** 3)
                    usage["vram"]["used_gb"] = round(used, 1)
                    usage["vram"]["total_gb"] = round(total, 1)
                    usage["vram"]["pct"] = round(used / total * 100, 1) if total else None
            except Exception:
                pass
        return usage

    # ──────────────────────────────────────────────────────────────
    # Hardware tiers β€” mirrors the "Model combos by hardware tier" table
    # in README.md exactly, so the HF-side dynamic model registry (see
    # model_registry.get_recommended_hf_models()) recommends the same
    # models the README documents for each tier. Checked from the
    # top (most capable) down, so a machine that qualifies for a higher
    # tier is never mistakenly placed in a lower one.
    # ──────────────────────────────────────────────────────────────
    TIER_48GB_VRAM = "48gb_vram"
    TIER_24GB_VRAM = "24gb_vram"
    TIER_16GB_VRAM = "16gb_vram"
    TIER_8GB_VRAM  = "8gb_vram"
    TIER_CPU_ONLY  = "cpu_only"
    TIER_UNKNOWN   = "unknown"

    @staticmethod
    def detect_hardware_tier() -> str:
        """Classify the current machine into one of the README's hardware

        tiers, based on detected VRAM (if a CUDA GPU is present) or system

        RAM (CPU-only case). Returns TIER_UNKNOWN if neither VRAM nor RAM

        could be determined β€” callers should fall back to the app's

        existing small defaults (BASE_MODEL_OPTIONS) in that case rather

        than guessing a tier that might recommend a model too large for

        the actual machine.

        """
        vram_gb = HardwareManager.detect_vram_gb()
        if vram_gb is not None:
            if vram_gb >= 44:   # 48 GB tier β€” a little headroom below the nominal 48
                return HardwareManager.TIER_48GB_VRAM
            if vram_gb >= 20:   # 24 GB tier
                return HardwareManager.TIER_24GB_VRAM
            if vram_gb >= 14:   # 16 GB tier
                return HardwareManager.TIER_16GB_VRAM
            if vram_gb >= 6:    # 8 GB tier β€” some headroom below nominal 8
                return HardwareManager.TIER_8GB_VRAM
            # A CUDA GPU exists but has less VRAM than any tier above
            # assumes β€” safer to fall back to CPU-only-style (smaller)
            # recommendations than to recommend an 8GB-tier model that
            # won't fit.
            return HardwareManager.TIER_CPU_ONLY

        ram_gb = HardwareManager.detect_system_ram_gb()
        if ram_gb is not None and ram_gb >= 56:   # 64GB tier β€” some headroom below nominal 64
            return HardwareManager.TIER_CPU_ONLY

        return HardwareManager.TIER_UNKNOWN

    @staticmethod
    def detect_nvidia_cuda_version() -> Optional[str]:
        """Best-effort read of the driver's supported CUDA version from

        nvidia-smi.



        Newer NVIDIA drivers (r580+ β€” e.g. the 610.x header line) stopped

        printing the legacy "CUDA Version: X.Y" text and now print

        "CUDA UMD Version: X.Y" instead. Parse BOTH spellings so driver

        detection doesn't silently fail β€” and the "Fix Environment" tool

        doesn't fall through to a CPU recommendation β€” on current drivers.

        """
        try:
            result = subprocess.run(
                ["nvidia-smi"], capture_output=True, text=True, check=False,
                creationflags=CREATE_NO_WINDOW,
            )
            if result.returncode == 0:
                for line in result.stdout.splitlines():
                    for marker in ("CUDA UMD Version:", "CUDA Version:"):
                        if marker in line:
                            val = line.split(marker)[1].strip().rstrip("|").strip()
                            if val and val.lower() != "n/a":
                                return val
            return None
        except Exception:
            return None

    @staticmethod
    def detect_installed_cuda_runtime_major() -> Optional[int]:
        """Best-effort read of the installed CUDA runtime DLL major version.



        We look for cublas64_*.dll on PATH plus common CUDA install

        locations. This is the version that matters for native wheels such

        as llama-cpp-python; the NVIDIA driver's reported CUDA version is

        only a compatibility hint and can disagree with the DLLs actually

        present on disk.

        """
        dirs = [d for d in os.environ.get("PATH", "").split(os.pathsep) if d.strip()]
        cu_path = os.environ.get("CUDA_PATH", "")
        if cu_path:
            dirs.append(os.path.join(cu_path, "bin"))
        for base in (
            "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA",
            "C:/Program Files/NVIDIA Corporation/CUDNN",
        ):
            base_p = Path(base)
            if not base_p.is_dir():
                continue
            for child in base_p.iterdir():
                if child.is_dir():
                    dirs.append(str(child / "bin") if (child / "bin").is_dir() else str(child))
        seen = set()
        majors = []
        for d in dirs:
            try:
                names = os.listdir(d)
            except Exception:
                continue
            for f in names:
                m = re.match(r"cublas64_(\d+)\.dll$", f, re.IGNORECASE)
                if not m or f in seen:
                    continue
                seen.add(f)
                try:
                    majors.append(int(m.group(1)))
                except ValueError:
                    pass
        return max(majors) if majors else None

    @staticmethod
    def get_required_torch_index(cuda_version: str) -> str:
        """Return the PyTorch wheel index best matching an NVIDIA driver's

        reported CUDA version. Mirrors the SETUP.ps1 STEP 4 mapping: a wheel

        is only offered if its bundled CUDA runtime is <= the driver's

        supported CUDA version (a driver reporting 12.6 cannot run cu128

        wheels; a 12.0 driver cannot run cu121+). For drivers newer than

        any known tier the newest known tier is used, since a new driver

        does not imply a new GPU β€” SETUP.ps1 re-verifies compatibility with

        a real-kernel smoke test after install.



        Also accepts the SETUP.ps1 brand tokens for non-NVIDIA backends

        ("rocm7.2.1" and "xpu"), mapping them to the correct index so the

        Fix Environment helper never suggests a bogus CUDA tier on an

        AMD/Intel machine.

        """
        if not cuda_version:
            return "https://download.pytorch.org/whl/cpu"

        if cuda_version == "xpu":
            return "https://download.pytorch.org/whl/xpu"
        if cuda_version.startswith("rocm"):
            return "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"

        try:
            v_parts = cuda_version.split('.')
            major = int(v_parts[0])
            minor = int(v_parts[1])

            if major == 11:
                return "https://download.pytorch.org/whl/cu118"
            elif major == 12:
                if minor == 0:
                    return "https://download.pytorch.org/whl/cu118"
                elif minor in (1, 2, 3):
                    return "https://download.pytorch.org/whl/cu121"
                elif minor in (4, 5):
                    return "https://download.pytorch.org/whl/cu124"
                elif minor in (6, 7):
                    return "https://download.pytorch.org/whl/cu126"
                elif minor in (8, 9):
                    return "https://download.pytorch.org/whl/cu128"
                else:
                    return "https://download.pytorch.org/whl/cu128"
            elif major >= 13:
                # Driver newer than any known tier -> newest known-good tier
                # (a new driver does not imply a new GPU; SETUP.ps1's
                # real-kernel smoke test re-verifies compatibility).
                return "https://download.pytorch.org/whl/cu128"
            # major < 11 (pre-Pascal-era driver): no current wheel fits,
            # but mirror SETUP.ps1 and offer the oldest tier β€” the smoke
            # test decides whether it actually runs.
            return "https://download.pytorch.org/whl/cu118"
        except Exception:
            return "https://download.pytorch.org/whl/cpu"

    @staticmethod
    def get_system_status() -> dict:
        decision = HardwareManager.get_acceleration_decision_tree()
        recommendations = {
            "gpus": decision["gpus"],
            "pytorch": decision["pytorch"],
            "llama_cpp": decision["llama_cpp"],
        }
        status = {
            "gpu_brand": "none",
            "gpus": recommendations["gpus"],
            "recommendations": recommendations,
            "acceleration_report": decision["report"],
            "cuda_version": None,
            "torch_cuda_available": False,
            "current_device": "cpu",
            "recommended_index": "https://download.pytorch.org/whl/cpu"
        }

        cuda_ver = HardwareManager.detect_nvidia_cuda_version()
        if cuda_ver:
            status["gpu_brand"] = "nvidia"
            status["cuda_version"] = cuda_ver
            status["recommended_index"] = HardwareManager.get_required_torch_index(cuda_ver)

        try:
            status["torch_cuda_available"] = torch.cuda.is_available()
            if status["torch_cuda_available"]:
                status["current_device"] = "cuda"
            elif hasattr(torch, "xpu") and torch.xpu.is_available():
                status["current_device"] = "xpu"
            elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
                status["current_device"] = "mps"
            else:
                status["current_device"] = "cpu"
        except Exception:
            pass

        if status["gpu_brand"] == "none":
            brands = {g["brand"] for g in recommendations["gpus"]}
            if "nvidia" in brands:
                status["gpu_brand"] = "nvidia"
                status["cuda_version"] = "unknown"
                status["recommended_index"] = "https://download.pytorch.org/whl/cu128"
            elif "amd" in brands:
                status["gpu_brand"] = "amd"
                status["cuda_version"] = "rocm7.2.1"
                status["recommended_index"] = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"
            elif "intel" in brands:
                status["gpu_brand"] = "intel"
                status["cuda_version"] = "xpu"
                status["recommended_index"] = "https://download.pytorch.org/whl/xpu"

        choice = recommendations["pytorch"]["choice"]
        if choice == HardwareManager.PYTORCH_CPU:
            status["recommended_index"] = "https://download.pytorch.org/whl/cpu"
        elif choice == HardwareManager.PYTORCH_XPU:
            status["recommended_index"] = "https://download.pytorch.org/whl/xpu"
        elif choice == HardwareManager.PYTORCH_ROCM:
            status["recommended_index"] = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"
        elif choice == HardwareManager.PYTORCH_CUDA and not status["recommended_index"].endswith("/cpu"):
            pass

        if False and status["gpu_brand"] == "none":
            # nvidia-smi was unavailable (or unparseable). Fall back to the
            # Windows device list so an NVIDIA machine is never mislabeled
            # "no GPU". Use PowerShell CIM first (works on all modern
            # Windows; wmic is deprecated/removed in newer releases), then
            # wmic as a fallback.
            vc_names = ""
            try:
                result = subprocess.run(
                    ["powershell", "-NoProfile", "-Command",
                     "(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue).Name -join ';'"],
                    capture_output=True, text=True, check=False,
                    creationflags=CREATE_NO_WINDOW,
                )
                if result.returncode == 0:
                    vc_names = result.stdout
            except Exception:
                pass
            if not vc_names:
                try:
                    result = subprocess.run(
                        ["wmic", "path", "win32_VideoController", "get", "name"],
                        capture_output=True, text=True, check=False,
                        creationflags=CREATE_NO_WINDOW,
                    )
                    if result.returncode == 0:
                        vc_names = result.stdout
                except Exception:
                    pass
            if "NVIDIA" in vc_names or "GeForce" in vc_names or "RTX" in vc_names or "Quadro" in vc_names:
                # NVIDIA card present but nvidia-smi didn't cooperate β€” treat
                # it as a modern driver and point at the proven RTX-tier
                # index (SETUP.ps1 uses the same fallback; the app's own
                # real-kernel check verifies the result at runtime).
                status["gpu_brand"] = "nvidia"
                status["cuda_version"] = "unknown"
                status["recommended_index"] = "https://download.pytorch.org/whl/cu128"
            elif "Radeon" in vc_names or "AMD" in vc_names:
                status["gpu_brand"] = "amd"
                status["cuda_version"] = "rocm7.2.1"
                status["recommended_index"] = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"
            elif "Intel" in vc_names:
                status["gpu_brand"] = "intel"
                status["cuda_version"] = "xpu"
                status["recommended_index"] = "https://download.pytorch.org/whl/xpu"

        return status

    @staticmethod
    def fix_environment_gen(choice=None):
        """Detect hardware and install a matching PyTorch build.



        choice ("auto" / "cpu" / "cuda" / "xpu" / "rocm", or None = auto):

        the explicit build the user picked in the Settings popup. Auto still

        decides by hardware; a non-viable explicit pick degrades to CPU with

        a clear message (never a mismatched GPU install β€” mirrors

        install_llama_cpp_python_gen)."""
        status = HardwareManager.get_system_status()
        if status["torch_cuda_available"]:
            yield "βœ… Environment is already correctly configured for GPU!", "cuda", ""
            return
        if hasattr(torch, "xpu") and torch.xpu.is_available():
            yield "βœ… Environment is already correctly configured for GPU!", "xpu", ""
            return

        choice = (choice or "auto").lower()
        if choice not in ("auto", "cpu", "cuda", "xpu", "rocm"):
            yield (f"❌ Unknown PyTorch build '{choice}' "
                   "(expected auto / cpu / cuda / xpu / rocm)."), "cpu", f"❌ Unknown PyTorch build '{choice}'."
            return

        brand = status["gpu_brand"]
        cc = _gpu_compute_capability()
        try:
            cc_f = float(cc) if cc else 0.0
        except (TypeError, ValueError):
            cc_f = 0.0
        gpus = status.get("gpus") or []
        intel_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "intel")
        amd_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "amd")

        # Resolve the build that will actually be installed. Every explicit
        # pick is guarded by the same machine signals the plan popup uses β€”
        # a non-viable pick degrades to CPU with a clear message, never a
        # mismatched GPU wheel (mirrors install_llama_cpp_python_gen).
        if choice == "cpu":
            effective = HardwareManager.PYTORCH_CPU
        elif choice == "cuda":
            if brand == "nvidia" and cc_f >= 7.0:
                effective = HardwareManager.PYTORCH_CUDA
            else:
                yield ("⚠️ The NVIDIA CUDA PyTorch build is not usable on this machine "
                       "(requires a modern NVIDIA GPU). Falling back to the CPU build."), "cpu", \
                    "⚠️ The NVIDIA CUDA PyTorch build is not usable on this machine. Falling back to the CPU build."
                effective = HardwareManager.PYTORCH_CPU
        elif choice == "xpu":
            if brand == "intel" and HardwareManager._intel_xpu_likely_supported(intel_names):
                effective = HardwareManager.PYTORCH_XPU
            else:
                yield ("⚠️ The Intel XPU PyTorch build is not usable on this machine "
                       "(requires a modern Intel Arc / Xe-class GPU). Falling back to the CPU build."), "cpu", \
                    "⚠️ The Intel XPU PyTorch build is not usable on this machine. Falling back to the CPU build."
                effective = HardwareManager.PYTORCH_CPU
        elif choice == "rocm":
            if brand == "amd" and HardwareManager._amd_rocm_likely_supported(amd_names):
                effective = HardwareManager.PYTORCH_ROCM
            else:
                yield ("⚠️ The AMD ROCm PyTorch build is not usable on this machine "
                       "(Windows ROCm needs a recent Radeon RX 7000-class GPU). Falling back to the CPU build."), "cpu", \
                    "⚠️ The AMD ROCm PyTorch build is not usable on this machine. Falling back to the CPU build."
                effective = HardwareManager.PYTORCH_CPU
        else:  # auto β€” the historical hardware-driven decision tree
            effective = status.get("recommendations", {}).get("pytorch", {}).get(
                "choice", HardwareManager.PYTORCH_CPU)

        if effective == HardwareManager.PYTORCH_CPU:
            report = status.get("acceleration_report") or HardwareManager.format_backend_recommendations()
            if choice == "cpu":
                # An explicit CPU pick needs no full report β€” just confirm the
                # user's choice (the report would mask this line in the log).
                yield "CPU PyTorch selected by the user.", "cpu", "CPU PyTorch selected by the user."
            else:
                yield "CPU PyTorch is recommended for this machine.", "cpu", report
            yield "No GPU PyTorch package was installed. The current CPU baseline is the safest option.", "cpu", ""
            return

        # Resolve the wheel index for the effective build (never the auto
        # recommendation's index β€” an explicit pick must map to its own tier).
        if effective == HardwareManager.PYTORCH_CUDA:
            index = HardwareManager.get_required_torch_index(status.get("cuda_version") or "")
            if index.endswith("/cpu"):
                # NVIDIA GPU present but driver CUDA version unknown β€” the same
                # proven RTX-tier index get_system_status falls back to.
                index = "https://download.pytorch.org/whl/cu128"
        elif effective == HardwareManager.PYTORCH_XPU:
            index = "https://download.pytorch.org/whl/xpu"
        else:  # PYTORCH_ROCM
            index = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"

        yield "πŸš€ Starting environment fix...", "cuda", "πŸš€ Starting environment fix..."
        yield f"πŸ” Detected GPU: {brand.upper()}", "cuda", f"πŸ” Detected GPU: {brand.upper()}"
        yield f"πŸ”— Using PyTorch index: {index}", "cuda", f"πŸ”— Using PyTorch index: {index}"

        try:
            if effective == HardwareManager.PYTORCH_ROCM:
                # AMD ROCm: SDK wheels must be installed before the torch
                # wheels, and everything comes from repo.radeon.com (the
                # CUDA-tier install below would resolve nothing there).
                roc_base = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1"
                sdk_wheels = [
                    f"{roc_base}/rocm_sdk_core-7.2.1-py3-none-win_amd64.whl",
                    f"{roc_base}/rocm_sdk_devel-7.2.1-py3-none-win_amd64.whl",
                    f"{roc_base}/rocm_sdk_libraries_custom-7.2.1-py3-none-win_amd64.whl",
                    f"{roc_base}/rocm-7.2.1.tar.gz",
                ]
                torch_wheels = [
                    f"{roc_base}/torch-2.9.1%2Brocm7.2.1-cp312-cp312-win_amd64.whl",
                    f"{roc_base}/torchaudio-2.9.1%2Brocm7.2.1-cp312-cp312-win_amd64.whl",
                    f"{roc_base}/torchvision-0.24.1%2Brocm7.2.1-cp312-cp312-win_amd64.whl",
                ]
                yield "Running: pip install ROCm SDK wheels", "cuda", "Running: pip install ROCm SDK wheels"
                sdk_cmd = _pip_base_args() + ["--no-cache-dir"] + sdk_wheels
                process = subprocess.Popen(
                    sdk_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
                    creationflags=CREATE_NO_WINDOW,
                )
                for line in process.stdout:
                    yield "πŸ› οΈ Installing...", "cuda", line.strip()
                process.wait()
                if process.returncode != 0:
                    yield f"❌ ROCm SDK install failed with exit code {process.returncode}", "cpu", f"❌ ROCm SDK install failed with exit code {process.returncode}"
                    return
                cmd = _pip_base_args() + ["--no-cache-dir"] + torch_wheels
            elif effective == HardwareManager.PYTORCH_XPU:
                # Intel XPU: pin exact versions (index outage bug #185608
                # can silently downgrade to an old torch otherwise).
                cmd = _pip_base_args() + [
                       "torch==2.11.0", "torchvision==0.26.0", "torchaudio==2.11.0",
                       "--index-url", index]
            else:
                cmd = _pip_base_args() + ["torch<2.12", "torchvision", "torchaudio", "--index-url", index]
            yield f"Running: {' '.join(cmd)}", "cuda", f"Running: {' '.join(cmd)}"

            process = subprocess.Popen(
                cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
                creationflags=CREATE_NO_WINDOW,
            )

            for line in process.stdout:
                yield "πŸ› οΈ Installing...", "cuda", line.strip()

            process.wait()

            if process.returncode == 0:
                yield "✨ Installation successful!", "cuda", "✨ Installation successful!"
                yield "βœ… Environment fixed! Please RESTART the app to apply changes.", "cuda", "βœ… Environment fixed! Please RESTART the app to apply changes."
            else:
                yield f"❌ Installation failed with exit code {process.returncode}", "cpu", f"❌ Installation failed with exit code {process.returncode}"
                yield "❌ Installation failed. Check the logs above.", "cpu", "❌ Installation failed. Check the logs above."

        except Exception as e:
            yield f"❌ Error: {str(e)}", "cpu", f"❌ Error: {str(e)}"

    @staticmethod
    def get_pytorch_install_plan() -> dict:
        """Detect which PyTorch builds are AVAILABLE on this machine and

        report each with a bilingual reason β€” the Settings popup shows the

        user every viable option and lets THEM choose, instead of silently

        installing the recommended path.



        Returns {

          "detected": {gpu_brand, gpu_name, cpu_name, cuda_version,

                       compute_capability, current_device},

          "options":   [ {"id", "label_key", "reason_key", "params",

                          "available", "recommended"}, ... ],

        }

        The option `id` is one of: auto / cpu / cuda / xpu / rocm. `auto` is

        always available and `recommended` mirrors the acceleration decision

        tree (the historical auto path).

        """
        status = HardwareManager.get_system_status()
        brand = status["gpu_brand"]
        gpus = status.get("gpus") or []
        cc = _gpu_compute_capability()
        try:
            cc_f = float(cc) if cc else 0.0
        except (TypeError, ValueError):
            cc_f = 0.0
        intel_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "intel")
        amd_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "amd")

        # Viability β€” the same machine signals the decision tree uses. CUDA
        # wheels bundle their own runtime DLLs, so the ONLY hard requirement
        # is a modern NVIDIA GPU (no installed-runtime / AVX-512 gate like
        # llama-cpp-python's CUDA wheels).
        cuda_available = brand == "nvidia" and cc_f >= 7.0
        xpu_available = brand == "intel" and HardwareManager._intel_xpu_likely_supported(intel_names)
        rocm_available = brand == "amd" and HardwareManager._amd_rocm_likely_supported(amd_names)

        if cuda_available:
            recommended = "cuda"
        elif rocm_available:
            recommended = "rocm"
        elif xpu_available:
            recommended = "xpu"
        else:
            recommended = "cpu"

        # CUDA reason β€” granular per obstacle (mirrors the llama-cpp plan).
        if cuda_available:
            cuda_key, cuda_params = "ptch_reason_cuda_ok", {}
        elif brand != "nvidia":
            cuda_key, cuda_params = "ptch_reason_cuda_requires_nvidia", {}
        elif not cc_f:
            cuda_key, cuda_params = "ptch_reason_cuda_cc_unknown", {}
        else:  # NVIDIA but too old for current CUDA wheels
            cuda_key, cuda_params = "ptch_reason_cuda_old_gpu", {"cc": cc}

        # XPU reason.
        if xpu_available:
            xpu_key, xpu_params = "ptch_reason_xpu_ok", {}
        elif brand != "intel":
            xpu_key, xpu_params = "ptch_reason_xpu_requires_intel", {}
        else:  # Intel but old UHD/HD-class iGPU
            xpu_key, xpu_params = "ptch_reason_xpu_old_gpu", {}

        # ROCm reason.
        if rocm_available:
            rocm_key, rocm_params = "ptch_reason_rocm_ok", {}
        elif brand != "amd":
            rocm_key, rocm_params = "ptch_reason_rocm_requires_amd", {}
        else:  # AMD but not RX 7000-class
            rocm_key, rocm_params = "ptch_reason_rocm_old_gpu", {}

        options = [
            {
                "id": "auto",
                "label_key": "ptch_opt_auto",
                "reason_key": "ptch_reason_auto",
                "params": {},
                "available": True,
                "recommended": False,
            },
            {
                "id": "cpu",
                "label_key": "ptch_opt_cpu",
                "reason_key": "ptch_reason_cpu_always",
                "params": {},
                "available": True,
                "recommended": recommended == "cpu",
            },
            {
                "id": "cuda",
                "label_key": "ptch_opt_cuda",
                "reason_key": cuda_key,
                "params": cuda_params,
                "available": cuda_available,
                "recommended": recommended == "cuda",
            },
            {
                "id": "xpu",
                "label_key": "ptch_opt_xpu",
                "reason_key": xpu_key,
                "params": xpu_params,
                "available": xpu_available,
                "recommended": recommended == "xpu",
            },
            {
                "id": "rocm",
                "label_key": "ptch_opt_rocm",
                "reason_key": rocm_key,
                "params": rocm_params,
                "available": rocm_available,
                "recommended": recommended == "rocm",
            },
        ]

        detected = {
            "gpu_brand": brand,
            "gpu_name": _gpu_name(),
            "cpu_name": _cpu_name(),
            "cuda_version": status.get("cuda_version"),
            "compute_capability": cc,
            "current_device": status.get("current_device", "cpu"),
        }
        return {"detected": detected, "options": options}

    @staticmethod
    def get_llama_cpp_install_plan() -> dict:
        """Detect which llama-cpp-python builds are AVAILABLE on this machine

        and report each with a bilingual reason β€” the Settings popup shows the

        user every viable option and lets THEM choose, instead of silently

        installing the CPU wheel.



        Returns {

          "detected": {gpu_brand, gpu_name, cpu_name, cuda_version,

                       runtime_major, compute_capability, avx512},

          "options":   [ {"id", "label_key", "reason_key", "params",

                          "available", "recommended"}, ... ],

        }

        The option `id` is one of: auto / cpu / cuda / vulkan. `reason_key`

        is an i18n key resolved with `params` (e.g. "{cc}" / "{runtime}"). An

        option is `available` when it can actually run on this machine and

        `recommended` when it is the best pick. `auto` is always available.

        """
        status = HardwareManager.get_system_status()
        brand = status["gpu_brand"]
        cuda_version = status["cuda_version"]
        runtime_major = HardwareManager.detect_installed_cuda_runtime_major()
        cc = _gpu_compute_capability()
        try:
            cc_f = float(cc) if cc else 0.0
        except (TypeError, ValueError):
            cc_f = 0.0
        avx512 = _cpu_supports_avx512()
        gpu_name = _gpu_name()
        cpu_name = _cpu_name()

        detected = {
            "gpu_brand": brand,
            "gpu_name": gpu_name,
            "cpu_name": cpu_name,
            "cuda_version": cuda_version,
            "runtime_major": runtime_major,
            "compute_capability": cc,
            "avx512": avx512,
        }

        options = [
            {
                "id": "auto",
                "label_key": "llcpp_opt_auto",
                "reason_key": "llcpp_reason_auto",
                "params": {},
                "available": True,
                "recommended": False,
            },
            {
                "id": "cpu",
                "label_key": "llcpp_opt_cpu",
                "reason_key": "llcpp_reason_cpu_always",
                "params": {},
                "available": True,
                "recommended": False,
            },
        ]

        # CUDA β€” viable ONLY when every hardware condition holds (same signals
        # the installer guards on: NVIDIA brand, modern compute capability, a
        # CUDA runtime DLL family actually installed, AVX-512-capable CPU).
        cuda_available = (
            brand == "nvidia"
            and cc_f >= 7.0
            and runtime_major in (12, 13)
            and avx512
        )
        if cuda_available:
            cuda_key, cuda_params = "llcpp_reason_cuda_ok", {"runtime": runtime_major}
            cuda_recommended = True
        elif brand != "nvidia":
            cuda_key, cuda_params = "llcpp_reason_cuda_requires_nvidia", {}
            cuda_recommended = False
        elif not cc_f:
            cuda_key, cuda_params = "llcpp_reason_cuda_cc_unknown", {}
            cuda_recommended = False
        elif cc_f < 7.0:
            cuda_key, cuda_params = "llcpp_reason_cuda_old_gpu", {"cc": cc}
            cuda_recommended = False
        elif runtime_major not in (12, 13):
            cuda_key, cuda_params = "llcpp_reason_cuda_no_runtime", {}
            cuda_recommended = False
        else:  # modern GPU + runtime but no AVX-512 β†’ CUDA wheels crash
            cuda_key, cuda_params = "llcpp_reason_cuda_no_avx512", {"cpu": cpu_name}
            cuda_recommended = False
        options.append({
            "id": "cuda",
            "label_key": "llcpp_opt_cuda",
            "reason_key": cuda_key,
            "params": cuda_params,
            "available": cuda_available,
            "recommended": cuda_recommended,
        })

        # Vulkan β€” viable for AMD/Intel GPUs (built without AVX-512, so it
        # also loads on the consumer CPUs where the CUDA wheels crash).
        vulkan_available = brand in ("amd", "intel")
        options.append({
            "id": "vulkan",
            "label_key": "llcpp_opt_vulkan",
            "reason_key": "llcpp_reason_vulkan_ok" if vulkan_available else "llcpp_reason_vulkan_no_gpu",
            "params": {},
            "available": vulkan_available,
            "recommended": vulkan_available and not cuda_available,
        })

        return {"detected": detected, "options": options}

    @staticmethod
    def install_llama_cpp_python_gen(choice=None):
        """Install a matching llama-cpp-python package for this machine.



        choice ("auto" / "cpu" / "cuda" / "vulkan", or None = auto): the

        explicit build the user picked in the Settings popup. Auto still

        decides by hardware; a non-viable explicit pick degrades to CPU with a

        clear message (never a mismatched GPU wheel).



        For NVIDIA CUDA GPUs:

          - Detects CUDA version / compute capability.

          - Installs from abetlen pre-built CUDA wheel index (e.g. cu124, cu121, cu118).

        For CPU / unknown:

          - Installs standard CPU llama-cpp-python package from PyPI.



        Yields progress messages for UI streaming.

        """
        status = HardwareManager.get_system_status()
        brand = status["gpu_brand"]
        cuda_ver = status["cuda_version"]
        runtime_major = HardwareManager.detect_installed_cuda_runtime_major()

        yield "πŸš€ Starting llama-cpp-python installation..."
        yield f"πŸ” Detected Hardware: GPU Brand = {brand.upper()}, CUDA Version = {cuda_ver or 'N/A'}"
        if runtime_major is not None:
            yield f"ℹ️ Detected installed CUDA runtime DLL family: cublas64_{runtime_major}.dll"

        # The ONLY signals that decide whether a CUDA wheel is safe here are
        # (a) the GPU's compute capability and (b) the CUDA runtime DLLs
        # actually installed on this PC. The NVIDIA driver's reported CUDA
        # version is NOT one of them (a modern driver can report CUDA 13 while
        # only a CUDA-12 runtime exists β€” a CUDA-13 wheel then fails to load),
        # and neither is torch.cuda.is_available() (a CPU-only torch build
        # simply cannot see the GPU at all, e.g. the Store package or any
        # machine whose torch got installed as the CPU build). Compute
        # capability is resolved independently of torch (torch β†’ nvidia-smi)
        # so the old-GPU guard below also fires on CPU-only builds.
        cc = _gpu_compute_capability()
        try:
            cc_f = float(cc) if cc else 0.0
        except (TypeError, ValueError):
            cc_f = 0.0
        gpu_name = _gpu_name()

        wheel_url = None
        # An explicit choice (cpu / cuda / vulkan β€” from the Settings popup)
        # overrides auto-detection. Every guard below still applies: a choice
        # the machine cannot actually run NEVER installs a broken wheel β€” it
        # degrades to the CPU build with a clear message, exactly like the
        # auto path (never a silent, mismatched GPU wheel).
        choice = (choice or "auto").lower()
        if choice not in ("auto", "cpu", "cuda", "vulkan"):
            yield f"❌ Unknown llama-cpp-python build '{choice}' (expected auto / cpu / cuda / vulkan)."
            return

        if choice == "cpu":
            yield "ℹ️ CPU build selected by the user."
        elif choice == "cuda":
            if (
                brand == "nvidia"
                and cc_f >= 7.0
                and runtime_major in (12, 13)
                and _cpu_supports_avx512()
            ):
                tag = "v0.3.34-cu130" if runtime_major >= 13 else "v0.3.34-cu124"
                wheel_url = (
                    f"https://github.com/abetlen/llama-cpp-python/releases/download/{tag}/"
                    f"llama_cpp_python-0.3.34-py3-none-win_amd64.whl"
                )
                yield f"ℹ️ NVIDIA CUDA build selected by the user ({tag})."
            else:
                yield (
                    "⚠️ The NVIDIA CUDA build is not usable on this machine "
                    "(requires a modern NVIDIA GPU, an installed CUDA 12/13 runtime "
                    "and an AVX-512 CPU). Falling back to the CPU build."
                )
        elif choice == "vulkan":
            if brand in ("amd", "intel"):
                vulkan_url = _llama_cpp_vulkan_wheel_url()
                if vulkan_url:
                    wheel_url = vulkan_url
                    yield "ℹ️ Vulkan build selected by the user (AMD/Intel GPU)."
                else:
                    yield (
                        "⚠️ The Vulkan prebuilt wheel is not available on this platform. "
                        "Falling back to the CPU build."
                    )
            else:
                yield (
                    "⚠️ The Vulkan build needs an AMD or Intel GPU (detected "
                    f"GPU brand: {brand or 'unknown'}). Falling back to the CPU build."
                )
        elif brand == "nvidia":
            if cc_f and cc_f < 7.0:
                # Pascal (6.x) and older cannot run the CUDA kernels in any
                # current llama.cpp build β€” a CUDA wheel would import (if the
                # runtime DLLs happen to be present) but blow up on the first
                # real kernel launch. CPU is the only correct choice.
                yield (
                    f"⚠️ NVIDIA GPU '{gpu_name or 'unknown'}' (compute capability {cc}, Pascal or older) "
                    "is too old for current llama.cpp CUDA kernels. "
                    "Using CPU llama-cpp-python to keep the app stable."
                )
            elif cc_f and cc_f >= 7.0 and runtime_major in (12, 13):
                # Modern GPU + a matching installed CUDA runtime: install the
                # wheel that links against the runtime DLLs actually present
                # (cublas64_12.dll β†’ cu124, cublas64_13.dll β†’ cu130) β€” BUT only
                # when the CPU can execute AVX-512. Those CUDA wheels are
                # compiled with AVX-512 code paths, and on Intel consumer CPUs
                # (no AVX-512 since Alder Lake, e.g. i7-14700F) EVERY model
                # load crashes with STATUS_ILLEGAL_INSTRUCTION (0xc000001d).
                # The CPU wheel below has no AVX-512 and loads fine; GPU
                # offload on such machines still works via the external
                # llama-server backend (per-architecture CPU DLL dispatch).
                if not _cpu_supports_avx512():
                    yield (
                        f"⚠️ CPU '{_cpu_name()}' does not support AVX-512, but the "
                        "llama-cpp-python CUDA wheels are compiled with AVX-512 "
                        "code paths and would crash loading any GGUF "
                        "(STATUS_ILLEGAL_INSTRUCTION 0xc000001d). Installing the "
                        "CPU wheel instead β€” GPU offload still works via the "
                        "πŸ–₯️ llama-server backend."
                    )
                else:
                    tag = "v0.3.34-cu130" if runtime_major >= 13 else "v0.3.34-cu124"
                    wheel_url = (
                        f"https://github.com/abetlen/llama-cpp-python/releases/download/{tag}/"
                        f"llama_cpp_python-0.3.34-py3-none-win_amd64.whl"
                    )
            elif cc_f and cc_f >= 7.0:
                # Modern GPU but no supported CUDA runtime DLLs on PATH (e.g.
                # driver-only gaming rigs β€” very common). A CUDA wheel cannot
                # load without the runtime it links against.
                yield (
                    "⚠️ Your GPU supports CUDA, but no matching CUDA runtime DLLs "
                    "(cublas64_12.dll / cublas64_13.dll) were found on this PC, so a CUDA "
                    "wheel could not load. Using the CPU llama-cpp-python package instead."
                )
            else:
                # Compute capability could not be determined (torch is a
                # CPU-only build and nvidia-smi is unavailable). Installing a
                # CUDA wheel blind is exactly how broken installs happen β€” CPU
                # is the safe out-of-the-box default.
                yield (
                    "⚠️ Could not verify this NVIDIA GPU's compute capability, so a CUDA wheel "
                    "could be mismatched. Using the safe CPU llama-cpp-python package instead "
                    "(install a CUDA wheel manually if your GPU is supported)."
                )
        elif brand in ("amd", "intel"):
            wheel_url = "https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34-vulkan/llama_cpp_python-0.3.34-py3-none-win_amd64.whl"

        try:
            if wheel_url:
                yield f"πŸ”— Found hardware-matched pre-built wheel: {wheel_url}"
                cmd = _pip_base_args() + ["--force-reinstall", "--no-cache-dir", wheel_url]
            else:
                cpu_url = _llama_cpp_cpu_wheel_url()
                if cpu_url:
                    yield f"ℹ️ Using prebuilt CPU wheel for llama-cpp-python (avoids a source build): {cpu_url}"
                    cmd = _pip_base_args() + ["--force-reinstall", "--no-cache-dir", cpu_url]
                else:
                    yield "ℹ️ Using standard CPU/default PyPI package for llama-cpp-python."
                    cmd = _pip_base_args() + ["--force-reinstall", "--no-cache-dir", "llama-cpp-python"]

            yield f"Running: {' '.join(cmd)}"
            process = subprocess.Popen(
                cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
                creationflags=CREATE_NO_WINDOW,
            )
            for line in process.stdout:
                yield line.strip()
            process.wait()

            if process.returncode != 0 and wheel_url:
                yield f"⚠️ CUDA wheel install exited with code {process.returncode}. Retrying with the CPU wheel..."
                cpu_url = _llama_cpp_cpu_wheel_url()
                cmd_fallback = _pip_base_args() + ["--no-cache-dir",
                                cpu_url or "llama-cpp-python"]
                yield f"Running: {' '.join(cmd_fallback)}"
                p2 = subprocess.Popen(
                    cmd_fallback, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
                    creationflags=CREATE_NO_WINDOW,
                )
                for line in p2.stdout:
                    yield line.strip()
                p2.wait()
                process = p2

            if process.returncode == 0:
                yield "✨ llama-cpp-python installation finished successfully!"
                try:
                    import importlib  # `sys` is already module-level; importing it here would shadow the global and break getattr(sys, 'frozen') above
                    for mod_name in list(sys.modules.keys()):
                        if mod_name == "llama_cpp" or mod_name.startswith("llama_cpp."):
                            del sys.modules[mod_name]
                    if "backend.llama_backend" in sys.modules:
                        importlib.reload(sys.modules["backend.llama_backend"])
                    import backend.llama_backend as lb
                    if not lb.LLAMA_CPP_AVAILABLE and wheel_url:
                        yield "⚠️ Installed wheel still cannot import cleanly. Reinstalling the CPU llama-cpp-python package..."
                        cpu_url = _llama_cpp_cpu_wheel_url()
                        cmd_cpu = _pip_base_args() + [
                                   "--force-reinstall", "--no-cache-dir",
                                   cpu_url or "llama-cpp-python"]
                        yield f"Running: {' '.join(cmd_cpu)}"
                        process_cpu = subprocess.Popen(
                            cmd_cpu, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
                            creationflags=CREATE_NO_WINDOW,
                        )
                        for line in process_cpu.stdout:
                            yield line.strip()
                        process_cpu.wait()
                        if process_cpu.returncode != 0:
                            yield f"❌ CPU fallback install failed with exit code {process_cpu.returncode}."
                            return
                        for mod_name in list(sys.modules.keys()):
                            if mod_name == "llama_cpp" or mod_name.startswith("llama_cpp."):
                                del sys.modules[mod_name]
                        if "backend.llama_backend" in sys.modules:
                            importlib.reload(sys.modules["backend.llama_backend"])
                        import backend.llama_backend as lb
                    lb.LLAMA_CPP_AVAILABLE = True
                    lb.LLAMA_CPP_GPU_AVAILABLE = lb._detect_llama_cpp_gpu_support()
                    gpu_state = "GPU CUDA offload" if lb.LLAMA_CPP_GPU_AVAILABLE else "CPU mode"
                    yield f"βœ… llama-cpp-python is ready ({gpu_state})!"
                except Exception as e:
                    yield f"βœ… llama-cpp-python installed! (Note: backend state refresh notice: {e})"
            else:
                yield f"❌ llama-cpp-python installation failed with exit code {process.returncode}."
        except Exception as e:
            yield f"❌ Error during installation: {e}"


# ──────────────────────────────────────────────────────────────────
# Real GPU/PyTorch kernel-compatibility check
# ──────────────────────────────────────────────────────────────────
# `torch.cuda.is_available()` only checks that the CUDA *driver* and
# runtime can be initialized β€” it does NOT mean this specific PyTorch
# build actually ships compiled kernels for this specific GPU's compute
# capability. PyTorch wheels only include kernels ("sm_XX" binaries) for
# a fixed list of architectures; older cards (e.g. Pascal/sm_6x,
# Maxwell/sm_5x) have been dropped from recent stable releases even
# though `torch.cuda.is_available()` still happily reports True and the
# model even *loads* onto the device β€” it only blows up the moment a
# real CUDA kernel is launched (e.g. during model loading's
# tie_weights()), with "CUDA error: no kernel image is available for
# execution on the device".
#
# This is exactly the gap that let a machine with e.g. an NVIDIA GeForce
# MX230 (compute capability 6.1) silently get a "cuda-capable" verdict
# from is_available(), install a GPU build via SETUP.ps1, and then crash
# on first real use. SETUP.ps1 now does a real-kernel smoke test right
# after installing torch (mirroring the same pattern already used there
# for llama-cpp-python) and falls back to a CPU wheel automatically if it
# fails β€” but a user could still end up here via a manual `pip install
# torch` re-install, a different Python environment, a driver/GPU swap,
# etc. So this same check is repeated here at app-import time as a
# runtime safety net: DEVICE only resolves to "cuda" if a real kernel
# actually runs successfully, not just because is_available() said so.
# ──────────────────────────────────────────────────────────────────
def _detect_gpu_kernel_incompatibility() -> Optional[dict]:
    """Best-effort: if a CUDA GPU is visible but this torch build has no

    compiled kernels for its compute capability, return a small dict with

    enough detail for the UI to build a clear, actionable warning

    (gpu_name, compute capability, and the archs this torch build DOES

    support). Returns None if the GPU is fully usable (or there's no GPU

    at all β€” that's a normal CPU-only setup, not a warning-worthy state).

    """
    if not torch.cuda.is_available():
        return None
    try:
        gpu_name = torch.cuda.get_device_name(0)
        cc_major, cc_minor = torch.cuda.get_device_capability(0)
        cc_str = f"{cc_major}.{cc_minor}"
        try:
            arch_list = torch.cuda.get_arch_list()
        except Exception:
            arch_list = []
        archs_str = ", ".join(a.replace("sm_", "") for a in arch_list) if arch_list else "unknown"

        # The real test: actually launch a kernel, not just check
        # is_available(). Wrapped so a torch UserWarning about the CC
        # mismatch (torch itself often prints one on this exact call)
        # doesn't spam the console a second time here β€” SETUP.ps1 /
        # the terminal already shows torch's own version of this warning;
        # this function only needs the pass/fail result.
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            try:
                x = torch.randn(8, device="cuda")
                _ = x @ x
                torch.cuda.synchronize()
                kernel_ok = True
            except Exception:
                kernel_ok = False

        if kernel_ok:
            return None

        return {
            "gpu_name": gpu_name,
            "compute_capability": cc_str,
            "supported_archs": archs_str,
        }
    except Exception:
        # Detection itself failing shouldn't block startup or produce a
        # false warning β€” treat as "couldn't determine", not "broken".
        return None


def _xpu_kernel_works() -> bool:
    """Real-kernel check for Intel XPU (torch.xpu). Like the CUDA path,

    is_available() can report True while this torch build/driver can't

    actually run kernels (or has no usable device); DEVICE must only

    resolve to "xpu" after a real kernel launches successfully.

    """
    if not (hasattr(torch, "xpu") and torch.xpu.is_available()):
        return False
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            x = torch.randn(8, device="xpu")
            _ = x @ x
            torch.xpu.synchronize()
        return True
    except Exception:
        return False


# ── Resolved once at import time ────────────────────────────────────
_GPU_INCOMPATIBILITY_INFO = _detect_gpu_kernel_incompatibility()

if torch.cuda.is_available() and _GPU_INCOMPATIBILITY_INFO is None:
    DEVICE = "cuda"
elif _xpu_kernel_works():
    DEVICE = "xpu"
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
    DEVICE = "mps"
else:
    DEVICE = "cpu"
    if _GPU_INCOMPATIBILITY_INFO is not None:
        print(
            f"[Hardware] WARNING: GPU '{_GPU_INCOMPATIBILITY_INFO['gpu_name']}' "
            f"(compute capability {_GPU_INCOMPATIBILITY_INFO['compute_capability']}) "
            f"was detected, but this PyTorch build has no compiled kernels for it "
            f"(supports: {_GPU_INCOMPATIBILITY_INFO['supported_archs']}). "
            f"Falling back to CPU β€” see the warning banner in the UI for how to fix this."
        )


def get_gpu_incompatibility_info() -> Optional[dict]:
    """Read-only accessor for ui.py: returns the dict built at import time

    (see _detect_gpu_kernel_incompatibility() above) describing a

    detected-but-unusable GPU, or None if the GPU is fine / there's no

    GPU. Used to render a one-time warning banner in the UI so a

    non-technical user isn't left guessing why everything is "running on

    CPU" despite clearly having an NVIDIA card β€” the banner explains it

    and points at the fix.

    """
    return _GPU_INCOMPATIBILITY_INFO


TORCH_DTYPE = torch.float16 if DEVICE != "cpu" else torch.float32


def refresh_system_ui():
    status = HardwareManager.get_system_status()
    return (
        "πŸ”„ Status Refreshed",
        # Report the DEVICE this app is ACTUALLY using (resolved once at
        # import time above, already accounting for the real-kernel
        # compatibility check) rather than status["current_device"], which
        # only reflects torch.cuda.is_available() and would misleadingly
        # say "CUDA" even on a machine that silently fell back to CPU due
        # to a GPU/PyTorch-build compute-capability mismatch.
        DEVICE.upper(),
        status["cuda_version"] or "N/A",
        "βœ… Yes" if status["torch_cuda_available"] else "❌ No",
        ""  # Clear logs
    )


def fix_system_ui_generator():
    status = HardwareManager.get_system_status()
    yield (
        "πŸš€ Starting fix...",
        status["current_device"].upper(),
        status["cuda_version"] or "N/A",
        "βœ… Yes" if status["torch_cuda_available"] else "❌ No",
        "Starting..."
    )

    for msg, dev, log in HardwareManager.fix_environment_gen():
        yield (
            msg,
            dev.upper(),
            status["cuda_version"] or "N/A",
            "βœ… Yes" if status["torch_cuda_available"] else "❌ No",
            log
        )