aboutsummaryrefslogtreecommitdiff
path: root/liblangdet/sentencepiece.c
diff options
context:
space:
mode:
authorOnur Gündüz <ogunduz@gmail.com>2026-09-29 14:38:02 +0200
committerOnur Gündüz <ogunduz@gmail.com>2026-09-29 14:38:02 +0200
commit91c6aa07597462705a7f30ee5b97e2c7943b5616 (patch)
treeb16f686279a1f1b0691a6c0d65a544084fcc1c1e /liblangdet/sentencepiece.c
parent6f98fc8cf3f7cc4b9d523d16492a07d3e2aea8c9 (diff)
downloadlangdet-91c6aa07597462705a7f30ee5b97e2c7943b5616.tar.gz
langdet-91c6aa07597462705a7f30ee5b97e2c7943b5616.zip
Remove unused checkpoint, tokenizer, and attention compatibility paths
Diffstat (limited to 'liblangdet/sentencepiece.c')
-rw-r--r--liblangdet/sentencepiece.c229
1 files changed, 33 insertions, 196 deletions
diff --git a/liblangdet/sentencepiece.c b/liblangdet/sentencepiece.c
index 33efab8..e60e913 100644
--- a/liblangdet/sentencepiece.c
+++ b/liblangdet/sentencepiece.c
@@ -10,7 +10,6 @@
#include "sentencepiece.h"
-#include <errno.h>
#include <float.h>
#include <limits.h>
#include <stdio.h>
@@ -22,9 +21,6 @@ enum {
SP_PIECE_NORMAL = 1,
SP_PIECE_UNKNOWN = 2,
SP_PIECE_CONTROL = 3,
- SP_PIECE_USER_DEFINED = 4,
- SP_PIECE_UNUSED = 5,
- SP_PIECE_BYTE = 6,
};
typedef struct {
@@ -96,11 +92,6 @@ static int map_get(const sp_entry_t *map, int cap, const char *key, int len) {
return -1;
}
-static int is_tokenizable_type(int type) {
- return type == SP_PIECE_NORMAL || type == SP_PIECE_USER_DEFINED || type == SP_PIECE_UNUSED ||
- type == SP_PIECE_BYTE;
-}
-
static int reserve_chars(char **buf, size_t *cap, size_t need) {
if (need <= *cap)
return 0;
@@ -302,12 +293,14 @@ static int parse_piece(tok_spm_t *tok, int idx, const unsigned char *data, size_
goto fail;
}
}
- if (!piece)
+ /* XLM-R stores <unk>, <s>, and </s> first, followed by normal pieces. */
+ static const char *const special[] = {"<unk>", "<s>", "</s>"};
+ int expected_type = idx == 0 ? SP_PIECE_UNKNOWN : idx < 3 ? SP_PIECE_CONTROL : SP_PIECE_NORMAL;
+ if (!piece || type != expected_type || (idx < 3 && strcmp(piece, special[idx]) != 0))
goto fail;
tok->id_to_piece[idx] = piece;
tok->scores[idx] = score;
- tok->types[idx] = (uint8_t)type;
- if (is_tokenizable_type(type) && tok->piece_lens[idx] > tok->max_piece_len)
+ if (type == SP_PIECE_NORMAL && tok->piece_lens[idx] > tok->max_piece_len)
tok->max_piece_len = tok->piece_lens[idx];
return 0;
fail:
@@ -315,7 +308,7 @@ fail:
return -1;
}
-static int parse_trainer(tok_spm_t *tok, const unsigned char *data, size_t len) {
+static int parse_trainer(const unsigned char *data, size_t len) {
const unsigned char *p = data, *end = data + len;
int model_type = SP_MODEL_UNIGRAM;
while (p < end) {
@@ -336,7 +329,6 @@ static int parse_trainer(tok_spm_t *tok, const unsigned char *data, size_t len)
model_type);
return -1;
}
- (void)tok;
return 0;
}
@@ -346,16 +338,12 @@ static int parse_normalizer(tok_spm_t *tok, const unsigned char *data, size_t le
int field = 0, wire = 0;
if (pb_read_key(&p, end, &field, &wire) != 0)
return -1;
+ /* NormalizerSpec fields 3..5 default to true: dummy prefix, whitespace
+ * merging, and escaping. XLM-R requires all three. */
if ((field == 3 || field == 4 || field == 5) && wire == 0) {
uint64_t v = 0;
- if (pb_read_varint(&p, end, &v) != 0)
+ if (pb_read_varint(&p, end, &v) != 0 || v != 1)
return -1;
- if (field == 3)
- tok->add_dummy_prefix = v != 0;
- else if (field == 4)
- tok->remove_extra_whitespaces = v != 0;
- else
- tok->escape_whitespaces = v != 0;
} else if (field == 2 && wire == 2) {
const unsigned char *blob = NULL;
size_t n = 0;
@@ -414,8 +402,7 @@ static int parse_model(tok_spm_t *tok, const unsigned char *data, size_t len) {
tok->id_to_piece = (char **)calloc((size_t)n_pieces, sizeof(*tok->id_to_piece));
tok->piece_lens = (uint16_t *)calloc((size_t)n_pieces, sizeof(*tok->piece_lens));
tok->scores = (float *)calloc((size_t)n_pieces, sizeof(*tok->scores));
- tok->types = (uint8_t *)calloc((size_t)n_pieces, sizeof(*tok->types));
- if (!tok->id_to_piece || !tok->piece_lens || !tok->scores || !tok->types)
+ if (!tok->id_to_piece || !tok->piece_lens || !tok->scores)
return -1;
const unsigned char *p = data, *end = data + len;
@@ -434,7 +421,7 @@ static int parse_model(tok_spm_t *tok, const unsigned char *data, size_t len) {
} else if (wire == 2 && field == 2) {
const unsigned char *msg = NULL;
size_t msg_len = 0;
- if (pb_read_len(&p, end, &msg, &msg_len) != 0 || parse_trainer(tok, msg, msg_len) != 0)
+ if (pb_read_len(&p, end, &msg, &msg_len) != 0 || parse_trainer(msg, msg_len) != 0)
return -1;
saw_trainer = 1;
} else if (wire == 2 && field == 3) {
@@ -451,85 +438,6 @@ static int parse_model(tok_spm_t *tok, const unsigned char *data, size_t len) {
return 0;
}
-static int raw_piece_id(const tok_spm_t *tok, const char *piece) {
- if (!tok || !piece)
- return -1;
- return map_get((const sp_entry_t *)tok->piece_map, tok->piece_map_cap, piece, (int)strlen(piece));
-}
-
-static int raw_to_model_id(const tok_spm_t *tok, int raw_id) {
- if (!tok || raw_id < 0 || raw_id >= tok->piece_count)
- return -1;
- if (tok->id_map == TOK_SPM_XLM_ROBERTA) {
- if (raw_id == 1)
- return 0; /* <s> */
- if (raw_id == 2)
- return 2; /* </s> */
- if (raw_id == 0)
- return 3; /* <unk> */
- return raw_id + 1;
- }
- return raw_id;
-}
-
-static int file_contains_xlm_roberta(const char *model_dir, const char *name) {
- char path[1024];
- int n = snprintf(path, sizeof(path), "%s/%s", model_dir, name);
- if (n < 0 || (size_t)n >= sizeof(path))
- return 0;
- FILE *f = fopen(path, "rb");
- if (!f)
- return 0;
- if (fseek(f, 0, SEEK_END) != 0) {
- fclose(f);
- return 0;
- }
- long sz = ftell(f);
- if (sz < 0 || (size_t)sz == SIZE_MAX || fseek(f, 0, SEEK_SET) != 0) {
- fclose(f);
- return 0;
- }
- char *buf = (char *)malloc((size_t)sz + 1);
- if (!buf) {
- fclose(f);
- return 0;
- }
- size_t got = fread(buf, 1, (size_t)sz, f);
- fclose(f);
- buf[got] = '\0';
- int yes = strstr(buf, "XLMRobertaTokenizer") != NULL ||
- strstr(buf, "XLMRobertaTokenizerFast") != NULL ||
- strstr(buf, "XLMRobertaModel") != NULL || strstr(buf, "xlm-roberta") != NULL;
- free(buf);
- return yes;
-}
-
-static int detect_xlm_roberta(const char *model_dir) {
- return file_contains_xlm_roberta(model_dir, "tokenizer_config.json") ||
- file_contains_xlm_roberta(model_dir, "config.json");
-}
-
-static int find_model_file(const char *model_dir, char path[1024]) {
- static const char *names[] = {
- "sentencepiece.bpe.model",
- "tokenizer.model",
- "spiece.model",
- };
- for (int i = 0; i < (int)(sizeof(names) / sizeof(names[0])); i++) {
- int n = snprintf(path, 1024, "%s/%s", model_dir, names[i]);
- if (n < 0 || n >= 1024)
- return -1;
- FILE *f = fopen(path, "rb");
- if (f) {
- fclose(f);
- return 0;
- }
- if (errno != ENOENT)
- return -1;
- }
- return -1;
-}
-
static int load_file(const char *path, unsigned char **out, size_t *out_len) {
FILE *f = fopen(path, "rb");
if (!f)
@@ -624,10 +532,7 @@ static int normalize_into(const tok_spm_t *tok, tok_spm_workspace_t *ws, const c
return -1;
size_t input_len = strlen(text);
const char space[] = "\xe2\x96\x81"; /* U+2581 */
- const char *space_s = tok->escape_whitespaces ? space : " ";
- size_t space_n = tok->escape_whitespaces ? 3 : 1;
int processing_non_ws = 0;
- int space_prepended = 0;
for (size_t off = 0; off < input_len;) {
norm_prefix_t r = normalize_prefix(tok, text, input_len, off);
@@ -636,22 +541,13 @@ static int normalize_into(const tok_spm_t *tok, tok_spm_workspace_t *ws, const c
if (c != ' ') {
if (!processing_non_ws) {
processing_non_ws = 1;
- if ((tok->add_dummy_prefix && !space_prepended) ||
- tok->remove_extra_whitespaces) {
- if (append_bytes(&ws->norm, &ws->norm_len, &ws->norm_cap, space_s, space_n) !=
- 0)
- return -1;
- space_prepended = 1;
- }
+ if (append_bytes(&ws->norm, &ws->norm_len, &ws->norm_cap, space, 3) != 0)
+ return -1;
}
if (append_bytes(&ws->norm, &ws->norm_len, &ws->norm_cap, &c, 1) != 0)
return -1;
} else {
processing_non_ws = 0;
- if (!tok->remove_extra_whitespaces) {
- if (append_bytes(&ws->norm, &ws->norm_len, &ws->norm_cap, space_s, space_n) != 0)
- return -1;
- }
}
}
off += r.consumed ? r.consumed : 1;
@@ -663,8 +559,8 @@ static int normalize_into(const tok_spm_t *tok, tok_spm_workspace_t *ws, const c
static double compute_unknown_score(const tok_spm_t *tok) {
float min_score = FLT_MAX;
- for (int i = 0; i < tok->piece_count; i++) {
- if (tok->types[i] == SP_PIECE_NORMAL && tok->scores[i] < min_score)
+ for (int i = 3; i < tok->piece_count; i++) {
+ if (tok->scores[i] < min_score)
min_score = tok->scores[i];
}
if (min_score == FLT_MAX)
@@ -680,8 +576,8 @@ static int segment(tok_spm_t const *tok, tok_spm_workspace_t *ws) {
reserve_ids(ws, (int)n + 1) != 0)
return -1;
for (size_t i = 0; i <= n; i++)
- ws->best[i] = (sp_best_t){tok->unk_id, -1, -DBL_MAX};
- ws->best[0] = (sp_best_t){tok->unk_id, 0, 0.0};
+ ws->best[i] = (sp_best_t){TOK_XLMR_UNK_ID, -1, -DBL_MAX};
+ ws->best[0] = (sp_best_t){TOK_XLMR_UNK_ID, 0, 0.0};
double unk_score = tok->unknown_score;
for (size_t off = 0; off < n;) {
@@ -697,13 +593,13 @@ static int segment(tok_spm_t const *tok, tok_spm_workspace_t *ws) {
for (size_t end = off + cp_len; end <= n && end - off <= (size_t)tok->max_piece_len;) {
int raw = map_get((const sp_entry_t *)tok->piece_map, tok->piece_map_cap, ws->norm + off,
(int)(end - off));
- if (raw >= 0 && is_tokenizable_type(tok->types[raw])) {
+ if (raw >= 0) {
if (end - off == cp_len)
single_cp_found = 1;
- double sc =
- cur.score + (tok->types[raw] == SP_PIECE_USER_DEFINED ? 0.0 : tok->scores[raw]);
+ double sc = cur.score + tok->scores[raw];
+ /* Normal XLM-R token IDs are the SentencePiece IDs plus one. */
if (sc > ws->best[end].score)
- ws->best[end] = (sp_best_t){raw_to_model_id(tok, raw), (int)off, sc};
+ ws->best[end] = (sp_best_t){raw + 1, (int)off, sc};
}
if (end == n)
break;
@@ -715,7 +611,7 @@ static int segment(tok_spm_t const *tok, tok_spm_workspace_t *ws) {
size_t end = off + cp_len;
double sc = cur.score + unk_score;
if (sc > ws->best[end].score)
- ws->best[end] = (sp_best_t){tok->unk_id, (int)off, sc};
+ ws->best[end] = (sp_best_t){TOK_XLMR_UNK_ID, (int)off, sc};
}
off += cp_len;
}
@@ -726,7 +622,7 @@ static int segment(tok_spm_t const *tok, tok_spm_workspace_t *ws) {
sp_best_t b = ws->best[off];
if (b.prev < 0 || b.prev >= (int)off)
return -1;
- int is_unk = b.id == tok->unk_id;
+ int is_unk = b.id == TOK_XLMR_UNK_ID;
if (!(prev_unk && is_unk)) {
if (out_n >= ws->ids_cap)
return -1;
@@ -747,8 +643,9 @@ tok_spm_t *tok_spm_load(const char *model_dir) {
if (!model_dir)
return NULL;
char path[1024];
- if (find_model_file(model_dir, path) != 0) {
- fprintf(stderr, "sentencepiece: model file not found under %s\n", model_dir);
+ int length = snprintf(path, sizeof(path), "%s/sentencepiece.bpe.model", model_dir);
+ if (length < 0 || (size_t)length >= sizeof(path)) {
+ fprintf(stderr, "sentencepiece: model path is too long\n");
return NULL;
}
unsigned char *data = NULL;
@@ -763,11 +660,8 @@ tok_spm_t *tok_spm_load(const char *model_dir) {
free(data);
return NULL;
}
- tok->add_dummy_prefix = 1;
- tok->remove_extra_whitespaces = 1;
- tok->escape_whitespaces = 1;
- tok->id_map = detect_xlm_roberta(model_dir) ? TOK_SPM_XLM_ROBERTA : TOK_SPM_IDENTITY;
- if (parse_model(tok, data, len) != 0) {
+ if (parse_model(tok, data, len) != 0 || tok->piece_count < 4 ||
+ tok->max_piece_len <= 0 || !tok->xcda || tok->xcda_count == 0) {
fprintf(stderr, "sentencepiece: malformed or unsupported model: %s\n", path);
free(data);
tok_spm_free(tok);
@@ -782,7 +676,7 @@ tok_spm_t *tok_spm_load(const char *model_dir) {
return NULL;
}
tok->piece_map_cap = cap;
- for (int i = 0; i < tok->piece_count; i++) {
+ for (int i = 3; i < tok->piece_count; i++) {
if (!tok->id_to_piece[i] || map_put((sp_entry_t *)tok->piece_map, cap, tok->id_to_piece[i],
tok->piece_lens[i], i) != 0) {
tok_spm_free(tok);
@@ -790,67 +684,10 @@ tok_spm_t *tok_spm_load(const char *model_dir) {
}
}
- tok->unk_id = raw_to_model_id(tok, raw_piece_id(tok, "<unk>"));
- tok->bos_id = raw_to_model_id(tok, raw_piece_id(tok, "<s>"));
- tok->eos_id = raw_to_model_id(tok, raw_piece_id(tok, "</s>"));
- tok->pad_id =
- tok->id_map == TOK_SPM_XLM_ROBERTA ? 1 : raw_to_model_id(tok, raw_piece_id(tok, "<pad>"));
- tok->mask_id = tok->id_map == TOK_SPM_XLM_ROBERTA
- ? tok->piece_count + 1
- : raw_to_model_id(tok, raw_piece_id(tok, "<mask>"));
- tok->vocab_size = tok->id_map == TOK_SPM_XLM_ROBERTA ? tok->piece_count + 2 : tok->piece_count;
tok->unknown_score = compute_unknown_score(tok);
- if (tok->unk_id < 0 || tok->max_piece_len <= 0) {
- fprintf(stderr, "sentencepiece: missing <unk> or normal pieces in %s\n", path);
- tok_spm_free(tok);
- return NULL;
- }
return tok;
}
-int tok_spm_token_id(const tok_spm_t *tok, const char *token) {
- if (!tok || !token)
- return -1;
- if (tok->id_map == TOK_SPM_XLM_ROBERTA) {
- if (!strcmp(token, "<s>"))
- return 0;
- if (!strcmp(token, "<pad>"))
- return 1;
- if (!strcmp(token, "</s>"))
- return 2;
- if (!strcmp(token, "<unk>"))
- return 3;
- if (!strcmp(token, "<mask>"))
- return tok->piece_count + 1;
- }
- return raw_to_model_id(tok, raw_piece_id(tok, token));
-}
-
-static int tok_spm_encode_into(const tok_spm_t *tok,
- tok_spm_workspace_t *ws,
- const char *text,
- int *out_ids,
- int out_cap,
- int *out_n_tokens) {
- if (out_n_tokens)
- *out_n_tokens = 0;
- if (!tok || !ws || !text)
- return -1;
- if (normalize_into(tok, ws, text) != 0)
- return -1;
- int n = segment(tok, ws);
- if (n < 0)
- return -1;
- if (out_n_tokens)
- *out_n_tokens = n;
- if (n == 0)
- return 0;
- if (!out_ids || out_cap < n)
- return -2;
- memcpy(out_ids, ws->ids, (size_t)n * sizeof(*out_ids));
- return 0;
-}
-
int *tok_spm_encode_with_workspace(const tok_spm_t *tok,
tok_spm_workspace_t *ws,
const char *text,
@@ -859,9 +696,10 @@ int *tok_spm_encode_with_workspace(const tok_spm_t *tok,
*out_n_tokens = -1;
if (!tok || !ws || !text)
return NULL;
- int n = 0;
- int rc = tok_spm_encode_into(tok, ws, text, NULL, 0, &n);
- if (rc < 0 && rc != -2)
+ if (normalize_into(tok, ws, text) != 0)
+ return NULL;
+ int n = segment(tok, ws);
+ if (n < 0)
return NULL;
if (out_n_tokens)
*out_n_tokens = n;
@@ -897,7 +735,6 @@ void tok_spm_free(tok_spm_t *tok) {
free(tok->id_to_piece);
free(tok->piece_lens);
free(tok->scores);
- free(tok->types);
free(tok->piece_map);
free(tok->xcda);
free(tok->prefix_replacements);