/ Модель

Характеристики

Контекст
8 192 токена
Параметры
356 млн
Лицензия
Apache 2.0
Архитектура
modernbert · dense
Базовая модель
ModernCantoneseBert-Large
Библиотека
transformers
Опубликована
26 ноя 2026

ModernCantoneseBert-Large-Char

Заполнение пропусковТекст → текст3 профессии
44скачиваний за 30 дней0лайковвеса обновлены26 ноя 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

Символьная модель ModernBERT-large для предсказания пропущенных символов и дообучения на задачах разметки кантонского текста.

hon9kon9ize/ModernCantoneseBert-Large-Char — модель ModernBERT-large для анализа кантонского языка и письменного китайского. Она дообучена на предсказание замаскированных символов и использует символьный токенизатор: каждый китайский иероглиф кодируется отдельным токеном. Модель содержит около 355,6 млн параметров, имеет 28 слоёв, словарь из 12 160 токенов и архитектурный контекст до 8192 токенов; обучение проводилось на последовательностях длиной 2048 токенов.

Основная задача — восстановление пропущенных символов. Представления модели также можно использовать как основу для дообучения на разметку последовательностей, включая распознавание именованных сущностей, сегментацию слов и извлечение фрагментов текста. Символьная токенизация удобна для задач, где метки должны соответствовать отдельным иероглифам. Модель разработана hon9kon9ize на основе hon9kon9ize/ModernCantoneseBert-Large; лицензия — Apache-2.0.

Оценивались только метрики MLM, поэтому качество на downstream-задачах не установлено. Токенизатор удаляет пробелы и заменяет латинские слова и числа обобщёнными токенами, теряя их исходное содержание; поэтому модель не подходит для задач, где важны латинские слова или конкретные числа. Поведение на последовательностях длиннее 2048 токенов не оценивалось.

Сценарии применения

  • восстановление пропущенных иероглифов в кантонском тексте
  • извлечение контекстных представлений для кантонского NLP
  • дообучение на распознавание именованных сущностей с метками по символам
  • сегментация слов в кантонском тексте
  • извлечение фрагментов текста с символьной разметкой

Ограничения

Качество на downstream-задачах не оценивалось, а обработка контекста длиннее 2048 токенов не проверялась. Токенизатор удаляет пробелы и заменяет латинские слова и числа общими токенами, поэтому исходное содержание этих фрагментов теряется.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

ModernCantoneseBert-Large-Char

ModernCantoneseBert

This model is a character-level version of hon9kon9ize/ModernCantoneseBert-Large: the same ModernBERT-large body with a new one-token-per-character tokenizer, further pretrained (masked language modeling) for 5 epochs on ~637M tokens of Cantonese and written-Chinese text (~3.2B tokens seen in total). It achieves the following results on the evaluation set:

  • Loss: 0.9725
  • Accuracy: 0.7807
  • Perplexity: 2.64

These numbers are not comparable with ModernCantoneseBert-Large (loss 1.4511, accuracy 0.7052). That model predicts BPE tokens that are often whole words; this one predicts single characters, usually with the rest of the word visible, and is evaluated on a filtered version of the corpus.

Model description

ModernCantoneseBert is a BERT model specifically designed for Cantonese language understanding. It uses the ModernBERT architecture (alternating local/global attention, RoPE, up to 8192-token context) from HuggingFace Transformers and is trained with masked language modeling (MLM) on Cantonese text.

ModernCantoneseBert-Large uses byte-level BPE, whose merges follow frequency rather than word or entity boundaries (for example 佢喺 is one token and 保安局局長 splits as 保安 + 局局長). That makes token-aligned tasks such as NER and span extraction unreliable. This model replaces the tokenizer so that every Chinese character is exactly one token:

  • Character tokenizer: 12,160 tokens — 10,950 Han characters plus punctuation, symbols, kana and Greek, 5 class tokens and 256 reserved [unusedN] slots for task-specific tokens. Traditional and Simplified characters are both kept and never unified. Chinese numerals (二零二零, 一千, 廿) stay as characters.

  • Class tokens: non-Chinese material is normalised inside the tokenizer to one token per item:

    TokenReplacesExample
    [URL]URLshttps://example.com/a?b=1
    [EMAIL]e-mail addressessomeone@example.com
    [LATIN]one Latin-script word, including words containing digitsHSBC, COVID-19, A380
    [NUM]Arabic-digit numbers2019, 1,000.5, 10:30
    [FOREIGN]runs of other scripts (Hangul, Cyrillic, Arabic, Thai, ...)한국어
  • Normalisation: NFKC, so full-width forms fold to half-width (,!?()ABC123 → ,!?()ABC123). CJK-only punctuation (。、「」《》) is unchanged. Whitespace is dropped.

  • Embedding initialisation: the 28-layer body of ModernCantoneseBert-Large is kept. Each character's embedding is initialised as the mean of the BPE token embeddings its text mapped to; the tied MLM decoder and its bias are initialised the same way.

  • Continued pretraining: the whole model was then trained with MLM on packed 2048-token sequences.

Parameters356,718,464
Layers / hidden / heads28 / 1024 / 16
Vocabulary12,160 (character-level)
Training sequence length2048
Max position embeddings8192

