turkish-diacritic-crf / crf_gpu.py
emircanerol's picture
Upload crf_gpu.py with huggingface_hub
3dfed56 verified
Raw History Blame Contribute Delete
23.1 kB
"""
GPU-accelerated CRF inference for Turkish diacritic restoration.
Converts a trained sklearn-crfsuite bidirectional CRF into a pure PyTorch
module. Feature weights are stored as frozen embedding lookup tables;
inference runs batched Viterbi on GPU.
Speed: ~500k–2M sentences/sec on RTX 4060 Ti (batch_size=512)
vs ~50k sentences/sec single-threaded sklearn-crfsuite
vs ~600k sentences/sec 16-thread multiprocessing
Saving / loading (safetensors)
------------------------------
import pickle
from crf_gpu import CRFGPUModel
# One-time conversion from sklearn
crf = pickle.load(open("crf_bidir.pkl", "rb"))
model = CRFGPUModel.from_sklearn(crf, "cuda")
model.save_pretrained("crf_gpu.safetensors") # labels stored in metadata
# Later inference
model = CRFGPUModel.from_pretrained("crf_gpu.safetensors", device="cuda")
preds = model.predict(["turkce cok guzel", "bugun hava guzel"])
# → ["türkçe çok güzel", "bugün hava güzel"]
"""
from __future__ import annotations
import time
from typing import Iterator
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
# ── Vocabulary (mirrors ldgc/vocab.py) ───────────────────────────────────────
from ldgc.vocab import VOCAB
_CHARS: list[str] = [c for c in VOCAB if c not in ("<PAD>", "<UNK>")]
_C2I: dict[str, int] = {c: i for i, c in enumerate(_CHARS)}
_N_CHARS: int = len(_CHARS) # 37
_BOS_IDX: int = _N_CHARS # 37 left boundary
_EOS_IDX: int = _N_CHARS + 1 # 38 right boundary
_UNK_IDX: int = _N_CHARS + 2 # 39 out-of-vocab char
_V: int = _UNK_IDX + 1 # 40 context-index vocab size
_VOWELS = frozenset("aeıioöuüâîû")
_DIAC_SRC = frozenset("acgiosu")
# Precomputed codepoint → char-index lookup (for numpy vectorisation).
# Covers BMP chars up to U+01FF; anything above maps to _UNK_IDX.
_CP_MAX = 0x200
_CHAR_LUT = np.full(_CP_MAX, _UNK_IDX, dtype=np.int32)
_VOWEL_LUT = np.zeros(_CP_MAX, dtype=np.float32)
_DIAC_LUT = np.zeros(_CP_MAX, dtype=np.float32)
_SPACE_IDX = _C2I.get(" ", -1)
for _c, _i in _C2I.items():
_o = ord(_c)
if _o < _CP_MAX:
_CHAR_LUT[_o] = _i
for _c in _VOWELS:
_o = ord(_c)
if _o < _CP_MAX:
_VOWEL_LUT[_o] = 1.0
for _c in _DIAC_SRC:
_o = ord(_c)
if _o < _CP_MAX:
_DIAC_LUT[_o] = 1.0
# ── Scalar feature indices ────────────────────────────────────────────────────
# Features whose contribution = weight × flag (boolean or one-hot).
# All stored in one (N_SCALAR, L) weight matrix; inference is a matmul.
F_IS_VOWEL = 0 # current char is a vowel
F_IS_DIAC = 1 # current char is in diac-source set (acgiosu)
F_P1_VOWEL = 2 # prev char is a vowel (-1:is_vowel)
F_N1_VOWEL = 3 # next char is a vowel (+1:is_vowel)
F_BOS = 4 # first char of sentence
F_EOS = 5 # last char of sentence
F_WP_START = 6 # word_pos == start (i==0 or prev==" ")
F_WP_MID = 7 # word_pos == mid
F_WP_END = 8 # word_pos == end (i==last or next==" ")
N_SCALAR = 9
class CRFGPUModel(nn.Module):
"""
Frozen PyTorch module for batched CRF inference on GPU.
Architecture
------------
Emission score at position i =
emb_char[c_i] + emb_p1[c_{i-1}] + emb_p2[c_{i-2}]
+ emb_n1[c_{i+1}] + emb_n2[c_{i+2}]
+ emb_bg_p1c[c_{i-1}*V + c_i]
+ emb_bg_p2p1[c_{i-2}*V + c_{i-1}]
+ emb_bg_cn1[c_i*V + c_{i+1}]
+ emb_bg_n1n2[c_{i+1}*V + c_{i+2}]
+ flags_i @ scalar_w # (N_SCALAR,) @ (N_SCALAR, L) → (L,)
+ bias
Decoding: batched log-space Viterbi, all sequences in one GPU pass.
"""
def __init__(self, n_labels: int) -> None:
super().__init__()
L, V = n_labels, _V
# Unigram context tables
self.emb_char = nn.Embedding(V, L)
self.emb_p1 = nn.Embedding(V, L)
self.emb_p2 = nn.Embedding(V, L)
self.emb_n1 = nn.Embedding(V, L)
self.emb_n2 = nn.Embedding(V, L)
# Bigram context tables (flat pair index = a*V + b)
self.emb_bg_p1c = nn.Embedding(V * V, L) # (c_{i-1}, c_i)
self.emb_bg_p2p1 = nn.Embedding(V * V, L) # (c_{i-2}, c_{i-1})
self.emb_bg_cn1 = nn.Embedding(V * V, L) # (c_i, c_{i+1})
self.emb_bg_n1n2 = nn.Embedding(V * V, L) # (c_{i+1}, c_{i+2})
# Scalar feature weights: flags (B,T,N_SCALAR) @ scalar_w → (B,T,L)
self.scalar_w = nn.Parameter(torch.zeros(N_SCALAR, L))
# Bias (always active)
self.bias = nn.Parameter(torch.zeros(L))
# CRF transition matrix: trans[i,j] = log-score from label i → j
self.trans = nn.Parameter(torch.zeros(L, L))
# Label metadata (set by from_sklearn)
self.labels: list[str] = []
self.label2i: dict[str, int] = {}
self._freeze()
def _freeze(self) -> None:
for p in self.parameters():
p.requires_grad_(False)
# ── Factory ───────────────────────────────────────────────────────────────
@classmethod
def from_sklearn(
cls,
crf,
device: torch.device | str | None = None,
) -> "CRFGPUModel":
"""
Convert a trained sklearn-crfsuite CRF to a GPU inference model.
Parses crf.state_features_ and crf.transition_features_ to populate
the embedding lookup tables. Unknown feature keys are silently ignored.
"""
labels = list(crf.classes_)
n_labels = len(labels)
label2i = {l: i for i, l in enumerate(labels)}
model = cls(n_labels)
model.labels = labels
model.label2i = label2i
for p in model.parameters():
p.data.zero_()
# ── State features ────────────────────────────────────────────────
for (feat, label), w in crf.state_features_.items():
li = label2i.get(label)
if li is None:
continue
w = float(w)
if feat == "bias": model.bias.data[li] += w
elif feat == "BOS": model.scalar_w.data[F_BOS, li] += w
elif feat == "EOS": model.scalar_w.data[F_EOS, li] += w
elif feat == "is_vowel": model.scalar_w.data[F_IS_VOWEL, li] += w
elif feat == "is_diac_src": model.scalar_w.data[F_IS_DIAC, li] += w
elif feat == "-1:is_vowel": model.scalar_w.data[F_P1_VOWEL, li] += w
elif feat == "+1:is_vowel": model.scalar_w.data[F_N1_VOWEL, li] += w
elif feat.startswith("word_pos:"):
idx = {"start": F_WP_START, "mid": F_WP_MID, "end": F_WP_END}.get(feat[9:])
if idx is not None:
model.scalar_w.data[idx, li] += w
elif feat.startswith("char:"):
ci = _C2I.get(feat[5:])
if ci is not None:
model.emb_char.weight.data[ci, li] += w
elif feat.startswith("-1:char:"):
model.emb_p1.weight.data[_C2I.get(feat[8:], _BOS_IDX), li] += w
elif feat.startswith("-2:char:"):
model.emb_p2.weight.data[_C2I.get(feat[8:], _BOS_IDX), li] += w
elif feat.startswith("+1:char:"):
model.emb_n1.weight.data[_C2I.get(feat[8:], _EOS_IDX), li] += w
elif feat.startswith("+2:char:"):
model.emb_n2.weight.data[_C2I.get(feat[8:], _EOS_IDX), li] += w
elif feat.startswith("-1+0:bigram:"):
bg = feat[12:]
if len(bg) == 2:
pi = _C2I.get(bg[0], _BOS_IDX)
ci = _C2I.get(bg[1], _UNK_IDX)
model.emb_bg_p1c.weight.data[pi * _V + ci, li] += w
elif feat.startswith("-2-1:bigram:"):
bg = feat[12:]
if len(bg) == 2:
p2 = _C2I.get(bg[0], _BOS_IDX)
p1 = _C2I.get(bg[1], _BOS_IDX)
model.emb_bg_p2p1.weight.data[p2 * _V + p1, li] += w
elif feat.startswith("0+1:bigram:"):
bg = feat[11:]
if len(bg) == 2:
ci = _C2I.get(bg[0], _UNK_IDX)
n1 = _C2I.get(bg[1], _EOS_IDX)
model.emb_bg_cn1.weight.data[ci * _V + n1, li] += w
elif feat.startswith("+1+2:bigram:"):
bg = feat[12:]
if len(bg) == 2:
n1 = _C2I.get(bg[0], _EOS_IDX)
n2 = _C2I.get(bg[1], _EOS_IDX)
model.emb_bg_n1n2.weight.data[n1 * _V + n2, li] += w
# ── Transition features ───────────────────────────────────────────
for (a, b), w in crf.transition_features_.items():
ai = label2i.get(a)
bi = label2i.get(b)
if ai is not None and bi is not None:
model.trans.data[ai, bi] += float(w)
if device is not None:
model = model.to(device)
return model
# ── Safetensors I/O ───────────────────────────────────────────────────────
def save_pretrained(self, path: str) -> None:
"""
Save model weights to a safetensors file.
Labels are stored as JSON inside the file's metadata — no separate file needed.
model.save_pretrained("crf_gpu.safetensors")
"""
import json
from safetensors.torch import save_file
metadata = {"labels": json.dumps(self.labels)}
save_file(self.state_dict(), path, metadata=metadata)
@classmethod
def from_pretrained(
cls,
path: str,
device: torch.device | str | None = None,
) -> "CRFGPUModel":
"""
Load a model previously saved with save_pretrained().
model = CRFGPUModel.from_pretrained("crf_gpu.safetensors", device="cuda")
"""
import json
from safetensors import safe_open
from safetensors.torch import load_file
with safe_open(path, framework="pt") as f:
labels = json.loads(f.metadata()["labels"])
state_dict = load_file(path, device=str(device) if device else "cpu")
model = cls(len(labels))
model.labels = labels
model.label2i = {l: i for i, l in enumerate(labels)}
model.load_state_dict(state_dict)
if device is not None:
model = model.to(device)
return model
# ── Batch encoding ────────────────────────────────────────────────────────
@staticmethod
def encode_batch(
sentences: list[str],
) -> tuple[Tensor, Tensor, Tensor]:
"""
Encode a batch of sentences to context index and flag tensors.
Uses numpy for fast codepoint lookups; output is CPU tensors
(caller transfers to GPU just before forward()).
Returns
-------
ctx : (B, T, 9) int64 [char,p1,p2,n1,n2,bg_p1c,bg_p2p1,bg_cn1,bg_n1n2]
flags : (B, T, N_SCALAR) float32 boolean/one-hot scalar features
lengths : (B,) int64
"""
B = len(sentences)
T = max((len(s) for s in sentences), default=1)
V = _V
ctx = np.zeros((B, T, 9), dtype=np.int64)
flags = np.zeros((B, T, N_SCALAR), dtype=np.float32)
lengths = np.zeros(B, dtype=np.int64)
for b, sent in enumerate(sentences):
n = len(sent)
if n == 0:
continue
lengths[b] = n
# Codepoint → char index via LUT
ords = np.array([ord(c) for c in sent], dtype=np.int32)
ords_safe = np.minimum(ords, _CP_MAX - 1)
idxs = _CHAR_LUT[ords_safe] # (n,) char indices
# ── Context windows ───────────────────────────────────────────
ci = idxs
p1 = np.empty(n, dtype=np.int64)
p1[0] = _BOS_IDX
p1[1:] = idxs[:-1]
p2 = np.full(n, _BOS_IDX, dtype=np.int64)
p2[2:] = idxs[:-2]
n1 = np.full(n, _EOS_IDX, dtype=np.int64)
n1[:-1] = idxs[1:]
n2 = np.full(n, _EOS_IDX, dtype=np.int64)
n2[:-2] = idxs[2:]
ctx[b, :n, 0] = ci
ctx[b, :n, 1] = p1
ctx[b, :n, 2] = p2
ctx[b, :n, 3] = n1
ctx[b, :n, 4] = n2
ctx[b, :n, 5] = p1 * V + ci # -1+0 bigram
ctx[b, :n, 6] = p2 * V + p1 # -2-1 bigram
ctx[b, :n, 7] = ci * V + n1 # 0+1 bigram
ctx[b, :n, 8] = n1 * V + n2 # +1+2 bigram
# ── Scalar flags ──────────────────────────────────────────────
is_vowel = _VOWEL_LUT[ords_safe]
is_diac = _DIAC_LUT[ords_safe]
ords_p1 = np.empty(n, dtype=np.int32)
ords_p1[0] = 0
ords_p1[1:] = ords_safe[:-1]
p1_vowel = _VOWEL_LUT[ords_p1]
p1_vowel[0] = 0.0 # BOS is not a vowel
ords_n1 = np.empty(n, dtype=np.int32)
ords_n1[-1] = 0
ords_n1[:-1] = ords_safe[1:]
n1_vowel = _VOWEL_LUT[ords_n1]
n1_vowel[-1] = 0.0 # EOS is not a vowel
bos = np.zeros(n, dtype=np.float32); bos[0] = 1.0
eos = np.zeros(n, dtype=np.float32); eos[-1] = 1.0
# word_pos: start if i==0 or prev==" ";
# end if i==last or next==" " (and not start);
# mid otherwise
is_space = (idxs == _SPACE_IDX)
is_start = np.zeros(n, dtype=bool)
is_start[0] = True
is_start[1:] |= is_space[:-1] # prev char was space
is_end = np.zeros(n, dtype=bool)
is_end[-1] = True
is_end[:-1] |= is_space[1:] # next char is space
wp_start = is_start.astype(np.float32)
wp_end = (is_end & ~is_start).astype(np.float32)
wp_mid = (~(is_start | is_end)).astype(np.float32)
flags[b, :n, F_IS_VOWEL] = is_vowel
flags[b, :n, F_IS_DIAC] = is_diac
flags[b, :n, F_P1_VOWEL] = p1_vowel
flags[b, :n, F_N1_VOWEL] = n1_vowel
flags[b, :n, F_BOS] = bos
flags[b, :n, F_EOS] = eos
flags[b, :n, F_WP_START] = wp_start
flags[b, :n, F_WP_MID] = wp_mid
flags[b, :n, F_WP_END] = wp_end
return (
torch.from_numpy(ctx),
torch.from_numpy(flags),
torch.from_numpy(lengths),
)
# ── Emission scoring ──────────────────────────────────────────────────────
def forward(self, ctx: Tensor, flags: Tensor) -> Tensor:
"""
Compute per-position emission scores.
ctx : (B, T, 9) int64
flags : (B, T, N_SCALAR) float32
returns (B, T, L) float32 emission log-scores
"""
em = (
self.emb_char(ctx[:, :, 0])
+ self.emb_p1(ctx[:, :, 1])
+ self.emb_p2(ctx[:, :, 2])
+ self.emb_n1(ctx[:, :, 3])
+ self.emb_n2(ctx[:, :, 4])
+ self.emb_bg_p1c(ctx[:, :, 5])
+ self.emb_bg_p2p1(ctx[:, :, 6])
+ self.emb_bg_cn1(ctx[:, :, 7])
+ self.emb_bg_n1n2(ctx[:, :, 8])
)
# (B, T, N_SCALAR) @ (N_SCALAR, L) → (B, T, L)
em = em + torch.matmul(flags.to(em.dtype), self.scalar_w)
return em + self.bias
# ── Batched Viterbi ───────────────────────────────────────────────────────
@torch.no_grad()
def _viterbi(self, emissions: Tensor, lengths: Tensor) -> Tensor:
"""
Batched log-space Viterbi decoding with variable-length masking.
emissions : (B, T, L) float32
lengths : (B,) int64
returns : (B, T) int64 label indices (0 outside valid range)
"""
B, T, L = emissions.shape
dev = emissions.device
score = emissions[:, 0].clone() # (B, L)
back = torch.zeros(B, T, L, dtype=torch.long, device=dev)
# For padding steps, back points to the same label (identity stay).
eye = torch.arange(L, device=dev).view(1, L).expand(B, L) # (B, L)
for t in range(1, T):
# cand[b, prev, curr] = score[b, prev] + trans[prev, curr]
cand = score.unsqueeze(2) + self.trans.unsqueeze(0) # (B, L, L)
best_score, best_prev = cand.max(dim=1) # (B, L)
valid = (t < lengths).view(B, 1)
score = torch.where(valid, best_score + emissions[:, t], score)
back[:, t] = torch.where(valid, best_prev, eye)
# Backtrack from final position
paths = torch.zeros(B, T, dtype=torch.long, device=dev)
cur = score.argmax(1) # (B,)
for t in range(T - 1, -1, -1):
paths[:, t] = cur
if t > 0:
cur = back[:, t].gather(1, cur.unsqueeze(1)).squeeze(1)
# Zero padding
mask = torch.arange(T, device=dev).unsqueeze(0) < lengths.unsqueeze(1)
paths.masked_fill_(~mask, 0)
return paths
# ── End-to-end prediction ─────────────────────────────────────────────────
@torch.no_grad()
def predict(
self,
sentences: list[str],
batch_size: int = 512,
) -> list[str]:
"""
Restore diacritics in a list of noisy Turkish sentences.
Parameters
----------
sentences : noisy input strings
batch_size : sentences per GPU batch (tune for VRAM)
Returns
-------
Restored strings in the same order as input.
"""
self.eval()
device = next(self.parameters()).device
labels = self.labels
out: list[str] = [""] * len(sentences)
for start in range(0, len(sentences), batch_size):
batch = sentences[start : start + batch_size]
ctx, flags, lengths = self.encode_batch(batch)
ctx = ctx.to(device)
flags = flags.to(device)
lengths = lengths.to(device)
em = self.forward(ctx, flags)
paths = self._viterbi(em, lengths)
paths_cpu = paths.cpu().numpy()
lens_cpu = lengths.cpu().numpy()
for i, (path, n) in enumerate(zip(paths_cpu, lens_cpu)):
out[start + i] = "".join(labels[j] for j in path[:n])
return out
# ── Throughput benchmark ──────────────────────────────────────────────────
def benchmark(
self,
n: int = 10_000,
avg_len: int = 50,
batch_size: int = 512,
) -> float:
"""Run a synthetic throughput test. Returns sentences / second."""
import random
chars = [c for c in _CHARS if c not in (" ", ".", ",", "!", "?")]
sents = [
" ".join(
"".join(random.choices(chars, k=random.randint(3, 12)))
for _ in range(avg_len // 8)
)
for _ in range(n)
]
t0 = time.perf_counter()
self.predict(sents, batch_size=batch_size)
return n / (time.perf_counter() - t0)
# ── Streaming iterator for very large corpora ─────────────────────────────────
def predict_stream(
model: CRFGPUModel,
sentences: Iterator[str],
batch_size: int = 512,
) -> Iterator[str]:
"""
Yield predictions one-by-one while processing in GPU batches.
Memory-efficient for datasets larger than RAM.
Usage:
with open("billion_sentences.txt") as f:
for restored in predict_stream(model, f, batch_size=512):
print(restored)
"""
buf: list[str] = []
for sent in sentences:
buf.append(sent.rstrip("\n"))
if len(buf) >= batch_size:
yield from model.predict(buf, batch_size=batch_size)
buf.clear()
if buf:
yield from model.predict(buf, batch_size=batch_size)
# ── CLI ───────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
import argparse, pickle, sys
p = argparse.ArgumentParser()
p.add_argument("--pkl", default="crf_bidir.pkl", help="sklearn model pickle")
p.add_argument("--save", default="crf_gpu.safetensors", help="output weights file")
p.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
p.add_argument("--bench", action="store_true", help="run throughput benchmark")
args = p.parse_args()
print(f"Loading {args.pkl} …")
crf = pickle.load(open(args.pkl, "rb"))
dev = torch.device(args.device)
model = CRFGPUModel.from_sklearn(crf, dev)
print(f" Labels: {len(model.labels)} Device: {dev}")
model.save_pretrained(args.save)
print(f"Saved GPU weights → {args.save}")
demos = ["turkce dogal dil isleme cok onemlidir",
"ruzgar bugun cok siddetli esiyor",
"guzel bir gun bugun"]
print("\nDemo:")
for d in demos:
print(f" {d} → {model.predict([d])[0]}")
if args.bench:
print("\nBenchmark …")
sps = model.benchmark()
print(f" {sps:,.0f} sentences/sec (batch=512, avg_len=50, device={dev})")