ngocdang83 commited on
Commit
b97e373
·
verified ·
1 Parent(s): f3dac7a

Add Hirashiba CT2 model options

Browse files
README.md CHANGED
@@ -1,34 +1,210 @@
1
- ---
2
- title: HachimiMT — Dịch Trung Việt
3
- emoji: 📜
4
- colorFrom: red
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 6.18.0
8
- app_file: app.py
9
- pinned: false
10
- short_description: Dịch truyện Trung → Việt
11
- ---
12
-
13
- # HachimiMT — Dịch Trung Việt
14
-
15
- Công cụ dịch truyện tiếng Trung sang tiếng Việt bằng các model MarianMT (CTranslate2 INT8):
16
-
17
- - [HachimiMT-60-zh-vi](https://huggingface.co/ngocdang83/HachimiMT-60-zh-vi) (mặc định)
18
- - [HachimiMT-30-zh-vi](https://huggingface.co/ngocdang83/HachimiMT-30-zh-vi) (nhẹ ~35 MB)
19
- - [MoxhiMT-60](https://huggingface.co/DanVP/MoxhiMT-60) · [MoxhiMT-30](https://huggingface.co/DanVP/MoxhiMT-30)
20
-
21
- ## Tính năng
22
-
23
- - Dịch văn bản trực tiếp + **đối chiếu song song** theo từng câu/đoạn, hoặc dịch file `.txt`.
24
- - **Chọn model** (HachimiMT / MoxhiMT, bản 60 hoặc 30) model tự tải từ Hugging Face khi
25
- chọn lần đầu (lazy), chạy CPU.
26
- - **Chuẩn hóa chữ Hán** phồn → giản trước khi dịch (model train trên giản thể).
27
- - **Tuỳ chọn chuẩn hóa xưng hô** (mục nâng cao, mặc định tắt) — ép xưng hô về Hán-Việt theo
28
- từ tường minh trong nguồn:
29
- - **Thân tộc**: `chị tỷ`, `anh trai ca ca`, `chị em → tỷ muội`… khi nguồn có 姐姐/哥哥/姐妹…
30
- - **Đại từ**: `cậu → ngươi`, `cô ấy nàng`, `tôi → ta` — chỉ áp ở văn cổ trang/tu tiên.
31
- - **Ổn định ngôi hiện đại**: chỉnh ngôi theo ngữ cảnh (thầy/em, mẹ/con…) cho truyện hiện đại.
32
-
33
- > Space chạy **CPU** (CTranslate2 INT8). Văn bản dài sẽ chậm hơn máy có GPU; chia **theo câu**
34
- > giúp giảm trôi tên riêng.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: HachimiMT — Dịch Trung Việt
3
+ emoji: 📜
4
+ colorFrom: red
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 6.18.0
8
+ app_file: app.py
9
+ pinned: false
10
+ short_description: Dịch truyện Trung → Việt
11
+ ---
12
+
13
+ # HachimiMT — Dịch Trung Việt
14
+
15
+ Công cụ dịch truyện tiếng Trung sang tiếng Việt, dùng các model MarianMT trên Hugging Face:
16
+
17
+ - [HachimiMT-60-zh-vi](https://huggingface.co/ngocdang83/HachimiMT-60-zh-vi)
18
+ - [HachimiMT-30-zh-vi](https://huggingface.co/ngocdang83/HachimiMT-30-zh-vi)
19
+ - [MoxhiMT-60](https://huggingface.co/DanVP/MoxhiMT-60)
20
+ - [MoxhiMT-30](https://huggingface.co/DanVP/MoxhiMT-30)
21
+ - [HirashibaMT-Medium](https://huggingface.co/Moleys/hirashiba-mt-medium) (CT2 mirror: [ngungodan/hirashiba-mt-medium-ct2](https://huggingface.co/ngungodan/hirashiba-mt-medium-ct2))
22
+ - [HirashibaMT-Tiny](https://huggingface.co/chi-vi/hirashiba-mt-tiny-zh-vi) (CT2 mirror: [ngungodan/hirashiba-mt-tiny-zh-vi-ct2](https://huggingface.co/ngungodan/hirashiba-mt-tiny-zh-vi-ct2))
23
+
24
+ > Có script sẵn cho **Windows** (`setup.bat` / `start.bat`) **macOS** (`setup_macos.sh` / `start_macos.sh`). Linux thể dùng gần giống macOS.
25
+
26
+ ## Tính năng
27
+
28
+ - Chọn model dịch (HachimiMT / MoxhiMT / HirashibaMT)
29
+ - Dịch văn bản trực tiếp với **đối chiếu song song** theo từng câu/đoạn
30
+ - Dịch file `.txt` tải bản dịch
31
+ - **CTranslate2 INT8** (mặc định) nhanh hơn nhiều so với PyTorch, hỗ trợ batch inference
32
+ - Tuỳ chọn hậu kỳ xưng hô:
33
+ - Hán-Việt hoá thân tộc/đại từ theo nguồn (`tỷ/muội/ca ca`, `ngươi/hắn/nàng/ta`)
34
+ - Ổn định ngôi xưng hiện đại V9 beta (`thầy/em`, `mẹ/con`, `anh/em`, phỏng vấn/nhà trường, giữ `ta/ngươi` ở đoạn tiên hiệp/độc thoại)
35
+ - **Tự nhận cấu hình máy**: CPU/GPU, số luồng, VRAM → tự chọn batch/thread phù hợp. Máy yếu hay mạnh đều chạy được, chỉ khác tốc độ.
36
+ - Tự nhận GPU NVIDIA khi có sẵn thư viện CUDA (qua torch CUDA); nếu không thì chạy CPU an toàn, không crash. Xem mục "Chạy bằng GPU NVIDIA".
37
+
38
+ ## Về model (tải từ Hugging Face)
39
+
40
+ Repo **không kèm sẵn model** (quá nặng cho git). Model tự tải từ Hugging Face vào thư mục `models/` **theo nhu cầu** (lazy):
41
+
42
+ - `setup.py` chỉ tải sẵn **1 model mặc định** (HachimiMT-60, bản CT2 ~57 MB) để dùng được ngay.
43
+ - Các model khác trong danh sách **chỉ tải khi bạn chọn dịch lần đầu** — nên thêm bao nhiêu model vào app cũng không làm setup nặng thêm.
44
+ - Trên giao diện, mỗi model có **badge trạng thái**: "✓ Đã tải — dịch được ngay" hoặc "⬇ Chưa có (~XX MB) — sẽ tự tải...". Khi bấm Dịch model chưa có, thanh tiến trình báo rõ "Đang tải … từ Hugging Face".
45
+ - Mỗi model tải **một lần duy nhất**; lần sau dùng lại từ `models/`, không tải lại.
46
+ - Đổi sang **engine PyTorch** thì cần cài thêm nhóm dependency PyTorch; app sẽ tự tải weights PyTorch (nặng hơn) ở lần dịch đầu với engine đó.
47
+ - Cần **internet** khi tải model lần đầu. Sau đó chạy offline được.
48
+
49
+ > Mẹo: muốn mang sang máy không có internet thì copy luôn thư mục `models/` đã tải sang — các model đã tải sẽ chạy ngay.
50
+
51
+ ### Thêm model mới vào app
52
+
53
+ Mở `src/translator.py`, thêm một mục vào dict `MODELS` (xem 2 model có sẵn làm mẫu). Lưu ý:
54
+ - `model_id`: đường dẫn repo HF (vd `DanVP/MoxhiMT-60`).
55
+ - `ct2_model_id`: chỉ cần khai khi bản CT2 nằm ở repo khác với model gốc.
56
+ - `ct2_subdir`: tên thư mục chứa bản CT2 trên repo — **mặc định `ct2-int8_float32`**; nếu repo dùng tên khác (vd `ct2-int8`) thì khai lại.
57
+ - `ct2_size_mb`: dung lượng bản CT2 (để badge hiện "~XX MB"); để trống cũng được.
58
+ - `use_marian_class`: `True` nếu config.json của model ghi `MarianMTModel`.
59
+
60
+ Không cần sửa gì thêm — model mới sẽ tự xuất hiện trong dropdown và lazy-download khi dùng.
61
+
62
+ ## Cài đặt (Windows)
63
+
64
+ **Cách nhanh:** chạy `setup.bat` rồi `start.bat`. Script sẽ cài các thư viện mặc định cho CTranslate2, tải model CT2 mặc định, và mở trình duyệt. Mặc định **không cài torch**.
65
+
66
+ **Cách thủ công** (nếu muốn dùng virtual environment — khuyến khích):
67
+
68
+ ```bat
69
+ cd D:\Projects\qt2
70
+ python -m venv .venv
71
+ .venv\Scripts\activate
72
+
73
+ :: 1) Cài phần mặc định: CTranslate2 + Gradio + tokenizer tooling
74
+ pip install -r requirements.txt
75
+
76
+ :: 2) Tải model lần đầu (~57 MB — chỉ model CT2 mặc định, một lần duy nhất)
77
+ cd src
78
+ python setup.py
79
+ ```
80
+
81
+ ### Chạy bằng GPU NVIDIA (nhanh hơn nhiều)
82
+
83
+ Engine mặc định là **CTranslate2** và chạy CPU. Để CTranslate2 dùng GPU NVIDIA, máy cần có **thư viện CUDA (cuBLAS/cuDNN)** — thường đi kèm khi bạn cài bản **torch CUDA**. Sau đó app tự nhận GPU, không cần đổi gì khác. GPU nhanh hơn CPU **nhiều lần** với văn bản dài (đo thực tế: gấp ~16× khi dịch hàng nghìn câu).
84
+
85
+ **Cách dễ nhất — nút ngay trong app (không cần terminal):** nếu máy có GPU NVIDIA mà app đang chạy CPU, giao diện sẽ hiện khối **"⚡ Phát hiện GPU… Cài torch để bật GPU"**. Bấm nút đó, app tự chọn đúng bản torch CUDA theo driver và cài (tải ~2–3 GB, cần ~5 GB ổ trống, một lần). App **tự kiểm tra** cả torch CUDA lẫn CTranslate2 CUDA sau khi cài; xong thì **tắt và mở lại app** (`stop.bat` rồi `start.bat`) là chạy GPU. Nếu thích cài tay thì xem lệnh bên dưới.
86
+
87
+ > ⚠️ **Lưu ý quan trọng (lỗi `cublas64_12.dll not found`):** CTranslate2 tự dò GPU NVIDIA **độc lập với torch**. Nếu máy **có GPU NVIDIA nhưng chưa cài torch CUDA**, CT2 sẽ cố dùng GPU rồi crash vì thiếu `cublas64_12.dll` (DLL này do torch CUDA cung cấp). Để tránh, app **tự động ép CT2 chạy CPU** khi không tìm thấy torch CUDA — nên mặc định bạn sẽ **không** gặp lỗi này, chỉ là chạy CPU.
88
+ >
89
+ > - Muốn GPU: cài **torch CUDA** (lệnh bên dưới) → app tự bật GPU.
90
+ > - Đã có cuBLAS sẵn (vd cài CUDA Toolkit riêng) và muốn ép CT2 dùng GPU dù không có torch: đặt biến môi trường `HACHIMIMT_FORCE_CT2_CUDA=1` trước khi chạy (tự chịu trách nhiệm nếu thiếu DLL).
91
+
92
+ Torch chỉ cần khi bạn muốn GPU cho CT2 (như trên) hoặc đổi sang backend **PyTorch** thử nghiệm. Backend PyTorch nặng hơn và thường chậm hơn CT2. Nếu muốn dùng PyTorch:
93
+
94
+ ```bat
95
+ :: CPU-only PyTorch
96
+ pip install torch --index-url https://download.pytorch.org/whl/cpu
97
+ pip install -r requirements-pytorch.txt
98
+
99
+ :: hoặc PyTorch CUDA cho NVIDIA, chọn đúng bản tại pytorch.org
100
+ pip install torch --index-url https://download.pytorch.org/whl/cu128
101
+ pip install -r requirements-pytorch.txt
102
+ ```
103
+
104
+ Lệnh chính xác cho từng cấu hình lấy tại <https://pytorch.org/get-started/locally/>.
105
+
106
+ ## Cài đặt (macOS)
107
+
108
+ Yêu cầu Python 3.10+. Trên macOS, app chạy mặc định bằng **CTranslate2 CPU**. CTranslate2 hiện không dùng Apple GPU/Metal/MPS, nên Mac M-series vẫn chạy bằng CPU.
109
+
110
+ ```bash
111
+ cd /path/to/qt2
112
+ chmod +x setup_macos.sh start_macos.sh stop_macos.sh
113
+ ./setup_macos.sh
114
+ ./start_macos.sh
115
+ ```
116
+
117
+ Script macOS tạo `.venv`, cài dependencies mặc định **không có torch**, tải model CT2 mặc định, rồi chạy Gradio tại `http://127.0.0.1:7860`.
118
+
119
+ Nếu muốn thử backend PyTorch trên macOS, cài thêm torch trong venv:
120
+
121
+ ```bash
122
+ source .venv/bin/activate
123
+ pip install torch
124
+ pip install -r requirements-pytorch.txt
125
+ ```
126
+
127
+ Lưu ý: backend PyTorch hiện chưa được tối ưu riêng cho MPS/Apple GPU trong app này.
128
+
129
+ ## Chạy
130
+
131
+ ```bat
132
+ start.bat
133
+ ```
134
+
135
+ hoặc thủ công:
136
+
137
+ ```bat
138
+ cd src
139
+ python app.py
140
+ ```
141
+
142
+ Mở trình duyệt tại `http://127.0.0.1:7860` (app chỉ chạy nội bộ trên máy, không mở ra mạng).
143
+
144
+ ## Gợi ý sử dụng
145
+
146
+ - **Engine CTranslate2** (mặc định): bản INT8 có sẵn trên HF, dịch batch nhiều chunk cùng lúc.
147
+ - **Engine PyTorch**: tùy chọn thử nghiệm, cần cài thêm `torch` và `requirements-pytorch.txt`; thường chậm hơn CT2.
148
+ - **HachimiMT-30**: nhẹ nhất (~35 MB), phù hợp thử nghiệm hoặc máy yếu.
149
+ - **HirashibaMT-Medium**: model tham khảo không phải do repo này train; CT2 INT8 nằm ở repo phụ `ngungodan/hirashiba-mt-medium-ct2`.
150
+ - **HirashibaMT-Tiny**: model tham khảo rất nhẹ; CT2 phải dùng bản `ct2-int8-keeppad` vì stock converter không giữ đúng `<pad>` decoder-start của Marian tiny. App đặt beam mặc định 1 để tránh lặp nhẹ ở beam cao.
151
+ - Chia **theo câu** giúp giảm drift tên riêng trên văn bản dài (theo khuyến nghị của tác giả model).
152
+ - Model được train trên **giản thể** (简体). App mặc định chuyển **phồn thể → giản thể** trước khi dịch; có thể đổi về "Giữ nguyên" trong phần cấu hình.
153
+ - `Chuẩn hóa xưng hô thân tộc` xử lý lỗi kiểu `chị em` ↔ `tỷ muội` khi nguồn có `姐妹/姐姐/哥哥...`.
154
+ - `Ổn định ngôi xưng hiện đại V9 (beta)` là option riêng, tắt mặc định; dùng khi chương hiện đại bị nhảy `ta/tôi`, `ngươi/cậu`, `thầy/em`, `mẹ/con`, `anh/em`. V9 ưu tiên quan hệ có tín hiệu rõ như phỏng vấn/nhà trường, giáo viên-học sinh, mẹ-con, anh-em, khoản vay; các đoạn tiên hiệp/độc thoại vẫn có thể giữ `ta/ngươi` để tránh sửa quá tay.
155
+ - Route hậu kỳ dùng quyết định cấp chương: route hiện đại do V9 sở hữu đại từ, route cổ trang do normalizer Hán-Việt sở hữu đại từ, route mixed/unknown sẽ guard để tránh tự sửa sai.
156
+ - File `.txt` đầu vào hỗ trợ UTF-8/UTF-8 BOM/GB18030/GBK/Big5; bản dịch xuất ra UTF-8.
157
+
158
+ ## Cấu hình tốc độ (tuỳ chọn)
159
+
160
+ App tự nhận CPU/GPU và chọn batch/thread theo máy. Có thể override bằng biến môi trường trước khi chạy:
161
+
162
+ ```bat
163
+ set HACHIMIMT_BATCH_SIZE=72
164
+ set HACHIMIMT_THREADS=12
165
+ set HACHIMIMT_TOKENIZE_WORKERS=16
166
+ set HACHIMIMT_TOKENIZE_JOB_SIZE=32
167
+ set HACHIMIMT_CT2_WINDOW_MULTIPLIER=4
168
+ set HACHIMIMT_CT2_BATCH_TYPE=tokens
169
+ set HACHIMIMT_INTER_THREADS=1
170
+ set HACHIMIMT_COMPUTE_TYPE=int8_float16
171
+ set HACHIMIMT_PROGRESS_SECONDS=0.5
172
+ start.bat
173
+ ```
174
+
175
+ - `HACHIMIMT_COMPUTE_TYPE`: mặc định GPU dùng `int8_float16`, CPU dùng `int8_float32`.
176
+ - `HACHIMIMT_BATCH_SIZE`: tăng nếu GPU còn rảnh VRAM; giảm nếu dịch lỗi/OOM.
177
+ - `HACHIMIMT_THREADS`: ngân sách thread CT2 tổng; khi có nhiều CT2 worker/replica, app tự chia `intra_threads` để tránh oversubscribe CPU.
178
+ - `HACHIMIMT_TOKENIZE_WORKERS`: tăng khi CPU còn rảnh và GPU chờ dữ liệu.
179
+ - `HACHIMIMT_TOKENIZE_JOB_SIZE`: số chunk mỗi tokenizer job; mặc định `32`.
180
+ - `HACHIMIMT_CT2_WINDOW_MULTIPLIER`: số batch đưa vào mỗi lần gọi CT2; mặc định `4`. Khi dùng multi-GPU + `batch_type=tokens`, app tự tăng window hiệu dụng để CT2 có đủ sub-batch chia việc cho các GPU.
181
+ - `HACHIMIMT_CT2_BATCH_TYPE`: mặc định `tokens`; đổi về `examples` nếu cần so sánh/fallback.
182
+ - `HACHIMIMT_INTER_THREADS`: mặc định `1`; chỉ tăng nếu benchmark chứng minh nhanh hơn.
183
+ - `HACHIMIMT_GPU_INDICES`: chọn GPU CT2, ví dụ `0`, `1`, hoặc `0,1`. Nếu không đặt, local PC mặc định dùng GPU `0`; Kaggle/Colab tự dùng toàn bộ GPU.
184
+ - `HACHIMIMT_AUTO_ALL_GPUS=1`: ép auto dùng toàn bộ GPU khi không đặt `HACHIMIMT_GPU_INDICES`; hữu ích khi chắc các GPU đồng cấu hình.
185
+ - `HACHIMIMT_PROGRESS_SECONDS`: giãn nhịp cập nhật UI progress; mặc định `0.5`.
186
+
187
+ ## Linux (gõ lệnh tay)
188
+
189
+ Các bước tương đương macOS:
190
+
191
+ ```bash
192
+ python3 -m venv .venv
193
+ source .venv/bin/activate
194
+ pip install -r requirements.txt
195
+ cd src && python setup.py # tải model lần đầu
196
+ python app.py # chạy app
197
+ ```
198
+
199
+ ## Benchmark file
200
+
201
+ ```bat
202
+ cd D:\Projects\qt2
203
+ python src\benchmark_file.py path\to\file.txt --model HachimiMT-60 --backend ct2 --beam 2 --chunk-mode sentence
204
+ ```
205
+
206
+ Mặc định benchmark cũng chuẩn hóa phồn thể → giản thể như UI. Muốn tắt:
207
+
208
+ ```bat
209
+ python src\benchmark_file.py path\to\file.txt --normalize none
210
+ ```
hachimimt-local.zip CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:1bd070a05e1cfb9cb45b78ab2caf13b04dacf52486856b321caa045b49021389
3
- size 89978
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a1c47e5e6973d9bd8f0277d928c27839f560bb1b14f0e8690ba562e8723b8c7
3
+ size 94764
requirements.txt CHANGED
@@ -1,4 +1,9 @@
 
 
 
 
1
  sentencepiece>=0.2.0
 
2
  gradio>=6.0.0,<7
3
  ctranslate2>=4.0.0
4
  huggingface_hub>=0.23.0
 
1
+ # LƯU Ý: KHÔNG cài torch ở file này.
2
+ # Engine mặc định CTranslate2 không cần torch/transformers.
3
+ # Chỉ cài nhóm PyTorch riêng nếu muốn dùng backend PyTorch thử nghiệm — xem README.
4
+
5
  sentencepiece>=0.2.0
6
+ tokenizers>=0.19.0
7
  gradio>=6.0.0,<7
8
  ctranslate2>=4.0.0
9
  huggingface_hub>=0.23.0
src/test_pronoun_harmonizer_v9.py CHANGED
@@ -673,4 +673,7 @@ check_rows(
673
  )
674
 
675
  print(f"KẾT QUẢ: {_pass} PASS / {_fail} FAIL")
676
- sys.exit(1 if _fail else 0)
 
 
 
 
673
  )
674
 
675
  print(f"KẾT QUẢ: {_pass} PASS / {_fail} FAIL")
676
+ if _fail:
677
+ raise AssertionError(f"pronoun_harmonizer_v9 suite failed: {_fail}")
678
+ if __name__ == "__main__":
679
+ sys.exit(0)
src/translator.py CHANGED
@@ -52,6 +52,9 @@ class ModelConfig:
52
  # Tên thư mục con chứa bản CT2 trên repo HF. Mặc định "ct2-int8_float32";
53
  # một số repo dùng tên khác (vd "ct2-int8"), khai lại ở đây cho từng model.
54
  ct2_subdir: str = "ct2-int8_float32"
 
 
 
55
 
56
 
57
  MODELS: dict[str, ModelConfig] = {
@@ -111,11 +114,42 @@ MODELS: dict[str, ModelConfig] = {
111
  "no_repeat_ngram_size": 2,
112
  "repetition_penalty": 1.2,
113
  },
114
- ct2_max_input_tokens=512,
 
 
115
  ct2_max_output_tokens=512,
116
  default_beam=1,
117
  ct2_size_mb=38,
118
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  }
120
 
121
  # Model tải sẵn khi chạy setup (dùng được ngay); các model khác lazy-download.
@@ -128,14 +162,20 @@ DEFAULT_CT2_SUBDIR = "ct2-int8_float32"
128
  def _ct2_download_patterns(config: ModelConfig) -> list[str]:
129
  return [
130
  "config.json",
 
131
  "source.spm",
132
  "target.spm",
 
133
  "vocab.json",
134
  "tokenizer_config.json",
135
  f"{config.ct2_subdir}/*",
136
  ]
137
 
138
 
 
 
 
 
139
  SourceTokenJobs = list[Future[list[list[str]]]]
140
 
141
 
@@ -176,14 +216,18 @@ def _ct2_translator_kwargs(
176
  inter_threads: int,
177
  gpu_indices: list[int] | None = None,
178
  ) -> tuple[dict[str, object], int, str | None]:
 
 
179
  kwargs: dict[str, object] = dict(
180
  device=device,
181
  compute_type=compute_type,
182
- intra_threads=intra_threads,
183
- inter_threads=max(1, int(inter_threads)),
184
  )
 
 
185
  if device != "cuda":
186
- return kwargs, max(1, int(inter_threads)), None
 
187
 
188
  if not gpu_indices:
189
  raise RuntimeError("Không có GPU CUDA khả dụng.")
@@ -199,7 +243,10 @@ def _ct2_translator_kwargs(
199
  kwargs["inter_threads"] = 1
200
 
201
  actual_inter_threads = int(kwargs["inter_threads"])
202
- return kwargs, len(selected) * actual_inter_threads, ",".join(str(i) for i in selected)
 
 
 
203
 
204
 
205
  @lru_cache(maxsize=1)
@@ -342,6 +389,100 @@ class CT2SentencePieceTokenizer:
342
  return decoded
343
 
344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  def model_local_dir(config: ModelConfig) -> Path:
346
  return MODELS_DIR / config.model_id.split("/")[-1]
347
 
@@ -356,7 +497,8 @@ def _pytorch_ready(path: Path) -> bool:
356
 
357
 
358
  def _tokenizer_ready(path: Path) -> bool:
359
- return (path / "source.spm").exists() or (path / "tokenizer_config.json").exists()
 
360
 
361
 
362
  def is_model_downloaded(model_key: str, backend: Backend | str = Backend.CT2) -> bool:
@@ -387,13 +529,15 @@ def ensure_model_files(config: ModelConfig, backend: Backend) -> Path:
387
  if _ct2_ready(local_dir, config.ct2_subdir) and _tokenizer_ready(local_dir):
388
  return local_dir
389
  patterns = _ct2_download_patterns(config)
 
390
  else:
391
  if _pytorch_ready(local_dir) and _tokenizer_ready(local_dir):
392
  return local_dir
393
  patterns = None
 
394
 
395
  snapshot_download(
396
- config.model_id,
397
  local_dir=str(local_dir),
398
  allow_patterns=patterns,
399
  )
@@ -433,6 +577,7 @@ class HachimiTranslator:
433
  batch_type = os.environ.get("HACHIMIMT_CT2_BATCH_TYPE", "tokens").strip().lower()
434
  self._ct2_batch_type = batch_type if batch_type in {"examples", "tokens"} else "tokens"
435
  self._ct2_compute_type: str | None = None
 
436
  self._ct2_actual_inter_threads = self._ct2_inter_threads
437
  self._ct2_worker_count = 1
438
  self._ct2_device_indices_label: str | None = None
@@ -543,6 +688,7 @@ class HachimiTranslator:
543
  msg += (
544
  f" · batch_type={self._ct2_batch_type}"
545
  f" · {window_part}"
 
546
  f" · inter={self._ct2_actual_inter_threads}"
547
  )
548
  if self._ct2_worker_count > 1:
@@ -563,6 +709,7 @@ class HachimiTranslator:
563
  self._tokenizer = None
564
  self._model_path = None
565
  self._ct2_compute_type = None
 
566
  self._ct2_actual_inter_threads = self._ct2_inter_threads
567
  self._ct2_worker_count = 1
568
  self._ct2_device_indices_label = None
@@ -611,7 +758,7 @@ class HachimiTranslator:
611
 
612
  def _load_ct2(self, config: ModelConfig) -> None:
613
  model_path = ensure_model_files(config, Backend.CT2)
614
- tokenizer = CT2SentencePieceTokenizer(model_path)
615
 
616
  env_compute_type = os.environ.get("HACHIMIMT_COMPUTE_TYPE", "").strip()
617
  ct2_device = "cuda" if self._profile.has_cuda else "cpu"
@@ -654,6 +801,7 @@ class HachimiTranslator:
654
  str(model_path / config.ct2_subdir), **kwargs
655
  )
656
  self._ct2_compute_type = compute_type
 
657
  self._ct2_actual_inter_threads = int(kwargs["inter_threads"])
658
  self._ct2_worker_count = worker_count
659
  self._ct2_device_indices_label = device_indices_label
 
52
  # Tên thư mục con chứa bản CT2 trên repo HF. Mặc định "ct2-int8_float32";
53
  # một số repo dùng tên khác (vd "ct2-int8"), khai lại ở đây cho từng model.
54
  ct2_subdir: str = "ct2-int8_float32"
55
+ # Nếu bản CT2 nằm ở repo khác với model gốc, khai riêng ở đây. PyTorch backend
56
+ # vẫn tải từ model_id, còn CT2 tải từ repo này vào cùng thư mục cache local.
57
+ ct2_model_id: str | None = None
58
 
59
 
60
  MODELS: dict[str, ModelConfig] = {
 
114
  "no_repeat_ngram_size": 2,
115
  "repetition_penalty": 1.2,
116
  },
117
+ # 30M model drifts/hallucinates on dense paragraph chunks. Keep the
118
+ # source cap short enough to split long entity-heavy paragraphs.
119
+ ct2_max_input_tokens=160,
120
  ct2_max_output_tokens=512,
121
  default_beam=1,
122
  ct2_size_mb=38,
123
  ),
124
+ "HirashibaMT-Medium": ModelConfig(
125
+ label="HirashibaMT-Medium",
126
+ model_id="Moleys/hirashiba-mt-medium",
127
+ use_marian_class=True,
128
+ generate_kwargs={
129
+ "max_new_tokens": 256,
130
+ },
131
+ ct2_max_input_tokens=128,
132
+ ct2_max_output_tokens=256,
133
+ default_beam=4,
134
+ ct2_size_mb=62,
135
+ ct2_model_id="ngungodan/hirashiba-mt-medium-ct2",
136
+ ),
137
+ "HirashibaMT-Tiny": ModelConfig(
138
+ label="HirashibaMT-Tiny",
139
+ model_id="chi-vi/hirashiba-mt-tiny-zh-vi",
140
+ use_marian_class=True,
141
+ generate_kwargs={
142
+ "max_length": 512,
143
+ },
144
+ # Tiny uses a 4-layer Marian model. Keep paragraph chunks short and use
145
+ # greedy/low-beam decoding; higher beams can introduce light duplicates.
146
+ ct2_max_input_tokens=160,
147
+ ct2_max_output_tokens=512,
148
+ default_beam=1,
149
+ ct2_size_mb=17,
150
+ ct2_subdir="ct2-int8-keeppad",
151
+ ct2_model_id="ngungodan/hirashiba-mt-tiny-zh-vi-ct2",
152
+ ),
153
  }
154
 
155
  # Model tải sẵn khi chạy setup (dùng được ngay); các model khác lazy-download.
 
162
  def _ct2_download_patterns(config: ModelConfig) -> list[str]:
163
  return [
164
  "config.json",
165
+ "generation_config.json",
166
  "source.spm",
167
  "target.spm",
168
+ "tokenizer.json",
169
  "vocab.json",
170
  "tokenizer_config.json",
171
  f"{config.ct2_subdir}/*",
172
  ]
173
 
174
 
175
+ def _ct2_repo_id(config: ModelConfig) -> str:
176
+ return config.ct2_model_id or config.model_id
177
+
178
+
179
  SourceTokenJobs = list[Future[list[list[str]]]]
180
 
181
 
 
216
  inter_threads: int,
217
  gpu_indices: list[int] | None = None,
218
  ) -> tuple[dict[str, object], int, str | None]:
219
+ actual_inter_threads = max(1, int(inter_threads))
220
+ requested_intra_threads = max(1, int(intra_threads))
221
  kwargs: dict[str, object] = dict(
222
  device=device,
223
  compute_type=compute_type,
224
+ inter_threads=actual_inter_threads,
 
225
  )
226
+ worker_count = actual_inter_threads
227
+ device_indices_label = None
228
  if device != "cuda":
229
+ kwargs["intra_threads"] = max(1, requested_intra_threads // worker_count)
230
+ return kwargs, worker_count, device_indices_label
231
 
232
  if not gpu_indices:
233
  raise RuntimeError("Không có GPU CUDA khả dụng.")
 
243
  kwargs["inter_threads"] = 1
244
 
245
  actual_inter_threads = int(kwargs["inter_threads"])
246
+ worker_count = len(selected) * actual_inter_threads
247
+ kwargs["intra_threads"] = max(1, requested_intra_threads // worker_count)
248
+ device_indices_label = ",".join(str(i) for i in selected)
249
+ return kwargs, worker_count, device_indices_label
250
 
251
 
252
  @lru_cache(maxsize=1)
 
389
  return decoded
390
 
391
 
392
+ class CT2FastTokenizer:
393
+ """Minimal tokenizer.json wrapper for CTranslate2 inference."""
394
+
395
+ def __init__(self, model_path: Path) -> None:
396
+ try:
397
+ from tokenizers import Tokenizer
398
+ except Exception as exc:
399
+ raise RuntimeError(
400
+ "Model này dùng tokenizer.json; cần cài package tokenizers."
401
+ ) from exc
402
+
403
+ self._tokenizer = Tokenizer.from_file(str(model_path / "tokenizer.json"))
404
+ self.pad_token_id = self._tokenizer.token_to_id("<pad>")
405
+ self._eos_token_id = self._tokenizer.token_to_id("</s>")
406
+
407
+ def _encode_one(
408
+ self,
409
+ text: str,
410
+ *,
411
+ truncation: bool = False,
412
+ max_length: int | None = None,
413
+ ) -> list[int]:
414
+ token_ids = list(self._tokenizer.encode(text).ids)
415
+ if truncation and max_length is not None and len(token_ids) > max_length:
416
+ token_ids = token_ids[:max_length]
417
+ if token_ids and self._eos_token_id is not None:
418
+ token_ids[-1] = self._eos_token_id
419
+ return token_ids
420
+
421
+ def __call__(
422
+ self,
423
+ text_or_texts: str | list[str],
424
+ *,
425
+ truncation: bool = False,
426
+ max_length: int | None = None,
427
+ padding: bool = False,
428
+ ) -> dict[str, list[int] | list[list[int]]]:
429
+ del padding
430
+ if isinstance(text_or_texts, str):
431
+ return {
432
+ "input_ids": self._encode_one(
433
+ text_or_texts,
434
+ truncation=truncation,
435
+ max_length=max_length,
436
+ )
437
+ }
438
+ return {
439
+ "input_ids": [
440
+ self._encode_one(text, truncation=truncation, max_length=max_length)
441
+ for text in text_or_texts
442
+ ]
443
+ }
444
+
445
+ def convert_ids_to_tokens(self, token_ids: list[int]) -> list[str]:
446
+ tokens: list[str] = []
447
+ for token_id in token_ids:
448
+ token = self._tokenizer.id_to_token(int(token_id))
449
+ if token is None:
450
+ raise ValueError(f"Token id không có trong vocab: {token_id}")
451
+ tokens.append(token)
452
+ return tokens
453
+
454
+ def convert_tokens_to_ids(self, tokens: list[str]) -> list[int]:
455
+ token_ids: list[int] = []
456
+ for token in tokens:
457
+ token_id = self._tokenizer.token_to_id(token)
458
+ if token_id is None:
459
+ raise ValueError(f"Token không có trong vocab: {token!r}")
460
+ token_ids.append(int(token_id))
461
+ return token_ids
462
+
463
+ def decode(self, token_ids: list[int], *, skip_special_tokens: bool = True) -> str:
464
+ return self.batch_decode([token_ids], skip_special_tokens=skip_special_tokens)[0]
465
+
466
+ def batch_decode(
467
+ self,
468
+ token_ids_batch: list[list[int]],
469
+ *,
470
+ skip_special_tokens: bool = True,
471
+ ) -> list[str]:
472
+ return [
473
+ self._tokenizer.decode(token_ids, skip_special_tokens=skip_special_tokens)
474
+ for token_ids in token_ids_batch
475
+ ]
476
+
477
+
478
+ def _load_ct2_tokenizer(model_path: Path):
479
+ if (model_path / "source.spm").exists() and (model_path / "target.spm").exists():
480
+ return CT2SentencePieceTokenizer(model_path)
481
+ if (model_path / "tokenizer.json").exists():
482
+ return CT2FastTokenizer(model_path)
483
+ raise RuntimeError("Không tìm thấy tokenizer CT2: cần source.spm/target.spm hoặc tokenizer.json.")
484
+
485
+
486
  def model_local_dir(config: ModelConfig) -> Path:
487
  return MODELS_DIR / config.model_id.split("/")[-1]
488
 
 
497
 
498
 
499
  def _tokenizer_ready(path: Path) -> bool:
500
+ has_sentencepiece = (path / "source.spm").exists() and (path / "target.spm").exists()
501
+ return has_sentencepiece or (path / "tokenizer.json").exists()
502
 
503
 
504
  def is_model_downloaded(model_key: str, backend: Backend | str = Backend.CT2) -> bool:
 
529
  if _ct2_ready(local_dir, config.ct2_subdir) and _tokenizer_ready(local_dir):
530
  return local_dir
531
  patterns = _ct2_download_patterns(config)
532
+ repo_id = _ct2_repo_id(config)
533
  else:
534
  if _pytorch_ready(local_dir) and _tokenizer_ready(local_dir):
535
  return local_dir
536
  patterns = None
537
+ repo_id = config.model_id
538
 
539
  snapshot_download(
540
+ repo_id,
541
  local_dir=str(local_dir),
542
  allow_patterns=patterns,
543
  )
 
577
  batch_type = os.environ.get("HACHIMIMT_CT2_BATCH_TYPE", "tokens").strip().lower()
578
  self._ct2_batch_type = batch_type if batch_type in {"examples", "tokens"} else "tokens"
579
  self._ct2_compute_type: str | None = None
580
+ self._ct2_actual_intra_threads = self._ct2_threads
581
  self._ct2_actual_inter_threads = self._ct2_inter_threads
582
  self._ct2_worker_count = 1
583
  self._ct2_device_indices_label: str | None = None
 
688
  msg += (
689
  f" · batch_type={self._ct2_batch_type}"
690
  f" · {window_part}"
691
+ f" · intra={self._ct2_actual_intra_threads}"
692
  f" · inter={self._ct2_actual_inter_threads}"
693
  )
694
  if self._ct2_worker_count > 1:
 
709
  self._tokenizer = None
710
  self._model_path = None
711
  self._ct2_compute_type = None
712
+ self._ct2_actual_intra_threads = self._ct2_threads
713
  self._ct2_actual_inter_threads = self._ct2_inter_threads
714
  self._ct2_worker_count = 1
715
  self._ct2_device_indices_label = None
 
758
 
759
  def _load_ct2(self, config: ModelConfig) -> None:
760
  model_path = ensure_model_files(config, Backend.CT2)
761
+ tokenizer = _load_ct2_tokenizer(model_path)
762
 
763
  env_compute_type = os.environ.get("HACHIMIMT_COMPUTE_TYPE", "").strip()
764
  ct2_device = "cuda" if self._profile.has_cuda else "cpu"
 
801
  str(model_path / config.ct2_subdir), **kwargs
802
  )
803
  self._ct2_compute_type = compute_type
804
+ self._ct2_actual_intra_threads = int(kwargs["intra_threads"])
805
  self._ct2_actual_inter_threads = int(kwargs["inter_threads"])
806
  self._ct2_worker_count = worker_count
807
  self._ct2_device_indices_label = device_indices_label