Text Classification
Transformers
Safetensors
English
deberta-v2
ai-generated-text-detection
4-bit precision
bitsandbytes
nf4
quantization
text-embeddings-inference
Run this model with HF Jobs
Run batmac/gradient-ai-text-detector-4bit on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/batmac/gradient-ai-text-detector-4bit. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/batmac/gradient-ai-text-detector-4bit on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use batmac/gradient-ai-text-detector-4bit with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use batmac/gradient-ai-text-detector-4bit with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="batmac/gradient-ai-text-detector-4bit")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("batmac/gradient-ai-text-detector-4bit") model = AutoModelForSequenceClassification.from_pretrained("batmac/gradient-ai-text-detector-4bit", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload folder using huggingface_hub
Browse filesFiles changed (4)
- scripts/README.mdAdded+43
- scripts/bench_quant.pyAdded+114
- scripts/eval_quant.pyAdded+71
- scripts/quantize.pyAdded+63
12345678910111213141516171819202122232425262728293031323334353637383940414243# Scripts
Tooling used to produce this checkpoint and the numbers in the model card. Noneof it is needed to use the model.
Install the dependencies first:
```bashuv venv --python 3.12 .venvuv pip install --python .venv/bin/python torch transformers bitsandbytes accelerate sentencepiece```
## `quantize.py`
Rebuilds the 4-bit NF4 checkpoint from the original fp32 weights and writes aself-contained repository (weights, tokenizer files, `.gitattributes`) that can beuploaded directly. Optional argument: output directory, defaulting to`../models/gradient-ai-text-detector-4bit`.
```bashpython scripts/quantize.py```
It finishes by reloading the saved checkpoint and printing a P(AI) sanity value.
## `bench_quant.py`
Compares fp32, bf16, and NF4 4-bit on CPU and Apple Silicon MPS, measuringresident memory, batch latency, and the maximum probability change against thefp32 reference.
```bashpython scripts/bench_quant.py```
## `eval_quant.py`
Measures how much quantization moves individual scores: max and mean absolutechange in P(AI) against fp32, and how many verdicts flip at the 0.5 threshold.
```bashpython scripts/eval_quant.py```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Benchmark quantization and dtype options for the AI text detector.
Compares fp32, bf16/fp16, and bitsandbytes NF4 4-bit on CPU and Apple SiliconMPS: memory footprint, throughput, and agreement with fp32 referenceprobabilities."""
import time
import torchfrom transformers import AutoModelForSequenceClassification, AutoTokenizer
MODEL_ID = "ShantanuT01/gradient-ai-text-detector"
SAMPLES = [ "In today's rapidly evolving digital landscape, organizations must leverage " "synergistic strategies to unlock unprecedented value.", "I went to the store yesterday and bought three apples. They were a bit " "bruised, but the price was right and I figured they would be fine in a pie.", "The committee reviewed the findings over several weeks and concluded that " "no further action was warranted at this time.", "Furthermore, it is important to note that the implementation of such " "measures requires careful consideration of multiple stakeholders.",] * 2
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
def footprint_mb(model): return model.get_memory_footprint() / 1024**2
def param_device(model): for param in model.parameters(): return param.device return torch.device("cpu")
@torch.no_grad()def probs(model, texts): encoded = tokenizer( texts, return_tensors="pt", truncation=True, max_length=512, padding=True ) device = param_device(model) encoded = {k: v.to(device) for k, v in encoded.items()} logits = model(**encoded).logits.squeeze(-1) return torch.sigmoid(logits).float().cpu().tolist()
def bench(name, model, device=None, reference=None): """Run a warm-up batch, then time a full batch of SAMPLES.""" model.eval() moved = "" if device is not None: try: model.to(device) except Exception as exc: moved = f" (stayed {param_device(model).type}: {type(exc).__name__})" try: probs(model, SAMPLES[:2]) except Exception as exc: print(f"{name:20s} FAILED: {type(exc).__name__}: {str(exc)[:120]}") return None start = time.perf_counter() values = probs(model, SAMPLES) elapsed = time.perf_counter() - start delta = max(abs(a - b) for a, b in zip(values, reference)) if reference else None print( f"{name:20s} dev {str(param_device(model)):4s} " f"mem {footprint_mb(model):7.1f} MB " f"{len(SAMPLES)} seqs {elapsed:6.3f}s max|dp| " f"{'n/a' if delta is None else f'{delta:.4f}'}{moved}" ) return values
def load(**kwargs): kwargs.setdefault("dtype", torch.float32) return AutoModelForSequenceClassification.from_pretrained(MODEL_ID, **kwargs)
def main(): reference = bench("fp32 cpu", load()) bench("fp32 mps", load(), torch.device("mps"), reference)
for dtype, label in [(torch.bfloat16, "bf16"), (torch.float16, "fp16")]: bench(f"{label} mps", load(dtype=dtype), torch.device("mps"), reference)
from transformers import BitsAndBytesConfig
four_bit = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float32, ) bench("nf4 4-bit cpu", load(quantization_config=four_bit), None, reference) bench( "nf4 4-bit mps", load(quantization_config=four_bit), torch.device("mps"), reference, )
try: int8 = torch.quantization.quantize_dynamic( load(), {torch.nn.Linear}, dtype=torch.qint8 ) bench("dynamic int8 cpu", int8, None, reference) except Exception as exc: print(f"dynamic int8 cpu unsupported: {str(exc)[:100]}")
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Check that 4-bit NF4 quantization preserves fp32 verdicts."""
import sysfrom pathlib import Path
import torchfrom transformers import BitsAndBytesConfig
sys.path.insert(0, str(Path(__file__).parent))from bench_quant import load, probs # noqa: E402
THRESHOLD = 0.5
TEXTS = [ "The quick brown fox jumps over the lazy dog, or so the saying goes.", "In conclusion, the multifaceted nature of this phenomenon necessitates a " "comprehensive reevaluation of our underlying assumptions.", "My neighbour keeps parking in front of my driveway and it drives me mad.", "I'm not sure whether I left the oven on this morning before work.", "Consequently, stakeholders across the value chain must align their " "incentives to foster sustainable growth trajectories.", "We tried the new ramen place on Thursday. Broth was good, noodles okay.", "It is crucial to note that the results underscore the importance of " "systematic approaches to problem-solving in contemporary environments.", "The dog barked at the postman again, and then went back to sleep on the rug.", "By leveraging cutting-edge methodologies, we can unlock pivotal insights " "that drive transformative outcomes for all parties involved.", "Everything happens for a reason, and that reason is usually traffic.", "The document outlines several key considerations that must be addressed " "prior to implementation of the proposed framework.", "Honestly I just want to finish this report and go home.", "Through the lens of interdisciplinary inquiry, the discourse surrounding " "this topic continues to evolve in ways that defy simple characterization.", "She sold her car and bought a bike instead, which she now regrets in winter.", "This paper presents a novel approach that seamlessly integrates the " "strengths of prior work while mitigating its principal limitations.", "I forgot to water the plants again and now the basil looks tragic.",]
if __name__ == "__main__": fp32 = load() reference = probs(fp32, TEXTS) del fp32
nf4 = load( quantization_config=BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float32, ) ) nf4.to(torch.device("mps")) quantized = probs(nf4, TEXTS)
deltas = [abs(a - b) for a, b in zip(reference, quantized)] flips = [ (ref, got, text) for ref, got, text in zip(reference, quantized, TEXTS) if (ref >= THRESHOLD) != (got >= THRESHOLD) ] borderline = [ (ref, got) for ref, got in zip(reference, quantized) if 0.2 < ref < 0.8 ]
print(f"texts {len(TEXTS)}") print(f"max |delta p| {max(deltas):.4f}") print(f"mean |delta p| {sum(deltas) / len(deltas):.4f}") print(f"verdict flips @0.5 {len(flips)}") print(f"fp32 borderline {len(borderline)}") for ref, got, text in flips: print(f" {ref:.3f} -> {got:.3f} {text[:70]}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""Save a 4-bit NF4 checkpoint of the detector for fast repeated loading.
Writes to models/gradient-ai-text-detector-4bit, which app.py picks upautomatically. The quantized checkpoint is roughly 650 MB instead of 1.7 GB.
Usage: .venv/bin/python scripts/quantize.py [output_dir]"""
import sysfrom pathlib import Path
import torchfrom transformers import ( AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig,)
MODEL_ID = "ShantanuT01/gradient-ai-text-detector"DEFAULT_OUT = Path(__file__).parent.parent / "models" / "gradient-ai-text-detector-4bit"
SAMPLE = "In today's rapidly evolving digital landscape, organizations must unlock value."
def main(out_dir): out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True)
model = AutoModelForSequenceClassification.from_pretrained( MODEL_ID, quantization_config=BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float32, ), ) model.eval() model.to(torch.device("cpu")) model.save_pretrained(out_dir, safe_serialization=True) AutoTokenizer.from_pretrained(MODEL_ID).save_pretrained(out_dir) AutoTokenizer.from_pretrained(MODEL_ID, use_fast=False).save_pretrained(out_dir) (out_dir / ".gitattributes").write_text( "*.safetensors filter=lfs diff=lfs merge=lfs -text\n" "*.bin filter=lfs diff=lfs merge=lfs -text\n" "*.spm filter=lfs diff=lfs merge=lfs -text\n" "*.model filter=lfs diff=lfs merge=lfs -text\n" )
size_mb = sum(f.stat().st_size for f in out_dir.rglob("*") if f.is_file()) / 1024**2 print(f"saved quantized checkpoint to {out_dir} ({size_mb:,.0f} MB)")
reloaded = AutoModelForSequenceClassification.from_pretrained(out_dir) reloaded.eval() reloaded.to(torch.device("cpu")) tokenizer = AutoTokenizer.from_pretrained(out_dir) with torch.no_grad(): logits = reloaded(**tokenizer(SAMPLE, return_tensors="pt")).logits.squeeze(-1) print(f"reload check P(AI) = {torch.sigmoid(logits).item():.4f}")
if __name__ == "__main__": main(sys.argv[1] if len(sys.argv) > 1 else DEFAULT_OUT)scripts/README.mdAdded+43
scripts/bench_quant.pyAdded+114
scripts/eval_quant.pyAdded+71
scripts/quantize.pyAdded+63