1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
|
# XLM-R language detection on macOS CPU
A native C CLI for `papluca/xlm-roberta-base-language-detection`, using the
liblangdet prediction API, ARM NEON kernels, and Apple Accelerate BLAS. It returns language
predictions for the checkpoint's 20 languages. No MLX, Metal, PyTorch, or Python
runtime is required for inference.
## Build and run
Use an Apple Silicon Mac with Xcode Command Line Tools installed
(`xcode-select --install` if needed). Python 3 is used for downloading the model
and running the optional reference checks, not for native inference.
```sh
python3 download_model.py
make -j8
./langdetect 'This is an English sentence.' 'Bugün hava çok güzel.'
printf '%s\n' 'Bonjour tout le monde.' 'これは日本語です。' | ./langdetect
```
Run these commands from this directory. The default model path is `./model`;
use `-d DIRECTORY` for a different path.
The Makefile currently targets macOS ARM64. The source includes Linux/OpenBLAS
and x86 paths, but Linux still needs build configuration and testing.
The model is loaded once per process. Each text argument, or each stdin line
when there are no text arguments, produces one JSON line in input order:
- `label` is the predicted language code.
- `score` is its softmax probability.
- `tokens` includes the leading `<s>` and trailing `</s>`.
- `truncated` indicates whether the input exceeded 512 tokens.
- `ms` measures tokenization and inference, excluding model loading and output.
`--all` includes a `scores` object with probabilities for every language.
`-t N` selects 1 to 16 CPU kernel threads; the default is the detected CPU count,
capped at 16. Accelerate manages its own BLAS threads. `-h` prints help.
Use `--` before text that begins with a hyphen. Diagnostics go to stderr.
## Inference
`liblangdet/langdet.c` loads and validates the four F32 classifier tensors and the
`id2label` mapping. `langdetect.c` handles only command-line input and JSON output. The encoder accepts F32 XLM-R weights with exact GeLU activation;
other model families and reduced-precision weights are not supported.
The encoder uses first-token pooling without L2 normalization.
The classifier applies a 768-to-768 linear layer, `tanh`, a 768-to-20 linear layer,
and stable softmax. Dropout is disabled during inference.
The native loader requires `config.json`, one `model.safetensors` file, and
`sentencepiece.bpe.model`. Sharded weights and alternate tokenizer files are not
supported. The safetensors and configuration readers both use `yyjson`.
The CPU encoder and tokenizer are in `liblangdet/`; the JSON parser is in
`deps/yyjson/`. Their license files are included. The build uses only local source
files and the macOS SDK, with no dependency on another repository.
Inputs are processed individually, not as a parallel batch. Long inputs are
truncated to 512 tokens while preserving the final `</s>`. Empty inputs are
accepted, but their predictions are not useful. The model always chooses among
its 20 labels; it has no unknown-language result, and scores are not a guarantee
of accuracy on ambiguous or unsupported text.
## CPU library
`make` builds both `langdetect` and the static archive `liblangdet.a`. Include
`liblangdet/langdet.h` to use the complete prediction API from C or C++:
- `langdet_open(model_dir, n_threads, err, errlen)` loads all inference resources.
Use `0` threads for automatic selection, or an explicit count from 1 to 16.
- `langdet_predict(detector, text, &result, err, errlen)` returns the best language,
its score, all 20 language scores, token count, and truncation flag.
- `langdet_free(detector)` releases the resources. Passing NULL is safe.
Opening returns NULL on failure. Prediction returns 0 on success or -1 on failure
and clears the result on failure. The optional error buffer receives a message;
model-file readers may also print diagnostics to stderr. Result label strings
remain valid until the detector is freed. Numeric scores are stored in the result
and do not change when another prediction runs.
Use one API call at a time per process, including when multiple detectors are
loaded. Internal CPU workers may cooperate on a prediction, but simultaneous calls
from application threads are not supported.
`examples/detect.c` is a complete application using only the public header:
```sh
cc -Iliblangdet examples/detect.c liblangdet.a -framework Accelerate -lm -pthread -o build/detect-example
./build/detect-example ./model 'This is an English sentence.' 'Bugün hava çok güzel.'
```
The archive includes its JSON parser. No separate parser library or private
inference headers are needed. The encoder, tokenizer, classifier, and thread
configuration are managed by the detector.
## Download
Python 3 and internet access are the only requirements. No Hugging Face token or
third-party Python packages are needed for this public checkpoint.
```sh
python3 download_model.py
# Alternatively, choose a destination:
python3 download_model.py ./models/language-detection
```
The default destination is `model/` beside the script. The download uses revision
`9865598389ca9d95637462f743f683b51d75b87b` and includes safetensors weights,
configuration, tokenizer files, and the model card. It excludes duplicate PyTorch
and TensorFlow weights. Allow about 1.13 GB of disk space for a fresh download.
The script checks each file's size and hash against Hugging Face metadata. Large
LFS files use SHA-256; ordinary files use Git blob SHA-1. Verified files are reused.
Downloads go to `.part` files and become final files only after verification.
Interrupted files restart on the next run; they do not resume from their previous
byte offset.
## Tests
With the model downloaded, install `uv` and have Python 3.10 through 3.13
available, then run:
```sh
make test
```
Use `make test MODEL=/path/to/model PYTHON=python3.12` to select a different
checkpoint directory or Python executable. The first run needs internet access
for the test-only Python packages. `uv` manages the pinned dependencies declared
in `tools/verify.py`; its cache stays in `.uv-cache/` inside this project.
The Transformers reference uses only the local model files and runs offline on
CPU in F32, with dropout disabled and eager attention.
The target builds and runs:
- `tools/test_api.c`: repeated predictions, score normalization, result ownership,
empty input, truncation, invalid arguments, error buffers, and detector lifecycle.
- `tools/test_safetensors.c`: single-file tensor loading, metadata, lookup, and
rejection of malformed shapes, offsets, and JSON headers.
- `tools/token_ids.c`: a test-only adapter that returns the native token IDs.
- `tools/verify.py`: exact token-ID comparison and all 20 language scores against
Transformers on 31 inputs. These cover the 20 languages, empty and whitespace
input, Unicode normalization, multiple lines, and lengths below, at, and above
the 128-token BLAS threshold and the 512-token limit. Scores must differ by no more than `1e-4` in absolute value,
and the predicted labels must match, with both one and four CPU kernel threads.
The Python checks also verify stdin behavior, invalid CLI arguments, NUL rejection,
and failures for missing or invalid configuration, weights, and tokenizer files.
They also check rejection of sharded weights, alternate tokenizer filenames, and
BERT model configuration.
No Python package is linked into or required by the native library.
## Verification status
- The executable builds and runs as native macOS ARM64, linked to Accelerate and
the system C library, with no GPU runtime.
- CLI smoke checks pass for one sample in each of the 20 supported languages,
normalized scores, stdin and argument input, empty and whitespace-only input,
single-thread inference, and 512-token truncation.
- Invalid thread counts, a missing model directory, and NUL bytes in stdin
produce errors.
- Standalone C and C++ applications link using only `langdet.h` and the static
archive. Prediction results, error returns, and detector lifecycle checks pass.
- The downloaded checkpoint files match Hugging Face's sizes and hashes.
- The reference comparisons pass on the 31 test inputs: token IDs match exactly,
labels agree, and probability differences stay below the `1e-4` tolerance.
These regression checks are not an accuracy benchmark or exhaustive tokenizer test.
|