Run this model with HF Jobs
Run hfvladkon/bert_token_classification_detector on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/hfvladkon/bert_token_classification_detector. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/hfvladkon/bert_token_classification_detector on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use hfvladkon/bert_token_classification_detector with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use hfvladkon/bert_token_classification_detector with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="hfvladkon/bert_token_classification_detector")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("hfvladkon/bert_token_classification_detector") model = AutoModelForTokenClassification.from_pretrained("hfvladkon/bert_token_classification_detector", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload main defect tagger (weights, tokenizer, inference code, card)
Browse filesFiles changed (21)
- .gitattributes+1
- README.mdAdded+79
- code/__pycache__/byt5_adapter.cpython-312.pycAdded
- code/__pycache__/metrics.cpython-312.pycAdded
- code/__pycache__/modeling.cpython-312.pycAdded
- code/__pycache__/native_adapter.cpython-312.pycAdded
- code/__pycache__/tag.cpython-312.pycAdded
- code/byt5_adapter.pyAdded+128
- code/metrics.pyAdded+348
- code/modeling.pyAdded+161
- code/native_adapter.pyAdded+148
- code/tag.pyAdded+116
- config.jsonAdded+148
- model.safetensorsAdded+3
- qwen_tokenizer/chat_template.jinjaAdded+170
- qwen_tokenizer/merges.txtAdded
- qwen_tokenizer/tokenizer.jsonAdded+3
- qwen_tokenizer/tokenizer_config.jsonAdded+305
- qwen_tokenizer/vocab.jsonAdded
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+17
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textqwen_tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879---language:- rulibrary_name: transformerspipeline_tag: token-classificationbase_model: deepvk/RuModernBERT-basetags:- token-classification- qwen- error-detection---
# RuModernBERT, родная токенизация, двухэтапное обучение (лучшая модель)
Ветка `main` репозитория `imvladikon/bert_token_classification_detector`.
Разметчик дефектов в ответах Qwen3.8-Flash-Next. Модель помечает токены ответа Qwen, в которых есть языковой дефект:иероглифы среди русского текста, латинские и прочие иностранные вставки, смешение алфавитов внутри слова, транслитерация,ошибки согласования, управления, морфологии, орфографии и пропуски слов.
- **Вход:** текст ответа (декодированные без потерь токены Qwen) в родной токенизации энкодера; вероятности усредняются обратно на токены Qwen.- **Выход:** метка на каждый токен ответа Qwen: `O`, `BAD-script`, `TAIL-script`, `BAD-grammar`, `TAIL-grammar`. BAD — первый дефектный токен ошибки, TAIL — продолжение той же ошибки.- **Пороги** (`config.defect_threshold`, [алфавит, грамматика]): [0.5, 0.9]. Токен считается дефектным, если сумма вероятностей BAD+TAIL его группы не меньше порога. Пороги подобраны по предсказаниям вне фолдов кросс-валидации (или на val, где CV нет); порог, подобранный на val основного сплита, лежит в `config.defect_threshold_val`.
## Как запустить
```pythonimport sysfrom huggingface_hub import snapshot_downloadpath = snapshot_download("imvladikon/bert_token_classification_detector", revision="main")sys.path.insert(0, f"{path}/code")from tag import Tagger
t = Tagger(path)# ответ текстом (токенизируется токенизатором Qwen3.8), либо готовые id Qwen: t.tag_ids(ids, answer_start, query)ids, answer_start, probs, spans = t.tag_text("текст ответа", query="вопрос пользователя")print(spans) # [{'tokens': [s, e], 'text': ..., 'p': ..., 'group': 'script'|'grammar'}]```
Из командной строки: `python code/tag.py --model <path> --query "..." --answer-file answer.txt`.Нужны `torch` и `transformers` 5.x.
## Обучение
Данные: 1000 ответов Qwen3.8-Flash-Next, размеченных вручную агентом по токенам (1129 ошибок; схема O / BAD / TAIL,зависимые, спорные и неуверенные места в обучении не участвуют), плюс исправленные версии тех же ответов как негативы и синтетические ошибки(pymorphy3: согласование, управление, морфология, орфография, пропуски; вставки иероглифов, латиницы и смешение алфавитов) на русской Википедии.Сплит 800 / 100 / 100 ответов.
Этап 1: только синтетика на русской Википедии и Викитеке (8000 документов, около 15 тыс. ошибок). Этап 2: реальная разметка плюс грамматическая синтетика с весом 0.3, 6 эпох, lr 3e-5, лучшая эпоха по F1 на пересечении спанов.
## Качество
Метрика — совпадение спанов по пересечению: эталонная ошибка найдена, если её пересекает предсказанный спан той же группы;предсказанный спан верен, если пересекает эталонный. Спаны извлекаются из BIO так же, как в seqeval.
| оценка | P | R | F1 | F1 алфавит | F1 грамматика ||---|---|---|---|---|---|| кросс-валидация, 1000 ответов (кросс-валидация той же схемы (CV-G)) | 0.79 | 0.58 | 0.669 | 0.930 | 0.278 || test основного сплита, 100 ответов | 0.70 | 0.56 | 0.622 | 0.962 | 0.251 |
Test содержит 114 ошибок, разброс между сидами там до ±0.07 F1, поэтому модели сравниваются по кросс-валидации.Если грамматику нужно ловить чаще: порог грамматики 0.5 даёт по CV F1 грамм��тики 0.311 (P 0.38, R 0.26) при общем F1 0.658.
### Все ветки
| ветка | CV F1 | CV P | CV R | CV F1 алфавит | CV F1 грамматика | test F1 ||---|---|---|---|---|---|---|| [`main`](https://huggingface.co/imvladikon/bert_token_classification_detector/tree/main) | 0.669 | 0.79 | 0.58 | 0.930 | 0.278 | 0.622 || [`xlm-roberta-large-qwen-tokens-2stage`](https://huggingface.co/imvladikon/bert_token_classification_detector/tree/xlm-roberta-large-qwen-tokens-2stage) | 0.661 | 0.84 | 0.54 | 0.920 | 0.204 | 0.635 || [`rumodernbert-qwen-tokens-2stage`](https://huggingface.co/imvladikon/bert_token_classification_detector/tree/rumodernbert-qwen-tokens-2stage) | 0.642 | 0.86 | 0.51 | 0.903 | 0.138 | 0.597 || [`mrt5-small-bytes-2stage`](https://huggingface.co/imvladikon/bert_token_classification_detector/tree/mrt5-small-bytes-2stage) | 0.622 | 0.88 | 0.48 | 0.903 | 0.011 | 0.584 || [`byt5-small-bytes`](https://huggingface.co/imvladikon/bert_token_classification_detector/tree/byt5-small-bytes) | – | – | – | – | – | 0.573 |
Ограничения: разметка агентская и неполная, часть «ложных» срабатываний — настоящие непомеченные ошибки. Грамматику все моделинаходят заметно хуже, чем алфавитные дефекты (иероглифы находятся почти всегда, английские вставки — примерно в 95% случаев).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Byte-level (ByT5) input for the same Qwen-token dataset.
Qwen3.8 uses byte-level BPE, so every Qwen token id maps to an exact byte string; the answer'sbytes are the concatenation of its tokens' bytes. ByT5 ids are byte + 3 (0 pad, 1 eos, 2 unk).Labels move from tokens to bytes: a BAD token gives B on its first byte and I on the rest, TAILbytes are I, -100 stays -100 (grouped scheme: +2 for grammar classes, as for token models).For evaluation byte probabilities are averaged back to Qwen tokens, so every metric is computed onexactly the same Qwen tokens as for the ModernBERT / XLM-R taggers."""from __future__ import annotations
import numpy as npimport torchfrom transformers import AutoTokenizer
from modeling import _byte_decoder
PROMPT_BYTES = 200SEP = "\n### ответ:\n".encode("utf-8")
class QwenBytes: def __init__(self, qwen_tokenizer_dir: str): qtok = AutoTokenizer.from_pretrained(qwen_tokenizer_dir, local_files_only=True) dec = _byte_decoder() # one get_vocab() call: per-id convert_ids_to_tokens is very slow in some transformers versions inv = {i: s for s, i in qtok.get_vocab().items()} self.tb = [] for i in range(248320): s = inv.get(i) if s is None or s.startswith("<|") or any(c not in dec for c in s): self.tb.append(b"") else: self.tb.append(bytes(dec[c] for c in s))
def prompt(self, query: str) -> list[int]: q = query.encode("utf-8")[:PROMPT_BYTES] return [b + 3 for b in q + SEP]
def answer(self, token_ids, token_labels=None): """Returns byte ids, byte labels, and for each token its [start, end) in the byte sequence.""" ids, labs, spans = [], [], [] for k, t in enumerate(token_ids): bs = self.tb[t] s = len(ids) ids.extend(b + 3 for b in bs) if token_labels is not None: l = token_labels[k] if l < 0: labs.extend([-100] * len(bs)) elif l == 0: labs.extend([0] * len(bs)) elif l % 2 == 1: # BAD-like: B then I labs.extend([l] + [l + 1] * (len(bs) - 1)) else: labs.extend([l] * len(bs)) spans.append((s, len(ids))) return ids, labs, spans
def byte_windows(n: int, a0: int, max_len: int, stride: int): span = max_len - a0 - 1 # room for eos starts, s = [], 0 while True: starts.append(s) if s + span >= n: break s += span - stride return [(s, min(n, s + span)) for s in starts]
def expand_windows_bytes(qb: QwenBytes, rows, max_len, stride, synth_weight, labels_fn, include_synth=True, include_corrected=True): out = {"input_ids": [], "labels": [], "weight": []} for r in rows: v = r["variant"] if (v.startswith("synthetic") and not include_synth) or (v == "corrected" and not include_corrected): continue a0 = r["answer_start"] lab = labels_fn(r) ids, blabs, _ = qb.answer(r["input_ids"][a0:], lab[a0:]) if not ids: continue p = qb.prompt(r["query"]) w = synth_weight if v.startswith("synthetic") else 1.0 for s, e in byte_windows(len(ids), len(p), max_len, stride): out["input_ids"].append(p + ids[s:e] + [1]) out["labels"].append([-100] * len(p) + blabs[s:e] + [-100]) out["weight"].append(w) return out
@torch.no_grad()def predict_row_bytes(qb: QwenBytes, model, row, max_len, stride, device, batch=8): a0 = row["answer_start"] ids, _, spans = qb.answer(row["input_ids"][a0:]) C = model.config.num_labels n_tok = len(spans) if not ids: return np.zeros((n_tok, C), dtype=np.float32) p0 = qb.prompt(row["query"]) ws = byte_windows(len(ids), len(p0), max_len, stride) probs = np.zeros((len(ids), C), dtype=np.float32) best = np.full(len(ids), -1.0) for b in range(0, len(ws), batch): chunk = ws[b:b + batch] seqs = [p0 + ids[s:e] + [1] for s, e in chunk] L = max(len(x) for x in seqs) x = torch.zeros((len(seqs), L), dtype=torch.long) m = torch.zeros((len(seqs), L), dtype=torch.long) for i, sq in enumerate(seqs): x[i, :len(sq)] = torch.as_tensor(sq) m[i, :len(sq)] = 1 logits = model(input_ids=x.to(device), attention_mask=m.to(device)).logits.float() p = torch.softmax(logits, -1).cpu().numpy() for i, (s, e) in enumerate(chunk): pos = np.arange(s, e) centr = np.minimum(pos - s, e - 1 - pos).astype(float) upd = centr > best[pos] probs[pos[upd]] = p[i, len(p0) + (pos[upd] - s)] best[pos[upd]] = centr[upd] out = np.zeros((n_tok, C), dtype=np.float32) for k, (s, e) in enumerate(spans): if e > s: out[k] = probs[s:e].mean(0) else: out[k, 0] = 1.0 # special tokens have no bytes return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348"""Windowed inference over long answers and defect-level metrics.
Scores: p_def(token) = P(BAD) + P(TAIL). A token is predicted defective when p_def >= threshold.With the grouped label scheme (O, BAD/TAIL-script, BAD/TAIL-grammar) the threshold is a pair(t_script, t_grammar) applied to P(script) and P(grammar) separately, since script leaks getp close to 1 while grammar errors score much lower.Predicted spans are maximal runs of predicted tokens.
Gold events are the BAD/TAIL tokens of one annotated error (event_ids). Positions with label -100inside the answer (DEPENDENT / EXCLUDED / UNCERTAIN) are neutral: a prediction there is neithera hit nor a false alarm.
event_recall share of gold events with at least one predicted token on their BAD/TAIL tokens head_recall share of BAD heads whose own token is predicted span_precision share of predicted spans (not fully neutral) overlapping a gold event token event_f1 harmonic mean of span_precision and event_recall row_* answer-level: "has at least one defect" vs "at least one predicted span" corrected_fp_per_1k predicted spans per 1000 tokens on repaired answers (should be ~0) ap_token average precision of p_def on labelled tokens (O vs BAD/TAIL), threshold-free *_tol2 the same with ±2 token tolerance: a prediction next to the annotated head (the annotation anchors e.g. an agreement error on one word of the phrase) counts as a hit and not as a false alarm"""from __future__ import annotations
from collections import defaultdict
import numpy as npimport torch
from modeling import model_inputs
def windows(n_answer: int, a0: int, max_len: int, stride: int): """Split answer positions [a0, a0+n) into windows that fit max_len together with the prompt.""" span = max_len - a0 if span <= stride: raise ValueError("prompt too long for max_len") starts, s = [], 0 while True: starts.append(s) if s + span >= n_answer: break s += span - stride return [(s, min(n_answer, s + span)) for s in starts]
@torch.no_grad()def predict_row(model, input_ids, a0: int, max_len: int, stride: int, device, batch: int = 8): """Return p(class) for every answer token, merging overlapping windows by centrality.""" ids = torch.as_tensor(input_ids, dtype=torch.long) prompt, ans = ids[:a0], ids[a0:] n = len(ans) if n == 0: return np.zeros((0, model.config.num_labels), dtype=np.float32) ws = windows(n, a0, max_len, stride) probs = np.zeros((n, model.config.num_labels), dtype=np.float32) best = np.full(n, -1.0) for b in range(0, len(ws), batch): chunk = ws[b:b + batch] seqs = [torch.cat([prompt, ans[s:e]]) for s, e in chunk] L = max(len(x) for x in seqs) pad = getattr(model.config, "qwen_pad_token_id", None) or model.config.pad_token_id or 0 x = torch.full((len(seqs), L), pad, dtype=torch.long) m = torch.zeros((len(seqs), L), dtype=torch.long) for i, sq in enumerate(seqs): x[i, :len(sq)] = sq m[i, :len(sq)] = 1 logits = model(**model_inputs(model, x.to(device), m.to(device))).logits.float() p = torch.softmax(logits, -1).cpu().numpy() for i, (s, e) in enumerate(chunk): pos = np.arange(s, e) centr = np.minimum(pos - s, e - 1 - pos).astype(float) upd = centr > best[pos] probs[pos[upd]] = p[i, a0 + (pos[upd] - s)] best[pos[upd]] = centr[upd] return probs
def average_precision(scores: np.ndarray, y: np.ndarray) -> float: if y.sum() == 0: return float("nan") order = np.argsort(-scores, kind="stable") y = y[order] tp = np.cumsum(y) prec = tp / np.arange(1, len(y) + 1) return float((prec * y).sum() / y.sum())
def spans_of(mask: np.ndarray): out, i, n = [], 0, len(mask) while i < n: if mask[i]: j = i while j + 1 < n and mask[j + 1]: j += 1 out.append((i, j + 1)) i = j + 1 else: i += 1 return out
SCRIPT_TYPES = {"CJK", "LATIN_INSERT", "MIXED_SCRIPT", "TRANSLITERATION"}
def p_def(p: np.ndarray) -> np.ndarray: return p[:, 1:].sum(1)
def defect_mask(p: np.ndarray, threshold) -> np.ndarray: if isinstance(threshold, (list, tuple)): return (p[:, 1:3].sum(1) >= threshold[0]) | (p[:, 3:5].sum(1) >= threshold[1]) return p_def(p) >= threshold
def dilate(mask: np.ndarray, k: int) -> np.ndarray: if k <= 0: return mask out = mask.copy() for d in range(1, k + 1): out[d:] |= mask[:-d] out[:-d] |= mask[d:] return out
def score_rows(rows, probs_list, threshold, tol: int = 2): """rows: dicts with labels (answer part, >0 = defect), event_ids, defect_type, variant.""" ev_total = ev_hit = heads = head_hit = 0 sp_total = sp_good = 0 ev_hit_t = sp_good_t = 0 by_type_t = defaultdict(int) row_tp = row_fp = row_fn = row_tn = 0 corr_spans = corr_tokens = 0 by_type = defaultdict(lambda: [0, 0]) for r, probs in zip(rows, probs_list): lab = np.asarray(r["labels"]) pred = defect_mask(probs, threshold) & (lab != -100) spans = spans_of(pred) if r["variant"] == "corrected": corr_spans += len(spans) corr_tokens += int((lab != -100).sum()) continue gold_pos = lab > 0 pred_near = dilate(pred, tol) gold_near = dilate(gold_pos, tol) events = defaultdict(list) for i, (l, ev) in enumerate(zip(lab, r["event_ids"])): if l > 0: events[ev].append(i) for ev, pos in events.items(): hit = bool(pred[pos].any()) ev_total += 1 ev_hit += hit t = next((r["defect_type"][i] for i in pos if lab[i] == 1), r["defect_type"][pos[0]]) by_type[t][0] += 1 by_type[t][1] += hit hit_t = bool(pred_near[pos].any()) ev_hit_t += hit_t by_type_t[t] += hit_t for i in np.flatnonzero(lab == 1): heads += 1 head_hit += bool(pred[i]) for s, e in spans: sp_total += 1 sp_good += bool(gold_pos[s:e].any()) sp_good_t += bool(gold_near[s:e].any()) has_gold, has_pred = bool(events), bool(spans) row_tp += has_gold and has_pred row_fp += (not has_gold) and has_pred row_fn += has_gold and not has_pred row_tn += (not has_gold) and not has_pred rec = ev_hit / ev_total if ev_total else float("nan") prec = sp_good / sp_total if sp_total else float("nan") f1 = 2 * prec * rec / (prec + rec) if sp_total and ev_total and prec + rec > 0 else 0.0 rec_t = ev_hit_t / ev_total if ev_total else float("nan") prec_t = sp_good_t / sp_total if sp_total else float("nan") f1_t = 2 * prec_t * rec_t / (prec_t + rec_t) if sp_total and ev_total and prec_t + rec_t > 0 else 0.0 rp = row_tp / (row_tp + row_fp) if row_tp + row_fp else float("nan") rr = row_tp / (row_tp + row_fn) if row_tp + row_fn else float("nan") return { "threshold": threshold, "event_recall": rec, "span_precision": prec, "event_f1": f1, "head_recall": head_hit / heads if heads else float("nan"), "events": ev_total, "pred_spans": sp_total, "row_precision": rp, "row_recall": rr, "rows_tp_fp_fn_tn": [row_tp, row_fp, row_fn, row_tn], "corrected_fp_per_1k": 1000 * corr_spans / corr_tokens if corr_tokens else float("nan"), "event_recall_tol2": rec_t, "span_precision_tol2": prec_t, "event_f1_tol2": f1_t, "recall_by_type": {k: {"events": v[0], "recall": v[1] / v[0], "recall_tol2": by_type_t[k] / v[0]} for k, v in sorted(by_type.items())}, }
def full_report(rows, probs_list, thresholds=None, fixed_threshold=None, tune_on: str = "event_f1_tol2"): lab = np.concatenate([np.asarray(r["labels"]) for r in rows]) pd = np.concatenate([p_def(p) for p in probs_list]) keep = lab != -100 ap = average_precision(pd[keep], (lab[keep] > 0).astype(int)) if fixed_threshold is not None: best = score_rows(rows, probs_list, fixed_threshold) else: grid = thresholds or [0.02, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.93, 0.95, 0.97, 0.98, 0.99, 0.995, 0.998] if probs_list[0].shape[1] == 5: coarse = [0.02, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.98, 0.99, 0.995] grid = [(a, b) for a in coarse for b in coarse] best = max((score_rows(rows, probs_list, t) for t in grid), key=lambda m: m[tune_on]) best["ap_token"] = ap half = (0.5, 0.5) if probs_list[0].shape[1] == 5 else 0.5 best["at_0.5"] = {k: v for k, v in score_rows(rows, probs_list, half).items() if k != "recall_by_type"} return best
# ---- standard span-level evaluation: seqeval (via HF evaluate) over BIO tags ------------------------_SEQEVAL = None
def seqeval_metric(): global _SEQEVAL if _SEQEVAL is None: import evaluate _SEQEVAL = evaluate.load("seqeval") return _SEQEVAL
def gold_bio(r, grouped: bool): """labels 0/1/2 (O/BAD/TAIL) -> BIO over reviewed positions only (label -100 dropped).""" out = [] for l, t in zip(r["labels"], r["defect_type"]): if l < 0: continue if l == 0: out.append("O") continue ent = ("SCRIPT" if t in SCRIPT_TYPES else "GRAM") if grouped else "DEF" out.append(("B-" if l == 1 else "I-") + ent) return out
def pred_bio(p: np.ndarray, labels, threshold=None): """Predicted BIO: argmax by default; with a threshold, a group fires when its summed p >= threshold.""" k = p.shape[1] groups = [("DEF", 1)] if k == 3 else [("SCRIPT", 1), ("GRAM", 3)] out = [] for i, l in enumerate(labels): if l < 0: continue if threshold is None: c = int(p[i].argmax()) if c == 0: out.append("O") continue name, base = groups[(c - 1) // 2] out.append(("B-" if c == base else "I-") + name) continue thr = threshold if isinstance(threshold, (list, tuple)) else [threshold] * len(groups) best = None for (name, base), t in zip(groups, thr): s = p[i, base] + p[i, base + 1] if s >= t and (best is None or s > best[0]): best = (s, name, base) if best is None: out.append("O") else: _, name, base = best out.append(("B-" if p[i, base] >= p[i, base + 1] else "I-") + name) return out
def seqeval_report(rows, probs_list, threshold=None, grouped=None): """seqeval on source answers; false alarms on repaired answers reported separately.""" grouped = probs_list[0].shape[1] == 5 if grouped is None else grouped gold, pred, fp_ent, corr_tok = [], [], 0, 0 for r, p in zip(rows, probs_list): pb = pred_bio(p, r["labels"], threshold) if r["variant"] == "corrected": fp_ent += sum(1 for t in pb if t.startswith("B-")) + sum( 1 for a, b in zip(["O"] + pb, pb) if b.startswith("I-") and a == "O") corr_tok += len(pb) continue gold.append(gold_bio(r, grouped)) pred.append(pb) res = seqeval_metric().compute(predictions=pred, references=gold, zero_division=0) out = {"precision": res["overall_precision"], "recall": res["overall_recall"], "f1": res["overall_f1"], "threshold": threshold, "corrected_fp_per_1k": 1000 * fp_ent / max(corr_tok, 1)} for k, v in res.items(): if isinstance(v, dict): out[k] = {m: float(v[m]) for m in ("precision", "recall", "f1", "number")} return out
def seqeval_sweep(rows, probs_list): """Best threshold on these rows by overall seqeval F1: a single threshold for 3 classes, a full 2-D grid (script, grammar) for grouped models, so a group that never helps gets a high threshold.""" grid = [0.02, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.98, 0.99, 0.999] cands = [(a, b) for a in grid for b in grid] if probs_list[0].shape[1] == 5 else grid return max((seqeval_report(rows, probs_list, t) for t in cands), key=lambda r: r["f1"])
# ---- span-overlap evaluation (same seqeval entities, overlap matching instead of exact) -------------def _entities(tags): from seqeval.metrics.sequence_labeling import get_entities return [(t, s, e + 1) for t, s, e in get_entities(tags)] # [start, end)
def overlap_report(rows, probs_list, threshold=None, grouped=None): """Entities are extracted from the BIO sequences exactly as seqeval does (get_entities); a gold entity counts as found if any predicted entity of the same group overlaps it, and a predicted entity counts as correct if it overlaps any gold entity of the same group. 'overall' ignores the group. False alarms on repaired answers are reported separately.""" grouped = probs_list[0].shape[1] == 5 if grouped is None else grouped stats = defaultdict(lambda: [0, 0, 0, 0]) # gold, gold_found, pred, pred_correct fp_corr = corr_tok = 0 for r, p in zip(rows, probs_list): pb = pred_bio(p, r["labels"], threshold) pe = _entities(pb) if r["variant"] == "corrected": fp_corr += len(pe) corr_tok += len(pb) continue ge = _entities(gold_bio(r, grouped)) for key, same in (("overall", False), (None, True)): for t, s, e in ge: k = key or t stats[k][0] += 1 stats[k][1] += any(ps < e and s < pe_ and (not same or pt == t) for pt, ps, pe_ in pe) for t, s, e in pe: k = key or t stats[k][2] += 1 stats[k][3] += any(gs < e and s < ge_ and (not same or gt == t) for gt, gs, ge_ in ge)
def prf(v): p_ = v[3] / v[2] if v[2] else 0.0 r_ = v[1] / v[0] if v[0] else 0.0 return {"precision": p_, "recall": r_, "f1": 2 * p_ * r_ / (p_ + r_) if p_ + r_ else 0.0, "number": v[0]}
out = prf(stats["overall"]) out |= {"threshold": threshold, "corrected_fp_per_1k": 1000 * fp_corr / max(corr_tok, 1), "_counts": {k: list(v) for k, v in stats.items()} | {"_corrected": [fp_corr, corr_tok]}} for k, v in stats.items(): if k != "overall": out[k] = prf(v) return out
def overlap_sweep(rows, probs_list): """Best threshold by overlap F1 (single for 3 classes, 2-D grid for grouped models).""" grid = [0.02, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.98, 0.99, 0.999] cands = [(a, b) for a in grid for b in grid] if probs_list[0].shape[1] == 5 else grid return max((overlap_report(rows, probs_list, t) for t in cands), key=lambda r: r["f1"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""Encoder token classifiers over the Qwen3.8-Flash-Next vocabulary (tokenizer only, no Qwen weights).
The pretrained encoder keeps its layers; its input embedding table is replaced by one row perQwen token id (248320). Row i is initialised from the encoder's own embeddings of Qwen token i:
* byte-level BPE encoders (ModernBERT / RuModernBERT): the Qwen token's byte-level string is split by the encoder's BPE directly. Both use the GPT-2 byte alphabet (checked: 0 mismatches on 20k random tokens), so partial UTF-8 fragments of CJK characters get their own byte pieces.* SentencePiece/Unigram encoders (XLM-RoBERTa): the token text with spaces as "▁" is split by the Unigram model (word-initial vs word-internal pieces are kept apart). A partial UTF-8 fragment gets the mean embedding of the encoder's single-character pieces whose UTF-8 bytes start or end with that fragment.
Row = mean of the piece embeddings. The saved model is a plain <Arch>ForTokenClassification withvocab_size=248320 that AutoModelForTokenClassification loads without custom code; the Qwentokenizer is saved next to it.
RoBERTa-family position ids are computed from input_ids != pad_token_id (=1); in the Qwenvocabulary id 1 is an ordinary token ('"'), so these models always get explicit position_ids(model_inputs); config.qwen_requires_position_ids marks it for users of the saved model."""from __future__ import annotations
from pathlib import Path
import torchfrom safetensors.torch import load_file, save_filefrom torch import nnfrom transformers import AutoModelForTokenClassification, AutoTokenizer
LABEL_NAMES = ["O", "BAD", "TAIL"]GROUPED_LABEL_NAMES = ["O", "BAD-script", "TAIL-script", "BAD-grammar", "TAIL-grammar"]QWEN_VOCAB = 248320ROBERTA_TYPES = {"xlm-roberta", "roberta", "camembert"}
def _byte_decoder(): bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) cs = bs[:] n = 0 for b in range(256): if b not in bs: bs.append(b) cs.append(256 + n) n += 1 return {chr(c): b for b, c in zip(bs, cs)}
def _special_map(qtok, btok): return {"<|im_start|>": btok.cls_token_id if btok.cls_token_id is not None else btok.bos_token_id, "<|im_end|>": btok.sep_token_id if btok.sep_token_id is not None else btok.eos_token_id, "<|endoftext|>": btok.pad_token_id}
@torch.no_grad()def build_mapped_table(E: torch.Tensor, base: str, qwen_tokenizer_dir: str, cache: Path | None = None): if cache and cache.exists(): return load_file(str(cache))["mapped"].float(), {"cache": str(cache)} qtok = AutoTokenizer.from_pretrained(qwen_tokenizer_dir, local_files_only=True) btok = AutoTokenizer.from_pretrained(base) model = btok.backend_tokenizer.model kind = type(model).__name__ special = _special_map(qtok, btok) E = E.float() fallback = E.mean(0) table = torch.empty(QWEN_VOCAB, E.shape[1]) stats = {"kind": kind, "mapped": 0, "special": 0, "fragment": 0, "fallback": 0} byte_dec = _byte_decoder() char_pieces = None if kind == "Unigram": # single-character pieces (with or without the word boundary mark) and their UTF-8 bytes char_pieces = [] for piece, pid in btok.get_vocab().items(): ch = piece.lstrip("▁") if len(ch) == 1 and ord(ch) > 127: char_pieces.append((ch.encode("utf-8"), pid)) inv = {i: s for s, i in qtok.get_vocab().items()} # per-id convert_ids_to_tokens is slow in some versions for i in range(QWEN_VOCAB): s = inv.get(i) if s in special and special[s] is not None: table[i] = E[special[s]] stats["special"] += 1 continue ids = [] if s and not s.startswith("<|"): if kind == "BPE": ids = [t.id for t in model.tokenize(s)] else: raw = bytes(byte_dec[c] for c in s) try: text = raw.decode("utf-8") ids = [t.id for t in model.tokenize(text.replace(" ", "▁"))] ids = [t for t in ids if t != btok.unk_token_id] except UnicodeDecodeError: core = raw.strip(b" ") ids = [pid for enc, pid in char_pieces if enc.startswith(core) or enc.endswith(core)] if ids: stats["fragment"] += 1 table[i] = E[ids].mean(0) continue if ids: table[i] = E[ids].mean(0) stats["mapped"] += 1 else: table[i] = fallback stats["fallback"] += 1 if cache: cache.parent.mkdir(parents=True, exist_ok=True) save_file({"mapped": table.to(torch.bfloat16).contiguous()}, str(cache)) return table, stats
def build_model(base: str, qwen_tokenizer_dir: str, mapped_cache: Path | None = None, freeze_embeddings: bool = False, label_names=LABEL_NAMES): qtok = AutoTokenizer.from_pretrained(qwen_tokenizer_dir, local_files_only=True) model = AutoModelForTokenClassification.from_pretrained( base, num_labels=len(label_names), id2label=dict(enumerate(label_names)), label2id={n: i for i, n in enumerate(label_names)}) old = model.get_input_embeddings() table, stats = build_mapped_table(old.weight.detach(), base, qwen_tokenizer_dir, mapped_cache) roberta = model.config.model_type in ROBERTA_TYPES emb = nn.Embedding(table.shape[0], table.shape[1], padding_idx=None if roberta else qtok.pad_token_id) emb.weight.data.copy_(table) emb.weight.requires_grad = not freeze_embeddings model.set_input_embeddings(emb) model.config.vocab_size = table.shape[0] model.config.tie_word_embeddings = False if roberta: # keep pad_token_id=1: RoBERTa uses it as the position offset; positions are passed explicitly model.config.qwen_requires_position_ids = True else: model.config.pad_token_id = qtok.pad_token_id model.config.qwen_pad_token_id = qtok.pad_token_id model.config.bos_token_id = None model.config.eos_token_id = qtok.convert_tokens_to_ids("<|im_end|>") for k in ("cls_token_id", "sep_token_id"): if hasattr(model.config, k): setattr(model.config, k, qtok.convert_tokens_to_ids("<|im_start|>" if k == "cls_token_id" else "<|im_end|>")) return model, stats
def model_inputs(model, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> dict: out = {"input_ids": input_ids, "attention_mask": attention_mask} if getattr(model.config, "qwen_requires_position_ids", False): # RoBERTa convention: positions start at pad_token_id + 1, padding gets pad_token_id off = model.config.pad_token_id pos = torch.cumsum(attention_mask, 1) * attention_mask + off out["position_ids"] = pos.long() return out
def max_positions(model) -> int: n = getattr(model.config, "max_position_embeddings", 8192) return n - 2 if model.config.model_type in ROBERTA_TYPES else n
def save_tagger(model, out: Path, qwen_tokenizer_dir: str, extra: dict | None = None): for k, v in (extra or {}).items(): setattr(model.config, k, v) model.save_pretrained(str(out)) AutoTokenizer.from_pretrained(qwen_tokenizer_dir, local_files_only=True).save_pretrained(str(out))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Native-tokenization input for a diagnostic experiment: is the Qwen-token input the bottleneck?
The Qwen answer bytes decode losslessly to text; the encoder re-tokenizes that text with its OWNtokenizer (the segmentation it was pretrained on). Labels move from Qwen tokens to native tokens bycharacter overlap: a native token gets the label of the first positive Qwen token it overlaps(B only on the first native token of that Qwen token, I after), 0 if it only overlaps O tokens,-100 otherwise. Predictions go back to Qwen tokens as the mean over the native tokens that overlapeach Qwen token, so every metric is computed on exactly the same Qwen tokens as the other taggers.Interface mirrors byt5_adapter.QwenBytes (prompt / answer / special ids)."""from __future__ import annotations
import numpy as npimport torchfrom transformers import AutoTokenizer
from byt5_adapter import QwenBytes
class NativeText: def __init__(self, qwen_tokenizer_dir: str, base: str): self.qb = QwenBytes(qwen_tokenizer_dir) self.tok = AutoTokenizer.from_pretrained(base) self.cls = [self.tok.cls_token_id] self.sep = [self.tok.sep_token_id] self.pad_id = self.tok.pad_token_id
def prompt(self, query: str) -> list[int]: return self.cls + self.tok(query, add_special_tokens=False)["input_ids"][:128] + self.sep
def answer(self, token_ids, token_labels=None): chunks = [self.qb.tb[t] for t in token_ids] full = b"".join(chunks) text = full.decode("utf-8", errors="replace") # byte offset -> char index char_of_byte, ci = [], 0 for ch in text: n = len(ch.encode("utf-8")) if ch != "�" else 1 char_of_byte += [ci] * n ci += 1 char_of_byte.append(ci) qspan, b = [], 0 for c in chunks: qspan.append((char_of_byte[b], char_of_byte[b + len(c)] if len(c) else char_of_byte[b])) b += len(c) enc = self.tok(text, add_special_tokens=False, return_offsets_mapping=True) ids, offs = enc["input_ids"], enc["offset_mapping"] # native token -> overlapping qwen tokens (both sorted by position: two pointers) per_native, k0 = [], 0 for s, e in offs: while k0 < len(qspan) and qspan[k0][1] <= s: k0 += 1 ks, k = [], k0 while k < len(qspan) and qspan[k][0] < max(e, s + 1): if qspan[k][1] > qspan[k][0]: ks.append(k) k += 1 per_native.append(ks) spans = [[] for _ in token_ids] for j, ks in enumerate(per_native): for k in ks: spans[k].append(j) labs = [] if token_labels is not None: seen_bad = set() for j, ks in enumerate(per_native): pos = [k for k in ks if token_labels[k] > 0] if pos: k = pos[0] l = token_labels[k] if l % 2 == 1 and k in seen_bad: l += 1 if l % 2 == 1: seen_bad.add(k) labs.append(l) elif ks and all(token_labels[k] == 0 for k in ks): labs.append(0) else: labs.append(-100) return ids, labs, spans
def windows(n: int, a0: int, max_len: int, stride: int): span = max_len - a0 - 1 starts, s = [], 0 while True: starts.append(s) if s + span >= n: break s += span - stride return [(s, min(n, s + span)) for s in starts]
def expand_windows_native(nt: NativeText, rows, max_len, stride, synth_weight, labels_fn, include_synth=True, include_corrected=True): out = {"input_ids": [], "labels": [], "weight": []} for r in rows: v = r["variant"] if (v.startswith("synthetic") and not include_synth) or (v == "corrected" and not include_corrected): continue a0 = r["answer_start"] lab = labels_fn(r) ids, nl, _ = nt.answer(r["input_ids"][a0:], lab[a0:]) if not ids: continue p = nt.prompt(r["query"]) w = synth_weight if v.startswith("synthetic") else 1.0 for s, e in windows(len(ids), len(p), max_len, stride): out["input_ids"].append(p + ids[s:e] + nt.sep) out["labels"].append([-100] * len(p) + nl[s:e] + [-100]) out["weight"].append(w) return out
@torch.no_grad()def predict_row_native(nt: NativeText, model, row, max_len, stride, device, batch=8): a0 = row["answer_start"] ids, _, spans = nt.answer(row["input_ids"][a0:]) C = model.config.num_labels out = np.zeros((len(spans), C), dtype=np.float32) out[:, 0] = 1.0 if not ids: return out p0 = nt.prompt(row["query"]) ws = windows(len(ids), len(p0), max_len, stride) probs = np.zeros((len(ids), C), dtype=np.float32) best = np.full(len(ids), -1.0) for b in range(0, len(ws), batch): chunk = ws[b:b + batch] seqs = [p0 + ids[s:e] + nt.sep for s, e in chunk] L = max(len(x) for x in seqs) x = torch.full((len(seqs), L), nt.pad_id, dtype=torch.long) m = torch.zeros((len(seqs), L), dtype=torch.long) for i, sq in enumerate(seqs): x[i, :len(sq)] = torch.as_tensor(sq) m[i, :len(sq)] = 1 logits = model(input_ids=x.to(device), attention_mask=m.to(device)).logits.float() p = torch.softmax(logits, -1).cpu().numpy() for i, (s, e) in enumerate(chunk): pos = np.arange(s, e) centr = np.minimum(pos - s, e - 1 - pos).astype(float) upd = centr > best[pos] probs[pos[upd]] = p[i, len(p0) + (pos[upd] - s)] best[pos[upd]] = centr[upd] for k, js in enumerate(spans): if js: out[k] = probs[js].mean(0) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116#!/usr/bin/env python3"""Tag defective Qwen3.8-Flash-Next tokens in an answer with any saved tagger of this project.
The input kind is read from the model config: native_text_input encoder with its own tokenizer (the Qwen answer is decoded to text), e.g. RuModernBERT qwen_byte_input byte model (ByT5 / MrT5) over the bytes of the Qwen tokens otherwise encoder whose embedding table is the Qwen vocabulary (input = Qwen ids)Output is always per Qwen token of the answer.
python tag.py --model MODEL_DIR --query "вопрос" --answer-file answer.txt python tag.py --model MODEL_DIR --ids-json ids.json --answer-start 12 # pre-tokenized Qwen ids
MODEL_DIR/qwen_tokenizer holds the Qwen3.8 tokenizer for native/byte models; for Qwen-id models theQwen tokenizer is the model's own tokenizer. Thresholds default to config.defect_threshold([script, grammar] for 5-class models)."""from __future__ import annotations
import argparseimport jsonfrom pathlib import Path
import torchfrom transformers import AutoConfig, AutoModelForTokenClassification, AutoTokenizer
from metrics import defect_mask, p_def, predict_row, spans_of
class Tagger: def __init__(self, path: str | Path, device: str | None = None, max_len: int | None = None, stride: int | None = None): path = Path(path) self.dev = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu")) raw = json.loads((path / "config.json").read_text()) qdir = path / "qwen_tokenizer" if (path / "qwen_tokenizer").exists() else path self.qtok = AutoTokenizer.from_pretrained(str(qdir)) if raw.get("native_text_input"): from native_adapter import NativeText, predict_row_native self.model = AutoModelForTokenClassification.from_pretrained(str(path)) nt = NativeText(str(qdir), str(path)) L, S = max_len or 2048, stride or 256 self._predict = lambda ids, a0, q: predict_row_native(nt, self.model, {"input_ids": ids, "answer_start": a0, "query": q}, L, S, self.dev) elif raw.get("qwen_byte_input"): from byt5_adapter import QwenBytes, predict_row_bytes if raw.get("model_type") == "mrt5": from mrt5.token_classification import MrT5ForTokenClassification, load_config self.model = MrT5ForTokenClassification.from_pretrained(str(path), config=load_config(path)) else: from transformers import T5ForTokenClassification self.model = T5ForTokenClassification.from_pretrained(str(path)) qb = QwenBytes(str(qdir)) L, S = max_len or raw.get("tagger_max_len", 2048), stride or raw.get("tagger_stride", 256) self._predict = lambda ids, a0, q: predict_row_bytes(qb, self.model, {"input_ids": ids, "answer_start": a0, "query": q}, L, S, self.dev) else: self.model = AutoModelForTokenClassification.from_pretrained(str(path)) L, S = max_len or raw.get("tagger_max_len", 2048), stride or raw.get("tagger_stride", 256) self._predict = lambda ids, a0, q: predict_row(self.model, ids, a0, L, S, self.dev) self.model.to(self.dev).eval() thr = raw.get("defect_threshold", 0.5) self.threshold = tuple(thr) if isinstance(thr, list) else thr
def prompt_ids(self, query: str) -> list[int]: return self.qtok(f"<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n", add_special_tokens=False)["input_ids"]
@torch.no_grad() def tag_ids(self, ids: list[int], answer_start: int, query: str = "", threshold=None): """Per-token class probabilities and defect spans (answer token indices) for Qwen ids.""" with torch.autocast("cuda", dtype=torch.bfloat16, enabled=self.dev.type == "cuda"): probs = self._predict(ids, answer_start, query) thr = self.threshold if threshold is None else threshold mask = defect_mask(probs, thr) ans = ids[answer_start:] spans = [] for s, e in spans_of(mask): span = {"tokens": [s, e], "text": self.qtok.decode(ans[s:e]), "p": round(float(p_def(probs)[s:e].max()), 4)} if probs.shape[1] == 5: span["group"] = "script" if probs[s:e, 1:3].sum(1).max() >= probs[s:e, 3:5].sum(1).max() else "grammar" spans.append(span) return probs, spans
def tag_text(self, answer: str, query: str = "", threshold=None): pre = self.prompt_ids(query) ids = pre + self.qtok(answer, add_special_tokens=False)["input_ids"] return ids, len(pre), *self.tag_ids(ids, len(pre), query, threshold)
def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--model", type=Path, required=True) ap.add_argument("--query", default="") ap.add_argument("--answer") ap.add_argument("--answer-file", type=Path) ap.add_argument("--ids-json", type=Path, help="JSON list of Qwen token ids: prompt + answer") ap.add_argument("--answer-start", type=int, help="index of the first answer token in --ids-json") ap.add_argument("--threshold", type=float, nargs="*", help="one value, or script grammar") a = ap.parse_args() t = Tagger(a.model) thr = None if not a.threshold else (tuple(a.threshold) if len(a.threshold) == 2 else a.threshold[0]) if a.ids_json: ids, a0 = json.loads(a.ids_json.read_text()), a.answer_start _, spans = t.tag_ids(ids, a0, a.query, thr) else: answer = a.answer if a.answer is not None else a.answer_file.read_text() ids, a0, _, spans = t.tag_text(answer, a.query, thr) ans = ids[a0:] marked, cur = [], 0 for sp in spans: s, e = sp["tokens"] marked += [t.qtok.decode(ans[cur:s]), "⟦" + t.qtok.decode(ans[s:e]) + "⟧"] cur = e marked.append(t.qtok.decode(ans[cur:])) print("".join(marked)) print(json.dumps(spans, ensure_ascii=False, indent=1))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148{ "activation_function": "gelu", "allow_embedding_resizing": true, "architectures": [ "ModernBertForTokenClassification" ], "attention_bias": false, "attention_dropout": 0.0, "attention_layer": "rope", "attention_probs_dropout_prob": 0.0, "attn_out_bias": false, "attn_out_dropout_prob": 0.1, "attn_qkv_bias": false, "bert_layer": "prenorm", "bos_token_id": 50281, "classifier_activation": "gelu", "classifier_bias": false, "classifier_dropout": 0.0, "classifier_pooling": "cls", "cls_token_id": 50281, "compile_model": true, "decoder_bias": true, "defect_label_names": [ "O", "BAD-script", "TAIL-script", "BAD-grammar", "TAIL-grammar" ], "defect_threshold": [ 0.5, 0.9 ], "deterministic_flash_attn": false, "dtype": "float32", "embed_dropout_prob": 0.0, "embed_norm": true, "embedding_dropout": 0.0, "embedding_layer": "sans_pos", "eos_token_id": 50282, "final_norm": true, "global_attn_every_n_layers": 3, "head_pred_act": "gelu", "hidden_act": "gelu", "hidden_activation": "gelu", "hidden_size": 768, "id2label": { "0": "O", "1": "BAD-script", "2": "TAIL-script", "3": "BAD-grammar", "4": "TAIL-grammar" }, "init_method": "full_megatron", "initializer_cutoff_factor": 2.0, "initializer_range": 0.02, "intermediate_size": 1152, "label2id": { "BAD-grammar": 3, "BAD-script": 1, "O": 0, "TAIL-grammar": 4, "TAIL-script": 2 }, "layer_types": [ "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention" ], "local_attention": 256, "local_attn_rotary_emb_base": 10000.0, "loss_function": "fa_cross_entropy", "loss_kwargs": { "reduction": "mean" }, "masked_prediction": true, "max_position_embeddings": 8192, "mlp_bias": false, "mlp_dropout": 0.0, "mlp_dropout_prob": 0.0, "mlp_in_bias": false, "mlp_layer": "glu", "mlp_out_bias": false, "model_type": "modernbert", "native_text_input": true, "norm_bias": false, "norm_eps": 1e-05, "norm_kwargs": { "bias": false, "eps": 1e-05 }, "normalization": "layernorm", "num_attention_heads": 12, "num_hidden_layers": 22, "pad_token_id": 50283, "padding": "unpadded", "prompt_format": "[CLS] query [SEP] decoded answer text [SEP]", "repad_logits_with_grad": false, "rope_parameters": { "full_attention": { "rope_theta": 160000.0, "rope_type": "default" }, "sliding_attention": { "rope_theta": 10000.0, "rope_type": "default" } }, "rotary_emb_base": 160000.0, "rotary_emb_dim": null, "rotary_emb_interleaved": false, "rotary_emb_scale_base": null, "sep_token_id": 50282, "skip_first_prenorm": true, "sparse_pred_ignore_index": -100, "sparse_prediction": false, "tie_word_embeddings": true, "transformers_version": "5.16.1", "unpad_embeddings": true, "use_cache": false, "vocab_size": 50368, "defect_threshold_val": [ 0.99, 0.98 ], "defect_threshold_note": "[script, grammar]; tuned on out-of-fold CV predictions (validation-tuned value in defect_threshold_val)", "tagger_max_len": 2048, "tagger_stride": 256}123version https://git-lfs.github.com/spec/v1oid sha256:deb23992c6062294571f423a820771164307352fc4a2179e6c0275b16f73dbe1size 598449012123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170{%- set image_count = namespace(value=0) %}{%- set video_count = namespace(value=0) %}{%- macro render_content(content, do_vision_count, is_system_content=false) %} {%- if content is string %} {{- content }} {%- elif content is iterable and content is not mapping %} {%- for item in content %} {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain images.') }} {%- endif %} {%- if do_vision_count %} {%- set image_count.value = image_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Picture ' ~ image_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|image_pad|><|vision_end|>' }} {%- elif 'video' in item or item.type == 'video' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain videos.') }} {%- endif %} {%- if do_vision_count %} {%- set video_count.value = video_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Video ' ~ video_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|video_pad|><|vision_end|>' }} {%- elif 'text' in item %} {{- item.text }} {%- else %} {{- raise_exception('Unexpected item type in content.') }} {%- endif %} {%- endfor %} {%- elif content is none or content is undefined %} {{- '' }} {%- else %} {{- raise_exception('Unexpected content type.') }} {%- endif %}{%- endmacro %}{%- if not messages %} {{- raise_exception('No messages provided.') }}{%- endif %}{%- set reasoning_instructions = '' %}{%- if enable_thinking is undefined or enable_thinking is true %} {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %} {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %} {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }} {%- endif %} {%- if resolved_reasoning_effort == 'xhigh' %} {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %} {%- elif resolved_reasoning_effort == 'low' %} {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %} {%- endif %}{%- endif %}{%- if tools and tools is iterable and tools is not mapping %} {{- '<|im_start|>system\n' }} {%- if reasoning_instructions %} {{- reasoning_instructions + '\n\n' }} {%- endif %} {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>" }} {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {%- if content %} {{- '\n\n' + content }} {%- endif %} {%- endif %} {{- '<|im_end|>\n' }}{%- else %} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {%- if content %} {{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + content + '<|im_end|>\n' }} {%- elif reasoning_instructions %} {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }} {%- endif %} {%- elif reasoning_instructions %} {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }} {%- endif %}{%- endif %}{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}{%- for message in messages[::-1] %} {%- set index = (messages|length - 1) - loop.index0 %} {%- if ns.multi_step_tool and message.role == "user" %} {%- set content = render_content(message.content, false)|trim %} {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %} {%- set ns.multi_step_tool = false %} {%- set ns.last_query_index = index %} {%- endif %} {%- endif %}{%- endfor %}{%- if ns.multi_step_tool %} {{- raise_exception('No user query found in messages.') }}{%- endif %}{%- for message in messages %} {%- set content = render_content(message.content, true)|trim %} {%- if message.role == "system" %} {%- if not loop.first %} {{- raise_exception('System message must be at the beginning.') }} {%- endif %} {%- elif message.role == "user" %} {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string %} {%- set reasoning_content = message.reasoning_content %} {%- endif %} {%- set reasoning_content = reasoning_content|trim %} {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %} {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} {%- for tool_call in message.tool_calls %} {%- if tool_call.function is defined %} {%- set tool_call = tool_call.function %} {%- endif %} {%- if loop.first %} {%- if content|trim %} {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- else %} {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- else %} {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- if tool_call.arguments is defined and tool_call.arguments != '' %} {%- for args_name, args_value in tool_call.arguments|items %} {{- '<parameter=' + args_name + '>\n' }} {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %} {{- args_value }} {{- '\n</parameter>\n' }} {%- endfor %} {%- endif %} {{- '</function>\n</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|im_end|>\n' }} {%- elif message.role == "tool" %} {%- if loop.previtem and loop.previtem.role != "tool" %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- content }} {{- '\n</tool_response>' }} {%- if not loop.last and loop.nextitem.role != "tool" %} {{- '<|im_end|>\n' }} {%- elif loop.last %} {{- '<|im_end|>\n' }} {%- endif %} {%- else %} {{- raise_exception('Unexpected message role.') }} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }} {%- if enable_thinking is defined and enable_thinking is false %} {{- '<think>\n\n</think>\n\n' }} {%- else %} {{- '<think>\n' }} {%- endif %}{%- endif %}123version https://git-lfs.github.com/spec/v1oid sha256:0997f410c57a1f4e53b09e4be8f4a172d90edd9564368fb0847030937229b9f3size 12809320123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305{ "add_prefix_space": false, "added_tokens_decoder": { "248044": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248045": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248046": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248047": { "content": "<|object_ref_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248048": { "content": "<|object_ref_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248049": { "content": "<|box_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248050": { "content": "<|box_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248051": { "content": "<|quad_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248052": { "content": "<|quad_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248053": { "content": "<|vision_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248054": { "content": "<|vision_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248055": { "content": "<|vision_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248056": { "content": "<|image_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248057": { "content": "<|video_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248058": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248059": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248060": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248061": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248062": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248063": { "content": "<|fim_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248064": { "content": "<|repo_name|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248065": { "content": "<|file_sep|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248066": { "content": "<tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248067": { "content": "</tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248068": { "content": "<think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248069": { "content": "</think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "248070": { "content": "<|audio_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248071": { "content": "<|audio_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248072": { "content": "<tts_pad>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248073": { "content": "<tts_text_bos>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248074": { "content": "<tts_text_eod>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248075": { "content": "<tts_text_bos_single>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "248076": { "content": "<|audio_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [ "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>", "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>", "<|image_pad|>", "<|video_pad|>" ], "bos_token": null, "chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n<tool_call>\\n<function=example_function_name>\\n<parameter=example_parameter_1>\\nvalue_1\\n</parameter>\\n<parameter=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter>\\n</function>\\n</tool_call>\\n\\n<IMPORTANT>\\nReminder:\\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n</IMPORTANT>' }}\n {%- if messages[0].role == 'system' %}\n {%- set content = render_content(messages[0].content, false, true)|trim %}\n {%- if content %}\n {{- '\\n\\n' + content }}\n {%- endif %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {%- set content = render_content(messages[0].content, false, true)|trim %}\n {%- if content %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + content + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if ns.multi_step_tool %}\n {{- raise_exception('No user query found in messages.') }}\n{%- endif %}\n{%- for message in messages %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" %}\n {%- if not loop.first %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- endif %}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content + '\\n</think>\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n<tool_call>\\n<function=' + tool_call.name + '>\\n' }}\n {%- else %}\n {{- '<tool_call>\\n<function=' + tool_call.name + '>\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n<tool_call>\\n<function=' + tool_call.name + '>\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is defined and tool_call.arguments != '' %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '<parameter=' + args_name + '>\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n</parameter>\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '</function>\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- else %}\n {{- '<think>\\n' }}\n {%- endif %}\n{%- endif %}", "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "errors": "replace", "model_max_length": 262144, "pad_token": "<|endoftext|>", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null, "add_bos_token": false, "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", "extra_special_tokens": { "audio_bos_token": "<|audio_start|>", "audio_eos_token": "<|audio_end|>", "audio_token": "<|audio_pad|>", "image_token": "<|image_pad|>", "video_token": "<|video_pad|>", "vision_bos_token": "<|vision_start|>", "vision_eos_token": "<|vision_end|>" }}1234567891011121314151617{ "backend": "tokenizers", "clean_up_tokenization_spaces": true, "cls_token": "[CLS]", "is_local": false, "local_files_only": false, "mask_token": "[MASK]", "model_input_names": [ "input_ids", "attention_mask" ], "model_max_length": 1000000000000000019884624838656, "pad_token": "[PAD]", "sep_token": "[SEP]", "tokenizer_class": "TokenizersBackend", "unk_token": "[UNK]"}.gitattributes+1
README.mdAdded+79
code/__pycache__/byt5_adapter.cpython-312.pycAdded
code/__pycache__/metrics.cpython-312.pycAdded
code/__pycache__/modeling.cpython-312.pycAdded
code/__pycache__/native_adapter.cpython-312.pycAdded
code/__pycache__/tag.cpython-312.pycAdded
code/byt5_adapter.pyAdded+128
code/metrics.pyAdded+348
code/modeling.pyAdded+161
code/native_adapter.pyAdded+148
code/tag.pyAdded+116
config.jsonAdded+148
model.safetensorsAdded+3
qwen_tokenizer/chat_template.jinjaAdded+170
qwen_tokenizer/merges.txtAdded
qwen_tokenizer/tokenizer.jsonAdded+3
qwen_tokenizer/tokenizer_config.jsonAdded+305
qwen_tokenizer/vocab.jsonAdded
tokenizer.jsonAdded
tokenizer_config.jsonAdded+17