@simplexai/localmodels-linux-x64 0.1.0-dev.32.build.git0f60eee490864cf83e343f8db13a335676a19dd8 → 0.1.0-dev.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +138 -97
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/app.py +7 -2
  6. package/modules/localmodels/approval.py +4 -4
  7. package/modules/localmodels/bifrost_checks.py +121 -3
  8. package/modules/localmodels/bifrost_provider.py +53 -0
  9. package/modules/localmodels/bifrost_unit.py +32 -1
  10. package/modules/localmodels/budget.py +5 -1
  11. package/modules/localmodels/catalog.json +51 -10
  12. package/modules/localmodels/catalog.py +30 -29
  13. package/modules/localmodels/catalog_add.py +1 -0
  14. package/modules/localmodels/cli_parser.py +10 -2
  15. package/modules/localmodels/component.py +7 -1
  16. package/modules/localmodels/decode_calibration.json +6 -0
  17. package/modules/localmodels/decode_calibration.py +104 -0
  18. package/modules/localmodels/deploy.py +44 -7
  19. package/modules/localmodels/deploy_steps.py +10 -1
  20. package/modules/localmodels/engines-strata-0.1.49.2.json +31 -0
  21. package/modules/localmodels/engines.json +57 -1
  22. package/modules/localmodels/engines.py +6 -2
  23. package/modules/localmodels/estimator.py +21 -7
  24. package/modules/localmodels/frontend.py +4 -4
  25. package/modules/localmodels/gateway.py +14 -4
  26. package/modules/localmodels/gateway_app_bifrost.py +4 -3
  27. package/modules/localmodels/gateway_bifrost.py +70 -57
  28. package/modules/localmodels/gateway_probe.py +3 -4
  29. package/modules/localmodels/gguf.py +7 -0
  30. package/modules/localmodels/harness.py +24 -25
  31. package/modules/localmodels/harness_gateway.py +19 -10
  32. package/modules/localmodels/harness_probe.py +33 -6
  33. package/modules/localmodels/hosts.py +73 -9
  34. package/modules/localmodels/install.py +36 -6
  35. package/modules/localmodels/library_cli.py +179 -0
  36. package/modules/localmodels/library_convert.py +132 -0
  37. package/modules/localmodels/library_gateway.py +471 -0
  38. package/modules/localmodels/library_jobs.py +314 -0
  39. package/modules/localmodels/library_model.py +246 -0
  40. package/modules/localmodels/library_pricing.py +347 -0
  41. package/modules/localmodels/library_serve.py +348 -0
  42. package/modules/localmodels/library_state.py +373 -0
  43. package/modules/localmodels/library_status.py +349 -0
  44. package/modules/localmodels/llm_rank.py +16 -2
  45. package/modules/localmodels/memcalc.py +7 -30
  46. package/modules/localmodels/metal.py +26 -0
  47. package/modules/localmodels/plan_envelope.py +4 -1
  48. package/modules/localmodels/preparation.py +49 -0
  49. package/modules/localmodels/probe.py +8 -8
  50. package/modules/localmodels/process_identity.py +536 -9
  51. package/modules/localmodels/quant_formats.py +123 -0
  52. package/modules/localmodels/recommend_cli.py +8 -4
  53. package/modules/localmodels/records.py +1 -0
  54. package/modules/localmodels/remote_ops.py +104 -6
  55. package/modules/localmodels/remote_ops_download.py +17 -2
  56. package/modules/localmodels/remote_ops_prepare.py +406 -0
  57. package/modules/localmodels/remote_ops_remove.py +40 -7
  58. package/modules/localmodels/remote_ops_service.py +110 -8
  59. package/modules/localmodels/remote_ops_verify.py +15 -2
  60. package/modules/localmodels/runtime_auth.py +31 -1
  61. package/modules/localmodels/runtime_cli.py +3 -4
  62. package/modules/localmodels/runtime_io.py +50 -6
  63. package/modules/localmodels/service_autostart.py +45 -1
  64. package/modules/localmodels/service_control.py +13 -0
  65. package/modules/localmodels/service_deployment.py +12 -3
  66. package/modules/localmodels/service_jobs.py +33 -4
  67. package/modules/localmodels/service_probe.py +67 -13
  68. package/modules/localmodels/service_stop.py +152 -0
  69. package/modules/localmodels/service_worker.py +9 -1
  70. package/modules/localmodels/services_cli.py +50 -6
  71. package/modules/localmodels/setup_inspection.py +34 -25
  72. package/modules/localmodels/setup_text.py +118 -0
  73. package/modules/localmodels/sizecalc.py +625 -0
  74. package/modules/localmodels/sizecalc_cli.py +249 -0
  75. package/modules/localmodels/stack.py +69 -17
  76. package/modules/localmodels/stack_args.py +91 -19
  77. package/modules/localmodels/stack_auto.py +78 -0
  78. package/modules/localmodels/stack_binding.py +23 -35
  79. package/modules/localmodels/stack_card.py +195 -0
  80. package/modules/localmodels/stack_cleanup.py +379 -0
  81. package/modules/localmodels/stack_clients.py +4 -1
  82. package/modules/localmodels/stack_compose.py +150 -194
  83. package/modules/localmodels/stack_console.py +2 -0
  84. package/modules/localmodels/stack_decision.py +3 -2
  85. package/modules/localmodels/stack_down.py +189 -0
  86. package/modules/localmodels/stack_events.py +54 -0
  87. package/modules/localmodels/stack_hardware.py +22 -23
  88. package/modules/localmodels/stack_journal.py +29 -8
  89. package/modules/localmodels/stack_ledger.py +411 -0
  90. package/modules/localmodels/stack_lifecycle.py +162 -167
  91. package/modules/localmodels/stack_llm_ram.py +57 -5
  92. package/modules/localmodels/stack_memory.py +721 -0
  93. package/modules/localmodels/stack_picks.py +139 -0
  94. package/modules/localmodels/stack_plan.py +140 -22
  95. package/modules/localmodels/stack_ports.py +22 -0
  96. package/modules/localmodels/stack_preflight.py +699 -0
  97. package/modules/localmodels/stack_review.py +123 -5
  98. package/modules/localmodels/stack_rollback.py +2 -0
  99. package/modules/localmodels/stack_route.py +256 -0
  100. package/modules/localmodels/stack_run.py +11 -0
  101. package/modules/localmodels/stack_suite.py +102 -17
  102. package/modules/localmodels/stack_summary.py +65 -4
  103. package/modules/localmodels/stack_try.py +354 -0
  104. package/modules/localmodels/stack_try_client.py +194 -0
  105. package/modules/localmodels/stack_try_docs.py +139 -0
  106. package/modules/localmodels/stack_up.py +8 -1
  107. package/modules/localmodels/stack_update.py +29 -4
  108. package/modules/localmodels/stack_verify.py +3 -1
  109. package/modules/localmodels/stack_view.py +10 -11
  110. package/modules/localmodels/stack_view_apply.py +4 -2
  111. package/modules/localmodels/stack_view_events.py +2 -1
  112. package/modules/localmodels/stack_view_serve.py +3 -0
  113. package/modules/localmodels/stack_view_text.py +1 -1
  114. package/modules/localmodels/stack_view_words.py +4 -1
  115. package/modules/localmodels/stack_warm.py +574 -0
  116. package/modules/localmodels/stack_whatif.py +558 -0
  117. package/modules/localmodels/suite.py +48 -39
  118. package/modules/localmodels/tool_archive.py +40 -0
  119. package/modules/localmodels/tools.json +8 -0
  120. package/modules/localmodels/transport.py +1 -0
  121. package/modules/localmodels/vision.py +8 -1
  122. package/modules/localmodels/web/sizecalc/app.js +431 -0
  123. package/modules/localmodels/web/sizecalc/calc.js +269 -0
  124. package/modules/localmodels/web/sizecalc/page.html +362 -0
  125. package/modules/localmodels/web/view/ASSET-SOURCES.md +11 -0
  126. package/modules/localmodels/web/view/i18n.js +1 -1
  127. package/modules/localmodels/web/view/logo-claude.svg +3 -0
  128. package/modules/localmodels/web/view/logo-codex.png +0 -0
  129. package/modules/localmodels/web/view/logo-pi.svg +6 -0
  130. package/modules/localmodels/web/view/view.css +4 -0
  131. package/modules/localmodels/web/view/view.js +15 -6
  132. package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/METADATA +1 -1
  133. package/modules/simplex_localmodels-0.1.0.dev35.dist-info/RECORD +241 -0
  134. package/package.json +1 -1
  135. package/tool.json +1 -1
  136. package/modules/simplex_localmodels-0.1.0.dev32.dist-info/RECORD +0 -200
  137. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/WHEEL +0 -0
  138. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/entry_points.txt +0 -0
  139. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/NOTICE +0 -0
  140. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,625 @@
