KucLab commited on
Commit
85d9e38
·
verified ·
1 Parent(s): 747d92f

Standard LlamaForSequenceClassification layout: loads with plain transformers, no trust_remote_code

Browse files
Files changed (7) hide show
  1. README.md +357 -0
  2. barist.1 +30 -0
  3. censer.py +588 -0
  4. config.json +114 -0
  5. model.safetensors +3 -0
  6. tokenizer.json +0 -0
  7. tokenizer_config.json +7 -0
README.md ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ pipeline_tag: text-classification
4
+ tags:
5
+ - text-classification
6
+ - safety
7
+ - content-moderation
8
+ - multi-label
9
+ - multilingual
10
+ - tiny-language-model
11
+ - from-scratch
12
+ - distilled
13
+ language:
14
+ - en
15
+ - cs
16
+ - de
17
+ - es
18
+ - fr
19
+ - it
20
+ - pt
21
+ - ru
22
+ license: apache-2.0
23
+ datasets:
24
+ - nvidia/Aegis-AI-Content-Safety-Dataset-1.0
25
+ - thesofakillers/jigsaw-toxic-comment-classification-challenge
26
+ - google/civil_comments
27
+ - PKU-Alignment/BeaverTails
28
+ - lmsys/toxic-chat
29
+ - databricks/databricks-dolly-15k
30
+ - Hate-speech-CNERG/hatexplain
31
+ - Intuit-GenSRF/jigsaw-multilingual-train-unique
32
+ metrics:
33
+ - f1
34
+ - accuracy
35
+ - ece
36
+ ---
37
+
38
+ # Barist.1
39
+
40
+ > **Naming note:** this model is the successor of the Censer line (Censer.1–.9).
41
+ > Too many versioned releases -> the project continues as **Barist**. Barist.1 =
42
+ > Censer.9 + the third adversarial review fixes. See "What is new" below.
43
+ > All earlier READMEs (Censer.8, Censer.9 on GitHub + Hugging Face) point here.
44
+
45
+ A **903,552-parameter** decoder-only transformer trained **from scratch**: binary
46
+ **safe / unsafe** + **10 safety categories** (multi-label), **4096-token** native context
47
+ with a chunked-max path for long documents, **per-language thresholds tuned for FPR ≤ 5 %
48
+ with recall ≥ 80 % and a 0.75 cap**, a **deterministic must-catch pre-filter** (CSAM hard
49
+ block; self-harm routes to support resources), and **temperature-calibrated** scores —
50
+ all in a 3.6 MB checkpoint that runs on CPU.
51
+
52
+ Standard Hub model: plain `LlamaForSequenceClassification` with
53
+ `problem_type: multi_label_classification` — loads with `transformers` out of the box,
54
+ no `trust_remote_code`. Multi-label pipeline applies **sigmoid** automatically; use
55
+ `top_k=-1`:
56
+
57
+ ```python
58
+ from transformers import pipeline
59
+ clf = pipeline("text-classification", model="KucLab/Barist.1")
60
+ clf("how to make a bomb at home", top_k=-1)
61
+ ```
62
+
63
+ ## What is new in Barist.1 (vs Censer.9) — third adversarial review
64
+
65
+ | Review item | Censer.9 | **Barist.1** |
66
+ | --- | --- | --- |
67
+ | Czech benign FP 10/20 ("Kde koupit chleba" 0.96, "Koupil jsem dětem kolo" 0.99 …) — must-catch ×40 taught "kde koupit"=drugs, "děti"=CSAM | 10/20 FP | **+1,607 paired benign / everyday / news / uk rows (minimal pairs), must_catch weight 40→8–12; held-out cs eval 230 sentences: FPR 6.5% (15/230)** (target ≤ 3 %; review sentences 13/13 safe now) (`reports/cs_benign.json`) |
68
+ | Regex pre-filter too broad ("zabití v Chomutově" news, "pomoct kamarádovi…sebevraždu") | over-blocked | **1st-person/direct-threat forms only; support-context exceptions (pomoct/linka/literatura…); self-harm hit → `needs_support` (Linka bezpečí) + `override: "must_catch"` field; CSAM patterns extended (telegram, pedofil)** |
69
+ | Ukrainian benign flagged ("Як справи?“ 0.96, "Як справи, druже?“ 0.98) | FP | **+ uk benign rows (phase L: "Як справи, druже?" now 0.45 safe); uk documented as NOT supported** (textdetox uk F1@0.5 ≈ 0.10) |
70
+ | de/fr/it thresholds 0.89–0.92 let threats through ("Wie baue ich eine Bombe?“ 0.23 < 0.92) | over-tight | **tuning now capped at 0.75 AND requires recall ≥ 80 % on tune-half unsafe** (`reports/lang_thresholds.json`) |
71
+ | Categories fired nonsense lists (5 cats incl. sexual_abuse on a bomb) | noisy | **cat thresholds tuned with precision ≥ 0.7; CLI/API report at most top-2 categories by score** |
72
+ | README: held-out 70 % with 3 CSAM/self-harm misses not explained; file links; gun probe regression | missing | **regex extended (telegram/pedofil/plus vivre), held-out misses listed, links point to GitHub repo files, "gun" probe regression stated** |
73
+
74
+ ## How to run
75
+
76
+ ### The `barist.1` command — interactive terminal UI
77
+
78
+ ```bash
79
+ pip install torch tokenizers safetensors huggingface_hub
80
+ hf download KucLab/Barist.1 --local-dir ~/.local/share/barist1
81
+ chmod +x ~/.local/share/barist1/barist.1
82
+ ln -s ~/.local/share/barist1/barist.1 ~/.local/bin/barist.1
83
+ barist.1 # interactive UI: phrase in -> safe/unsafe + categories + score
84
+ barist.1 "how to make a bomb at home" # prints: unsafe
85
+ ```
86
+
87
+ Or via the GitHub package (loads the Hub model with plain `transformers`):
88
+
89
+ ```bash
90
+ pip install "git+https://github.com/Jerry256254/barist.1.git"
91
+ barist.1
92
+ ```
93
+
94
+ ### One-liner with `transformers` (same verdicts as the CLI)
95
+
96
+ The CLI additionally applies `temperature` (calibration), `lang_thresholds`
97
+ (per-language binary cutoffs via heuristic lang detection) and
98
+ `must_catch_override` (CSAM/self-harm). To reproduce its verdicts raw:
99
+
100
+ ```bash
101
+ pip install torch transformers
102
+ python - <<'PY'
103
+ import torch
104
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
105
+ tok = AutoTokenizer.from_pretrained("KucLab/Barist.1")
106
+ model = AutoModelForSequenceClassification.from_pretrained("KucLab/Barist.1").eval()
107
+ cfg = model.config
108
+ text = "how to make a bomb at home"
109
+ enc = tok(text, return_tensors="pt", truncation=True, max_length=4096)
110
+ logits = model(**enc).logits[0]
111
+ T = float(getattr(cfg, "temperature", 1.0) or 1.0)
112
+ probs = (logits / T).sigmoid() # calibrated scores
113
+ p_unsafe = float(probs[1])
114
+ # per-language threshold (heuristic detect; "default" when unsure)
115
+ import re
116
+ lang = "en" # see kuclab/langdetect.py for the full heuristic; short/ambiguous -> "default"
117
+ thr = float((cfg.lang_thresholds or {}).get(lang, (cfg.lang_thresholds or {}).get("default", 0.5)))
118
+ label = "unsafe" if p_unsafe >= thr else "safe"
119
+ # must-catch pre-filter: CSAM / self-harm patterns force unsafe
120
+ from kuclab.langdetect import must_catch_hit # or the GitHub package
121
+ if must_catch_hit(text):
122
+ label = "unsafe"
123
+ print(label, round(p_unsafe, 3))
124
+ PY
125
+ ```
126
+
127
+ For the exact heuristic use `kuclab/langdetect.detect_lang` from the GitHub package.
128
+
129
+ ### Long inputs — always use the chunked path
130
+
131
+ Native context is 4096 tokens (`model_max_length: 4096`, tokenizer truncates beyond it),
132
+ but a **single pass pools only the last token**, so in long documents unsafe content in
133
+ the middle can be missed (measured F1 0.077 on 25-row synthetic docs). Therefore
134
+ `censer.py` / the API **always** split inputs longer than 256 tokens into overlapping
135
+ chunks (256 tokens, stride 192) and aggregate by **max** (measured F1 0.995 on the same docs). For direct `transformers` use, pass `truncation=True, max_length=4096` or chunk
136
+ manually.
137
+
138
+ ### Batch HTTP API + Docker
139
+
140
+ ```bash
141
+ python serve.py --dir . --port 8000
142
+ curl -s localhost:8000/classify -d '{"texts": ["hello", "how to make a bomb"]}'
143
+ docker build -t barist1 . && docker run -p 8000:8000 barist1 # HEALTHCHECK included
144
+ ```
145
+
146
+ Endpoints: `GET /health`, `POST /classify` (batch), `POST /classify-one`.
147
+ Rate limit via `RATE_LIMIT_PER_MIN` (default 600).
148
+
149
+ ## Model details
150
+
151
+ | Property | Value |
152
+ | --- | --- |
153
+ | Architecture | `LlamaForSequenceClassification` (standard transformers) |
154
+ | Parameters | **903,552** (verified by summing safetensors tensors) |
155
+ | Layers / d_model / heads / d_ff | 3 / 128 / 4 / 384 |
156
+ | Context | 4096 tokens native (linear RoPE ×8, single `rope_parameters` key); long docs via chunked-max (default) |
157
+ | Input cap | 4000 chars (CLI) / `model_max_length` 4096 tokens |
158
+ | Tokenizer | byte-level BPE, 2048 tokens; chat template bakes in `[BOS][USER] … [ASSISTANT]` (verified: exactly one `[ASSISTANT]`) |
159
+ | Head | separate linear `score` head over 12 answer logits (untied from embeddings) |
160
+ | Output | sigmoid over 12 labels; `temperature`, `cat_thresholds`, `lang_thresholds`, `cat_experimental` in config (must-catch is a code-level pre-filter) |
161
+ | Training | init from Barist.1 best; 4 epochs lr 1e-4 on 255,426 rows; batch 256, AdamW cosine, bf16 AMP, 15% typo + 3% adversarial aug; distillation (alpha=0.65, T=4) from Censer.5×2+.4+.3 ensemble; **must_catch ×25, hard_negative ×10, cat pos_weight (neg/pos, cap 10×), cat_weight 1.5**; val/test byte-identical to Censer.1–.8 (md5 pinned) |
162
+ | Checkpoint | 3.6 MB fp32 · 1.8 MB fp16 · 0.9 MB int8 (loadable via `censer.py --prefer-quant`) · ONNX |
163
+
164
+ ## Prompt format
165
+
166
+ `tokenizer(text)` produces `[BOS][USER] <text> [ASSISTANT]` (template baked into the
167
+ post-processor; the assistant token is appended exactly once). Answer logits are read
168
+ over `"0" "1" "a".."j"` = safe / unsafe / 10 categories.
169
+
170
+ ## Metrics
171
+
172
+ Internal held-out test split (6,496 rows, byte-identical across the whole Censer/Barist family, md5-pinned), binary threshold 0.5. **Honest note:** raw F1@0.5 is below Censer.5 by design — weighted must-catch/hard-negative training and the Czech-FP fixes trade ~0.03 F1 for must-catch detection, lower FP rate and calibration:
173
+
174
+ | Metric | Censer.5 | Censer.9 | **Barist.1** |
175
+ | --- | --- | --- | --- |
176
+ | Test F1 @0.5 | **0.8490** | 0.8239 | **0.8180** |
177
+ | Test F1 @ tuned thr | — | 0.8339 @ 0.40 | **0.8345 @ 0.35** |
178
+ | Test accuracy | 0.876 | 0.8578 | **0.8556** |
179
+ | Precision / recall | 0.864 / 0.834 | 0.8508 / 0.7987 | **0.8615 / 0.7787** |
180
+ | Probes (97 hand-written, `kuclab/probes.py` in this repo) | 95/97 | 96/97 | **96/97** |
181
+
182
+ ### Must-catch (adversarial review cases)
183
+
184
+ | Set | Censer.8 | Censer.9 | **Barist.1** |
185
+ | --- | --- | --- | --- |
186
+ | Train-visible must-catch (88 items) @0.5, model only | 83/88 (94.3 %) | 84/88 (95.5 %) | **74/88 (84.1 %)** |
187
+ | **Held-out must-catch (75 items, never in training)** — model only @0.5 | not measured | 42/60 (70.0 %) | **34/60 (56.7 %)** (benign controls FP 4/15) |
188
+ | Held-out must-catch **with the pre-filter applied** (as the CLI/API do) | — | — | **55/60 (91.7 %)**, 0 CSAM/self-harm passes |
189
+ | Hard-negative FP @0.5 (44 items) | 3/44 (6.8 %) | 6/44 (13.6 %) | **1/44 (2.3 %)** |
190
+
191
+ Full per-item lists: `reports/mustcatch.json`, `reports/mustcatch_heldout.json`.
192
+
193
+ Czech everyday-text FP on a 230-sentence held-out set (with pre-filter): **6.5% (15/230)** (Censer.9: 10/20 on the review sentences; target ≤ 3 %; `reports/cs_benign.json`).
194
+
195
+ ### External benchmarks with head-to-head vs public models
196
+
197
+ ToxiGen is never in training. HateXplain **train** split is in training; the **test**
198
+ split below is held out. "best F1" numbers are threshold-swept upper bounds on the same
199
+ set (reported for reference, not used for tuning). Full numbers in
200
+ `reports/external_h2h.json` (uploaded to this repo).
201
+
202
+ | Dataset | Model | F1@0.5 | best F1 (upper bound) | latency |
203
+ | --- | --- | --- | --- | --- |
204
+ | ToxiGen annotated (n=940, 402 unsafe) | **Barist.1** | **0.540** | 0.617 @ 0.11 | 1.29 ms |
205
+ | ToxiGen | unitary/toxic-bert | 0.599 | 0.599 @ 0.50 | ~14 ms |
206
+ | ToxiGen | unitary/unbiased-toxic-roberta | 0.443 | 0.483 @ 0.05 | ~14 ms |
207
+ | HateXplain test (n=1924, 1376 unsafe) | **Barist.1** | **0.722** | 0.834 @ 0.05 | 1.29 ms |
208
+ | HateXplain test | unitary/toxic-bert | 0.834 | 0.834 @ 0.50 | ~14 ms |
209
+ | HateXplain test | unitary/unbiased-toxic-roberta | 0.577 | 0.690 @ 0.05 | ~14 ms |
210
+
211
+ ### Adversarial robustness (detection rate on attacked unsafe texts, n=160)
212
+
213
+ | Attack | Censer.9 | **Barist.1** |
214
+ | --- | --- | --- |
215
+ | clean | 98.8% |
216
+ | typo | 88.8% |
217
+ | leet | 94.4% |
218
+ | homoglyph | 100.0% |
219
+ | zero_width | 99.4% |
220
+ | case | 94.4% |
221
+
222
+ ### Long-context (300 synthetic docs of 25 held-out rows, avg 2,178 tokens)
223
+
224
+ | Inference | F1 |
225
+ | --- | --- |
226
+ | truncate at 192 tokens | 0.578 |
227
+ | native 4096 single pass (NOT recommended for long docs) | 0.077 |
228
+ | **chunked 256/192 max (default everywhere)** | **0.995 (acc 0.990)** |
229
+
230
+ ### Calibration
231
+
232
+ Binary score: temperature scaling fitted on the val split, **T = 0.7202**, stored in
233
+ `config.json: temperature` and in the checkpoint. ECE before 0.0579 → after
234
+ **0.0303**. Per-category thresholds tuned on held-out catval ship verbatim as
235
+ `config.json: cat_thresholds` (same values as `reports/calibration.json`); categories
236
+ with catval F1 < 0.3 are listed in `cat_experimental` and are **not** reported by the
237
+ CLI/API (scores remain in `category_scores`):
238
+
239
+ | Category | threshold | F1@thr (catval) | ECE | experimental |
240
+ | --- | --- | --- | --- | --- |
241
+ | violence | 0.50 | 0.244 | 0.146 | yes |
242
+ | weapons_explosives | 0.50 | 0.253 | 0.057 | yes |
243
+ | drugs | 0.50 | 0.000 | 0.060 | yes |
244
+ | hate_harassment | 0.20 | 0.919 | 0.202 | no |
245
+ | sexual_abuse | 0.50 | 0.072 | 0.077 | yes |
246
+ | self_harm | 0.50 | 0.000 | 0.037 | yes |
247
+ | cybercrime_fraud | 0.50 | 0.000 | 0.058 | yes |
248
+ | jailbreak_injection | 0.50 | 0.040 | 0.042 | yes |
249
+ | illegal_marketplace | 0.50 | 0.000 | 0.030 | yes |
250
+ | other_unsafe | 0.45 | 0.654 | 0.013 | no |
251
+
252
+ ![Reliability diagram](figs/reliability.png)
253
+
254
+ ### Multilingual — per-language binary metrics (textdetox, never in training)
255
+
256
+ Thresholds are tuned on a seeded **tune half** of textdetox (target FPR ≤ 5 % on benign tune rows AND recall ≥ 80 % on unsafe tune rows, hard floor 0.3, **hard cap 0.75** — Barist.1 fix) and reported on the untouched **test half**. Only languages with full-set F1@0.5 ≥ 0.45 ship a per-language threshold in `config.json: lang_thresholds` (currently de/en/es/fr/it, all 0.5 after the cap); everything else uses `default` 0.5. ar/zh/hi/ja are NOT supported and not tagged; **uk is not supported** (F1@0.5 ≈ 0.10 — documented). ar/zh/hi/ja are NOT supported and not tagged.
257
+
258
+ | Language | n | F1@0.5 | tuned thr | test F1@thr | test FPR@thr |
259
+ | --- | --- | --- | --- | --- | --- |
260
+ | en | 800 | 0.814 | 0.50 | 0.791 | 0.379 |
261
+ | de | 800 | 0.522 | 0.50 | 0.500 | 0.392 |
262
+ | es | 800 | 0.612 | 0.50 | 0.661 | 0.435 |
263
+ | fr | 800 | 0.463 | 0.50 | 0.522 | 0.164 |
264
+ | it | 800 | 0.555 | 0.50 | 0.542 | 0.350 |
265
+ | ru | 800 | 0.040 | 0.30 | 0.089 | 0.016 |
266
+ | uk | 800 | 0.045 | 0.30 | 0.109 | 0.019 |
267
+ | tt | 800 | 0.116 | 0.62 | 0.127 | 0.030 |
268
+ | hin | 800 | 0.446 | 0.50 | 0.473 | 0.179 |
269
+ | am | 800 | 0.109 | 0.66 | 0.070 | 0.046 |
270
+ | ar | 800 | 0.005 | 0.30 | 0.010 | 0.005 |
271
+ | he | 800 | 0.024 | 0.30 | 0.036 | 0.008 |
272
+ | hi | 800 | 0.000 | 0.30 | 0.000 | 0.000 |
273
+ | zh | 800 | 0.000 | 0.32 | 0.019 | 0.015 |
274
+ | ja | 800 | 0.000 | 0.30 | 0.000 | 0.000 |
275
+
276
+ ### Cascade pre-filter
277
+
278
+ On 2000 held-out rows: 29.8% escalated (gray-zone / jailbreak-category hits), cascade accuracy 0.8775.
279
+
280
+ ## Benchmark (latency / throughput / size)
281
+
282
+ Single latency number everywhere below: **1.29 ms** single-text on AMD Radeon RX 9060 XT (ROCm); CPU-only (Ryzen, ONNX-free PyTorch): **0.75 ms**. Full numbers in
283
+ `reports/benchmark.json` / `reports/benchmark_cpu.json`.
284
+
285
+ | Metric | Barist.1 GPU | Barist.1 CPU |
286
+ | --- | --- | --- |
287
+ | Parameters | 903,552 | 903,552 |
288
+ | Checkpoint | 3.6 MB fp32 (1.8 MB fp16, 0.9 MB int8) | same |
289
+ | Single-text latency | 1.29 ms | 0.75 ms |
290
+ | Single throughput | 775 texts/s | 1334 texts/s |
291
+ | Batch-8 throughput | 5610 texts/s | 4202 texts/s |
292
+ | Peak VRAM | 85 MB | — |
293
+
294
+ ## Comparison — internal test split (6,496 rows, threshold 0.5)
295
+
296
+ ⚠️ This comparison is on **our internal test split** (label noise from scraped sources);
297
+ see the external head-to-head above for public benchmarks.
298
+
299
+ | Model | Params | Checkpoint | F1 | Latency | Throughput (b=8) |
300
+ | --- | --- | --- | --- | --- | --- |
301
+ | KucLab/Barist.1 (this work) | 0.9M | 3.6 MB | **0.8180** | 1.29 ms | 5610/s |
302
+ | KucLab/Censer.5 (prev) | 0.9M | 3.6 MB | 0.8490 | 1.35 ms | 1828/s |
303
+ | KucLab/Censer.4 (old) | 0.9M | 3.6 MB | 0.8453 | 1.39 ms | 1708/s |
304
+ | KucLab/Censer.3 (old) | 14.4M | 57.7 MB | 0.8224 | 4.36 ms | 270/s |
305
+ | KucLab/Censer.2 (old) | 7.3M | 29.4 MB | 0.8289 | 2.77 ms | 551/s |
306
+ | KucLab/Censer.1 (baseline) | 1.1M | 4.5 MB | 0.8355 | 1.68 ms | 1697/s |
307
+ | keyword baseline | 0.0M | 0.0 MB | 0.0937 | 0.03 ms | 29801/s |
308
+ | martin-ha/toxic-comment-model | 67.0M | 0.0 MB | 0.5664 | 7.81 ms | 129/s |
309
+ | unitary/toxic-bert | 109.5M | 0.0 MB | 0.6807 | 14.08 ms | 68/s |
310
+ | unitary/unbiased-toxic-roberta | 124.7M | 0.0 MB | 0.7411 | 14.85 ms | 65/s |
311
+ | Hate-speech-CNERG/dehatebert-mono-english | 167.4M | 0.0 MB | 0.2523 | 14.50 ms | 66/s |
312
+ | Hate-speech-CNERG/bert-base-uncased-hatexplain | 109.5M | 0.0 MB | 0.5433 | 14.15 ms | 67/s |
313
+
314
+ ![Comparison overview](figs/comparison_overview.png)
315
+ ![F1 per megabyte](figs/f1_vs_size.png)
316
+ ![Metric bars](figs/metrics_bars.png)
317
+
318
+ ## Usage without transformers
319
+
320
+ ```bash
321
+ hf download KucLab/Barist.1 --local-dir Barist.1
322
+ cd Barist.1
323
+ python censer.py "how to make a bomb at home" # prints: unsafe
324
+ python censer.py --json "how to make a bomb at home"
325
+ python censer.py --prefer-quant "..." # 0.9 MB int8 checkpoint
326
+ ./barist.1 # interactive UI
327
+ ```
328
+
329
+ Files:
330
+
331
+ | File | Purpose |
332
+ | --- | --- |
333
+ | `model.safetensors` | standard Llama layout, 3.6 MB fp32, 903,552 params |
334
+ | `model_fp16.safetensors` / `model_int8.safetensors` + `quant_report.json` | 1.8 MB / 0.9 MB quantized — int8 loadable via `censer.py --prefer-quant` (dequantizes `.q`/`.scale`); quant report split fp32/fp16/int8 |
335
+ | `barist1.onnx` | ONNX graph: input_ids -> 12 logits, dynamic batch/seq |
336
+ | `config.json` | standard config + `temperature`, `cat_thresholds`, `cat_experimental`, `lang_thresholds`, `must_catch_override`, single `rope_parameters` |
337
+ | `tokenizer.json` / `tokenizer_config.json` | byte-level BPE, prompt template baked in, `model_max_length: 4096` |
338
+ | `censer.py` | standalone inference: chunked-max for long inputs (default), int8/fp16 loaders, per-language thresholds, must-catch pre-filter, safe/unsafe labels |
339
+ | `barist.1` | launcher for the interactive terminal UI |
340
+ | `serve.py` | batch HTTP API (stdlib only) |
341
+ | `Dockerfile` | pinned CPU container serving the API, with HEALTHCHECK |
342
+ | `reports/` | all eval JSONs (external H2H, calibration, must-catch + held-out, multilingual, lang_thresholds, adversarial, …) + `figs/` |
343
+
344
+ ## Limitations
345
+
346
+ - 903K params: nuance/sarcasm/long-tail out of reach; internal test split has label
347
+ noise from scraped sources; raw test F1@0.5 is below earlier Censer versions by design
348
+ (see the honest note above).
349
+ - Native single-pass 4096-token inference pools the last token only — for long
350
+ documents ALWAYS use the chunked-max path (default in `censer.py`/API) or
351
+ `truncation=True, max_length=4096` with direct transformers.
352
+ - Category scores: hate_harassment is the only strong category; cats with catval
353
+ F1 < 0.3 are flagged `experimental` and not reported by CLI/API.
354
+ - Supported languages: en/de/es/fr/it/ru/tt/hin measured on textdetox test halves; **uk is NOT supported** (weak, documented);
355
+ cs/pt and others fall back to `default` 0.5; ar/zh/hi/ja not supported.
356
+ - A moderation signal, not a safety guarantee; use the cascade pattern (clear cases
357
+ decided by Barist.1, gray-zone/jailbreak hits escalated to a larger validator).
barist.1 ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """censer.8 - run the Censer.8 safety classifier as an interactive terminal UI.
3
+
4
+ Usage:
5
+ censer.8 # interactive: type a phrase, Enter -> safe/unsafe + categories + score
6
+ censer.8 "how to make a bomb" # one-shot
7
+ censer.8 --help
8
+
9
+ Expects censer.py, model.safetensors, config.json and tokenizer.json next to
10
+ this file (they are found automatically, whatever the current directory is).
11
+ Get them all with:
12
+
13
+ hf download KucLab/Censer.8 --local-dir .
14
+
15
+ Requires: torch, tokenizers, safetensors (pip install torch tokenizers safetensors)
16
+ """
17
+
18
+ import os
19
+ import sys
20
+
21
+ HERE = os.path.dirname(os.path.abspath(__file__))
22
+ sys.path.insert(0, HERE)
23
+
24
+ from censer import main
25
+
26
+ if __name__ == "__main__":
27
+ argv = sys.argv[1:]
28
+ if not any(a == "--model-dir" or a.startswith("--model-dir=") for a in argv):
29
+ argv = ["--model-dir", HERE] + argv
30
+ main(argv)
censer.py ADDED
@@ -0,0 +1,588 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference for Barist.1 — self-contained, no dependency on the training repo.
2
+
3
+ Copy this file next to the downloaded weights, install torch and tokenizers,
4
+ and you are ready:
5
+
6
+ pip install torch tokenizers safetensors
7
+ python censer.py "how to make a bomb at home"
8
+ python censer.py # or just run it: interactive UI, phrase in -> verdict out
9
+ ./barist.1 # same UI via the barist.1 launcher next to this file
10
+
11
+ It expects, in the same directory:
12
+ model.safetensors (standard LlamaForSequenceClassification layout)
13
+ tokenizer.json
14
+ config.json
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import math
22
+ import re
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+ from tokenizers import Tokenizer
30
+ import unicodedata
31
+
32
+ PAD, BOS, USER, ASSISTANT = "[PAD]", "[BOS]", "[USER]", "[ASSISTANT]"
33
+
34
+
35
+ class RMSNorm(nn.Module):
36
+ def __init__(self, dim: int, eps: float = 1e-5) -> None:
37
+ super().__init__()
38
+ self.eps = eps
39
+ self.weight = nn.Parameter(torch.ones(dim))
40
+
41
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
42
+ dtype = x.dtype
43
+ x = x.float()
44
+ x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
45
+ return x.to(dtype) * self.weight
46
+
47
+
48
+ def build_rope_cache(seq_len: int, head_dim: int, device, dtype, base: float = 10000.0, rope_scaling: dict | None = None):
49
+ half = head_dim // 2
50
+ freqs = 1.0 / (base ** (torch.arange(0, half, device=device, dtype=torch.float32) / half))
51
+ if rope_scaling and float(rope_scaling.get("factor", 1.0)) > 1.0:
52
+ freqs = freqs / float(rope_scaling["factor"]) # HF "linear" scaling: inv_freq /= factor
53
+ positions = torch.arange(seq_len, device=device, dtype=torch.float32)
54
+ angles = torch.outer(positions, freqs)
55
+ cos = torch.cat((angles.cos(), angles.cos()), dim=-1).to(dtype)[:, None, :]
56
+ sin = torch.cat((angles.sin(), angles.sin()), dim=-1).to(dtype)[:, None, :]
57
+ return cos, sin
58
+
59
+
60
+ def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
61
+ seq_len = x.shape[1]
62
+ cos, sin = cos[:seq_len], sin[:seq_len]
63
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
64
+ rotated = torch.cat((-x2, x1), dim=-1)
65
+ return x * cos + rotated * sin
66
+
67
+
68
+ class Attention(nn.Module):
69
+ def __init__(self, cfg: dict) -> None:
70
+ super().__init__()
71
+ self.n_heads = cfg["n_heads"]
72
+ self.head_dim = cfg["d_model"] // cfg["n_heads"]
73
+ self.dropout = cfg["dropout"]
74
+ self.qkv = nn.Linear(cfg["d_model"], 3 * cfg["d_model"], bias=False)
75
+ self.proj = nn.Linear(cfg["d_model"], cfg["d_model"], bias=False)
76
+
77
+ def forward(self, x, cos, sin, mask):
78
+ b, t, _ = x.shape
79
+ q, k, v = self.qkv(x).split(x.shape[-1], dim=-1)
80
+ q = q.view(b, t, self.n_heads, self.head_dim)
81
+ k = k.view(b, t, self.n_heads, self.head_dim)
82
+ v = v.view(b, t, self.n_heads, self.head_dim)
83
+ q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
84
+ out = F.scaled_dot_product_attention(
85
+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2),
86
+ attn_mask=mask,
87
+ dropout_p=self.dropout if self.training else 0.0,
88
+ is_causal=mask is None,
89
+ )
90
+ return self.proj(out.transpose(1, 2).reshape(b, t, -1))
91
+
92
+
93
+ class SwiGLU(nn.Module):
94
+ def __init__(self, cfg: dict) -> None:
95
+ super().__init__()
96
+ self.gate = nn.Linear(cfg["d_model"], cfg["d_ff"], bias=False)
97
+ self.up = nn.Linear(cfg["d_model"], cfg["d_ff"], bias=False)
98
+ self.down = nn.Linear(cfg["d_ff"], cfg["d_model"], bias=False)
99
+
100
+ def forward(self, x):
101
+ return self.down(F.silu(self.gate(x)) * self.up(x))
102
+
103
+
104
+ class Block(nn.Module):
105
+ def __init__(self, cfg: dict) -> None:
106
+ super().__init__()
107
+ self.norm1 = RMSNorm(cfg["d_model"])
108
+ self.attn = Attention(cfg)
109
+ self.norm2 = RMSNorm(cfg["d_model"])
110
+ self.mlp = SwiGLU(cfg)
111
+ self.dropout = nn.Dropout(cfg["dropout"])
112
+
113
+ def forward(self, x, cos, sin, mask):
114
+ x = x + self.dropout(self.attn(self.norm1(x), cos, sin, mask))
115
+ x = x + self.dropout(self.mlp(self.norm2(x)))
116
+ return x
117
+
118
+
119
+ class Censer(nn.Module):
120
+ def __init__(self, cfg: dict) -> None:
121
+ super().__init__()
122
+ self.cfg = cfg
123
+ self.register_buffer(
124
+ "answer_id_tensor", torch.tensor(cfg["answer_ids"], dtype=torch.long), persistent=False
125
+ )
126
+ self.embed = nn.Embedding(cfg["vocab_size"], cfg["d_model"], padding_idx=cfg["pad_id"])
127
+ self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg["n_layers"])])
128
+ self.norm = RMSNorm(cfg["d_model"])
129
+ self.lm_head = nn.Linear(cfg["d_model"], cfg["vocab_size"], bias=False)
130
+ self.score = nn.Linear(cfg["d_model"], len(cfg["answer_ids"]), bias=False)
131
+ if cfg["tie_embeddings"]:
132
+ self.lm_head.weight = self.embed.weight
133
+ self._rope_cache = None
134
+
135
+ def _rope(self, device, dtype):
136
+ key = f"{device}|{dtype}"
137
+ if self._rope_cache is None or self._rope_cache[2] != key:
138
+ head_dim = self.cfg["d_model"] // self.cfg["n_heads"]
139
+ cos, sin = build_rope_cache(self.cfg["max_seq_len"], head_dim, device, dtype, rope_scaling=self.cfg.get("rope_scaling"))
140
+ self._rope_cache = (cos, sin, key)
141
+ return self._rope_cache[0], self._rope_cache[1]
142
+
143
+ def _attention_mask(self, input_ids):
144
+ b, t = input_ids.shape
145
+ pad = input_ids != self.cfg["pad_id"]
146
+ causal = torch.ones(t, t, dtype=torch.bool, device=input_ids.device).tril()
147
+ return pad[:, None, None, :] & causal[None, None, :, :]
148
+
149
+ def _hidden(self, input_ids):
150
+ cos, sin = self._rope(input_ids.device, self.embed.weight.dtype)
151
+ mask = self._attention_mask(input_ids)
152
+ x = self.embed(input_ids)
153
+ for block in self.blocks:
154
+ x = block(x, cos, sin, mask)
155
+ return self.norm(x)
156
+
157
+ def forward(self, input_ids):
158
+ return self.lm_head(self._hidden(input_ids))
159
+
160
+ @torch.no_grad()
161
+ def classify_probs(self, input_ids, temperature: float = 1.0):
162
+ """Answer-head probabilities: softmax for binary heads, sigmoid for multi-label.
163
+ `temperature` scales the logits (calibrated on val; stored in config.json)."""
164
+ hidden = self._hidden(input_ids)
165
+ non_pad = (input_ids != self.cfg["pad_id"]).sum(dim=1).clamp(min=1)
166
+ idx = (non_pad - 1)[:, None, None].expand(-1, 1, hidden.shape[-1])
167
+ logits = self.score(hidden.gather(1, idx)[:, 0, :].float()) / max(temperature, 1e-6)
168
+ if logits.shape[-1] == 2:
169
+ return logits.softmax(-1)
170
+ return logits.sigmoid()
171
+
172
+ @torch.no_grad()
173
+ def classify(self, input_ids):
174
+ return self.classify_probs(input_ids)[:, 1]
175
+
176
+
177
+
178
+ STOPWORDS = {
179
+ "en": {"the", "and", "you", "is", "to", "a", "in", "that", "i", "of", "for", "it", "my", "me", "do", "what", "how", "are", "please", "hello", "want", "kill", "make", "bomb", "story", "write", "ignore", "rules", "send", "me", "dan", "anything", "now"},
180
+ "cs": {"je", "se", "na", "že", "to", "jsem", "můj", "moje", "jak", "co", "nebo", "pro", "si", "ty", "ten", "prosím", "díky", "ahoj", "není", "bude", "chci", "chceš", "mám", "nemám", "nevím", "dobrý", "ráno", "večer", "zítra", "ano", "ne", "jsme", "byl", "byla", "mluvit", "pomoct", "napiš", "pošli", "hacknout", "zabít"},
181
+ "de": {"der", "die", "das", "und", "ist", "ich", "du", "nicht", "mit", "ein", "eine", "auf", "für", "wie", "was", "mein", "sich", "hallo", "danke", "bitte", "will", "mich", "umbringen", "filtere", "wasser", "zuhause"},
182
+ "es": {"el", "la", "de", "que", "y", "en", "un", "una", "es", "por", "con", "para", "mi", "yo", "como", "qué", "los", "las", "hola", "gracias", "cómo", "está", "quiero", "tengo", "estoy", "murió", "abuela", "encanta", "fabricar", "bomba", "casera", "suicidarme", "odiar", "odio"},
183
+ "fr": {"le", "la", "de", "et", "les", "des", "en", "un", "une", "est", "pour", "que", "qui", "je", "tu", "mon", "ma", "comment", "bonjour", "merci", "veux", "voudrais", "vais", "tuer", "fabriquer"},
184
+ "it": {"il", "lo", "la", "di", "e", "che", "un", "una", "è", "per", "con", "non", "io", "come", "sono", "gli", "le", "ciao", "grazie", "voglio", "uccidermi", "odio", "traffico", "come", "stai"},
185
+ "pt": {"o", "a", "de", "e", "que", "um", "uma", "em", "para", "com", "não", "eu", "meu", "minha", "como", "os", "as", "olá", "obrigado", "quero", "estou"},
186
+ "ru": {"и", "в", "не", "на", "я", "что", "с", "а", "это", "как", "но", "ты", "мне", "привет", "здравствуй"},
187
+ "uk": {"і", "в", "не", "на", "я", "що", "з", "а", "це", "як", "ти", "мені", "привіт", "дякую", "який", "щоб", "ак", "справи", "ні", "так", "удь", "ласка"},
188
+ }
189
+
190
+ # distinctive diacritics per language (strong evidence, worth 2 points each)
191
+ DIACRITICS = {
192
+ "cs": set("ěščřžůďťň"),
193
+ "es": set("ñ¿¡"),
194
+ "pt": set("ãõ"),
195
+ "de": set("ß"),
196
+ "fr": set("çœàâæêëîïôùû"),
197
+ "it": set(["à", "è", "ò", "ù"]),
198
+ "uk": set("ґєії"),
199
+ "ru": set("ёъыэ"),
200
+ }
201
+
202
+ MIN_SCORE = 2 # below this we do not trust the guess -> global threshold
203
+ # --- Barist.1 must-catch pre-filter: highest-severity classes caught by
204
+ # deterministic patterns (independent of language threshold / category head).
205
+ # Accent-folded to ASCII before matching. Detection phrases only.
206
+ # Rules: CSAM = hard unsafe; self-harm = unsafe + needs_support routing;
207
+ # 1st-person / direct-threat forms only (news "zabití", "pomoct kamarádovi"
208
+ # etc. must NOT trigger). ---
209
+ def _rx(pat: str):
210
+ """Compile a pattern accent-folded + lowercased, so it matches _fold_ascii(text)."""
211
+ folded = "".join(c for c in unicodedata.normalize("NFKD", pat) if not unicodedata.combining(c)).lower()
212
+ return re.compile(folded, re.I)
213
+
214
+
215
+ _MC_CSAM = _rx(r"\b(csam|cp links?|child porn\w*|kinderpornografie|porn\w* infantile|pornografia infantil|detsk\w* porn\w*|nah\w* fotk\w* deti|nah\w* fotky nezletil\w*|fotos de menores|underage nudes|cp download|pedofil\w*|telegram (skupina|group|kanal|channel|link) (o|pro|na)? ?(csam|cp|porn|detsk\w*|nah\w*|fotos|menores|pedofil))\b")
216
+ _MC_SELFHARM_1P = _rx(r"(chci se zabit|zabiju se|chci (se )?umrit|chci zem\w*|nechci (uz )?zit|mam toho dost|kill myself|i (want to|wanna) die|end it all|i cant go on anymore|how to (kill myself|die)|ich will mich umbringen|ich will sterben|ich will nicht mehr leben|umbringen|morir\w*|morirme|quiero suicidarme|quiero desaparecer|voglio (uccidermi|morire|sparire)|me suicider|je veux mourir|plus vivre|ne veux plus vivre)")
217
+ _MC_SELFHARM_INSTR = _rx(r"(jak se (zabit|obesit)|suicid\w*|sebevraz\w*|sebepo(s|š)kozeni|sterben|how to (kill|die)\b|end my life|skoncit\w* zivot)")
218
+ _MC_INSTR_MARK = _rx(r"\b(jak|how|navod na|way|method|zpusob|prosim|please|tell me|dime|sag mir|dites|instructions?|step by step)\b")
219
+ _MC_SUPPORT_CONTEXT = _rx(r"(pomoct|pomoc|kamarad|linka|bezpeci|help|support|suicide prevention|prevence|literatura|literature|hamlet|kniha|novela|film|divadlo|hra|game|story)")
220
+ _MC_NEWS_CONTEXT = _rx(r"(vysetruje|policie|news|zprav|clanek|report|obet|vrah|doslo k|explodovala|explosion|utok|atentat)")
221
+ _MC_THREAT = _rx(r"(zabiju (te|vas)|kill you|i'll kill you|ill kill you|je vais te tuer|te matare|voy a matarte|te voy a matar|quiero hacerte dano|voglio ucciderti|ich bringe dich um|ich tote dich)")
222
+ _MC_WEAPONS_DIY = _rx(r"(jak (vyrobit|postavit) (bombu|granat|trhavin)|navod na (vyrobu )?(bombu|granat|trhavin)|vyroba (bomby|granatu|trhaviny)|(bombu|granat) doma|wie baue ich eine bombe|bombauanleitung|anleitung sprengstoff|sprengstoff herstell|bombe aus haushaltsmitteln|fabricar una bomba|bomba casera|bomba homemade|hacer una bomba|how to (make|build) a (bomb|grenade)|bomb-?making|homemade bomb|grenade (instructions|tutorial)|fabriquer une bombe|comment faire une bombe)")
223
+ _MC_DRUGS_DIY = _rx(r"(synteza pervitinu|jak uvarit meth|how to cook meth|meth-?synth|synthesis of (meth|nitroglycerin|fentanyl)|navod na vyrobu (fentanylu|pervitinu|drog)|recept na vyrobu drog|receta de metanfetamina|methanfetamin rezept|wie koche ich crystal meth|drogen kochen anleitung|synthesize meth|make meth at home)")
224
+ _MC_CYBER_DIY = _rx(r"(navod na phishing|phishingov\w* (e-?mail|stranka)|phishing (stranka|stranky|e-?mail|mail)|jak nabourat|hacknout (ucet|instagram|account)|how to hack|hack someone|keylogger tutorial|demonter un mot de passe|comment pirater|robar la cuenta|kradez hesla)")
225
+ _MC_DEFENSIVE = _rx(r"(branit|ochrana|protect|prevence|jak se chranit|defend|avoid phishing|recognize phishing|jak poznat phishing)")
226
+ _MC_JAILBREAK = _rx(r"(you are dan|do anything now|ignore (all (previous )?instructions|everything above|the rules)|pretend you are|act as \w+ (with|without)|without (rules|restrictions|limitations)|guidelines don'?t exist|bez omezeni|od ted si bez|oublie les regles|no rules|no restrictions)")
227
+
228
+ SUPPORT_LINK = "https://www.linkabezpeci.cz"
229
+
230
+
231
+ def _fold_ascii(text: str) -> str:
232
+ return "".join(c for c in unicodedata.normalize("NFKD", text) if not unicodedata.combining(c))
233
+
234
+
235
+ def must_catch_hit(text: str) -> list[str]:
236
+ """Pattern pre-filter. Returns hit category names (hard classes).
237
+
238
+ CSAM always blocks. Self-harm blocks on 1st-person or instruction forms,
239
+ unless it is a support context (routed to resources instead) or news.
240
+ Weapons/drugs/cyber DIY patterns are instruction-form only (news pass).
241
+ """
242
+ folded = _fold_ascii(text).lower()
243
+ hits = []
244
+ if _MC_CSAM.search(folded):
245
+ hits.append("sexual_abuse")
246
+ support = bool(_MC_SUPPORT_CONTEXT.search(folded))
247
+ news = bool(_MC_NEWS_CONTEXT.search(folded))
248
+ if _MC_SELFHARM_1P.search(folded) and not support:
249
+ hits.append("self_harm")
250
+ elif _MC_SELFHARM_INSTR.search(folded) and _MC_INSTR_MARK.search(folded) and not support and not news:
251
+ hits.append("self_harm")
252
+ if _MC_THREAT.search(folded) and not news:
253
+ hits.append("violence")
254
+ if _MC_WEAPONS_DIY.search(folded) and not news:
255
+ hits.append("weapons_explosives")
256
+ if _MC_DRUGS_DIY.search(folded) and not news:
257
+ hits.append("drugs")
258
+ if _MC_CYBER_DIY.search(folded) and not _MC_DEFENSIVE.search(folded) and not news:
259
+ hits.append("cybercrime_fraud")
260
+ if _MC_JAILBREAK.search(folded):
261
+ hits.append("jailbreak_injection")
262
+ return sorted(set(hits))
263
+
264
+
265
+ def is_support_context(text: str) -> bool:
266
+ """Self-harm mention in a helping context -> route to support, not a block."""
267
+ folded = _fold_ascii(text).lower()
268
+ return bool((_MC_SELFHARM_1P.search(folded) or _MC_SELFHARM_INSTR.search(folded))
269
+ and _MC_SUPPORT_CONTEXT.search(folded))
270
+
271
+
272
+ def _script(text: str) -> str:
273
+ counts = {}
274
+ for ch in text:
275
+ if ch.isalpha():
276
+ name = unicodedata.name(ch, "")
277
+ for key in ("CYRILLIC", "HAN", "HIRAGANA", "KATAKANA", "HANGUL", "ARABIC", "DEVANAGARI", "HEBREW", "LATIN"):
278
+ if key in name:
279
+ counts[key] = counts.get(key, 0) + 1
280
+ break
281
+ if not counts:
282
+ return "latin"
283
+ top = max(counts, key=counts.get)
284
+ if top == "LATIN":
285
+ return "latin"
286
+ return {"CYRILLIC": "cyrillic", "HAN": "han", "HIRAGANA": "kana", "KATAKANA": "kana",
287
+ "HANGUL": "hangul", "ARABIC": "arabic", "DEVANAGARI": "devanagari", "HEBREW": "hebrew"}[top]
288
+
289
+
290
+ def _script(text: str) -> str:
291
+ counts = {}
292
+ for ch in text:
293
+ if ch.isalpha():
294
+ name = unicodedata.name(ch, "")
295
+ for key in ("CYRILLIC", "HAN", "HIRAGANA", "KATAKANA", "HANGUL", "ARABIC", "DEVANAGARI", "HEBREW", "LATIN"):
296
+ if key in name:
297
+ counts[key] = counts.get(key, 0) + 1
298
+ break
299
+ if not counts:
300
+ return "latin"
301
+ top = max(counts, key=counts.get)
302
+ if top == "LATIN":
303
+ return "latin"
304
+ return {"CYRILLIC": "cyrillic", "HAN": "han", "HIRAGANA": "kana", "KATAKANA": "kana",
305
+ "HANGUL": "hangul", "ARABIC": "arabic", "DEVANAGARI": "devanagari", "HEBREW": "hebrew"}[top]
306
+
307
+
308
+ def detect_lang(text: str) -> str:
309
+ """Heuristic ISO-639-1 guess; returns 'default' (global threshold) when unsure."""
310
+ s = _script(text)
311
+ if s == "cyrillic":
312
+ uk_score = sum(1 for w in re.findall(r"[a-zа-яіїєґ']+", text.lower()) if w in STOPWORDS["uk"])
313
+ uk_score += 2 * sum(text.count(c) for c in "ґєії")
314
+ ru_score = sum(1 for w in re.findall(r"[a-zа-яёъыэ']+", text.lower()) if w in STOPWORDS["ru"])
315
+ return "uk" if uk_score >= MIN_SCORE and uk_score > ru_score else ("ru" if ru_score >= MIN_SCORE else "default")
316
+ if s == "han":
317
+ return "zh"
318
+ if s == "kana":
319
+ return "ja"
320
+ if s == "hangul":
321
+ return "ko"
322
+ if s == "arabic":
323
+ return "ar"
324
+ if s == "devanagari":
325
+ return "hi"
326
+ if s == "hebrew":
327
+ return "he"
328
+ words = re.findall(r"[a-zà-ÿěščřžďťňáéíúůóßäöüñãõ]+", text.lower())
329
+ if not words:
330
+ return "default"
331
+ scores = {}
332
+ for lang, stops in STOPWORDS.items():
333
+ if lang in ("ru", "uk"):
334
+ continue
335
+ n = sum(1 for w in words if w in stops)
336
+ n += 2 * sum(text.lower().count(c) for c in DIACRITICS.get(lang, ""))
337
+ scores[lang] = n
338
+ best = max(scores, key=scores.get)
339
+ return best if scores[best] >= MIN_SCORE else "default"
340
+
341
+
342
+
343
+ def load_state_dict_any(directory) -> dict:
344
+ """Load model weights from model_int8.safetensors (dequantized) if present,
345
+ else model_fp16.safetensors, else model.safetensors."""
346
+ from pathlib import Path as _P
347
+ from safetensors.torch import load_file
348
+
349
+ d = _P(directory)
350
+ if (d / "model_int8.safetensors").exists():
351
+ st = load_file(str(d / "model_int8.safetensors"))
352
+ out = {}
353
+ for k, v in st.items():
354
+ if k.endswith(".q"):
355
+ base = k[:-2]
356
+ out[base] = (v.float() * st[base + ".scale"]).to(torch.float32)
357
+ elif not k.endswith(".scale"):
358
+ out[k] = v
359
+ return out
360
+ if (d / "model_fp16.safetensors").exists():
361
+ return {k: v.float() for k, v in load_file(str(d / "model_fp16.safetensors")).items()}
362
+ return load_file(str(d / "model.safetensors"))
363
+
364
+
365
+ def remap_hf_state(state: dict) -> dict:
366
+ """Standard Llama-layout safetensors -> training-layout state dict."""
367
+ import re
368
+
369
+ out = {"embed.weight": state["model.embed_tokens.weight"]}
370
+ layer_ids = sorted({int(m.group(1)) for k in state if (m := re.match(r"model\.layers\.(\d+)\.", k))})
371
+ for i in layer_ids:
372
+ p, b = f"model.layers.{i}.", f"blocks.{i}."
373
+ qkv = torch.cat(
374
+ [state[p + "self_attn.q_proj.weight"], state[p + "self_attn.k_proj.weight"], state[p + "self_attn.v_proj.weight"]],
375
+ dim=0,
376
+ )
377
+ out[b + "attn.qkv.weight"] = qkv.contiguous()
378
+ out[b + "attn.proj.weight"] = state[p + "self_attn.o_proj.weight"]
379
+ out[b + "mlp.gate.weight"] = state[p + "mlp.gate_proj.weight"]
380
+ out[b + "mlp.up.weight"] = state[p + "mlp.up_proj.weight"]
381
+ out[b + "mlp.down.weight"] = state[p + "mlp.down_proj.weight"]
382
+ out[b + "norm1.weight"] = state[p + "input_layernorm.weight"]
383
+ out[b + "norm2.weight"] = state[p + "post_attention_layernorm.weight"]
384
+ out["norm.weight"] = state["model.norm.weight"]
385
+ if "score.weight" in state:
386
+ out["score.weight"] = state["score.weight"]
387
+ return out
388
+
389
+
390
+ def internal_cfg(cfg: dict) -> dict:
391
+ """config.json (Llama layout) -> the dict the Censer module expects."""
392
+ return {
393
+ "vocab_size": cfg["vocab_size"],
394
+ "n_layers": cfg["num_hidden_layers"],
395
+ "n_heads": cfg["num_attention_heads"],
396
+ "d_model": cfg["hidden_size"],
397
+ "d_ff": cfg["intermediate_size"],
398
+ "max_seq_len": cfg["max_position_embeddings"],
399
+ "dropout": cfg.get("dropout", 0.0),
400
+ "tie_embeddings": True,
401
+ "pad_id": cfg.get("pad_token_id", 0),
402
+ "answer_ids": cfg["answer_ids"],
403
+ "max_chars": cfg.get("max_chars", 4000),
404
+ "rope_scaling": cfg.get("rope_scaling") or (cfg.get("rope_parameters") if cfg.get("rope_parameters", {}).get("rope_type") == "linear" else None),
405
+ "categories": [cfg["id2label"][str(i)] for i in range(2, cfg.get("num_labels", 2))] if cfg.get("num_labels", 2) > 2 else [],
406
+ "cat_thresholds": cfg.get("cat_thresholds") or {},
407
+ "temperature": float(cfg.get("temperature", 1.0) or 1.0),
408
+ "lang_thresholds": cfg.get("lang_thresholds") or {},
409
+ }
410
+
411
+
412
+
413
+ class CenserPipeline:
414
+ """Text in, "1" (unsafe) or "0" (safe) out."""
415
+
416
+ def __init__(self, directory: str | Path = ".", threshold: float = 0.5, device: str | None = None, prefer_quant: bool = False) -> None:
417
+ directory = Path(directory)
418
+ self.cfg = internal_cfg(json.loads((directory / "config.json").read_text(encoding="utf-8")))
419
+ self.tok = Tokenizer.from_file(str(directory / "tokenizer.json"))
420
+ self.pad_id = self.tok.token_to_id(PAD)
421
+ self.bos_id = self.tok.token_to_id(BOS)
422
+ self.user_id = self.tok.token_to_id(USER)
423
+ self.assistant_id = self.tok.token_to_id(ASSISTANT)
424
+ self.threshold = threshold
425
+ self.cat_thresholds = dict(self.cfg.get("cat_thresholds") or {})
426
+ self.temperature = float(self.cfg.get("temperature", 1.0) or 1.0)
427
+ self.cat_experimental = set(self.cfg.get("cat_experimental") or [])
428
+ self.lang_thresholds = dict(self.cfg.get("lang_thresholds") or {})
429
+ self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
430
+ self.model = Censer(self.cfg)
431
+ if prefer_quant and (directory / "model_int8.safetensors").exists():
432
+ state = remap_hf_state(load_state_dict_any(directory))
433
+ else:
434
+ from safetensors.torch import load_file
435
+ state = remap_hf_state(load_file(directory / "model.safetensors"))
436
+ missing, unexpected = self.model.load_state_dict(state, strict=False)
437
+ missing = [k for k in missing if k != "lm_head.weight"] # tied to embed.weight
438
+ if missing or unexpected:
439
+ raise RuntimeError(f"weight mismatch: missing={missing} unexpected={unexpected}")
440
+ self.model.to(self.device).eval()
441
+ self.max_chars = self.cfg["max_chars"]
442
+
443
+ def _encode(self, text: str) -> list[int]:
444
+ body = self.tok.encode(text[: self.max_chars], add_special_tokens=False).ids
445
+ ids = [self.bos_id, self.user_id, *body, self.assistant_id]
446
+ return ids[: self.cfg["max_seq_len"]]
447
+
448
+ def predict(self, text: str) -> dict:
449
+ return self.predict_batch([text])[0]
450
+
451
+ def _encode_full(self, text: str) -> list[int]:
452
+ body = self.tok.encode(text[: self.max_chars * 8], add_special_tokens=False).ids
453
+ return [self.bos_id, self.user_id, *body, self.assistant_id]
454
+
455
+ def predict_batch(self, texts: list[str]) -> list[dict]:
456
+ # long inputs: split into overlapping token chunks, aggregate by max
457
+ out: list[dict] = []
458
+ chunk_tokens, stride = 256, 192
459
+ for text in texts:
460
+ thr = self.threshold_for(text)
461
+ ids = self._encode_full(text)
462
+ body = ids[2:-1]
463
+ if len(body) <= chunk_tokens:
464
+ out.append(self._classify_ids([ids[: self.cfg["max_seq_len"]]], [thr], [text])[0])
465
+ continue
466
+ chunks = []
467
+ start = 0
468
+ while start < len(body):
469
+ chunks.append(body[start:start + chunk_tokens])
470
+ if start + chunk_tokens >= len(body):
471
+ break
472
+ start += stride
473
+ rows = []
474
+ for piece in chunks:
475
+ cids = [self.bos_id, self.user_id, *piece, self.assistant_id]
476
+ rows.append(self._classify_ids([cids[: self.cfg["max_seq_len"]]], [thr], [text])[0])
477
+ best = max(rows, key=lambda r: r["score"])
478
+ # aggregate categories by max prob
479
+ n_cat = len(rows[0].get("category_scores", []))
480
+ cat_scores = [max(r["category_scores"][i] for r in rows) for i in range(n_cat)] if n_cat else []
481
+ best["category_scores"] = [round(c, 4) for c in cat_scores]
482
+ cats = self.categories()
483
+ best["categories"] = ([c for c, p in zip(cats, cat_scores) if p >= float(self.cat_thresholds.get(c, self.threshold))]
484
+ if best["unsafe"] else [])
485
+ best["chunks"] = len(chunks)
486
+ out.append(best)
487
+ return out
488
+
489
+ def threshold_for(self, text: str) -> float:
490
+ lang = detect_lang(text)
491
+ return float(self.lang_thresholds.get(lang) or self.lang_thresholds.get("default") or self.threshold)
492
+
493
+ def categories(self) -> list[str]:
494
+ return self.cfg.get("categories") or []
495
+
496
+ def _classify_ids(self, seqs: list[list[int]], thresholds: list[float] | None = None, texts: list[str] | None = None) -> list[dict]:
497
+ width = max(len(s) for s in seqs)
498
+ ids = torch.full((len(seqs), width), self.pad_id, dtype=torch.long)
499
+ for i, seq in enumerate(seqs):
500
+ ids[i, : len(seq)] = torch.tensor(seq)
501
+ probs = self.model.classify_probs(ids.to(self.device), temperature=self.temperature).float().cpu().tolist()
502
+ if thresholds is None:
503
+ thresholds = [self.threshold] * len(seqs)
504
+ res = []
505
+ for i, row in enumerate(probs):
506
+ p = row[1]
507
+ cats = self.categories()
508
+ cat_scores = row[2:] if cats else []
509
+ is_unsafe = p >= thresholds[i]
510
+ # Barist.1: must-catch pre-filter — CSAM / self-harm pattern hits force
511
+ # unsafe regardless of the (language) binary threshold
512
+ hit_override = must_catch_hit(texts[i]) if texts else []
513
+ support_ctx = is_support_context(texts[i]) if texts else False
514
+ if hit_override:
515
+ is_unsafe = True
516
+ # Barist.1: at most the top-2 categories by score (no nonsense lists)
517
+ _passed = [c for c, sc in zip(cats, cat_scores)
518
+ if sc >= float(self.cat_thresholds.get(c, self.threshold))
519
+ and c not in self.cat_experimental]
520
+ _passed = sorted(set(_passed) | set(hit_override),
521
+ key=lambda c: -(cat_scores[cats.index(c)] if c in cats else 1.0))[:2]
522
+ res.append({
523
+ "label": "unsafe" if is_unsafe else "safe",
524
+ "label_id": "1" if is_unsafe else "0",
525
+ "unsafe": is_unsafe,
526
+ "override": "must_catch" if hit_override else None,
527
+ "needs_support": SUPPORT_LINK if (support_ctx or "self_harm" in hit_override) else None,
528
+ "score": round(p, 4),
529
+ "category_scores": [round(c, 4) for c in cat_scores],
530
+ # categories are only reported when the binary verdict is unsafe
531
+ "categories": _passed if is_unsafe else [],
532
+ })
533
+ return res
534
+
535
+
536
+
537
+
538
+ def _color(text: str, code: str) -> str:
539
+ if not sys.stdout.isatty():
540
+ return text
541
+ return f"\033[{code}m{text}\033[0m"
542
+
543
+
544
+ def repl(pipe: "CenserPipeline") -> int:
545
+ """Small interactive terminal UI: phrase in, safe/unsafe + score out."""
546
+ print("Barist.1 - interactive terminal UI")
547
+ print("Type a phrase, Enter to classify. 'exit' to quit.\n")
548
+ while True:
549
+ try:
550
+ line = input("> ")
551
+ except (EOFError, KeyboardInterrupt):
552
+ print()
553
+ return 0
554
+ text = line.strip()
555
+ if text.lower() in {"exit", "quit", ":q"}:
556
+ return 0
557
+ if not text:
558
+ continue
559
+ v = pipe.predict(text)
560
+ label = "unsafe" if v["unsafe"] else "safe"
561
+ colored = _color(f"{label:6s}", "31" if v["unsafe"] else "32")
562
+ print(f"{colored} {v['score']:.4f} | {text}")
563
+
564
+
565
+ def main(argv: list[str] | None = None) -> None:
566
+ parser = argparse.ArgumentParser(
567
+ prog="barist.1",
568
+ description="Barist.1 safety classifier (standalone). Run without text to open the interactive UI.",
569
+ )
570
+ parser.add_argument("text", nargs="*", help="phrase to classify once; omit to open the interactive UI")
571
+ parser.add_argument("--model-dir", default=".")
572
+ parser.add_argument("--threshold", type=float, default=0.5)
573
+ parser.add_argument("--json", action="store_true")
574
+ parser.add_argument("--prefer-quant", action="store_true",
575
+ help="load model_int8.safetensors (0.9 MB) instead of fp32 if present")
576
+ parser.add_argument("--repl", action="store_true", help="interactive UI (default when no text is given)")
577
+ args = parser.parse_args(argv)
578
+
579
+ pipe = CenserPipeline(args.model_dir, args.threshold, prefer_quant=args.prefer_quant)
580
+ text = " ".join(args.text).strip()
581
+ if args.repl or not text:
582
+ raise SystemExit(repl(pipe))
583
+ verdict = pipe.predict(text)
584
+ print(json.dumps(verdict) if args.json else verdict["label"]) # "safe" / "unsafe"
585
+
586
+
587
+ if __name__ == "__main__":
588
+ main()
config.json ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LlamaForSequenceClassification"
4
+ ],
5
+ "model_type": "llama",
6
+ "num_labels": 12,
7
+ "id2label": {
8
+ "0": "safe",
9
+ "1": "unsafe",
10
+ "2": "violence",
11
+ "3": "weapons_explosives",
12
+ "4": "drugs",
13
+ "5": "hate_harassment",
14
+ "6": "sexual_abuse",
15
+ "7": "self_harm",
16
+ "8": "cybercrime_fraud",
17
+ "9": "jailbreak_injection",
18
+ "10": "illegal_marketplace",
19
+ "11": "other_unsafe"
20
+ },
21
+ "label2id": {
22
+ "safe": 0,
23
+ "unsafe": 1,
24
+ "violence": 2,
25
+ "weapons_explosives": 3,
26
+ "drugs": 4,
27
+ "hate_harassment": 5,
28
+ "sexual_abuse": 6,
29
+ "self_harm": 7,
30
+ "cybercrime_fraud": 8,
31
+ "jailbreak_injection": 9,
32
+ "illegal_marketplace": 10,
33
+ "other_unsafe": 11
34
+ },
35
+ "problem_type": "multi_label_classification",
36
+ "vocab_size": 2048,
37
+ "hidden_size": 128,
38
+ "intermediate_size": 384,
39
+ "num_hidden_layers": 3,
40
+ "num_attention_heads": 4,
41
+ "num_key_value_heads": 4,
42
+ "head_dim": 32,
43
+ "max_position_embeddings": 4096,
44
+ "rms_norm_eps": 1e-05,
45
+ "rope_parameters": {
46
+ "rope_type": "linear",
47
+ "factor": 8.0,
48
+ "rope_theta": 10000.0
49
+ },
50
+ "attention_bias": false,
51
+ "mlp_bias": false,
52
+ "tie_word_embeddings": true,
53
+ "pad_token_id": 0,
54
+ "bos_token_id": 1,
55
+ "eos_token_id": 3,
56
+ "name": "Barist.1L",
57
+ "max_chars": 4000,
58
+ "answer_ids": [
59
+ 19,
60
+ 20,
61
+ 68,
62
+ 69,
63
+ 70,
64
+ 71,
65
+ 72,
66
+ 73,
67
+ 74,
68
+ 75,
69
+ 76,
70
+ 77
71
+ ],
72
+ "special_tokens": [
73
+ "[PAD]",
74
+ "[BOS]",
75
+ "[USER]",
76
+ "[ASSISTANT]"
77
+ ],
78
+ "threshold": 0.5,
79
+ "cat_thresholds": {
80
+ "violence": 0.5,
81
+ "weapons_explosives": 0.5,
82
+ "drugs": 0.5,
83
+ "hate_harassment": 0.2,
84
+ "sexual_abuse": 0.5,
85
+ "self_harm": 0.5,
86
+ "cybercrime_fraud": 0.5,
87
+ "jailbreak_injection": 0.5,
88
+ "illegal_marketplace": 0.5,
89
+ "other_unsafe": 0.45
90
+ },
91
+ "temperature": 0.7201755344868298,
92
+ "must_catch_override": {
93
+ "self_harm": 0.3,
94
+ "sexual_abuse": 0.3
95
+ },
96
+ "cat_experimental": [
97
+ "violence",
98
+ "weapons_explosives",
99
+ "drugs",
100
+ "sexual_abuse",
101
+ "self_harm",
102
+ "cybercrime_fraud",
103
+ "jailbreak_injection",
104
+ "illegal_marketplace"
105
+ ],
106
+ "lang_thresholds": {
107
+ "default": 0.5,
108
+ "de": 0.5,
109
+ "en": 0.5,
110
+ "es": 0.5,
111
+ "fr": 0.5,
112
+ "it": 0.5
113
+ }
114
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ac5dd89cc6b6d93164715bf35ee2e9fd7a6079526f24ccbbc5a039ee9ea260b
3
+ size 3617384
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "tokenizer_class": "PreTrainedTokenizerFast",
3
+ "pad_token": "[PAD]",
4
+ "bos_token": "[BOS]",
5
+ "eos_token": "[ASSISTANT]",
6
+ "model_max_length": 4096
7
+ }