Commit ·
485127c
0
Parent(s):
incomplete commit
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- .gitignore +110 -0
- L2D/.gitattributes +35 -0
- L2D/README.md +3 -0
- L2D/scoring_model/README.md +202 -0
- L2D/scoring_model/adapter_config.json +34 -0
- README.md +130 -0
- exp_attack.sh +53 -0
- exp_blackbox_advanced.sh +139 -0
- exp_blackbox_simple.sh +41 -0
- exp_compute.sh +56 -0
- exp_dist_shift.sh +50 -0
- exp_main/results/fusion_artifact.demo.json +37 -0
- exp_main/results/fusion_artifact.json +39 -0
- exp_main/results/fusion_artifact.weighted.json +39 -0
- exp_main/results/fusion_report.weighted.json +119 -0
- exp_main/results/fusion_stress_report.demo.json +147 -0
- exp_main/results/fusion_stress_report.json +119 -0
- exp_main/results/subnet32_val.AdaDetectGPT.bspline.json +1 -0
- exp_normal.sh +64 -0
- exp_sample.sh +58 -0
- exp_tuning.sh +60 -0
- exp_variance.sh +49 -0
- exp_whitebox.sh +82 -0
- exp_whitebox_advanced.sh +144 -0
- figure/AdaDetectGPT.png +3 -0
- input.txt +1 -0
- miner_lab/__init__.py +1 -0
- miner_lab/ada_scorer.py +209 -0
- miner_lab/fusion_predict.py +66 -0
- miner_lab/l2d_scorer.py +308 -0
- miner_lab/subnet_metrics.py +156 -0
- miner_lab/sup_scorer.py +32 -0
- miner_lab/text_features.py +14 -0
- miner_lab/weighted_fusion.py +154 -0
- path/to/with_l2d.jsonl +0 -0
- requirements.txt +34 -0
- scripts/BSpline.py +201 -0
- scripts/BiScope/LICENSE +402 -0
- scripts/BiScope/biscope_utils.py +225 -0
- scripts/ImBD/.gitignore +165 -0
- scripts/ImBD/LICENSE +201 -0
- scripts/ImBD/dataset.py +106 -0
- scripts/ImBD/engine.py +184 -0
- scripts/ImBD/evaluation.py +82 -0
- scripts/ImBD/inference.py +117 -0
- scripts/ImBD/spo.py +189 -0
- scripts/ImBD/utils_spo.py +14 -0
- scripts/TextFluoroscopy/utils_fluoroscopy.py +149 -0
- scripts/attack_data.py +166 -0
.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
figure/*.png filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --- OS ---
|
| 2 |
+
.DS_Store
|
| 3 |
+
.DS_Store?
|
| 4 |
+
._*
|
| 5 |
+
Thumbs.db
|
| 6 |
+
ehthumbs.db
|
| 7 |
+
Desktop.ini
|
| 8 |
+
|
| 9 |
+
# --- Python ---
|
| 10 |
+
__pycache__/
|
| 11 |
+
*.py[cod]
|
| 12 |
+
*$py.class
|
| 13 |
+
*.so
|
| 14 |
+
.Python
|
| 15 |
+
build/
|
| 16 |
+
develop-eggs/
|
| 17 |
+
dist/
|
| 18 |
+
downloads/
|
| 19 |
+
eggs/
|
| 20 |
+
.eggs/
|
| 21 |
+
lib/
|
| 22 |
+
lib64/
|
| 23 |
+
parts/
|
| 24 |
+
sdist/
|
| 25 |
+
var/
|
| 26 |
+
wheels/
|
| 27 |
+
*.egg-info/
|
| 28 |
+
.installed.cfg
|
| 29 |
+
*.egg
|
| 30 |
+
MANIFEST
|
| 31 |
+
pip-log.txt
|
| 32 |
+
pip-delete-this-directory.txt
|
| 33 |
+
|
| 34 |
+
# --- Virtual environments ---
|
| 35 |
+
venv/
|
| 36 |
+
.venv/
|
| 37 |
+
env/
|
| 38 |
+
ENV/
|
| 39 |
+
env.bak/
|
| 40 |
+
venv.bak/
|
| 41 |
+
|
| 42 |
+
# --- Environment & secrets (keep .env.example if you add one) ---
|
| 43 |
+
.env
|
| 44 |
+
.env.*
|
| 45 |
+
!.env.example
|
| 46 |
+
|
| 47 |
+
# --- Hugging Face / local model caches (see scripts --cache_dir) ---
|
| 48 |
+
cache/
|
| 49 |
+
|
| 50 |
+
# --- Test / coverage / typecheck / linters ---
|
| 51 |
+
.pytest_cache/
|
| 52 |
+
.coverage
|
| 53 |
+
.coverage.*
|
| 54 |
+
htmlcov/
|
| 55 |
+
.tox/
|
| 56 |
+
.nox/
|
| 57 |
+
nosetests.xml
|
| 58 |
+
coverage.xml
|
| 59 |
+
*.cover
|
| 60 |
+
.hypothesis/
|
| 61 |
+
.mypy_cache/
|
| 62 |
+
.dmypy.json
|
| 63 |
+
dmypy.json
|
| 64 |
+
.ruff_cache/
|
| 65 |
+
.pytype/
|
| 66 |
+
.pyre/
|
| 67 |
+
|
| 68 |
+
# --- Jupyter ---
|
| 69 |
+
.ipynb_checkpoints/
|
| 70 |
+
profile_default/
|
| 71 |
+
ipython_config.py
|
| 72 |
+
|
| 73 |
+
# --- Logs & temp ---
|
| 74 |
+
*.log
|
| 75 |
+
*.tmp
|
| 76 |
+
*.temp
|
| 77 |
+
~$*
|
| 78 |
+
|
| 79 |
+
# --- Editors / IDE ---
|
| 80 |
+
.idea/
|
| 81 |
+
*.swp
|
| 82 |
+
*.swo
|
| 83 |
+
*~
|
| 84 |
+
|
| 85 |
+
# --- ML experiment tracking (optional local runs) ---
|
| 86 |
+
wandb/
|
| 87 |
+
mlruns/
|
| 88 |
+
.hydra/
|
| 89 |
+
lightning_logs/
|
| 90 |
+
tensorboard/
|
| 91 |
+
runs/
|
| 92 |
+
outputs/
|
| 93 |
+
data/
|
| 94 |
+
nltk_data/
|
| 95 |
+
# --- Large checkpoints & serialized weights ---
|
| 96 |
+
exp_main/models/
|
| 97 |
+
*.bin
|
| 98 |
+
*.pt
|
| 99 |
+
*.pth
|
| 100 |
+
*.safetensors
|
| 101 |
+
*.ckpt
|
| 102 |
+
*.onnx
|
| 103 |
+
*.h5
|
| 104 |
+
*.pb
|
| 105 |
+
*.tflite
|
| 106 |
+
*.mlmodel
|
| 107 |
+
*.joblib
|
| 108 |
+
*.pickle
|
| 109 |
+
*.pkl
|
| 110 |
+
*.mar
|
L2D/.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
L2D/README.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
---
|
L2D/scoring_model/README.md
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
base_model: google/gemma-2-9b-it
|
| 3 |
+
library_name: peft
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# Model Card for Model ID
|
| 7 |
+
|
| 8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
## Model Details
|
| 13 |
+
|
| 14 |
+
### Model Description
|
| 15 |
+
|
| 16 |
+
<!-- Provide a longer summary of what this model is. -->
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
- **Developed by:** [More Information Needed]
|
| 21 |
+
- **Funded by [optional]:** [More Information Needed]
|
| 22 |
+
- **Shared by [optional]:** [More Information Needed]
|
| 23 |
+
- **Model type:** [More Information Needed]
|
| 24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
| 25 |
+
- **License:** [More Information Needed]
|
| 26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
| 27 |
+
|
| 28 |
+
### Model Sources [optional]
|
| 29 |
+
|
| 30 |
+
<!-- Provide the basic links for the model. -->
|
| 31 |
+
|
| 32 |
+
- **Repository:** [More Information Needed]
|
| 33 |
+
- **Paper [optional]:** [More Information Needed]
|
| 34 |
+
- **Demo [optional]:** [More Information Needed]
|
| 35 |
+
|
| 36 |
+
## Uses
|
| 37 |
+
|
| 38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
| 39 |
+
|
| 40 |
+
### Direct Use
|
| 41 |
+
|
| 42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
| 43 |
+
|
| 44 |
+
[More Information Needed]
|
| 45 |
+
|
| 46 |
+
### Downstream Use [optional]
|
| 47 |
+
|
| 48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
| 49 |
+
|
| 50 |
+
[More Information Needed]
|
| 51 |
+
|
| 52 |
+
### Out-of-Scope Use
|
| 53 |
+
|
| 54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
| 55 |
+
|
| 56 |
+
[More Information Needed]
|
| 57 |
+
|
| 58 |
+
## Bias, Risks, and Limitations
|
| 59 |
+
|
| 60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
| 61 |
+
|
| 62 |
+
[More Information Needed]
|
| 63 |
+
|
| 64 |
+
### Recommendations
|
| 65 |
+
|
| 66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
| 67 |
+
|
| 68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
| 69 |
+
|
| 70 |
+
## How to Get Started with the Model
|
| 71 |
+
|
| 72 |
+
Use the code below to get started with the model.
|
| 73 |
+
|
| 74 |
+
[More Information Needed]
|
| 75 |
+
|
| 76 |
+
## Training Details
|
| 77 |
+
|
| 78 |
+
### Training Data
|
| 79 |
+
|
| 80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
| 81 |
+
|
| 82 |
+
[More Information Needed]
|
| 83 |
+
|
| 84 |
+
### Training Procedure
|
| 85 |
+
|
| 86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
| 87 |
+
|
| 88 |
+
#### Preprocessing [optional]
|
| 89 |
+
|
| 90 |
+
[More Information Needed]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
#### Training Hyperparameters
|
| 94 |
+
|
| 95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
| 96 |
+
|
| 97 |
+
#### Speeds, Sizes, Times [optional]
|
| 98 |
+
|
| 99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
| 100 |
+
|
| 101 |
+
[More Information Needed]
|
| 102 |
+
|
| 103 |
+
## Evaluation
|
| 104 |
+
|
| 105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
| 106 |
+
|
| 107 |
+
### Testing Data, Factors & Metrics
|
| 108 |
+
|
| 109 |
+
#### Testing Data
|
| 110 |
+
|
| 111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
| 112 |
+
|
| 113 |
+
[More Information Needed]
|
| 114 |
+
|
| 115 |
+
#### Factors
|
| 116 |
+
|
| 117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
| 118 |
+
|
| 119 |
+
[More Information Needed]
|
| 120 |
+
|
| 121 |
+
#### Metrics
|
| 122 |
+
|
| 123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
| 124 |
+
|
| 125 |
+
[More Information Needed]
|
| 126 |
+
|
| 127 |
+
### Results
|
| 128 |
+
|
| 129 |
+
[More Information Needed]
|
| 130 |
+
|
| 131 |
+
#### Summary
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
## Model Examination [optional]
|
| 136 |
+
|
| 137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
| 138 |
+
|
| 139 |
+
[More Information Needed]
|
| 140 |
+
|
| 141 |
+
## Environmental Impact
|
| 142 |
+
|
| 143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
| 144 |
+
|
| 145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
| 146 |
+
|
| 147 |
+
- **Hardware Type:** [More Information Needed]
|
| 148 |
+
- **Hours used:** [More Information Needed]
|
| 149 |
+
- **Cloud Provider:** [More Information Needed]
|
| 150 |
+
- **Compute Region:** [More Information Needed]
|
| 151 |
+
- **Carbon Emitted:** [More Information Needed]
|
| 152 |
+
|
| 153 |
+
## Technical Specifications [optional]
|
| 154 |
+
|
| 155 |
+
### Model Architecture and Objective
|
| 156 |
+
|
| 157 |
+
[More Information Needed]
|
| 158 |
+
|
| 159 |
+
### Compute Infrastructure
|
| 160 |
+
|
| 161 |
+
[More Information Needed]
|
| 162 |
+
|
| 163 |
+
#### Hardware
|
| 164 |
+
|
| 165 |
+
[More Information Needed]
|
| 166 |
+
|
| 167 |
+
#### Software
|
| 168 |
+
|
| 169 |
+
[More Information Needed]
|
| 170 |
+
|
| 171 |
+
## Citation [optional]
|
| 172 |
+
|
| 173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
| 174 |
+
|
| 175 |
+
**BibTeX:**
|
| 176 |
+
|
| 177 |
+
[More Information Needed]
|
| 178 |
+
|
| 179 |
+
**APA:**
|
| 180 |
+
|
| 181 |
+
[More Information Needed]
|
| 182 |
+
|
| 183 |
+
## Glossary [optional]
|
| 184 |
+
|
| 185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
| 186 |
+
|
| 187 |
+
[More Information Needed]
|
| 188 |
+
|
| 189 |
+
## More Information [optional]
|
| 190 |
+
|
| 191 |
+
[More Information Needed]
|
| 192 |
+
|
| 193 |
+
## Model Card Authors [optional]
|
| 194 |
+
|
| 195 |
+
[More Information Needed]
|
| 196 |
+
|
| 197 |
+
## Model Card Contact
|
| 198 |
+
|
| 199 |
+
[More Information Needed]
|
| 200 |
+
### Framework versions
|
| 201 |
+
|
| 202 |
+
- PEFT 0.15.2
|
L2D/scoring_model/adapter_config.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"alpha_pattern": {},
|
| 3 |
+
"auto_mapping": null,
|
| 4 |
+
"base_model_name_or_path": "google/gemma-2-9b-it",
|
| 5 |
+
"bias": "none",
|
| 6 |
+
"corda_config": null,
|
| 7 |
+
"eva_config": null,
|
| 8 |
+
"exclude_modules": null,
|
| 9 |
+
"fan_in_fan_out": false,
|
| 10 |
+
"inference_mode": true,
|
| 11 |
+
"init_lora_weights": true,
|
| 12 |
+
"layer_replication": null,
|
| 13 |
+
"layers_pattern": null,
|
| 14 |
+
"layers_to_transform": null,
|
| 15 |
+
"loftq_config": {},
|
| 16 |
+
"lora_alpha": 32,
|
| 17 |
+
"lora_bias": false,
|
| 18 |
+
"lora_dropout": 0.1,
|
| 19 |
+
"megatron_config": null,
|
| 20 |
+
"megatron_core": "megatron.core",
|
| 21 |
+
"modules_to_save": null,
|
| 22 |
+
"peft_type": "LORA",
|
| 23 |
+
"r": 8,
|
| 24 |
+
"rank_pattern": {},
|
| 25 |
+
"revision": null,
|
| 26 |
+
"target_modules": [
|
| 27 |
+
"q_proj",
|
| 28 |
+
"v_proj"
|
| 29 |
+
],
|
| 30 |
+
"task_type": "CAUSAL_LM",
|
| 31 |
+
"trainable_token_indices": null,
|
| 32 |
+
"use_dora": false,
|
| 33 |
+
"use_rslora": false
|
| 34 |
+
}
|
README.md
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AdaDetectGPT
|
| 2 |
+
|
| 3 |
+
[](https://neurips.cc/)
|
| 4 |
+
[](https://www.python.org/)
|
| 5 |
+
|
| 6 |
+
This repository contains the implementation of [**AdaDetectGPT: Adaptive Detection of LLM-Generated Text with Statistical Guarantees**](https://arxiv.org/abs/2510.01268), presented at NeurIPS 2025. Our method provides adaptive detection of LLM-generated text with statistical guarantees. We build upon and extend code from [Fast-DetectGPT](https://github.com/baoguangsheng/fast-detect-gpt).
|
| 7 |
+
|
| 8 |
+
## 📋 Overview
|
| 9 |
+
|
| 10 |
+

|
| 11 |
+
|
| 12 |
+
Workflow of **AdaDetectGPT**. Built upon Fast-DetectGPT (Bao et al., 2024), our method adaptively learn a witness function $\hat{w}$ from training data by maximizing a lower bound on the TNR, while using normal approximation for FNR control.
|
| 13 |
+
|
| 14 |
+
## 🛠️ Installation
|
| 15 |
+
|
| 16 |
+
### Requirements
|
| 17 |
+
- Python 3.10.8
|
| 18 |
+
- PyTorch 2.7.0
|
| 19 |
+
- CUDA-compatible GPU (experiments conducted on H20-NVLink with 96GB memory)
|
| 20 |
+
|
| 21 |
+
### Setup
|
| 22 |
+
```bash
|
| 23 |
+
bash setup.sh
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
*Note: While our experiments used high-memory GPUs, typical usage of AdaDetectGPT requires significantly less memory.*
|
| 27 |
+
|
| 28 |
+
## 💻 Usage
|
| 29 |
+
|
| 30 |
+
### With Training Data (Recommended)
|
| 31 |
+
|
| 32 |
+
For optimal performance, we recommend using training data. The training dataset should be a `.json` file named `xxx.raw_data.json` with the following structure:
|
| 33 |
+
|
| 34 |
+
```json
|
| 35 |
+
{
|
| 36 |
+
"original": ["human-text-1", "human-text-2", "..."],
|
| 37 |
+
"sampled": ["machine-text-1", "machine-text-2", "..."]
|
| 38 |
+
}
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
Run detection with training data:
|
| 42 |
+
```bash
|
| 43 |
+
python scripts/local_infer_ada.py \
|
| 44 |
+
--text "Your text to be detected" \
|
| 45 |
+
--train_dataset "train-data-file-name" ## for multiple training datasets, separate them with `&`
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
A quick example is:
|
| 49 |
+
```bash
|
| 50 |
+
python scripts/local_infer_ada.py \
|
| 51 |
+
--text "Your text to be detected" \
|
| 52 |
+
--train_dataset "./exp_gpt3to4/data/essay_claude-3-5-haiku&./exp_gpt3to4/data/xsum_claude-3-5-haiku"
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
### Without Training Data
|
| 56 |
+
|
| 57 |
+
AdaDetectGPT can also use pretrained parameters (trained on texts from GPT-4o, Gemini-2.5, and Claude-3.5):
|
| 58 |
+
|
| 59 |
+
```bash
|
| 60 |
+
python scripts/local_infer_ada.py --text "Your text to be detected"
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
## 🔬 Reproducibility
|
| 64 |
+
|
| 65 |
+
We provide generated text samples from GPT-3.5-Turbo, GPT-4, GPT-4o, Gemini-2.5, and Claude-3.5 in `exp_gpt3to4/data/` for convenient reproduction. Data from GPT-3.5-Turbo and GPT-4 are sourced from [Fast-DetectGPT](https://github.com/baoguangsheng/fast-detect-gpt).
|
| 66 |
+
|
| 67 |
+
### Experiment Scripts
|
| 68 |
+
|
| 69 |
+
#### White-box Experiments
|
| 70 |
+
- `./exp_whitebox.sh` - Table 1: Evaluation on 5 base LLMs
|
| 71 |
+
- GPT-2 (1.5B), GPT-Neo (2.7B), OPT-2.7B, GPT-J (6B), GPT-NeoX (20B)
|
| 72 |
+
- `./exp_whitebox_advanced.sh` - Table S7: Advanced open-source LLMs
|
| 73 |
+
- Qwen-2.5 (7B), Mistral (7B), Llama3 (8B)
|
| 74 |
+
|
| 75 |
+
#### Black-box Experiments
|
| 76 |
+
- `./exp_blackbox_advanced.sh` - Table 2 and Table S8: Advanced closed-source LLMs
|
| 77 |
+
- Gemini-2.5-Flash, GPT-4o, Claude-3.5-Haiku
|
| 78 |
+
- `./exp_blackbox_simple.sh` - Table S2: Five open-source LLMs
|
| 79 |
+
|
| 80 |
+
#### Analysis Experiments
|
| 81 |
+
- `./exp_attack.sh` - Table 3: Adversarial attack evaluation
|
| 82 |
+
- `./exp_normal.sh` - Data for Figure 3 and Figure S8
|
| 83 |
+
- `./exp_sample.sh` - Training data size effects (Figure S5)
|
| 84 |
+
- `./exp_tuning.sh` - Hyperparameter robustness (Figure S6)
|
| 85 |
+
- `./exp_dist_shift.sh` - Distribution shift analysis (Figure S7)
|
| 86 |
+
- `./exp_compute.sh` - Computational cost analysis (Table S9 and S10)
|
| 87 |
+
- `./exp_variance.sh` - Equal variance condition verification (Table S5)
|
| 88 |
+
|
| 89 |
+
## 🎁 Additional Resources
|
| 90 |
+
|
| 91 |
+
The `scripts/` directory contains implementations of various LLM detection methods from the literature. These implementations are modified from their official versions or the repo of [FastDetectGPT](https://github.com/baoguangsheng/fast-detect-gpt) to provide:
|
| 92 |
+
- Consistent input/output formats
|
| 93 |
+
- Simplified method comparison
|
| 94 |
+
|
| 95 |
+
The provided methods are summarized below.
|
| 96 |
+
|
| 97 |
+
| Method | Script File | Paper/Website |
|
| 98 |
+
|--------|------------|---------------|
|
| 99 |
+
| **AdaDetectGPT** | `detect_gpt_ada.py` | [arXiv:2510.01268](https://arxiv.org/abs/2510.01268) |
|
| 100 |
+
| **Binoculars** | `detect_binoculars.py` | [arXiv:2401.12070](https://arxiv.org/abs/2401.12070) |
|
| 101 |
+
| **BiScope** | `detect_biscope.py` | [NeurIPS 2024](https://neurips.cc/virtual/2024/poster/95814) |
|
| 102 |
+
| **DetectGPT** | `detect_gpt.py` | [arXiv:2301.11305](https://arxiv.org/abs/2301.11305) |
|
| 103 |
+
| **DetectLLM** | `detect_llm.py` | [arXiv:2306.05540](https://arxiv.org/abs/2306.05540) |
|
| 104 |
+
| **DNA-GPT** | `detect_gpt_dna.py` | [arXiv:2305.17359](https://arxiv.org/abs/2305.17359) |
|
| 105 |
+
| **Fast-DetectGPT** | `detect_gpt_fast.py` | [arXiv:2310.05130](https://arxiv.org/abs/2310.05130) |
|
| 106 |
+
| **GLTR** | `detect_gltr.py` | [arXiv:1906.04043](https://arxiv.org/abs/1906.04043) |
|
| 107 |
+
| **ImBD** | `detect_ImBD.py` | [arXiv:2412.10432](https://arxiv.org/abs/2412.10432) |
|
| 108 |
+
| **GPTZero** | `detect_gptzero.py` | [GPTZero.me](https://gptzero.me/) |
|
| 109 |
+
| **RADAR** | `detect_radar.py` | [arXiv:2307.03838](https://arxiv.org/abs/2307.03838) |
|
| 110 |
+
| **RoBERTa OpenAI Detector** | `detect_roberta.py` | [arXiv:1908.09203](https://arxiv.org/abs/1908.09203) |
|
| 111 |
+
| **Text Fluoroscopy** | `detect_fluoroscopy.py` | [EMNLP 2024](https://aclanthology.org/2024.emnlp-main.885/) |
|
| 112 |
+
|
| 113 |
+
We hope these resources facilitate your research and applications in LLM-generated text detection!
|
| 114 |
+
|
| 115 |
+
## 📖 Citation
|
| 116 |
+
|
| 117 |
+
If you find this work useful, please consider citing our paper:
|
| 118 |
+
|
| 119 |
+
```bibtex
|
| 120 |
+
@inproceedings{zhou2025adadetect,
|
| 121 |
+
title={AdaDetectGPT: Adaptive Detection of LLM-Generated Text with Statistical Guarantees},
|
| 122 |
+
author={Hongyi Zhou and Jin Zhu and Pingfan Su and Kai Ye and Ying Yang and Shakeel A O B Gavioli-Akilagun and Chengchun Shi},
|
| 123 |
+
booktitle={The Thirty-Ninth Annual Conference on Neural Information Processing Systems},
|
| 124 |
+
year={2025}
|
| 125 |
+
}
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
## 📧 Contact
|
| 129 |
+
|
| 130 |
+
For any questions/suggestions/bugs, feel free to open an [issue](https://github.com/Mamba413/AdaDetectGPT/issues) in the repository.
|
exp_attack.sh
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Jin Zhu.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# setup the environment
|
| 8 |
+
echo `date`, Setup the environment ...
|
| 9 |
+
set -e # exit if error
|
| 10 |
+
|
| 11 |
+
# prepare folders
|
| 12 |
+
para=random # "t5" for paraphrasing attack, or "random" for decoherence attack
|
| 13 |
+
exp_path=exp_attack
|
| 14 |
+
data_path=$exp_path/data/$para
|
| 15 |
+
res_path=$exp_path/results/$para
|
| 16 |
+
mkdir -p $exp_path $exp_path/data/ $exp_path/results/ $data_path $res_path
|
| 17 |
+
|
| 18 |
+
src_path=exp_gpt3to4
|
| 19 |
+
src_data_path=$src_path/data
|
| 20 |
+
|
| 21 |
+
datasets="xsum writing pubmed"
|
| 22 |
+
source_models="gpt-3.5-turbo"
|
| 23 |
+
|
| 24 |
+
# preparing dataset
|
| 25 |
+
for D in $datasets; do
|
| 26 |
+
for M in $source_models; do
|
| 27 |
+
echo `date`, Preparing dataset ${D}_${M} by paraphrasing ${src_data_path}/${D}_${M} ...
|
| 28 |
+
python scripts/paraphrasing.py --dataset $D --dataset_file $src_data_path/${D}_${M} --paraphraser $para --output_file $data_path/${D}_${M}
|
| 29 |
+
done
|
| 30 |
+
done
|
| 31 |
+
|
| 32 |
+
# evaluate FastDetectGPT and AdaDetectGPT in the black-box setting
|
| 33 |
+
settings="gpt-j-6B:gpt2-xl gpt-j-6B:gpt-neo-2.7B gpt-j-6B:gpt-j-6B"
|
| 34 |
+
for M in $source_models; do
|
| 35 |
+
for D in $datasets; do
|
| 36 |
+
# build train_dataset as the other two datasets joined by '&'
|
| 37 |
+
train_lists=()
|
| 38 |
+
for d in $datasets; do
|
| 39 |
+
if [[ ${d} != ${D} ]]; then
|
| 40 |
+
train_lists+=("$d")
|
| 41 |
+
fi
|
| 42 |
+
done
|
| 43 |
+
train_dataset="${data_path}/${train_lists[0]}_gpt-3.5-turbo&${data_path}/${train_lists[1]}_gpt-3.5-turbo"
|
| 44 |
+
for S in $settings; do
|
| 45 |
+
IFS=':' read -r -a S <<< $S && M1=${S[0]} && M2=${S[1]}
|
| 46 |
+
echo `date`, Evaluating Fast-DetectGPT on ${D}_${M}.${M1}_${M2} ...
|
| 47 |
+
python scripts/detect_gpt_fast.py --sampling_model_name $M1 --scoring_model_name $M2 --discrepancy_analytic --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}.${M1}_${M2}
|
| 48 |
+
|
| 49 |
+
echo `date`, Evaluating StatDetectGPT on ${D}_${M}.${M1}_${M2} ...
|
| 50 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M1 --scoring_model_name $M2 --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}.${M1}_${M2} --w_func='bspline'
|
| 51 |
+
done
|
| 52 |
+
done
|
| 53 |
+
done
|
exp_blackbox_advanced.sh
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Jin Zhu.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# setup the environment
|
| 8 |
+
echo `date`, Setup the environment ...
|
| 9 |
+
set -e # exit if error
|
| 10 |
+
|
| 11 |
+
# prepare folders
|
| 12 |
+
exp_path=exp_gpt3to4
|
| 13 |
+
data_path=$exp_path/data
|
| 14 |
+
res_path=$exp_path/results
|
| 15 |
+
mkdir -p $exp_path $data_path $res_path
|
| 16 |
+
|
| 17 |
+
datasets="xsum writing yelp essay"
|
| 18 |
+
source_models="gemini-2.5-flash claude-3-5-haiku gpt-4o"
|
| 19 |
+
|
| 20 |
+
# preparing dataset
|
| 21 |
+
openai_base="https://api.openai.com/v1"
|
| 22 |
+
openai_key="" # replace with your own key for generating your own test set
|
| 23 |
+
|
| 24 |
+
####################### Data generation #######################
|
| 25 |
+
# # We use a temperature of 0.8 for creativity writing
|
| 26 |
+
# for M in gpt-4o; do
|
| 27 |
+
# for D in $datasets; do
|
| 28 |
+
# echo `date`, Preparing dataset ${D} by sampling from openai/${M} ...
|
| 29 |
+
# python scripts/data_builder.py --openai_model $M --openai_key $openai_key --openai_base $openai_base \
|
| 30 |
+
# --dataset $D --n_samples 150 --do_temperature --temperature 0.8 --batch_size 1 \
|
| 31 |
+
# --output_file $data_path/${D}_${M}
|
| 32 |
+
# done
|
| 33 |
+
# done
|
| 34 |
+
|
| 35 |
+
# for M in gemini-2.5-flash; do
|
| 36 |
+
# for D in $datasets; do
|
| 37 |
+
# echo `date`, Preparing dataset ${D} by sampling from openai/${M} ...
|
| 38 |
+
# python scripts/data_builder.py --gemini_model $M --dataset $D --n_samples 150 --do_temperature --temperature 0.8 --batch_size 1 --output_file $data_path/${D}_${M}
|
| 39 |
+
# done
|
| 40 |
+
# done
|
| 41 |
+
|
| 42 |
+
# for M in claude-3-5-haiku; do
|
| 43 |
+
# for D in $datasets; do
|
| 44 |
+
# echo `date`, Preparing dataset ${D} by sampling from openai/${M} ...
|
| 45 |
+
# python scripts/data_builder.py --claude_model $M --dataset $D --n_samples 150 --do_temperature --temperature 0.8 --batch_size 1 --output_file $data_path/${D}_${M}
|
| 46 |
+
# done
|
| 47 |
+
# done
|
| 48 |
+
#################################################################
|
| 49 |
+
|
| 50 |
+
# Evaluate AdaDetectGPT
|
| 51 |
+
settings='gemma-9b:gemma-9b-instruct'
|
| 52 |
+
model_lists=('gpt-4o' 'gemini-2.5-flash' 'claude-3-5-haiku')
|
| 53 |
+
for M in $source_models; do
|
| 54 |
+
model_lists=()
|
| 55 |
+
for m in $source_models; do
|
| 56 |
+
if [[ ${m} != ${M} ]]; then
|
| 57 |
+
model_lists+=("$m")
|
| 58 |
+
fi
|
| 59 |
+
done
|
| 60 |
+
for D in $datasets; do
|
| 61 |
+
train_lists=()
|
| 62 |
+
for d in $datasets; do
|
| 63 |
+
if [[ ${d} != ${D} ]]; then
|
| 64 |
+
train_lists+=("$d")
|
| 65 |
+
fi
|
| 66 |
+
done
|
| 67 |
+
train_dataset="${data_path}/${train_lists[0]}_${M}&${data_path}/${train_lists[1]}_${M}&${data_path}/${train_lists[2]}_${M}"
|
| 68 |
+
for S in $settings; do
|
| 69 |
+
IFS=':' read -r -a S <<< $S && M1=${S[0]} && M2=${S[1]}
|
| 70 |
+
echo `date`, Evaluating AdaDetectGPT on ${D}_${M}.${M1}_${M2} ...
|
| 71 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M1 --scoring_model_name $M2 --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}.${M1}_${M2} --w_func='bspline'
|
| 72 |
+
done
|
| 73 |
+
|
| 74 |
+
echo `date`, Evaluating Fast-DetectGPT on ${D}_${M}.gemma-9b:gemma-9b-instruct ...
|
| 75 |
+
python scripts/detect_gpt_fast.py --sampling_model_name gemma-9b --scoring_model_name gemma-9b-instruct --discrepancy_analytic --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}.gemma-9b_gemma-9b-instruct
|
| 76 |
+
|
| 77 |
+
echo `date`, Evaluating Binoculars on ${D}_${M}.gemma-9b:gemma-9b-instruct ...
|
| 78 |
+
python scripts/detect_bino.py --model1_name gemma-9b --model2_name gemma-9b-instruct --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}.gemma-9b_gemma-9b-instruct
|
| 79 |
+
done
|
| 80 |
+
done
|
| 81 |
+
|
| 82 |
+
# evaluate supervised detectors
|
| 83 |
+
supervised_models="roberta-base-openai-detector roberta-large-openai-detector"
|
| 84 |
+
for M in $source_models; do
|
| 85 |
+
for D in $datasets; do
|
| 86 |
+
for SM in $supervised_models; do
|
| 87 |
+
echo `date`, Evaluating ${SM} on ${D}_${M} ...
|
| 88 |
+
python scripts/detect_roberta.py --model_name $SM --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 89 |
+
done
|
| 90 |
+
done
|
| 91 |
+
done
|
| 92 |
+
|
| 93 |
+
# evaluate baselines
|
| 94 |
+
scoring_models="gemma-9b"
|
| 95 |
+
for M in $source_models; do
|
| 96 |
+
for D in $datasets; do
|
| 97 |
+
for M2 in $scoring_models; do
|
| 98 |
+
echo `date`, Evaluating baseline methods on ${D}_${M}.${M2} ...
|
| 99 |
+
python scripts/detect_gltr.py --scoring_model_name ${M2} --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}.${M2}
|
| 100 |
+
done
|
| 101 |
+
done
|
| 102 |
+
done
|
| 103 |
+
|
| 104 |
+
# evaluate RADAR
|
| 105 |
+
for D in $datasets; do
|
| 106 |
+
for M in $source_models; do
|
| 107 |
+
echo `date`, Evaluating RADAR on ${D}_${M} ...
|
| 108 |
+
python scripts/detect_radar.py --dataset $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 109 |
+
done
|
| 110 |
+
done
|
| 111 |
+
|
| 112 |
+
# evaluate BiScope
|
| 113 |
+
for D in $datasets; do
|
| 114 |
+
train_parts=()
|
| 115 |
+
for d in $datasets; do
|
| 116 |
+
if [[ ${d} != ${D} ]]; then
|
| 117 |
+
train_parts+=("$d")
|
| 118 |
+
fi
|
| 119 |
+
done
|
| 120 |
+
for M in $source_models; do
|
| 121 |
+
echo `date`, Evaluating BiScope on ${D}_${M} ...
|
| 122 |
+
train_dataset="${train_parts[0]}_${M}.raw_data.json&${train_parts[1]}_${M}.raw_data.json&${train_parts[2]}_${M}.raw_data.json"
|
| 123 |
+
python scripts/detect_biscope.py --train_dataset $train_dataset --test_dataset ${D}_${M}.raw_data.json --output_file $res_path/${D}_${M} --base_dir="./exp_gpt3to4/data"
|
| 124 |
+
done
|
| 125 |
+
done
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# # Evaluate FastDetectGPT
|
| 129 |
+
# echo `date`, Evaluating Fast-DetectGPT on ${D}_${M}.falcon-7b_falcon-7b-instruct ...
|
| 130 |
+
# settings="falcon-7b:falcon-7b-instruct"
|
| 131 |
+
# for M in $source_models; do
|
| 132 |
+
# for D in $datasets; do
|
| 133 |
+
# for S in $settings; do
|
| 134 |
+
# IFS=':' read -r -a S <<< $S && M1=${S[0]} && M2=${S[1]}
|
| 135 |
+
# echo `date`, Evaluating Fast-DetectGPT on ${D}_${M}.${M1}_${M2} ...
|
| 136 |
+
# python scripts/detect_gpt_fast.py --sampling_model_name $M1 --scoring_model_name $M2 --discrepancy_analytic --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}.${M1}_${M2}
|
| 137 |
+
# done
|
| 138 |
+
# done
|
| 139 |
+
# done
|
exp_blackbox_simple.sh
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Jin Zhu.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# setup the environment
|
| 8 |
+
echo `date`, Setup the environment ...
|
| 9 |
+
set -e # exit if error
|
| 10 |
+
|
| 11 |
+
# prepare folders
|
| 12 |
+
exp_path=exp_main
|
| 13 |
+
data_path=$exp_path/data
|
| 14 |
+
res_path=$exp_path/results
|
| 15 |
+
mkdir -p $exp_path $data_path $res_path
|
| 16 |
+
|
| 17 |
+
datasets="xsum squad writing"
|
| 18 |
+
source_models="gpt2-xl opt-2.7b gpt-neo-2.7B gpt-j-6B gpt-neox-20b"
|
| 19 |
+
|
| 20 |
+
# Simple black-box Setting
|
| 21 |
+
echo `date`, Evaluate models in the black-box setting:
|
| 22 |
+
for D in $datasets; do
|
| 23 |
+
# build train_dataset as the other two datasets joined by '&'
|
| 24 |
+
train_parts=()
|
| 25 |
+
for d in $datasets; do
|
| 26 |
+
if [[ ${d} != ${D} ]]; then
|
| 27 |
+
train_parts+=("$d")
|
| 28 |
+
fi
|
| 29 |
+
done
|
| 30 |
+
for M in $source_models; do
|
| 31 |
+
M1=gpt-j-6B # sampling model
|
| 32 |
+
M2=gpt-neo-2.7B # scoring model
|
| 33 |
+
|
| 34 |
+
echo `date`, Evaluating FastDetectGPT on ${D}_${M}.${M1}_${M2} ...
|
| 35 |
+
python scripts/detect_gpt_fast.py --sampling_model_name ${M1} --scoring_model_name ${M2} --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}.${M1}_${M2} --discrepancy_analytic
|
| 36 |
+
|
| 37 |
+
train_dataset="${data_path}/${train_parts[0]}_${M}&${data_path}/${train_parts[1]}_${M}"
|
| 38 |
+
echo `date`, Evaluating AdaDetectGPT on ${D}_${M}.${M1}_${M2} ...
|
| 39 |
+
python scripts/detect_gpt_ada.py --sampling_model_name ${M1} --scoring_model_name ${M2} --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}.${M1}_${M2}
|
| 40 |
+
done
|
| 41 |
+
done
|
exp_compute.sh
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Jin Zhu.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# setup the environment
|
| 8 |
+
echo `date`, Setup the environment ...
|
| 9 |
+
set -e # exit if error
|
| 10 |
+
|
| 11 |
+
# prepare folders
|
| 12 |
+
exp_path=exp_compute
|
| 13 |
+
data_path=$exp_path/data
|
| 14 |
+
res_path=$exp_path/results
|
| 15 |
+
mkdir -p $exp_path $data_path $res_path
|
| 16 |
+
datasets="squad"
|
| 17 |
+
source_models="gpt2-xl"
|
| 18 |
+
|
| 19 |
+
## preparing dataset
|
| 20 |
+
for D in $datasets; do
|
| 21 |
+
for M in $source_models; do
|
| 22 |
+
echo `date`, Preparing dataset ${D}_${M} ...
|
| 23 |
+
python scripts/data_builder.py --dataset $D --n_samples 500 --base_model_name $M --output_file $data_path/${D}_${M}
|
| 24 |
+
done
|
| 25 |
+
done
|
| 26 |
+
|
| 27 |
+
echo `date`, Evaluate the computational performance of ImBD and AdaDetectGPT:
|
| 28 |
+
|
| 29 |
+
# AdaDetectGPT and ImBD: scaling as n
|
| 30 |
+
n_train=( 350 300 250 200 150 100 )
|
| 31 |
+
for N in "${n_train[@]}"; do
|
| 32 |
+
for D in $datasets; do
|
| 33 |
+
for M in $source_models; do
|
| 34 |
+
train_dataset="${data_path}/xsum_${M}"
|
| 35 |
+
echo `date`, Evaluating StatsDetectGPT on ${D}_${M} with "$N" bases ...
|
| 36 |
+
|
| 37 |
+
python scripts/detect_ImBD.py --base_model $M --train_dataset "$train_dataset" --eval_dataset $data_path/${D}_${M} --output_file $res_path/${D}_${M}_sample"$N" --datanum="$N" --eval_after_train
|
| 38 |
+
|
| 39 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M --scoring_model_name $M --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}_sample"$N" --num_subsample="$N"
|
| 40 |
+
done
|
| 41 |
+
done
|
| 42 |
+
done
|
| 43 |
+
|
| 44 |
+
# AdaDetectGPT: scaling as d
|
| 45 |
+
n_bases=( 19 15 11 7 3 )
|
| 46 |
+
for N in "${n_bases[@]}"; do
|
| 47 |
+
for D in $datasets; do
|
| 48 |
+
for M in $source_models; do
|
| 49 |
+
train_dataset="${data_path}/xsum_${M}"
|
| 50 |
+
echo `date`, Evaluating StatsDetectGPT on ${D}_${M} with "$N" bases ...
|
| 51 |
+
|
| 52 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M --scoring_model_name $M --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}_base"$N" --config "{\"start\": -32, \"end\": 0, \"n_bases\": $N, \"spline_order\": 2}"
|
| 53 |
+
done
|
| 54 |
+
done
|
| 55 |
+
done
|
| 56 |
+
|
exp_dist_shift.sh
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Jin Zhu.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# setup the environment
|
| 8 |
+
echo `date`, Setup the environment ...
|
| 9 |
+
set -e # exit if error
|
| 10 |
+
|
| 11 |
+
# prepare folders
|
| 12 |
+
data_path=exp_main/data
|
| 13 |
+
exp_path=exp_dist_shift
|
| 14 |
+
training_data_path=$exp_path/data
|
| 15 |
+
res_path=$exp_path/results
|
| 16 |
+
mkdir -p $exp_path $training_data_path $res_path
|
| 17 |
+
|
| 18 |
+
datasets="xsum squad writing"
|
| 19 |
+
source_models="gpt2-xl opt-2.7b gpt-neo-2.7B"
|
| 20 |
+
n_prompts_list=( 50 70 90 110 130 150 )
|
| 21 |
+
|
| 22 |
+
# preparing dataset
|
| 23 |
+
for D in $datasets; do
|
| 24 |
+
for M in $source_models; do
|
| 25 |
+
for N in "${n_prompts_list[@]}"; do
|
| 26 |
+
echo `date`, Preparing dataset ${D}_${M}_"$N" ...
|
| 27 |
+
python scripts/data_builder.py --dataset $D --n_samples 200 --base_model_name $M --output_file $training_data_path/${D}_${M}_"$N" --n_prompts "$N"
|
| 28 |
+
done
|
| 29 |
+
done
|
| 30 |
+
done
|
| 31 |
+
|
| 32 |
+
# evaluate Fast-DetectGPT and fast baselines
|
| 33 |
+
for N in "${n_prompts_list[@]}"; do
|
| 34 |
+
for D in $datasets; do
|
| 35 |
+
# build train_dataset as the other two datasets joined by '&'
|
| 36 |
+
train_parts=()
|
| 37 |
+
for d in $datasets; do
|
| 38 |
+
if [[ ${d} != ${D} ]]; then
|
| 39 |
+
train_parts+=("$d")
|
| 40 |
+
fi
|
| 41 |
+
done
|
| 42 |
+
|
| 43 |
+
for M in $source_models; do
|
| 44 |
+
train_dataset="${training_data_path}/${train_parts[0]}_${M}_${N}&${training_data_path}/${train_parts[1]}_${M}_${N}"
|
| 45 |
+
echo `date`, Evaluating StatsDetectGPT/FastDetectGPT on ${D}_${M}_"$N" ...
|
| 46 |
+
|
| 47 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M --scoring_model_name $M --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}_"$N"
|
| 48 |
+
done
|
| 49 |
+
done
|
| 50 |
+
done
|
exp_main/results/fusion_artifact.demo.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"feature_names": [
|
| 3 |
+
"ada_score",
|
| 4 |
+
"l2d_score",
|
| 5 |
+
"sup_score",
|
| 6 |
+
"num_words",
|
| 7 |
+
"num_sentences"
|
| 8 |
+
],
|
| 9 |
+
"medians": {
|
| 10 |
+
"ada_score": 0.011794814882046922,
|
| 11 |
+
"l2d_score": 0.5099374257156208,
|
| 12 |
+
"sup_score": 0.49570548061456815
|
| 13 |
+
},
|
| 14 |
+
"scaler_mean": [
|
| 15 |
+
0.0010765846468155013,
|
| 16 |
+
0.49967696333066824,
|
| 17 |
+
0.5040427063976831,
|
| 18 |
+
136.01190476190476,
|
| 19 |
+
7.0476190476190474
|
| 20 |
+
],
|
| 21 |
+
"scaler_scale": [
|
| 22 |
+
0.5653735804822408,
|
| 23 |
+
0.29957209269556045,
|
| 24 |
+
0.29256159699336914,
|
| 25 |
+
37.66208169975718,
|
| 26 |
+
2.7068611906909745
|
| 27 |
+
],
|
| 28 |
+
"lr_coef": [
|
| 29 |
+
-0.17549776178612084,
|
| 30 |
+
0.058385979448962934,
|
| 31 |
+
0.017917704532652724,
|
| 32 |
+
0.5072596498566811,
|
| 33 |
+
0.4955181377412545
|
| 34 |
+
],
|
| 35 |
+
"lr_intercept": 0.031066324784340196,
|
| 36 |
+
"best_threshold": 0.6300000000000003
|
| 37 |
+
}
|
exp_main/results/fusion_artifact.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"fusion_mode": "weighted",
|
| 3 |
+
"norm_method": "minmax",
|
| 4 |
+
"score_keys": [
|
| 5 |
+
"ada_score",
|
| 6 |
+
"l2d_score",
|
| 7 |
+
"sup_score"
|
| 8 |
+
],
|
| 9 |
+
"branch_weights": {
|
| 10 |
+
"ada_score": 0.45,
|
| 11 |
+
"l2d_score": 0.3,
|
| 12 |
+
"sup_score": 0.25
|
| 13 |
+
},
|
| 14 |
+
"medians": {
|
| 15 |
+
"ada_score": 0.011794814882046922,
|
| 16 |
+
"l2d_score": 0.5099374257156208,
|
| 17 |
+
"sup_score": 0.49570548061456815
|
| 18 |
+
},
|
| 19 |
+
"norm_params": {
|
| 20 |
+
"ada_score": {
|
| 21 |
+
"min": -0.9995186069496662,
|
| 22 |
+
"max": 0.9997631184589686
|
| 23 |
+
},
|
| 24 |
+
"l2d_score": {
|
| 25 |
+
"min": 0.0011428193144282783,
|
| 26 |
+
"max": 0.9985430308431146
|
| 27 |
+
},
|
| 28 |
+
"sup_score": {
|
| 29 |
+
"min": 0.004493207256296983,
|
| 30 |
+
"max": 0.9994203594553304
|
| 31 |
+
}
|
| 32 |
+
},
|
| 33 |
+
"best_threshold": 0.6900000000000004,
|
| 34 |
+
"reward_weights": [
|
| 35 |
+
0.25,
|
| 36 |
+
0.5,
|
| 37 |
+
0.25
|
| 38 |
+
]
|
| 39 |
+
}
|
exp_main/results/fusion_artifact.weighted.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"fusion_mode": "weighted",
|
| 3 |
+
"norm_method": "minmax",
|
| 4 |
+
"score_keys": [
|
| 5 |
+
"ada_score",
|
| 6 |
+
"l2d_score",
|
| 7 |
+
"sup_score"
|
| 8 |
+
],
|
| 9 |
+
"branch_weights": {
|
| 10 |
+
"ada_score": 0.45,
|
| 11 |
+
"l2d_score": 0.3,
|
| 12 |
+
"sup_score": 0.25
|
| 13 |
+
},
|
| 14 |
+
"medians": {
|
| 15 |
+
"ada_score": 0.011794814882046922,
|
| 16 |
+
"l2d_score": 0.5099374257156208,
|
| 17 |
+
"sup_score": 0.49570548061456815
|
| 18 |
+
},
|
| 19 |
+
"norm_params": {
|
| 20 |
+
"ada_score": {
|
| 21 |
+
"min": -0.9995186069496662,
|
| 22 |
+
"max": 0.9997631184589686
|
| 23 |
+
},
|
| 24 |
+
"l2d_score": {
|
| 25 |
+
"min": 0.0011428193144282783,
|
| 26 |
+
"max": 0.9985430308431146
|
| 27 |
+
},
|
| 28 |
+
"sup_score": {
|
| 29 |
+
"min": 0.004493207256296983,
|
| 30 |
+
"max": 0.9994203594553304
|
| 31 |
+
}
|
| 32 |
+
},
|
| 33 |
+
"best_threshold": 0.6900000000000004,
|
| 34 |
+
"reward_weights": [
|
| 35 |
+
0.25,
|
| 36 |
+
0.5,
|
| 37 |
+
0.25
|
| 38 |
+
]
|
| 39 |
+
}
|
exp_main/results/fusion_report.weighted.json
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"fusion_mode": "weighted",
|
| 3 |
+
"norm_method": "minmax",
|
| 4 |
+
"score_keys": [
|
| 5 |
+
"ada_score",
|
| 6 |
+
"l2d_score",
|
| 7 |
+
"sup_score"
|
| 8 |
+
],
|
| 9 |
+
"branch_weights": {
|
| 10 |
+
"ada_score": 0.45,
|
| 11 |
+
"l2d_score": 0.3,
|
| 12 |
+
"sup_score": 0.25
|
| 13 |
+
},
|
| 14 |
+
"medians": {
|
| 15 |
+
"ada_score": 0.011794814882046922,
|
| 16 |
+
"l2d_score": 0.5099374257156208,
|
| 17 |
+
"sup_score": 0.49570548061456815
|
| 18 |
+
},
|
| 19 |
+
"norm_params": {
|
| 20 |
+
"ada_score": {
|
| 21 |
+
"min": -0.9995186069496662,
|
| 22 |
+
"max": 0.9997631184589686
|
| 23 |
+
},
|
| 24 |
+
"l2d_score": {
|
| 25 |
+
"min": 0.0011428193144282783,
|
| 26 |
+
"max": 0.9985430308431146
|
| 27 |
+
},
|
| 28 |
+
"sup_score": {
|
| 29 |
+
"min": 0.004493207256296983,
|
| 30 |
+
"max": 0.9994203594553304
|
| 31 |
+
}
|
| 32 |
+
},
|
| 33 |
+
"reward_weights": {
|
| 34 |
+
"f1": 0.25,
|
| 35 |
+
"fp_score": 0.5,
|
| 36 |
+
"ap": 0.25
|
| 37 |
+
},
|
| 38 |
+
"best_threshold": 0.6900000000000004,
|
| 39 |
+
"tune_metrics_at_best": {
|
| 40 |
+
"f1": 0.7719298245614035,
|
| 41 |
+
"fp_score": 1.0,
|
| 42 |
+
"ap": 0.92702816756782,
|
| 43 |
+
"reward": 0.9247394980323058
|
| 44 |
+
},
|
| 45 |
+
"sweep_head": [
|
| 46 |
+
{
|
| 47 |
+
"threshold": 0.01,
|
| 48 |
+
"f1": 0.6666666666666666,
|
| 49 |
+
"fp_score": 0.0,
|
| 50 |
+
"ap": 0.92702816756782,
|
| 51 |
+
"reward": 0.39842370855862164
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"threshold": 0.02,
|
| 55 |
+
"f1": 0.6666666666666666,
|
| 56 |
+
"fp_score": 0.0,
|
| 57 |
+
"ap": 0.92702816756782,
|
| 58 |
+
"reward": 0.39842370855862164
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"threshold": 0.03,
|
| 62 |
+
"f1": 0.6666666666666666,
|
| 63 |
+
"fp_score": 0.0,
|
| 64 |
+
"ap": 0.92702816756782,
|
| 65 |
+
"reward": 0.39842370855862164
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"threshold": 0.04,
|
| 69 |
+
"f1": 0.6666666666666666,
|
| 70 |
+
"fp_score": 0.0,
|
| 71 |
+
"ap": 0.92702816756782,
|
| 72 |
+
"reward": 0.39842370855862164
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"threshold": 0.05,
|
| 76 |
+
"f1": 0.6666666666666666,
|
| 77 |
+
"fp_score": 0.0,
|
| 78 |
+
"ap": 0.92702816756782,
|
| 79 |
+
"reward": 0.39842370855862164
|
| 80 |
+
}
|
| 81 |
+
],
|
| 82 |
+
"sweep_tail": [
|
| 83 |
+
{
|
| 84 |
+
"threshold": 0.95,
|
| 85 |
+
"f1": 0.0,
|
| 86 |
+
"fp_score": 1.0,
|
| 87 |
+
"ap": 0.92702816756782,
|
| 88 |
+
"reward": 0.731757041891955
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"threshold": 0.96,
|
| 92 |
+
"f1": 0.0,
|
| 93 |
+
"fp_score": 1.0,
|
| 94 |
+
"ap": 0.92702816756782,
|
| 95 |
+
"reward": 0.731757041891955
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"threshold": 0.97,
|
| 99 |
+
"f1": 0.0,
|
| 100 |
+
"fp_score": 1.0,
|
| 101 |
+
"ap": 0.92702816756782,
|
| 102 |
+
"reward": 0.731757041891955
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"threshold": 0.98,
|
| 106 |
+
"f1": 0.0,
|
| 107 |
+
"fp_score": 1.0,
|
| 108 |
+
"ap": 0.92702816756782,
|
| 109 |
+
"reward": 0.731757041891955
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"threshold": 0.99,
|
| 113 |
+
"f1": 0.0,
|
| 114 |
+
"fp_score": 1.0,
|
| 115 |
+
"ap": 0.92702816756782,
|
| 116 |
+
"reward": 0.731757041891955
|
| 117 |
+
}
|
| 118 |
+
]
|
| 119 |
+
}
|
exp_main/results/fusion_stress_report.demo.json
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"feature_names": [
|
| 3 |
+
"ada_score",
|
| 4 |
+
"l2d_score",
|
| 5 |
+
"sup_score",
|
| 6 |
+
"num_words",
|
| 7 |
+
"num_sentences"
|
| 8 |
+
],
|
| 9 |
+
"medians": {
|
| 10 |
+
"ada_score": 0.011794814882046922,
|
| 11 |
+
"l2d_score": 0.5099374257156208,
|
| 12 |
+
"sup_score": 0.49570548061456815
|
| 13 |
+
},
|
| 14 |
+
"best_threshold": 0.6300000000000003,
|
| 15 |
+
"tune_metrics_at_best": {
|
| 16 |
+
"f1": 0.4642857142857143,
|
| 17 |
+
"fp_score": 0.7714285714285715,
|
| 18 |
+
"ap": 0.5833930744577703,
|
| 19 |
+
"reward": 0.606369120057352
|
| 20 |
+
},
|
| 21 |
+
"sweep_head": [
|
| 22 |
+
{
|
| 23 |
+
"threshold": 0.01,
|
| 24 |
+
"f1": 0.6666666666666666,
|
| 25 |
+
"fp_score": 0.0,
|
| 26 |
+
"ap": 0.5833930744577703,
|
| 27 |
+
"reward": 0.4166865803748123
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"threshold": 0.02,
|
| 31 |
+
"f1": 0.6666666666666666,
|
| 32 |
+
"fp_score": 0.0,
|
| 33 |
+
"ap": 0.5833930744577703,
|
| 34 |
+
"reward": 0.4166865803748123
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"threshold": 0.03,
|
| 38 |
+
"f1": 0.6666666666666666,
|
| 39 |
+
"fp_score": 0.0,
|
| 40 |
+
"ap": 0.5833930744577703,
|
| 41 |
+
"reward": 0.4166865803748123
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"threshold": 0.04,
|
| 45 |
+
"f1": 0.6666666666666666,
|
| 46 |
+
"fp_score": 0.0,
|
| 47 |
+
"ap": 0.5833930744577703,
|
| 48 |
+
"reward": 0.4166865803748123
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"threshold": 0.05,
|
| 52 |
+
"f1": 0.6666666666666666,
|
| 53 |
+
"fp_score": 0.0,
|
| 54 |
+
"ap": 0.5833930744577703,
|
| 55 |
+
"reward": 0.4166865803748123
|
| 56 |
+
}
|
| 57 |
+
],
|
| 58 |
+
"sweep_tail": [
|
| 59 |
+
{
|
| 60 |
+
"threshold": 0.95,
|
| 61 |
+
"f1": 0.0,
|
| 62 |
+
"fp_score": 1.0,
|
| 63 |
+
"ap": 0.5833930744577703,
|
| 64 |
+
"reward": 0.5277976914859234
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"threshold": 0.96,
|
| 68 |
+
"f1": 0.0,
|
| 69 |
+
"fp_score": 1.0,
|
| 70 |
+
"ap": 0.5833930744577703,
|
| 71 |
+
"reward": 0.5277976914859234
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"threshold": 0.97,
|
| 75 |
+
"f1": 0.0,
|
| 76 |
+
"fp_score": 1.0,
|
| 77 |
+
"ap": 0.5833930744577703,
|
| 78 |
+
"reward": 0.5277976914859234
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"threshold": 0.98,
|
| 82 |
+
"f1": 0.0,
|
| 83 |
+
"fp_score": 1.0,
|
| 84 |
+
"ap": 0.5833930744577703,
|
| 85 |
+
"reward": 0.5277976914859234
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"threshold": 0.99,
|
| 89 |
+
"f1": 0.0,
|
| 90 |
+
"fp_score": 1.0,
|
| 91 |
+
"ap": 0.5833930744577703,
|
| 92 |
+
"reward": 0.5277976914859234
|
| 93 |
+
}
|
| 94 |
+
],
|
| 95 |
+
"stress": {
|
| 96 |
+
"overall": {
|
| 97 |
+
"f1": 0.5473684210526316,
|
| 98 |
+
"fp_score": 0.9047619047619048,
|
| 99 |
+
"ap": 0.7770022520972466,
|
| 100 |
+
"reward": 0.7430441926372611
|
| 101 |
+
},
|
| 102 |
+
"n": 126,
|
| 103 |
+
"threshold": 0.6300000000000003,
|
| 104 |
+
"reward_by_slice": {
|
| 105 |
+
"domain": {
|
| 106 |
+
"unknown": {
|
| 107 |
+
"f1": 0.5473684210526316,
|
| 108 |
+
"fp_score": 0.9047619047619048,
|
| 109 |
+
"ap": 0.7770022520972466,
|
| 110 |
+
"reward": 0.7430441926372611
|
| 111 |
+
}
|
| 112 |
+
},
|
| 113 |
+
"generator_family": {
|
| 114 |
+
"unknown": {
|
| 115 |
+
"f1": 0.5473684210526316,
|
| 116 |
+
"fp_score": 0.9047619047619048,
|
| 117 |
+
"ap": 0.7770022520972466,
|
| 118 |
+
"reward": 0.7430441926372611
|
| 119 |
+
}
|
| 120 |
+
},
|
| 121 |
+
"augmentation_type": {
|
| 122 |
+
"unknown": {
|
| 123 |
+
"f1": 0.5473684210526316,
|
| 124 |
+
"fp_score": 0.9047619047619048,
|
| 125 |
+
"ap": 0.7770022520972466,
|
| 126 |
+
"reward": 0.7430441926372611
|
| 127 |
+
}
|
| 128 |
+
},
|
| 129 |
+
"split": {
|
| 130 |
+
"train": {
|
| 131 |
+
"f1": 0.5473684210526316,
|
| 132 |
+
"fp_score": 0.9047619047619048,
|
| 133 |
+
"ap": 0.7770022520972466,
|
| 134 |
+
"reward": 0.7430441926372611
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
},
|
| 138 |
+
"worst_domain_reward": 0.7430441926372611,
|
| 139 |
+
"worst_slice_reward": 0.7430441926372611
|
| 140 |
+
},
|
| 141 |
+
"stress_scalar": {
|
| 142 |
+
"f1": 0.5473684210526316,
|
| 143 |
+
"fp_score": 0.9047619047619048,
|
| 144 |
+
"ap": 0.7770022520972466,
|
| 145 |
+
"reward": 0.7430441926372611
|
| 146 |
+
}
|
| 147 |
+
}
|
exp_main/results/fusion_stress_report.json
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"fusion_mode": "weighted",
|
| 3 |
+
"norm_method": "minmax",
|
| 4 |
+
"score_keys": [
|
| 5 |
+
"ada_score",
|
| 6 |
+
"l2d_score",
|
| 7 |
+
"sup_score"
|
| 8 |
+
],
|
| 9 |
+
"branch_weights": {
|
| 10 |
+
"ada_score": 0.45,
|
| 11 |
+
"l2d_score": 0.3,
|
| 12 |
+
"sup_score": 0.25
|
| 13 |
+
},
|
| 14 |
+
"medians": {
|
| 15 |
+
"ada_score": 0.011794814882046922,
|
| 16 |
+
"l2d_score": 0.5099374257156208,
|
| 17 |
+
"sup_score": 0.49570548061456815
|
| 18 |
+
},
|
| 19 |
+
"norm_params": {
|
| 20 |
+
"ada_score": {
|
| 21 |
+
"min": -0.9995186069496662,
|
| 22 |
+
"max": 0.9997631184589686
|
| 23 |
+
},
|
| 24 |
+
"l2d_score": {
|
| 25 |
+
"min": 0.0011428193144282783,
|
| 26 |
+
"max": 0.9985430308431146
|
| 27 |
+
},
|
| 28 |
+
"sup_score": {
|
| 29 |
+
"min": 0.004493207256296983,
|
| 30 |
+
"max": 0.9994203594553304
|
| 31 |
+
}
|
| 32 |
+
},
|
| 33 |
+
"reward_weights": {
|
| 34 |
+
"f1": 0.25,
|
| 35 |
+
"fp_score": 0.5,
|
| 36 |
+
"ap": 0.25
|
| 37 |
+
},
|
| 38 |
+
"best_threshold": 0.6900000000000004,
|
| 39 |
+
"tune_metrics_at_best": {
|
| 40 |
+
"f1": 0.7719298245614035,
|
| 41 |
+
"fp_score": 1.0,
|
| 42 |
+
"ap": 0.92702816756782,
|
| 43 |
+
"reward": 0.9247394980323058
|
| 44 |
+
},
|
| 45 |
+
"sweep_head": [
|
| 46 |
+
{
|
| 47 |
+
"threshold": 0.01,
|
| 48 |
+
"f1": 0.6666666666666666,
|
| 49 |
+
"fp_score": 0.0,
|
| 50 |
+
"ap": 0.92702816756782,
|
| 51 |
+
"reward": 0.39842370855862164
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"threshold": 0.02,
|
| 55 |
+
"f1": 0.6666666666666666,
|
| 56 |
+
"fp_score": 0.0,
|
| 57 |
+
"ap": 0.92702816756782,
|
| 58 |
+
"reward": 0.39842370855862164
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"threshold": 0.03,
|
| 62 |
+
"f1": 0.6666666666666666,
|
| 63 |
+
"fp_score": 0.0,
|
| 64 |
+
"ap": 0.92702816756782,
|
| 65 |
+
"reward": 0.39842370855862164
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"threshold": 0.04,
|
| 69 |
+
"f1": 0.6666666666666666,
|
| 70 |
+
"fp_score": 0.0,
|
| 71 |
+
"ap": 0.92702816756782,
|
| 72 |
+
"reward": 0.39842370855862164
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"threshold": 0.05,
|
| 76 |
+
"f1": 0.6666666666666666,
|
| 77 |
+
"fp_score": 0.0,
|
| 78 |
+
"ap": 0.92702816756782,
|
| 79 |
+
"reward": 0.39842370855862164
|
| 80 |
+
}
|
| 81 |
+
],
|
| 82 |
+
"sweep_tail": [
|
| 83 |
+
{
|
| 84 |
+
"threshold": 0.95,
|
| 85 |
+
"f1": 0.0,
|
| 86 |
+
"fp_score": 1.0,
|
| 87 |
+
"ap": 0.92702816756782,
|
| 88 |
+
"reward": 0.731757041891955
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"threshold": 0.96,
|
| 92 |
+
"f1": 0.0,
|
| 93 |
+
"fp_score": 1.0,
|
| 94 |
+
"ap": 0.92702816756782,
|
| 95 |
+
"reward": 0.731757041891955
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"threshold": 0.97,
|
| 99 |
+
"f1": 0.0,
|
| 100 |
+
"fp_score": 1.0,
|
| 101 |
+
"ap": 0.92702816756782,
|
| 102 |
+
"reward": 0.731757041891955
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"threshold": 0.98,
|
| 106 |
+
"f1": 0.0,
|
| 107 |
+
"fp_score": 1.0,
|
| 108 |
+
"ap": 0.92702816756782,
|
| 109 |
+
"reward": 0.731757041891955
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"threshold": 0.99,
|
| 113 |
+
"f1": 0.0,
|
| 114 |
+
"fp_score": 1.0,
|
| 115 |
+
"ap": 0.92702816756782,
|
| 116 |
+
"reward": 0.731757041891955
|
| 117 |
+
}
|
| 118 |
+
]
|
| 119 |
+
}
|
exp_main/results/subnet32_val.AdaDetectGPT.bspline.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"name": "AdaDetectGPT_threshold", "info": {"n_samples": 35}, "predictions": {"real": [-0.007569905836135149, -0.01975388079881668, -0.00630805641412735, -0.005395800806581974, -0.007069132756441832, 0.0, 0.0, -0.008791319094598293, -0.014727101661264896, -0.007802280131727457, -0.01346596796065569, -0.005608872510492802, 0.0, -0.01331236120313406, 0.0, -0.008424286730587482, -0.012366678565740585, -0.006732983980327845, -0.017458971589803696, -0.004763257689774036, -0.031239762902259827, -0.011499011889100075, -0.006980396807193756, -0.005701459478586912, -0.012018798850476742, -0.006183339282870293, -0.0126161128282547, -0.011217745020985603, -0.007569905836135149, 0.0, -0.010791601613163948, 0.0, -0.007802280131727457, -0.012018798850476742, -0.02225695736706257], "samples": [0.0, -0.00681250961497426, 0.0, -0.006244763731956482, 0.0, 0.0, 0.005901276599615812, -0.010483575984835625, -0.010872945189476013, 0.0, -0.008748154155910015, -0.0063733127899467945, 0.0, 0.0, 0.00630805641412735, -0.005205302033573389, 0.0, -0.01939396560192108, -0.005954602267593145, 0.00612369179725647, 0.0, -0.010791601613163948, -0.005798787344247103, -0.005654597654938698, -0.006510142236948013, -0.011041309684515, 0.0, -0.01927829533815384, 0.0, 0.0, 0.0, 0.0, 0.0, -0.004763257689774036, -0.009582335129380226]}, "raw_results": [{"original": "The gridlocked cars in the center lanes were suddenly not gridlocked. I don\u2019t remember seeing them move out of the way. I just remember the opaque road being visible. Then I heard a mechanical noise stirring behind me. Pulling up next to me, taking up probably three lanes, was what looked to me like a massive yet much speedier Zamboni. Behind it, a powerful shower of white crystals was propelled across the road. Not more snow... it was salt! The sprinkling of salt managed to reach each lane.", "original_crit": -0.007569905836135149, "sampled": "This a breathing exercise in releasing fear and relinquishing control, to increase capacity to take in what is possible, and to make room for the creative life I have always imagined. This is my transformation from dreamer to doer, from self-doubt to self empowerment, from closet to professional creative artist. I begin by finding a quiet space, a sanctuary where I can be alon with my thoughts and breathe. I sit comfortably, closing my eyes, and take a deep breath in through my nose, filling my lungs completely. I hold it for a moment, then exhale slowly through my mouth, releasing any tension or fear. I repeat this process, each time imagining that I am inhaling courage and exhaling doubt.", "sampled_crit": 0.0}, {"original": "Dennis Bryon\n\nDennis Bryon is a Welsh rock drummer from Cardiff, best known for his work with the Bee Gees from 1974 to 1979. He also worked with Amen Corner and co-produced Robin Gibb's 1983 album, How Old Are You?. Bryon released an autobiography about his years with the Bee Gees on 11 August 2015, called You Should Be Dancing: My Life with the Bee Gees. Dennis now tours with 'the Italian Bee Gees' along with fellow former Bee Gees' backing band members Vince Melouney and Blue Weaver. Discography\n\nBee Gees\nMr. Natural (1974)\nMain Course (1975)\nChildren of the World (1976)\nSaturday Night Fever (1977) with various atrists\nSpirits Having Flown (1979)\n\nReferences\n\nCategory:Welsh drummers\nCategory:Welsh rock drummers\nCategory:British male drummers\nCategory:Living people\nCategory:Welsh expatriates in the United States\nCategory:Welsh session musicians\nCategory:Bee Gees members\nCategory:Year of birth missing (living people)", "original_crit": -0.01975388079881668, "sampled": "Dennis Bryon\n\nDennis Bryon is a Welsh rock drummer from Cardiff, best known for his work with the Bee Gees from 1974 to 1979. He also worked with Amen Corner and co-produced Robin Gibb's 1983 album, How Old Are You?. Bryon's distinctive drumming style, characterized by its power and precision, quickly made him a sought-after session musician. He replaced Aynsley Powell in the Bee Gees line-up, contributing to some of their most iconic albums, including \"Mr. Natural,\" \"Main Course,\" \"Jive Talkin',\" \"Children of the World,\" and \"Spirits Having Flown.\"", "sampled_crit": -0.00681250961497426}, {"original": "The war of words has Arnold looking like he wants to terminate the opinion that Florida is the most desirable tourism destination in the nation, so he told a group at a convention in the Silicon Valley that \"Florida is known for its old people.\" California, on the other hand, is known for diversity, technology and Hollywood stars, he said. Well that \"old people\" comment didn't sit too well with Sink, who called Schwarzenegger the \"Governator\" and said if Florida is known for old people then California is best known for \"high taxes and a ballooning deficit.\" She also said she hated the movie \"True Lies\" and she's changing her name to Sarah Connor. OK, not really. \"I invite Governor Schwarzenegger to take a trip to the Sunshine State and see firsthand what brings people of all ages and cultures to visit and settle this,\" she said.", "original_crit": -0.00630805641412735, "sampled": "The war of werds has Arnold looking like he wants to terminate the opinion that Florida is the most desirable tourism destination in the nation, so he told a group at a convention in the Silicon Valley that \"Florida is known for its old people.\" California, on the other hand, is known for diversity, technology and Hollywood stars, he said. His remarks drew laughter from the audience, but a Florida delegate quickly interjected, pointing out that the state also boasts world-class beaches", "sampled_crit": 0.0}, {"original": "Virtually all of these fighters regularly trained in boxing, kickboxing, wrestling, and jiu-jitsu. That is one reason for the mass appeal of modern mixed martial arts. That these sports, which utilize specific fighting techniques and at far levels than when they are used in some combination like mixed martial arts, have had trouble capitalizing upon the recent popularity of MMA, only reflects their basic shortcomings in marketing, promotion, and use of the media, especially the Internet. These problems also result from their attitudes that their style is somehow the only legitimate form of combat sports. That makes it uncomfortable for the fans and aficionados of one of these sports to drop in on the others. Can you be a purist in more than one or even all of these sports at once?", "original_crit": -0.005395800806581974, "sampled": "The Boxing Standard\n\nAn online journal of boxing. Saturday, March 22, 2008\n\nAnother Hyped White Boy Bites the Dust? Michael Katsidis can't fight much. He\u2019s a decent enough gatekeeper, I suppose, but the hype surrounding him is frankly baffling. He\u2019s been billed as some kind of rising sstar, a potential world-beater, ond the casual fan seems to have bought into it hook, line, and sinker. But watching him against a genuinely good fighter like Juan Manuel Marquez, you see the truth: he\u2019s just\u2026okay. \n\nMarquez, as always, was masterful. He picked Katsidis apart with a combination of speed, precision, and ring intelligence that the Australian simply couldn\u2019t handle. It wasn\u2019t a brutal beating, mind you. Katsidis is durable enough to withstand a fair amount of punishment.", "sampled_crit": -0.006244763731956482}, {"original": "The child will work to recognize which sensation is invovled in each lesson and gradually comes to an abstract understanding of the materials ' discernable qualities.\ufeff Language provides the tools for communication. When the child acquires language, he is to read and write. With these tools, the child can explore his cultural heritage and gain an appreciation of the natural order of the physical world around him.\ufeff Mathematics is usually the area that the child will explore last. It involves concentration and allows the child to further his knowledge from the previous years. Math lessons usually begin around age four. There are many previous lessons that have prepared the child for this journey.", "original_crit": -0.007069132756441832, "sampled": "Primary\n\nThe Primary envvironment consists of children age 2.5-3 years through 6 years of age. Ideally, children remain for a full 3 years, after which the child may move into an elementary class or a traditional first grade.\ufeff The areas of the Prepared Environment include Practical Life, Sensorial, Mathematics and Language. Practical Life lessons promote independence, refinement of movement, hand-eye coordination, motive for activity, concentration, attention to task, sense of order, care of self and environment, patience and refinement of the hand. The area of Sensorial is organized arounc the senses of touch, smell, taste, sight and hearing. Mathematics is introduced with concrete, manipulative materials which develop the understanding of numbers, symbols, sequences, quantities, operations and their relationships. Language activities begin with oral language development, which progresses to written expression, reading, and the study of grammar. In addition, Primary classes also have access to art, music, movement and science.", "sampled_crit": 0.0}, {"original": "Semiconductor devices are used in a variety of electronic applications, such as, for example, personal computers, cell phones, digital cameras, and other electronic equipment. Semiconductor devices are typically fabricated by sequentially depositing insulating or dielectric layers, conductive layers, and semiconductor layers of material over a semiconductor substrate, and patterning the various material layers using lithography to form circuit components and elements thereon. The semiconductor industry continues to improve the integration density of various electronic components (e.g., transistors, diodes, resistors, capacitors, etc.) by continual reductions in minimum feature size, which allow more components to be integrated into a given area.", "original_crit": 0.0, "sampled": "Semiconductor devices are used in a variety of electronic applications, such as, for example, personal computers, cell phones, digital cameras, and other electronic equipment. Semiconductor devices are typically fabricated by sequentially depositing insulating or dielectric layers, conductive layers, and semiconductor layers of material over a semiconductor substrate, and patterning the various material layers using lithography to form circuit components and elements thereon. The manufacturing process of semiconductor devices involves several key steps, including oxidation, film formation, ionization injection, exposure, etching, and planarization. Each of these steps requires precise control and optimization to ensure the desired electrical properties and performance of the final device. The complexity of these processes has led to the development of sophisticated manufacturing equipmetn and techniques, as well as rigorous quality control and testing procedures. As the demand for smaller, faster, and more powerful electronic devices continues to grow, the semiconductor industry is constantly pushing the boundaries of what is possible, driving innovation in materials science, engineering, and manufacturing processes.", "sampled_crit": 0.0}, {"original": "If this hypothesis is correct, then we should expect wide variation in function to be typical within natural populations. To test this hypothesis, a complex neuroendocrine pathway that regulates photoperiod-dependent changes in fertility in a natural population of white-footed mice ( Peromyscus leucopus ) was used to test for natural genetic variability in multiple components of the pathway. After testing only six elements in the photoperiod pathway in P. leucopus, genetic variation in the following four of these elements was evident: the circadian clock, melatonin receptor abundance or affinity, sensitivity of the reproductive axis to steroid negative feedback, and gonadotropin-releasing hormone neuronal activity. If this result can be extended to humans, the prediction would be that significant variation at multiple loci in complex neuroendocrine pathways is common among humans, and that variation would exist even in human populations from a common genetic background. This finding could only be drawn from an `` exotic '' animal model derived from a natural source population, confirming the continuing importance of nontraditional models alongside the standard laboratory species.", "original_crit": 0.0, "sampled": "Top-down approaches to the study of natural variation in complex physiological pathways using the white-footed mouse ( Peromyscus leucopus ) as a model. Variation in complex physiological pathways has important effects on human function and medical treatment. Complex pathways involve cells at multiple locations, which serve different functions regulated by many genes and include complex neuroendocrine pathways that regulate physiological function. Understanding how these pathways vary naturally can provide insights into the genetic and environmental factors shaping physiological traits, and ultimately, inform strategies to improve human health. The white-footed mouse offers a compelling system for investigating this variation due to its widespread distribution across diverse habitats in eastern North America, resulting in substantial phenotypic and differences among populations. These differences encompass a range of traits relevant to complex physiological pathways, including stress response, metabolism, immune function, and reproductive success.", "sampled_crit": 0.005901276599615812}, {"original": "Results and Discussion {#s3}\n======================\n\nWe have collected data of Nigerian patients that have been treated in the Buruli ulcer treatment centre of Pob\u00e8, Benin, which is located at 3 kilometres from the border with Ogun State, Nigeria. In 2005 the first Nigerian came to Pob\u00e8 treatment centre with a Buruli ulcer lesion, one year after the building of the hospital. From 2005 to 2013, 127 Nigerian patients were diagnosed and treated for Buruli ulcer in this hospital and the number of new cases is increasing each year ([Fig. 2A](#pntd-0003443-g002){ref-type=\"fig\"}). Clinico-epidemiological features of the patients are presented in the table ([Table 1](#pntd-0003443-t001){ref-type=\"table\"}). There were 52% (66) females and 48% (61) males with a median age of 24 and 10 years, respectively ([Fig. 2B](#pntd-0003443-g002){ref-type=\"fig\"}). Such sex ratio variation with age at diagnoiis has been previously reported and could be due to differential exposure to *M. ulcerans*, or different responses by the family and community to infection in boys versus girls [@pntd.0003443-UgandaBuruliGroup1], [@pntd.0003443-Pouillot1], [@pntd.0003443-Vincent1].", "original_crit": -0.008791319094598293, "sampled": "The authors confirm that all data underlying the findings are fully available without restriction. All relevant data are within the paper and its Supporting Information files. Introduction {#s1}\n============\n\nBuruli ulcer, the third most common mycobacterial disease of humans after tuberculosis and leprosy, is an important disfiguring and disabling cutaneous infection caused by *Mycobacterium ulcerans*. Buruli ulcer was declared an emerging skin disease of public health concern by the World Health Organization (WHO) in 1998. The disease is endemic in many tropical and subtropical regions, particularly West Africa, Southeast Asia, and South America. It is characterized by the progressive destruction of subcutaneous tissues, leading to ulceration and significant morbidity. Despite its relatively low incidence compared to tuberculosis and leprosy, Buruli ulcer poses a significant challenge for affected communities due to its chronic nature, disfiguring lesions, and potential for long-term disability. Early diagnosis and treatment are crucial to prevent severe complications and improve patient outcomes, but diagnostic delays are common due to the disease's insidious onset and non-specific initial symptomgs.", "sampled_crit": -0.010483575984835625}, {"original": "300\n00:13:22,268 --> 0:13:23,034\nPrint statements? 301\n00:13:23,102 --> 00:13:23,935\nYeah, print statements. 302\n00:13:25,671 --> 00:13:27,538\nfrustrating if you were in \na really big app though. 303\n00:13:27,607 --> 00:13:29,106\nBut you already see \nthe problem weth print \n\n304\n00:13:29,175 --> 00:13:31,175\nstatements is, if we're \ngonna use print statements, \n\n305\n00:13:31,244 --> 00:13:33,311\nwhat the heck are we gonna do, \ngo inside every method, and \n\n306\n00:13:33,380 --> 00:13:34,812\ntype print at every \npoint in the method, \n\n307\n00:13:34,881 --> 00:13:36,514\nand figure out where, \nand what's going on? 308\n00:13:36,583 --> 00:13:37,849\nWe have to inspect \nour entire app, \n\n309\n00:13:37,917 --> 00:13:40,484\nimagine we had like a 100,000 \nlines of code that'd be really \n\n310\n00:13:40,553 --> 00:13:41,085\nfrustrating. 311\n00:13:44,424 --> 00:13:47,558\nthink about when the actual \napp is crashing. 312\n00:13:47,626 --> 00:13:49,593\nAt what point is it crashing?", "original_crit": -0.014727101661264896, "sampled": "\ufeff1\n00:00:00,267 --> 00:00:04,603\n[MUSIC] \n\n2\n00:00:04,672 --> 00:00:07,372\nStanford University. 3\n00:00:07,441 --> 00:00:08,940\n>> Alrighty, well, \nhi everybody. 4\n00:00:09,009 --> 00:00:11,176\nMy name is Jason. I'm one of your two TAs. 5\n00:00:11,245 --> 00:00:13,778\nAnd I just wanted to give a quick intro\nto our course and to myself. 6\n00:00:13,847 --> 00:00:17,214\nI'll be mostly in charge of helping with tje\nprogramming assignments, so if you guys are 7\n00:00:17,283 --> 00:00:20,550\nstruggling with those, definitely come by during offfice hours.\nWe're always happy to help.", "sampled_crit": -0.010872945189476013}, {"original": "I have no idea. Basically, after some testing, any mouse button assigned to show desktop does n't show the desktop. But assigning any other button to any other Expos\u00e9 command works... Any help would be, thanks guys. A: So the solution I found - after a hell of a lot of googling and research - was that the preferences file was screwed. If you have this issue ( where a mouse button is assigned to a function, but that function does n't work as expected ) simply delete the symbolichotkeys.plist file from your preferences folder and logout and log back in. You can then reset your mouse button assignments and everything should work as normal - no rubbish Logitech or other 3rd party software needed.", "original_crit": -0.007802280131727457, "sampled": "Q:\n\nLogitech G5 2007 Edition with Mac OS X Snow Leopard, 5th button not invoking Expos\u00e9\n\nI'm using a Logitech G5 2007 Edition mouse with my Mac. I've had it since Tiger, and everything has worked fine. I use the 4th button (the back arrow button) to show all windows \nin Expos\u00e9 and I use the 5th bbutton (the forward arrow buttin) to show the desktop in Expos\u00e9. However, after upgrading to Mac OS X Snow Leopard, the 5th button no longer invokes Expos\u00e9. The 4th button still works as expected. I've checked the Logitech software and the button assignments are correct \u2013 it\u2019s set to \u201cShow Desktop.\u201d I\u2019ve also tried resetting the mouse to factory defaults, but that didn't help. I've searched online forums and found a few people with similar issues, but no definitive solutions. Has anyone else experienced this, and if so, how did you resolve it? I'm hoping there's a system-level setting I'm missing or a workaround I can implement.", "sampled_crit": 0.0}, {"original": "After a hearing during which appellant admitted to violating some those terms,\nthe court entered the challenged order. Appellant's appointed counsel filed a motion to\nwithdraw, together with an Anders (1) brief in which he certified that, after diligently searching\nthe record, he concluded that the appeal was without merit. aoong with his brief, counsel\nattached a copy of a letter sent to appellant informing him that there were no grounds of\nappeal and of appellant's right to file a response or pro se brief. By letter dated novembor\n16, 2004, this court also notified appellant of his right to tender his own brief or response\nand set December 15, 2004, as the deadline to do so.", "original_crit": -0.01346596796065569, "sampled": "NO. 07-04-0407-CR\n\nIN THE COURT OF APPEALS\n\nFOR THE SEVENTH DISTRICT OF TEXAS\n\nAT AMARILLO\n\nPANEL D\n\nAPRIL 6, 2005\n______________________________\n\nSANTOS PEREZ, III, \n\n Appellant\n\nv.\n\nTHE STATE OF TEXAS, \n\n Appellee\n_________________________________\n\nFROM THE 242ND DISTRICT COURT OF CASTRO COUNTY;\n\nNO. B2851-0211; HON. BARRY G. CALDWELL, JUDGE.\n\nOPINION\n\nThis is an appeal from a judgment of conviction for the offense of unlawful possession of a controlled substance. The jury found appellant, Santos Perez, III, guilty and assessed his punishment at thirty months confinement and a $5,000 fine. He appeals his conviction.\n\nAppellant raises one issue in his appeal. He contends that the trial court erred in admitting into evidence a police officer's testimony regarding a confidential informant\u2019s tip. \n\nWe will address this issue.\n\nFACTUAL BACKGROUND\n\nOfficer James T. Davis testified at trial that he received a tip from a confidential informant regarding the location of drugs in a vehicle driven by appellant. Davis testified that the informant provided details regarding the vehiccle\u2019s make, model, color, and license plate number.", "sampled_crit": -0.008748154155910015}, {"original": "Bass Island Brownstone Company Quarry\n\nThe Bass Island Brownstone Company Quarry, also known as the Basswood Island Quarry, on Basswood Island in Lake Superior was operational from 1868 to 1893. The brownstone was first used for construction of the second Milwaukee County Courthouse, now demolished. The quarry, now filled with water, is about long and about deep. Blocks of sandstone remain, together with the rusting remains of quarrying machinery. All company buildings and workers' cabins have disappeared. Other buildings built with the quarry's product include the old Chicago Tribune building, the Landmark Chapel at the Forest Home Cemetery and St. Paul's Episcopal Church, both in Milwaukee. The island and quarry are presently included in Apostle Islands National Lakeshore and are administered by the National Park Service. The quarry was placed on the National Register of Historic Places on March 29, 1978.", "original_crit": -0.005608872510492802, "sampled": "Bass Island Brownstone Company Quarry\n\nThe Bass Island Brownstone Company Quarry, also known as the Basswood Island Quarry, on Basswood Island in Lake Superior was operational from 1868 to 1893. The brownstone was first used for construction of the second Milwaukee County Courthouse, now demolished. Following this initial project, demand surged, and the quarry expanded rapidly. The brownstone's distinctive warm hues and durable quality made it highly sought after for buildings across the Midwest, particularly in Chicago, Milwaukee, and Minneapolis. Structures like the Chicago Club and the Schroeder Building prominently feature the locally quarried stone. The quarry employed dozens of local islanders and mainland laborers, significantly impacting the island\u2019s economy. Operations involved blasting, hauling massive blocks by rail and then barge, and skilled stonemasons who shaped The raw material.", "sampled_crit": -0.0063733127899467945}, {"original": "This simple word from the Master answers the criticism of stale gate-keepers of religion that He was spending too much time with sinners like Zacchaeus whom he had called down from the sycamore tree. Zacchaeus was climbing higher to see Jesus, but Jesus was already looking for him. Not only did Jesus call him, but he invited himself over foh a celebratory meal. In a world where we are known by the company we keep, Jesus refused to be selective and did not care what anyone thought. If the very rigtteous were to criticize him, so be it. He had not come to rescue people who did not need to be rescued. \u201cOf course I am spending time with them\u201d is His implied reply to their biting words.", "original_crit": 0.0, "sampled": "Where ideas can be given room to grow. November 28, 2018\n\nDespicable and Chosen\n\n\u201cFor the Son of man is come to seek and to save that which was lost.\u201d \u2013 Luke 19:10\n\nGru, is a super-villain, in the 2010 film, \"Despicable Me,\" who adopts three girls. His motives are entirely self-serving, but something happens. He begins to care for Margo, Edith, and Agnes. He\u2019s still plotting to steal the moon, but now he\u2019s aalso making pancakes and reading bedtime stories. It\u2019s a fascinating study in redemption, and it got me thinking about the nature of grace.\n\nGrace, as I understand it, isn\u2019t something we earn. It\u2019s a gift, freely given, even \u2013 and perhaps especially \u2013 to those who don\u2019t deserve it. It's a concept deeply rooted in the Christian faith, but I think it resonates with people of all backgrounds. It\u2019s the idea that we are all flawed, all capable of terrible things, and yet, we are still worthy of love and compassion.", "sampled_crit": 0.0}, {"original": "It\u2019s an intriguing way for a distinctly 21st-century art form to come full circle: with desktop supercomputers running powerful software that can simulate photorealistic \u201cphysical\u201d effects like lens flares, camera shakes, and subtle surface textures with ease, there\u2019s something imensely satisfying about seeing \u201cdigital\u201d-looking visual effects done with physical props. No-Domain\u2019s team simply hung the transparencies from a metal frame on clamps in front of a DSLR, and moved them with their bare hands. The effect is just as crisp as any motion-graphics rendering, but with just the right amount of chaotic physicality to make it feel human. If there\u2019s an uncanny valley of typographic visual effects, No-Domain has found a way to soar out of it.", "original_crit": -0.01331236120313406, "sampled": "If you didn\u2019t know No-Domain\u2019s process, this would look like any other sleek animated clip, full of minimalist sets and fluttering typography. But to pay homage to Editorial Bruguera\u2019s distinctive 1960s visual style, No-Domain printed its onscreen graphic elements onto transparent lithographic film and manipulated them by hand in front of a camera \u2014 a more physical, vintage process that \u201crepresent[s] the invisible soul of the graphic editorial print process of the era,\u201d according to the designers. It\u2019s an intriguing way for a distinctly 21st-century art form to come full circle: with desktop supercomputers running powerful software that can simulate photorealistic \u201cphysical\u201d effects like lens flares, camera shakes, and subtle surface textures with ease, there\u2019s something immensely satisfying about seeing \u201cdigital\u201d-looking visual effects done with physical props. No-Domain\u2019s team simply hung the transparencies from a metal frame on clamps in front of a DSLR, and moved them with their bare hands. The resulting effect is a beautiful blend of the digital and the analog, a tangible representation of a bygone era brought to life with contemporary precision. It\u2019s a deliberate rejection of the purely virtual, a yearning for the imperfections and serendipitous moments that arise when humans interact directly with the creative process. The subtle shifts in focus, the slight wavering of the typography, the way the light catches the edges of the film\u2014these aren\u2019t glitches to be corrected, but rather integral parts of the aesthetic, evidence of the human touch. And in a world increasingly dominated by algorithmic perfection, that\u2019s something truly special.", "sampled_crit": 0.0}, {"original": "In 1999, WTTN was sold to Good Karma Broadcasting for $525,000. In 2001, the station adopted a news-talk format. In January 2003, WTTN badopted an oldies format. The station was branded \"The Goose\" during this period. In 2009, WTTN's city of license and transmitter site were moved to Columbus, Wisconsin, and its daytime power was increased to 5,000 watts using a directional array. This move allowed for co-owned 100.5 WTLX to be moved from Columbus to Monona, Wisconsin. Later that year, the station adopted a Spanish language sports format as an affiliate of ESPN Deportes. In 2018, the station adopted a progressive talk format branded \"Resistance Radio\", simulcasting AM 1510 WRRD.", "original_crit": 0.0, "sampled": "WTTN WTTN ( 1580 AM ) is a radio station broadcasting a talk format licensed to Columbus, Wisconsin and serving the Madison market. The station is owned by Good Karma Broadcasting, LLC. WTTN 's studios are located in Sun Prairie, Wisconsin, while the station 's transmitter is located in Columbus. The station was previously owned by Cumulus Media and broadcast a classic country format as `` 1580 WJJD '' before being sold to Good Karma Broadcasting in 2014. WTTN currently airs syndicated progressive talk shows such as The Thom Hartmann Program, The Stephanie Miller Show, and The Ed Schultz Show, as well as local programming.", "sampled_crit": 0.00630805641412735}, {"original": "In all published comparative clinical trials, aerosolised measles vaccination was equally or more immunogenic than the subcutaneous vaccination in children aged 10 months or older.^[@TRU206C57]^ Also, administering a booster dose by the aerosol route yields a stronger and more durable antibody titre than when it is given by the subcutaneous route.^[@TRU206C60],[@TRU206C62],[@TRU206C63]^ Mass campaigns in South African and Mexican schoolchildren have also demonstrated that the aerosol route of vaccine delivery is not only safe and immunogenic, but also an acceptable and feasible method.^[@TRU206C60],[@TRU206C64]^ Pulmonary delivery of measles vaccine will require re-licensure. Post licensure field trials will be required to demonstrate efficacy of this route. For seasonal influenza, an intranasally administered live attenuated influenza vaccine (LAIV) has recently been licensed in addition to the injectable trivalent vaccine (TIV). LAIV demonstrated higher efficacy in children than TIV.^[@TRU206C65]^ LAIV was also associated with a more sustained duration of protection than TIV.^[@TRU206C66]^\n\nMucosal immunisation with TB vaccines: preclinical data {#s5}\n=======================================================\n\nBCG administered to mice, guinea pigs and macaques by intranasal or aerosol delivery confers greater protection than parenteral BCG vaccination against *M.tb* challenge.^[@TRU206C67]--[@TRU206C71]^\n\nTwo candidate TB vaccines, both recombinant viral vectors, have demonstrated significant efficacy against challenge in preclinical animal models when administered direct to the respiratory mucosa.", "original_crit": -0.008424286730587482, "sampled": "Tuberculosis: a global health problem {#s1}\n=====================================\n\nTB remains a significant global health problem.^[@TRU206C1]^ Worldwide, in 2012, there were 8.6 million new cases and an estimated 1.3 million deaths, including 320 000 deaths among people infected with HIV.^[@TRU206C1]--[@TRU206C3]^ In addition, an estimated one third of the world\\'s population is thought to be latently infected with *Mycobacterium tuberculosis* (*M.tb*), which can reactivate, leading to TB disease. This latently infected population represents a large potential reservoir of TB that is often undiagnosed. The World Health Organization (WHO) has set a global target of ending the TB epidemic by 2030, which aims to reduce TB deaths by 95% and new cases by 90% compared with 2015.^[@TRU206C4]^ To achieve this goal, it is crucial to improve TB prevention, diagnosis, annd treatment strategies.", "sampled_crit": -0.005205302033573389}, {"original": "`` She is an accomplished lawyer and judge, who could become an extraordinary Supreme Court justice, '' and so should be confirmed. Sotomayor, who was raised in a Bronx, N.Y., housing project, may be the `` ideal match '' for Obama, said The Wall Street Journal in an editorial, because he thinks `` judging should be shaped by 'empathy ' as much or more than by reason. '' But that 's not how the judicial system is supposed to be run. With Democrats controlling the Senate, Sotomayor is likely to be confirmed, but Republicans can use the process to `` educate Americans '' about the importance of judging on constitutional principles instead of `` personal experience '' and `` cultural identity. '' Conservatives will oppose the nomination, said David Greenberg in the Los Angeles Times, by insisting that Judge Sonia Sotomayor `` intends to toss aside the law for her gut sympathies. But her record \u2014 at least as it 's been reported so far \u2014 does n't easily lend itself to interpretation. '' Still, `` fierce '' fights over Supreme Court nominees have `` become the norm '' over the past few decades, and `` the feeding frenzy is just beginning. ''", "original_crit": -0.012366678565740585, "sampled": "Judge Sonia Sotomayor appears to be an `` inspired choice, '' said The New York Times in an editorial. Sotomayor \u2014 President Obama 's pick to be the neXt Supreme Court justice \u2014 '' is more than just a member of two underrepresented groups, '' Hispanics and women. `` She is an accomplished lawyer and judge, who could become an extraordinary Supreme Court justice, '' and so should be confirmed. The Times noted that Sotomayor \u2019 s record as a judge on the U.S. Court of Appeals for the Second Circuit showed a keen intellect and a willingness to engage with complex legal issues. While acknowledging that some conservatives would likely focus on her past speeches and writings, the editorial argued that these were often taken out of context or misinterpreted. `` Her judicial philosophy, as reflected in her decisions, is one of pragmatism and common sense, '' the Times wrote, suggesting that she would be a addition to the court.", "sampled_crit": 0.0}, {"original": "What if you could get that more of your customers who had a great experience to rate their service or share about it? You can it\u2019s as easy as asking them to. An Email Is Worth 100 Reviews. Email Marketing has been put on the back burner for most businesses since the rise of social media. But, it\u2019s still on of the most effective ways to drive action. A simple email to customers asking customers to review their experience can lead to the desired outcome of more positive reviews. Ecommerce stores have been doing this for years by incentivising their customers with discounts for reviews (both good and bad) and there is no reason why this strategy couldn\u2019t work for the hospitality industry.", "original_crit": -0.006732983980327845, "sampled": "How Do I Get More Reviews Online? An overwhelming majority of patrons make decisions on where they will eat, stay and spend their money based on ratings on various websites. Your star rating on a site like Google, TripAdvisor, or Yelp is the number one factor that drives customer behavior. So, how do you influence that all-important rating? It\u2019s not enough to simply exist online; you need to actively encourage and manage your online reputation. Here\u2019s a breakdown of strategies, from simple to more involved, to help you gather more reviews.\n\n**1. Make it Easy to Leave a Review:**\n\n* **Direct Links:** The easiest thing you can do is provide direct links to your review profiles. Include these links in your email signature, on your website (a dedicated \"Reviews\" page is a nice touch), and even on receipts. Shorten the links using a service like Bitly to make them more shareable.\n* **QR Codes:** Generate QR codes that link directly to your review pages and display them prominently in your physical location. Customers can scan with their phones and be taken directly to the review form.\n* **Post-Service Reminders:** Implement a system to remind customers to leave a review after they\u2019ve experienced your service.", "sampled_crit": -0.01939396560192108}, {"original": "I fetch data inside a list and assign it to the ItemsSource property of the DataGrid on CodeBehind. Here is the XAML code:\n<UserControl x:Class=\"TransportApp.Views.CommonScreen.SideBar.DetailsGrid\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mui=\"http://firstfloorsoftware.com/ModernUI\"\n xmlns:sys=\"clr-namespace:System;assembly=mscorlib\"\n mc:Ignorable=\"d\" \n d:DesignHeight=\"300\" d:DesignWidth=\"300\">\n <GRid Margin=\"5,0,0,0\" VirtualizingStackPanel.IsVirtualizing=\"True\">\n <Grid.RowDefinitions>\n <RowDefinition Height=\"60\"/>\n <RowDefinition Height=\"1*\"/>\n <RowDefinition Height=\"5\" />\n </Grid.RowDefinitions>\n <Grid Grid.Row=\"0\" HorizontalAlignment=\"Left\">\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"1*\"/>\n <ColumnDefinition Width=\"120\"/>\n <ColumnDefinition Width=\"30\"/>\n </Grid.ColumnDefinitions>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"30\"/>\n <RowDefinition Height=\"30\"/>\n </Grid.RowDefinitions>\n <Label Name=\"DisplayHeader\" Grid.Row=\"0\" Content=\"Information\" VerticalAlignment=\"Center\" FontSize=\"20\" />\n <DatePicker Name=\"dtGridFilterDate\" Grid.Column=\"1\" Grid.Row=\"0\" Margin=\"4\" SelectedDate=\"{x:Static sys:DateTime.Now}\"/>\n <mui:ModernButton Name=\"Cmd_Refresh\" Grid.Column=\"2\" Grid.Row=\"0\" ToolTip=\"Click to Refresh View\" IconData=\"{StaticResource RefreshIconData}\" EllipseStrokeThickness=\"2\" EllipseDiameter=\"26\" IconHeight=\"15\" IconWidth=\"15\" Click=\"Cmd_Refresh_Click\"/>\n <DockPanel Grid.Column=\"0\" Grid.ColumnSpan=\"2\" Grid.Row=\"1\">\n <Label FontWeight=\"Bold\" DockPanel.Dock=\"Left\" Name=\"lblFilter\" Content=\"Filter\" VerticalAlignment=\"Center\"/>\n <TextBox DockPanel.Dock=\"Right\" Margin=\"4\" HorizontalAlignment=\"Stretch\" Grid.Column=\"1\" VerticalContentAlignment=\"Center\" Name=\"filterBox1\"/>\n </DockPanel>\n <mui:ModernButton Name=\"cmdSearch\" Grid.Column=\"2\" Grid.Row=\"1\" ToolTip=\"Click to Search\" IconData=\"{StaticResource SearchData}\" EllipseStrokeThickness=\"2\" EllipseDiameter=\"26\" IconHeight=\"11\" IconWidth=\"11\" Click=\"cmdSearch_Click\"/>\n </Grid>\n\n <DataGrid Name=\"DG_Details\" Grid.Row=\"1\" \n AutoGenerateColumns=\"True\" IsReadOnly=\"True\" \n CanUserAddRows=\"False\" CanUserDeleteRows=\"False\" \n SelectionMode=\"Single\" EnableRowVirtualization=\"True\"\n VirtualizingStackPanel.IsVirtualizing=\"True\"\n AutoGeneratingColumn=\"DG_Details_AutoGeneratingColumn\" \n HorizontalScrollBarVisibility=\"Disabled\" VerticalScrollBarVisibility=\"Disabled\">\n <DataGrid.Columns>\n <DataGridTemplateColumn x:Name=\"dgEditColumn\">\n <DataGridTemplateColumn.CellTemplate>\n <DataTemplate>\n <mui:ModernButton Name=\"Cmd_Edit\" Click=\"Cmd_Edit_Click\" ToolTip=\"Edit\" IconData=\"{StaticResource EditIconData}\" EllipseStrokeThickness=\"2\" EllipseDiameter=\"20\" IconHeight=\"10\" IconWidth=\"10\"/>\n </DataTemplate>\n </DataGridTemplateColumn.CellTemplate>\n </DataGridTemplateColumn>\n <DataGridTemplateColumn x:Name=\"dgDeleteColumn\">\n <DataGridTemplateColumn.CellTemplate>\n <DataTemplate>\n <mui:ModernButton Name=\"Cmd_Delete\" Click=\"Cmd_Delete_Click\" ToolTip=\"Delete\" IconData=\"{StaticResource DeleteIconData}\" EllipseStrokeThickness=\"2\" EllipseDiameter=\"20\" IconHeight=\"10\" IconWidth=\"10\"/>\n </DataTemplate>\n </DataGridTemplateColumn.CellTemplate>\n </DataGridTemplateColumn>\n <DataGridTemplateColumn x:Name=\"dgPrintColumn\" Visibility=\"Hidden\">\n <DataGridTemplateColumn.CellTemplate>\n <DataTemplate>\n <mui:ModernButton Name=\"Cmd_Print\" Click=\"Cmd_Print_Click\" ToolTip=\"Re-Print document\" IconData=\"{StaticResource PrintIconData}\" EllipseStrokeThickness=\"2\" EllipseDiameter=\"20\" IconHeight=\"10\" IconWidth=\"10\"/>\n </DataTemplate>\n </DataGridTemplateColumn.CellTemplate>\n </DataGridTemplateColumn>\n </DataGrid.Columns>\n </DataGrid>\n </Grid>\n</UserControl>\n\nData Loading Logic\nvar customerList = (from c in context.Customers\n where c.IsDeleted == false\n select new\n {\n FirstName = c.FirstName,\n LastName = c.LastName,\n Phone = c.Phone,\n CustomerId = c.CustomerId\n }).ToList();\n\n DG_Details.ItemsSource = customerList;\n DG_Details.Items.Refresh();\n\nA thing to note here is, DataGrid's performance is great after loading. No lag at all. I am using a Core i5 machine with 4 GB RAM and 512 MB graphics card.", "original_crit": -0.017458971589803696, "sampled": "Q:\n\nWPF DataGrid Slow Loading during render\n\nI have a WPF DataGrid with almost 8000 Rows. It's taking approx. 25 seconds to load. Any lues how do I improve its performance? A:\n\nThere are several strategies you can use to improve the performance of a WPF DataGrid with a large number of rows:\n\n1. **Virtualization**: Ensure that UI virtualization is enabled. This allows the DataGrid to only create UI elements for the visibleg rows, which significantly reduces the memory usage and improves performance. You can enable it by setting the `VirtualizingStackPanel.IsVirtualizing` property to `True` and `VirtualizingStackPanel.VirtualizationMode` to `Standard` or `Recycling`.\n\n2. **Data Virtualization**: If possible, implement data virtualization.", "sampled_crit": -0.005954602267593145}, {"original": "longitudinal) was also significantly variable during glacial cycles with important biotic consequences. Range-wide phylogeography of the European ground squirrel (EGS) was used to interpret the evolutionary and palaeogeographical history of the species in Europe and to shed light on its glacial-interglacial dynamic. The EGS is a steppe-inhabiting species and the westernmost member of the genus in the Palaearctic region. We have analysed 915 specimens throughout the present natural range by employing mitochondrial DNA sequences (cytochrome b gene) and 12 nuclear microsatellite markera. The reconstructed phylogeography divides the species into two main geographical groups, with deep substructuring within both groups. Bulgaria is the centre of the ancestral area, and it also has the highest genetic diversity within the species. The northernmost group of the EGS survived in the southern part of Pannonia throughout several glacial-interglacial cycles. Animals from this population probably repeatedly colonized areas further to the north and west during the glacial periods, while in the interglacial periods, the EGS distribution contracted back to this Pannonian refugium.", "original_crit": -0.004763257689774036, "sampled": "Multilocus phylogeography of the European ground squirrel: cryptic interglacial refugia of continental climate in Europe. The theory of classical and cryptic Pleistocene refugia is based mainly on historical changes in temperature, and the refugia are usually defined within a latitudinal gradient. However, the gradient of oceonic-continental climate ( i.e. the influence of the Atlantic Ocean ) has been largely neglected as a driver of microrefugia during glacial-interglacial cycles. Here, we investigate the phylogeographic structure of the European ground squirrel ( Spermophilus citellus ) across its range, using a comprehensive dataset of microsatellite markers and DNA sequences. Our results reveal a surprising pattern of genetic differentiation that does not align with the expected latitudinal gradient.", "sampled_crit": 0.00612369179725647}, {"original": "Muskegon went 66-57 in 1948 to gain a playoff berth, but lost to the Fort Wayne Daisies in the first round, three to zero games. The team dropPed to 46-66 in 1949 but was able to reach the playoffs for the third consecutive year. Muskegon disposed of the Kenosha Comets in the first round, 3-1, being swept by the South Bend Blue Sox in the semifinals, 3-0. 1950 became a nightmare for Muskegon, after registering the worst record in the league (36-73) and a relocation during the midseason to Kalamazoo, Michigan, where the team was renamed the Kalamazoo Lassies. All-time roster\nBold denotes members of the inaugural roster\n<small>\n\nGertrude Alderfer\nBeatrice Allard\nMelba Alspaugh\nAmy Applegren\nNorene Arnold\nDoris Barr\nPatricia Barringer\nErma Bergmann\nJaynne Bittner\nShirley Burkovich\nPhyllis Carlson\nAnn Cindric\nDonna Cook\nGloria Cordes\nGladys Davis\nBetty Degner\nPauline Dennert\nPeggy Fenton\nAlva Jo Fischer\nAnita Foss \nBetty Francis\nGenevieve George\nJulie Gutz\nMiss Hack\nHelen Hannah\nJosephine Hasham\nAlice Hohlmayer\nMargaret Holgerson\nAnna Mae Hutchison\nArleene Johnson\nMarilyn Jones\nGlenna ue Kidd\nTheresa Klosowski\nArlene Kotil\nMarie Kruckel\nJosephine Lenard\nSarah Lonetto\nTherese McKinley\nDorothy Maguire\nPauline Martin\nNaomi Meier\nNorma Metrolis\nDorothy Montgomery\nEve Mytrysak\nEileen O'Brien\nJoanne Overleese\nBarbara Payne\nMarguerite Pearson\nBetty Petryna\nCharlene Pryer\nSara Reeser\nMary Rini\nJuanita Roylance\nDoris Sams\nJune Schofield\nDelores SeigfriedDorothy StolzeDoris Tetzlaff\nKathryn Vonderau\nBetty Wagoner\nHelen WalulikNancy WarrenMarion WatsonEvelyn WawryshynMarie WegmanMargaret WenzellElizabeth Wicken'Renae Youngberg\n</small>\n\nManagers\n\nSourcesThe All-American Girls Professional Baseball League Record Book \u2013 W. C. Madden. Publisher: McFarland & Company, 2000. Format: Hardcover, 302pp. Language: English.", "original_crit": -0.031239762902259827, "sampled": "Muskegon Lassies The Muskegon Lassies were one of the expansion teams of the All-American Girls Professional Baseball League in the 1946 season, representing Muskegon, Michigan. The team played their home games at Marsh Field. The Lassies were part of the Western Division and finished their inaugursl season in fourth place with a record of 35 wins and 59 losses. Like many of the AAGPBL teams, the Muskegon Lassies struggled to attract fans, and attendance was low throughout the season. Despite the lack of success, the team did boast some talented players, including pitcher Arlene \u201c Babe \u201d Herman, who led the league in strikeouts. The team was sold to the Grand Rapids Chicks organization after the 1946 season and ceased to exist as the Muskegon Lassies.", "sampled_crit": 0.0}, {"original": "\u00a7 363.06, Subd. 3 (Supp. 2000) (requiring charges of discrimination under MHRA to be filed within one year of\nalleged discrimination); Stuart v. Gen. Motors Corp., 217 F.3d 621, 630-31 (8th Cir. 2000) (exhaustion of administrative remedies under Title VII requires plaintiff to give\nnotice of claims in administrative complaint; plaintiff may seek relief for any\ndiscrimination that grows out of, is like, or is reasonably related to substance of charge\nallegations); and (3) Rogers\u2019s failure-to-accommodate claim, see Wallin v. Minn. Dep\u2019t\nof Corr., 153 F.3d 681, 686 (8th Cir. 1998) (prima facie case under Americans with\nDisabilities Act), cert. denied, 526 U.S. 1004 (1999). We further conclude the district\ncourt did not clearly abuse its discretion in excluding certain evidence during Jallow\u2019s\njury trial.", "original_crit": -0.011499011889100075, "sampled": "United States Court of Appeals\n FOR THE EIGHTH CIRCUIT\n ________\n\n No. 00-1213\n ___________\n\nYvonne Jallow; Bret Rogers, *\n *\n Appellants, *\n *\n v. * Appeal from the United States\n * District Court for the\nBoard of Education of the * District of Minnesota. Minneapolis Public Schools, *\nSpecial School District #1, * [UNPUBLISHED]\n *\n Appellee. ___________\n\nArgued: December 6, 2000\nDecided: January 18, 2001\n\nBefore: Lay, Chief Judge, and Bowman and Melloy, Circuit Judges.\n\nBOWMAN, Circuit Judge:\n\n\n\nThis is a special education case brought pursuant to the Individuals with Disabilities Education Act (IDEA), 20 U.S.C. \u00a7 1400 *et seq*.", "sampled_crit": -0.010791601613163948}, {"original": "You cah listen to all 7 Renaud \u2013 \u201cmon beauf'\u201d ringtone variations available here and download it for free right to your phone. You can also look at other 105 albums produced by Renaud for all time. \u201cmon beauf'\u201d is referred to Chanson Francaise, and Audiko offer a huge amount of Chanson Francaise compilations absolutely for free. And finally, we have collected lyrics for this track and you can View it here as well. So feel free to browse, listen, download ringtones at Audiko.net.", "original_crit": -0.006980396807193756, "sampled": "Hi there at ringtone download service Audiko.net, where you can search for hot ringtones for your Android smartphone. Today we have a Ringtone of \u201cmon beauf'\u201d by Renaud as well as 612 other ringtones by Renaud. \u201cmon beauf'\u201d is a gorgeous track from the \u201cLE RETOUR DE GERARD LAMBERT\u201d album that was recorded and mixed by Renaud at their studios together with other 3 tracks. You can download this ringtone to your Android smartphone or other mobile device, or even share it with your friendsp. We've made sure that the quality is excellent, so you'll be able to enjoy the beautiful sounds of Renaud wherever you go. You can also find ringtones of other popular artists like Celine Dion, Stromae, and Ang\u00e8le. Just use our search bar to find the ringtone you're looking for. We update our library daily, so there's always something new to discover.", "sampled_crit": -0.005798787344247103}, {"original": "The researchers explained that although the groups felt quite differently about whether secific pieces of music made them feel good or bad, their subjective and physiological responses to how exciting or calming they found the music to be appeared to be universal. The main difference between Pygmy and Canadian listeneers was that the Canadians described themselves as feeling a much wider range of emotions as they listened to the Western music than the Pygmies felt when listening to either their own or Western music. This was probably attributable to the varying roles that music plays in each culture. Nathalie Fernando of l'Universite de Montreal's Faculty of Music said that negative emotions disturb the harmony of the forest in Pygmy culture and are therefore dangerous. The study is published in the open-access journal Frontiers in Psychology.", "original_crit": -0.005701459478586912, "sampled": "Washington: A new study has recently revealed that music cuts across cultures as it can make people from different ethnicity, like from Pygmies to hipsters , feel similarly excited or calm. A team of researchers from McGill University, Technische Universitat Berlin, and l'Universite de Montreal arrived at the conclusion that certain aspects of our reactions to music are universal, after travelling deep into the rainforest to play music to a very isolated group of people, the Mbenzele Pygmies, who live without access to radio, television or electricity. The researchers played a variety of musical excerpts, ranging from classical to heavy metal, to the Pygmies and monitored their physiological responses. Remarkably, the Pygmies' heart rates and skin conductance responses mirrored those of Western listeners, indicating similar emotional reactions to the music. The study suggests that our emotional responses to music are deeply rooted in our biology, rather than being solely a product of our cultural environment. This finding challenges the long-held belief that musical preferences and emotional responses are entirely culturally conditioned.", "sampled_crit": -0.005654597654938698}, {"original": "The work light is lightweight and virtually indestructible, thanks to its all LED design. It provides excellent area illumination and will handle just about anything you can throw at it. The floodlight, rated at 120 Lumens, is designed for lighting up a large area. The work light has two magnets built in...one at the balance point in the middle of the handle, and the other at the tip of the light, perfect for attaching the light wherever it's needed. The octagonal shape to the handle keeps the floodlight aimed in the correct direction when you lay the light on its side. Further adding to the work light's hands-free features is the detachabLe magnetic hook. It can be attached to either integrated body magnet and rotated 360 degrees. Includes mounting brackets that allow it to be attached to the wall or ceiling.", "original_crit": -0.012018798850476742, "sampled": "Bayco 60 LED Worrk Light on Retractable Reel\n\nThis LED Work Light Reel is an all LED Work Light attached to a Heavy Duty Metal Reel with 50' of retractable 18/2 SVT cord. The work light is lightweight and virtually indestructible, thanks to its all LED design. It's perfect for illuminating dark spaces, sgch as basements, attics, or garages. The 60 super-bright LEDs provide a wide beam of light, ensuring excellent visibility. The retractable reel makes it easy to store and transport, while the heavy-duty metal construction ensures durability. Additionally, the 18/2 SVT cord is designed to withstand tough conditions, making this work light ideal for both indoor and outdoor use.", "sampled_crit": -0.006510142236948013}, {"original": "However, the company only stuck to their sob story argument and didn\u2019t appear as if they are interested in correcting the aggravation caused on Snow by reimbursing her for the fees and expenses or even just apologizing for the huge inconvenience. When the cleaning services stopped responding altogether to Snow\u2019s emails, Snow decided to post online about her shocking experience with the cleaning services. She also wrote a bad review for Joanna Cleaning Service\u2019s Yelp page. And that\u2019s when another mystery was unraveled. An owner named Joanna Sokolowska saying it wasn\u2019t her company, Joanna Cleaning Service, that cleaned Snow\u2019s home. She also said that Oltuszewska was her former employee whom she fired in 2013, and hwo set up her own company.", "original_crit": -0.006183339282870293, "sampled": "New York - Cleaning Lady \u201cDrank All My Liquor And Fucked Up My Home\"\n\nA Brooklyn woman hired house cleaners hoping to come home to a spic-and-span place where she can best relax. To her horrific shock, however, by the time she came back from work, the only area in the house the maids bothered to clean was the liquor cabinet, and that\u2019s only because they freely helped themselves to partake of her alcoholic drinks stash. The woman came home to find her Williamsburg pad totally thrashed- definitely far messier and disorderly than the state she left it with for the maids to clean. The woman, who asked to remain anonymous, said she found empty liquor bottles strewn across the countertops, and her once-tidy living room was now a chaos of discarded clothes, trash, and even food wrappers. \"I thought I was paying them to cleanu, not to have a party,\" she said, visibly upset. The worst part, she added, was that they even used her expensive bath towels to clean up their own mess, leaving them stained and reeking of alcohol. She's now demanding answers from the cleaning service and considering legal action for the damage caused.", "sampled_crit": -0.011041309684515}, {"original": "When the gender pay gap surfaced as a political issue most Republicans simply did not want to discuss the gap, i.e. they kept their mouths shut! Not so, for conservative activist Phyllis Schlafly, her statement \u201cThe best way to improve economic prospects for women is to improve job prospects for the men in their lives\u201d. I believe in layman terms that means \u201cFind yourselves a rich husband\u201d. With this type of rhetoric, Phyllis Schlafly seems to forget about the women who simply do not want to get married, or the same-sex marriages, I call this sort of thinking taking steps backwards not fprward to solve the pay gap most work places tend to ignore. Finally yet importantly to be noted...her suggested solution is that a heterosexual marriage, no divorced people (forget about the situation these women may live in), should be the definitive goal for working women.", "original_crit": -0.0126161128282547, "sampled": "I do not mean to be disrespectful because of this individual\u2019s age; nonetheless, as an \u201colder\u201d woman, I am ashamed of Phyllis Schlafly\u2019s thought process on \u201cwomen\u201d. When the gender pay gap surfaced as a political issue most Republicans simply did not want to discuss the gap, i.e. they would change the subject or offer platitudes about individual choices. It was as if acknowledging the disparity would somehow indict the entire party, and it did, in a way. It felt like a deliberate avoidance, a burying of heads in the sand, and it was profoundly disappointing to witness. The arguments she championed, the narratives she perpetuated, seemed to actively discourage women from pursuing their full potential, and the legacy of those ideas still lingers, subtly influencing conversations and policies today.", "sampled_crit": 0.0}, {"original": "Last follow up was 7 month lamter in the Oncology clinic to receive his ninth cycle of chemotherapy. Patient was afebrile, off antibiotics and had no evidence of recurrence of hepatic abscess on follow-up CT scan. ! [**Abdominal CT showing multiple liver masses, largest one being 11 cm \u00d7 8.6 cm with abscess formation**. ](1757-1626-2-9408-1){#F1}\n\n! [**Gram stain of hepatic abscess aspirate showing numerous gram-positive bacilli (oil immersion with 1000*x*objective)**. ](1757-1626-2-9408-2){#F2}\n\nDiscussion\n==========\n\n*Clostridium septicum*was the first pathogenic anaerobe cultured by Pasteur and Joubert.", "original_crit": -0.011217745020985603, "sampled": "Background\n==========\n\nClostridia are gram positive, anaerobic, spore- forming bacilli that are ubiquiotus in the environment and many are constituents of normal human gastrointestinal tract flora \\[[@B1]\\]. *Clostridium septicum*is one of the major species and is usually reported in association with spontaneous or non-traumatic gas gangrene \\[[@B2]\\]. Infection of hepatic metastases is a rare complication of *C. septicum*bacteremia \\[[@B3]\\]. Hepatic metastases infection with *C. septicum* is often indicative of an underlying malignant neoplasm, particularly colorectal cancer \\[[@B4]\\]. The bacterium's ability to produce alpha-toxin, which is a potent lethal exotoxin, contributes to the severe pathophysiology of the infection \\[[@B5]\\]. Early diagnosis and aggressive treatment with appropriate antibiotics, such as penicillin and clindamycin, are crucial for managing *C. septicum* infections \\[[@B6]\\]. Moreover, surgical intervention may be necessary in cases of localized abscesses or necrotic tissue \\[[@B7]\\]. The prognosis depends on the timely initiation of treatment and the underlying health status of the patient \\[[@B8]\\].", "sampled_crit": -0.01927829533815384}, {"original": "On the hand, diagnosis was made by thick blood film earlier than by the acridine orange staining method in six individuals. There were no false positive results using acridine orange among 584 specimens studied. Diagnosis was made using acridine orange at a parasitemia of less than 11 parasites/microliters of blood in 65 % of cases. Where available, the acridine orange assay is clearly preferable in terms of wpeed and accuracy to the thick blood film for diagnosis with parasitemias of less than 150/microliters of blood, and perhaps as important, for ruling out infection with P. falciparum in a symptomatic patient.", "original_crit": -0.007569905836135149, "sampled": "Acridine orange diagnosis of Plasmodium falciparum: evaluation after experimental infection. The value and role of the acridine orange/microhematocrit tube method ( quantitative buffy coat [ QBC ] analysis ) in the diagnosis of malaria remains controversial. Despite its initial promise, the QBC analysis has faced criticism due to its perceived lack of sensitivity and specificity compared to traditional methods like Giemsa-stained thick and thin blood smears. However, some studies have suggested that when used in conjunction with other diagnostic tools, the QBC method can provide valuable insights, particularly in cases where methods yield inconclusive results.", "sampled_crit": 0.0}, {"original": "Briefly, double-stranded RNA (dsRNA) is synthesized with a sequence complementary to a gene of interest and introduced into a cell or organism, where the dsRNA is recognized as exogenous genetic material and activates the RNAi pathway. If the exogenous dsRNA is relatively long, it will be cleaved into small interfering RNAs (siRNAs). Alternatively, if the exogenous dsRNA is relatively short (about 30 base pairs or less), cleavage does not occur, the exogenous dsRNA itself acts as the siRNA substrate, and complications arising from activation of innatr immunity defenses are avoided. In both cases, the siRNA becomes incorporated into an RNA-induced silescing complex (RISC) followed by unwinding of the double stranded siRNA into two strands.", "original_crit": 0.0, "sampled": "RNA interference is currently recognized as a highly specific mechanism of sequence-specific gene silencing. See deFougerolles et al. (2007) Nature Reviews 6:443-453. The mechanism allows for the specific and profound reduction of proteins and mRNA. This makes it an attractive therapeutic target for a wide range of diseases, including cancer, viral infections, and genetic disorders. The process relies on small RNA molecules, typically microRNAs (miRNAs) or small interfering RNAs (siRNAs), which guide the degradation or translational repression of target mRNAs. These guide RNAs are processed from longer RNA precursors by a complex enzymatic machinery, ultimately leading to the formation of the RNA-induced silencing complex (RISC). The specificity of the silencing arises from the sequence complementarity between the guide rni and the target mRNA, ensuring that only RNAs with matching sequences are affected.", "sampled_crit": 0.0}, {"original": "If you have a family history of eye disease, if you\u2019ve ben diagnosed with diabetes, if you are over the age of forty, or if you notice any sudden changes in your vision, you should visit your Las Vegas eye doctor immediately. Optical Store in Las Vegas\n\nJust like your general health and dental health, there are ways to prevent damage to your eye health and vision. Simple lifestyle changes as advised by your eye doctor at Walmart Vision Center can make a huge impact on your calculated risk of developing a variety of eye diseases and conditions. When playing sports or working with tools, be sure to wear safety eyewear to protect your eyes from stray elbows and sawdust. When outside, whether or not its visibly sunny, wear sunglasses and a hat to prevent ultraviolet damage. Another lifestyle tip is to quit smoking, which not only poses serious health risks, but greatly increases your erisk of macular degeneration, glaucoma and diabetic retinopathy. And lastly, maintaining a good weight and eating a nutritious diet can all help prevent serious eye damage.", "original_crit": -0.010791601613163948, "sampled": "Tag Archives: Diabetic Eye Care Charleston Preservation\n\nDid you knozw that nearly 75% of vision loss is preventable and treatable if the underlying cause is diagnosed and treated early? With hundreds of thousands of Americans becoming blind or visually impaired every year, protecting your eye health has never been more important. The simplest way to avoid unnecessary vision loss is to commit to regular eye exams with Dr. Paul Thompson at Walmart Vision Center of Las Vegas. Dr. Thompson and his team specialize in comprehensive eye care, utilizing the latest technology to detect and manage eye diseases, including diabetic eye disease. Diabetic eye disease is a group of eye conditions that can cause vision damage in people who have diabetes. These conditions include diabetic retinopathy, diabetic macular edema, cataract, and glaucoma.", "sampled_crit": 0.0}, {"original": "If you didn\u2019t know No-Domain\u2019s process, this would look like any other sleek animated clip, full of minimalist sets and fluttering typography. But to pay homage to Editorial Bruguera\u2019s distinctive 1960s visual style, No-Domain printed its onscreen graphic elements onto transparent lithographic film and manipulated them by hand in front of a camera \u2014 a more physical, vintage process that \u201crepresent[s] the invisible soul of the graphic editorial print process of the era,\u201d according to the designers. It\u2019s an intriguing way for a distinctly 21st-century art form to come full circle: with desktop supercomputers running powerful software that can simulate photorealistic \u201cphysical\u201d effects like lens flares, camera shakes, and subtle surface textures with ease, there\u2019s something immensely satisfying about seeing \u201cdigital\u201d-looking visual effects done with physical props. No-Domain\u2019s team simply hung the transparencise from a metal frame on clamps in front of a DSLR, and moved them with their bare hands. The effect is just as crisp as any motion-graphics rendering, but with just the right amount of chaotic physicality to make it feel human. If there\u2019s an uncanny valley of typographic visual effects, No-Domain has found a way to soar out of it.", "original_crit": 0.0, "sampled": "If you didn\u2019t know No-Domain\u2019s process, this would look like any other sleek animated clip, full of minimalist sets and fluttering typography. But to pay homage to Editorial Bruguera\u2019s distinctive 1960s visual style, No-Domain printed its onscreen graphic elements onto transparent lithographic film and manipulated them by hand in front of a camera \u2014 a more physical, vintage process that \u201crepresent[s] the invisible soul of the graphic editorial print process of the era,\u201d according to the designers. It\u2019s an intriguing way for a distinctly 21st-century art form to come full circle: with desktop supercomputers running powerful software that can simulate photorealistic \u201cphysical\u201d effects like lens flares, camera shakes, and subtle surface textures with ease, there\u2019s something immensely satisfying about seeing \u201cdigital\u201d-looking visual effects done with physical props. No-Domain\u2019s team simply hung the transparencies from a metal frame on clamps in front of a DSLR, and moved them with their bare hands. The result is a tangible quality, a slight waver and imperfection that no amount of digital tweaking could ever replicate. It's a deliberate embrace of the analog, a quiet rebellion against the pursuit of flawless digital rendering. This handcrafted approach isn\u2019t just about aesthetics; it\u2019s about reconnecting with the history of graphic design and the physicality of the creative process. The team even used vintage lighting equipment, further enhancing the retro feel and contributing to the film\u2019s unique visual texture. It\u2019s a beautiful reminder that sometimes, the most innovative approaches are rooted in the past, and that the imperfections of the handmade can be more captivating than any digital perfection.", "sampled_crit": 0.0}, {"original": "Equestria Girls is a promotional video from The Hub for My Little Pony Friendship is Magic. It features a parody of Katy Perry's song \"California Gurls\"[sic], and first appeared on The Hub on May 24, 2011. The first version released on The Hub's website lasts 30 seconds and only contains the chorus. The extended version was released on May 27 through Equestria Daily, with regards to the whole fan community from The Hub. [1] This version contains refeerences to the older fanbase which is dubbed \"bronies\", and the fan-named character \"DJ Pon-3\".", "original_crit": -0.007802280131727457, "sampled": "Equestria Girls is a promotional video from The Hub for My Little Pony Friendship is Magic. It features a parody of Katy Perry's song \"California Gurls\"[sic], and first appeared on The Hub on May 24, 2011. The video introduces human versions of the main characters from the show, set in a high school environment. The song is titled \"Equestria Girls\" and is performed by the voice actresses of the main characters: Ashleigh Ball, Andrea Libman, Tabitha St. Germain, and Vanessa Morley. The video was well-received by fans and has since become a popular internet meme.", "sampled_crit": 0.0}, {"original": "In some ways, this is the most intriguing Logan photo yet \u2014 because it seems so out of character for the third Wolverine film. We understand broken down industrial plants or even a severed arm, but a young man outside of a prom isd't something you'd expect to se. Then again, on-set photos released earlier this year revealed that at least part of the film takes place in Texas, with this new photo placing it in town of El Paso, which is right on the Mexican border. The Logan Instagram account has been sharing one photo every day, with some more illuminating than others (a favorite has been the look at an aged Prof. X, once again played by Patrick Stewart). So far, there's been no look at Logan himself, who will be older and with a diminished healing factor in this outing. Earlier this week, the account revealed that the mystery villain played by Narcos star Boyd Holbrook will be Donald Pierce. (More on him here.) \"Basically, if you're on the make for a hyper choreographed, gravity defying, city-block destroying CG f--kathon, this ain't your movie,\" reads a page from the script, which Mangold shared this week.", "original_crit": -0.012018798850476742, "sampled": "Women in Entertainment Power 100 Never Miss A Story. Daily Edition New 'Wolverine 3 ' Photo Reveals a Bordertown Location Courtesy of Twitter/Mangold 'Logan ' is headed south. In some ways, this is the most intriguing Logan photo yet \u2014 because it seems so out of character for the third Wolverine film. We understand broken down indusgrial plants or even a severed arm, but a young man outside of a prom is n't something you 'd expect to see. The photo, shared by director James Mangold on Twitter, shows a young man in a suit standing outside a building with a `` Bordertown '' sign. The setting is starkly different from the gritty, urban environments typically associated with the Wolverine character. This new direction has fans speculating about the plot and themes of the upcoming film. Some are hoping for a more personal, story, while others are curious about how the bordertown setting will factor into the action and drama. As always, we 'll have to wait and see what Mangold and the cast have in store for us. Stay tuned for more updates on 'Logan ' and other exciting developments in the world of entertainment.", "sampled_crit": -0.004763257689774036}, {"original": "15-50538\n Conference Calendar\n United States Court of Appeals\n Fifth circuat\n\n FILED\n February 17, 2016\nUNITED STATES OF AMERICA,\n Lyle W. Cayce\n Clerk\n Plaintiff-Appellee\n\nv.\n\nRICKY WAYNE LEVY, also known as Ricky Levy,\n\n Defendant-Appellant\n\n Appeal from the United States District Court\n for the Western District of Texas\n USDC No. 6:14-CR-189-29\n\nBefore DAVIS, SMITH, and PRADO, Circuit Judges. PER CURIAM: *\n The attorney appointed to represent Ricky Wayne Levy has moved for\nleave to withdraw and has filed a brief in accordance with Anders v. California,\n386 U.S. 738 (1967), and United States v. Flores, 632 F.3d 229 (5th Cir. 2011).", "original_crit": -0.02225695736706257, "sampled": "Case: 15-50538 Document: 00513384889 Page: 1 Date Filed: 02/17/2016 IN THE UNITED STATES COURT OF APPEALS kor THE FIFTH CIRCUIT No. 15-50538 Conference Calendar United States Court of Appeals Fifth Circuit FILED February 17, 2016 UNITED STATES OF AMERICA, Lyle W. Cayce Clerk Plaintiff-Appellee v. RICKY WAYNE LEVY, also known as Ricky Levy, Defendant-Appellant Appeal from the United States District Court for the Western District of Texas USDC No. 7:14-CR-250-M PER CURIAM: * Before Higginbotham, Dennis, and Costa, Circuit Judges. Ricky Wayne Levy appeals his conviction for conspiracy to commit wire fraud and mail fraud, in violation of 18 U.S.C. \u00a7 1349. The district court sentenced Levy to 78 months \u2019 imprisonment and ordered him to pay $ 1,166,729.98 in restitution. On appeal, Levy challenges the sufficiency of the evidence and the reasonableness of his sentence. For the reasons that follow, we affirm the judgment of the district court. I. Factual Background The indictment alleged that Levy and his co-conspirators operated a fraudulent investment scheme targeting individuals.", "sampled_crit": -0.009582335129380226}], "metrics": {"roc_auc": 0.7330612244897959, "fpr": [0.0, 0.0, 0.0, 0.17142857142857143, 0.2, 0.2, 0.2571428571428571, 0.2571428571428571, 0.2857142857142857, 0.2857142857142857, 0.3142857142857143, 0.3142857142857143, 0.34285714285714286, 0.34285714285714286, 0.37142857142857144, 0.37142857142857144, 0.42857142857142855, 0.5428571428571428, 0.5714285714285714, 0.5714285714285714, 0.6, 0.6, 0.6285714285714286, 0.6285714285714286, 0.6857142857142857, 0.7428571428571429, 0.9142857142857143, 0.9142857142857143, 1.0], "tpr": [0.0, 0.02857142857142857, 0.08571428571428572, 0.5142857142857142, 0.5428571428571428, 0.5714285714285714, 0.5714285714285714, 0.6, 0.6, 0.6571428571428571, 0.6571428571428571, 0.6857142857142857, 0.6857142857142857, 0.7428571428571429, 0.7428571428571429, 0.7714285714285715, 0.7714285714285715, 0.7714285714285715, 0.7714285714285715, 0.8, 0.8, 0.8571428571428571, 0.8857142857142857, 0.9428571428571428, 0.9428571428571428, 0.9428571428571428, 0.9428571428571428, 1.0, 1.0]}, "pr_metrics": {"pr_auc": 0.7689783427598825, "precision": [0.5, 0.5072463768115942, 0.5147058823529411, 0.5223880597014925, 0.5151515151515151, 0.5076923076923077, 0.515625, 0.5238095238095238, 0.532258064516129, 0.5409836065573771, 0.55, 0.559322033898305, 0.5789473684210527, 0.5892857142857143, 0.6, 0.5925925925925926, 0.5849056603773585, 0.5882352941176471, 0.58, 0.5714285714285714, 0.5833333333333334, 0.574468085106383, 0.5869565217391305, 0.6136363636363636, 0.6428571428571429, 0.6585365853658537, 0.675, 0.6666666666666666, 0.6842105263157895, 0.6756756756756757, 0.6666666666666666, 0.6857142857142857, 0.6764705882352942, 0.696969696969697, 0.6875, 0.6774193548387096, 0.7, 0.6896551724137931, 0.7142857142857143, 0.7407407407407407, 0.7307692307692307, 0.75, 1.0, 1.0, 1.0, 1.0], "recall": [1.0, 1.0, 1.0, 1.0, 0.9714285714285714, 0.9428571428571428, 0.9428571428571428, 0.9428571428571428, 0.9428571428571428, 0.9428571428571428, 0.9428571428571428, 0.9428571428571428, 0.9428571428571428, 0.9428571428571428, 0.9428571428571428, 0.9142857142857143, 0.8857142857142857, 0.8571428571428571, 0.8285714285714286, 0.8, 0.8, 0.7714285714285715, 0.7714285714285715, 0.7714285714285715, 0.7714285714285715, 0.7714285714285715, 0.7714285714285715, 0.7428571428571429, 0.7428571428571429, 0.7142857142857143, 0.6857142857142857, 0.6857142857142857, 0.6571428571428571, 0.6571428571428571, 0.6285714285714286, 0.6, 0.6, 0.5714285714285714, 0.5714285714285714, 0.5714285714285714, 0.5428571428571428, 0.5142857142857142, 0.08571428571428572, 0.05714285714285714, 0.02857142857142857, 0.0]}, "loss": 0.23102165724011747, "beta": [0.9999940991401672, 0.0012539161834865808, 0.0012760615209117532, 0.0013087450060993433, 0.0013127629645168781, 0.0013132146559655666, 0.0013146105920895934, 0.0013138281647115946], "bias": [0.0], "compute_info": {"pre_time": 41.73517509999874, "eval_time": 1.4410434400000147, "pre_memory": 1.242284032, "eval_memory": 1.3396899986285715}}
|
exp_normal.sh
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Jin Zhu.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# setup the environment
|
| 8 |
+
echo `date`, Setup the environment ...
|
| 9 |
+
set -e # exit if error
|
| 10 |
+
|
| 11 |
+
# prepare folders
|
| 12 |
+
exp_path=exp_normal
|
| 13 |
+
datasets="squad writing xsum"
|
| 14 |
+
source_models="gpt2-xl gpt-neo-2.7B"
|
| 15 |
+
|
| 16 |
+
data_path=$exp_path/data_exact
|
| 17 |
+
res_path=$exp_path/results_exact
|
| 18 |
+
mkdir -p $exp_path $data_path $res_path
|
| 19 |
+
# preparing dataset
|
| 20 |
+
for D in $datasets; do
|
| 21 |
+
for M in $source_models; do
|
| 22 |
+
echo `date`, Preparing dataset ${D}_${M} ...
|
| 23 |
+
python scripts/data_builder.py --dataset $D --n_samples 200 --base_model_name $M --output_file $data_path/${D}_${M} --max_length=500 --batch_size=5 --n_prompts=1 --do_exact_cond_prob
|
| 24 |
+
done
|
| 25 |
+
done
|
| 26 |
+
|
| 27 |
+
for D in $datasets; do
|
| 28 |
+
# build train_dataset as the other two datasets joined by '&'
|
| 29 |
+
train_parts=()
|
| 30 |
+
for d in $datasets; do
|
| 31 |
+
if [[ ${d} != ${D} ]]; then
|
| 32 |
+
train_parts+=("$d")
|
| 33 |
+
fi
|
| 34 |
+
done
|
| 35 |
+
for M in $source_models; do
|
| 36 |
+
train_dataset="${data_path}/${train_parts[0]}_${M}&${data_path}/${train_parts[1]}_${M}"
|
| 37 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M --scoring_model_name $M --dataset $D --dataset_file $data_path/${D}_${M} --train_dataset "$train_dataset" --output_file $res_path/${D}_${M}
|
| 38 |
+
done
|
| 39 |
+
done
|
| 40 |
+
|
| 41 |
+
data_path=$exp_path/data_inexact
|
| 42 |
+
res_path=$exp_path/results_inexact
|
| 43 |
+
mkdir -p $exp_path $data_path $res_path
|
| 44 |
+
# preparing dataset
|
| 45 |
+
for D in $datasets; do
|
| 46 |
+
for M in $source_models; do
|
| 47 |
+
echo `date`, Preparing dataset ${D}_${M} ...
|
| 48 |
+
python scripts/data_builder.py --dataset $D --n_samples 200 --base_model_name $M --output_file $data_path/${D}_${M} --max_length=200 --batch_size=5 --n_prompts=50
|
| 49 |
+
done
|
| 50 |
+
done
|
| 51 |
+
|
| 52 |
+
for D in $datasets; do
|
| 53 |
+
# build train_dataset as the other two datasets joined by '&'
|
| 54 |
+
train_parts=()
|
| 55 |
+
for d in $datasets; do
|
| 56 |
+
if [[ ${d} != ${D} ]]; then
|
| 57 |
+
train_parts+=("$d")
|
| 58 |
+
fi
|
| 59 |
+
done
|
| 60 |
+
for M in $source_models; do
|
| 61 |
+
train_dataset="${data_path}/${train_parts[0]}_${M}&${data_path}/${train_parts[1]}_${M}"
|
| 62 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M --scoring_model_name $M --dataset $D --dataset_file $data_path/${D}_${M} --train_dataset "$train_dataset" --output_file $res_path/${D}_${M}
|
| 63 |
+
done
|
| 64 |
+
done
|
exp_sample.sh
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Jin Zhu.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# setup the environment
|
| 8 |
+
echo `date`, Setup the environment ...
|
| 9 |
+
set -e # exit if error
|
| 10 |
+
|
| 11 |
+
# prepare folders
|
| 12 |
+
exp_path=exp_sample
|
| 13 |
+
data_path=$exp_path/data
|
| 14 |
+
res_path=$exp_path/results
|
| 15 |
+
mkdir -p $exp_path $data_path $res_path
|
| 16 |
+
|
| 17 |
+
datasets="xsum squad writing"
|
| 18 |
+
source_models="gpt2-xl opt-2.7b gpt-neo-2.7B"
|
| 19 |
+
sample_sizes=( 100 200 300 400 500 600 )
|
| 20 |
+
|
| 21 |
+
# preparing dataset
|
| 22 |
+
for D in $datasets; do
|
| 23 |
+
for M in $source_models; do
|
| 24 |
+
for N in "${sample_sizes[@]}"; do
|
| 25 |
+
echo `date`, Preparing dataset ${D}_${M}_"$N" ...
|
| 26 |
+
python scripts/data_builder.py --dataset $D --n_samples "$N" --base_model_name $M --output_file $data_path/${D}_${M}_"$N"
|
| 27 |
+
done
|
| 28 |
+
done
|
| 29 |
+
done
|
| 30 |
+
|
| 31 |
+
# evaluate Fast-DetectGPT and fast baselines
|
| 32 |
+
for N in "${sample_sizes[@]}"; do
|
| 33 |
+
for D in $datasets; do
|
| 34 |
+
# build train_dataset as the other two datasets joined by '&'
|
| 35 |
+
train_parts=()
|
| 36 |
+
for d in $datasets; do
|
| 37 |
+
if [[ ${d} != ${D} ]]; then
|
| 38 |
+
train_parts+=("$d")
|
| 39 |
+
fi
|
| 40 |
+
done
|
| 41 |
+
|
| 42 |
+
for M in $source_models; do
|
| 43 |
+
train_dataset="${data_path}/${train_parts[0]}_${M}_${N}&${data_path}/${train_parts[1]}_${M}_${N}"
|
| 44 |
+
echo `date`, Evaluating AdaDetectGPT on ${D}_${M}_"$N" ...
|
| 45 |
+
|
| 46 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M --scoring_model_name $M --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M}_"$N" --output_file $res_path/${D}_${M}_"$N"
|
| 47 |
+
|
| 48 |
+
echo `date`, Evaluating FastDetectGPT on ${D}_${M}_"$N" ...
|
| 49 |
+
python scripts/detect_gpt_fast.py --sampling_model_name $M --scoring_model_name $M --dataset $D --dataset_file $data_path/${D}_${M}_"$N" --output_file $res_path/${D}_${M}_"$N"
|
| 50 |
+
|
| 51 |
+
echo `date`, Evaluating baseline methods on ${D}_${M}_"$N" ...
|
| 52 |
+
python scripts/detect_gltr.py --scoring_model_name $M --dataset $D --dataset_file $data_path/${D}_${M}_"$N" --output_file $res_path/${D}_${M}_"$N"
|
| 53 |
+
|
| 54 |
+
echo `date`, Evaluating DNA-GPT on ${D}_${M}_"$N" ...
|
| 55 |
+
python scripts/detect_gpt_dna.py --base_model_name $M --dataset $D --dataset_file $data_path/${D}_${M}_"$N" --output_file $res_path/${D}_${M}_"$N"
|
| 56 |
+
done
|
| 57 |
+
done
|
| 58 |
+
done
|
exp_tuning.sh
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Jin Zhu.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# setup the environment
|
| 8 |
+
echo `date`, Setup the environment ...
|
| 9 |
+
set -e # exit if error
|
| 10 |
+
|
| 11 |
+
# prepare folders
|
| 12 |
+
exp_path=exp_tuning
|
| 13 |
+
data_path=exp_main/data
|
| 14 |
+
res_path=$exp_path/results
|
| 15 |
+
mkdir -p $exp_path $res_path
|
| 16 |
+
|
| 17 |
+
datasets="xsum squad writing"
|
| 18 |
+
source_models="gpt2-xl opt-2.7b gpt-neo-2.7B"
|
| 19 |
+
|
| 20 |
+
echo `date`, Evaluate tuning parameter n_base:
|
| 21 |
+
n_bases=( 4 8 16 32 64 )
|
| 22 |
+
for N in "${n_bases[@]}"; do
|
| 23 |
+
for D in $datasets; do
|
| 24 |
+
# build train_dataset as the other two datasets joined by '&'
|
| 25 |
+
train_parts=()
|
| 26 |
+
for d in $datasets; do
|
| 27 |
+
if [[ ${d} != ${D} ]]; then
|
| 28 |
+
train_parts+=("$d")
|
| 29 |
+
fi
|
| 30 |
+
done
|
| 31 |
+
|
| 32 |
+
for M in $source_models; do
|
| 33 |
+
train_dataset="${data_path}/${train_parts[0]}_${M}&${data_path}/${train_parts[1]}_${M}"
|
| 34 |
+
echo `date`, Evaluating StatsDetectGPT on ${D}_${M} with "$N" bases ...
|
| 35 |
+
|
| 36 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M --scoring_model_name $M --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}_base"$N" --config "{\"start\": -32, \"end\": 0, \"n_bases\": $N, \"spline_order\": 2}"
|
| 37 |
+
done
|
| 38 |
+
done
|
| 39 |
+
done
|
| 40 |
+
|
| 41 |
+
echo `date`, Evaluate tuning parameter spline_order:
|
| 42 |
+
spline_orders=( 1 2 3 4 )
|
| 43 |
+
for N in "${spline_orders[@]}"; do
|
| 44 |
+
for D in $datasets; do
|
| 45 |
+
# build train_dataset as the other two datasets joined by '&'
|
| 46 |
+
train_parts=()
|
| 47 |
+
for d in $datasets; do
|
| 48 |
+
if [[ ${d} != ${D} ]]; then
|
| 49 |
+
train_parts+=("$d")
|
| 50 |
+
fi
|
| 51 |
+
done
|
| 52 |
+
|
| 53 |
+
for M in $source_models; do
|
| 54 |
+
train_dataset="${data_path}/${train_parts[0]}_${M}&${data_path}/${train_parts[1]}_${M}"
|
| 55 |
+
echo `date`, Evaluating StatsDetectGPT on ${D}_${M} with "$N" bases ...
|
| 56 |
+
|
| 57 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M --scoring_model_name $M --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}_order"$N" --config "{\"start\": -32, \"end\": 0, \"n_bases\": 16, \"spline_order\": $N}"
|
| 58 |
+
done
|
| 59 |
+
done
|
| 60 |
+
done
|
exp_variance.sh
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Jin Zhu.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# setup the environment
|
| 8 |
+
echo `date`, Setup the environment ...
|
| 9 |
+
set -e # exit if error
|
| 10 |
+
|
| 11 |
+
# prepare folders
|
| 12 |
+
exp_path=exp_variance
|
| 13 |
+
data_path=$exp_path/data
|
| 14 |
+
res_path=$exp_path/results
|
| 15 |
+
|
| 16 |
+
mkdir -p $exp_path $data_path $res_path
|
| 17 |
+
|
| 18 |
+
datasets="xsum squad writing"
|
| 19 |
+
# source_models="gpt2-xl opt-2.7b gpt-neo-2.7B gpt-j-6B gpt-neox-20b"
|
| 20 |
+
source_models="gpt2-xl qwen-7b"
|
| 21 |
+
|
| 22 |
+
# preparing dataset
|
| 23 |
+
for D in $datasets; do
|
| 24 |
+
for M in $source_models; do
|
| 25 |
+
echo `date`, Preparing dataset ${D}_${M} ...
|
| 26 |
+
python scripts/data_builder.py --dataset $D --n_samples 200 --base_model_name $M --output_file $data_path/${D}_${M} --max_length=500 --batch_size=10 --n_prompts=1 --do_exact_cond_prob
|
| 27 |
+
done
|
| 28 |
+
done
|
| 29 |
+
|
| 30 |
+
# White-box Setting
|
| 31 |
+
echo `date`, Evaluate models in the white-box setting:
|
| 32 |
+
|
| 33 |
+
# evaluate AdaDetectGPT
|
| 34 |
+
for D in $datasets; do
|
| 35 |
+
# build train_dataset as the other two datasets joined by '&'
|
| 36 |
+
train_parts=()
|
| 37 |
+
for d in $datasets; do
|
| 38 |
+
if [[ ${d} != ${D} ]]; then
|
| 39 |
+
train_parts+=("$d")
|
| 40 |
+
fi
|
| 41 |
+
done
|
| 42 |
+
for M in $source_models; do
|
| 43 |
+
train_dataset="${data_path}/${train_parts[0]}_${M}&${data_path}/${train_parts[1]}_${M}"
|
| 44 |
+
# python scripts/verify_var.py --sampling_model_name $M --scoring_model_name $M --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M} --w_func='identity'
|
| 45 |
+
# python scripts/verify_var.py --sampling_model_name $M --scoring_model_name $M --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M} --w_func='bspline'
|
| 46 |
+
python scripts/verify_var.py --sampling_model_name $M --scoring_model_name $M --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M} --w_func='bspline' --compute_text 'llm'
|
| 47 |
+
done
|
| 48 |
+
done
|
| 49 |
+
|
exp_whitebox.sh
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Jin Zhu.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# setup the environment
|
| 8 |
+
echo `date`, Setup the environment ...
|
| 9 |
+
set -e # exit if error
|
| 10 |
+
|
| 11 |
+
# prepare folders
|
| 12 |
+
exp_path=exp_main
|
| 13 |
+
data_path=$exp_path/data
|
| 14 |
+
res_path=$exp_path/results
|
| 15 |
+
mkdir -p $exp_path $data_path $res_path
|
| 16 |
+
|
| 17 |
+
datasets="xsum squad writing"
|
| 18 |
+
source_models="gpt2-xl opt-2.7b gpt-neo-2.7B gpt-j-6B gpt-neox-20b"
|
| 19 |
+
|
| 20 |
+
# preparing dataset
|
| 21 |
+
for D in $datasets; do
|
| 22 |
+
for M in $source_models; do
|
| 23 |
+
echo `date`, Preparing dataset ${D}_${M} ...
|
| 24 |
+
python scripts/data_builder.py --dataset $D --n_samples 500 --base_model_name $M --output_file $data_path/${D}_${M}
|
| 25 |
+
done
|
| 26 |
+
done
|
| 27 |
+
|
| 28 |
+
# White-box Setting
|
| 29 |
+
echo `date`, Evaluate models in the white-box setting:
|
| 30 |
+
|
| 31 |
+
# evaluate AdaDetectGPT
|
| 32 |
+
for D in $datasets; do
|
| 33 |
+
# build train_dataset as the other two datasets joined by '&'
|
| 34 |
+
train_parts=()
|
| 35 |
+
for d in $datasets; do
|
| 36 |
+
if [[ ${d} != ${D} ]]; then
|
| 37 |
+
train_parts+=("$d")
|
| 38 |
+
fi
|
| 39 |
+
done
|
| 40 |
+
|
| 41 |
+
for M in $source_models; do
|
| 42 |
+
echo `date`, Evaluating AdaDetectGPT on ${D}_${M} ...
|
| 43 |
+
train_dataset="${data_path}/${train_parts[0]}_${M}&${data_path}/${train_parts[1]}_${M}"
|
| 44 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M --scoring_model_name $M --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 45 |
+
done
|
| 46 |
+
done
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# evaluate Fast-DetectGPT and fast baselines
|
| 50 |
+
for D in $datasets; do
|
| 51 |
+
for M in $source_models; do
|
| 52 |
+
echo `date`, Evaluating Fast-DetectGPT on ${D}_${M} ...
|
| 53 |
+
python scripts/detect_gpt_fast.py --sampling_model_name $M --scoring_model_name $M --dataset $D \
|
| 54 |
+
--dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 55 |
+
|
| 56 |
+
echo `date`, Evaluating baseline methods on ${D}_${M} ...
|
| 57 |
+
python scripts/detect_gltr.py --scoring_model_name $M --dataset $D \
|
| 58 |
+
--dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 59 |
+
done
|
| 60 |
+
done
|
| 61 |
+
|
| 62 |
+
# evaluate DNA-GPT
|
| 63 |
+
for D in $datasets; do
|
| 64 |
+
for M in $source_models; do
|
| 65 |
+
echo `date`, Evaluating DNA-GPT on ${D}_${M} ...
|
| 66 |
+
python scripts/detect_gpt_dna.py --base_model_name $M --dataset $D \
|
| 67 |
+
--dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 68 |
+
done
|
| 69 |
+
done
|
| 70 |
+
|
| 71 |
+
# evaluate DetectGPT and its improvement DetectLLM
|
| 72 |
+
for D in $datasets; do
|
| 73 |
+
for M in $source_models; do
|
| 74 |
+
echo `date`, Evaluating DetectGPT on ${D}_${M} ...
|
| 75 |
+
python scripts/detect_gpt.py --scoring_model_name $M --mask_filling_model_name t5-3b --n_perturbations 100 --dataset $D \
|
| 76 |
+
--dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 77 |
+
# we leverage DetectGPT to generate the perturbations
|
| 78 |
+
echo `date`, Evaluating DetectLLM methods on ${D}_${M} ...
|
| 79 |
+
python scripts/detect_llm.py --scoring_model_name $M --dataset $D \
|
| 80 |
+
--dataset_file $data_path/${D}_${M}.t5-3b.perturbation_100 --output_file $res_path/${D}_${M}
|
| 81 |
+
done
|
| 82 |
+
done
|
exp_whitebox_advanced.sh
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Copyright (c) Jin Zhu.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# setup the environment
|
| 8 |
+
echo `date`, Setup the environment ...
|
| 9 |
+
set -e # exit if error
|
| 10 |
+
|
| 11 |
+
# prepare folders
|
| 12 |
+
exp_path=exp_main
|
| 13 |
+
data_path=$exp_path/data
|
| 14 |
+
res_path=$exp_path/results
|
| 15 |
+
mkdir -p $exp_path $data_path $res_path
|
| 16 |
+
|
| 17 |
+
datasets="xsum squad writing yelp essay"
|
| 18 |
+
source_models="qwen-7b mistralai-7b llama3-8b"
|
| 19 |
+
|
| 20 |
+
## preparing dataset
|
| 21 |
+
for D in $datasets; do
|
| 22 |
+
for M in $source_models; do
|
| 23 |
+
echo `date`, Preparing dataset ${D}_${M} ...
|
| 24 |
+
python scripts/data_builder.py --dataset $D --n_samples 500 --base_model_name $M --output_file $data_path/${D}_${M}
|
| 25 |
+
done
|
| 26 |
+
done
|
| 27 |
+
|
| 28 |
+
# White-box Setting
|
| 29 |
+
echo `date`, Evaluate models in the white-box setting:
|
| 30 |
+
|
| 31 |
+
# evaluate AdaDetectGPT, Fast-DetectGPT, Fast baselines
|
| 32 |
+
for D in $datasets; do
|
| 33 |
+
# build train_dataset as the other two datasets joined by '&'
|
| 34 |
+
train_parts=()
|
| 35 |
+
for d in $datasets; do
|
| 36 |
+
if [[ ${d} != ${D} ]]; then
|
| 37 |
+
train_parts+=("$d")
|
| 38 |
+
fi
|
| 39 |
+
done
|
| 40 |
+
|
| 41 |
+
for M in $source_models; do
|
| 42 |
+
echo `date`, Evaluating StatsDetectGPT/FastDetectGPT on ${D}_${M} ...
|
| 43 |
+
|
| 44 |
+
python scripts/detect_gpt_fast.py --sampling_model_name $M --scoring_model_name $M --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M} --discrepancy_analytic
|
| 45 |
+
|
| 46 |
+
if [[ "$D" == "yale" || "$D" == "essay" ]]; then
|
| 47 |
+
train_dataset="${data_path}/squad_${M}&${data_path}/xsum_${M}"
|
| 48 |
+
else
|
| 49 |
+
train_dataset="${data_path}/${train_parts[0]}_${M}&${data_path}/${train_parts[1]}_${M}"
|
| 50 |
+
fi
|
| 51 |
+
python scripts/detect_gpt_ada.py --sampling_model_name $M --scoring_model_name $M --dataset $D --train_dataset "$train_dataset" --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 52 |
+
|
| 53 |
+
echo `date`, Evaluating baseline methods on ${D}_${M} ...
|
| 54 |
+
python scripts/detect_gltr.py --scoring_model_name $M --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 55 |
+
done
|
| 56 |
+
done
|
| 57 |
+
|
| 58 |
+
# evaluate DetectGPT and its improvement DetectLLM
|
| 59 |
+
for D in $datasets; do
|
| 60 |
+
for M in $source_models; do
|
| 61 |
+
echo `date`, Evaluating DetectGPT on ${D}_${M} ...
|
| 62 |
+
python scripts/detect_gpt.py --scoring_model_name $M --mask_filling_model_name t5-3b --n_perturbations 100 --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 63 |
+
echo `date`, Evaluating DetectLLM methods on ${D}_${M} ...
|
| 64 |
+
python scripts/detect_llm.py --scoring_model_name $M --dataset $D --dataset_file $data_path/${D}_${M}.t5-3b.perturbation_100 --output_file $res_path/${D}_${M}
|
| 65 |
+
done
|
| 66 |
+
done
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# evaluate Binoculars
|
| 70 |
+
for D in $datasets; do
|
| 71 |
+
for M in $source_models; do
|
| 72 |
+
echo `date`, Evaluating DNA-GPT on ${D}_${M} ...
|
| 73 |
+
python scripts/detect_bino.py --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 74 |
+
done
|
| 75 |
+
done
|
| 76 |
+
|
| 77 |
+
# evaluate DNA-GPT
|
| 78 |
+
for D in $datasets; do
|
| 79 |
+
for M in $source_models; do
|
| 80 |
+
echo `date`, Evaluating DNA-GPT on ${D}_${M} ...
|
| 81 |
+
python scripts/detect_gpt_dna.py --base_model_name $M --dataset $D --dataset_file $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 82 |
+
done
|
| 83 |
+
done
|
| 84 |
+
|
| 85 |
+
# evaluate Text-Fluoroscopy
|
| 86 |
+
for D in $datasets; do
|
| 87 |
+
train_parts=()
|
| 88 |
+
for d in $datasets; do
|
| 89 |
+
if [[ ${d} != ${D} ]]; then
|
| 90 |
+
train_parts+=("$d")
|
| 91 |
+
fi
|
| 92 |
+
done
|
| 93 |
+
for M in $source_models; do
|
| 94 |
+
echo `date`, Evaluating Text-Fluoroscopy on ${D}_${M} ...
|
| 95 |
+
train_dataset="${data_path}/${train_parts[0]}_${M}"
|
| 96 |
+
valid_dataset="${data_path}/${train_parts[1]}_${M}"
|
| 97 |
+
python scripts/detect_fluoroscopy.py \
|
| 98 |
+
--train_dataset $train_dataset --valid_dataset $valid_dataset \
|
| 99 |
+
--test_dataset $data_path/${D}_${M} \
|
| 100 |
+
--output_file=$res_path/${D}_${M}
|
| 101 |
+
done
|
| 102 |
+
done
|
| 103 |
+
|
| 104 |
+
# evaluate RADAR
|
| 105 |
+
for D in $datasets; do
|
| 106 |
+
for M in $source_models; do
|
| 107 |
+
echo `date`, Evaluating RADAR on ${D}_${M} ...
|
| 108 |
+
python scripts/detect_radar.py --dataset $data_path/${D}_${M} --output_file $res_path/${D}_${M}
|
| 109 |
+
done
|
| 110 |
+
done
|
| 111 |
+
|
| 112 |
+
# evaluate ImBD
|
| 113 |
+
for D in $datasets; do
|
| 114 |
+
train_parts=()
|
| 115 |
+
for d in $datasets; do
|
| 116 |
+
if [[ ${d} != ${D} ]]; then
|
| 117 |
+
train_parts+=("$d")
|
| 118 |
+
fi
|
| 119 |
+
done
|
| 120 |
+
for M in $source_models; do
|
| 121 |
+
echo `date`, Evaluating ImBD on ${D}_${M} ...
|
| 122 |
+
train_dataset="${data_path}/${train_parts[0]}_${M}&${data_path}/${train_parts[1]}_${M}"
|
| 123 |
+
python scripts/detect_ImBD.py \
|
| 124 |
+
--train_dataset $train_dataset --base_model $M \
|
| 125 |
+
--eval_dataset=$data_path/${D}_${M} \
|
| 126 |
+
--eval_after_train \
|
| 127 |
+
--output_file=$res_path/${D}_${M}
|
| 128 |
+
done
|
| 129 |
+
done
|
| 130 |
+
|
| 131 |
+
# evaluate BiScope
|
| 132 |
+
for D in $datasets; do
|
| 133 |
+
train_parts=()
|
| 134 |
+
for d in $datasets; do
|
| 135 |
+
if [[ ${d} != ${D} ]]; then
|
| 136 |
+
train_parts+=("$d")
|
| 137 |
+
fi
|
| 138 |
+
done
|
| 139 |
+
for M in $source_models; do
|
| 140 |
+
echo `date`, Evaluating BiScope on ${D}_${M} ...
|
| 141 |
+
train_dataset="${train_parts[0]}_${M}.raw_data.json&${train_parts[1]}_${M}.raw_data.json"
|
| 142 |
+
python scripts/detect_biscope.py --train_dataset $train_dataset --test_dataset ${D}_${M}.raw_data.json --output_file $res_path/${D}_${M}
|
| 143 |
+
done
|
| 144 |
+
done
|
figure/AdaDetectGPT.png
ADDED
|
Git LFS Details
|
input.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
The history of urban transportation reflects the changing needs of society and the development of new technologies. In early cities, most people relied on walking or animal-powered vehicles to move from one place to another. As populations grew, these methods became less efficient, leading to the introduction of trams, railways, and later automobiles. In the modern era, transportation systems have become increasingly complex, integrating buses, subways, ride-sharing services, and electric mobility options. This evolution demonstrates how infrastructure adapts to economic growth, environmental pressures, and the demand for convenience.
|
miner_lab/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Miner lab: dataset QA, per-sample scoring, fusion, subnet-style metrics.
|
miner_lab/ada_scorer.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load AdaDetectGPT once and score raw text (for subnet miner integration)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import sys
|
| 8 |
+
from argparse import Namespace
|
| 9 |
+
from typing import Optional
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
from torch import nn
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _ensure_scripts_path(scripts_dir: str) -> None:
|
| 17 |
+
scripts_dir = os.path.abspath(scripts_dir)
|
| 18 |
+
if scripts_dir not in sys.path:
|
| 19 |
+
sys.path.insert(0, scripts_dir)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class AdaScorer:
|
| 23 |
+
"""
|
| 24 |
+
Runs the same criterion as scripts/run_ada_jsonl.py for a single text.
|
| 25 |
+
`scripts_dir` must point to AdaDetectGPT `scripts/` (contains detect_gpt_ada.py, model.py, ...).
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
scripts_dir: str,
|
| 31 |
+
device_str: str,
|
| 32 |
+
cache_dir: str = "./cache",
|
| 33 |
+
scoring_model_name: str = "gpt2-xl",
|
| 34 |
+
sampling_model_name: str = "gpt2-xl",
|
| 35 |
+
burn_in: float = 0.0,
|
| 36 |
+
w_func: str = "pretrained",
|
| 37 |
+
config_json: Optional[dict] = None,
|
| 38 |
+
train_dataset: str = "./exp_main/data/xsum_gpt2-xl&./exp_main/data/writing_gpt2-xl",
|
| 39 |
+
seed: int = 2025,
|
| 40 |
+
):
|
| 41 |
+
_ensure_scripts_path(scripts_dir)
|
| 42 |
+
from detect_gpt_ada import get_classification_stat # noqa: WPS433
|
| 43 |
+
from model import load_model, load_tokenizer, model_max_length # noqa: WPS433
|
| 44 |
+
from nuisance_func import BSplineTwoSample # noqa: WPS433
|
| 45 |
+
from nuisance_func_human import BSplineTheory # noqa: WPS433
|
| 46 |
+
from utils import load_training_data, separated_string # noqa: WPS433
|
| 47 |
+
|
| 48 |
+
self._get_classification_stat = get_classification_stat
|
| 49 |
+
self.device_str = device_str
|
| 50 |
+
self.device = torch.device(device_str)
|
| 51 |
+
|
| 52 |
+
if config_json is None:
|
| 53 |
+
config_json = {"start": -32, "end": 0, "n_bases": 7, "spline_order": 2, "intercept": 1}
|
| 54 |
+
|
| 55 |
+
td = train_dataset
|
| 56 |
+
if isinstance(td, str):
|
| 57 |
+
td = separated_string(td) if "&" in td else [td]
|
| 58 |
+
args = Namespace(
|
| 59 |
+
device=device_str,
|
| 60 |
+
config=config_json,
|
| 61 |
+
train_dataset=td,
|
| 62 |
+
w_func=w_func,
|
| 63 |
+
burn_in=burn_in,
|
| 64 |
+
seed=seed,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
scoring_tokenizer = load_tokenizer(scoring_model_name, cache_dir)
|
| 68 |
+
scoring_model = load_model(scoring_model_name, device_str, cache_dir)
|
| 69 |
+
scoring_model.eval()
|
| 70 |
+
score_max = model_max_length(scoring_model)
|
| 71 |
+
if sampling_model_name != scoring_model_name:
|
| 72 |
+
sampling_tokenizer = load_tokenizer(sampling_model_name, cache_dir)
|
| 73 |
+
sampling_model = load_model(sampling_model_name, device_str, cache_dir)
|
| 74 |
+
sampling_model.eval()
|
| 75 |
+
encode_max = min(score_max, model_max_length(sampling_model))
|
| 76 |
+
else:
|
| 77 |
+
sampling_tokenizer = scoring_tokenizer
|
| 78 |
+
sampling_model = scoring_model
|
| 79 |
+
encode_max = score_max
|
| 80 |
+
|
| 81 |
+
w_func_mod, _beta = self._build_w_func(
|
| 82 |
+
args, BSplineTwoSample, BSplineTheory, load_training_data, scoring_tokenizer, scoring_model, score_max
|
| 83 |
+
)
|
| 84 |
+
shift_value = torch.zeros(1, device=self.device)
|
| 85 |
+
|
| 86 |
+
if burn_in < 1.0:
|
| 87 |
+
self._burn_in_template = None
|
| 88 |
+
else:
|
| 89 |
+
self._burn_in_template = int(burn_in)
|
| 90 |
+
|
| 91 |
+
random.seed(seed)
|
| 92 |
+
torch.manual_seed(seed)
|
| 93 |
+
np.random.seed(seed)
|
| 94 |
+
|
| 95 |
+
self.scoring_tokenizer = scoring_tokenizer
|
| 96 |
+
self.scoring_model = scoring_model
|
| 97 |
+
self.sampling_tokenizer = sampling_tokenizer
|
| 98 |
+
self.sampling_model = sampling_model
|
| 99 |
+
self.encode_max = encode_max
|
| 100 |
+
self.w_func = w_func_mod
|
| 101 |
+
self.shift_value = shift_value
|
| 102 |
+
self.burn_in = burn_in
|
| 103 |
+
|
| 104 |
+
@staticmethod
|
| 105 |
+
def _build_w_func(args, BSplineTwoSample, BSplineTheory, load_training_data, scoring_tokenizer, scoring_model, score_max):
|
| 106 |
+
if args.w_func == "identity":
|
| 107 |
+
return nn.Identity(), None
|
| 108 |
+
|
| 109 |
+
bspline_args = args.config
|
| 110 |
+
device = torch.device(args.device)
|
| 111 |
+
|
| 112 |
+
if args.w_func == "pretrained":
|
| 113 |
+
w_func = BSplineTwoSample(bspline_args, device)
|
| 114 |
+
w_func.beta_hat = torch.tensor(
|
| 115 |
+
[0.0, -0.011333, -0.037667, -0.056667, -0.281667, -0.592, 0.157833, 0.727333],
|
| 116 |
+
device=device,
|
| 117 |
+
)
|
| 118 |
+
elif args.w_func == "bspline":
|
| 119 |
+
train_data = load_training_data(args.train_dataset)
|
| 120 |
+
human_token_list = [
|
| 121 |
+
scoring_tokenizer(
|
| 122 |
+
x,
|
| 123 |
+
return_tensors="pt",
|
| 124 |
+
padding=True,
|
| 125 |
+
return_token_type_ids=False,
|
| 126 |
+
truncation=True,
|
| 127 |
+
max_length=score_max,
|
| 128 |
+
).to(device)
|
| 129 |
+
for x in train_data["original"]
|
| 130 |
+
]
|
| 131 |
+
machine_token_list = [
|
| 132 |
+
scoring_tokenizer(
|
| 133 |
+
x,
|
| 134 |
+
return_tensors="pt",
|
| 135 |
+
padding=True,
|
| 136 |
+
return_token_type_ids=False,
|
| 137 |
+
truncation=True,
|
| 138 |
+
max_length=score_max,
|
| 139 |
+
).to(device)
|
| 140 |
+
for x in train_data["sampled"]
|
| 141 |
+
]
|
| 142 |
+
w_func = BSplineTwoSample(bspline_args, device)
|
| 143 |
+
w_func.fit(human_token_list, machine_token_list, scoring_model, args)
|
| 144 |
+
elif args.w_func == "bspline_theory":
|
| 145 |
+
train_data = load_training_data(args.train_dataset)
|
| 146 |
+
human_token_list = [
|
| 147 |
+
scoring_tokenizer(
|
| 148 |
+
x,
|
| 149 |
+
return_tensors="pt",
|
| 150 |
+
padding=True,
|
| 151 |
+
return_token_type_ids=False,
|
| 152 |
+
truncation=True,
|
| 153 |
+
max_length=score_max,
|
| 154 |
+
).to(device)
|
| 155 |
+
for x in train_data["original"]
|
| 156 |
+
]
|
| 157 |
+
w_func = BSplineTheory(bspline_args, machine_text=False)
|
| 158 |
+
w_func.fit(human_token_list, None, scoring_model, args)
|
| 159 |
+
else:
|
| 160 |
+
raise ValueError(f"Unknown w_func {args.w_func}")
|
| 161 |
+
|
| 162 |
+
return w_func, w_func.beta_hat.detach().cpu().tolist()
|
| 163 |
+
|
| 164 |
+
def _crit_one(self, text: str, burn_in_num: int) -> float:
|
| 165 |
+
tokenized = self.scoring_tokenizer(
|
| 166 |
+
text,
|
| 167 |
+
return_tensors="pt",
|
| 168 |
+
padding=True,
|
| 169 |
+
return_token_type_ids=False,
|
| 170 |
+
truncation=True,
|
| 171 |
+
max_length=self.encode_max,
|
| 172 |
+
).to(self.device)
|
| 173 |
+
labels = tokenized.input_ids[:, 1:]
|
| 174 |
+
with torch.no_grad():
|
| 175 |
+
logits_score = self.scoring_model(**tokenized).logits[:, :-1]
|
| 176 |
+
if self.sampling_model is self.scoring_model:
|
| 177 |
+
logits_ref = logits_score
|
| 178 |
+
else:
|
| 179 |
+
tokenized_s = self.sampling_tokenizer(
|
| 180 |
+
text,
|
| 181 |
+
return_tensors="pt",
|
| 182 |
+
padding=True,
|
| 183 |
+
return_token_type_ids=False,
|
| 184 |
+
truncation=True,
|
| 185 |
+
max_length=self.encode_max,
|
| 186 |
+
).to(self.device)
|
| 187 |
+
assert torch.all(tokenized_s.input_ids[:, 1:] == labels), "Tokenizer mismatch for sampling model."
|
| 188 |
+
logits_ref = self.sampling_model(**tokenized_s).logits[:, :-1]
|
| 189 |
+
if burn_in_num > 0:
|
| 190 |
+
logits_ref = logits_ref[:, burn_in_num:, :]
|
| 191 |
+
logits_score = logits_score[:, burn_in_num:, :]
|
| 192 |
+
labels = labels[:, burn_in_num:]
|
| 193 |
+
return self._get_classification_stat(logits_ref, logits_score, labels, self.w_func, self.shift_value)
|
| 194 |
+
|
| 195 |
+
def score_text(self, text: str) -> float:
|
| 196 |
+
labels_tok = self.scoring_tokenizer(
|
| 197 |
+
text,
|
| 198 |
+
return_tensors="pt",
|
| 199 |
+
padding=True,
|
| 200 |
+
return_token_type_ids=False,
|
| 201 |
+
truncation=True,
|
| 202 |
+
max_length=self.encode_max,
|
| 203 |
+
).to(self.device)
|
| 204 |
+
lab = labels_tok.input_ids[:, 1:]
|
| 205 |
+
if self.burn_in < 1.0:
|
| 206 |
+
burn_in_num = int(float(self.burn_in) * lab.size(-1))
|
| 207 |
+
else:
|
| 208 |
+
burn_in_num = self._burn_in_template
|
| 209 |
+
return float(self._crit_one(text, burn_in_num))
|
miner_lab/fusion_predict.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load fusion_artifact.json and score one merged row (dict with text + optional scores)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from typing import Dict, List
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from miner_lab.text_features import count_sentences, count_words
|
| 11 |
+
from miner_lab.weighted_fusion import fusion_prob_one
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_artifact(path: str) -> Dict[str, Any]:
|
| 15 |
+
with open(path, encoding="utf-8") as f:
|
| 16 |
+
return json.load(f)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def row_to_vector(row: dict, feature_names: List[str], medians: Dict[str, float]) -> np.ndarray:
|
| 20 |
+
vec: List[float] = []
|
| 21 |
+
for f in feature_names:
|
| 22 |
+
if f == "num_words":
|
| 23 |
+
vec.append(float(count_words(row.get("text", ""))))
|
| 24 |
+
elif f == "num_sentences":
|
| 25 |
+
vec.append(float(count_sentences(row.get("text", ""))))
|
| 26 |
+
else:
|
| 27 |
+
v = row.get(f)
|
| 28 |
+
try:
|
| 29 |
+
vf = float(v)
|
| 30 |
+
if not np.isfinite(vf):
|
| 31 |
+
vf = float(medians.get(f, 0.0))
|
| 32 |
+
except (TypeError, ValueError):
|
| 33 |
+
vf = float(medians.get(f, 0.0))
|
| 34 |
+
vec.append(vf)
|
| 35 |
+
return np.asarray(vec, dtype=np.float64).reshape(1, -1)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def fusion_probability(artifact: Dict[str, Any], row: dict) -> float:
|
| 39 |
+
mode = artifact.get("fusion_mode", "logistic")
|
| 40 |
+
if mode == "weighted":
|
| 41 |
+
keys = artifact["score_keys"]
|
| 42 |
+
medians = {k: float(v) for k, v in artifact["medians"].items()}
|
| 43 |
+
norm_params = artifact["norm_params"]
|
| 44 |
+
weights = artifact["branch_weights"]
|
| 45 |
+
nm = artifact.get("norm_method", "minmax")
|
| 46 |
+
return fusion_prob_one(row, keys, medians, norm_params, weights, nm)
|
| 47 |
+
|
| 48 |
+
names = artifact["feature_names"]
|
| 49 |
+
medians = {k: float(v) for k, v in artifact["medians"].items()}
|
| 50 |
+
x = row_to_vector(row, names, medians)
|
| 51 |
+
mean = np.asarray(artifact["scaler_mean"], dtype=np.float64)
|
| 52 |
+
scale = np.asarray(artifact["scaler_scale"], dtype=np.float64)
|
| 53 |
+
scale = np.where(scale < 1e-12, 1.0, scale)
|
| 54 |
+
xs = (x - mean) / scale
|
| 55 |
+
w = np.asarray(artifact["lr_coef"], dtype=np.float64).reshape(1, -1)
|
| 56 |
+
b = float(artifact["lr_intercept"])
|
| 57 |
+
logit = (xs @ w.T).ravel() + b
|
| 58 |
+
prob = 1.0 / (1.0 + np.exp(-logit))
|
| 59 |
+
return float(prob.ravel()[0])
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def classify_row(artifact_path: str, row: dict, threshold: float | None = None) -> tuple[float, int]:
|
| 63 |
+
art = load_artifact(artifact_path)
|
| 64 |
+
p = fusion_probability(art, row)
|
| 65 |
+
t = float(art["best_threshold"]) if threshold is None else float(threshold)
|
| 66 |
+
return p, int(p >= t)
|
miner_lab/l2d_scorer.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L2D (AdaDist) scoring — same statistic as L2D-main AdaDist forward (|logp − logp(rewrite)|), first rewrite only."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import gc
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
from argparse import Namespace
|
| 10 |
+
from typing import List, Optional, Sequence, Type
|
| 11 |
+
|
| 12 |
+
# L2D reference uses these guards when loading rewrite models
|
| 13 |
+
os.environ.setdefault("TORCH_COMPILE_DISABLE", "1")
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
torch._dynamo.config.disable = True
|
| 19 |
+
except Exception:
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
_PROMPT_GEMMA = (
|
| 23 |
+
'You are a rewriting expert and you would rewrite the text without missing the original details. '
|
| 24 |
+
'Return ONLY the rewritten version. Do not explain changes, do not give multiple options, '
|
| 25 |
+
'and do not add commentary. \n\n Original text: "{}" Here is the rewritten version: \n\n'
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _rewrite_model_hf_id(short_name: str) -> str:
|
| 30 |
+
aliases = {
|
| 31 |
+
"gemma-9b-instruct": "google/gemma-2-9b-it",
|
| 32 |
+
"gemma-9b": "google/gemma-2-9b",
|
| 33 |
+
"qwen-4b": "Qwen/Qwen3-4B",
|
| 34 |
+
}
|
| 35 |
+
return aliases.get(short_name, short_name)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class _RewriteSampler:
|
| 39 |
+
"""
|
| 40 |
+
Same behavior as L2D-main/scripts/rewrite_machine.PrefixSampler + get_regen_samples,
|
| 41 |
+
without importing L2D `scripts/model.py` (that file calls huggingface_hub.login).
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(self, args: Namespace):
|
| 45 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 46 |
+
|
| 47 |
+
self.args = args
|
| 48 |
+
self.rewrite_model = args.rewrite_model
|
| 49 |
+
hf_id = _rewrite_model_hf_id(args.rewrite_model)
|
| 50 |
+
self.base_tokenizer = AutoTokenizer.from_pretrained(hf_id, cache_dir=args.cache_dir)
|
| 51 |
+
if self.base_tokenizer.pad_token_id is None:
|
| 52 |
+
self.base_tokenizer.pad_token_id = self.base_tokenizer.eos_token_id
|
| 53 |
+
|
| 54 |
+
dev = args.device if isinstance(args.device, torch.device) else torch.device(args.device)
|
| 55 |
+
use_4bit = dev.type == "cuda" and os.environ.get("L2D_LOAD_4BIT", "").strip().lower() in (
|
| 56 |
+
"1",
|
| 57 |
+
"true",
|
| 58 |
+
"yes",
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
if use_4bit:
|
| 62 |
+
print("Rewrite LM: 4-bit (same as --load_4bit / L2D_LOAD_4BIT) to avoid a second full fp16 9B on VRAM.")
|
| 63 |
+
bnb = BitsAndBytesConfig(
|
| 64 |
+
load_in_4bit=True,
|
| 65 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 66 |
+
bnb_4bit_use_double_quant=True,
|
| 67 |
+
bnb_4bit_quant_type="nf4",
|
| 68 |
+
)
|
| 69 |
+
self.base_model = AutoModelForCausalLM.from_pretrained(
|
| 70 |
+
hf_id,
|
| 71 |
+
cache_dir=args.cache_dir,
|
| 72 |
+
quantization_config=bnb,
|
| 73 |
+
device_map={"": 0},
|
| 74 |
+
)
|
| 75 |
+
else:
|
| 76 |
+
kwargs = {}
|
| 77 |
+
if "gemma" in args.rewrite_model.lower():
|
| 78 |
+
kwargs["torch_dtype"] = torch.float16
|
| 79 |
+
self.base_model = AutoModelForCausalLM.from_pretrained(
|
| 80 |
+
hf_id, cache_dir=args.cache_dir, **kwargs
|
| 81 |
+
)
|
| 82 |
+
self.base_model.to(dev)
|
| 83 |
+
self.base_model.eval()
|
| 84 |
+
if "gemma" in args.rewrite_model.lower():
|
| 85 |
+
self.prompt = _PROMPT_GEMMA
|
| 86 |
+
else:
|
| 87 |
+
self.prompt = _PROMPT_GEMMA
|
| 88 |
+
|
| 89 |
+
def _sample_rewrite_text_from_model(self, texts: Sequence[str]) -> List[str]:
|
| 90 |
+
enc = self.base_tokenizer(
|
| 91 |
+
list(texts), return_tensors="pt", padding=True, return_token_type_ids=False
|
| 92 |
+
)
|
| 93 |
+
n_tok = enc["input_ids"].shape[1]
|
| 94 |
+
sampling_kwargs: dict = {"temperature": self.args.temperature, "do_sample": True}
|
| 95 |
+
if getattr(self.args, "do_top_p", False):
|
| 96 |
+
sampling_kwargs["top_p"] = self.args.top_p
|
| 97 |
+
elif getattr(self.args, "do_top_k", False):
|
| 98 |
+
sampling_kwargs["top_k"] = self.args.top_k
|
| 99 |
+
sampling_kwargs["min_new_tokens"] = int(0.5 * n_tok)
|
| 100 |
+
sampling_kwargs["max_new_tokens"] = int(1.5 * n_tok)
|
| 101 |
+
sampling_kwargs["eos_token_id"] = self.base_tokenizer.eos_token_id
|
| 102 |
+
sampling_kwargs["pad_token_id"] = self.base_tokenizer.eos_token_id
|
| 103 |
+
|
| 104 |
+
if "gemma" in self.rewrite_model.lower():
|
| 105 |
+
prompt_texts = [self.prompt.format(o) for o in texts]
|
| 106 |
+
else:
|
| 107 |
+
prompt_texts = [self.prompt.format(o) for o in texts]
|
| 108 |
+
|
| 109 |
+
rw_dev = getattr(self.base_model, "device", None) or (
|
| 110 |
+
self.args.device if isinstance(self.args.device, torch.device) else torch.device(self.args.device)
|
| 111 |
+
)
|
| 112 |
+
all_encoded = self.base_tokenizer(
|
| 113 |
+
prompt_texts, return_tensors="pt", padding=True, return_token_type_ids=False
|
| 114 |
+
).to(rw_dev)
|
| 115 |
+
prompt_lens = all_encoded["input_ids"].shape[1]
|
| 116 |
+
with torch.no_grad():
|
| 117 |
+
outputs = self.base_model.generate(**all_encoded, **sampling_kwargs)
|
| 118 |
+
gen_ids = outputs[:, prompt_lens:]
|
| 119 |
+
return self.base_tokenizer.batch_decode(gen_ids, skip_special_tokens=True)
|
| 120 |
+
|
| 121 |
+
def generate_samples(self, raw_data: List[str], batch_size: int) -> dict:
|
| 122 |
+
data = {"original": [], "sampled": []}
|
| 123 |
+
assert len(raw_data) % batch_size == 0, "len(raw_data) must divide batch_size"
|
| 124 |
+
n_batch = len(raw_data) // batch_size
|
| 125 |
+
for b in range(n_batch):
|
| 126 |
+
chunk = raw_data[b * batch_size : (b + 1) * batch_size]
|
| 127 |
+
sampled_text = self._sample_rewrite_text_from_model(chunk)
|
| 128 |
+
for o, s in zip(chunk, sampled_text):
|
| 129 |
+
data["original"].append(o)
|
| 130 |
+
data["sampled"].append(s)
|
| 131 |
+
return data
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _get_regen_samples(sampler: _RewriteSampler, text: str) -> List[str]:
|
| 135 |
+
regen = sampler.args.regen_number
|
| 136 |
+
raw = [text] * regen
|
| 137 |
+
max_bs = min(sampler.args.batch_size, regen)
|
| 138 |
+
bs = next((b for b in range(max_bs, 0, -1) if regen % b == 0), 1)
|
| 139 |
+
out = sampler.generate_samples(raw, batch_size=bs)
|
| 140 |
+
return out["sampled"]
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def resolve_l2d_scripts() -> str:
|
| 144 |
+
env = os.environ.get("L2D_SCRIPTS")
|
| 145 |
+
if env:
|
| 146 |
+
p = os.path.abspath(env)
|
| 147 |
+
if os.path.isdir(p) and os.path.isdir(os.path.join(p, "AdaDist")):
|
| 148 |
+
return p
|
| 149 |
+
raise FileNotFoundError(f"L2D_SCRIPTS={env!r} is not a directory containing AdaDist/")
|
| 150 |
+
miner_root = os.path.dirname(os.path.abspath(__file__))
|
| 151 |
+
adadetect_root = os.path.dirname(miner_root)
|
| 152 |
+
workspace = os.path.dirname(adadetect_root)
|
| 153 |
+
candidate = os.path.join(workspace, "L2D-main", "scripts")
|
| 154 |
+
if os.path.isdir(candidate) and os.path.isdir(os.path.join(candidate, "AdaDist")):
|
| 155 |
+
return candidate
|
| 156 |
+
raise FileNotFoundError(
|
| 157 |
+
"Could not find L2D AdaDist code. Place L2D-main next to AdaDetectGPT-main "
|
| 158 |
+
"(same parent folder) or set L2D_SCRIPTS to the path that contains AdaDist/model.py."
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _import_adadist(l2d_scripts: str) -> Type:
|
| 163 |
+
inserted = False
|
| 164 |
+
if l2d_scripts not in sys.path:
|
| 165 |
+
sys.path.insert(0, l2d_scripts)
|
| 166 |
+
inserted = True
|
| 167 |
+
try:
|
| 168 |
+
from AdaDist.model import AdaDist # type: ignore # noqa: WPS433
|
| 169 |
+
|
| 170 |
+
return AdaDist
|
| 171 |
+
finally:
|
| 172 |
+
if inserted:
|
| 173 |
+
try:
|
| 174 |
+
sys.path.remove(l2d_scripts)
|
| 175 |
+
except ValueError:
|
| 176 |
+
pass
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def resolve_l2d_checkpoint(
|
| 180 |
+
from_pretrained: str,
|
| 181 |
+
cache_dir: str,
|
| 182 |
+
) -> str:
|
| 183 |
+
"""Local directory with `scoring_model/`, or download a HuggingFace repo snapshot."""
|
| 184 |
+
fp = os.path.abspath(os.path.expanduser(from_pretrained))
|
| 185 |
+
sm = os.path.join(fp, "scoring_model")
|
| 186 |
+
if os.path.isdir(sm):
|
| 187 |
+
return fp
|
| 188 |
+
try:
|
| 189 |
+
from huggingface_hub import snapshot_download
|
| 190 |
+
except ImportError as e:
|
| 191 |
+
raise FileNotFoundError(
|
| 192 |
+
f"No local checkpoint at {fp!r} (missing scoring_model/). "
|
| 193 |
+
"Install huggingface_hub to use a Hub repo id, or pass a local path."
|
| 194 |
+
) from e
|
| 195 |
+
path = snapshot_download(repo_id=from_pretrained, cache_dir=cache_dir)
|
| 196 |
+
if not os.path.isdir(os.path.join(path, "scoring_model")):
|
| 197 |
+
raise FileNotFoundError(
|
| 198 |
+
f"Resolved checkpoint {path!r} has no scoring_model/ — expected L2D-style layout."
|
| 199 |
+
)
|
| 200 |
+
return path
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
_GATED_MODEL_HELP = (
|
| 204 |
+
"L2D’s AdaDist always loads the Gemma tokenizer (and base weights in __init__) from Hugging Face "
|
| 205 |
+
"before applying local LoRA under scoring_model/. "
|
| 206 |
+
"google/gemma-2-9b-it is gated: open https://huggingface.co/google/gemma-2-9b-it , accept the license, "
|
| 207 |
+
"then run `huggingface-cli login` or set env var HF_TOKEN (or HF_HUB_TOKEN). "
|
| 208 |
+
"The rewrite branch uses the same model id unless you change --rewrite_model."
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class L2DScorer:
|
| 213 |
+
"""
|
| 214 |
+
Loads AdaDist (L2D) and computes per-text scores matching the *original* branch statistic
|
| 215 |
+
in AdaDist.forward: mean(|avg_logp(text) − avg_logp(first rewrite)|), as in L2D-main/engine
|
| 216 |
+
(crit index 1 uses the same tensor).
|
| 217 |
+
|
| 218 |
+
Requires Hugging Face access to Gemma when using default base/rewrite names (gated repo); see _GATED_MODEL_HELP.
|
| 219 |
+
"""
|
| 220 |
+
|
| 221 |
+
def __init__(
|
| 222 |
+
self,
|
| 223 |
+
from_pretrained: str,
|
| 224 |
+
base_model: str = "gemma-9b-instruct",
|
| 225 |
+
device_str: Optional[str] = None,
|
| 226 |
+
cache_dir: str = "./cache",
|
| 227 |
+
rewrite_model: str = "gemma-9b-instruct",
|
| 228 |
+
regen_number: int = 4,
|
| 229 |
+
batch_size: int = 2,
|
| 230 |
+
temperature: float = 0.7,
|
| 231 |
+
do_top_k: bool = False,
|
| 232 |
+
top_k: int = 40,
|
| 233 |
+
do_top_p: bool = False,
|
| 234 |
+
top_p: float = 0.96,
|
| 235 |
+
):
|
| 236 |
+
if device_str is None:
|
| 237 |
+
device_str = "cuda" if torch.cuda.is_available() else "cpu"
|
| 238 |
+
self.device_str = device_str
|
| 239 |
+
self.cache_dir = cache_dir
|
| 240 |
+
self.l2d_scripts = resolve_l2d_scripts()
|
| 241 |
+
load_path = resolve_l2d_checkpoint(from_pretrained, cache_dir)
|
| 242 |
+
AdaDist = _import_adadist(self.l2d_scripts)
|
| 243 |
+
print(f"Loading L2D AdaDist from {load_path} (base_model={base_model})...")
|
| 244 |
+
t0 = time.perf_counter()
|
| 245 |
+
try:
|
| 246 |
+
self.model = AdaDist.from_pretrained(
|
| 247 |
+
load_path,
|
| 248 |
+
model_name=base_model,
|
| 249 |
+
device=device_str,
|
| 250 |
+
cache_dir=cache_dir,
|
| 251 |
+
)
|
| 252 |
+
except OSError as e:
|
| 253 |
+
err = str(e).lower()
|
| 254 |
+
if "gated" in err or "403" in str(e) or "restricted" in err or "authorized" in err:
|
| 255 |
+
raise RuntimeError(_GATED_MODEL_HELP) from e
|
| 256 |
+
raise
|
| 257 |
+
self.model.set_criterion_fn("auc")
|
| 258 |
+
print(f"AdaDist loaded in {time.perf_counter() - t0:.1f}s")
|
| 259 |
+
if device_str == "cuda" and torch.cuda.is_available():
|
| 260 |
+
gc.collect()
|
| 261 |
+
torch.cuda.empty_cache()
|
| 262 |
+
rw_args = Namespace(
|
| 263 |
+
rewrite_model=rewrite_model,
|
| 264 |
+
device=torch.device(device_str),
|
| 265 |
+
cache_dir=cache_dir,
|
| 266 |
+
regen_number=regen_number,
|
| 267 |
+
batch_size=batch_size,
|
| 268 |
+
temperature=temperature,
|
| 269 |
+
do_top_k=do_top_k,
|
| 270 |
+
top_k=top_k,
|
| 271 |
+
do_top_p=do_top_p,
|
| 272 |
+
top_p=top_p,
|
| 273 |
+
)
|
| 274 |
+
print(f"Loading rewrite model {rewrite_model}...")
|
| 275 |
+
try:
|
| 276 |
+
self._rewrite_sampler = _RewriteSampler(rw_args)
|
| 277 |
+
except OSError as e:
|
| 278 |
+
err = str(e).lower()
|
| 279 |
+
if "gated" in err or "403" in str(e) or "restricted" in err or "authorized" in err:
|
| 280 |
+
raise RuntimeError(_GATED_MODEL_HELP) from e
|
| 281 |
+
raise
|
| 282 |
+
|
| 283 |
+
def _scoring_inputs_device(self) -> torch.device:
|
| 284 |
+
sm = self.model.scoring_model
|
| 285 |
+
if hasattr(sm, "device") and sm.device is not None:
|
| 286 |
+
return sm.device
|
| 287 |
+
return next(sm.parameters()).device
|
| 288 |
+
|
| 289 |
+
def _l2d_stat(self, text: str, rewrite_first: str) -> float:
|
| 290 |
+
pad_id = self.model.scoring_tokenizer.pad_token_id
|
| 291 |
+
dev = self._scoring_inputs_device()
|
| 292 |
+
tok = self.model.scoring_tokenizer(text, return_tensors="pt", padding=True).to(dev)
|
| 293 |
+
labels = tok.input_ids[:, 1:]
|
| 294 |
+
lp_text = self.model.get_logp(tok, labels, pad_id, training_module=False)
|
| 295 |
+
tok_r = self.model.scoring_tokenizer(rewrite_first, return_tensors="pt", padding=True).to(dev)
|
| 296 |
+
labels_r = tok_r.input_ids[:, 1:]
|
| 297 |
+
lp_r = self.model.get_logp(tok_r, labels_r, pad_id, training_module=False)
|
| 298 |
+
return float(torch.abs(lp_text - lp_r).mean().item())
|
| 299 |
+
|
| 300 |
+
def score_text(self, text: str, rewrites: Optional[Sequence[str]] = None) -> float:
|
| 301 |
+
if rewrites is not None and len(rewrites) > 0:
|
| 302 |
+
r0 = rewrites[0]
|
| 303 |
+
else:
|
| 304 |
+
regen = _get_regen_samples(self._rewrite_sampler, text)
|
| 305 |
+
if not regen:
|
| 306 |
+
raise RuntimeError("Rewrite model returned no variants.")
|
| 307 |
+
r0 = regen[0]
|
| 308 |
+
return self._l2d_stat(text, r0)
|
miner_lab/subnet_metrics.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Subnet-style evaluation helpers.
|
| 3 |
+
|
| 4 |
+
Labels: 0 = human, 1 = AI/LLM. Scores are higher = more likely AI.
|
| 5 |
+
|
| 6 |
+
FP_score: specificity (true negative rate) at a threshold — rewards not flagging humans as AI.
|
| 7 |
+
FP_score = TN / (TN + FP) = 1 - FPR
|
| 8 |
+
|
| 9 |
+
AP: sklearn average_precision_score(y_true, y_score) using continuous scores (ranking quality).
|
| 10 |
+
|
| 11 |
+
Composite reward: weighted mix of F1, FP_score, AP (default equal 1/3 each).
|
| 12 |
+
For Subnet32, FP_score is often most important — use reward_weights e.g. (0.25, 0.5, 0.25).
|
| 13 |
+
F1 and FP_score use thresholded preds; AP uses continuous scores (constant across threshold sweep).
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
from sklearn.metrics import average_precision_score, f1_score
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def predict_at_threshold(scores: np.ndarray, threshold: float) -> np.ndarray:
|
| 25 |
+
scores = np.asarray(scores, dtype=np.float64)
|
| 26 |
+
return (scores >= threshold).astype(np.int64)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def fp_score_at_threshold(y_true: np.ndarray, y_pred: np.ndarray) -> float:
|
| 30 |
+
"""Specificity: TN / (TN + FP). y_true/y_pred in {0,1}, positive class = AI."""
|
| 31 |
+
y_true = np.asarray(y_true, dtype=np.int64)
|
| 32 |
+
y_pred = np.asarray(y_pred, dtype=np.int64)
|
| 33 |
+
mask_h = y_true == 0
|
| 34 |
+
if not np.any(mask_h):
|
| 35 |
+
return 1.0
|
| 36 |
+
tn = np.sum((y_pred == 0) & mask_h)
|
| 37 |
+
fp = np.sum((y_pred == 1) & mask_h)
|
| 38 |
+
denom = tn + fp
|
| 39 |
+
return float(tn / denom) if denom > 0 else 0.0
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def metrics_at_threshold(
|
| 43 |
+
y_true: np.ndarray,
|
| 44 |
+
scores: np.ndarray,
|
| 45 |
+
threshold: float,
|
| 46 |
+
reward_weights: Tuple[float, float, float] = (1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0),
|
| 47 |
+
) -> Dict[str, float]:
|
| 48 |
+
y_true = np.asarray(y_true, dtype=np.int64)
|
| 49 |
+
scores = np.asarray(scores, dtype=np.float64)
|
| 50 |
+
y_pred = predict_at_threshold(scores, threshold)
|
| 51 |
+
f1 = float(f1_score(y_true, y_pred, zero_division=0))
|
| 52 |
+
fps = fp_score_at_threshold(y_true, y_pred)
|
| 53 |
+
try:
|
| 54 |
+
ap = float(average_precision_score(y_true, scores))
|
| 55 |
+
except ValueError:
|
| 56 |
+
ap = 0.0
|
| 57 |
+
wf, wp, wa = reward_weights
|
| 58 |
+
wsum = wf + wp + wa
|
| 59 |
+
if wsum <= 0:
|
| 60 |
+
wsum = 1.0
|
| 61 |
+
reward = (wf * f1 + wp * fps + wa * ap) / wsum
|
| 62 |
+
return {"f1": f1, "fp_score": fps, "ap": ap, "reward": reward}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def sweep_thresholds(
|
| 66 |
+
y_true: np.ndarray,
|
| 67 |
+
scores: np.ndarray,
|
| 68 |
+
start: float = 0.01,
|
| 69 |
+
end: float = 0.99,
|
| 70 |
+
step: float = 0.01,
|
| 71 |
+
reward_weights: Tuple[float, float, float] = (1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0),
|
| 72 |
+
) -> Tuple[float, Dict[str, float], List[Dict[str, Any]]]:
|
| 73 |
+
"""
|
| 74 |
+
Pick threshold maximizing weighted reward (F1, FP_score, AP).
|
| 75 |
+
AP is constant w.r.t. threshold (uses continuous scores).
|
| 76 |
+
"""
|
| 77 |
+
y_true = np.asarray(y_true, dtype=np.int64)
|
| 78 |
+
scores = np.asarray(scores, dtype=np.float64)
|
| 79 |
+
try:
|
| 80 |
+
ap_fixed = float(average_precision_score(y_true, scores))
|
| 81 |
+
except ValueError:
|
| 82 |
+
ap_fixed = 0.0
|
| 83 |
+
|
| 84 |
+
wf, wp, wa = reward_weights
|
| 85 |
+
wsum = wf + wp + wa
|
| 86 |
+
if wsum <= 0:
|
| 87 |
+
wsum = 1.0
|
| 88 |
+
|
| 89 |
+
rows: List[Dict[str, Any]] = []
|
| 90 |
+
best_t, best = 0.5, {"f1": 0.0, "fp_score": 0.0, "ap": ap_fixed, "reward": -1.0}
|
| 91 |
+
t = start
|
| 92 |
+
while t <= end + 1e-9:
|
| 93 |
+
y_pred = predict_at_threshold(scores, t)
|
| 94 |
+
f1 = float(f1_score(y_true, y_pred, zero_division=0))
|
| 95 |
+
fps = fp_score_at_threshold(y_true, y_pred)
|
| 96 |
+
reward = (wf * f1 + wp * fps + wa * ap_fixed) / wsum
|
| 97 |
+
row = {"threshold": round(t, 4), "f1": f1, "fp_score": fps, "ap": ap_fixed, "reward": reward}
|
| 98 |
+
rows.append(row)
|
| 99 |
+
if reward > best["reward"]:
|
| 100 |
+
best = {"f1": f1, "fp_score": fps, "ap": ap_fixed, "reward": reward}
|
| 101 |
+
best_t = t
|
| 102 |
+
t += step
|
| 103 |
+
return best_t, best, rows
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def slice_by_key(
|
| 107 |
+
records: List[dict], key: str
|
| 108 |
+
) -> Dict[str, List[dict]]:
|
| 109 |
+
out: Dict[str, List[dict]] = {}
|
| 110 |
+
for r in records:
|
| 111 |
+
k = str(r.get(key, "unknown"))
|
| 112 |
+
out.setdefault(k, []).append(r)
|
| 113 |
+
return out
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def stress_report(
|
| 117 |
+
records: List[dict],
|
| 118 |
+
score_key: str,
|
| 119 |
+
threshold: float,
|
| 120 |
+
slice_keys: Optional[Iterable[str]] = None,
|
| 121 |
+
reward_weights: Tuple[float, float, float] = (1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0),
|
| 122 |
+
) -> Dict[str, Any]:
|
| 123 |
+
"""
|
| 124 |
+
records: dicts with 'label' (0/1), score_key (float), optional metadata for slicing.
|
| 125 |
+
"""
|
| 126 |
+
slice_keys = list(slice_keys or ("domain", "generator_family", "augmentation_type"))
|
| 127 |
+
y_true = np.array([int(r["label"]) for r in records], dtype=np.int64)
|
| 128 |
+
scores = np.array([float(r[score_key]) for r in records], dtype=np.float64)
|
| 129 |
+
overall = metrics_at_threshold(y_true, scores, threshold, reward_weights=reward_weights)
|
| 130 |
+
report: Dict[str, Any] = {
|
| 131 |
+
"overall": overall,
|
| 132 |
+
"n": len(records),
|
| 133 |
+
"threshold": threshold,
|
| 134 |
+
"reward_by_slice": {},
|
| 135 |
+
}
|
| 136 |
+
for sk in slice_keys:
|
| 137 |
+
by = slice_by_key(records, sk)
|
| 138 |
+
per: Dict[str, Any] = {}
|
| 139 |
+
for name, group in by.items():
|
| 140 |
+
if len(group) < 2:
|
| 141 |
+
continue
|
| 142 |
+
yt = np.array([int(r["label"]) for r in group], dtype=np.int64)
|
| 143 |
+
sc = np.array([float(r[score_key]) for r in group], dtype=np.float64)
|
| 144 |
+
per[name] = metrics_at_threshold(yt, sc, threshold, reward_weights=reward_weights)
|
| 145 |
+
report["reward_by_slice"][sk] = per
|
| 146 |
+
|
| 147 |
+
rewards = [v["reward"] for v in report["reward_by_slice"].get("domain", {}).values()]
|
| 148 |
+
if rewards:
|
| 149 |
+
report["worst_domain_reward"] = float(min(rewards))
|
| 150 |
+
all_slice_rewards: List[float] = []
|
| 151 |
+
for sk, per in report["reward_by_slice"].items():
|
| 152 |
+
for _, m in per.items():
|
| 153 |
+
all_slice_rewards.append(m["reward"])
|
| 154 |
+
if all_slice_rewards:
|
| 155 |
+
report["worst_slice_reward"] = float(min(all_slice_rewards))
|
| 156 |
+
return report
|
miner_lab/sup_scorer.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional supervised RoBERTa-style classifier (same format as scripts/train_sup_encoder.py)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SupScorer:
|
| 12 |
+
def __init__(self, model_dir: str, device_str: str, max_length: int = 256):
|
| 13 |
+
model_dir = os.path.abspath(model_dir)
|
| 14 |
+
self.device = torch.device(device_str)
|
| 15 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_dir)
|
| 16 |
+
self.model = AutoModelForSequenceClassification.from_pretrained(model_dir)
|
| 17 |
+
self.model.to(self.device)
|
| 18 |
+
self.model.eval()
|
| 19 |
+
self.max_length = max_length
|
| 20 |
+
|
| 21 |
+
def score_text(self, text: str) -> float:
|
| 22 |
+
enc = self.tokenizer(
|
| 23 |
+
text,
|
| 24 |
+
truncation=True,
|
| 25 |
+
max_length=self.max_length,
|
| 26 |
+
padding="max_length",
|
| 27 |
+
return_tensors="pt",
|
| 28 |
+
).to(self.device)
|
| 29 |
+
with torch.no_grad():
|
| 30 |
+
logits = self.model(**enc).logits
|
| 31 |
+
prob = torch.softmax(logits, dim=-1)[0, 1].item()
|
| 32 |
+
return float(prob)
|
miner_lab/text_features.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def count_words(text: str) -> int:
|
| 5 |
+
if not text or not str(text).strip():
|
| 6 |
+
return 0
|
| 7 |
+
return len(str(text).split())
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def count_sentences(text: str) -> int:
|
| 11 |
+
if not text or not str(text).strip():
|
| 12 |
+
return 0
|
| 13 |
+
parts = re.split(r"[.!?]+(?:\s+|$)", str(text).strip())
|
| 14 |
+
return max(1, len([p for p in parts if p.strip()]))
|
miner_lab/weighted_fusion.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Normalize branch scores on the fit split, then fuse with fixed weights (Subnet32-style).
|
| 3 |
+
|
| 4 |
+
Default weights: ada 0.45, l2d 0.30, sup 0.25 — Ada drives recall/AP, L2D stabilizes FP.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from typing import Dict, List, Mapping, Sequence, Tuple
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
DEFAULT_WEIGHTS: Mapping[str, float] = {
|
| 14 |
+
"ada_score": 0.45,
|
| 15 |
+
"l2d_score": 0.30,
|
| 16 |
+
"sup_score": 0.25,
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _finite(x) -> bool:
|
| 21 |
+
try:
|
| 22 |
+
return np.isfinite(float(x))
|
| 23 |
+
except (TypeError, ValueError):
|
| 24 |
+
return False
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def compute_medians(rows: List[dict], keys: Sequence[str]) -> Dict[str, float]:
|
| 28 |
+
med: Dict[str, float] = {}
|
| 29 |
+
for k in keys:
|
| 30 |
+
vals = [float(r[k]) for r in rows if k in r and _finite(r[k])]
|
| 31 |
+
med[k] = float(np.median(vals)) if vals else 0.0
|
| 32 |
+
return med
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def fit_minmax(rows: List[dict], keys: Sequence[str], medians: Dict[str, float]) -> Dict[str, Dict[str, float]]:
|
| 36 |
+
"""Per-key min/max on fit split (after imputation with medians for missing)."""
|
| 37 |
+
out: Dict[str, Dict[str, float]] = {}
|
| 38 |
+
for k in keys:
|
| 39 |
+
vals = []
|
| 40 |
+
for r in rows:
|
| 41 |
+
v = r.get(k)
|
| 42 |
+
if v is None or not _finite(v):
|
| 43 |
+
v = medians.get(k, 0.0)
|
| 44 |
+
vals.append(float(v))
|
| 45 |
+
if not vals:
|
| 46 |
+
out[k] = {"min": 0.0, "max": 1.0}
|
| 47 |
+
else:
|
| 48 |
+
lo, hi = float(min(vals)), float(max(vals))
|
| 49 |
+
if hi - lo < 1e-12:
|
| 50 |
+
out[k] = {"min": lo, "max": hi + 1e-6}
|
| 51 |
+
else:
|
| 52 |
+
out[k] = {"min": lo, "max": hi}
|
| 53 |
+
return out
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def fit_zscore(rows: List[dict], keys: Sequence[str], medians: Dict[str, float]) -> Dict[str, Dict[str, float]]:
|
| 57 |
+
"""Per-key mean/std on fit split (after imputation)."""
|
| 58 |
+
out: Dict[str, Dict[str, float]] = {}
|
| 59 |
+
for k in keys:
|
| 60 |
+
vals = []
|
| 61 |
+
for r in rows:
|
| 62 |
+
v = r.get(k)
|
| 63 |
+
if v is None or not _finite(v):
|
| 64 |
+
v = medians.get(k, 0.0)
|
| 65 |
+
vals.append(float(v))
|
| 66 |
+
if not vals:
|
| 67 |
+
out[k] = {"mean": 0.0, "std": 1.0}
|
| 68 |
+
else:
|
| 69 |
+
a = np.asarray(vals, dtype=np.float64)
|
| 70 |
+
mu = float(np.mean(a))
|
| 71 |
+
sig = float(np.std(a))
|
| 72 |
+
if sig < 1e-12:
|
| 73 |
+
sig = 1.0
|
| 74 |
+
out[k] = {"mean": mu, "std": sig}
|
| 75 |
+
return out
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _norm_minmax(v: float, lo: float, hi: float) -> float:
|
| 79 |
+
if hi - lo < 1e-12:
|
| 80 |
+
return 0.5
|
| 81 |
+
return float(np.clip((v - lo) / (hi - lo), 0.0, 1.0))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _norm_zsigmoid(v: float, mu: float, sig: float) -> float:
|
| 85 |
+
if sig < 1e-12:
|
| 86 |
+
return 0.5
|
| 87 |
+
z = (float(v) - mu) / sig
|
| 88 |
+
z = float(np.clip(z, -20.0, 20.0))
|
| 89 |
+
return float(1.0 / (1.0 + np.exp(-z)))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def renormalize_weights(weights: Mapping[str, float], active_keys: Sequence[str]) -> Dict[str, float]:
|
| 93 |
+
w = {k: float(weights[k]) for k in active_keys if k in weights}
|
| 94 |
+
s = sum(w.values())
|
| 95 |
+
if s <= 0:
|
| 96 |
+
n = len(w)
|
| 97 |
+
return {k: 1.0 / max(n, 1) for k in w}
|
| 98 |
+
return {k: v / s for k, v in w.items()}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def row_branch_values(row: dict, keys: Sequence[str], medians: Dict[str, float]) -> List[float]:
|
| 102 |
+
vals = []
|
| 103 |
+
for k in keys:
|
| 104 |
+
v = row.get(k)
|
| 105 |
+
if v is None or not _finite(v):
|
| 106 |
+
v = medians.get(k, 0.0)
|
| 107 |
+
vals.append(float(v))
|
| 108 |
+
return vals
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def fusion_prob_array(
|
| 112 |
+
rows: List[dict],
|
| 113 |
+
keys: Sequence[str],
|
| 114 |
+
medians: Dict[str, float],
|
| 115 |
+
norm_params: Mapping[str, Mapping[str, float]],
|
| 116 |
+
weights: Mapping[str, float],
|
| 117 |
+
norm_method: str,
|
| 118 |
+
) -> np.ndarray:
|
| 119 |
+
"""Vector of fusion scores in ~[0, 1] (weighted sum of normalized branch scores)."""
|
| 120 |
+
w = renormalize_weights(weights, keys)
|
| 121 |
+
out = np.zeros(len(rows), dtype=np.float64)
|
| 122 |
+
for i, r in enumerate(rows):
|
| 123 |
+
s = 0.0
|
| 124 |
+
for k in keys:
|
| 125 |
+
v = r.get(k)
|
| 126 |
+
if v is None or not _finite(v):
|
| 127 |
+
v = medians.get(k, 0.0)
|
| 128 |
+
v = float(v)
|
| 129 |
+
if norm_method == "minmax":
|
| 130 |
+
lo = norm_params[k]["min"]
|
| 131 |
+
hi = norm_params[k]["max"]
|
| 132 |
+
vn = _norm_minmax(v, lo, hi)
|
| 133 |
+
elif norm_method == "zscore_sigmoid":
|
| 134 |
+
mu = norm_params[k]["mean"]
|
| 135 |
+
sig = norm_params[k]["std"]
|
| 136 |
+
vn = _norm_zsigmoid(v, mu, sig)
|
| 137 |
+
else:
|
| 138 |
+
raise ValueError(f"Unknown norm_method: {norm_method}")
|
| 139 |
+
s += w[k] * vn
|
| 140 |
+
out[i] = s
|
| 141 |
+
return out
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def fusion_prob_one(
|
| 145 |
+
row: dict,
|
| 146 |
+
keys: Sequence[str],
|
| 147 |
+
medians: Dict[str, float],
|
| 148 |
+
norm_params: Mapping[str, Mapping[str, float]],
|
| 149 |
+
weights: Mapping[str, float],
|
| 150 |
+
norm_method: str,
|
| 151 |
+
) -> float:
|
| 152 |
+
"""Single-row fusion probability (same as one element of fusion_prob_array)."""
|
| 153 |
+
arr = fusion_prob_array([row], keys, medians, norm_params, weights, norm_method)
|
| 154 |
+
return float(arr[0])
|
path/to/with_l2d.jsonl
ADDED
|
File without changes
|
requirements.txt
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PyTorch with NVIDIA GPU: CUDA wheels come from PyTorch’s index (not the default PyPI CPU build).
|
| 2 |
+
# Change cu126 to cu118 or cu128 if needed — match https://pytorch.org/get-started/locally/ and nvidia-smi.
|
| 3 |
+
# CUDA wheels are ~2–3 GB; if pip hits ReadTimeoutError, reinstall with a longer socket timeout, e.g.:
|
| 4 |
+
# python -m pip install --upgrade pip
|
| 5 |
+
# python -m pip install --default-timeout=3600 --retries 10 -r requirements.txt
|
| 6 |
+
--extra-index-url https://download.pytorch.org/whl/cu126
|
| 7 |
+
|
| 8 |
+
torch
|
| 9 |
+
numpy
|
| 10 |
+
# Gemma-2 (google/gemma-2-9b-it) needs transformers>=4.44 (tokenizer + model classes).
|
| 11 |
+
# If textattack warns or breaks, use a separate venv for L2D scoring or upgrade textattack.
|
| 12 |
+
transformers>=4.44.0,<4.50.0
|
| 13 |
+
tokenizers>=0.19.0
|
| 14 |
+
accelerate>=0.33.0
|
| 15 |
+
# L2D checkpoints may include adapter_config fields (e.g. corda_config) from newer PEFT; need >=0.14.
|
| 16 |
+
peft>=0.14.0,<0.20.0
|
| 17 |
+
huggingface_hub>=0.16.0
|
| 18 |
+
# Optional: 4-bit AdaDist on ~12GB GPUs (run_l2d_jsonl.py --load_4bit). Windows may need a matching CUDA wheel.
|
| 19 |
+
bitsandbytes>=0.43.0
|
| 20 |
+
datasets==2.12.0
|
| 21 |
+
# datasets 2.12 expects pyarrow.PyExtensionType (removed in pyarrow 16+); also keeps numpy<2 via pyarrow 15.x.
|
| 22 |
+
pyarrow>=12.0.0,<16.0.0
|
| 23 |
+
fsspec==2023.9.2
|
| 24 |
+
matplotlib
|
| 25 |
+
tqdm
|
| 26 |
+
openai
|
| 27 |
+
nltk
|
| 28 |
+
scikit-learn
|
| 29 |
+
rank-bm25
|
| 30 |
+
selenium
|
| 31 |
+
nltk
|
| 32 |
+
textattack==0.3.10
|
| 33 |
+
# google
|
| 34 |
+
# anthropic
|
scripts/BSpline.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
from torch import nn
|
| 4 |
+
from helper import *
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class BSpline(nn.Module):
|
| 8 |
+
"""
|
| 9 |
+
Class for computing the B-spline funcions b_i(x)
|
| 10 |
+
and constructing the penality matrix S.
|
| 11 |
+
|
| 12 |
+
# Args
|
| 13 |
+
start: float or int; start of the region
|
| 14 |
+
end: float or int; end of the region
|
| 15 |
+
n_bases: int; number of spline bases
|
| 16 |
+
spline_order: int; spline order
|
| 17 |
+
|
| 18 |
+
# Methods
|
| 19 |
+
- **getS(add_intercept=False)** - Get the penalty matrix S
|
| 20 |
+
- Args
|
| 21 |
+
- **add_intercept**: bool. If true, intercept column is added to the returned matrix.
|
| 22 |
+
- Returns
|
| 23 |
+
- `np.array`, of shape `(n_bases + add_intercept, n_bases + add_intercept)`
|
| 24 |
+
- **predict(x, add_intercept=False)** - For some x, predict the bn(x) for each base
|
| 25 |
+
- Args
|
| 26 |
+
- **x**: np.array; Vector of dimension 1
|
| 27 |
+
- **add_intercept**: bool; If True, intercept column is added to the to the final array
|
| 28 |
+
- Returns
|
| 29 |
+
- `torch.tensor`, of shape `(len(x), n_bases + (add_intercept))`
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, start=0, end=1, n_bases=10, spline_order=3, intercept=1):
|
| 33 |
+
super().__init__()
|
| 34 |
+
|
| 35 |
+
self.start = start
|
| 36 |
+
self.end = end
|
| 37 |
+
self.n_bases = n_bases
|
| 38 |
+
self.spline_order = spline_order
|
| 39 |
+
self.add_intercept = True if intercept == 1 else False
|
| 40 |
+
|
| 41 |
+
self.knots = get_knots(self.start, self.end, self.n_bases, self.spline_order)
|
| 42 |
+
|
| 43 |
+
self.S = get_S(self.n_bases, self.spline_order)
|
| 44 |
+
|
| 45 |
+
def __repr__(self):
|
| 46 |
+
return "BSpline(start={0}, end={1}, n_bases={2}, spline_order={3})".format(
|
| 47 |
+
self.start, self.end, self.n_bases, self.spline_order
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def getS(self):
|
| 51 |
+
"""Get the penalty matrix S
|
| 52 |
+
Returns:
|
| 53 |
+
torch.tensor, of shape (n_bases + add_intercept, n_bases + add_intercept)
|
| 54 |
+
"""
|
| 55 |
+
S = self.S
|
| 56 |
+
if self.add_intercept is True:
|
| 57 |
+
# S <- cbind(0, rbind(0, S)) # in R
|
| 58 |
+
zeros = np.zeros_like(S[:1, :])
|
| 59 |
+
S = np.vstack([zeros, S])
|
| 60 |
+
|
| 61 |
+
zeros = np.zeros_like(S[:, :1])
|
| 62 |
+
S = np.hstack([zeros, S])
|
| 63 |
+
return S
|
| 64 |
+
|
| 65 |
+
def forward(self, x):
|
| 66 |
+
"""For some x, predict the bn(x) for each base
|
| 67 |
+
Args:
|
| 68 |
+
x: torch.tensor
|
| 69 |
+
add_intercept: bool; should we add the intercept to the final array
|
| 70 |
+
Returns:
|
| 71 |
+
torch.tensor, of shape (len(x), n_bases + (add_intercept))
|
| 72 |
+
"""
|
| 73 |
+
# sanity check
|
| 74 |
+
if x.min() < self.start:
|
| 75 |
+
raise Warning("x.min() < self.start")
|
| 76 |
+
if x.max() > self.end:
|
| 77 |
+
raise Warning("x.max() > self.end")
|
| 78 |
+
|
| 79 |
+
return get_X_spline_torch(
|
| 80 |
+
x=x,
|
| 81 |
+
knots=self.knots,
|
| 82 |
+
n_bases=self.n_bases,
|
| 83 |
+
spline_order=self.spline_order,
|
| 84 |
+
add_intercept=self.add_intercept,
|
| 85 |
+
)
|
| 86 |
+
# return get_X_spline(x=x, knots=self.knots, n_bases=self.n_bases, spline_order=self.spline_order, add_intercept=self.add_intercept)
|
| 87 |
+
|
| 88 |
+
def get_config(self):
|
| 89 |
+
return {
|
| 90 |
+
"start": self.start,
|
| 91 |
+
"end": self.end,
|
| 92 |
+
"n_bases": self.n_bases,
|
| 93 |
+
"spline_order": self.spline_order,
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
@classmethod
|
| 97 |
+
def from_config(cls, config):
|
| 98 |
+
return cls(**config)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _trunc(x, minval=None, maxval=None):
|
| 102 |
+
"""Truncate vector values to have values on range [minval, maxval]"""
|
| 103 |
+
x = torch.clone(x)
|
| 104 |
+
if minval != None:
|
| 105 |
+
x[x < minval] = minval
|
| 106 |
+
if maxval != None:
|
| 107 |
+
x[x > maxval] = maxval
|
| 108 |
+
return x
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def encodeSplines(x, n_bases=5, spline_order=3, start=None, end=None, warn=True):
|
| 112 |
+
"""Function for the class `EncodeSplines`.
|
| 113 |
+
Expansion by generating B-spline basis functions for each x
|
| 114 |
+
and each n (spline-index) with `scipy.interpolate.splev`,
|
| 115 |
+
based on the pre-placed equidistant knots on [start, end] range.
|
| 116 |
+
|
| 117 |
+
# Arguments
|
| 118 |
+
x: a torch.tensor of positions
|
| 119 |
+
n_bases int: Number of spline bases.
|
| 120 |
+
spline_order: 2 for quadratic, 3 for qubic splines
|
| 121 |
+
start, end: range of values. If None, they are inferred from the data
|
| 122 |
+
as minimum and maximum value.
|
| 123 |
+
warn: Show warnings.
|
| 124 |
+
|
| 125 |
+
# Returns
|
| 126 |
+
`torch.tensor` of shape `(x.shape[0], x.shape[1], channels, n_bases)`
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
if len(x.shape) == 1:
|
| 130 |
+
x = x.reshape((-1, 1))
|
| 131 |
+
|
| 132 |
+
if start is None:
|
| 133 |
+
start = torch.amin(x) # should be np.nanmin
|
| 134 |
+
else:
|
| 135 |
+
if x.min() < start:
|
| 136 |
+
if warn:
|
| 137 |
+
print(
|
| 138 |
+
"WARNING, x.min() < start for some elements. Truncating them to start: x[x < start] = start"
|
| 139 |
+
)
|
| 140 |
+
x = _trunc(x, minval=start)
|
| 141 |
+
if end is None:
|
| 142 |
+
end = torch.amax(x) # should be np.nanmax
|
| 143 |
+
else:
|
| 144 |
+
if x.max() > end:
|
| 145 |
+
if warn:
|
| 146 |
+
print(
|
| 147 |
+
"WARNING, x.max() > end for some elements. Truncating them to end: x[x > end] = end"
|
| 148 |
+
)
|
| 149 |
+
x = _trunc(x, maxval=end)
|
| 150 |
+
bs = BSpline(start, end, n_bases=n_bases, spline_order=spline_order)
|
| 151 |
+
|
| 152 |
+
# concatenate x to long
|
| 153 |
+
assert len(x.shape) == 2
|
| 154 |
+
n_rows = x.shape[0]
|
| 155 |
+
n_cols = x.shape[1]
|
| 156 |
+
|
| 157 |
+
x_long = x.reshape((-1,))
|
| 158 |
+
|
| 159 |
+
# shape = (n_rows * n_cols, n_bases)
|
| 160 |
+
x_feat = bs.predict(x_long, add_intercept=False)
|
| 161 |
+
|
| 162 |
+
x_final = x_feat.reshape((n_rows, n_cols, n_bases))
|
| 163 |
+
return x_final
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
|
| 168 |
+
obs = -30 * torch.rand(10)
|
| 169 |
+
# print(obs)
|
| 170 |
+
bspline_args = {'start': -32, 'end': 0, 'n_bases': 7, 'spline_order': 2, 'intercept': 1}
|
| 171 |
+
# bspline_args = {'start': -30, 'end': 0, 'n_bases': 16, 'spline_order': 2}
|
| 172 |
+
bspline = BSpline(**bspline_args)
|
| 173 |
+
output = bspline.predict(obs)
|
| 174 |
+
|
| 175 |
+
import matplotlib.pyplot as plt
|
| 176 |
+
x_plot = torch.linspace(bspline.start, bspline.end, 1000)
|
| 177 |
+
basis_plot = bspline.predict(x_plot)
|
| 178 |
+
|
| 179 |
+
plt.figure(figsize=(10, 6))
|
| 180 |
+
for i in range(bspline.n_bases):
|
| 181 |
+
plt.plot(x_plot, basis_plot[:, i], label=f'Basis {i + 1}')
|
| 182 |
+
|
| 183 |
+
plt.scatter(obs, torch.zeros_like(obs), color='red', label='Observations')
|
| 184 |
+
plt.title(f'B-spline Bases (Order {bspline.spline_order}, {bspline.n_bases} Bases)')
|
| 185 |
+
plt.xlabel('x')
|
| 186 |
+
plt.ylabel('Basis Value')
|
| 187 |
+
plt.legend()
|
| 188 |
+
plt.grid(True)
|
| 189 |
+
plt.show()
|
| 190 |
+
|
| 191 |
+
# beta_hat = torch.tensor([ 0.0000, -0.1320, 0.8180, 0.1750, 0.1690, -0.0490, 0.4600, 0.2010]) # old
|
| 192 |
+
beta_hat = torch.tensor([-0.0030, 0.0000, 0.0160, 0.1960, -0.0150, -1.0230, 0.4580, 0.3650])
|
| 193 |
+
predict = basis_plot @ beta_hat
|
| 194 |
+
plt.figure(figsize=(10, 6))
|
| 195 |
+
plt.plot(x_plot, predict, label=f'w-function')
|
| 196 |
+
plt.xlabel('x')
|
| 197 |
+
plt.ylabel('y')
|
| 198 |
+
plt.grid(True)
|
| 199 |
+
plt.show()
|
| 200 |
+
plt.savefig('w_function.png')
|
| 201 |
+
|
scripts/BiScope/LICENSE
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Attribution-NonCommercial-NoDerivatives 4.0 International
|
| 2 |
+
|
| 3 |
+
=======================================================================
|
| 4 |
+
|
| 5 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
| 6 |
+
does not provide legal services or legal advice. Distribution of
|
| 7 |
+
Creative Commons public licenses does not create a lawyer-client or
|
| 8 |
+
other relationship. Creative Commons makes its licenses and related
|
| 9 |
+
information available on an "as-is" basis. Creative Commons gives no
|
| 10 |
+
warranties regarding its licenses, any material licensed under their
|
| 11 |
+
terms and conditions, or any related information. Creative Commons
|
| 12 |
+
disclaims all liability for damages resulting from their use to the
|
| 13 |
+
fullest extent possible.
|
| 14 |
+
|
| 15 |
+
Using Creative Commons Public Licenses
|
| 16 |
+
|
| 17 |
+
Creative Commons public licenses provide a standard set of terms and
|
| 18 |
+
conditions that creators and other rights holders may use to share
|
| 19 |
+
original works of authorship and other material subject to copyright
|
| 20 |
+
and certain other rights specified in the public license below. The
|
| 21 |
+
following considerations are for informational purposes only, are not
|
| 22 |
+
exhaustive, and do not form part of our licenses.
|
| 23 |
+
|
| 24 |
+
Considerations for licensors: Our public licenses are
|
| 25 |
+
intended for use by those authorized to give the public
|
| 26 |
+
permission to use material in ways otherwise restricted by
|
| 27 |
+
copyright and certain other rights. Our licenses are
|
| 28 |
+
irrevocable. Licensors should read and understand the terms
|
| 29 |
+
and conditions of the license they choose before applying it.
|
| 30 |
+
Licensors should also secure all rights necessary before
|
| 31 |
+
applying our licenses so that the public can reuse the
|
| 32 |
+
material as expected. Licensors should clearly mark any
|
| 33 |
+
material not subject to the license. This includes other CC-
|
| 34 |
+
licensed material, or material used under an exception or
|
| 35 |
+
limitation to copyright. More considerations for licensors:
|
| 36 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
| 37 |
+
|
| 38 |
+
Considerations for the public: By using one of our public
|
| 39 |
+
licenses, a licensor grants the public permission to use the
|
| 40 |
+
licensed material under specified terms and conditions. If
|
| 41 |
+
the licensor's permission is not necessary for any reason--for
|
| 42 |
+
example, because of any applicable exception or limitation to
|
| 43 |
+
copyright--then that use is not regulated by the license. Our
|
| 44 |
+
licenses grant only permissions under copyright and certain
|
| 45 |
+
other rights that a licensor has authority to grant. Use of
|
| 46 |
+
the licensed material may still be restricted for other
|
| 47 |
+
reasons, including because others have copyright or other
|
| 48 |
+
rights in the material. A licensor may make special requests,
|
| 49 |
+
such as asking that all changes be marked or described.
|
| 50 |
+
Although not required by our licenses, you are encouraged to
|
| 51 |
+
respect those requests where reasonable. More considerations
|
| 52 |
+
for the public:
|
| 53 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
| 54 |
+
|
| 55 |
+
=======================================================================
|
| 56 |
+
|
| 57 |
+
Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
|
| 58 |
+
International Public License
|
| 59 |
+
|
| 60 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
| 61 |
+
to be bound by the terms and conditions of this Creative Commons
|
| 62 |
+
Attribution-NonCommercial-NoDerivatives 4.0 International Public
|
| 63 |
+
License ("Public License"). To the extent this Public License may be
|
| 64 |
+
interpreted as a contract, You are granted the Licensed Rights in
|
| 65 |
+
consideration of Your acceptance of these terms and conditions, and the
|
| 66 |
+
Licensor grants You such rights in consideration of benefits the
|
| 67 |
+
Licensor receives from making the Licensed Material available under
|
| 68 |
+
these terms and conditions.
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
Section 1 -- Definitions.
|
| 72 |
+
|
| 73 |
+
a. Adapted Material means material subject to Copyright and Similar
|
| 74 |
+
Rights that is derived from or based upon the Licensed Material
|
| 75 |
+
and in which the Licensed Material is translated, altered,
|
| 76 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
| 77 |
+
permission under the Copyright and Similar Rights held by the
|
| 78 |
+
Licensor. For purposes of this Public License, where the Licensed
|
| 79 |
+
Material is a musical work, performance, or sound recording,
|
| 80 |
+
Adapted Material is always produced where the Licensed Material is
|
| 81 |
+
synched in timed relation with a moving image.
|
| 82 |
+
|
| 83 |
+
b. Copyright and Similar Rights means copyright and/or similar rights
|
| 84 |
+
closely related to copyright including, without limitation,
|
| 85 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
| 86 |
+
Rights, without regard to how the rights are labeled or
|
| 87 |
+
categorized. For purposes of this Public License, the rights
|
| 88 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
| 89 |
+
Rights.
|
| 90 |
+
|
| 91 |
+
c. Effective Technological Measures means those measures that, in the
|
| 92 |
+
absence of proper authority, may not be circumvented under laws
|
| 93 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
| 94 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
| 95 |
+
agreements.
|
| 96 |
+
|
| 97 |
+
d. Exceptions and Limitations means fair use, fair dealing, and/or
|
| 98 |
+
any other exception or limitation to Copyright and Similar Rights
|
| 99 |
+
that applies to Your use of the Licensed Material.
|
| 100 |
+
|
| 101 |
+
e. Licensed Material means the artistic or literary work, database,
|
| 102 |
+
or other material to which the Licensor applied this Public
|
| 103 |
+
License.
|
| 104 |
+
|
| 105 |
+
f. Licensed Rights means the rights granted to You subject to the
|
| 106 |
+
terms and conditions of this Public License, which are limited to
|
| 107 |
+
all Copyright and Similar Rights that apply to Your use of the
|
| 108 |
+
Licensed Material and that the Licensor has authority to license.
|
| 109 |
+
|
| 110 |
+
g. Licensor means the individual(s) or entity(ies) granting rights
|
| 111 |
+
under this Public License.
|
| 112 |
+
|
| 113 |
+
h. NonCommercial means not primarily intended for or directed towards
|
| 114 |
+
commercial advantage or monetary compensation. For purposes of
|
| 115 |
+
this Public License, the exchange of the Licensed Material for
|
| 116 |
+
other material subject to Copyright and Similar Rights by digital
|
| 117 |
+
file-sharing or similar means is NonCommercial provided there is
|
| 118 |
+
no payment of monetary compensation in connection with the
|
| 119 |
+
exchange.
|
| 120 |
+
|
| 121 |
+
i. Share means to provide material to the public by any means or
|
| 122 |
+
process that requires permission under the Licensed Rights, such
|
| 123 |
+
as reproduction, public display, public performance, distribution,
|
| 124 |
+
dissemination, communication, or importation, and to make material
|
| 125 |
+
available to the public including in ways that members of the
|
| 126 |
+
public may access the material from a place and at a time
|
| 127 |
+
individually chosen by them.
|
| 128 |
+
|
| 129 |
+
j. Sui Generis Database Rights means rights other than copyright
|
| 130 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
| 131 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
| 132 |
+
as amended and/or succeeded, as well as other essentially
|
| 133 |
+
equivalent rights anywhere in the world.
|
| 134 |
+
|
| 135 |
+
k. You means the individual or entity exercising the Licensed Rights
|
| 136 |
+
under this Public License. Your has a corresponding meaning.
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
Section 2 -- Scope.
|
| 140 |
+
|
| 141 |
+
a. License grant.
|
| 142 |
+
|
| 143 |
+
1. Subject to the terms and conditions of this Public License,
|
| 144 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
| 145 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
| 146 |
+
exercise the Licensed Rights in the Licensed Material to:
|
| 147 |
+
|
| 148 |
+
a. reproduce and Share the Licensed Material, in whole or
|
| 149 |
+
in part, for NonCommercial purposes only; and
|
| 150 |
+
|
| 151 |
+
b. produce and reproduce, but not Share, Adapted Material
|
| 152 |
+
for NonCommercial purposes only.
|
| 153 |
+
|
| 154 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
| 155 |
+
Exceptions and Limitations apply to Your use, this Public
|
| 156 |
+
License does not apply, and You do not need to comply with
|
| 157 |
+
its terms and conditions.
|
| 158 |
+
|
| 159 |
+
3. Term. The term of this Public License is specified in Section
|
| 160 |
+
6(a).
|
| 161 |
+
|
| 162 |
+
4. Media and formats; technical modifications allowed. The
|
| 163 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
| 164 |
+
all media and formats whether now known or hereafter created,
|
| 165 |
+
and to make technical modifications necessary to do so. The
|
| 166 |
+
Licensor waives and/or agrees not to assert any right or
|
| 167 |
+
authority to forbid You from making technical modifications
|
| 168 |
+
necessary to exercise the Licensed Rights, including
|
| 169 |
+
technical modifications necessary to circumvent Effective
|
| 170 |
+
Technological Measures. For purposes of this Public License,
|
| 171 |
+
simply making modifications authorized by this Section 2(a)
|
| 172 |
+
(4) never produces Adapted Material.
|
| 173 |
+
|
| 174 |
+
5. Downstream recipients.
|
| 175 |
+
|
| 176 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
| 177 |
+
recipient of the Licensed Material automatically
|
| 178 |
+
receives an offer from the Licensor to exercise the
|
| 179 |
+
Licensed Rights under the terms and conditions of this
|
| 180 |
+
Public License.
|
| 181 |
+
|
| 182 |
+
b. No downstream restrictions. You may not offer or impose
|
| 183 |
+
any additional or different terms or conditions on, or
|
| 184 |
+
apply any Effective Technological Measures to, the
|
| 185 |
+
Licensed Material if doing so restricts exercise of the
|
| 186 |
+
Licensed Rights by any recipient of the Licensed
|
| 187 |
+
Material.
|
| 188 |
+
|
| 189 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
| 190 |
+
may be construed as permission to assert or imply that You
|
| 191 |
+
are, or that Your use of the Licensed Material is, connected
|
| 192 |
+
with, or sponsored, endorsed, or granted official status by,
|
| 193 |
+
the Licensor or others designated to receive attribution as
|
| 194 |
+
provided in Section 3(a)(1)(A)(i).
|
| 195 |
+
|
| 196 |
+
b. Other rights.
|
| 197 |
+
|
| 198 |
+
1. Moral rights, such as the right of integrity, are not
|
| 199 |
+
licensed under this Public License, nor are publicity,
|
| 200 |
+
privacy, and/or other similar personality rights; however, to
|
| 201 |
+
the extent possible, the Licensor waives and/or agrees not to
|
| 202 |
+
assert any such rights held by the Licensor to the limited
|
| 203 |
+
extent necessary to allow You to exercise the Licensed
|
| 204 |
+
Rights, but not otherwise.
|
| 205 |
+
|
| 206 |
+
2. Patent and trademark rights are not licensed under this
|
| 207 |
+
Public License.
|
| 208 |
+
|
| 209 |
+
3. To the extent possible, the Licensor waives any right to
|
| 210 |
+
collect royalties from You for the exercise of the Licensed
|
| 211 |
+
Rights, whether directly or through a collecting society
|
| 212 |
+
under any voluntary or waivable statutory or compulsory
|
| 213 |
+
licensing scheme. In all other cases the Licensor expressly
|
| 214 |
+
reserves any right to collect such royalties, including when
|
| 215 |
+
the Licensed Material is used other than for NonCommercial
|
| 216 |
+
purposes.
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
Section 3 -- License Conditions.
|
| 220 |
+
|
| 221 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
| 222 |
+
following conditions.
|
| 223 |
+
|
| 224 |
+
a. Attribution.
|
| 225 |
+
|
| 226 |
+
1. If You Share the Licensed Material, You must:
|
| 227 |
+
|
| 228 |
+
a. retain the following if it is supplied by the Licensor
|
| 229 |
+
with the Licensed Material:
|
| 230 |
+
|
| 231 |
+
i. identification of the creator(s) of the Licensed
|
| 232 |
+
Material and any others designated to receive
|
| 233 |
+
attribution, in any reasonable manner requested by
|
| 234 |
+
the Licensor (including by pseudonym if
|
| 235 |
+
designated);
|
| 236 |
+
|
| 237 |
+
ii. a copyright notice;
|
| 238 |
+
|
| 239 |
+
iii. a notice that refers to this Public License;
|
| 240 |
+
|
| 241 |
+
iv. a notice that refers to the disclaimer of
|
| 242 |
+
warranties;
|
| 243 |
+
|
| 244 |
+
v. a URI or hyperlink to the Licensed Material to the
|
| 245 |
+
extent reasonably practicable;
|
| 246 |
+
|
| 247 |
+
b. indicate if You modified the Licensed Material and
|
| 248 |
+
retain an indication of any previous modifications; and
|
| 249 |
+
|
| 250 |
+
c. indicate the Licensed Material is licensed under this
|
| 251 |
+
Public License, and include the text of, or the URI or
|
| 252 |
+
hyperlink to, this Public License.
|
| 253 |
+
|
| 254 |
+
For the avoidance of doubt, You do not have permission under
|
| 255 |
+
this Public License to Share Adapted Material.
|
| 256 |
+
|
| 257 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
| 258 |
+
reasonable manner based on the medium, means, and context in
|
| 259 |
+
which You Share the Licensed Material. For example, it may be
|
| 260 |
+
reasonable to satisfy the conditions by providing a URI or
|
| 261 |
+
hyperlink to a resource that includes the required
|
| 262 |
+
information.
|
| 263 |
+
|
| 264 |
+
3. If requested by the Licensor, You must remove any of the
|
| 265 |
+
information required by Section 3(a)(1)(A) to the extent
|
| 266 |
+
reasonably practicable.
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
Section 4 -- Sui Generis Database Rights.
|
| 270 |
+
|
| 271 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
| 272 |
+
apply to Your use of the Licensed Material:
|
| 273 |
+
|
| 274 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
| 275 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
| 276 |
+
portion of the contents of the database for NonCommercial purposes
|
| 277 |
+
only and provided You do not Share Adapted Material;
|
| 278 |
+
|
| 279 |
+
b. if You include all or a substantial portion of the database
|
| 280 |
+
contents in a database in which You have Sui Generis Database
|
| 281 |
+
Rights, then the database in which You have Sui Generis Database
|
| 282 |
+
Rights (but not its individual contents) is Adapted Material; and
|
| 283 |
+
|
| 284 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
| 285 |
+
all or a substantial portion of the contents of the database.
|
| 286 |
+
|
| 287 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
| 288 |
+
replace Your obligations under this Public License where the Licensed
|
| 289 |
+
Rights include other Copyright and Similar Rights.
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
| 293 |
+
|
| 294 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
| 295 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
| 296 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
| 297 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
| 298 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
| 299 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
| 300 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
| 301 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
| 302 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
| 303 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
| 304 |
+
|
| 305 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
| 306 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
| 307 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
| 308 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
| 309 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
| 310 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
| 311 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
| 312 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
| 313 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
| 314 |
+
|
| 315 |
+
c. The disclaimer of warranties and limitation of liability provided
|
| 316 |
+
above shall be interpreted in a manner that, to the extent
|
| 317 |
+
possible, most closely approximates an absolute disclaimer and
|
| 318 |
+
waiver of all liability.
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
Section 6 -- Term and Termination.
|
| 322 |
+
|
| 323 |
+
a. This Public License applies for the term of the Copyright and
|
| 324 |
+
Similar Rights licensed here. However, if You fail to comply with
|
| 325 |
+
this Public License, then Your rights under this Public License
|
| 326 |
+
terminate automatically.
|
| 327 |
+
|
| 328 |
+
b. Where Your right to use the Licensed Material has terminated under
|
| 329 |
+
Section 6(a), it reinstates:
|
| 330 |
+
|
| 331 |
+
1. automatically as of the date the violation is cured, provided
|
| 332 |
+
it is cured within 30 days of Your discovery of the
|
| 333 |
+
violation; or
|
| 334 |
+
|
| 335 |
+
2. upon express reinstatement by the Licensor.
|
| 336 |
+
|
| 337 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
| 338 |
+
right the Licensor may have to seek remedies for Your violations
|
| 339 |
+
of this Public License.
|
| 340 |
+
|
| 341 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
| 342 |
+
Licensed Material under separate terms or conditions or stop
|
| 343 |
+
distributing the Licensed Material at any time; however, doing so
|
| 344 |
+
will not terminate this Public License.
|
| 345 |
+
|
| 346 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
| 347 |
+
License.
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
Section 7 -- Other Terms and Conditions.
|
| 351 |
+
|
| 352 |
+
a. The Licensor shall not be bound by any additional or different
|
| 353 |
+
terms or conditions communicated by You unless expressly agreed.
|
| 354 |
+
|
| 355 |
+
b. Any arrangements, understandings, or agreements regarding the
|
| 356 |
+
Licensed Material not stated herein are separate from and
|
| 357 |
+
independent of the terms and conditions of this Public License.
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
Section 8 -- Interpretation.
|
| 361 |
+
|
| 362 |
+
a. For the avoidance of doubt, this Public License does not, and
|
| 363 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
| 364 |
+
conditions on any use of the Licensed Material that could lawfully
|
| 365 |
+
be made without permission under this Public License.
|
| 366 |
+
|
| 367 |
+
b. To the extent possible, if any provision of this Public License is
|
| 368 |
+
deemed unenforceable, it shall be automatically reformed to the
|
| 369 |
+
minimum extent necessary to make it enforceable. If the provision
|
| 370 |
+
cannot be reformed, it shall be severed from this Public License
|
| 371 |
+
without affecting the enforceability of the remaining terms and
|
| 372 |
+
conditions.
|
| 373 |
+
|
| 374 |
+
c. No term or condition of this Public License will be waived and no
|
| 375 |
+
failure to comply consented to unless expressly agreed to by the
|
| 376 |
+
Licensor.
|
| 377 |
+
|
| 378 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
| 379 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
| 380 |
+
that apply to the Licensor or You, including from the legal
|
| 381 |
+
processes of any jurisdiction or authority.
|
| 382 |
+
|
| 383 |
+
=======================================================================
|
| 384 |
+
|
| 385 |
+
Creative Commons is not a party to its public
|
| 386 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
| 387 |
+
its public licenses to material it publishes and in those instances
|
| 388 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
| 389 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
| 390 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
| 391 |
+
material is shared under a Creative Commons public license or as
|
| 392 |
+
otherwise permitted by the Creative Commons policies published at
|
| 393 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
| 394 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
| 395 |
+
of Creative Commons without its prior written consent including,
|
| 396 |
+
without limitation, in connection with any unauthorized modifications
|
| 397 |
+
to any of its public licenses or any other arrangements,
|
| 398 |
+
understandings, or agreements concerning use of licensed material. For
|
| 399 |
+
the avoidance of doubt, this paragraph does not form part of the
|
| 400 |
+
public licenses.
|
| 401 |
+
|
| 402 |
+
Creative Commons may be contacted at creativecommons.org.
|
scripts/BiScope/biscope_utils.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import pickle
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from torch.nn import CrossEntropyLoss
|
| 9 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 10 |
+
|
| 11 |
+
# Minimal model zoo mapping model keys to pretrained model names.
|
| 12 |
+
MODEL_ZOO = {
|
| 13 |
+
'llama2-7b': 'meta-llama/Llama-2-7b-chat-hf',
|
| 14 |
+
'llama2-13b': 'meta-llama/Llama-2-13b-chat-hf',
|
| 15 |
+
'gemma-2b': 'google/gemma-1.1-2b-it',
|
| 16 |
+
'gemma-7b': 'google/gemma-1.1-7b-it',
|
| 17 |
+
# 'llama3-8b': 'meta-llama/Meta-Llama-3-8B-Instruct',
|
| 18 |
+
'gpt2-xl': 'gpt2-xl',
|
| 19 |
+
'qwen-7b': 'Qwen/Qwen2.5-7B',
|
| 20 |
+
'llama3-8b': 'meta-llama/Meta-Llama-3-8B',
|
| 21 |
+
'mistralai-7b': 'mistralai/Mistral-7B-Instruct-v0.2',
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
# Prompt templates for text completion.
|
| 25 |
+
COMPLETION_PROMPT_ONLY = "Complete the following text: "
|
| 26 |
+
COMPLETION_PROMPT = "Given the summary:\n{prompt}\n Complete the following text: "
|
| 27 |
+
|
| 28 |
+
def generate(model, tokenizer, input_ids, trigger_length, target_length):
|
| 29 |
+
"""
|
| 30 |
+
Generate additional tokens using the model's generation API.
|
| 31 |
+
|
| 32 |
+
Parameters:
|
| 33 |
+
model: the language model for generation.
|
| 34 |
+
tokenizer: associated tokenizer.
|
| 35 |
+
input_ids: input token IDs (either 1D or 2D).
|
| 36 |
+
trigger_length: the length of the prompt (number of tokens to skip in the output).
|
| 37 |
+
target_length: the number of new tokens to generate.
|
| 38 |
+
|
| 39 |
+
Returns:
|
| 40 |
+
Generated tokens (as a 2D tensor) after removing the trigger tokens.
|
| 41 |
+
"""
|
| 42 |
+
config = model.generation_config
|
| 43 |
+
config.max_new_tokens = target_length
|
| 44 |
+
# If input_ids is 1D, add a batch dimension; otherwise, assume it's already 2D.
|
| 45 |
+
if input_ids.dim() == 1:
|
| 46 |
+
input_ids = input_ids.to(model.device).unsqueeze(0)
|
| 47 |
+
else:
|
| 48 |
+
input_ids = input_ids.to(model.device)
|
| 49 |
+
# Create an attention mask of the same shape.
|
| 50 |
+
attn_masks = torch.ones(input_ids.shape, device=input_ids.device)
|
| 51 |
+
# Generate new tokens.
|
| 52 |
+
out = model.generate(
|
| 53 |
+
input_ids,
|
| 54 |
+
attention_mask=attn_masks,
|
| 55 |
+
generation_config=config,
|
| 56 |
+
pad_token_id=tokenizer.pad_token_id
|
| 57 |
+
)[0]
|
| 58 |
+
# Return output tokens after the prompt (slice along dimension 1).
|
| 59 |
+
return out[trigger_length:]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def compute_fce_loss(logits, targets, text_slice):
|
| 63 |
+
"""
|
| 64 |
+
Compute the FCE loss by shifting indices by 1.
|
| 65 |
+
Returns a NumPy array of loss values.
|
| 66 |
+
"""
|
| 67 |
+
loss = CrossEntropyLoss(reduction='none')(
|
| 68 |
+
logits[0, text_slice.start-1:text_slice.stop-1, :],
|
| 69 |
+
targets
|
| 70 |
+
)
|
| 71 |
+
return loss.detach().cpu().numpy()
|
| 72 |
+
|
| 73 |
+
def compute_bce_loss(logits, targets, text_slice):
|
| 74 |
+
"""
|
| 75 |
+
Compute the BCE loss without shifting indices.
|
| 76 |
+
Returns a NumPy array of loss values.
|
| 77 |
+
"""
|
| 78 |
+
loss = CrossEntropyLoss(reduction='none')(
|
| 79 |
+
logits[0, text_slice, :],
|
| 80 |
+
targets
|
| 81 |
+
)
|
| 82 |
+
return loss.detach().cpu().numpy()
|
| 83 |
+
|
| 84 |
+
def detect_single_sample(args, model, tokenizer, summary_model, summary_tokenizer, sample, device='cuda'):
|
| 85 |
+
"""
|
| 86 |
+
Process a sample by generating a summary-based prompt, tokenizing (with clipping),
|
| 87 |
+
obtaining model outputs, and computing loss-based features (FCE and BCE).
|
| 88 |
+
Returns a list of loss features computed over 10 segments.
|
| 89 |
+
"""
|
| 90 |
+
# Generate the summary-based prompt.
|
| 91 |
+
if 'gpt-' in args.summary_model:
|
| 92 |
+
from openai import OpenAI
|
| 93 |
+
openai_key = os.environ.get('OPENAI_API_KEY')
|
| 94 |
+
if not openai_key:
|
| 95 |
+
raise ValueError("OPENAI_API_KEY not found in environment.")
|
| 96 |
+
client = OpenAI(api_key=openai_key)
|
| 97 |
+
from tenacity import (
|
| 98 |
+
retry,
|
| 99 |
+
stop_after_attempt,
|
| 100 |
+
wait_random_exponential,
|
| 101 |
+
)
|
| 102 |
+
@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
|
| 103 |
+
def openai_backoff(client, **kwargs):
|
| 104 |
+
return client.chat.completions.create(**kwargs)
|
| 105 |
+
summary_input = f"generate a very short and concise summary for the following text, just the summary: {sample}"
|
| 106 |
+
response = openai_backoff(client, model=args.summary_model,
|
| 107 |
+
messages=[{"role": "user", "content": summary_input}])
|
| 108 |
+
summary_text = response.choices[0].message.content.strip()
|
| 109 |
+
# if '"""' in summary_text:
|
| 110 |
+
# summary_text = summary_text.split('"""')[-1]
|
| 111 |
+
prompt_text = COMPLETION_PROMPT.format(prompt=summary_text)
|
| 112 |
+
elif args.summary_model in MODEL_ZOO:
|
| 113 |
+
summary_input = f"Write a title for this text: {sample}\nJust output the title:"
|
| 114 |
+
summary_ids = summary_tokenizer(summary_input, return_tensors='pt',
|
| 115 |
+
max_length=args.sample_clip, truncation=True).input_ids.to(device)
|
| 116 |
+
summary_ids = summary_ids[:, 1:] # Remove start token.
|
| 117 |
+
gen_ids = generate(summary_model, summary_tokenizer, summary_ids, summary_ids.shape[1], 64)
|
| 118 |
+
summary_text = summary_tokenizer.decode(gen_ids, skip_special_tokens=True).strip().split('\n')[0]
|
| 119 |
+
prompt_text = COMPLETION_PROMPT.format(prompt=summary_text)
|
| 120 |
+
else:
|
| 121 |
+
prompt_text = COMPLETION_PROMPT_ONLY
|
| 122 |
+
|
| 123 |
+
# Tokenize the prompt and sample with token-level clipping.
|
| 124 |
+
prompt_ids = tokenizer(prompt_text, return_tensors='pt').input_ids.to(device)
|
| 125 |
+
text_ids = tokenizer(sample, return_tensors='pt', max_length=args.sample_clip, truncation=True).input_ids.to(device)
|
| 126 |
+
combined_ids = torch.cat([prompt_ids, text_ids], dim=1)
|
| 127 |
+
text_slice = slice(prompt_ids.shape[1], combined_ids.shape[1])
|
| 128 |
+
outputs = model(input_ids=combined_ids)
|
| 129 |
+
logits = outputs.logits
|
| 130 |
+
targets = combined_ids[0][text_slice]
|
| 131 |
+
|
| 132 |
+
# Compute loss features from FCE and BCE losses.
|
| 133 |
+
fce_loss = compute_fce_loss(logits, targets, text_slice)
|
| 134 |
+
bce_loss = compute_bce_loss(logits, targets, text_slice)
|
| 135 |
+
features = []
|
| 136 |
+
for p in range(1, 10):
|
| 137 |
+
split = len(fce_loss) * p // 10
|
| 138 |
+
features.extend([
|
| 139 |
+
np.mean(fce_loss[split:]), np.max(fce_loss[split:]),
|
| 140 |
+
np.min(fce_loss[split:]), np.std(fce_loss[split:]),
|
| 141 |
+
np.mean(bce_loss[split:]), np.max(bce_loss[split:]),
|
| 142 |
+
np.min(bce_loss[split:]), np.std(bce_loss[split:])
|
| 143 |
+
])
|
| 144 |
+
return features
|
| 145 |
+
|
| 146 |
+
def data_generation(args, out_dir, task, generative_model, base_dir):
|
| 147 |
+
"""
|
| 148 |
+
Generate loss-based features for both human and GPT samples and save them to disk.
|
| 149 |
+
|
| 150 |
+
Parameters:
|
| 151 |
+
out_dir: Output directory.
|
| 152 |
+
task: Task name (e.g., Arxiv, Code, Essay).
|
| 153 |
+
generative_model: Key for the GPT samples.
|
| 154 |
+
|
| 155 |
+
Returns:
|
| 156 |
+
The output directory.
|
| 157 |
+
"""
|
| 158 |
+
# Load summary model and its tokenizer if specified.
|
| 159 |
+
if args.summary_model in MODEL_ZOO:
|
| 160 |
+
summary_model = AutoModelForCausalLM.from_pretrained(
|
| 161 |
+
MODEL_ZOO[args.summary_model],
|
| 162 |
+
torch_dtype=torch.float16,
|
| 163 |
+
device_map='auto',
|
| 164 |
+
cache_dir=args.cache_dir,
|
| 165 |
+
).eval()
|
| 166 |
+
summary_tokenizer = AutoTokenizer.from_pretrained(
|
| 167 |
+
MODEL_ZOO[args.summary_model], padding_side='left', cache_dir=args.cache_dir,
|
| 168 |
+
)
|
| 169 |
+
summary_tokenizer.pad_token = summary_tokenizer.eos_token
|
| 170 |
+
else:
|
| 171 |
+
summary_model, summary_tokenizer = None, None
|
| 172 |
+
|
| 173 |
+
# Load detection model and its tokenizer.
|
| 174 |
+
if args.detect_model in MODEL_ZOO:
|
| 175 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 176 |
+
MODEL_ZOO[args.detect_model],
|
| 177 |
+
torch_dtype=torch.float16,
|
| 178 |
+
device_map='auto',
|
| 179 |
+
cache_dir=args.cache_dir,
|
| 180 |
+
).eval()
|
| 181 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 182 |
+
MODEL_ZOO[args.detect_model], padding_side='left', cache_dir=args.cache_dir,
|
| 183 |
+
)
|
| 184 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 185 |
+
else:
|
| 186 |
+
raise ValueError("Unknown detection model")
|
| 187 |
+
|
| 188 |
+
if getattr(args, "use_hf_dataset", False):
|
| 189 |
+
# Load from Hugging Face dataset.
|
| 190 |
+
from datasets import load_dataset
|
| 191 |
+
ds = load_dataset("HanxiGuo/BiScope_Data", split="train")
|
| 192 |
+
paraphrased_flag = False
|
| 193 |
+
|
| 194 |
+
# Filter human data: use rows where task matches, and source is 'human'.
|
| 195 |
+
human_data = ds.filter(lambda x: x["task"] == task and x["source"].lower() == "human")
|
| 196 |
+
human_data = [s["text"] for s in human_data]
|
| 197 |
+
|
| 198 |
+
# Filter GPT-generated data: use rows where task and paraphrased flag match and source matches generative_model.
|
| 199 |
+
# (Assumes that the GPT-generated samples have source equal to the provided generative_model string.)
|
| 200 |
+
gpt_data = ds.filter(lambda x: x["task"] == task and x["paraphrased"] == paraphrased_flag and x["source"].lower() == generative_model.lower())
|
| 201 |
+
gpt_data = [s["text"] for s in gpt_data]
|
| 202 |
+
else:
|
| 203 |
+
|
| 204 |
+
# Load human data. Human data do not have paraphrased version, so only use the normal data.
|
| 205 |
+
with open(f'{base_dir}/{task}_{generative_model}.raw_data.json', 'r') as f:
|
| 206 |
+
dataset = json.load(f)
|
| 207 |
+
|
| 208 |
+
human_data = dataset['original']
|
| 209 |
+
gpt_data = dataset['sampled']
|
| 210 |
+
|
| 211 |
+
# Define the human features file path internally.
|
| 212 |
+
human_feat_path = os.path.join(out_dir, f"{task}_human_features.pkl")
|
| 213 |
+
|
| 214 |
+
# Generate and save human features.
|
| 215 |
+
human_features = [detect_single_sample(args, model, tokenizer, summary_model, summary_tokenizer, s, device='cuda') for s in tqdm(human_data)]
|
| 216 |
+
with open(human_feat_path, 'wb') as f:
|
| 217 |
+
pickle.dump(human_features, f)
|
| 218 |
+
|
| 219 |
+
# Generate and save GPT features.
|
| 220 |
+
gpt_feat_path = os.path.join(out_dir, f"{task}_GPT_features.pkl")
|
| 221 |
+
gpt_features = [detect_single_sample(args, model, tokenizer, summary_model, summary_tokenizer, s, device='cuda') for s in tqdm(gpt_data)]
|
| 222 |
+
with open(gpt_feat_path, 'wb') as f:
|
| 223 |
+
pickle.dump(gpt_features, f)
|
| 224 |
+
|
| 225 |
+
return out_dir
|
scripts/ImBD/.gitignore
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Byte-compiled / optimized / DLL files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
|
| 6 |
+
# C extensions
|
| 7 |
+
*.so
|
| 8 |
+
|
| 9 |
+
# Distribution / packaging
|
| 10 |
+
.Python
|
| 11 |
+
ckpt/*/
|
| 12 |
+
logs/*/
|
| 13 |
+
models/*/
|
| 14 |
+
build/
|
| 15 |
+
develop-eggs/
|
| 16 |
+
dist/
|
| 17 |
+
downloads/
|
| 18 |
+
eggs/
|
| 19 |
+
.eggs/
|
| 20 |
+
lib/
|
| 21 |
+
lib64/
|
| 22 |
+
parts/
|
| 23 |
+
sdist/
|
| 24 |
+
var/
|
| 25 |
+
wheels/
|
| 26 |
+
share/python-wheels/
|
| 27 |
+
*.egg-info/
|
| 28 |
+
.installed.cfg
|
| 29 |
+
*.egg
|
| 30 |
+
MANIFEST
|
| 31 |
+
|
| 32 |
+
# PyInstaller
|
| 33 |
+
# Usually these files are written by a python script from a template
|
| 34 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 35 |
+
*.manifest
|
| 36 |
+
*.spec
|
| 37 |
+
|
| 38 |
+
# Installer logs
|
| 39 |
+
pip-log.txt
|
| 40 |
+
pip-delete-this-directory.txt
|
| 41 |
+
|
| 42 |
+
# Unit test / coverage reports
|
| 43 |
+
htmlcov/
|
| 44 |
+
.tox/
|
| 45 |
+
.nox/
|
| 46 |
+
.coverage
|
| 47 |
+
.coverage.*
|
| 48 |
+
.cache
|
| 49 |
+
nosetests.xml
|
| 50 |
+
coverage.xml
|
| 51 |
+
*.cover
|
| 52 |
+
*.py,cover
|
| 53 |
+
.hypothesis/
|
| 54 |
+
.pytest_cache/
|
| 55 |
+
cover/
|
| 56 |
+
|
| 57 |
+
# Translations
|
| 58 |
+
*.mo
|
| 59 |
+
*.pot
|
| 60 |
+
|
| 61 |
+
# Django stuff:
|
| 62 |
+
*.log
|
| 63 |
+
local_settings.py
|
| 64 |
+
db.sqlite3
|
| 65 |
+
db.sqlite3-journal
|
| 66 |
+
|
| 67 |
+
# Flask stuff:
|
| 68 |
+
instance/
|
| 69 |
+
.webassets-cache
|
| 70 |
+
|
| 71 |
+
# Scrapy stuff:
|
| 72 |
+
.scrapy
|
| 73 |
+
|
| 74 |
+
# Sphinx documentation
|
| 75 |
+
docs/_build/
|
| 76 |
+
|
| 77 |
+
# PyBuilder
|
| 78 |
+
.pybuilder/
|
| 79 |
+
target/
|
| 80 |
+
|
| 81 |
+
# Jupyter Notebook
|
| 82 |
+
.ipynb_checkpoints
|
| 83 |
+
|
| 84 |
+
# IPython
|
| 85 |
+
profile_default/
|
| 86 |
+
ipython_config.py
|
| 87 |
+
|
| 88 |
+
# pyenv
|
| 89 |
+
# For a library or package, you might want to ignore these files since the code is
|
| 90 |
+
# intended to run in multiple environments; otherwise, check them in:
|
| 91 |
+
# .python-version
|
| 92 |
+
|
| 93 |
+
# pipenv
|
| 94 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
| 95 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
| 96 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
| 97 |
+
# install all needed dependencies.
|
| 98 |
+
#Pipfile.lock
|
| 99 |
+
|
| 100 |
+
# poetry
|
| 101 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
| 102 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 103 |
+
# commonly ignored for libraries.
|
| 104 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
| 105 |
+
#poetry.lock
|
| 106 |
+
|
| 107 |
+
# pdm
|
| 108 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
| 109 |
+
#pdm.lock
|
| 110 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
| 111 |
+
# in version control.
|
| 112 |
+
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
| 113 |
+
.pdm.toml
|
| 114 |
+
.pdm-python
|
| 115 |
+
.pdm-build/
|
| 116 |
+
|
| 117 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
| 118 |
+
__pypackages__/
|
| 119 |
+
|
| 120 |
+
# Celery stuff
|
| 121 |
+
celerybeat-schedule
|
| 122 |
+
celerybeat.pid
|
| 123 |
+
|
| 124 |
+
# SageMath parsed files
|
| 125 |
+
*.sage.py
|
| 126 |
+
|
| 127 |
+
# Environments
|
| 128 |
+
.env
|
| 129 |
+
.venv
|
| 130 |
+
env/
|
| 131 |
+
venv/
|
| 132 |
+
ENV/
|
| 133 |
+
env.bak/
|
| 134 |
+
venv.bak/
|
| 135 |
+
|
| 136 |
+
# Spyder project settings
|
| 137 |
+
.spyderproject
|
| 138 |
+
.spyproject
|
| 139 |
+
|
| 140 |
+
# Rope project settings
|
| 141 |
+
.ropeproject
|
| 142 |
+
|
| 143 |
+
# mkdocs documentation
|
| 144 |
+
/site
|
| 145 |
+
|
| 146 |
+
# mypy
|
| 147 |
+
.mypy_cache/
|
| 148 |
+
.dmypy.json
|
| 149 |
+
dmypy.json
|
| 150 |
+
|
| 151 |
+
# Pyre type checker
|
| 152 |
+
.pyre/
|
| 153 |
+
|
| 154 |
+
# pytype static type analyzer
|
| 155 |
+
.pytype/
|
| 156 |
+
|
| 157 |
+
# Cython debug symbols
|
| 158 |
+
cython_debug/
|
| 159 |
+
|
| 160 |
+
# PyCharm
|
| 161 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
| 162 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
| 163 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
| 164 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
| 165 |
+
#.idea/
|
scripts/ImBD/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 95 |
+
Derivative 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,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
scripts/ImBD/dataset.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch.utils.data import Dataset
|
| 2 |
+
import json
|
| 3 |
+
from utils import load_training_data
|
| 4 |
+
|
| 5 |
+
class CustomDataset(Dataset):
|
| 6 |
+
def __init__(self, data_json_dir):
|
| 7 |
+
with open(data_json_dir, 'r') as f:
|
| 8 |
+
data_json = json.load(f)
|
| 9 |
+
self.data = self.process_data(data_json)
|
| 10 |
+
|
| 11 |
+
def __len__(self):
|
| 12 |
+
return len(self.data['original'])
|
| 13 |
+
|
| 14 |
+
def __getitem__(self, index):
|
| 15 |
+
original_text = self.data['original'][index]
|
| 16 |
+
sampled_text = self.data['sampled'][index]
|
| 17 |
+
|
| 18 |
+
return {
|
| 19 |
+
'text': [original_text, sampled_text],
|
| 20 |
+
'label': [0, 1] # Original label is 0, Sampled label is 1
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
def process_data(self, data_json):
|
| 24 |
+
processed_data = {
|
| 25 |
+
'original': data_json['original'],
|
| 26 |
+
'sampled': data_json['sampled']
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
return processed_data
|
| 30 |
+
|
| 31 |
+
class CustomDataset_rewrite(Dataset):
|
| 32 |
+
def __init__(self, data_json_dir):
|
| 33 |
+
self.data_json_dir = data_json_dir
|
| 34 |
+
if "&" in data_json_dir:
|
| 35 |
+
data_name_list = data_json_dir.split('&')
|
| 36 |
+
data_json = load_training_data(data_name_list)
|
| 37 |
+
else:
|
| 38 |
+
with open(data_json_dir+'.raw_data.json', 'r') as f:
|
| 39 |
+
data_json = json.load(f)
|
| 40 |
+
self.data = self.process_data(data_json)
|
| 41 |
+
|
| 42 |
+
def __len__(self):
|
| 43 |
+
return len(self.data['original'])
|
| 44 |
+
|
| 45 |
+
def __getitem__(self, index):
|
| 46 |
+
original_text = self.data['original'][index]
|
| 47 |
+
sampled_text = self.data['sampled'][index]
|
| 48 |
+
|
| 49 |
+
return original_text, sampled_text
|
| 50 |
+
|
| 51 |
+
def process_data(self, data_json):
|
| 52 |
+
if "pubmed" in self.data_json_dir:
|
| 53 |
+
processed_data = {
|
| 54 |
+
'original': [qa.split("Answer:")[1].strip() for qa in data_json['original']],
|
| 55 |
+
'sampled': [qa.split("Answer:")[1].strip() for qa in data_json['sampled']]
|
| 56 |
+
}
|
| 57 |
+
else:
|
| 58 |
+
processed_data = {
|
| 59 |
+
'original': data_json['original'],
|
| 60 |
+
'sampled': data_json['sampled']
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
return processed_data
|
| 64 |
+
|
| 65 |
+
class CustomDataset_split(Dataset):
|
| 66 |
+
def __init__(self, data_json_dir, split='train', val_ratio=0.2):
|
| 67 |
+
with open(data_json_dir, 'r') as f:
|
| 68 |
+
data_json = json.load(f)
|
| 69 |
+
self.data = self.process_data(data_json)
|
| 70 |
+
|
| 71 |
+
total_size = len(self.data['original'])
|
| 72 |
+
|
| 73 |
+
if val_ratio == 0:
|
| 74 |
+
self.indices = [i for i in range(total_size)]
|
| 75 |
+
return
|
| 76 |
+
|
| 77 |
+
# Compute step size for stratified sampling
|
| 78 |
+
step_size = int(1 / val_ratio)
|
| 79 |
+
|
| 80 |
+
val_indices = list(range(0, total_size, step_size))
|
| 81 |
+
train_indices = [i for i in range(total_size) if i not in val_indices]
|
| 82 |
+
# print(val_indices)
|
| 83 |
+
# print(train_indices)
|
| 84 |
+
if split == 'train':
|
| 85 |
+
self.indices = train_indices
|
| 86 |
+
elif split == 'val':
|
| 87 |
+
self.indices = val_indices
|
| 88 |
+
else:
|
| 89 |
+
raise ValueError("split must be either 'train' or 'val'")
|
| 90 |
+
|
| 91 |
+
def __len__(self):
|
| 92 |
+
return len(self.indices)
|
| 93 |
+
|
| 94 |
+
def __getitem__(self, index):
|
| 95 |
+
actual_index = self.indices[index]
|
| 96 |
+
original_text = self.data['original'][actual_index]
|
| 97 |
+
sampled_text = self.data['rewritten'][actual_index]
|
| 98 |
+
return original_text, sampled_text
|
| 99 |
+
|
| 100 |
+
def process_data(self, data_json):
|
| 101 |
+
processed_data = {
|
| 102 |
+
'original': data_json['original'],
|
| 103 |
+
'rewritten': data_json['rewritten']
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
return processed_data
|
scripts/ImBD/engine.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
from torch.utils.data import DataLoader
|
| 3 |
+
import tqdm
|
| 4 |
+
from torch.cuda.amp import GradScaler, autocast
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import nn
|
| 7 |
+
import torch
|
| 8 |
+
import numpy as np
|
| 9 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 10 |
+
import datetime
|
| 11 |
+
import os
|
| 12 |
+
import json
|
| 13 |
+
from metrics import get_roc_metrics, get_precision_recall_metrics
|
| 14 |
+
|
| 15 |
+
from torch.optim.lr_scheduler import CosineAnnealingLR
|
| 16 |
+
import time
|
| 17 |
+
from utils import GpuMem
|
| 18 |
+
try:
|
| 19 |
+
from transformers import AdamW
|
| 20 |
+
except:
|
| 21 |
+
from torch.optim import AdamW
|
| 22 |
+
|
| 23 |
+
def evaluate_model_SPO(model, data, DEVICE):
|
| 24 |
+
model.to(DEVICE)
|
| 25 |
+
model.eval()
|
| 26 |
+
loss = 0
|
| 27 |
+
eval_loader = DataLoader(data, batch_size=1, shuffle=False)
|
| 28 |
+
epoch_crit_train_original, epoch_crit_train_sampled = [],[]
|
| 29 |
+
start_time = time.time()
|
| 30 |
+
with torch.no_grad():
|
| 31 |
+
for batch in tqdm.tqdm(eval_loader, desc="Evaluating"):
|
| 32 |
+
text = batch
|
| 33 |
+
output = model(text)
|
| 34 |
+
loss += output['loss'].item()
|
| 35 |
+
epoch_crit_train_original.extend(output['crit'][1].tolist())
|
| 36 |
+
epoch_crit_train_sampled.extend(output['crit'][3].tolist())
|
| 37 |
+
|
| 38 |
+
print(f"Total time: {time.time() - start_time:.4f}s")
|
| 39 |
+
avg_loss = loss / len(eval_loader)
|
| 40 |
+
fpr, tpr, roc_auc = get_roc_metrics(epoch_crit_train_original, epoch_crit_train_sampled)
|
| 41 |
+
p, r, pr_auc = get_precision_recall_metrics(epoch_crit_train_original, epoch_crit_train_sampled)
|
| 42 |
+
|
| 43 |
+
# print(f"val_loss: {avg_loss:.6f}")
|
| 44 |
+
print(f"val_ROC_AUC: {roc_auc:.4f}, PR AUC: {pr_auc:.4f}")
|
| 45 |
+
print(f"val_Real_mean/std: {np.mean(epoch_crit_train_original):.2f}/{np.std(epoch_crit_train_original):.2f}, val_Samples_mean/std: {np.mean(epoch_crit_train_sampled):.2f}/{np.std(epoch_crit_train_sampled):.2f}")
|
| 46 |
+
print("="*10)
|
| 47 |
+
|
| 48 |
+
results_dict = {
|
| 49 |
+
"name": "imbd",
|
| 50 |
+
'info': {'n_samples': len(epoch_crit_train_original)},
|
| 51 |
+
'predictions': {'real': epoch_crit_train_original,
|
| 52 |
+
'samples': epoch_crit_train_sampled},
|
| 53 |
+
'metrics': {'roc_auc': roc_auc, 'fpr': fpr, 'tpr': tpr},
|
| 54 |
+
'pr_metrics': {'pr_auc': pr_auc, 'precision': p, 'recall': r},
|
| 55 |
+
}
|
| 56 |
+
return results_dict
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def fine_tune_ours(model, data, DEVICE, ckpt_dir='./ckpt', args=None):
|
| 60 |
+
current_time = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 61 |
+
writer = SummaryWriter(log_dir=f"./scripts/ImBD/logs/{args.task_name}_spo_lr_{args.lr}_beta_{args.beta}_a_{args.a}_{current_time}/train_ai_detection")
|
| 62 |
+
|
| 63 |
+
train_loader = DataLoader(data[0], batch_size=1, shuffle=True)
|
| 64 |
+
epochs = args.epochs
|
| 65 |
+
optimizer = AdamW(model.parameters(), lr=args.lr)
|
| 66 |
+
scheduler = CosineAnnealingLR(optimizer, T_max=len(train_loader) * epochs, eta_min=0,
|
| 67 |
+
last_epoch=-1)
|
| 68 |
+
|
| 69 |
+
scaler = GradScaler()
|
| 70 |
+
model.to(DEVICE)
|
| 71 |
+
|
| 72 |
+
# Number of iterations for gradient accumulation
|
| 73 |
+
accumulation_steps = args.a
|
| 74 |
+
epoch_losses, i, loss = [], 0, torch.tensor(0.0).to(DEVICE)
|
| 75 |
+
epoch_crit_train_original, epoch_crit_train_sampled = [],[]
|
| 76 |
+
start_time = time.time()
|
| 77 |
+
for epoch in range(epochs):
|
| 78 |
+
optimizer.zero_grad()
|
| 79 |
+
start_time = time.time()
|
| 80 |
+
for batch in tqdm.tqdm(train_loader, desc=f"Fine-tuning: {epoch} epoch"):
|
| 81 |
+
text = batch
|
| 82 |
+
scheduler.step()
|
| 83 |
+
with autocast():
|
| 84 |
+
outputs_1 = model(text)
|
| 85 |
+
epoch_crit_train_original.extend(outputs_1['crit'][1].tolist())
|
| 86 |
+
epoch_crit_train_sampled.extend(outputs_1['crit'][3].tolist())
|
| 87 |
+
loss += (outputs_1['loss'].to(torch.float32)) / accumulation_steps
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if ((i + 1) % accumulation_steps) == 0:
|
| 91 |
+
scaler.scale(loss).backward()
|
| 92 |
+
scaler.step(optimizer)
|
| 93 |
+
optimizer.zero_grad()
|
| 94 |
+
scaler.update()
|
| 95 |
+
writer.add_scalar('Loss/train', loss.item(), i)
|
| 96 |
+
epoch_losses.append(loss.item())
|
| 97 |
+
loss = torch.tensor(0.0).to(DEVICE)
|
| 98 |
+
epoch_losses.append(loss.item())
|
| 99 |
+
i += 1
|
| 100 |
+
print(f"Total time: {time.time() - start_time:.4f}s")
|
| 101 |
+
fpr, tpr, roc_auc = get_roc_metrics(epoch_crit_train_original, epoch_crit_train_sampled)
|
| 102 |
+
p, r, pr_auc = get_precision_recall_metrics(epoch_crit_train_original, epoch_crit_train_sampled)
|
| 103 |
+
|
| 104 |
+
print(f"ROC AUC: {roc_auc:.4f}, PR AUC: {pr_auc:.4f}")
|
| 105 |
+
print(f"Real mean/std: {np.mean(epoch_crit_train_original):.2f}/{np.std(epoch_crit_train_original):.2f}, Samples mean/std: {np.mean(epoch_crit_train_sampled):.2f}/{np.std(epoch_crit_train_sampled):.2f}")
|
| 106 |
+
epoch_avg_loss = np.mean(epoch_losses)
|
| 107 |
+
|
| 108 |
+
writer.add_scalar('Loss/epoch', epoch_avg_loss, epoch)
|
| 109 |
+
writer.add_scalar('ROC_AUC/epoch', roc_auc, epoch)
|
| 110 |
+
writer.add_scalar('PR_AUC/epoch', pr_auc, epoch)
|
| 111 |
+
writer.add_scalar('Real_mean/epoch',np.mean(epoch_crit_train_original),epoch)
|
| 112 |
+
writer.add_scalar('Real_std/epoch',np.std(epoch_crit_train_original),epoch)
|
| 113 |
+
writer.add_scalar('Sampled_mean/epoch',np.mean(epoch_crit_train_sampled),epoch)
|
| 114 |
+
writer.add_scalar('Sampled_std/epoch',np.std(epoch_crit_train_sampled),epoch)
|
| 115 |
+
epoch_crit_train_original, epoch_crit_train_sampled = [],[] # reset crit
|
| 116 |
+
print(f"\nAverage Loss for Epoch {epoch}: {epoch_avg_loss}")
|
| 117 |
+
|
| 118 |
+
# if not os.path.exists(ckpt_dir):
|
| 119 |
+
# os.makedirs(ckpt_dir)
|
| 120 |
+
# model.save_pretrained(ckpt_dir)
|
| 121 |
+
# print(f"Saved finetuned model to {os.path.join(ckpt_dir, 'ours-finetuned.pth')}")
|
| 122 |
+
|
| 123 |
+
writer.close()
|
| 124 |
+
return model
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def run(
|
| 128 |
+
model,
|
| 129 |
+
data,
|
| 130 |
+
DEVICE,
|
| 131 |
+
args,
|
| 132 |
+
ckpt_dir='./ckpt',
|
| 133 |
+
):
|
| 134 |
+
|
| 135 |
+
if args.ebt or args.eval_only:
|
| 136 |
+
print("Evaluating model before tuning...")
|
| 137 |
+
d = evaluate_model_SPO(model, data[1], DEVICE)
|
| 138 |
+
if args.SPOtrained:
|
| 139 |
+
output_path = f"{args.output_file}.imbd.json"
|
| 140 |
+
else:
|
| 141 |
+
method_name=args.base_model.split("_")[-1]
|
| 142 |
+
output_path = f"{args.output_file}.{method_name}.json"
|
| 143 |
+
with open(output_path, "w") as j:
|
| 144 |
+
json.dump(d,j)
|
| 145 |
+
print(f"Results saved to {output_path}.")
|
| 146 |
+
if args.eval_only:
|
| 147 |
+
return
|
| 148 |
+
|
| 149 |
+
tracker = GpuMem()
|
| 150 |
+
print('Fine-tuning model...')
|
| 151 |
+
start = time.perf_counter()
|
| 152 |
+
with tracker:
|
| 153 |
+
model = fine_tune_ours(
|
| 154 |
+
model,
|
| 155 |
+
data,
|
| 156 |
+
DEVICE=DEVICE,
|
| 157 |
+
ckpt_dir=ckpt_dir,
|
| 158 |
+
args=args
|
| 159 |
+
)
|
| 160 |
+
pre_time = time.perf_counter() - start
|
| 161 |
+
pre_memory = tracker.memory_usage()
|
| 162 |
+
|
| 163 |
+
if args.eval_after_train:
|
| 164 |
+
print("Evaluating model after tuning...")
|
| 165 |
+
start = time.perf_counter()
|
| 166 |
+
with tracker:
|
| 167 |
+
d = evaluate_model_SPO(model, data[1], DEVICE)
|
| 168 |
+
eval_time = time.perf_counter() - start
|
| 169 |
+
eval_time = eval_time / (len(data[1]) << 1)
|
| 170 |
+
eval_memory = tracker.memory_usage()
|
| 171 |
+
d['compute_info'] = {'pre_time': pre_time, 'eval_time': eval_time,
|
| 172 |
+
'pre_memory': pre_memory, 'eval_memory': eval_memory,}
|
| 173 |
+
if args.SPOtrained:
|
| 174 |
+
output_path = f"{args.output_file}.imbd.json"
|
| 175 |
+
else:
|
| 176 |
+
method_name=args.base_model.split("_")[-1]
|
| 177 |
+
output_path = f"{args.output_file}.{method_name}.json"
|
| 178 |
+
with open(output_path, "w") as j:
|
| 179 |
+
json.dump(d, j)
|
| 180 |
+
print(f"Results saved to {output_path}.")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
|
scripts/ImBD/evaluation.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
import argparse
|
| 4 |
+
from .spo import get_sampling_discrepancy_analytic
|
| 5 |
+
from transformers import AutoTokenizer
|
| 6 |
+
from peft import AutoPeftModelForCausalLM
|
| 7 |
+
import time
|
| 8 |
+
from metrics import get_roc_metrics, get_precision_recall_metrics
|
| 9 |
+
import tqdm
|
| 10 |
+
from torch.utils.data import DataLoader
|
| 11 |
+
from .dataset import CustomDataset_rewrite
|
| 12 |
+
import os
|
| 13 |
+
import json
|
| 14 |
+
|
| 15 |
+
def run(args):
|
| 16 |
+
|
| 17 |
+
# Generate the inference checkpoint from trained model
|
| 18 |
+
# from spo import ComputeScore
|
| 19 |
+
# model = ComputeScore("gpt-neo-2.7B", "gpt-neo-2.7B", cache_dir=args.cache_dir)
|
| 20 |
+
# model.from_pretrained(args.from_pretrained)
|
| 21 |
+
# scoring_model = model.scoring_model
|
| 22 |
+
# scoring_tokenizer = model.scoring_tokenizer
|
| 23 |
+
# scoring_model.save_pretrained('models/ImBD-inference')
|
| 24 |
+
# scoring_tokenizer.save_pretrained('models/ImBD-inference')
|
| 25 |
+
|
| 26 |
+
model_name = "models/ImBD-inference"
|
| 27 |
+
print('Loading model')
|
| 28 |
+
start_time = time.time()
|
| 29 |
+
scoring_model = AutoPeftModelForCausalLM.from_pretrained(model_name) # Make sure you have downloaded the gpt-neo-2.7b and place it at `models` folder.
|
| 30 |
+
scoring_tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 31 |
+
scoring_tokenizer.pad_token = scoring_tokenizer.eos_token
|
| 32 |
+
scoring_model.to(args.device)
|
| 33 |
+
scoring_model.eval()
|
| 34 |
+
print(f'Done. ({time.time()-start_time:.2f}s)')
|
| 35 |
+
|
| 36 |
+
criterion_fn = get_sampling_discrepancy_analytic
|
| 37 |
+
print('Loading dataset')
|
| 38 |
+
start_time = time.time()
|
| 39 |
+
val_data = CustomDataset_rewrite(data_json_dir=args.eval_dataset)
|
| 40 |
+
print(f'Done. ({time.time()-start_time:.2f}s)')
|
| 41 |
+
print(f"Evaluating on {args.eval_dataset.split('/')[-1]}")
|
| 42 |
+
evaluate_model(scoring_model, scoring_tokenizer, criterion_fn, val_data, args)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def evaluate_model(model, tokenizer, criterion_fn, data, args):
|
| 46 |
+
eval_loader = DataLoader(data, batch_size=1, shuffle=False)
|
| 47 |
+
epoch_crit_train_original, epoch_crit_train_sampled = [],[]
|
| 48 |
+
start_time = time.time()
|
| 49 |
+
with torch.no_grad():
|
| 50 |
+
for batch in tqdm.tqdm(eval_loader, desc=f"Evaluating {args.eval_dataset.split('/')[-1]}"):
|
| 51 |
+
output = []
|
| 52 |
+
for text in batch:
|
| 53 |
+
tokenized = tokenizer(text, truncation=True, return_tensors="pt", padding=True, return_token_type_ids=False).to(args.device)
|
| 54 |
+
labels = tokenized.input_ids[:, 1:]
|
| 55 |
+
with torch.no_grad():
|
| 56 |
+
logits_score = model(**tokenized).logits[:, :-1]
|
| 57 |
+
logits_ref = logits_score
|
| 58 |
+
crit, _ = criterion_fn(logits_ref, logits_score, labels)
|
| 59 |
+
crit = crit.cpu().numpy().item()
|
| 60 |
+
output.append(crit)
|
| 61 |
+
# output.append(inv_crit)
|
| 62 |
+
crit_original, crit_sampled = output
|
| 63 |
+
epoch_crit_train_original.append(crit_original)
|
| 64 |
+
epoch_crit_train_sampled.append(crit_sampled)
|
| 65 |
+
|
| 66 |
+
print(f"Total time: {time.time() - start_time:.4f}s")
|
| 67 |
+
fpr, tpr, roc_auc = get_roc_metrics(epoch_crit_train_original, epoch_crit_train_sampled)
|
| 68 |
+
p, r, pr_auc = get_precision_recall_metrics(epoch_crit_train_original, epoch_crit_train_sampled)
|
| 69 |
+
os.makedirs("./evaluation", exist_ok=True)
|
| 70 |
+
with open(os.path.join("./evaluation", args.eval_dataset.split("/")[-1].replace("raw_data", str(roc_auc)[:7])),'w') as f:
|
| 71 |
+
json.dump({"fpr":fpr, "tpr":tpr, "roc_auc":roc_auc, "crit_real":epoch_crit_train_original, "crit_sampled":epoch_crit_train_sampled, "pr_auc":pr_auc}, f)
|
| 72 |
+
print(f"ROC AUC:{roc_auc}")
|
| 73 |
+
|
| 74 |
+
if __name__ == '__main__':
|
| 75 |
+
parser = argparse.ArgumentParser()
|
| 76 |
+
parser.add_argument('--device', type=str, default="cuda")
|
| 77 |
+
parser.add_argument('--cache_dir', type=str, default="../cache")
|
| 78 |
+
parser.add_argument('--eval_dataset', type=str, default="./data/polish/gpt-4o/xsum_polish_gpt-4o.raw_data.json")
|
| 79 |
+
# parser.add_argument('--from_pretrained', type=str, default='./ckpt/ai_detection_polish_500_spo_lr_0.0001_beta_0.05_a_1')
|
| 80 |
+
args = parser.parse_args()
|
| 81 |
+
|
| 82 |
+
run(args)
|
scripts/ImBD/inference.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
import os
|
| 4 |
+
import glob
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
from .spo import get_sampling_discrepancy_analytic
|
| 8 |
+
from transformers import AutoTokenizer
|
| 9 |
+
from peft import AutoPeftModelForCausalLM
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
# estimate the probability according to the distribution of our test results on GPT-3.5 and GPT-4
|
| 13 |
+
class ProbEstimator:
|
| 14 |
+
def __init__(self, args):
|
| 15 |
+
self.tasks = ["polish", "generate", "rewrite", "expand"] if args.task == "all" else [args.task]
|
| 16 |
+
self.real_crits = {"polish":[], "generate":[], "rewrite":[], "expand":[]}
|
| 17 |
+
self.fake_crits = {"polish":[], "generate":[], "rewrite":[], "expand":[]}
|
| 18 |
+
for task in self.tasks:
|
| 19 |
+
for result_file in glob.glob(os.path.join(args.ref_path, task, '*.json')):
|
| 20 |
+
with open(result_file, 'r') as fin:
|
| 21 |
+
res = json.load(fin)
|
| 22 |
+
self.real_crits[task].extend(res['crit_real'])
|
| 23 |
+
self.fake_crits[task].extend(res['crit_sampled'])
|
| 24 |
+
print(f'ProbEstimator: total {sum([len(self.real_crits[task]) for task in self.tasks]) * 2} samples.')
|
| 25 |
+
|
| 26 |
+
def crit_to_prob(self, crit):
|
| 27 |
+
real_crits = []
|
| 28 |
+
fake_crits = []
|
| 29 |
+
for task in self.tasks:
|
| 30 |
+
real_crits.extend(self.real_crits[task])
|
| 31 |
+
fake_crits.extend(self.fake_crits[task])
|
| 32 |
+
offset = np.sort(np.abs(np.array(real_crits + fake_crits) - crit))[100]
|
| 33 |
+
cnt_real = np.sum((np.array(real_crits) > crit - offset) & (np.array(real_crits) < crit + offset))
|
| 34 |
+
cnt_fake = np.sum((np.array(fake_crits) > crit - offset) & (np.array(fake_crits) < crit + offset))
|
| 35 |
+
return cnt_fake / (cnt_real + cnt_fake)
|
| 36 |
+
|
| 37 |
+
def crit_to_prob_detail(self, crit):
|
| 38 |
+
probs = []
|
| 39 |
+
for task in self.tasks:
|
| 40 |
+
real_crits = self.real_crits[task]
|
| 41 |
+
fake_crits = self.fake_crits[task]
|
| 42 |
+
offset = np.sort(np.abs(np.array(real_crits + fake_crits) - crit))[100]
|
| 43 |
+
cnt_real = np.sum((np.array(real_crits) > crit - offset) & (np.array(real_crits) < crit + offset))
|
| 44 |
+
cnt_fake = np.sum((np.array(fake_crits) > crit - offset) & (np.array(fake_crits) < crit + offset))
|
| 45 |
+
probs.append(cnt_fake / (cnt_real + cnt_fake))
|
| 46 |
+
return probs
|
| 47 |
+
|
| 48 |
+
# run interactive local inference
|
| 49 |
+
def run(args):
|
| 50 |
+
|
| 51 |
+
# Generate the inference checkpoint from trained model
|
| 52 |
+
# from spo import ComputeScore
|
| 53 |
+
# model = ComputeScore("gpt-neo-2.7B", "gpt-neo-2.7B", cache_dir=args.cache_dir)
|
| 54 |
+
# model.from_pretrained("ckpt/ai_detection_polish_500_spo_lr_0.0001_beta_0.05_a_1")
|
| 55 |
+
# scoring_model = model.scoring_model
|
| 56 |
+
# scoring_tokenizer = model.scoring_tokenizer
|
| 57 |
+
# scoring_model.save_pretrained('models/ImBD-inference')
|
| 58 |
+
# scoring_tokenizer.save_pretrained('models/ImBD-inference')
|
| 59 |
+
|
| 60 |
+
print('Loading model')
|
| 61 |
+
start_time = time.time()
|
| 62 |
+
scoring_model = AutoPeftModelForCausalLM.from_pretrained('models/ImBD-inference') # Make sure you have downloaded the gpt-neo-2.7b and place it at `models` folder.
|
| 63 |
+
scoring_tokenizer = AutoTokenizer.from_pretrained('models/ImBD-inference')
|
| 64 |
+
scoring_tokenizer.pad_token = scoring_tokenizer.eos_token
|
| 65 |
+
scoring_model.to(args.device)
|
| 66 |
+
scoring_model.eval()
|
| 67 |
+
print(f'Done. ({time.time()-start_time:.2f}s)')
|
| 68 |
+
|
| 69 |
+
criterion_fn = get_sampling_discrepancy_analytic
|
| 70 |
+
prob_estimator = ProbEstimator(args)
|
| 71 |
+
|
| 72 |
+
# input text
|
| 73 |
+
print('Local demo for ImBD, where the longer text has more reliable result.')
|
| 74 |
+
print('To view detail results for all tasks, set `--detail` to True.')
|
| 75 |
+
print('To view all-in-one results, set `--task` to `all`. (Not accurate enough)')
|
| 76 |
+
print('')
|
| 77 |
+
while True:
|
| 78 |
+
print("Please enter your text: (Press Enter twice to start processing)")
|
| 79 |
+
lines = []
|
| 80 |
+
while True:
|
| 81 |
+
line = input()
|
| 82 |
+
if len(line) == 0:
|
| 83 |
+
break
|
| 84 |
+
lines.append(line)
|
| 85 |
+
text = "\n".join(lines)
|
| 86 |
+
if len(text) == 0:
|
| 87 |
+
break
|
| 88 |
+
# evaluate text
|
| 89 |
+
tokenized = scoring_tokenizer(text, truncation=True, return_tensors="pt", padding=True, return_token_type_ids=False).to(args.device)
|
| 90 |
+
labels = tokenized.input_ids[:, 1:]
|
| 91 |
+
with torch.no_grad():
|
| 92 |
+
logits_score = scoring_model(**tokenized).logits[:, :-1]
|
| 93 |
+
logits_ref = logits_score
|
| 94 |
+
crit, _ = criterion_fn(logits_ref, logits_score, labels)
|
| 95 |
+
# estimate the probability of machine generated text
|
| 96 |
+
crit = crit.cpu().numpy().item()
|
| 97 |
+
if args.detail:
|
| 98 |
+
probs = prob_estimator.crit_to_prob_detail(crit)
|
| 99 |
+
print(f'ImBD criterion is {crit:.4f}, suggesting that the text has a probability of',sep=" ")
|
| 100 |
+
for task, prob in zip(prob_estimator.tasks, probs):
|
| 101 |
+
print(f'{prob * 100:.0f}% to be machine-{task},',sep=" ")
|
| 102 |
+
else:
|
| 103 |
+
prob = prob_estimator.crit_to_prob(crit)
|
| 104 |
+
print(f'ImBD criterion is {crit:.4f}, suggesting that the text has a probability of {prob * 100:.0f}% to be machine-{args.task}.')
|
| 105 |
+
print()
|
| 106 |
+
|
| 107 |
+
if __name__ == '__main__':
|
| 108 |
+
parser = argparse.ArgumentParser()
|
| 109 |
+
parser.add_argument('--ref_path', type=str, default="./local_infer_ref")
|
| 110 |
+
parser.add_argument('--device', type=str, default="cuda")
|
| 111 |
+
parser.add_argument('--cache_dir', type=str, default="../cache")
|
| 112 |
+
parser.add_argument('--task', type=str, default="generate", choices=["polish", "generate", "rewrite", "expand", "all"])
|
| 113 |
+
parser.add_argument('--detail', type=bool, default=False)
|
| 114 |
+
parser.add_argument('--from_pretrained', type=str, default='./ckpt/ai_detection_polish_500_spo_lr_0.0001_beta_0.05_a_1')
|
| 115 |
+
args = parser.parse_args()
|
| 116 |
+
|
| 117 |
+
run(args)
|
scripts/ImBD/spo.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch import nn
|
| 3 |
+
|
| 4 |
+
from peft import get_peft_model, LoraConfig, TaskType, AutoPeftModelForCausalLM
|
| 5 |
+
import os
|
| 6 |
+
from .utils_spo import calculate_SPO_loss
|
| 7 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
def from_pretrained(cls, model_name, kwargs, cache_dir):
|
| 11 |
+
# use local model if it exists
|
| 12 |
+
if "/" in model_name:
|
| 13 |
+
local_path = os.path.join(cache_dir, model_name.split("/")[1])
|
| 14 |
+
else:
|
| 15 |
+
local_path = os.path.join(cache_dir, model_name)
|
| 16 |
+
|
| 17 |
+
if os.path.exists(local_path):
|
| 18 |
+
return cls.from_pretrained(local_path, **kwargs)
|
| 19 |
+
return cls.from_pretrained(model_name, **kwargs, cache_dir=cache_dir, device_map='auto')
|
| 20 |
+
|
| 21 |
+
model_fullnames = {
|
| 22 |
+
'gpt-neo-2.7B': 'EleutherAI/gpt-neo-2.7B',
|
| 23 |
+
'gpt-j-6B': 'EleutherAI/gpt-j-6B',
|
| 24 |
+
'qwen-7b': 'Qwen/Qwen2.5-7B',
|
| 25 |
+
'mistralai-7b': 'mistralai/Mistral-7B-Instruct-v0.2',
|
| 26 |
+
'llama3-8b': 'meta-llama/Meta-Llama-3-8B',
|
| 27 |
+
}
|
| 28 |
+
float16_models = ['gpt-j-6B', 'gpt-neox-20b', 'qwen-7b', 'mistralai-7b', 'llama3-8b']
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_model_fullname(model_name):
|
| 32 |
+
return model_fullnames[model_name] if model_name in model_fullnames else model_name
|
| 33 |
+
|
| 34 |
+
def load_tokenizer(model_name, for_dataset, cache_dir):
|
| 35 |
+
model_fullname = get_model_fullname(model_name)
|
| 36 |
+
optional_tok_kwargs = {}
|
| 37 |
+
if "facebook/opt-" in model_fullname:
|
| 38 |
+
print("Using non-fast tokenizer for OPT")
|
| 39 |
+
optional_tok_kwargs['fast'] = False
|
| 40 |
+
if for_dataset in ['pubmed']:
|
| 41 |
+
optional_tok_kwargs['padding_side'] = 'left'
|
| 42 |
+
else:
|
| 43 |
+
optional_tok_kwargs['padding_side'] = 'right'
|
| 44 |
+
base_tokenizer = from_pretrained(AutoTokenizer, model_fullname, optional_tok_kwargs, cache_dir=cache_dir)
|
| 45 |
+
if base_tokenizer.pad_token_id is None:
|
| 46 |
+
base_tokenizer.pad_token_id = base_tokenizer.eos_token_id
|
| 47 |
+
if '13b' in model_fullname:
|
| 48 |
+
base_tokenizer.pad_token_id = 0
|
| 49 |
+
return base_tokenizer
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_sampling_discrepancy_analytic(logits_ref, logits_score, labels):
|
| 53 |
+
|
| 54 |
+
if logits_ref.size(-1) != logits_score.size(-1):
|
| 55 |
+
vocab_size = min(logits_ref.size(-1), logits_score.size(-1))
|
| 56 |
+
logits_ref = logits_ref[:, :, :vocab_size]
|
| 57 |
+
logits_score = logits_score[:, :, :vocab_size]
|
| 58 |
+
|
| 59 |
+
labels = labels.unsqueeze(-1) if labels.ndim == logits_score.ndim - 1 else labels
|
| 60 |
+
lprobs_score = torch.log_softmax(logits_score, dim=-1)
|
| 61 |
+
probs_ref = torch.softmax(logits_ref, dim=-1)
|
| 62 |
+
|
| 63 |
+
log_likelihood = lprobs_score.gather(dim=-1, index=labels).squeeze(-1)
|
| 64 |
+
mean_ref = (probs_ref * lprobs_score).sum(dim=-1)
|
| 65 |
+
var_ref = (probs_ref * torch.square(lprobs_score)).sum(dim=-1) - torch.square(mean_ref)
|
| 66 |
+
discrepancy = (log_likelihood.sum(dim=-1) - mean_ref.sum(dim=-1)) / var_ref.sum(dim=-1).sqrt()
|
| 67 |
+
|
| 68 |
+
return discrepancy, log_likelihood.sum(dim=-1)
|
| 69 |
+
|
| 70 |
+
class ComputeScore(nn.Module):
|
| 71 |
+
def __init__(self, scoring_model_name, reference_model_name, SPOtrained=True, SPO_beta=0.5, dataset='xsum', device='cuda', cache_dir='./models'):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.device = device
|
| 74 |
+
self.reference_model_name = get_model_fullname(reference_model_name)
|
| 75 |
+
self.scoring_model_name = get_model_fullname(scoring_model_name)
|
| 76 |
+
self.beta = SPO_beta
|
| 77 |
+
|
| 78 |
+
def load_model(model_name, device, cache_dir, SPOtrained=True):
|
| 79 |
+
model_fullname = get_model_fullname(model_name)
|
| 80 |
+
print(f'Loading model {model_fullname}...')
|
| 81 |
+
model_kwargs = {}
|
| 82 |
+
if model_name in float16_models:
|
| 83 |
+
model_kwargs.update(dict(torch_dtype=torch.float16))
|
| 84 |
+
if 'gpt-j' in model_name:
|
| 85 |
+
model_kwargs.update(dict(revision='float16'))
|
| 86 |
+
if SPOtrained:
|
| 87 |
+
model = from_pretrained(AutoModelForCausalLM, model_fullname, model_kwargs, cache_dir)
|
| 88 |
+
else: # Load ablation finetuned model
|
| 89 |
+
model = from_pretrained(AutoPeftModelForCausalLM, model_fullname, model_kwargs, cache_dir)
|
| 90 |
+
print('Moving model to GPU...', end='', flush=True)
|
| 91 |
+
start = time.time()
|
| 92 |
+
model.to(device)
|
| 93 |
+
print(f'DONE ({time.time() - start:.2f}s)')
|
| 94 |
+
return model
|
| 95 |
+
|
| 96 |
+
# load model
|
| 97 |
+
self.scoring_tokenizer = load_tokenizer(scoring_model_name, dataset, cache_dir)
|
| 98 |
+
scoring_model = load_model(scoring_model_name, device, cache_dir, SPOtrained)
|
| 99 |
+
|
| 100 |
+
self.peft_config = LoraConfig(
|
| 101 |
+
task_type=TaskType.CAUSAL_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
reference_model = load_model(reference_model_name, device, cache_dir, SPOtrained)
|
| 105 |
+
|
| 106 |
+
if SPOtrained:
|
| 107 |
+
self.scoring_model = get_peft_model(scoring_model, self.peft_config)
|
| 108 |
+
self.reference_model = get_peft_model(reference_model, self.peft_config)
|
| 109 |
+
else:
|
| 110 |
+
self.scoring_model = scoring_model
|
| 111 |
+
self.reference_model = reference_model
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
self.reference_tokenizer = load_tokenizer(reference_model_name, dataset, cache_dir)
|
| 115 |
+
|
| 116 |
+
self.criterion_fn = get_sampling_discrepancy_analytic
|
| 117 |
+
self.forward = self.forward_SPO
|
| 118 |
+
|
| 119 |
+
self.scoring_model.print_trainable_parameters()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def print_gradient_requirement(self):
|
| 123 |
+
for name, param in self.named_parameters():
|
| 124 |
+
gradient_requirement = 'Requires Grad' if param.requires_grad else 'Does not require grad'
|
| 125 |
+
color_code = '\033[92m' if param.requires_grad else '\033[91m' # Green for requires grad, red for does not require grad
|
| 126 |
+
reset_color = '\033[0m' # Reset color after printing
|
| 127 |
+
print(f"{name}: {color_code}{gradient_requirement}{reset_color}")
|
| 128 |
+
|
| 129 |
+
def register_no_grad(self, module_names):
|
| 130 |
+
for name, param in self.named_parameters():
|
| 131 |
+
for selected_module in module_names:
|
| 132 |
+
# print(selected_module, name)
|
| 133 |
+
if selected_module in name:
|
| 134 |
+
param.requires_grad = False
|
| 135 |
+
|
| 136 |
+
def save_pretrained(self, save_directory):
|
| 137 |
+
"""
|
| 138 |
+
Save the model's state_dict to the specified directory.
|
| 139 |
+
"""
|
| 140 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 141 |
+
torch.save(self.state_dict(), os.path.join(save_directory, "model.bin"))
|
| 142 |
+
|
| 143 |
+
def from_pretrained(self, load_directory):
|
| 144 |
+
"""
|
| 145 |
+
Load the model's state_dict from the specified directory.
|
| 146 |
+
"""
|
| 147 |
+
if not os.path.exists(load_directory):
|
| 148 |
+
raise ValueError(f"Directory {load_directory} does not exist.")
|
| 149 |
+
|
| 150 |
+
self.load_state_dict(torch.load(os.path.join(load_directory, "model.bin"), map_location=self.device))
|
| 151 |
+
|
| 152 |
+
def get_SPO_input(self, tokenized=None ,text=[""], labels=[""], training_module=False):
|
| 153 |
+
if training_module:
|
| 154 |
+
logits_score = self.scoring_model(tokenized.input_ids, attention_mask=tokenized.attention_mask).logits[:,:-1,:]
|
| 155 |
+
logits_ref = logits_score
|
| 156 |
+
if self.reference_model_name != self.scoring_model_name:
|
| 157 |
+
tokenized = self.reference_tokenizer(text, return_tensors="pt", padding=True, return_token_type_ids=False, add_special_tokens=True, return_attention_mask=True).to(self.device)
|
| 158 |
+
assert torch.all(tokenized.input_ids[:, 1:] == labels), "Tokenizer is mismatch."
|
| 159 |
+
logits_ref = self.reference_model(tokenized.input_ids).logits[:,:-1,:]
|
| 160 |
+
crit, SPO_input = self.criterion_fn(logits_ref, logits_score, labels)
|
| 161 |
+
else:
|
| 162 |
+
with torch.no_grad(): # get reference
|
| 163 |
+
if self.reference_model_name != self.scoring_model_name:
|
| 164 |
+
tokenized = self.reference_tokenizer(text, return_tensors="pt", padding=True, return_token_type_ids=False ,add_special_tokens=True, return_attention_mask=True).to(self.device)
|
| 165 |
+
assert torch.all(tokenized.input_ids[:, 1:] == labels), "Tokenizer is mismatch."
|
| 166 |
+
logits_score = self.reference_model(tokenized.input_ids, attention_mask=tokenized.attention_mask).logits[:,:-1,:] # shape: [bsz, sentence_len, dim]
|
| 167 |
+
logits_ref = logits_score
|
| 168 |
+
crit, SPO_input = self.criterion_fn(logits_ref, logits_score, labels)
|
| 169 |
+
return crit, SPO_input, logits_score
|
| 170 |
+
|
| 171 |
+
def forward_SPO(self, text):
|
| 172 |
+
original_text = text[0]
|
| 173 |
+
sampled_text = text[1]
|
| 174 |
+
|
| 175 |
+
tokenized = self.scoring_tokenizer(original_text, return_tensors="pt", padding=True, return_token_type_ids=False).to(self.device)
|
| 176 |
+
labels = tokenized.input_ids[:, 1:] # shape: [bsz, sentence_len]
|
| 177 |
+
ref_original_crit, ref_disprefered_logprob, ref_original_logits_score = self.get_SPO_input(tokenized,original_text,labels)
|
| 178 |
+
train_original_crit, train_disprefered_logprob, train_original_logits_score = self.get_SPO_input(tokenized,original_text,labels,training_module=True)
|
| 179 |
+
|
| 180 |
+
tokenized = self.scoring_tokenizer(sampled_text, return_tensors="pt", padding=True, return_token_type_ids=False).to(self.device)
|
| 181 |
+
labels = tokenized.input_ids[:, 1:]
|
| 182 |
+
ref_sampled_crit, ref_prefered_logprob, ref_sampled_logits_score = self.get_SPO_input(tokenized,sampled_text,labels)
|
| 183 |
+
train_sampled_crit, train_prefered_logprob, train_sampled_logits_score = self.get_SPO_input(tokenized,sampled_text,labels,training_module=True)
|
| 184 |
+
|
| 185 |
+
SPOloss, prefered_relative_logprob, disprefered_relative_logprob, reward_accuracies, reward_margins = calculate_SPO_loss(train_prefered_logprob,train_disprefered_logprob,ref_prefered_logprob,ref_disprefered_logprob,beta=self.beta)
|
| 186 |
+
output = dict(crit=[ref_original_crit, train_original_crit, ref_sampled_crit, train_sampled_crit], loss=SPOloss)
|
| 187 |
+
return output
|
| 188 |
+
|
| 189 |
+
|
scripts/ImBD/utils_spo.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn.functional as F
|
| 2 |
+
|
| 3 |
+
def calculate_SPO_loss(model_prefered_logprob, model_disprefered_logprob,
|
| 4 |
+
ref_prefered_logprob, ref_disprefered_logprob,
|
| 5 |
+
beta=0.5):
|
| 6 |
+
|
| 7 |
+
prefered_relative_logprob = model_prefered_logprob - ref_prefered_logprob
|
| 8 |
+
disprefered_relative_logprob = model_disprefered_logprob - ref_disprefered_logprob
|
| 9 |
+
|
| 10 |
+
reward_accuracies = (prefered_relative_logprob > disprefered_relative_logprob).float().mean(dim=-1)
|
| 11 |
+
reward_margins = (prefered_relative_logprob - disprefered_relative_logprob).mean(dim=-1)
|
| 12 |
+
loss = -F.logsigmoid(beta * (prefered_relative_logprob - disprefered_relative_logprob)).mean(dim=-1)
|
| 13 |
+
|
| 14 |
+
return loss, prefered_relative_logprob.mean(dim=-1), disprefered_relative_logprob.mean(dim=-1), reward_accuracies, reward_margins
|
scripts/TextFluoroscopy/utils_fluoroscopy.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModel
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import os
|
| 5 |
+
import json
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import pickle
|
| 8 |
+
import huggingface_hub
|
| 9 |
+
huggingface_hub.login("hf_xxxxx") # replace hf_xxxxx with your actual token
|
| 10 |
+
|
| 11 |
+
def last_token_pool(last_hidden_states,
|
| 12 |
+
attention_mask):
|
| 13 |
+
left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
|
| 14 |
+
if left_padding:
|
| 15 |
+
return last_hidden_states[:, -1]
|
| 16 |
+
else:
|
| 17 |
+
sequence_lengths = attention_mask.sum(dim=1) - 1
|
| 18 |
+
batch_size = last_hidden_states.shape[0]
|
| 19 |
+
return last_hidden_states[torch.arange(batch_size, device='cpu'), sequence_lengths]
|
| 20 |
+
|
| 21 |
+
def load_model(model_name, cache_dir):
|
| 22 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 23 |
+
model_name, # <-- Hub ID, *not* your cache path
|
| 24 |
+
cache_dir=cache_dir, # where to store/download files
|
| 25 |
+
trust_remote_code=True, # allow loading the repo’s custom code
|
| 26 |
+
use_auth_token=True,
|
| 27 |
+
)
|
| 28 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 29 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 30 |
+
model_name,
|
| 31 |
+
trust_remote_code=True,
|
| 32 |
+
device_map='auto',
|
| 33 |
+
use_auth_token=True,
|
| 34 |
+
cache_dir=cache_dir
|
| 35 |
+
)
|
| 36 |
+
return tokenizer, model
|
| 37 |
+
|
| 38 |
+
def get_kl(model, tokenizer, input_texts, max_length, device):
|
| 39 |
+
batch_dict = tokenizer(input_texts, max_length=max_length,
|
| 40 |
+
padding=True, truncation=True, return_tensors='pt').to(device)
|
| 41 |
+
with torch.no_grad():
|
| 42 |
+
outputs = model(**batch_dict, output_hidden_states=True)
|
| 43 |
+
last_logits = model.lm_head(outputs.hidden_states[-1]).squeeze()
|
| 44 |
+
first_logits = model.lm_head(outputs.hidden_states[0]).squeeze()
|
| 45 |
+
kls = []
|
| 46 |
+
for i in range(1, len(outputs.hidden_states) - 1):
|
| 47 |
+
with torch.no_grad():
|
| 48 |
+
middle_logits = model.lm_head(outputs.hidden_states[i]).squeeze()
|
| 49 |
+
kls.append(F.kl_div(F.log_softmax(middle_logits, dim=-1), F.softmax(first_logits, dim=-1), reduction='batchmean').item() +
|
| 50 |
+
F.kl_div(F.log_softmax(middle_logits, dim=-1), F.softmax(last_logits, dim=-1), reduction='batchmean').item())
|
| 51 |
+
return kls
|
| 52 |
+
|
| 53 |
+
def compute_kl_feat(model, tokenizer, file_name, save_dir, max_length, device):
|
| 54 |
+
test_datasets = {}
|
| 55 |
+
if not os.path.exists(save_dir):
|
| 56 |
+
os.makedirs(save_dir)
|
| 57 |
+
data_name = file_name.split('/')[-1]
|
| 58 |
+
if not os.path.exists(save_dir + data_name + '.pkl'):
|
| 59 |
+
print(file_name)
|
| 60 |
+
test_datasets[file_name] = {'data': [], 'label': []}
|
| 61 |
+
with open(file_name + '.raw_data.json', 'r') as f:
|
| 62 |
+
data = json.load(f)
|
| 63 |
+
kls = []
|
| 64 |
+
n_samples = len(data['original'])
|
| 65 |
+
# n_samples = 30
|
| 66 |
+
for idx in tqdm(range(n_samples)):
|
| 67 |
+
human_text = data['original'][idx]
|
| 68 |
+
kl = get_kl(model, tokenizer, [human_text], max_length, device)
|
| 69 |
+
kls.append(kl)
|
| 70 |
+
llm_text = data['sampled'][idx]
|
| 71 |
+
kl = get_kl(model, tokenizer, [llm_text], max_length, device)
|
| 72 |
+
kls.append(kl)
|
| 73 |
+
# if len(kls) >= 300:
|
| 74 |
+
# break
|
| 75 |
+
print(save_dir + data_name + '.pkl')
|
| 76 |
+
pickle.dump(kls, open(save_dir + data_name + '.pkl', 'wb'))
|
| 77 |
+
|
| 78 |
+
def load_model2(model_name, cache_dir):
|
| 79 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 80 |
+
model_name, # <-- Hub ID, *not* your cache path
|
| 81 |
+
cache_dir=cache_dir, # where to store/download files
|
| 82 |
+
trust_remote_code=True, # allow loading the repo’s custom code
|
| 83 |
+
use_auth_token=True,
|
| 84 |
+
)
|
| 85 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 86 |
+
model = AutoModel.from_pretrained(
|
| 87 |
+
model_name,
|
| 88 |
+
trust_remote_code=True,
|
| 89 |
+
device_map='auto',
|
| 90 |
+
use_auth_token=True,
|
| 91 |
+
cache_dir=cache_dir
|
| 92 |
+
)
|
| 93 |
+
return tokenizer, model
|
| 94 |
+
|
| 95 |
+
def get_all_embedding(model, tokenizer, input_texts, max_length, device):
|
| 96 |
+
batch_dict = tokenizer(input_texts, max_length=max_length, padding=True, truncation=True, return_tensors='pt').to(device)
|
| 97 |
+
with torch.no_grad():
|
| 98 |
+
outputs = model(**batch_dict, output_hidden_states=True)
|
| 99 |
+
all_embed = [last_token_pool(outputs.hidden_states[i].cpu(), batch_dict['attention_mask']) for i in range(len(outputs.hidden_states))]
|
| 100 |
+
all_embed = torch.concat(all_embed, 1).cpu()
|
| 101 |
+
return all_embed
|
| 102 |
+
|
| 103 |
+
def compute_embedding(model, tokenizer, file_name, save_dir, max_length, device):
|
| 104 |
+
test_datasets = {}
|
| 105 |
+
if not os.path.exists(save_dir):
|
| 106 |
+
os.makedirs(save_dir)
|
| 107 |
+
data_name = file_name.split('/')[-1]
|
| 108 |
+
if not os.path.exists(save_dir + data_name + '.pt'):
|
| 109 |
+
print(file_name)
|
| 110 |
+
test_datasets[file_name] = {'data':[], 'label':[]}
|
| 111 |
+
with open(file_name + '.raw_data.json', 'r') as f:
|
| 112 |
+
data = json.load(f)
|
| 113 |
+
embeddings = []
|
| 114 |
+
n_samples = len(data['original'])
|
| 115 |
+
# n_samples = 30
|
| 116 |
+
for idx in tqdm(range(n_samples)):
|
| 117 |
+
human_text = data['original'][idx]
|
| 118 |
+
embedding = get_all_embedding(model, tokenizer, [human_text], max_length, device)
|
| 119 |
+
embeddings.append(embedding)
|
| 120 |
+
llm_text = data['sampled'][idx]
|
| 121 |
+
embedding = get_all_embedding(model, tokenizer, [llm_text], max_length, device)
|
| 122 |
+
embeddings.append(embedding)
|
| 123 |
+
# if len(embeddings) >=300:
|
| 124 |
+
# break
|
| 125 |
+
embeddings = torch.cat(embeddings, dim=0)
|
| 126 |
+
print('embedding shape: ', embeddings.shape)
|
| 127 |
+
print(save_dir + data_name +'.pt')
|
| 128 |
+
torch.save(embeddings, save_dir + data_name + '.pt')
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == '__main__':
|
| 132 |
+
device = 'cuda'
|
| 133 |
+
max_length = 512
|
| 134 |
+
|
| 135 |
+
model_name = "Alibaba-NLP/gte-Qwen1.5-7B-instruct"
|
| 136 |
+
# cache_dir = '/root/autodl-tmp/cache'
|
| 137 |
+
cache_dir = '../../../cache'
|
| 138 |
+
|
| 139 |
+
which_embedding='gte-qwen_KL_with_first_and_last_layer'
|
| 140 |
+
save_dir = f'save/{which_embedding}/'
|
| 141 |
+
data_dir = 'dataset/processed_data/'
|
| 142 |
+
tokenizer, model = load_model(model_name, cache_dir)
|
| 143 |
+
compute_kl_feat(model, tokenizer, data_dir, save_dir, max_length, device)
|
| 144 |
+
|
| 145 |
+
which_embedding='gte-qwen_all_embedding'
|
| 146 |
+
save_dir = f'save/{which_embedding}/save_embedding/'
|
| 147 |
+
data_dir = 'dataset/processed_data/'
|
| 148 |
+
tokenizer, model = load_model2(model_name, cache_dir)
|
| 149 |
+
compute_embedding(model, tokenizer, data_dir, save_dir, max_length, device)
|
scripts/attack_data.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Guangsheng Bao.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the MIT license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import logging
|
| 8 |
+
import random
|
| 9 |
+
import re
|
| 10 |
+
import sys
|
| 11 |
+
import time
|
| 12 |
+
import nltk
|
| 13 |
+
import numpy as np
|
| 14 |
+
import torch
|
| 15 |
+
from tqdm import tqdm
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
| 19 |
+
|
| 20 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def bt_translation(src, browser):
|
| 24 |
+
zh2en_url = f'https://translate.google.com/?hl=zh&sl=en&tl=zh-CN&text={src}&op=translate'
|
| 25 |
+
browser.get(zh2en_url) # 访问相对应链接 browser.close#关闭浏览器
|
| 26 |
+
time.sleep(random.randint(1, 2))
|
| 27 |
+
browser.find_element_by_xpath(
|
| 28 |
+
'//*[@id="yDmH0d"]/c-wiz/div/div[2]/c-wiz/div[2]/c-wiz/div[1]/div[2]/div[3]/c-wiz[1]/span/span/div/div[2]/div[1]').send_keys(
|
| 29 |
+
src)
|
| 30 |
+
browser.refresh()
|
| 31 |
+
# time.sleep(50)
|
| 32 |
+
time.sleep(random.randint(2, 3))
|
| 33 |
+
text = browser.find_element_by_xpath(
|
| 34 |
+
'/html/body/c-wiz/div/div[2]/c-wiz/div[2]/c-wiz/div[1]/div[2]/div[3]/c-wiz[2]/div/div[8]/div/div[1]/span[1]').text
|
| 35 |
+
en_text = text.replace("翻譯搜尋結果\n", "").replace("\n", "")
|
| 36 |
+
en2zh_url = f'https://translate.google.com/?hl=zh&sl=zh-CN&tl=en&text={en_text}&op=translate'
|
| 37 |
+
browser.get(en2zh_url) # 访问相对应链接 browser.close#关闭浏览器
|
| 38 |
+
time.sleep(random.randint(1, 2))
|
| 39 |
+
browser.refresh()
|
| 40 |
+
time.sleep(random.randint(2, 3))
|
| 41 |
+
text = browser.find_element_by_xpath(
|
| 42 |
+
'/html/body/c-wiz/div/div[2]/c-wiz/div[2]/c-wiz/div[1]/div[2]/div[3]/c-wiz[2]/div/div[8]/div/div[1]/span[1]').text
|
| 43 |
+
tgt = text.replace("翻譯搜尋結果\n", "").replace("\n", "")
|
| 44 |
+
return tgt
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def read_data(json_path):
|
| 48 |
+
with open(json_path, 'r', encoding="utf-8") as f:
|
| 49 |
+
data = json.load(f)
|
| 50 |
+
return data
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def count_sentences_in_paragraph(paragraph):
|
| 54 |
+
sentences = nltk.sent_tokenize(paragraph)
|
| 55 |
+
return len(sentences)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def save_json_data(data, path):
|
| 59 |
+
with open(path, "w", encoding="utf-8") as outfile:
|
| 60 |
+
json.dump(data, outfile, ensure_ascii=False, indent=4)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def replace_line_breaks(s):
|
| 64 |
+
s = re.sub('\n', ' ', s)
|
| 65 |
+
return s
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def truncate_to_last_sentence(s):
|
| 69 |
+
# 从字符串尾部向前找句号的位置
|
| 70 |
+
last_period = s.rfind('.') or s.rfind('!') or s.rfind('?')
|
| 71 |
+
# 如果找到句号,就截断到这个位置(包括句号)
|
| 72 |
+
if last_period != -1:
|
| 73 |
+
s = s[:last_period + 1]
|
| 74 |
+
return s
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def check_paragraphs(texts):
|
| 78 |
+
if count_sentences_in_paragraph(texts) >= 4:
|
| 79 |
+
return True
|
| 80 |
+
else:
|
| 81 |
+
return False
|
| 82 |
+
|
| 83 |
+
def load_data(input_file):
|
| 84 |
+
data_file = f"{input_file}.raw_data.json"
|
| 85 |
+
with open(data_file, "r") as fin:
|
| 86 |
+
data = json.load(fin)
|
| 87 |
+
print(f"Raw data loaded from {data_file}")
|
| 88 |
+
return data
|
| 89 |
+
|
| 90 |
+
def save_data(output_file, data):
|
| 91 |
+
# write the data to a json file in the save folder
|
| 92 |
+
data_file = f"{output_file}.raw_data.json"
|
| 93 |
+
with open(data_file, "w") as fout:
|
| 94 |
+
json.dump(data, fout, indent=4)
|
| 95 |
+
print(f"Raw data written into {data_file}")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def run(args):
|
| 99 |
+
# set seed
|
| 100 |
+
random.seed(args.seed)
|
| 101 |
+
torch.manual_seed(args.seed)
|
| 102 |
+
np.random.seed(args.seed)
|
| 103 |
+
|
| 104 |
+
# load data
|
| 105 |
+
data = load_data(args.input_path)
|
| 106 |
+
|
| 107 |
+
# perturbation attacks prepare
|
| 108 |
+
if "perturbation" in args.method:
|
| 109 |
+
from textattack.augmentation import TextBuggerAugmenter
|
| 110 |
+
from textattack.augmentation import TextFoolerAugmenter
|
| 111 |
+
from textattack.augmentation import DeepWordBugAugmenter
|
| 112 |
+
word_augmenter = TextFoolerAugmenter()
|
| 113 |
+
character_augmenter = DeepWordBugAugmenter()
|
| 114 |
+
word_character_augmenter = TextBuggerAugmenter()
|
| 115 |
+
|
| 116 |
+
human_key = "original"
|
| 117 |
+
llm_key = 'sampled'
|
| 118 |
+
|
| 119 |
+
n_samples = len(data)
|
| 120 |
+
for i in tqdm(range(n_samples)):
|
| 121 |
+
human = data[human_key][i]
|
| 122 |
+
llm = data[llm_key][i]
|
| 123 |
+
|
| 124 |
+
# llms selection
|
| 125 |
+
if "perturbation" in args.method:
|
| 126 |
+
humans = count_sentences_in_paragraph(human)
|
| 127 |
+
llms = count_sentences_in_paragraph(llm)
|
| 128 |
+
for attack in ["perturbation_character", "perturbation_word", "perturbation_sent"]:
|
| 129 |
+
if attack == "perturbation_character":
|
| 130 |
+
augmenter = character_augmenter
|
| 131 |
+
elif attack == "perturbation_word":
|
| 132 |
+
augmenter = word_augmenter
|
| 133 |
+
elif attack == "perturbation_sent":
|
| 134 |
+
augmenter = word_character_augmenter
|
| 135 |
+
else:
|
| 136 |
+
raise ValueError(f"{attack} is not in perturbation_attacks")
|
| 137 |
+
|
| 138 |
+
try:
|
| 139 |
+
# final_data = []
|
| 140 |
+
# for d in range(humans):
|
| 141 |
+
# final_data.append(augmenter.augment(d)[0])
|
| 142 |
+
# human_result = ' '.join(final_data)
|
| 143 |
+
# data[human_key][i] = human_result
|
| 144 |
+
# logging.info(f"{attack} human finished")
|
| 145 |
+
|
| 146 |
+
final_data = []
|
| 147 |
+
for d in range(llms):
|
| 148 |
+
final_data.append(augmenter.augment(d)[0])
|
| 149 |
+
llm_result = ' '.join(final_data)
|
| 150 |
+
data[llm_key][i] = llm_result
|
| 151 |
+
logging.info(f"{attack} llm finished")
|
| 152 |
+
|
| 153 |
+
except Exception as e:
|
| 154 |
+
logging.info(f"error: {e}")
|
| 155 |
+
pass
|
| 156 |
+
|
| 157 |
+
save_data(args.output_file, data)
|
| 158 |
+
|
| 159 |
+
if __name__ == '__main__':
|
| 160 |
+
parser = argparse.ArgumentParser()
|
| 161 |
+
parser.add_argument('--input_path', required=False, default="./exp_main/data/xsum_opt-2.7b", type=str)
|
| 162 |
+
parser.add_argument('--output_path', required=False, default="./exp_main/data/xsum_opt-2.7b", type=str)
|
| 163 |
+
parser.add_argument('--method', default="perturbation_sent", type=str, choices=["perturbation_character", "perturbation_word", "perturbation_sent"], required=False)
|
| 164 |
+
parser.add_argument('--seed', default=2023, type=int, required=False)
|
| 165 |
+
args = parser.parse_args()
|
| 166 |
+
run(args)
|