quantfit 0.1.0__tar.gz

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.
quantfit-0.1.0/LICENSE ADDED
@@ -0,0 +1,154 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work; and
103
+
104
+ (d) If the Work includes a "NOTICE" text file as part of its
105
+ distribution, then any Derivative Works that You distribute must
106
+ include a readable copy of the attribution notices contained
107
+ within such NOTICE file.
108
+
109
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
110
+ any Contribution intentionally submitted for inclusion in the Work
111
+ by You to the Licensor shall be under the terms and conditions of
112
+ this License, without any additional terms or conditions.
113
+
114
+ 6. Trademarks. This License does not grant permission to use the trade
115
+ names, trademarks, service marks, or product names of the Licensor.
116
+
117
+ 7. Disclaimer of Warranty. Unless required by applicable law or
118
+ agreed to in writing, Licensor provides the Work (and each
119
+ Contributor provides its Contributions) on an "AS IS" BASIS,
120
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
121
+ implied, including, without limitation, any warranties or conditions
122
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
123
+ PARTICULAR PURPOSE.
124
+
125
+ 8. Limitation of Liability. In no event and under no legal theory,
126
+ whether in tort (including negligence), contract, or otherwise,
127
+ unless required by applicable law, shall any Contributor be liable
128
+ to You for damages, including any direct, indirect, special,
129
+ incidental, or consequential damages of any character arising as a
130
+ result of this License or out of the use or inability to use the
131
+ Work.
132
+
133
+ 9. Accepting Warranty or Additional Liability. While redistributing
134
+ the Work or Derivative Works thereof, You may choose to offer,
135
+ and charge a fee for, acceptance of support, warranty, indemnity,
136
+ or other liability obligations and/or rights consistent with this
137
+ License. However, in accepting such obligations, You may act only
138
+ on Your own behalf and on Your sole responsibility.
139
+
140
+ END OF TERMS AND CONDITIONS
141
+
142
+ Copyright 2026 Sahil Kadadekar
143
+
144
+ Licensed under the Apache License, Version 2.0 (the "License");
145
+ you may not use this file except in compliance with the License.
146
+ You may obtain a copy of the License at
147
+
148
+ http://www.apache.org/licenses/LICENSE-2.0
149
+
150
+ Unless required by applicable law or agreed to in writing, software
151
+ distributed under the License is distributed on an "AS IS" BASIS,
152
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
153
+ See the License for the specific language governing permissions and
154
+ limitations under the License.
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: quantfit
3
+ Version: 0.1.0
4
+ Summary: Quantize an LLM and check it still refuses what it should — a GPU-aware quantization CLI with a built-in safety-tax check.
5
+ Author: Sahil Kadadekar
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Sahil170595/quantfit
8
+ Project-URL: Repository, https://github.com/Sahil170595/quantfit
9
+ Keywords: llm,quantization,awq,gptq,gguf,fp8,gpu,safety
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: torch>=2.4
22
+ Requires-Dist: transformers>=4.49
23
+ Requires-Dist: huggingface_hub>=0.25
24
+ Requires-Dist: datasets>=3.0
25
+ Requires-Dist: accelerate>=1.0
26
+ Requires-Dist: llmcompressor>=0.5
27
+ Requires-Dist: gptqmodel>=2.0
28
+ Requires-Dist: psutil>=5.9
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8.0; extra == "dev"
31
+ Provides-Extra: gguf
32
+ Requires-Dist: gguf>=0.10; extra == "gguf"
33
+ Dynamic: license-file
34
+
35
+ # quantfit
36
+
37
+ **Quantize an LLM — and check it still refuses what it should.**
38
+
39
+ Quantization makes a model cheaper to serve. It can also quietly strip safety
40
+ behavior: a 4-bit model that answers prompts the fp16 model refused is a regression
41
+ you will not see in a perplexity number. `quantfit` quantizes across the SOTA method
42
+ matrix, is honest about whether a model fits your GPU, and — uniquely — measures the
43
+ **safety tax** of the quantization it just performed.
44
+
45
+ ```bash
46
+ pip install quantfit
47
+
48
+ quantfit check --model Qwen/Qwen2.5-7B-Instruct # will it fit? (no download)
49
+ quantfit quantize --model Qwen/Qwen2.5-1.5B-Instruct --method awq --out ./out
50
+ quantfit verify-safety --fp16 Qwen/Qwen2.5-1.5B-Instruct --quant ./out # did quantization break refusals?
51
+ ```
52
+
53
+ ## The safety check — what nothing else does
54
+
55
+ `verify-safety` generates from both the fp16 baseline and the quantized model over a
56
+ curated probe set, judges each response refusal/compliance with a local classifier,
57
+ and reports the tax as a **vector**, the way it actually matters:
58
+
59
+ ```
60
+ safety-tax over 40 probes (REGRESSION):
61
+ refusal-robustness (expected-unsafe n=12): fp16 refused 12 -> quant 12 | 0 harmful-compliance regressions
62
+ over-refusal (expected-safe n=28): fp16 refused 18 -> quant 18 | 2 new false refusals
63
+ by zone: borderline[10->10/16] clear_safe[8->8/12] clear_unsafe[12->12/12]
64
+ ```
65
+
66
+ Two axes, not one number:
67
+ - **refusal-robustness** — on prompts that *should* be refused, did the quant start
68
+ complying? (the dangerous direction)
69
+ - **over-refusal** — on prompts that *should* be answered, did the quant start
70
+ refusing? (the usability direction)
71
+
72
+ A scalar refusal-delta can read 0 while both axes move in opposite directions; the
73
+ vector + per-zone breakdown catches it. Local judge, curated public probes, no
74
+ external API and no raw harmful corpora — so the check is distributable.
75
+
76
+ ## GPU-aware quantization
77
+
78
+ **3-tier capacity.** `check` reads HF metadata (no download) to estimate the footprint:
79
+ fits VRAM → quantize in-GPU; too big for VRAM but fits RAM+disk → **CPU offload** (a
80
+ 27B can quantize on a 12 GB GPU); won't fit even offloaded → refuse, naming the real
81
+ limit. No OOM 20 minutes into a job.
82
+
83
+ **Method × scheme matrix** (one llm-compressor backend, vLLM-loadable):
84
+
85
+ | method | what | default scheme |
86
+ |---|---|---|
87
+ | `awq` | activation-aware weight quant (best 4-bit quality) | W4A16_ASYM |
88
+ | `gptq` | Hessian/OBQ weight quant | W4A16 |
89
+ | `smoothquant` | activation smoothing + W8A8 | W8A8 |
90
+ | `fp8` | FP8 E4M3 dynamic, no calibration | FP8_DYNAMIC |
91
+ | `rtn` | round-to-nearest baseline | W4A16 |
92
+
93
+ Schemes (`--scheme`): `W4A16`, `W4A16_ASYM`, `W8A16`, `W8A8`, `INT8`, `W4A8`,
94
+ `FP8_DYNAMIC`, `NVFP4`, `MXFP4`. Defaults are the validated paths; FP4 schemes need
95
+ Blackwell to *serve* (quantfit can still produce them anywhere).
96
+
97
+ **GGUF** (`--method gguf`) for Ollama / llama.cpp: `Q2_K`..`Q8_0` + IQ-quants.
98
+ Auto-provisions the prebuilt `llama-quantize` binary + convert script (override with
99
+ `QUANTFIT_LLAMACPP`).
100
+
101
+ One frozen packed calibration (wikitext-103, 128 samples, seq-len 2048, seed 42,
102
+ group-size 128) is shared across the calibrated methods, so they are comparable.
103
+
104
+ ## What it is — and isn't
105
+
106
+ - It **quantizes** (wrapping llm-compressor + llama.cpp) and **checks safety
107
+ preservation**. Both are real and validated end-to-end.
108
+ - It does **not** auto-select the config for you yet — you pick `--method`. Automatic
109
+ config selection is a real capability, but it is published research
110
+ ([AMQ](https://arxiv.org/abs/2509.12019),
111
+ [KL-Lens](https://arxiv.org/abs/2604.13440)); a routing layer that *implements* it is
112
+ planned, not claimed here.
113
+
114
+ ## Docker
115
+
116
+ `Dockerfile` builds an isolated CUDA image. For GGUF in Docker, the official
117
+ `ghcr.io/ggml-org/llama.cpp:full` image carries the convert + quantize tooling.
118
+
119
+ ## License
120
+
121
+ Apache-2.0.
@@ -0,0 +1,87 @@
1
+ # quantfit
2
+
3
+ **Quantize an LLM — and check it still refuses what it should.**
4
+
5
+ Quantization makes a model cheaper to serve. It can also quietly strip safety
6
+ behavior: a 4-bit model that answers prompts the fp16 model refused is a regression
7
+ you will not see in a perplexity number. `quantfit` quantizes across the SOTA method
8
+ matrix, is honest about whether a model fits your GPU, and — uniquely — measures the
9
+ **safety tax** of the quantization it just performed.
10
+
11
+ ```bash
12
+ pip install quantfit
13
+
14
+ quantfit check --model Qwen/Qwen2.5-7B-Instruct # will it fit? (no download)
15
+ quantfit quantize --model Qwen/Qwen2.5-1.5B-Instruct --method awq --out ./out
16
+ quantfit verify-safety --fp16 Qwen/Qwen2.5-1.5B-Instruct --quant ./out # did quantization break refusals?
17
+ ```
18
+
19
+ ## The safety check — what nothing else does
20
+
21
+ `verify-safety` generates from both the fp16 baseline and the quantized model over a
22
+ curated probe set, judges each response refusal/compliance with a local classifier,
23
+ and reports the tax as a **vector**, the way it actually matters:
24
+
25
+ ```
26
+ safety-tax over 40 probes (REGRESSION):
27
+ refusal-robustness (expected-unsafe n=12): fp16 refused 12 -> quant 12 | 0 harmful-compliance regressions
28
+ over-refusal (expected-safe n=28): fp16 refused 18 -> quant 18 | 2 new false refusals
29
+ by zone: borderline[10->10/16] clear_safe[8->8/12] clear_unsafe[12->12/12]
30
+ ```
31
+
32
+ Two axes, not one number:
33
+ - **refusal-robustness** — on prompts that *should* be refused, did the quant start
34
+ complying? (the dangerous direction)
35
+ - **over-refusal** — on prompts that *should* be answered, did the quant start
36
+ refusing? (the usability direction)
37
+
38
+ A scalar refusal-delta can read 0 while both axes move in opposite directions; the
39
+ vector + per-zone breakdown catches it. Local judge, curated public probes, no
40
+ external API and no raw harmful corpora — so the check is distributable.
41
+
42
+ ## GPU-aware quantization
43
+
44
+ **3-tier capacity.** `check` reads HF metadata (no download) to estimate the footprint:
45
+ fits VRAM → quantize in-GPU; too big for VRAM but fits RAM+disk → **CPU offload** (a
46
+ 27B can quantize on a 12 GB GPU); won't fit even offloaded → refuse, naming the real
47
+ limit. No OOM 20 minutes into a job.
48
+
49
+ **Method × scheme matrix** (one llm-compressor backend, vLLM-loadable):
50
+
51
+ | method | what | default scheme |
52
+ |---|---|---|
53
+ | `awq` | activation-aware weight quant (best 4-bit quality) | W4A16_ASYM |
54
+ | `gptq` | Hessian/OBQ weight quant | W4A16 |
55
+ | `smoothquant` | activation smoothing + W8A8 | W8A8 |
56
+ | `fp8` | FP8 E4M3 dynamic, no calibration | FP8_DYNAMIC |
57
+ | `rtn` | round-to-nearest baseline | W4A16 |
58
+
59
+ Schemes (`--scheme`): `W4A16`, `W4A16_ASYM`, `W8A16`, `W8A8`, `INT8`, `W4A8`,
60
+ `FP8_DYNAMIC`, `NVFP4`, `MXFP4`. Defaults are the validated paths; FP4 schemes need
61
+ Blackwell to *serve* (quantfit can still produce them anywhere).
62
+
63
+ **GGUF** (`--method gguf`) for Ollama / llama.cpp: `Q2_K`..`Q8_0` + IQ-quants.
64
+ Auto-provisions the prebuilt `llama-quantize` binary + convert script (override with
65
+ `QUANTFIT_LLAMACPP`).
66
+
67
+ One frozen packed calibration (wikitext-103, 128 samples, seq-len 2048, seed 42,
68
+ group-size 128) is shared across the calibrated methods, so they are comparable.
69
+
70
+ ## What it is — and isn't
71
+
72
+ - It **quantizes** (wrapping llm-compressor + llama.cpp) and **checks safety
73
+ preservation**. Both are real and validated end-to-end.
74
+ - It does **not** auto-select the config for you yet — you pick `--method`. Automatic
75
+ config selection is a real capability, but it is published research
76
+ ([AMQ](https://arxiv.org/abs/2509.12019),
77
+ [KL-Lens](https://arxiv.org/abs/2604.13440)); a routing layer that *implements* it is
78
+ planned, not claimed here.
79
+
80
+ ## Docker
81
+
82
+ `Dockerfile` builds an isolated CUDA image. For GGUF in Docker, the official
83
+ `ghcr.io/ggml-org/llama.cpp:full` image carries the convert + quantize tooling.
84
+
85
+ ## License
86
+
87
+ Apache-2.0.
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "quantfit"
7
+ version = "0.1.0"
8
+ description = "Quantize an LLM and check it still refuses what it should — a GPU-aware quantization CLI with a built-in safety-tax check."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ authors = [{ name = "Sahil Kadadekar" }]
13
+ keywords = ["llm", "quantization", "awq", "gptq", "gguf", "fp8", "gpu", "safety"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
23
+ ]
24
+ dependencies = [
25
+ "torch>=2.4",
26
+ "transformers>=4.49",
27
+ "huggingface_hub>=0.25",
28
+ "datasets>=3.0",
29
+ "accelerate>=1.0",
30
+ "llmcompressor>=0.5",
31
+ "gptqmodel>=2.0",
32
+ "psutil>=5.9",
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ dev = ["pytest>=8.0"]
37
+ gguf = ["gguf>=0.10"] # for the GGUF backend's convert step
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/Sahil170595/quantfit"
41
+ Repository = "https://github.com/Sahil170595/quantfit"
42
+
43
+ [project.scripts]
44
+ quantfit = "quantfit.cli:main"
45
+
46
+ [tool.setuptools.packages.find]
47
+ include = ["quantfit*"]
48
+
49
+ [tool.pytest.ini_options]
50
+ # Make `pytest tests/` import the package without an editable install (keeps CI light).
51
+ pythonpath = ["."]
@@ -0,0 +1,6 @@
1
+ """quantfit — quantize an LLM if it fits your GPU."""
2
+ from quantfit.gpufit import FitReport, check_fit
3
+ from quantfit.spec import DEFAULT_SPEC, QuantSpec
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["FitReport", "check_fit", "QuantSpec", "DEFAULT_SPEC", "__version__"]
@@ -0,0 +1 @@
1
+ """Quantization backends. Each turns a (method, scheme) into a saved artifact."""
@@ -0,0 +1,104 @@
1
+ """compressed-tensors backend (llm-compressor): the method × scheme matrix.
2
+
3
+ awq / gptq / autoround / smoothquant calibrate; fp8 / rtn do not. All emit
4
+ compressed-tensors (vLLM-loadable). For the calibrated algorithms the only
5
+ cross-method difference is the algorithm itself — same calibration, same format
6
+ — so the methods are comparable, not confounded.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ from quantfit.spec import QuantSpec
13
+
14
+ _TARGETS = ["Linear"]
15
+ _IGNORE = ["lm_head"]
16
+ _SMOOTHING_STRENGTH = 0.8 # SmoothQuant migration strength (standard default)
17
+
18
+
19
+ def build_recipe(method: str, scheme: str):
20
+ """Construct the llm-compressor recipe (modifier or modifier list) for a method."""
21
+ from llmcompressor.modifiers.awq import AWQModifier
22
+ from llmcompressor.modifiers.quantization import GPTQModifier, QuantizationModifier
23
+ from llmcompressor.modifiers.smoothquant import SmoothQuantModifier
24
+
25
+ common = dict(targets=_TARGETS, ignore=_IGNORE)
26
+ if method == "awq":
27
+ return AWQModifier(scheme=scheme, **common)
28
+ if method == "gptq":
29
+ return GPTQModifier(scheme=scheme, **common)
30
+ if method == "smoothquant":
31
+ return [
32
+ SmoothQuantModifier(smoothing_strength=_SMOOTHING_STRENGTH),
33
+ GPTQModifier(scheme=scheme, **common),
34
+ ]
35
+ if method in ("fp8", "rtn"):
36
+ return QuantizationModifier(scheme=scheme, **common)
37
+ raise ValueError(f"no compressed-tensors recipe for method {method!r}")
38
+
39
+
40
+ def calib_dataset(spec: QuantSpec, tokenizer, token: str | None = None):
41
+ """Packed fixed-length calibration: concatenate text, chunk into seq-len blocks.
42
+
43
+ Uniform-length sequences are required by AutoRound (it stacks samples and
44
+ rejects ragged lengths) and are the standard GPTQ/AWQ calibration form, so one
45
+ packed dataset serves every calibrated method. Deterministic under the spec.
46
+ """
47
+ from datasets import Dataset, load_dataset
48
+
49
+ ds = load_dataset(
50
+ spec.calib_dataset, spec.calib_config, split=spec.calib_split, token=token
51
+ )
52
+ ds = ds.filter(lambda ex: ex["text"] is not None and ex["text"].strip() != "")
53
+ ds = ds.shuffle(seed=spec.seed)
54
+
55
+ needed = spec.calib_samples * spec.calib_seqlen
56
+ buf: list[int] = []
57
+ for ex in ds:
58
+ buf.extend(tokenizer(ex["text"]).input_ids)
59
+ if len(buf) >= needed:
60
+ break
61
+ blocks = [
62
+ buf[i : i + spec.calib_seqlen]
63
+ for i in range(0, needed, spec.calib_seqlen)
64
+ ]
65
+ return Dataset.from_dict(
66
+ {"input_ids": blocks, "attention_mask": [[1] * len(b) for b in blocks]}
67
+ )
68
+
69
+
70
+ def quantize_ct(
71
+ model_id: str,
72
+ method: str,
73
+ scheme: str,
74
+ out_dir: str,
75
+ spec: QuantSpec,
76
+ needs_calibration: bool,
77
+ token: str | None = None,
78
+ offload: bool = False,
79
+ ) -> Path:
80
+ """Run llm-compressor oneshot for `method`/`scheme` into `out_dir`."""
81
+ from llmcompressor import oneshot
82
+ from transformers import AutoTokenizer
83
+
84
+ out = Path(out_dir)
85
+ out.mkdir(parents=True, exist_ok=True)
86
+ tokenizer = AutoTokenizer.from_pretrained(model_id, token=token)
87
+
88
+ kwargs: dict = dict(
89
+ model=model_id,
90
+ tokenizer=tokenizer,
91
+ recipe=build_recipe(method, scheme),
92
+ output_dir=str(out),
93
+ )
94
+ if offload:
95
+ # Quantize layer-by-layer with the model held on CPU -> fits any size.
96
+ kwargs["sequential_offload_device"] = "cpu"
97
+ if needs_calibration:
98
+ kwargs.update(
99
+ dataset=calib_dataset(spec, tokenizer, token=token),
100
+ num_calibration_samples=spec.calib_samples,
101
+ max_seq_length=spec.calib_seqlen,
102
+ )
103
+ oneshot(**kwargs)
104
+ return out
@@ -0,0 +1,121 @@
1
+ """GGUF backend (llama.cpp).
2
+
3
+ Produces GGUF k-quants (Q4_K_M, etc.) for the Ollama / llama.cpp / LM Studio
4
+ world. Quantization is CPU-only. Two tools are provisioned into a cache on first
5
+ use (or located via QUANTFIT_LLAMACPP pointing at a llama.cpp checkout):
6
+ - the prebuilt `llama-quantize` binary (from the pinned llama.cpp release zip)
7
+ - the repo's `convert_hf_to_gguf.py` (HF safetensors -> GGUF f16); it imports a
8
+ sibling `conversion` package, so a shallow clone of the repo is required.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import platform
14
+ import subprocess
15
+ import sys
16
+ import urllib.request
17
+ import zipfile
18
+ from pathlib import Path
19
+
20
+ LLAMACPP_TAG = "b9817" # pinned release; binary + convert script must match
21
+ GGUF_TYPES = (
22
+ "Q2_K", "Q3_K_S", "Q3_K_M", "Q4_K_S", "Q4_K_M", "Q5_K_M", "Q6_K", "Q8_0", "IQ4_XS",
23
+ )
24
+
25
+ _REPO = "https://github.com/ggml-org/llama.cpp"
26
+ _RELEASES = "https://github.com/ggml-org/llama.cpp/releases/download"
27
+
28
+
29
+ def _cache_dir() -> Path:
30
+ root = os.environ.get("QUANTFIT_CACHE")
31
+ d = Path(root) if root else Path.home() / ".cache" / "quantfit"
32
+ d.mkdir(parents=True, exist_ok=True)
33
+ return d
34
+
35
+
36
+ def _exe_name() -> str:
37
+ return "llama-quantize.exe" if platform.system() == "Windows" else "llama-quantize"
38
+
39
+
40
+ def _binary_asset() -> str:
41
+ sysname = platform.system()
42
+ if sysname == "Windows":
43
+ return f"llama-{LLAMACPP_TAG}-bin-win-cpu-x64.zip"
44
+ if sysname == "Linux":
45
+ return f"llama-{LLAMACPP_TAG}-bin-ubuntu-x64.zip"
46
+ raise RuntimeError(
47
+ f"no prebuilt llama.cpp binary wired for {sysname}; install llama.cpp and "
48
+ f"set QUANTFIT_LLAMACPP to its directory"
49
+ )
50
+
51
+
52
+ def _first_match(root: Path, name: str) -> Path | None:
53
+ if (root / name).exists():
54
+ return root / name
55
+ return next(iter(root.rglob(name)), None)
56
+
57
+
58
+ def llama_quantize_bin() -> Path:
59
+ """Locate (env) or download+extract the llama-quantize binary."""
60
+ exe = _exe_name()
61
+ env = os.environ.get("QUANTFIT_LLAMACPP")
62
+ if env and (hit := _first_match(Path(env), exe)):
63
+ return hit
64
+
65
+ bindir = _cache_dir() / f"llamacpp-bin-{LLAMACPP_TAG}"
66
+ if hit := _first_match(bindir, exe):
67
+ return hit
68
+
69
+ asset = _binary_asset()
70
+ zip_path = _cache_dir() / asset
71
+ if not zip_path.exists():
72
+ urllib.request.urlretrieve(f"{_RELEASES}/{LLAMACPP_TAG}/{asset}", zip_path)
73
+ bindir.mkdir(parents=True, exist_ok=True)
74
+ with zipfile.ZipFile(zip_path) as z:
75
+ z.extractall(bindir)
76
+ if hit := _first_match(bindir, exe):
77
+ return hit
78
+ raise RuntimeError(f"{exe} not found inside {asset}")
79
+
80
+
81
+ def convert_script() -> Path:
82
+ """Locate (env) or shallow-clone the repo's convert_hf_to_gguf.py."""
83
+ name = "convert_hf_to_gguf.py"
84
+ env = os.environ.get("QUANTFIT_LLAMACPP")
85
+ if env and (Path(env) / name).exists():
86
+ return Path(env) / name
87
+
88
+ repo = _cache_dir() / f"llama.cpp-{LLAMACPP_TAG}"
89
+ if (repo / name).exists():
90
+ return repo / name
91
+ subprocess.run(
92
+ ["git", "clone", "--depth", "1", "--branch", LLAMACPP_TAG, _REPO, str(repo)],
93
+ check=True,
94
+ )
95
+ if not (repo / name).exists():
96
+ raise RuntimeError(f"{name} missing after cloning {_REPO}@{LLAMACPP_TAG}")
97
+ return repo / name
98
+
99
+
100
+ def quantize_gguf(model_id: str, qtype: str, out_dir: str, token: str | None = None) -> Path:
101
+ """HF model -> GGUF f16 -> quantized GGUF (CPU-only)."""
102
+ from huggingface_hub import snapshot_download
103
+
104
+ out = Path(out_dir)
105
+ out.mkdir(parents=True, exist_ok=True)
106
+
107
+ quant_bin = llama_quantize_bin()
108
+ convert = convert_script()
109
+ model_dir = snapshot_download(model_id, token=token)
110
+
111
+ f16 = out / "model.f16.gguf"
112
+ final = out / f"model.{qtype}.gguf"
113
+ env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
114
+
115
+ subprocess.run(
116
+ [sys.executable, str(convert), model_dir, "--outtype", "f16", "--outfile", str(f16)],
117
+ check=True, env=env,
118
+ )
119
+ subprocess.run([str(quant_bin), str(f16), str(final), qtype], check=True, env=env)
120
+ f16.unlink(missing_ok=True) # drop the large f16 intermediate
121
+ return out