File size: 7,462 Bytes
e695de7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
import os
import shutil

import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from huggingface_hub import HfApi, create_repo
from huggingface_hub.constants import HF_HUB_CACHE

from llmcompressor import oneshot
from llmcompressor.modifiers.transform import AWQModifier
from llmcompressor.modifiers.transform.awq import AWQMapping
from llmcompressor.modifiers.quantization import QuantizationModifier


MODEL_ID = "Qwen/Qwen3-8B"


QWEN_AWQ_MAPPINGS = [
    AWQMapping(
        "re:.*input_layernorm",
        ["re:.*q_proj", "re:.*k_proj", "re:.*v_proj"],
    ),
    AWQMapping(
        "re:.*v_proj",
        ["re:.*o_proj"],
    ),
    AWQMapping(
        "re:.*post_attention_layernorm",
        ["re:.*gate_proj", "re:.*up_proj"],
    ),
    AWQMapping(
        "re:.*up_proj",
        ["re:.*down_proj"],
    ),
]


SCHEMES = {
    "fp8": "FP8_BLOCK",
    "nvfp4": "NVFP4",
    "mxfp4": "MXFP4",
    "mxfp8": "MXFP8",
}


def purge_base_cache(model_id: str):
    """Delete the downloaded base-model snapshot from the HF hub cache.

    Safe to call only after the model has been fully loaded into (GPU) memory,
    since the on-disk safetensors are no longer needed to quantize and save.
    """
    org_name = model_id.replace("/", "--")
    cache_dir = os.path.join(HF_HUB_CACHE, f"models--{org_name}")
    if os.path.isdir(cache_dir):
        print(f"Purging base-model cache: {cache_dir}")
        shutil.rmtree(cache_dir, ignore_errors=True)
    else:
        print(f"No base-model cache found at: {cache_dir}")


def load_wikitext2(num_samples: int):
    ds = load_dataset(
        "Salesforce/wikitext",
        "wikitext-2-raw-v1",
        split="train",
    )

    ds = ds.filter(lambda x: x["text"] is not None and len(x["text"].strip()) > 64)
    ds = ds.shuffle(seed=42)
    ds = ds.select(range(min(num_samples, len(ds))))

    return ds


def build_hub_repo_id(
    model_id: str,
    scheme_name: str,
    namespace: str | None = None,
    token: str | None = None,
):
    model_name = model_id.split("/")[-1]
    repo_name = f"{model_name}-{scheme_name.upper()}-AWQ-wikitext2"

    if namespace is None:
        api = HfApi(token=token)
        user_info = api.whoami(token=token)
        namespace = user_info["name"]

    return f"{namespace}/{repo_name}"


def upload_to_hub(
    local_dir: str,
    repo_id: str,
    private: bool,
    commit_message: str,
    token: str | None = None,
):
    print(f"Creating/checking HF repo: {repo_id}")

    create_repo(
        repo_id=repo_id,
        repo_type="model",
        private=private,
        exist_ok=True,
        token=token,
    )

    api = HfApi(token=token)

    print(f"Uploading local checkpoint from: {local_dir}")
    print(f"Target repo: https://huggingface.co/{repo_id}")

    api.upload_folder(
        folder_path=local_dir,
        repo_id=repo_id,
        repo_type="model",
        commit_message=commit_message,
        token=token,
    )

    print("Upload complete")


def main():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--scheme",
        choices=["fp8", "nvfp4", "mxfp4", "mxfp8"],
        required=True,
    )

    parser.add_argument("--model-id", default=MODEL_ID)
    parser.add_argument("--num-calibration-samples", type=int, default=512)
    parser.add_argument("--max-seq-length", type=int, default=2048)
    parser.add_argument("--output-dir", default=None)

    parser.add_argument(
        "--upload-to-hub",
        action="store_true",
        help="Upload saved compressed checkpoint to Hugging Face Hub",
    )

    parser.add_argument(
        "--purge-base-after-load",
        action="store_true",
        help="Delete the base-model HF cache after loading it into memory "
        "(frees disk before saving large quantized outputs).",
    )

    parser.add_argument(
        "--delete-local-after-upload",
        action="store_true",
        help="Delete the local compressed checkpoint after a successful upload.",
    )

    parser.add_argument(
        "--hub-namespace",
        default=None,
        help="HF username/org. If not passed, uses logged-in HF user.",
    )

    parser.add_argument(
        "--private",
        action="store_true",
        help="Create Hugging Face repo as private",
    )

    parser.add_argument(
        "--hf-token",
        default=None,
        help="Optional HF token. Prefer HF_TOKEN env var or huggingface-cli login.",
    )

    args = parser.parse_args()

    scheme = SCHEMES[args.scheme]

    model_name = args.model_id.split("/")[-1]
    output_dir = args.output_dir or f"{model_name}-{args.scheme.upper()}-AWQ-wikitext2"

    print(f"Loading model: {args.model_id}")

    # Shard the model across all visible GPUs (no CPU offloading). With two
    # 97GB GPUs, accelerate places different decoder layers on each device,
    # leaving ample headroom for the AWQ activation cache so we can run the
    # full-quality calibration footprint.
    model = AutoModelForCausalLM.from_pretrained(
        args.model_id,
        torch_dtype="auto",
        device_map="auto",
        trust_remote_code=True,
    )

    tokenizer = AutoTokenizer.from_pretrained(
        args.model_id,
        trust_remote_code=True,
    )

    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token

    if args.purge_base_after_load:
        purge_base_cache(args.model_id)

    print("Loading WikiText-2 calibration dataset")

    calib_ds = load_wikitext2(args.num_calibration_samples)

    recipe = [
        AWQModifier(
            mappings=QWEN_AWQ_MAPPINGS,
        ),
        QuantizationModifier(
            targets="Linear",
            scheme=scheme,
            ignore=["lm_head"],
        ),
    ]

    print(f"Running AWQ + {scheme} quantization")

    oneshot(
        model=model,
        tokenizer=tokenizer,
        dataset=calib_ds,
        recipe=recipe,
        max_seq_length=args.max_seq_length,
        num_calibration_samples=args.num_calibration_samples,
    )

    print(f"Saving compressed model locally to: {output_dir}")

    model.save_pretrained(
        output_dir,
        save_compressed=True,
    )

    tokenizer.save_pretrained(output_dir)

    if args.upload_to_hub:
        hf_token = args.hf_token or os.environ.get("HF_TOKEN")

        hub_repo_id = build_hub_repo_id(
            model_id=args.model_id,
            scheme_name=args.scheme,
            namespace=args.hub_namespace,
            token=hf_token,
        )

        upload_to_hub(
            local_dir=output_dir,
            repo_id=hub_repo_id,
            private=args.private,
            commit_message=(
                f"Upload {args.model_id} {args.scheme.upper()} "
                "AWQ compressed checkpoint calibrated on WikiText-2"
            ),
            token=hf_token,
        )

        if args.delete_local_after_upload:
            print(f"Deleting local checkpoint after upload: {output_dir}")
            shutil.rmtree(output_dir, ignore_errors=True)

    print("Done")


if __name__ == "__main__":
    main()


#python quantize_my_model.py --scheme fp8 --upload-to-hub --hub-namespace jaytonde5
#python quantize_my_model.py --scheme nvfp4 --upload-to-hub --hub-namespace jaytonde5
#python quantize_my_model.py --scheme mxfp4 --upload-to-hub --hub-namespace jaytonde5
#python quantize_my_model.py --scheme mxfp8 --upload-to-hub --hub-namespace jaytonde5