batmac commited on
Commit
8465953
·
verified ·
1 Parent(s): 4161c5c

Upload folder using huggingface_hub

Browse files
scripts/README.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Scripts
2
+
3
+ Tooling used to produce this checkpoint and the numbers in the model card. None
4
+ of it is needed to use the model.
5
+
6
+ Install the dependencies first:
7
+
8
+ ```bash
9
+ uv venv --python 3.12 .venv
10
+ uv pip install --python .venv/bin/python torch transformers bitsandbytes accelerate sentencepiece
11
+ ```
12
+
13
+ ## `quantize.py`
14
+
15
+ Rebuilds the 4-bit NF4 checkpoint from the original fp32 weights and writes a
16
+ self-contained repository (weights, tokenizer files, `.gitattributes`) that can be
17
+ uploaded directly. Optional argument: output directory, defaulting to
18
+ `../models/gradient-ai-text-detector-4bit`.
19
+
20
+ ```bash
21
+ python scripts/quantize.py
22
+ ```
23
+
24
+ It finishes by reloading the saved checkpoint and printing a P(AI) sanity value.
25
+
26
+ ## `bench_quant.py`
27
+
28
+ Compares fp32, bf16, and NF4 4-bit on CPU and Apple Silicon MPS, measuring
29
+ resident memory, batch latency, and the maximum probability change against the
30
+ fp32 reference.
31
+
32
+ ```bash
33
+ python scripts/bench_quant.py
34
+ ```
35
+
36
+ ## `eval_quant.py`
37
+
38
+ Measures how much quantization moves individual scores: max and mean absolute
39
+ change in P(AI) against fp32, and how many verdicts flip at the 0.5 threshold.
40
+
41
+ ```bash
42
+ python scripts/eval_quant.py
43
+ ```
scripts/bench_quant.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Benchmark quantization and dtype options for the AI text detector.
2
+
3
+ Compares fp32, bf16/fp16, and bitsandbytes NF4 4-bit on CPU and Apple Silicon
4
+ MPS: memory footprint, throughput, and agreement with fp32 reference
5
+ probabilities.
6
+ """
7
+
8
+ import time
9
+
10
+ import torch
11
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
12
+
13
+ MODEL_ID = "ShantanuT01/gradient-ai-text-detector"
14
+
15
+ SAMPLES = [
16
+ "In today's rapidly evolving digital landscape, organizations must leverage "
17
+ "synergistic strategies to unlock unprecedented value.",
18
+ "I went to the store yesterday and bought three apples. They were a bit "
19
+ "bruised, but the price was right and I figured they would be fine in a pie.",
20
+ "The committee reviewed the findings over several weeks and concluded that "
21
+ "no further action was warranted at this time.",
22
+ "Furthermore, it is important to note that the implementation of such "
23
+ "measures requires careful consideration of multiple stakeholders.",
24
+ ] * 2
25
+
26
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
27
+
28
+
29
+ def footprint_mb(model):
30
+ return model.get_memory_footprint() / 1024**2
31
+
32
+
33
+ def param_device(model):
34
+ for param in model.parameters():
35
+ return param.device
36
+ return torch.device("cpu")
37
+
38
+
39
+ @torch.no_grad()
40
+ def probs(model, texts):
41
+ encoded = tokenizer(
42
+ texts, return_tensors="pt", truncation=True, max_length=512, padding=True
43
+ )
44
+ device = param_device(model)
45
+ encoded = {k: v.to(device) for k, v in encoded.items()}
46
+ logits = model(**encoded).logits.squeeze(-1)
47
+ return torch.sigmoid(logits).float().cpu().tolist()
48
+
49
+
50
+ def bench(name, model, device=None, reference=None):
51
+ """Run a warm-up batch, then time a full batch of SAMPLES."""
52
+ model.eval()
53
+ moved = ""
54
+ if device is not None:
55
+ try:
56
+ model.to(device)
57
+ except Exception as exc:
58
+ moved = f" (stayed {param_device(model).type}: {type(exc).__name__})"
59
+ try:
60
+ probs(model, SAMPLES[:2])
61
+ except Exception as exc:
62
+ print(f"{name:20s} FAILED: {type(exc).__name__}: {str(exc)[:120]}")
63
+ return None
64
+ start = time.perf_counter()
65
+ values = probs(model, SAMPLES)
66
+ elapsed = time.perf_counter() - start
67
+ delta = max(abs(a - b) for a, b in zip(values, reference)) if reference else None
68
+ print(
69
+ f"{name:20s} dev {str(param_device(model)):4s} "
70
+ f"mem {footprint_mb(model):7.1f} MB "
71
+ f"{len(SAMPLES)} seqs {elapsed:6.3f}s max|dp| "
72
+ f"{'n/a' if delta is None else f'{delta:.4f}'}{moved}"
73
+ )
74
+ return values
75
+
76
+
77
+ def load(**kwargs):
78
+ kwargs.setdefault("dtype", torch.float32)
79
+ return AutoModelForSequenceClassification.from_pretrained(MODEL_ID, **kwargs)
80
+
81
+
82
+ def main():
83
+ reference = bench("fp32 cpu", load())
84
+ bench("fp32 mps", load(), torch.device("mps"), reference)
85
+
86
+ for dtype, label in [(torch.bfloat16, "bf16"), (torch.float16, "fp16")]:
87
+ bench(f"{label} mps", load(dtype=dtype), torch.device("mps"), reference)
88
+
89
+ from transformers import BitsAndBytesConfig
90
+
91
+ four_bit = BitsAndBytesConfig(
92
+ load_in_4bit=True,
93
+ bnb_4bit_quant_type="nf4",
94
+ bnb_4bit_compute_dtype=torch.float32,
95
+ )
96
+ bench("nf4 4-bit cpu", load(quantization_config=four_bit), None, reference)
97
+ bench(
98
+ "nf4 4-bit mps",
99
+ load(quantization_config=four_bit),
100
+ torch.device("mps"),
101
+ reference,
102
+ )
103
+
104
+ try:
105
+ int8 = torch.quantization.quantize_dynamic(
106
+ load(), {torch.nn.Linear}, dtype=torch.qint8
107
+ )
108
+ bench("dynamic int8 cpu", int8, None, reference)
109
+ except Exception as exc:
110
+ print(f"dynamic int8 cpu unsupported: {str(exc)[:100]}")
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()
scripts/eval_quant.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check that 4-bit NF4 quantization preserves fp32 verdicts."""
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import torch
7
+ from transformers import BitsAndBytesConfig
8
+
9
+ sys.path.insert(0, str(Path(__file__).parent))
10
+ from bench_quant import load, probs # noqa: E402
11
+
12
+ THRESHOLD = 0.5
13
+
14
+ TEXTS = [
15
+ "The quick brown fox jumps over the lazy dog, or so the saying goes.",
16
+ "In conclusion, the multifaceted nature of this phenomenon necessitates a "
17
+ "comprehensive reevaluation of our underlying assumptions.",
18
+ "My neighbour keeps parking in front of my driveway and it drives me mad.",
19
+ "I'm not sure whether I left the oven on this morning before work.",
20
+ "Consequently, stakeholders across the value chain must align their "
21
+ "incentives to foster sustainable growth trajectories.",
22
+ "We tried the new ramen place on Thursday. Broth was good, noodles okay.",
23
+ "It is crucial to note that the results underscore the importance of "
24
+ "systematic approaches to problem-solving in contemporary environments.",
25
+ "The dog barked at the postman again, and then went back to sleep on the rug.",
26
+ "By leveraging cutting-edge methodologies, we can unlock pivotal insights "
27
+ "that drive transformative outcomes for all parties involved.",
28
+ "Everything happens for a reason, and that reason is usually traffic.",
29
+ "The document outlines several key considerations that must be addressed "
30
+ "prior to implementation of the proposed framework.",
31
+ "Honestly I just want to finish this report and go home.",
32
+ "Through the lens of interdisciplinary inquiry, the discourse surrounding "
33
+ "this topic continues to evolve in ways that defy simple characterization.",
34
+ "She sold her car and bought a bike instead, which she now regrets in winter.",
35
+ "This paper presents a novel approach that seamlessly integrates the "
36
+ "strengths of prior work while mitigating its principal limitations.",
37
+ "I forgot to water the plants again and now the basil looks tragic.",
38
+ ]
39
+
40
+ if __name__ == "__main__":
41
+ fp32 = load()
42
+ reference = probs(fp32, TEXTS)
43
+ del fp32
44
+
45
+ nf4 = load(
46
+ quantization_config=BitsAndBytesConfig(
47
+ load_in_4bit=True,
48
+ bnb_4bit_quant_type="nf4",
49
+ bnb_4bit_compute_dtype=torch.float32,
50
+ )
51
+ )
52
+ nf4.to(torch.device("mps"))
53
+ quantized = probs(nf4, TEXTS)
54
+
55
+ deltas = [abs(a - b) for a, b in zip(reference, quantized)]
56
+ flips = [
57
+ (ref, got, text)
58
+ for ref, got, text in zip(reference, quantized, TEXTS)
59
+ if (ref >= THRESHOLD) != (got >= THRESHOLD)
60
+ ]
61
+ borderline = [
62
+ (ref, got) for ref, got in zip(reference, quantized) if 0.2 < ref < 0.8
63
+ ]
64
+
65
+ print(f"texts {len(TEXTS)}")
66
+ print(f"max |delta p| {max(deltas):.4f}")
67
+ print(f"mean |delta p| {sum(deltas) / len(deltas):.4f}")
68
+ print(f"verdict flips @0.5 {len(flips)}")
69
+ print(f"fp32 borderline {len(borderline)}")
70
+ for ref, got, text in flips:
71
+ print(f" {ref:.3f} -> {got:.3f} {text[:70]}")
scripts/quantize.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Save a 4-bit NF4 checkpoint of the detector for fast repeated loading.
2
+
3
+ Writes to models/gradient-ai-text-detector-4bit, which app.py picks up
4
+ automatically. The quantized checkpoint is roughly 650 MB instead of 1.7 GB.
5
+
6
+ Usage:
7
+ .venv/bin/python scripts/quantize.py [output_dir]
8
+ """
9
+
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ import torch
14
+ from transformers import (
15
+ AutoModelForSequenceClassification,
16
+ AutoTokenizer,
17
+ BitsAndBytesConfig,
18
+ )
19
+
20
+ MODEL_ID = "ShantanuT01/gradient-ai-text-detector"
21
+ DEFAULT_OUT = Path(__file__).parent.parent / "models" / "gradient-ai-text-detector-4bit"
22
+
23
+ SAMPLE = "In today's rapidly evolving digital landscape, organizations must unlock value."
24
+
25
+
26
+ def main(out_dir):
27
+ out_dir = Path(out_dir)
28
+ out_dir.mkdir(parents=True, exist_ok=True)
29
+
30
+ model = AutoModelForSequenceClassification.from_pretrained(
31
+ MODEL_ID,
32
+ quantization_config=BitsAndBytesConfig(
33
+ load_in_4bit=True,
34
+ bnb_4bit_quant_type="nf4",
35
+ bnb_4bit_compute_dtype=torch.float32,
36
+ ),
37
+ )
38
+ model.eval()
39
+ model.to(torch.device("cpu"))
40
+ model.save_pretrained(out_dir, safe_serialization=True)
41
+ AutoTokenizer.from_pretrained(MODEL_ID).save_pretrained(out_dir)
42
+ AutoTokenizer.from_pretrained(MODEL_ID, use_fast=False).save_pretrained(out_dir)
43
+ (out_dir / ".gitattributes").write_text(
44
+ "*.safetensors filter=lfs diff=lfs merge=lfs -text\n"
45
+ "*.bin filter=lfs diff=lfs merge=lfs -text\n"
46
+ "*.spm filter=lfs diff=lfs merge=lfs -text\n"
47
+ "*.model filter=lfs diff=lfs merge=lfs -text\n"
48
+ )
49
+
50
+ size_mb = sum(f.stat().st_size for f in out_dir.rglob("*") if f.is_file()) / 1024**2
51
+ print(f"saved quantized checkpoint to {out_dir} ({size_mb:,.0f} MB)")
52
+
53
+ reloaded = AutoModelForSequenceClassification.from_pretrained(out_dir)
54
+ reloaded.eval()
55
+ reloaded.to(torch.device("cpu"))
56
+ tokenizer = AutoTokenizer.from_pretrained(out_dir)
57
+ with torch.no_grad():
58
+ logits = reloaded(**tokenizer(SAMPLE, return_tensors="pt")).logits.squeeze(-1)
59
+ print(f"reload check P(AI) = {torch.sigmoid(logits).item():.4f}")
60
+
61
+
62
+ if __name__ == "__main__":
63
+ main(sys.argv[1] if len(sys.argv) > 1 else DEFAULT_OUT)