Intended Uses & Limitations

Intended Uses

This model is intended for research and academic purposes in Cantonese natural language processing tasks, including:

  • Masked language modeling (fill-mask)
  • Feature extraction for downstream NLP tasks
  • Fine-tuning for token-aligned tasks: named entity recognition, word segmentation, span extraction and other sequence labeling, where one label per character is needed

Limitations

  • Research Purpose Only: This project is intended for research and academic use. It may not be suitable for production environments without further evaluation and fine-tuning.
  • No downstream evaluation yet: Only MLM loss and accuracy have been measured. The model has not been fine-tuned or benchmarked on NER, classification or any other task.
  • Class tokens hide the surface form: every Latin word is the same [LATIN] token and every number the same [NUM], so the model cannot tell HSBC from MTR or 2019 from 2020. It is not suitable for English or code-switched content where the Latin words matter. Recover the original string from character offsets when you need it.
  • Tokenization is lossy: decoding token ids does not reproduce the input (whitespace is dropped, class tokens replace their text).
  • Offsets of class tokens: the offset_mapping of a class token covers only the last character it replaced, not the whole word or number. Offsets of ordinary characters are exact.
  • Context Length: Training used 2048-token sequences; behaviour on longer inputs (up to the architectural 8192) has not been evaluated.

Training and Evaluation Data

The model was trained on a filtered subset of the ModernCantoneseBert-Large corpus: ~384k of the ~626k documents (311,221 packed 2048-token sequences, ~637M tokens per epoch; 20,000 sequences held out) from open source datasets and web-scraped content, including:

  • Cantonese filtered Common Crawl
  • Web scraped news and articles

Documents were dropped if more than 70% of their non-whitespace characters were Latin letters or digits, fewer than 15% were Han characters, or more than 10% were letters of other scripts. This kept 97% of the Han characters and raised their share of the text from 30% to 74%. Written Chinese in both Traditional and Simplified script is deliberately kept alongside Cantonese.

Due to respect for copyright, the training dataset will not be released.

Quick Start

Installation

pip install transformers torch

Trained and tested with Transformers 5.23.0. The tokenizer and config also load with Transformers 4.52; the model weights have not been run on 4.x.

Usage

Use the model for fill-mask tasks with the HuggingFace Transformers library:

from transformers import pipeline

mask_filler = pipeline(
    "fill-mask",
    model="hon9kon9ize/ModernCantoneseBert-Large-Char"
)

mask_filler("雞蛋六隻,糖呢就兩茶匙,仲有[MASK]橙皮添。")
mask_filler("香港特首係李家[MASK]。")   # -> 超 (0.96)

Each [MASK] stands for exactly one character (or one class token).

from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("hon9kon9ize/ModernCantoneseBert-Large-Char")
tok.tokenize("我今日去咗HSBC攞咗3,000蚊。")
# ['我', '今', '日', '去', '咗', '[LATIN]', '攞', '咗', '[NUM]', '蚊', '。']

Training procedure

Trained for 3 h 37 min on 4 × NVIDIA H100 80GB (DDP). The first 400 of the 45,505 optimizer steps ran on a single 12 GB H100 MIG slice with the same effective batch size before the run moved to the 4-GPU node.

Training hyperparameters

The following hyperparameters were used during training:

  • learning_rate: 5e-05
  • train_batch_size: 8 per GPU × 4 GPUs
  • eval_batch_size: 8
  • seed: 42
  • total_train_batch_size: 32 (65,536 tokens)
  • optimizer: AdamW (torch fused) with betas=(0.9,0.999), epsilon=1e-08, weight_decay=0.01
  • lr_scheduler_type: cosine
  • lr_scheduler_warmup_ratio: 0.05
  • num_epochs: 5.0
  • precision: bf16 mixed precision, torch.compile

Training results

Evaluation uses 500 held-out sequences with masking re-sampled each time, so repeated evaluations differ by about ±0.01.

Training LossEpochStepValidation LossAccuracy
1.31270.219820001.28890.7260
1.24240.439540001.21260.7396
1.17480.659360001.17280.7460
1.12030.879080001.14200.7514
1.12671.0988100001.11980.7550
1.10861.3185120001.10100.7577
1.09041.5383140001.08480.7602
1.07561.7580160001.08030.7611
1.07601.9778180001.05220.7653
1.06802.1976200001.04690.7667
1.03812.4173220001.03200.7699
1.00492.6371240001.03220.7698
0.99452.8568260001.02350.7705
1.04283.0766280001.00350.7743
0.99823.2963300001.00420.7743
0.99853.5161320000.99920.7757
0.98743.7359340000.99430.7758
1.00063.9556360000.98280.7784
1.02224.1754380000.97700.7799
0.99144.3951400000.97300.7807
0.99014.6149420000.97140.7798
0.96754.8346440000.98330.7781
-5.0455050.97250.7807

Framework versions

  • Transformers 5.23.0
  • Pytorch 2.8.0+cu128
  • Datasets 3.6.0
  • Tokenizers 0.23.3

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers · fill-mask

Можно запустить

Подбираем GPU…

Класс архитектуры
ModernBertForMaskedLM
Ревизия весов
e8db550

0 моделей