Download gpu/run.py from matthewagi/AI-Detector-35BA3B: direct link, hf CLI and curl.
- Browser
- Download file 5.21 kB
-
https://huggingface.co/matthewagi/AI-Detector-35BA3B/resolve/main/gpu/run.py
- Command line
-
hf download hf://matthewagi/AI-Detector-35BA3B/gpu/run.py
-
curl -L -o run.py https://huggingface.co/matthewagi/AI-Detector-35BA3B/resolve/main/gpu/run.py
5.21 kB
| """Read a JSONL file of texts and save logits in original document order.""" | |
| import argparse | |
| import json | |
| import os | |
| from pathlib import Path | |
| import tempfile | |
| import numpy as np | |
| ROOT = Path(__file__).absolute().parents[1] | |
| GPU = Path(__file__).absolute().parent | |
| def plan(lengths, copies, budget, limit, padded): | |
| rows, used = [], 0 | |
| for index in sorted(range(len(lengths)), key=lengths.__getitem__): | |
| size = lengths[index] * copies | |
| width = (size + 63) // 64 * 64 if padded else size | |
| if width > budget: | |
| raise ValueError( | |
| f"Document {index} requires {width} positions; budget is {budget}." | |
| ) | |
| cost = width * (len(rows) + 1) if padded else used + size | |
| if rows and (cost > budget or len(rows) == limit): | |
| yield rows | |
| rows, used = [], 0 | |
| rows.append(index) | |
| used += size | |
| if rows: | |
| yield rows | |
| def save_scores(rows, groups, score, output): | |
| offsets = np.r_[0, np.cumsum([len(row) for row in rows], dtype=np.int64)] | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| with tempfile.TemporaryDirectory(dir=output.parent) as directory: | |
| logits = np.lib.format.open_memmap( | |
| Path(directory) / "scores.npy", | |
| mode="w+", | |
| dtype=np.float32, | |
| shape=(int(offsets[-1]), 3), | |
| ) | |
| for group in groups: | |
| result = score([rows[index] for index in group]) | |
| if ( | |
| result.shape != (sum(len(rows[index]) for index in group), 3) | |
| or not np.isfinite(result).all() | |
| ): | |
| raise ValueError("Unexpected token score shape or nonfinite scores.") | |
| start = 0 | |
| for index in group: | |
| end = start + len(rows[index]) | |
| logits[offsets[index] : offsets[index + 1]] = result[start:end] | |
| start = end | |
| with (Path(directory) / "output.npz").open("wb") as f: | |
| np.savez(f, offsets=offsets, input_ids=np.concatenate(rows), logits=logits) | |
| os.replace(Path(directory) / "output.npz", output) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument( | |
| "input", type=Path, help='JSONL with one {"text": "..."} per line' | |
| ) | |
| parser.add_argument("output", type=Path, help="NumPy .npz file") | |
| parser.add_argument("--copies", choices=[1, 2], type=int, default=2) | |
| parser.add_argument( | |
| "--merged", type=Path, required=True, help="Directory produced by export.py" | |
| ) | |
| args = parser.parse_args() | |
| from transformers import AutoTokenizer | |
| tokenizer = AutoTokenizer.from_pretrained(args.merged) | |
| texts = [json.loads(line)["text"] for line in args.input.read_text().splitlines()] | |
| if not texts or any( | |
| not isinstance(text, str) or not text.strip() for text in texts | |
| ): | |
| parser.error( | |
| "Supply at least one document and a nonempty text string on every line." | |
| ) | |
| rows = tokenizer(texts, add_special_tokens=False, verbose=False)["input_ids"] | |
| if not all(rows): | |
| parser.error("A document tokenized to zero tokens.") | |
| fp8 = bool( | |
| json.loads((args.merged / "config.json").read_text()).get("quantization_config") | |
| ) | |
| profile = json.loads((GPU / "profiles.json").read_text())["h100" if fp8 else "a100"] | |
| groups = list( | |
| plan( | |
| [len(r) for r in rows], | |
| args.copies, | |
| profile["batch_tokens"], | |
| profile["max_documents"], | |
| not fp8, | |
| ) | |
| ) | |
| os.environ["VLLM_USE_V2_MODEL_RUNNER"] = "0" | |
| os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" | |
| os.environ["VLLM_PLUGINS"] = "ai_detector_35b" | |
| os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") | |
| if fp8: | |
| os.environ["VLLM_USE_DEEP_GEMM_E8M0"] = "1" | |
| else: | |
| os.environ["VLLM_TUNED_CONFIG_FOLDER"] = str(GPU / "configs") | |
| from vllm import LLM | |
| from vllm.config import KernelConfig | |
| engine = LLM( | |
| model=str(args.merged.resolve()), | |
| runner="pooling", | |
| dtype="bfloat16", | |
| moe_backend="triton", | |
| pooler_config={"task": "classify"}, | |
| max_num_batched_tokens=profile["batch_tokens"], | |
| max_num_seqs=profile["max_documents"], | |
| max_model_len=2048, | |
| gpu_memory_utilization=profile["memory_utilization"], | |
| skip_tokenizer_init=True, | |
| enforce_eager=True, | |
| enable_prefix_caching=False, | |
| enable_chunked_prefill=False, | |
| kernel_config=KernelConfig( | |
| enable_jit_warmup=False, | |
| enable_cutedsl_warmup=False, | |
| enable_flashinfer_autotune=False, | |
| ), | |
| worker_extension_cls="detector35_gpu.worker.TokenWorker", | |
| additional_config={ | |
| "gdn_prefill_backend": "triton", | |
| "clef_stateless_prefill": True, | |
| }, | |
| ) | |
| engine.collective_rpc( | |
| "initialize_detector", args=(str(ROOT), str(args.merged.resolve())) | |
| ) | |
| def score(batch): | |
| return engine.collective_rpc("score_detector", args=(batch, args.copies))[0] | |
| save_scores(rows, groups, score, args.output) | |
| if __name__ == "__main__": | |
| main() | |