
Product
Socket Zero Introduces Automated Remediation PRs
Put vulnerability remediation on autopilot with automated security patches and intelligent dependency upgrades across your GitHub repositories.
crfsuite-compliant-rs
Advanced tools
A pure Rust implementation of CRFsuite — Conditional Random Fields for labeling sequential data.
This is a Rust port of Naoaki Okazaki's CRFsuite 0.12 chokkan/crfsuite, commit a2a1547.
Most users should probably first see if the existing original code works for them, unless they have reason otherwise. The original source may have newer features and it has had more love in terms of fixing bugs. In fact, we aim to replicate bugs if they are present, for the sake of reproducibility! (but then we might have added a few more in the process)
There are however cases when you might prefer this Rust version. We generally agree with this manifesto but more specifically:
But:
This blurb might be out of date. Go to this page for the latest information and further information about how we approach translation
# As a library
cargo add crfsuite-compliant-rs
# As a CLI tool
cargo install crfsuite-compliant-rs
Add to your Cargo.toml:
[dependencies]
crfsuite-compliant-rs = { version = "0.4", default-features = false }
(Use default-features = false to avoid pulling in clap when you only need the library.)
The default feature set includes the CLI. For library-only use, disable default features:
crfsuite-compliant-rs = { version = "0.4", default-features = false }
The optional sse-exp feature makes vecexp use the experimental CRFsuite USE_SSE polynomial approximation instead of the default platform exp implementation:
cargo install crfsuite-compliant-rs --features sse-exp
cargo test --features sse-exp
For library use:
crfsuite-compliant-rs = { version = "0.4", default-features = false, features = ["sse-exp"] }
use crfsuite_compliant_rs::crf1d::encode::Crf1dEncoder;
use crfsuite_compliant_rs::quark::Quark;
use crfsuite_compliant_rs::train;
use crfsuite_compliant_rs::types::{Attribute, Item, Instance};
// Build training data
let mut labels = Quark::new();
let mut attrs = Quark::new();
let mut instance = Instance::new();
instance.items.push(Item {
contents: vec![
Attribute { aid: attrs.get("w=the"), value: 1.0 },
Attribute { aid: attrs.get("pos=DT"), value: 1.0 },
],
});
instance.labels.push(labels.get("B-NP"));
instance.items.push(Item {
contents: vec![
Attribute { aid: attrs.get("w=cat"), value: 1.0 },
Attribute { aid: attrs.get("pos=NN"), value: 1.0 },
],
});
instance.labels.push(labels.get("I-NP"));
let instances = vec![instance];
// Initialize encoder and train
let mut encoder = Crf1dEncoder::new(
&instances,
labels.num(), // num_labels
attrs.num(), // num_attrs
0.0, // min_freq
false, false, // possible_states, possible_transitions
);
let mut log = train::stdout_logger();
let weights = train::lbfgs::train_lbfgs(
&mut encoder, &instances,
0.0, 1.0, // c1 (L1), c2 (L2)
100, 6, // max_iterations, num_memories
1e-5, 10, 1e-5, // epsilon, period, delta
"MoreThuente", 20, // linesearch, max_linesearch
&mut log,
);
// Save model
let label_strings: Vec<String> = (0..labels.num())
.map(|i| labels.to_string(i as i32).unwrap().to_string())
.collect();
let attr_strings: Vec<String> = (0..attrs.num())
.map(|i| attrs.to_string(i as i32).unwrap().to_string())
.collect();
let model_bytes = encoder.save_model(&weights, &label_strings, &attr_strings);
std::fs::write("model.bin", &model_bytes).unwrap();
use crfsuite_compliant_rs::model::ModelReader;
use crfsuite_compliant_rs::crf1d::tag::Crf1dTagger;
use crfsuite_compliant_rs::types::{Attribute, Item, Instance};
// Load model
let data = std::fs::read("model.bin").unwrap();
let model = ModelReader::open(&data).unwrap();
let mut tagger = Crf1dTagger::new(&model);
// Build an instance to tag
let mut inst = Instance::new();
inst.items.push(Item {
contents: vec![
Attribute { aid: model.to_aid("w=the").unwrap_or(-1), value: 1.0 },
Attribute { aid: model.to_aid("pos=DT").unwrap_or(-1), value: 1.0 },
],
});
inst.labels.push(0); // placeholder
inst.items.push(Item {
contents: vec![
Attribute { aid: model.to_aid("w=cat").unwrap_or(-1), value: 1.0 },
Attribute { aid: model.to_aid("pos=NN").unwrap_or(-1), value: 1.0 },
],
});
inst.labels.push(0);
// Tag
tagger.set(&inst);
let (labels, score) = tagger.viterbi();
for (t, label_id) in labels.iter().enumerate() {
let label = model.to_label(*label_id).unwrap_or("?");
println!("Item {}: {}", t, label);
}
# Train with L-BFGS (default)
crfsuite-compliant-rs learn -a lbfgs -m model.bin train.txt
# Train with other algorithms
crfsuite-compliant-rs learn -a l2sgd -m model.bin train.txt
crfsuite-compliant-rs learn -a ap -m model.bin train.txt # averaged perceptron
crfsuite-compliant-rs learn -a pa -m model.bin train.txt # passive-aggressive
crfsuite-compliant-rs learn -a arow -m model.bin train.txt
# Set algorithm parameters
crfsuite-compliant-rs learn -a lbfgs -p c2=0.1 -p max_iterations=200 -m model.bin train.txt
# Set deterministic shuffle seed for split and online-trainer shuffles
crfsuite-compliant-rs learn -a ap --seed=42 -m model.bin train.txt
# Basic tagging
crfsuite-compliant-rs tag -m model.bin test.txt
# With reference labels and evaluation
crfsuite-compliant-rs tag -m model.bin -t test.txt
# With probability scores
crfsuite-compliant-rs tag -m model.bin -p test.txt
# With marginal probabilities
crfsuite-compliant-rs tag -m model.bin -i test.txt # predicted label marginal
crfsuite-compliant-rs tag -m model.bin -l test.txt # all label marginals
crfsuite-compliant-rs dump model.bin
Input uses the IWA (Item With Attributes) format — tab-separated fields, one item per line, blank lines between sequences:
LABEL1 attr1:value1 attr2:value2 attr3
LABEL2 attr1:value1 attr4
LABEL1 attr2:value2 attr5:0.5
LABEL3 attr1:value1
attribute:value pairs (value defaults to 1.0 if omitted)\: and \\ escape colons and backslashes in attribute namesOriginal benchmark baseline: the vendored CRFsuite source is commit
a2a154772798 (git describe: 0.12-111-ga2a1547).
The previous README table used a synthetic fixture and single-run shell timings, so it is not a benchmark claim. For speed and RSS comparisons against original CRFSuite, use the reproducible benchmark harness instead:
python3 scripts/prepare_conll2000_iwa.py --out-dir .tmp/conll2000
cargo build --release
python3 scripts/bench_original_rss.py \
--train .tmp/conll2000/train.iwa \
--test .tmp/conll2000/test.iwa \
--runs 3 \
--algos lbfgs,ap,pa,arow,l2sgd \
--out-dir benchmarks/conll2000-original-rss
The harness prepares real CoNLL-2000 chunking data in CRFSuite IWA format, measures both binaries with /usr/bin/time -v, records max RSS, dataset hashes, commands, and output hashes, and compares tag/dump output on a C-trained model. It requires parseable /usr/bin/time -v elapsed/RSS output instead of falling back to Python wall-clock timing, and alternates C/Rust execution order across repeated runs to reduce cache/order bias. It refuses test_data/bench_10k.txt unless --allow-synthetic is passed.
Current local single-run CoNLL-2000 IWA measurements (211727 training items, 47377 test items) produced:
Latest rustification roll-up rerun: 2026-07-14 at Rust repo commit
cd957ff282f3a993ac68ad81d1016eaeb72c92c4, generated by
scripts/bench_original_rss.py into /tmp/pres_rustification_crf_bench using
the public NLTK CoNLL-2000 archive prepared by scripts/prepare_conll2000_iwa.py.
The raw rows are tracked in pres_rustification/benchmarks/crf.tsv; the
roll-up uses C/Rust wall-time speedup and Rust/C RSS ratio, reporting mean
speedup 1.22x and mean RSS ratio 0.95 across 10 paired train/tag/dump tasks.
Tag and dump parity checks were byte-identical after the harness's documented
normalization of the tag -t -q elapsed-time line.
Ratios are Rust divided by C; values above 1.00x mean Rust is slower or uses more memory.
| Task | C wall s | Rust wall s | Time ratio | C RSS MiB | Rust RSS MiB | RSS ratio |
|---|---|---|---|---|---|---|
| Train L-BFGS | 90.630 | 86.640 | 0.96x | 202.2 | 234.3 | 1.16x |
| Train AP | 31.520 | 22.710 | 0.72x | 153.4 | 149.6 | 0.98x |
| Train PA | 32.130 | 25.110 | 0.78x | 153.4 | 152.4 | 0.99x |
| Train AROW | 30.250 | 21.980 | 0.73x | 153.4 | 146.5 | 0.96x |
| Train L2SGD | 219.060 | 213.680 | 0.98x | 153.8 | 185.1 | 1.20x |
| Tag plain | 0.340 | 0.300 | 0.88x | 37.2 | 31.6 | 0.85x |
Tag -p -i | 0.400 | 0.380 | 0.95x | 37.5 | 31.6 | 0.84x |
Tag -l | 0.690 | 0.530 | 0.77x | 37.5 | 31.6 | 0.84x |
Tag -t -q | 0.340 | 0.310 | 0.91x | 37.2 | 31.6 | 0.85x |
| Dump | 0.240 | 0.190 | 0.79x | 36.9 | 30.9 | 0.84x |
Output parity was byte-identical for tag plain, -p -i, -l, and dump. For tag -t -q, the only difference was the self-reported elapsed-time line, which the harness normalizes because timing is measured externally.
src/
lib.rs Library root
types.rs Attribute, Item, Instance types
model.rs Binary model reader
model_writer.rs Binary model writer
dump.rs Human-readable model dump
quark.rs String-to-ID dictionary
vecmath.rs Vector math with exact SSE2 exp() polynomial
dataset.rs Dataset with shuffle
cqdb/ Constant Quark Database (model string lookup)
crf1d/
context.rs Forward-backward algorithm, Viterbi decoding
encode.rs Training encoder (gradient computation)
feature.rs Feature extraction
tag.rs Tagger (inference)
train/ Training algorithms (lbfgs, l2sgd, ap, pa, arow)
bin/crfsuite-compliant-rs/ CLI binary, shared CLI metadata, learn data loading/training, and C-compatible parameter metadata
tests/ Conformance tests vs original C implementation
# Run all tests
cargo test
# Lint all targets with warnings denied
cargo clippy --all-targets -- -D warnings
The conformance tests run automatically as part of cargo test. Tests that need
the original C executable skip themselves when the binary is not present at
crfsuite/frontend/.libs/crfsuite.
To run the full conformance suite, keep a local checkout of the original
CRFsuite source at crfsuite/ and build it first:
(cd crfsuite && ./autogen.sh && ./configure && make)
cargo test --test conformance
The test harness sets LD_LIBRARY_PATH to crfsuite/lib/crf/.libs for C
commands, so no shell-level environment variable is normally required. If you run
the C binary manually, use:
LD_LIBRARY_PATH=crfsuite/lib/crf/.libs crfsuite/frontend/.libs/crfsuite --help
The conformance suite verifies:
@weight, CRLF input, empty fields, and C-compatible atoi/atof behavior.learn -g and online trainer shuffles use a Rust ChaCha12Rng seeded with 0 by default; pass --seed=N to choose a different seed. Shuffled training is reproducible across supported Rust targets for the same crate versions. This intentionally differs from the original C code's platform C srand(0)/rand() stream; models that depend on shuffled instance order are not expected to be byte-identical to C solely because of RNG order.This is a port of CRFsuite by Naoaki Okazaki, licensed under the modified BSD license.
FAQs
Unknown package
We found that crfsuite-compliant-rs demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.

Product
Put vulnerability remediation on autopilot with automated security patches and intelligent dependency upgrades across your GitHub repositories.

Product
Socket Zero automates vulnerability remediation with upgrades and targeted patches, including fixes for 100% of known, patchable RubyGems CVEs.

Product
Explore Socket’s redesigned Alerts UI, multi-branch repository monitoring, and new tools for resolving findings, searching scans, and filtering security alerts.