Token Classification
Transformers
Safetensors
Swedish
bert
grammaticality

Swedish grammaticality scorer

Xuehai Wang · KeTuTu/swedish-grammaticality-scoring

A rank-8 LoRA update to KB/bert-base-swedish-cased and a two-class token head estimate local error evidence. Length-normalized log-sum-exp at temperature 0.5 pools this evidence over all content subwords. A fitted logistic function converts it to one correctness score between 0 and 1. The length-sorted PyTorch encoder loads either the adapter or the merged native model and runs inference without importing Transformers or PEFT.

The native FP32 model has 124,101,890 parameters, including the OK/ERROR classifier. Training updated 296,450 parameters in the attention adapter and head. The weights here incorporate those updates. Training data

Scoring

For each content subword, let $m_i$ equal its ERROR logit minus its OK logit. For $N>0$ subwords the score uses

E=T(log⁡∑i=1Nemi/T−log⁡N),s=11+exp⁡(clip(aE+b,−700,700)). E = T\left(\log\sum_{i=1}^N e^{m_i/T}-\log N\right),\qquad s = \frac{1}{1+\exp(\mathrm{clip}(aE+b,-700,700))}.

Here $T=0.5$, $a=0.6535880249$ and $b=-1.019142231$. The same mapping retains the measured ranks on the official inputs. The implementation caps the exponent for finite output. Empty or whitespace-only input scores 0.0. The tokenizer splits long texts into nonoverlapping windows of 126 content subwords, with two boundary tokens added to each window. The scorer combines all content margins before computing the final score.

Command line

From the code repository, score one JSONL input record per line with id and text fields. The local native folder includes the model, tokenizer and calibration configuration.

pip install -r requirements-inference.txt
python predict.py --model ../hf_model --input test.jsonl --output scores.jsonl

After publication, use --model KeTuTu/swedish-grammaticality-scoring to load from the Hub. Code repository

Native Transformers example

Install the full requirements from the code repository for this CPU example. It computes the whole-text score across all tokenizer windows. The CLI additionally sorts windows by length and uses the configured CUDA precision.

from pathlib import Path
import json
import math
import torch
from transformers import AutoModelForTokenClassification, AutoTokenizer

path = Path("../hf_model")
cfg = json.loads((path / "scoring_config.json").read_text())
tokenizer = AutoTokenizer.from_pretrained(path, local_files_only=True)
model = AutoModelForTokenClassification.from_pretrained(path, local_files_only=True).eval()

@torch.inference_mode()
def score(text):
    batch = tokenizer(
        text, truncation=True, max_length=128, padding=True,
        return_overflowing_tokens=True, return_special_tokens_mask=True,
        return_tensors="pt",
    )
    batch.pop("overflow_to_sample_mapping")
    content = batch.pop("special_tokens_mask").eq(0) & batch["attention_mask"].bool()
    z = model(**batch).logits.float()
    margins = (z[..., 1] - z[..., 0])[content].double()
    if margins.numel() == 0:
        return 0.0
    t = cfg["temperature"]
    evidence = t * (torch.logsumexp(margins / t, 0) - math.log(margins.numel()))
    exponent = (cfg["scale_a"] * evidence + cfg["scale_b"]).clamp(-700, 700)
    return 1.0 / (1.0 + math.exp(exponent.item()))

print(score("Hon läser en bok."))

Evaluation and scope

On 120 organizer public texts, GPU Spearman was 0.825, ROC-AUC 0.978 and MAE 0.115. Grammatical variants of subordinate word order, older spelling and northern nonagreeing predicative adjectives remain difficult. A text score has no access to a speaker's region or a text's date. Benchmark · Variation tests

Credits

Xuehai Wang trained the adapter and constructed the paired derivative. KBLab at the National Library of Sweden released the cased Swedish BERT backbone under CC0. The trained model and the derived dataset are distributed under CC BY 4.0. KBLab model · Malmsten et al. · CC BY 4.0

Elena Volodina and Yousuf Ali Mohammed created DaLAJ-GED-SuperLim 2.0 at Språkbanken Text, University of Gothenburg. Historical treebank evaluations follow their separate CC BY-SA 4.0 licenses. Source and license · DaLAJ-GED paper

Downloads last month
22
Safetensors
Model size
0.1B params
Tensor type
F32
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Model tree for KeTuTu/swedish-grammaticality-scoring

Finetuned
(17)
this model

Dataset used to train KeTuTu/swedish-grammaticality-scoring

Paper for KeTuTu/swedish-grammaticality-scoring