File size: 24,374 Bytes
8bd6fc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Agentic-27B-V2 量化版本选型脚本 / quantized-variant picker.

按本机硬件的资源上限(显存或内存总量)列出能跑的版本、
每个版本预计需要的内存,并给出推荐。只用 Python 标准库,不需要 GPU 驱动以外的依赖。

Reads the total capacity of this machine, lists every
variant that is compatible and fits, with the estimated memory each one needs.

用法 / usage:
    python select_quant.py                     # 自动检测 / auto-detect
    python select_quant.py --ctx 131072        # 按 128K 上下文估算
    python select_quant.py --vision            # 需要图像输入(GGUF 加上 mmproj)
    python select_quant.py --device nvidia --mem 24 --cc 8.9     # 不在目标机器上时手动指定
    python select_quant.py --device apple --mem 36
    python select_quant.py --lang en
"""
import argparse
import ctypes
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import unicodedata

PLATFORM = "huggingface"
ORG = "opencsg"
DATA = json.loads(r"""{
 "_comment": "Agentic-27B-V2 量化版本的唯一数据源。大小来自 ModelScope 文件列表(GB = 1e9 字节,含视觉塔和 MTP 头);质量指标来自各仓库模型卡(KL 已扣除指标固定偏移)。render.py 用它生成模型卡、选型表和 select_quant.py 里的数据。",
 "base": {
  "repo": "Agentic-27B-V2",
  "size_gb": 55.59,
  "arch": {
   "layers": 64,
   "full_attention_layers": 16,
   "linear_attention_layers": 48,
   "num_kv_heads": 4,
   "head_dim": 256,
   "linear_value_heads": 48,
   "linear_head_dim": 128,
   "max_context": 262144
  }
 },
 "variants": [
  {
   "id": "FP8",
   "repo": "Agentic-27B-V2-FP8",
   "family": "vllm",
   "format": "FP8 block(权重按 128 块缩放,激活动态)",
   "hardware": "NVIDIA Hopper / Blackwell / Ada(H100、H200、H20、B200、L40S)",
   "device": "nvidia",
   "min_cc": 8.9,
   "size_gb": 31.26,
   "kl": 0.0043,
   "top1": 0.9751,
   "ppl": 2.083,
   "dlp": -0.002,
   "engine": "vLLM / SGLang"
  },
  {
   "id": "INT8",
   "repo": "Agentic-27B-V2-INT8",
   "family": "vllm",
   "format": "INT8 W8A8(SmoothQuant + GPTQ)",
   "hardware": "NVIDIA Ampere 及以上(A100、A10、A800、L40、RTX 30/40)",
   "device": "nvidia",
   "min_cc": 8.0,
   "size_gb": 31.26,
   "kl": 0.0109,
   "top1": 0.9647,
   "ppl": 2.096,
   "dlp": -0.0049,
   "engine": "vLLM"
  },
  {
   "id": "NVFP4",
   "repo": "Agentic-27B-V2-NVFP4",
   "family": "vllm",
   "format": "NVFP4(GPTQ)",
   "hardware": "NVIDIA Blackwell(B200、B300、RTX 50、RTX PRO 6000)",
   "device": "nvidia",
   "min_cc": 10.0,
   "size_gb": 20.58,
   "kl": 0.0079,
   "top1": 0.969,
   "ppl": 2.088,
   "dlp": -0.0035,
   "engine": "vLLM"
  },
  {
   "id": "W4AFP8",
   "repo": "Agentic-27B-V2-W4AFP8",
   "family": "vllm",
   "format": "INT4 权重 + FP8 激活",
   "hardware": "NVIDIA Hopper(H100、H200、H20)",
   "device": "nvidia",
   "min_cc": 9.0,
   "max_cc": 9.0,
   "size_gb": 19.47,
   "kl": 0.0138,
   "top1": 0.958,
   "ppl": 2.101,
   "dlp": -0.0058,
   "engine": "vLLM"
  },
  {
   "id": "W4A16-G32",
   "repo": "Agentic-27B-V2-W4A16-G32",
   "family": "vllm",
   "format": "INT4 权重(GPTQ,group 32)",
   "hardware": "NVIDIA Ampere 及以上",
   "device": "nvidia",
   "min_cc": 8.0,
   "size_gb": 20.61,
   "kl": 0.0084,
   "top1": 0.9691,
   "ppl": 2.09,
   "dlp": -0.0032,
   "engine": "vLLM / SGLang"
  },
  {
   "id": "W4A16",
   "repo": "Agentic-27B-V2-W4A16",
   "family": "vllm",
   "format": "INT4 权重(GPTQ,group 128)",
   "hardware": "NVIDIA Ampere 及以上",
   "device": "nvidia",
   "min_cc": 8.0,
   "size_gb": 19.47,
   "kl": 0.0111,
   "top1": 0.9642,
   "ppl": 2.096,
   "dlp": -0.0043,
   "engine": "vLLM / SGLang"
  },
  {
   "id": "EXL3-3.0bpw",
   "repo": "Agentic-27B-V2-EXL3-3.0bpw",
   "family": "exl3",
   "format": "EXL3 3.0 bpw",
   "hardware": "NVIDIA Ampere 及以上单卡(RTX 3090/4090/5090 等)",
   "device": "nvidia",
   "min_cc": 8.0,
   "size_gb": 13.49,
   "kl": 0.0134,
   "top1": 0.9593,
   "ppl": 2.1,
   "dlp": -0.0051,
   "engine": "ExLlamaV3 / TabbyAPI"
  },
  {
   "id": "EXL3-2.5bpw",
   "repo": "Agentic-27B-V2-EXL3-2.5bpw",
   "family": "exl3",
   "format": "EXL3 2.5 bpw",
   "hardware": "NVIDIA Ampere 及以上单卡(16 GB 显存)",
   "device": "nvidia",
   "min_cc": 8.0,
   "size_gb": 11.97,
   "kl": 0.03,
   "top1": 0.9379,
   "ppl": 2.13,
   "dlp": -0.0118,
   "engine": "ExLlamaV3 / TabbyAPI"
  },
  {
   "id": "Ascend-W8A8",
   "repo": "Agentic-27B-V2-Ascend-W8A8",
   "family": "ascend",
   "format": "msModelSlim W8A8",
   "hardware": "华为昇腾 Atlas A2 / A3(910B、910C)",
   "device": "ascend",
   "size_gb": 32.15,
   "kl": null,
   "engine": "vLLM-Ascend"
  },
  {
   "id": "MLX-8bit",
   "repo": "Agentic-27B-V2-MLX-8bit",
   "family": "mlx",
   "format": "MLX 8-bit",
   "hardware": "Apple Silicon Mac(M1–M5)",
   "device": "apple",
   "size_gb": 29.52,
   "kl": null,
   "bits": 8,
   "engine": "mlx-lm / mlx-vlm / LM Studio"
  },
  {
   "id": "MLX-6bit",
   "repo": "Agentic-27B-V2-MLX-6bit",
   "family": "mlx",
   "format": "MLX 6-bit",
   "hardware": "Apple Silicon Mac(M1–M5)",
   "device": "apple",
   "size_gb": 22.8,
   "kl": null,
   "bits": 6,
   "engine": "mlx-lm / mlx-vlm / LM Studio"
  },
  {
   "id": "MLX-4bit",
   "repo": "Agentic-27B-V2-MLX-4bit",
   "family": "mlx",
   "format": "MLX 4-bit(group 64)",
   "hardware": "Apple Silicon Mac(M1–M5)",
   "device": "apple",
   "size_gb": 16.07,
   "kl": null,
   "bits": 4,
   "engine": "mlx-lm / mlx-vlm / LM Studio"
  },
  {
   "id": "MLX-MXFP4",
   "repo": "Agentic-27B-V2-MLX-MXFP4",
   "family": "mlx",
   "format": "MLX MXFP4",
   "hardware": "Apple Silicon Mac(M1–M5)",
   "device": "apple",
   "size_gb": 15.23,
   "kl": null,
   "bits": 4,
   "engine": "mlx-lm / mlx-vlm / LM Studio"
  }
 ],
 "gguf": {
  "repo": "Agentic-27B-V2-GGUF",
  "family": "gguf",
  "device": "any",
  "hardware": "任意:NVIDIA / AMD / Intel 显卡、Apple Silicon、纯 CPU",
  "engine": "llama.cpp / Ollama / LM Studio",
  "mmproj_gb": 0.93,
  "quants": [
   {
    "id": "Q8_0",
    "file": "Agentic-27B-V2-Q8_0.gguf",
    "size_gb": 29.05,
    "kl": 0.0002,
    "top1": 0.9931,
    "ppl": 2.078,
    "dlp": -0.0001
   },
   {
    "id": "Q6_K",
    "file": "Agentic-27B-V2-Q6_K.gguf",
    "size_gb": 22.53,
    "kl": 0.0008,
    "top1": 0.9879,
    "ppl": 2.079,
    "dlp": -0.0003
   },
   {
    "id": "Q5_K_M",
    "file": "Agentic-27B-V2-Q5_K_M.gguf",
    "size_gb": 19.78,
    "kl": 0.0017,
    "top1": 0.984,
    "ppl": 2.08,
    "dlp": -0.0006
   },
   {
    "id": "Q4_K_M",
    "file": "Agentic-27B-V2-Q4_K_M.gguf",
    "size_gb": 17.19,
    "kl": 0.005,
    "top1": 0.973,
    "ppl": 2.086,
    "dlp": -0.0025
   },
   {
    "id": "IQ4_XS",
    "file": "Agentic-27B-V2-IQ4_XS.gguf",
    "size_gb": 15.77,
    "kl": 0.0067,
    "top1": 0.9696,
    "ppl": 2.089,
    "dlp": -0.0023
   },
   {
    "id": "Q3_K_M",
    "file": "Agentic-27B-V2-Q3_K_M.gguf",
    "size_gb": 13.96,
    "kl": 0.0212,
    "top1": 0.9445,
    "ppl": 2.115,
    "dlp": -0.0088
   },
   {
    "id": "IQ3_XXS",
    "file": "Agentic-27B-V2-IQ3_XXS.gguf",
    "size_gb": 11.91,
    "kl": 0.0351,
    "top1": 0.9303,
    "ppl": 2.139,
    "dlp": -0.0157
   },
   {
    "id": "IQ2_M",
    "file": "Agentic-27B-V2-IQ2_M.gguf",
    "size_gb": 10.82,
    "kl": 0.0675,
    "top1": 0.9034,
    "ppl": 2.201,
    "dlp": -0.0276
   }
  ]
 }
}""")

# ---------------------------------------------------------------- memory model
A = DATA["base"]["arch"]
# 只有 16 层全注意力层有 KV 缓存;48 层线性注意力层的状态大小与上下文长度无关。
KV_BYTES_PER_TOKEN = 2 * A["full_attention_layers"] * A["num_kv_heads"] * A["head_dim"] * 2  # BF16 K+V
LINEAR_STATE_GB = A["linear_attention_layers"] * A["linear_value_heads"] * A["linear_head_dim"] ** 2 * 4 / 1e9
OVERHEAD_GB = {"vllm": 2.5, "ascend": 3.0, "exl3": 1.0, "gguf": 1.0, "mlx": 1.0}
UTIL = {"vllm": 0.9, "ascend": 0.9}  # vLLM 默认 gpu_memory_utilization


def kv_gb(ctx):
    return ctx * KV_BYTES_PER_TOKEN / 1e9 + LINEAR_STATE_GB


def need_gb(family, weights_gb, ctx, tp=1):
    """单卡需要的内存(GB)。tp>1 时权重和 KV 按卡均分。"""
    n = (weights_gb + kv_gb(ctx)) / tp + OVERHEAD_GB[family]
    return n / UTIL.get(family, 1.0)


# ---------------------------------------------------------------- detection
def run(cmd):
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=20).stdout
    except Exception:
        return ""


def total_ram_gb():
    try:
        if sys.platform == "darwin":
            return int(run(["sysctl", "-n", "hw.memsize"]).strip()) / 1e9
        if sys.platform.startswith("linux"):
            return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / 1e9
        if sys.platform == "win32":
            class MS(ctypes.Structure):
                _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong),
                            ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong),
                            ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong),
                            ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong),
                            ("ullAvailExtendedVirtual", ctypes.c_ulonglong)]
            m = MS()
            m.dwLength = ctypes.sizeof(MS)
            ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m))
            return m.ullTotalPhys / 1e9
    except Exception:
        pass
    return 0.0


# 旧驱动的 nvidia-smi 不支持 compute_cap 字段时,按型号推断
CC_BY_NAME = [(r"B200|B300|GB200|GB300", 10.0), (r"RTX 50|RTX PRO 6000 Blackwell|RTX PRO .* Blackwell", 12.0),
              (r"H100|H200|H800|H20|GH200", 9.0), (r"L40|L4\b|RTX 40|RTX 6000 Ada|RTX [0-9]+ Ada", 8.9),
              (r"A100|A800|A30\b", 8.0), (r"A10|A40|A16|A2\b|RTX 30|RTX A[0-9]", 8.6),
              (r"T4|RTX 20|Quadro RTX", 7.5), (r"V100", 7.0)]


def detect_nvidia():
    if not shutil.which("nvidia-smi"):
        return None
    out = run(["nvidia-smi", "--query-gpu=name,memory.total,compute_cap", "--format=csv,noheader,nounits"])
    if not out.strip():
        out = run(["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv,noheader,nounits"])
    gpus = []
    for line in out.strip().splitlines():
        parts = [p.strip() for p in line.split(",")]
        if len(parts) < 2:
            continue
        name, mem = parts[0], float(parts[1]) * 1024 * 1024 / 1e9  # MiB -> GB
        cc = None
        if len(parts) > 2:
            try:
                cc = float(parts[2])
            except ValueError:
                pass
        if cc is None:
            cc = next((v for pat, v in CC_BY_NAME if re.search(pat, name)), 0.0)
        gpus.append((name, mem, cc))
    if not gpus:
        return None
    return {"device": "nvidia", "name": gpus[0][0], "count": len(gpus),
            "mem": min(g[1] for g in gpus), "cc": min(g[2] for g in gpus)}


def detect_ascend():
    if not shutil.which("npu-smi"):
        return None
    out = run(["npu-smi", "info"])
    totals = [int(b) for a, b in re.findall(r"(\d+)\s*/\s*(\d+)", out) if int(b) >= 16000]  # HBM 总量(MB)
    if not totals:
        return None
    m = re.search(r"(910\w*|Ascend\s*\w+)", out)
    name = m.group(1) if m else "Ascend"
    return {"device": "ascend", "name": name, "count": len(totals), "mem": min(totals) * 1024 * 1024 / 1e9}


def detect_amd():
    if not shutil.which("rocm-smi"):
        return None
    try:
        d = json.loads(run(["rocm-smi", "--showmeminfo", "vram", "--json"]) or "{}")
        mems = [int(v.get("VRAM Total Memory (B)", 0)) / 1e9 for v in d.values() if isinstance(v, dict)]
        mems = [m for m in mems if m > 0]
        if mems:
            return {"device": "amd", "name": "AMD GPU", "count": len(mems), "mem": min(mems)}
    except Exception:
        pass
    return None


def detect_apple():
    if sys.platform == "darwin" and platform.machine() == "arm64":
        ram = total_ram_gb()
        chip = run(["sysctl", "-n", "machdep.cpu.brand_string"]).strip() or "Apple Silicon"
        return {"device": "apple", "name": chip, "count": 1, "mem": ram}
    return None


def detect():
    for f in (detect_nvidia, detect_ascend, detect_amd, detect_apple):
        r = f()
        if r:
            return r
    return {"device": "cpu", "name": platform.processor() or platform.machine(), "count": 1, "mem": total_ram_gb()}


def apple_gpu_limit(ram):
    # macOS 默认只允许 GPU 使用一部分统一内存(约 2/3,≥64 GB 机型约 3/4)
    return ram * (0.75 if ram >= 64 else 0.67)


# ---------------------------------------------------------------- planning
def plan(hw, ctx, vision):
    rows = []
    dev = hw["device"]
    for v in DATA["variants"]:
        fam = v["family"]
        ok_dev = v["device"] == dev
        if ok_dev and dev == "nvidia":
            ok_dev = hw.get("cc", 0) >= v.get("min_cc", 0) and hw.get("cc", 0) <= v.get("max_cc", 99)
        if not ok_dev:
            continue
        if fam in ("vllm", "ascend"):
            best = None
            for tp in (1, 2, 4):
                if tp > hw["count"]:
                    break
                n = need_gb(fam, v["size_gb"], ctx, tp)
                if n <= hw["mem"]:
                    best = (tp, n)
                    break
            tp, n = best if best else (1, need_gb(fam, v["size_gb"], ctx, 1))
            rows.append(dict(v, need=n, tp=tp, fits=best is not None, limit=hw["mem"]))
        elif fam == "exl3":
            n = need_gb(fam, v["size_gb"], ctx)
            rows.append(dict(v, need=n, tp=1, fits=n <= hw["mem"], limit=hw["mem"]))
        elif fam == "mlx":
            lim = apple_gpu_limit(hw["mem"])
            n = need_gb(fam, v["size_gb"], ctx)
            rows.append(dict(v, need=n, tp=1, fits=n <= lim, limit=lim))
    g = DATA["gguf"]
    if dev in ("nvidia", "amd"):
        lim, where = hw["mem"] * hw["count"], "gpu"
    elif dev == "apple":
        lim, where = apple_gpu_limit(hw["mem"]), "gpu"
    else:
        lim, where = total_ram_gb() * 0.8, "cpu"
    if dev == "ascend":
        lim = 0  # 昇腾请用 Ascend-W8A8
    for q in g["quants"]:
        n = need_gb("gguf", q["size_gb"] + (g["mmproj_gb"] if vision else 0), ctx)
        rows.append(dict(q, id="GGUF " + q["id"], repo=g["repo"], family="gguf", engine=g["engine"],
                         need=n, tp=1, fits=lim > 0 and n <= lim, limit=lim, where=where))
    return rows


def pad(s, n):
    w = sum(2 if unicodedata.east_asian_width(c) in "WF" else 1 for c in s)
    return s + " " * max(1, n - w)


def gib(gb):
    return gb * 1e9 / 2 ** 30


FAMILY_ORDER = {"nvidia": ["vllm", "exl3", "gguf"], "apple": ["mlx", "gguf"], "ascend": ["ascend"],
                "amd": ["gguf"], "cpu": ["gguf"]}


def quality_key(r):
    if r.get("kl") is not None:
        return r["kl"]
    return {8: 0.0005, 6: 0.002, 4: 0.012}.get(r.get("bits"), 1.0)  # MLX 暂无实测,按位宽排序


T = {
    "zh": dict(hw="检测到的硬件", limit="按硬件的资源上限估算,上下文", ctx="tokens",
               head=["#", "版本", "权重", "预计显存", "推理引擎", "top-1 一致率"], rec="推荐",
               none="当前资源上限内没有能运行的版本。可以缩短上下文(--ctx),或用 GGUF 把部分层放到 CPU。",
               nofit="另有 {n} 个版本超出资源上限,未列出(--all 查看)。",
               pick="请输入编号选择版本 [默认 1]: ", act="接下来要做什么?\n  1) 下载模型\n  2) 部署模型(下载并启动 OpenAI 兼容服务)\n请选择 [默认 1]: ",
               run="需要我帮你执行吗?\n  1) 执行\n  2) 不用,我自己来\n请选择 [默认 1]: ", noclient="未找到 `{bin}`,请先安装:{pkg}",
               running="正在执行……", bad="输入无效。",
               note="预计显存包含权重、上下文缓存和运行时开销;列出的版本都在资源上限以内,选小一些的版本可以留出更长上下文或更高并发。",
               mac="macOS 默认只允许 GPU 使用部分统一内存,可用 `sudo sysctl iogpu.wired_limit_mb=<MB>` 调高。",
               nokl="—"),
    "en": dict(hw="Detected hardware", limit="Budgeted against total capacity, context", ctx="tokens",
               head=["#", "Variant", "Weights", "Est. memory", "Engine", "Top-1 agreement"], rec="recommended",
               none="No variant fits within this capacity. Try a shorter context (--ctx) or GGUF with CPU offload.",
               nofit="{n} more variants exceed the capacity and are hidden (use --all).",
               pick="Pick a variant by number [default 1]: ", act="What next?\n  1) Download the model\n  2) Deploy the model (download and start an OpenAI-compatible server)\nChoose [default 1]: ",
               run="Run it for you now?\n  1) Run\n  2) No, I'll do it myself\nChoose [default 1]: ", noclient="`{bin}` not found. Install it first: {pkg}",
               running="Running...", bad="Invalid input.",
               note="Estimates include weights, context cache and runtime overhead. Every listed variant fits; a smaller one leaves room for longer context or more concurrency.",
               mac="macOS caps GPU memory to part of unified memory by default; raise it with `sudo sysctl iogpu.wired_limit_mb=<MB>`.",
               nokl="—"),
}

HUB = {
    "opencsg": dict(org="OpenCSG", bin="csghub-cli", pkg="pip install csghub-sdk",
                    cmd=["csghub-cli", "download", "{rid}", "--local-dir", "{dir}"]),
    "modelscope": dict(org="opencsg", bin="modelscope", pkg="pip install modelscope",
                       cmd=["modelscope", "download", "--model", "{rid}", "--local_dir", "{dir}"]),
    "huggingface": dict(org="opencsg", bin="hf", pkg="pip install huggingface_hub",
                        cmd=["hf", "download", "{rid}", "--local-dir", "{dir}"]),
}


def download_cmd(hub, r, vision):
    h = HUB[hub]
    local = r["repo"]
    cmd = [c.format(rid=f"{h['org']}/{r['repo']}", dir=local) for c in h["cmd"]]
    if r.get("file"):
        files = [r["file"]] + (["mmproj-Agentic-27B-V2-F16.gguf"] if vision else [])
        cmd = cmd[:3 if hub != "modelscope" else 4] + files + cmd[3 if hub != "modelscope" else 4:]
    return cmd, local


SERVE_BIN = {"vllm": ("vllm", "pip install vllm"), "ascend": ("vllm", "pip install vllm vllm-ascend"),
             "gguf": ("llama-server", "brew install llama.cpp  或参考 https://github.com/ggml-org/llama.cpp"),
             "mlx": ("python3", "pip install mlx-vlm"), "exl3": ("python3", "git clone https://github.com/theroyallab/tabbyAPI")}


def serve_cmd(r, local, ctx, vision, port=8000):
    fam = r["family"]
    if fam in ("vllm", "ascend"):
        cmd = (f"vllm serve ./{local} --served-model-name Agentic-27B-V2 --port {port} \\\n"
               f"  --max-model-len {ctx} --trust-remote-code \\\n"
               "  --reasoning-parser qwen3 --enable-auto-tool-choice --tool-call-parser qwen3_xml")
        if r.get("tp", 1) > 1:
            cmd += f" \\\n  --tensor-parallel-size {r['tp']}"
        if fam == "vllm":
            cmd += " \\\n  --speculative-config '{\"method\":\"mtp\",\"num_speculative_tokens\":3}'"
        return cmd
    if fam == "gguf":
        mm = f" --mmproj ./{local}/mmproj-Agentic-27B-V2-F16.gguf" if vision else ""
        return f"llama-server -m ./{local}/{r['file']}{mm} \\\n  -c {ctx} --jinja -ngl 99 --port {port}"
    if fam == "mlx":
        return f"python3 -m mlx_vlm.server --model ./{local} --port {port}"
    if fam == "exl3":
        return (f"# 在 TabbyAPI 目录下运行\n"
                f"python3 main.py --model-dir .. --model-name {local} --max-seq-len {ctx} --port {port}")
    return ""


def ask(q, default, n=None):
    try:
        v = input(q).strip()
    except EOFError:
        v = ""
    if not v:
        return default
    if v.isdigit() and (n is None or 1 <= int(v) <= n):
        return int(v)
    return v


def main():
    ap = argparse.ArgumentParser(description="Pick an Agentic-27B-V2 quantized variant for this machine")
    ap.add_argument("--ctx", type=int, default=32768, help="context length to budget for (default 32768)")
    ap.add_argument("--vision", action="store_true", help="need image input (adds mmproj for GGUF)")
    ap.add_argument("--device", choices=["nvidia", "apple", "ascend", "amd", "cpu"])
    ap.add_argument("--mem", type=float, help="memory per device in GB as marketed, e.g. 24 for RTX 4090, 36 for a 36GB Mac")
    ap.add_argument("--count", type=int, default=1, help="number of devices (with --device)")
    ap.add_argument("--cc", type=float, default=8.9, help="NVIDIA compute capability (with --device nvidia)")
    ap.add_argument("--hub", choices=list(HUB), default=PLATFORM, help="where to download from")
    ap.add_argument("--all", action="store_true", help="also list variants that do not fit")
    ap.add_argument("--list", action="store_true", help="only print the list, no questions")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--lang", choices=["zh", "en"], default="zh")
    a = ap.parse_args()
    t = T[a.lang]

    if a.device:
        hw = {"device": a.device, "name": a.device, "count": a.count, "mem": (a.mem or 0) * 2 ** 30 / 1e9, "cc": a.cc}
    else:
        hw = detect()
    rows = plan(hw, a.ctx, a.vision)
    if a.json:
        print(json.dumps({"hardware": hw, "ctx": a.ctx, "variants": rows}, ensure_ascii=False, indent=1))
        return

    order = FAMILY_ORDER.get(hw["device"], [])
    key = lambda r: (not r["fits"], order.index(r["family"]) if r["family"] in order else 9, quality_key(r))
    shown = sorted([r for r in rows if r["fits"] or a.all], key=key)
    best = {}
    for r in shown:
        if r["fits"]:
            best.setdefault(r["family"], r["id"])

    cc = f", compute capability {hw['cc']}" if hw["device"] == "nvidia" else ""
    print(f"{t['hw']}: {hw['name']} × {hw['count']}, {gib(hw['mem']):.0f} GB{cc}")
    print(f"{t['limit']} {a.ctx:,} {t['ctx']}\n")
    if not shown:
        print(t["none"])
        return
    w = [4, 16, 10, 13, 32, 8]
    print("".join(pad(h, x) for h, x in zip(t["head"], w)))
    for i, r in enumerate(shown, 1):
        need = f"{gib(r['need']):.1f} GB" + (f" ×{r['tp']}" if r["tp"] > 1 else "")
        q = f"{r['top1'] * 100:.1f}%" if r.get("top1") is not None else t["nokl"]
        mark = f"  ← {t['rec']}" if best.get(r["family"]) == r["id"] else ""
        print("".join(pad(c, x) for c, x in zip([str(i), r["id"], f"{r['size_gb']:.1f} GB", need, r["engine"], q], w)) + mark)
    hidden = sum(1 for r in rows if not r["fits"]) if not a.all else 0
    print()
    if hidden:
        print(t["nofit"].format(n=hidden))
    print(t["note"])
    if hw["device"] == "apple":
        print(t["mac"])
    if a.list or not sys.stdin.isatty():
        return

    print()
    i = ask(t["pick"], 1, len(shown))
    if not isinstance(i, int):
        print(t["bad"])
        return
    r = shown[i - 1]
    act = ask(t["act"], 1, 2)
    if act not in (1, 2):
        print(t["bad"])
        return
    dl, local = download_cmd(a.hub, r, a.vision)
    steps = [" ".join(dl)]
    if act == 2:
        steps.append(serve_cmd(r, local, a.ctx, a.vision))
    script_text = "\n".join(steps)
    print("\n" + script_text + "\n")
    if ask(t["run"], 1, 2) != 1:
        return
    need = [HUB[a.hub]["bin"], HUB[a.hub]["pkg"]], list(SERVE_BIN.get(r["family"], ("", "")))
    for b, pkg in (need if act == 2 else need[:1]):
        if b and not shutil.which(b):
            print(t["noclient"].format(bin=b, pkg=pkg))
            return
    print(t["running"] + "\n")
    if act == 1:
        subprocess.run(dl)
    else:
        if not os.path.isdir(local) or not os.listdir(local):
            if subprocess.run(dl).returncode != 0:
                return
        subprocess.run(steps[1].split("\n")[-1] if r["family"] == "exl3" else steps[1], shell=True)

if __name__ == "__main__":
    main()