1
+ """``localmodels sizecalc``: from a model's shape (dense or MoE, total and active parameters) and
2
+ its weight format, the weight file size, the memory running it takes, and the class of device
3
+ that holds it: phone, laptop, consumer NVIDIA card, large unified memory, workstation, one server
4
+ GPU or an 8-GPU server.
5
+
6
+ Any two of parameters, format and file size give the third. The KV cache per token is either
7
+ given (``memcalc`` prints it for a real model) or guessed from the active parameters and the
8
+ attention kind. Engine overheads reuse the llama.cpp constants ``stack`` plans with
9
+ (``estimator``) and Apple's working-set share (``metal``); the vLLM, MLX and ExLlama overheads
10
+ are estimates. Every number is an estimate for sizing, not a measurement: use ``memcalc`` for one
11
+ model's context curve and ``stack memory`` for the stack's own posture.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Sequence
17
+ from dataclasses import dataclass
18
+ from typing import Any
19
+
20
+ from localmodels import estimator, metal, quant_formats
21
+ from localmodels.memcalc import GIB, KIB, MemcalcError
22
+ from localmodels.quant_formats import QuantFormat
23
+
24
+ SCHEMA = "localmodels.sizecalc/v1"
25
+ MIB = 1 << 20
26
+
27
+ # KV cache guess: f16 K+V bytes one token adds, scaled from Llama-3.1-8B's 128 KiB (32 full
28
+ # layers x 8 KV heads x 128 x 2 x 2) by active parameters^0.45, which lands within 20% of
29
+ # Llama-3.3-70B (320 KiB), Qwen3-32B (256), Qwen3-235B-A22B (188) and Qwen3-30B-A3B (96); GQA
30
+ # models with 4 KV heads (Qwen2.5-7B, 56 KiB) sit at half. Other layouts keep a share of it:
31
+ # sliding-window mixes (Gemma 3 27B, gpt-oss) about a third, linear/SSM hybrids (Qwen3.5/3.8,
32
+ # Qwen3-Next) a quarter, MLA latents (DeepSeek V3, Kimi K2: 70 KiB) under a third.
33
+ KV_REF_BYTES = 128 * KIB
34
+ KV_REF_PARAMS = 8e9
35
+ KV_EXPONENT = 0.45
36
+ ATTENTION_KV_SHARE = {"full": 1.0, "swa": 0.35, "hybrid": 0.25, "mla": 0.3}
37
+ KV_BYTES_PER_ELEM = {"f16": 2.0, "bf16": 2.0, "fp8": 1.0, "q8_0": 34 / 32, "q4_0": 18 / 32}
38
+ # Share of an MoE's active parameters outside the routed experts (attention, embeddings, shared
39
+ # experts): what --n-cpu-moe keeps on the card. Half matches Qwen3-30B-A3B (1.5 of 3.3B),
40
+ # gpt-oss-120b (2.5 of 5.1B) and DeepSeek V3 (17 of 37B); older 2-of-8 MoEs (Mixtral) keep less,
41
+ # so the card side errs high.
42
+ MOE_SHARED_OF_ACTIVE = 0.5
43
+ # What a PC keeps for itself beside an offloaded model (stack_plan.RAM_FLOOR), and the system-RAM
44
+ # bandwidth of a dual-channel DDR5 desktop that offloaded weights decode from.
45
+ HOST_RAM_FLOOR = 4 * GIB
46
+ DEFAULT_HOST_RAM = 64 * GIB
47
+ DEFAULT_HOST_BANDWIDTH_GB_S = 80.0
48
+ # What one foreground app may hold on a phone. Android 17's Memory Limiter caps a visible app at
49
+ # 5 / 8 / 10 GiB on 8 / 12 / 16 GB devices and sets no default cap from 18 GiB of RAM
50
+ # (source.android.com/docs/core/perf/memory-limiter). Apple publishes no iOS figure: half the RAM
51
+ # is an unverified assumption; os_proc_available_memory() on the device is the real answer.
52
+ ANDROID_FOREGROUND_GIB = {8: 5, 12: 8, 16: 10}
53
+ IOS_APP_SHARE = 0.5
54
+ # Below this many parameters embeddings dominate: Qwen3-0.6B Q4_K_M files hold 5.30 bits per
55
+ # weight and Gemma 3 270M 7.46, against 4.89 at 8B.
56
+ SMALL_MODEL_PARAMS = 3e9
57
+ DEFAULT_CONTEXT = 8192
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Engine:
62
+ name: str
63
+ fixed_bytes: int # compute buffers and process cost per GPU
64
+ per_context_token: int # compute bytes that grow with the context
65
+ card_share: float # share of a discrete card the engine claims (vLLM gpu_memory_utilization)
66
+ basis: str
67
+
68
+
69
+ ENGINES = {
70
+ "llama.cpp": Engine(
71
+ "llama.cpp",
72
+ estimator.AGENT_PROCESS_OVERHEAD_BYTES + estimator.AGENT_COMPUTE_BASE_BYTES,
73
+ 512 * 2, # the KQ mask: context x ubatch 512 x f16
74
+ 1.0,
75
+ "measured on CUDA llama.cpp (estimator)",
76
+ ),
77
+ "mlx": Engine("mlx", int(1.05 * GIB), 0, 1.0, "estimate: one 2048-token prefill + process"),
78
+ "vllm": Engine(
79
+ "vllm", 2 * GIB, 0, 0.92, "estimate: CUDA context, activation peak, CUDA graphs; 92% claim"
80
+ ),
81
+ "exllama": Engine("exllama", 1 * GIB, 0, 1.0, "estimate"),
82
+ "transformers": Engine("transformers", int(1.5 * GIB), 0, 1.0, "estimate"),
83
+ }
84
+
85
+ # Which engine runs a format family on a backend, and from which CUDA compute capability:
86
+ # (engine, native from, runs from). A family absent for a backend needs converting first.
87
+ # 0 means any device of that backend.
88
+ SUPPORT: dict[str, dict[str, tuple[str, float, float]]] = {
89
+ "float": {
90
+ "cuda": ("vllm", 8.0, 7.0),
91
+ "rocm": ("vllm", 0, 0),
92
+ "metal": ("mlx", 0, 0),
93
+ "ios": ("mlx", 0, 0),
94
+ "android": ("llama.cpp", 0, 0),
95
+ },
96
+ "gguf": {b: ("llama.cpp", 0, 0) for b in ("cuda", "rocm", "metal", "ios", "android")},
97
+ "mxfp4": {b: ("llama.cpp", 0, 0) for b in ("cuda", "rocm", "metal", "ios", "android")},
98
+ "mlx": {"metal": ("mlx", 0, 0), "ios": ("mlx", 0, 0)},
99
+ "awq": {"cuda": ("vllm", 7.5, 7.5), "rocm": ("vllm", 0, 0)},
100
+ "gptq": {"cuda": ("vllm", 7.5, 7.5), "rocm": ("vllm", 0, 0)},
101
+ "fp8": {"cuda": ("vllm", 8.9, 8.0), "rocm": ("vllm", 0, 0)}, # Ampere: weight-only Marlin
102
+ "nvfp4": {"cuda": ("vllm", 10.0, 8.0)}, # elsewhere: weight-only fallback, engine-dependent
103
+ "exl": {"cuda": ("exllama", 8.0, 8.0)},
104
+ "bnb": {"cuda": ("transformers", 7.5, 7.5)},
105
+ }
106
+
107
+ # (id, label, what the tier holds), cheapest first.
108
+ TIERS: tuple[tuple[str, str, str], ...] = (
109
+ ("phone", "phone", "8-16 GB; Android lets one app hold 5-10 GiB"),
110
+ ("laptop", "laptop / small Mac", "16-36 GB unified memory"),
111
+ ("pc-gpu", "consumer NVIDIA card", "8-32 GB VRAM, plus system RAM for offload"),
112
+ ("big-unified", "large unified memory", "64-128 GB: Mac Max, DGX Spark, Ryzen AI Max"),
113
+ ("workstation", "workstation", "48-96 GB card, Mac Studio Ultra 256-512 GB"),
114
+ ("server-gpu", "one server GPU", "80-192 GB HBM"),
115
+ ("node", "8-GPU server", "640-1536 GB HBM, tensor parallel"),
116
+ )
117
+ TIER_LABEL = {tier: label for tier, label, _ in TIERS}
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class Device:
122
+ id: str
123
+ name: str
124
+ tier: str
125
+ backend: str # cuda, rocm, metal, ios, android
126
+ memory_gib: float # per accelerator, or the whole unified memory
127
+ bandwidth_gb_s: float # per accelerator, vendor spec
128
+ count: int = 1
129
+ unified: bool = False
130
+ sm: float = 0.0 # CUDA compute capability
131
+ host_offload: bool = False # a PC whose system RAM takes llama.cpp offload
132
+
133
+ @property
134
+ def memory_bytes(self) -> int:
135
+ return int(self.memory_gib * GIB)
136
+
137
+
138
+ def _d(*args: Any, **kwargs: Any) -> Device:
139
+ return Device(*args, **kwargs)
140
+
141
+
142
+ # Representative devices per tier: vendor memory and bandwidth (gpu_specs.py for NVIDIA cards).
143
+ DEVICES: tuple[Device, ...] = (
144
+ _d("iphone-8", "iPhone 16 Pro (8 GB)", "phone", "ios", 8, 60, unified=True),
145
+ _d("iphone-12", "iPhone 17 Pro (12 GB)", "phone", "ios", 12, 77, unified=True),
146
+ _d("android-12", "Android flagship 12 GB", "phone", "android", 12, 85, unified=True),
147
+ _d("android-16", "Android flagship 16 GB", "phone", "android", 16, 85, unified=True),
148
+ _d("mac-16", "MacBook Air M4 16 GB", "laptop", "metal", 16, 120, unified=True),
149
+ _d("mac-24", "Mac mini M4 Pro 24 GB", "laptop", "metal", 24, 273, unified=True),
150
+ _d("mac-36", "MacBook Pro M4 Max 36 GB", "laptop", "metal", 36, 410, unified=True),
151
+ _d("rtx4060", "RTX 4060 8 GB", "pc-gpu", "cuda", 8, 272, sm=8.9, host_offload=True),
152
+ _d("rtx3060", "RTX 3060 12 GB", "pc-gpu", "cuda", 12, 360, sm=8.6, host_offload=True),
153
+ _d("rtx4060ti", "RTX 4060 Ti 16 GB", "pc-gpu", "cuda", 16, 288, sm=8.9, host_offload=True),
154
+ _d("rtx5070ti", "RTX 5070 Ti 16 GB", "pc-gpu", "cuda", 16, 896, sm=12.0, host_offload=True),
155
+ _d("rtx3090", "RTX 3090 24 GB", "pc-gpu", "cuda", 24, 936, sm=8.6, host_offload=True),
156
+ _d("rtx4090", "RTX 4090 24 GB", "pc-gpu", "cuda", 24, 1008, sm=8.9, host_offload=True),
157
+ _d("rtx5090", "RTX 5090 32 GB", "pc-gpu", "cuda", 32, 1792, sm=12.0, host_offload=True),
158
+ _d("mac-64", "Mac Studio M4 Max 64 GB", "big-unified", "metal", 64, 546, unified=True),
159
+ _d("mac-128", "MacBook Pro M4 Max 128 GB", "big-unified", "metal", 128, 546, unified=True),
160
+ _d("dgx-spark", "DGX Spark 128 GB", "big-unified", "cuda", 128, 273, unified=True, sm=12.1),
161
+ _d("ryzen-ai-max", "Ryzen AI Max+ 395 128 GB", "big-unified", "rocm", 128, 256, unified=True),
162
+ _d("rtx6000ada", "RTX 6000 Ada 48 GB", "workstation", "cuda", 48, 960, sm=8.9),
163
+ _d("rtxpro6000", "RTX PRO 6000 Blackwell 96 GB", "workstation", "cuda", 96, 1792, sm=12.0),
164
+ _d("mac-256", "Mac Studio M3 Ultra 256 GB", "workstation", "metal", 256, 819, unified=True),
165
+ _d("mac-512", "Mac Studio M3 Ultra 512 GB", "workstation", "metal", 512, 819, unified=True),
166
+ _d("a100", "A100 80 GB", "server-gpu", "cuda", 80, 2039, sm=8.0),
167
+ _d("h100", "H100 SXM 80 GB", "server-gpu", "cuda", 80, 3350, sm=9.0),
168
+ _d("h200", "H200 141 GB", "server-gpu", "cuda", 140, 4800, sm=9.0),
169
+ _d("b200", "B200 180 GB", "server-gpu", "cuda", 179, 8000, sm=10.0),
170
+ _d("mi300x", "MI300X 192 GB", "server-gpu", "rocm", 192, 5300),
171
+ _d("8xh100", "8x H100 80 GB", "node", "cuda", 80, 3350, count=8, sm=9.0),
172
+ _d("8xh200", "8x H200 141 GB", "node", "cuda", 140, 4800, count=8, sm=9.0),
173
+ _d("8xb200", "8x B200 180 GB", "node", "cuda", 179, 8000, count=8, sm=10.0),
174
+ _d("8xmi300x", "8x MI300X 192 GB", "node", "rocm", 192, 5300, count=8),
175
+ )
176
+ DEVICE_IDS = {d.id: d for d in DEVICES}
177
+
178
+ # Public model shapes the page offers as presets. Parameters from each model card; KV bytes per
179
+ # token from each config.json: full-attention layers x KV heads x (K + V head dims) x 2 bytes,
180
+ # or the MLA latent (kv_lora_rank + rope dims) x 2 per layer. file_bytes: a published GGUF;
181
+ # catalog: the file size of that catalog.json variant and the entry's KV layout, filled in when
182
+ # the page is built.
183
+ EXAMPLES: tuple[dict[str, Any], ...] = (
184
+ {"id": "qwen3-1.7b", "name": "Qwen3 1.7B", "params": 2.03e9, "attention": "full",
185
+ "kv_per_token": 28 * 8 * 256 * 2, "quant": "Q4_K_M"},
186
+ {"id": "llama3.2-3b", "name": "Llama 3.2 3B", "params": 3.21e9, "attention": "full",
187
+ "kv_per_token": 28 * 8 * 256 * 2, "quant": "Q4_K_M"},
188
+ {"id": "qwen3-4b", "name": "Qwen3 4B", "params": 4.02e9, "attention": "full",
189
+ "kv_per_token": 36 * 8 * 256 * 2, "quant": "Q4_K_M"},
190
+ {"id": "llama3.1-8b", "name": "Llama 3.1 8B", "params": 8.03e9, "attention": "full",
191
+ "kv_per_token": 32 * 8 * 256 * 2, "quant": "Q4_K_M", "file_bytes": 4920739200},
192
+ {"id": "gemma3-27b", "name": "Gemma 3 27B", "params": 27e9, "attention": "swa",
193
+ "kv_per_token": 10 * 16 * 256 * 2, "quant": "Q4_K_M"},
194
+ {"id": "qwen38-27b", "name": "Qwen3.8 27B", "params": 27e9, "attention": "hybrid",
195
+ "quant": "Q4_K_M", "catalog": ["qwen3.8-27b", "UD-Q4_K_M"]},
196
+ {"id": "qwen3-30b-a3b", "name": "Qwen3 30B-A3B", "params": 30.5e9, "active": 3.3e9,
197
+ "attention": "full", "kv_per_token": 48 * 4 * 256 * 2, "quant": "Q4_K_M"},
198
+ {"id": "gpt-oss-20b", "name": "gpt-oss-20b", "params": 20.9e9, "active": 3.6e9,
199
+ "attention": "swa", "kv_per_token": 12 * 8 * 128 * 2, "quant": "MXFP4",
200
+ "file_bytes": 12109566624},
201
+ {"id": "llama3.3-70b", "name": "Llama 3.3 70B", "params": 70.6e9, "attention": "full",
202
+ "kv_per_token": 80 * 8 * 256 * 2, "quant": "Q4_K_M"},
203
+ {"id": "gpt-oss-120b", "name": "gpt-oss-120b", "params": 116.8e9, "active": 5.1e9,
204
+ "attention": "swa", "kv_per_token": 18 * 8 * 128 * 2, "quant": "MXFP4",
205
+ "file_bytes": 63387346208},
206
+ {"id": "qwen3-235b", "name": "Qwen3 235B-A22B", "params": 235e9, "active": 22e9,
207
+ "attention": "full", "kv_per_token": 94 * 4 * 256 * 2, "quant": "Q4_K_M"},
208
+ {"id": "deepseek-v3", "name": "DeepSeek V3 / R1", "params": 671e9, "active": 37e9,
209
+ "attention": "mla", "kv_per_token": 61 * 576 * 2, "quant": "FP8"},
210
+ {"id": "kimi-k2", "name": "Kimi K2", "params": 1.0e12, "active": 32e9, "attention": "mla",
211
+ "kv_per_token": 61 * 576 * 2, "quant": "FP8"},
212
+ ) # fmt: skip
213
+
214
+
215
+ # ── the model ───────────────────────────────────────────────────────────
216
+
217
+
218
+ @dataclass(frozen=True)
219
+ class Shape:
220
+ params: int # total
221
+ active: int # read per token; equal to params for a dense model
222
+ format: QuantFormat
223
+ file_bytes: int
224
+ kv_per_token: int # f16 K+V bytes per token
225
+ kv_source: str # "given" or "guess (<attention>)"
226
+
227
+ @property
228
+ def moe(self) -> bool:
229
+ return self.active < self.params
230
+
231
+ @property
232
+ def bits(self) -> float:
233
+ return self.file_bytes * 8 / self.params
234
+
235
+ @property
236
+ def active_bytes(self) -> float:
237
+ return self.file_bytes * self.active / self.params
238
+
239
+
240
+ def guess_kv_per_token(active: int, attention: str) -> int:
241
+ """f16 K+V bytes per token for a model of ``active`` parameters with this attention kind."""
242
+ if attention not in ATTENTION_KV_SHARE:
243
+ raise MemcalcError(f"attention {attention!r}: use one of {', '.join(ATTENTION_KV_SHARE)}")
244
+ full = KV_REF_BYTES * (active / KV_REF_PARAMS) ** KV_EXPONENT
245
+ return int(full * ATTENTION_KV_SHARE[attention])
246
+
247
+
248
+ def resolve_format(text: str) -> QuantFormat:
249
+ """A named format, or a bare bits-per-weight number priced as the nearest GGUF family."""
250
+ found = quant_formats.lookup(text)
251
+ if found is not None:
252
+ return found
253
+ try:
254
+ bits = float(text)
255
+ except ValueError:
256
+ names = ", ".join(f.name for f in quant_formats.FORMATS)
257
+ raise MemcalcError(
258
+ f"unknown format {text!r}; use bits per weight, EXL3-4.0 or {names}"
259
+ ) from None
260
+ if not 1.0 <= bits <= 32.0:
261
+ raise MemcalcError(f"{text!r} bits per weight is outside 1-32")
262
+ near = quant_formats.nearest(bits)
263
+ return QuantFormat(f"{bits:g} bpw", near.family, bits, "exact", f"priced as {near.family}")
264
+
265
+
266
+ def shape(
267
+ *,
268
+ params: int | None,
269
+ active: int | None,
270
+ fmt: str | None,
271
+ file_bytes: int | None,
272
+ attention: str = "full",
273
+ kv_per_token: int | None = None,
274
+ ) -> tuple[Shape, list[str]]:
275
+ """Fill in the one of parameters, format and file size that is missing; notes say what was
276
+ inferred. At least two of the three are required."""
277
+ notes: list[str] = []
278
+ file_given = file_bytes is not None
279
+ given = sum(x is not None for x in (params, fmt, file_bytes))
280
+ if given < 2:
281
+ raise MemcalcError("give two of --params, --quant and --file-size")
282
+ if params is not None and params <= 0 or file_bytes is not None and file_bytes <= 0:
283
+ raise MemcalcError("parameters and file size must be positive")
284
+ if params is None:
285
+ assert fmt is not None and file_bytes is not None
286
+ f = resolve_format(fmt)
287
+ params = int(file_bytes * 8 / f.bits)
288
+ notes.append(
289
+ f"{params / 1e9:.1f}B parameters inferred from the file size at {f.bits:g} bpw"
290
+ )
291
+ elif file_bytes is None:
292
+ assert fmt is not None
293
+ f = resolve_format(fmt)
294
+ file_bytes = int(params * f.bits / 8)
295
+ else:
296
+ bits = file_bytes * 8 / params
297
+ if fmt is None:
298
+ near = quant_formats.nearest(bits)
299
+ f = QuantFormat(
300
+ f"{bits:.2f} bpw", near.family, bits, "exact", f"nearest listed: {near.name}"
301
+ )
302
+ notes.append(f"{bits:.2f} bits per weight; the nearest listed format is {near.name}")
303
+ else:
304
+ f = resolve_format(fmt)
305
+ if abs(bits - f.bits) / f.bits > 0.15:
306
+ notes.append(
307
+ f"the file holds {bits:.2f} bits per weight, {f.name} is typically {f.bits:g}: "
308
+ "check the parameter count (embeddings, vision tower, MTP heads)"
309
+ )
310
+ if f.family == "exl" and not file_given:
311
+ notes.append(
312
+ "EXL bit rates leave out the 16-bit embeddings and 6-bit head, so the file runs "
313
+ "larger than this; give --file-size when known"
314
+ )
315
+ if params < SMALL_MODEL_PARAMS and fmt is not None and not file_given:
316
+ notes.append(
317
+ "small model: embeddings are a large share, so real files run above the table "
318
+ "(Qwen3-0.6B Q4_K_M holds 5.30 bits per weight); give --file-size when known"
319
+ )
320
+ active = params if active is None else active
321
+ if not 0 < active <= params:
322
+ raise MemcalcError("active parameters must be positive and at most the total")
323
+ if kv_per_token is None:
324
+ kv = guess_kv_per_token(active, attention)
325
+ source = f"guessed for {attention} attention"
326
+ else:
327
+ kv, source = kv_per_token, "given"
328
+ return Shape(params, active, f, file_bytes, kv, source), notes
329
+
330
+
331
+ def expert_share(s: Shape) -> float:
332
+ """Share of the weights in routed experts: what --n-cpu-moe can move to system RAM."""
333
+ if not s.moe:
334
+ return 0.0
335
+ return 1 - MOE_SHARED_OF_ACTIVE * s.active / s.params
336
+
337
+
338
+ # ── one device ──────────────────────────────────────────────────────────
339
+
340
+
341
+ @dataclass(frozen=True)
342
+ class Posture:
343
+ context: int = DEFAULT_CONTEXT
344
+ slots: int = 1
345
+ kv_type: str = "f16"
346
+ host_ram: int = DEFAULT_HOST_RAM
347
+ host_bandwidth_gb_s: float = DEFAULT_HOST_BANDWIDTH_GB_S
348
+
349
+
350
+ def kv_bytes(s: Shape, posture: Posture) -> int:
351
+ scale = KV_BYTES_PER_ELEM[posture.kv_type] / 2
352
+ return int(s.kv_per_token * scale * posture.context * posture.slots)
353
+
354
+
355
+ def support(fmt: QuantFormat, device: Device) -> tuple[str, str]:
356
+ """(engine, status): status is native, fallback, or convert (the format does not run here; a
357
+ GGUF or MLX build of the same size would)."""
358
+ rule = SUPPORT.get(fmt.family, {}).get(device.backend)
359
+ if rule is None:
360
+ fallback = "mlx" if device.backend in ("metal", "ios") else "llama.cpp"
361
+ return fallback, "convert"
362
+ engine, native, runs = rule
363
+ if device.backend != "cuda" or device.sm >= native:
364
+ return engine, "native"
365
+ return (engine, "fallback") if device.sm >= runs else (engine, "convert")
366
+
367
+
368
+ def usable_bytes(device: Device, engine: Engine) -> int:
369
+ """Memory the engine may fill on the device, all accelerators together."""
370
+ total = device.memory_bytes
371
+ if device.backend == "android":
372
+ cap = ANDROID_FOREGROUND_GIB.get(round(device.memory_gib))
373
+ return cap * GIB if cap else total
374
+ if device.backend == "ios":
375
+ return int(total * IOS_APP_SHARE)
376
+ if device.unified:
377
+ room = total - metal.in_use(total) - metal.HOST_KEEP_BYTES
378
+ if device.backend == "metal":
379
+ room = min(metal.default_working_set(total), room)
380
+ return max(0, room - estimator.METAL_VRAM_RESERVE_BYTES)
381
+ if engine.card_share < 1:
382
+ per_card = int(total * engine.card_share)
383
+ else:
384
+ per_card = total - estimator.AGENT_VRAM_RESERVE_BYTES
385
+ return per_card * device.count
386
+
387
+
388
+ def need(s: Shape, engine: Engine, posture: Posture, count: int = 1) -> dict[str, int]:
389
+ """Bytes the model takes on the accelerators by part; ``total`` is their sum."""
390
+ out = {
391
+ "weights": s.file_bytes,
392
+ "kv": kv_bytes(s, posture),
393
+ "overhead": (engine.fixed_bytes + engine.per_context_token * posture.context) * count,
394
+ }
395
+ out["total"] = sum(out.values())
396
+ return out
397
+
398
+
399
+ def _tok_s(read_gpu: float, bw_gpu: float, read_host: float = 0, bw_host: float = 1) -> float:
400
+ seconds = read_gpu / (bw_gpu * 1e9) + read_host / (bw_host * 1e9)
401
+ return round(1 / seconds, 1) if seconds > 0 else 0.0
402
+
403
+
404
+ def place(s: Shape, device: Device, posture: Posture) -> dict[str, Any]:
405
+ """Whether the model fits the device, offloads to its system RAM, or does not fit, with the
406
+ bandwidth ceiling of one sequence's decode."""
407
+ engine_name, status = support(s.format, device)
408
+ engine = ENGINES[engine_name]
409
+ room = usable_bytes(device, engine)
410
+ parts = need(s, engine, posture, device.count)
411
+ kv_read = parts["kv"] / posture.slots
412
+ row: dict[str, Any] = {
413
+ "device": device.id,
414
+ "name": device.name,
415
+ "tier": device.tier,
416
+ "engine": engine.name,
417
+ "format_support": status,
418
+ "usable_bytes": room,
419
+ "need": parts,
420
+ "verdict": "no",
421
+ "decode_ceiling_tok_s": 0.0,
422
+ }
423
+ bandwidth = device.bandwidth_gb_s * device.count
424
+ if parts["total"] <= room:
425
+ row["verdict"] = "fits"
426
+ row["decode_ceiling_tok_s"] = _tok_s(s.active_bytes + kv_read, bandwidth)
427
+ return row
428
+ if device.host_offload:
429
+ offload = _offload(s, device, posture)
430
+ if offload is not None:
431
+ row.update(offload)
432
+ return row
433
+
434
+
435
+ def _offload(s: Shape, device: Device, posture: Posture) -> dict[str, Any] | None:
436
+ """llama.cpp's placement with system RAM: an MoE keeps attention, shared weights and the KV
437
+ on the card and moves routed experts (--n-cpu-moe); a dense model moves whole layers with
438
+ their KV (-ngl). Decode reads each side at its own bandwidth."""
439
+ engine = ENGINES["llama.cpp"]
440
+ room = usable_bytes(device, engine)
441
+ host_room = posture.host_ram - HOST_RAM_FLOOR - estimator.LLAMA_HOST_BASE_BYTES
442
+ parts = need(s, engine, posture)
443
+ kv_read = parts["kv"] / posture.slots
444
+ if s.moe:
445
+ movable = s.file_bytes * expert_share(s)
446
+ movable_read = s.active_bytes * (1 - MOE_SHARED_OF_ACTIVE) # routed experts per token
447
+ else:
448
+ movable = s.file_bytes + parts["kv"]
449
+ movable_read = s.active_bytes + kv_read
450
+ if parts["total"] - movable > room:
451
+ return None
452
+ to_host = max(0, parts["total"] - room)
453
+ if to_host > host_room:
454
+ return None
455
+ read_host = movable_read * to_host / movable
456
+ read_gpu = s.active_bytes + kv_read - read_host
457
+ host_kv = 0 if s.moe else int(parts["kv"] * (to_host / movable))
458
+ return {
459
+ "verdict": "offload",
460
+ "engine": engine.name,
461
+ "format_support": "native" if s.format.family in ("gguf", "mxfp4") else "convert",
462
+ "usable_bytes": room,
463
+ "need": parts,
464
+ "offload_bytes": int(to_host),
465
+ "host_weights_bytes": int(to_host) - host_kv,
466
+ "host_kv_bytes": host_kv,
467
+ "host_room_bytes": int(host_room),
468
+ "decode_ceiling_tok_s": _tok_s(
469
+ read_gpu, device.bandwidth_gb_s, read_host, posture.host_bandwidth_gb_s
470
+ ),
471
+ }
472
+
473
+
474
+ # ── the report ──────────────────────────────────────────────────────────
475
+
476
+ LADDER = ("BF16", "FP8", "Q8_0", "Q6_K", "Q5_K_M", "Q4_K_M", "AWQ-INT4", "IQ3_S", "IQ2_XXS")
477
+
478
+
479
+ def _rank(row: dict[str, Any]) -> tuple[bool, bool]:
480
+ """Fitting before offloading, and the format as given before a conversion."""
481
+ return (row["verdict"] != "fits", row["format_support"] == "convert")
482
+
483
+
484
+ def tiers(rows: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
485
+ """Per tier: the smallest device that fits, else the smallest that offloads, preferring
486
+ devices that run the format as given."""
487
+ out = []
488
+ for tier, label, _ in TIERS:
489
+ usable = [r for r in rows if r["tier"] == tier and r["verdict"] != "no"]
490
+ pick = min(usable, key=_rank) if usable else None
491
+ out.append(
492
+ {
493
+ "tier": tier,
494
+ "label": label,
495
+ "verdict": pick["verdict"] if pick else "no",
496
+ "format_support": pick["format_support"] if pick else None,
497
+ "device": pick["device"] if pick else None,
498
+ "name": pick["name"] if pick else None,
499
+ "decode_ceiling_tok_s": pick["decode_ceiling_tok_s"] if pick else 0.0,
500
+ }
501
+ )
502
+ return out
503
+
504
+
505
+ def magnitude(tier_rows: Sequence[dict[str, Any]]) -> dict[str, str | None]:
506
+ """The first tier the model fits (in some format of its size), the first that holds it in
507
+ the format as given, and the first it runs on with system RAM's help."""
508
+ fits = next((t["tier"] for t in tier_rows if t["verdict"] == "fits"), None)
509
+ as_is = next(
510
+ (
511
+ t["tier"]
512
+ for t in tier_rows
513
+ if t["verdict"] == "fits" and t["format_support"] != "convert"
514
+ ),
515
+ None,
516
+ )
517
+ runs = next((t["tier"] for t in tier_rows if t["verdict"] != "no"), None)
518
+ return {"fits": fits, "fits_as_is": as_is, "runs": runs}
519
+
520
+
521
+ def ladder(s: Shape, posture: Posture) -> list[dict[str, Any]]:
522
+ """The same model at the common formats: file size and the first tier it fits. The format
523
+ given keeps its own file size."""
524
+ out = []
525
+ names = list(LADDER)
526
+ if s.format.name not in names:
527
+ names.append(s.format.name)
528
+ for name in names:
529
+ if name == s.format.name:
530
+ other = s
531
+ else:
532
+ fmt = quant_formats.BY_NAME[name]
533
+ size = int(s.params * fmt.bits / 8)
534
+ other = Shape(s.params, s.active, fmt, size, s.kv_per_token, s.kv_source)
535
+ rows = [place(other, d, posture) for d in DEVICES]
536
+ mag = magnitude(tiers(rows))
537
+ out.append(
538
+ {
539
+ "format": other.format.name,
540
+ "bits": round(other.bits, 3),
541
+ "file_bytes": other.file_bytes,
542
+ "fits": mag["fits"],
543
+ "fits_as_is": mag["fits_as_is"],
544
+ "runs": mag["runs"],
545
+ "current": name == s.format.name,
546
+ }
547
+ )
548
+ return sorted(out, key=lambda r: -r["bits"])
549
+
550
+
551
+ def report(
552
+ s: Shape, posture: Posture, notes: Sequence[str] = (), devices: Sequence[str] = ()
553
+ ) -> dict[str, Any]:
554
+ rows = [place(s, d, posture) for d in DEVICES]
555
+ tier_rows = tiers(rows)
556
+ shown = [r for r in rows if not devices or r["device"] in devices]
557
+ engine = ENGINES[quant_formats.DEFAULT_ENGINE[s.format.family]]
558
+ return {
559
+ "schema": SCHEMA,
560
+ "model": {
561
+ "kind": "moe" if s.moe else "dense",
562
+ "params": s.params,
563
+ "active_params": s.active,
564
+ "expert_share": round(expert_share(s), 4),
565
+ },
566
+ "format": {
567
+ "name": s.format.name,
568
+ "family": s.format.family,
569
+ "bits_per_weight": round(s.bits, 3),
570
+ "default_engine": engine.name,
571
+ "note": s.format.note,
572
+ },
573
+ "file_bytes": s.file_bytes,
574
+ "kv_bytes_per_token": s.kv_per_token,
575
+ "kv_source": s.kv_source,
576
+ "posture": {
577
+ "context": posture.context,
578
+ "slots": posture.slots,
579
+ "kv_type": posture.kv_type,
580
+ "host_ram_bytes": posture.host_ram,
581
+ "host_bandwidth_gb_s": posture.host_bandwidth_gb_s,
582
+ },
583
+ "runtime": need(s, engine, posture),
584
+ "magnitude": magnitude(tier_rows),
585
+ "tiers": tier_rows,
586
+ "devices": shown,
587
+ "ladder": ladder(s, posture),
588
+ "notes": list(notes),
589
+ "estimate": True,
590
+ }
591
+
592
+
593
+ def page_data() -> dict[str, Any]:
594
+ """Every table the HTML page computes with, so it prices exactly as this module does."""
595
+ return {
596
+ "schema": SCHEMA,
597
+ "formats": [vars(f) for f in quant_formats.FORMATS],
598
+ "default_engine": quant_formats.DEFAULT_ENGINE,
599
+ "engines": {k: vars(e) for k, e in ENGINES.items()},
600
+ "support": {fam: {b: list(r) for b, r in rules.items()} for fam, rules in SUPPORT.items()},
601
+ "tiers": [list(t) for t in TIERS],
602
+ "devices": [
603
+ {
604
+ **vars(d),
605
+ "usable": {k: usable_bytes(d, e) for k, e in ENGINES.items()},
606
+ }
607
+ for d in DEVICES
608
+ ],
609
+ "ladder": list(LADDER),
610
+ "examples": [dict(e) for e in EXAMPLES],
611
+ "constants": {
612
+ "kv_ref_bytes": KV_REF_BYTES,
613
+ "kv_ref_params": KV_REF_PARAMS,
614
+ "kv_exponent": KV_EXPONENT,
615
+ "attention_kv_share": ATTENTION_KV_SHARE,
616
+ "kv_bytes_per_elem": KV_BYTES_PER_ELEM,
617
+ "moe_shared_of_active": MOE_SHARED_OF_ACTIVE,
618
+ "host_ram_floor": HOST_RAM_FLOOR,
619
+ "llama_host_base": estimator.LLAMA_HOST_BASE_BYTES,
620
+ "default_host_ram": DEFAULT_HOST_RAM,
621
+ "default_host_bandwidth_gb_s": DEFAULT_HOST_BANDWIDTH_GB_S,
622
+ "default_context": DEFAULT_CONTEXT,
623
+ "small_model_params": SMALL_MODEL_PARAMS,
624
+ },
625
+ }