neoneai-andrey commited on
Commit
cc725be
·
verified ·
1 Parent(s): 00ea462

Upload 9 files

Browse files
arm_tokenizer/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 NeoneAI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
arm_tokenizer/README.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - ru
5
+ - en
6
+ tags:
7
+ - tokenizer
8
+ - bpe
9
+ - byte-level
10
+ - russian
11
+ - english
12
+ - emoji
13
+ ---
14
+
15
+ # ARM Tokenizer
16
+
17
+ A byte-level BPE tokenizer built by **NeoneAI** for Russian, English, and emoji.
18
+
19
+ Part of the ARM research project.
20
+
21
+ ## Overview
22
+
23
+ - **Vocab size:** 65 536
24
+ - **Algorithm:** Byte-level BPE
25
+ - **Languages:** Russian + English
26
+ - **Emoji:** supported
27
+ - **Special tokens:** `<|endoftext|>`, `<|pad|>`, `<|user|>`, `<|assistant|>`, `<|system|>`, `<|bos|>`, `<|eos|>`
28
+ - **Tool:** Hugging Face Tokenizers
29
+
30
+ ## Why
31
+
32
+ Most open tokenizers (GPT-2, LLaMA, Mistral) are English-first.
33
+ ARM Tokenizer is built for **Russian + English + emoji**.
34
+
35
+ It compresses Russian text **3.3× better** than GPT-2
36
+ and beats Gemma-2 (256k vocab) with only a 65k vocabulary.
37
+
38
+ ## Benchmarks
39
+
40
+ All benchmarks use **1000 randomly sampled real-world texts**
41
+ (500 Russian + 500 English) with fixed seed (`42`).
42
+ Margin of error: **±1%**.
43
+
44
+ ### vs GPT-2 (50k)
45
+
46
+ | Metric | ARM | GPT-2 |
47
+ |---|---|---|
48
+ | Total tokens | **153 473** | 414 971 |
49
+ | Avg tok/char | **0.2965** | 0.8018 |
50
+ | Russian (500) | **111 803** | 371 960 |
51
+ | English (500) | **41 670** | 43 011 |
52
+ | Wins | **928** | 16 |
53
+ | Ties | 56 | |
54
+
55
+ **Result:** ARM is **63.02% ±1% more efficient** than GPT-2.
56
+ On Russian, ARM is **3.3× more efficient** than GPT-2.
57
+
58
+ ### vs Gemma-2 (256k)
59
+
60
+ | Metric | ARM | Gemma-2 |
61
+ |---|---|---|
62
+ | Total tokens | **153 473** | 167 105 |
63
+ | Avg tok/char | **0.2965** | 0.3198 |
64
+ | Russian (500) | **111 803** | 126 941 |
65
+ | English (500) | 41 670 | **40 164** |
66
+ | Wins | **791** | 108 |
67
+ | Ties | 101 | |
68
+
69
+ **Result:** ARM is **8.16% ±1% more efficient** than Gemma-2 overall,
70
+ and **12% ±1% more efficient on Russian**, with only a 65k vocabulary.
71
+
72
+ ## Reproducing the benchmarks
73
+
74
+ Two test scripts are included:
75
+
76
+ - **`test_gpt-2.py`** — compares ARM Tokenizer with GPT-2 Tokenizer
77
+ - **`test_gemma-2.py`** — compares ARM Tokenizer with Gemma-2 Tokenizer
78
+
79
+ Both scripts read from `sample/` folder:
80
+
81
+ - `sample/gutenberg_sample.txt` — 5000 English texts from Project Gutenberg
82
+ - `sample/ru_books_sample.txt` — 5000 Russian texts from RuHeritage-Corpus
83
+
84
+ ### Generate test data
85
+
86
+ ```bash
87
+ python build_test_data.py
arm_tokenizer/README.ru.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ---
3
+
4
+ ## README.ru.md (Русский)
5
+
6
+ ```markdown
7
+ ---
8
+ license: apache-2.0
9
+ language:
10
+ - ru
11
+ - en
12
+ tags:
13
+ - tokenizer
14
+ - bpe
15
+ - byte-level
16
+ - russian
17
+ - english
18
+ - emoji
19
+ ---
20
+
21
+ # ARM Tokenizer
22
+
23
+ Байтовый BPE-токенизатор от **NeoneAI** для русского, английского и эмодзи.
24
+
25
+ Часть исследовательского проекта ARM.
26
+
27
+ ## Обзор
28
+
29
+ - **Размер словаря:** 65 536
30
+ - **Алгоритм:** Byte-level BPE
31
+ - **Языки:** русский + английский
32
+ - **Эмодзи:** поддерживаются
33
+ - **Спецтокены:** `<|endoftext|>`, `<|pad|>`, `<|user|>`, `<|assistant|>`, `<|system|>`, `<|bos|>`, `<|eos|>`
34
+ - **Инструмент:** Hugging Face Tokenizers
35
+
36
+ ## Зачем
37
+
38
+ Большинство открытых токенизаторов (GPT-2, LLaMA, Mistral) заточены под английский.
39
+ ARM Tokenizer создан для **русского + английского + эмодзи**.
40
+
41
+ Он сжимает русский текст **в 3.3 раза лучше**, чем GPT-2,
42
+ и обходит Gemma-2 (256k словарь) при словаре всего 65k.
43
+
44
+ ## Результаты
45
+
46
+ Все тесты на **1000 случайных реальных текстов**
47
+ (500 русских + 500 английских) с фиксированным seed (`42`).
48
+ Погрешность: **±1%**.
49
+
50
+ ### vs GPT-2 (50k)
51
+
52
+ | Метрика | ARM | GPT-2 |
53
+ |---|---|---|
54
+ | Всего токенов | **153 473** | 414 971 |
55
+ | Средний tok/char | **0.2965** | 0.8018 |
56
+ | Русский (500) | **111 803** | 371 960 |
57
+ | Английский (500) | **41 670** | 43 011 |
58
+ | Побед | **928** | 16 |
59
+ | Ничьих | 56 | |
60
+
61
+ **Итог:** ARM на **63.02% ±1% эффективнее** GPT-2.
62
+ На русском ARM в **3.3 раза эффективнее** GPT-2.
63
+
64
+ ### vs Gemma-2 (256k)
65
+
66
+ | Метрика | ARM | Gemma-2 |
67
+ |---|---|---|
68
+ | Всего токенов | **153 473** | 167 105 |
69
+ | Средний tok/char | **0.2965** | 0.3198 |
70
+ | Русский (500) | **111 803** | 126 941 |
71
+ | Английский (500) | 41 670 | **40 164** |
72
+ | Побед | **791** | 108 |
73
+ | Ничьих | 101 | |
74
+
75
+ **Итог:** ARM на **8.16% ±1% эффективнее** Gemma-2 в общем,
76
+ и **на 12% ±1% эффективнее на русском**, при словаре всего 65k.
77
+
78
+ ## Воспроизведение тестов
79
+
80
+ В репозитории два скрипта:
81
+
82
+ - **`test_gpt-2.py`** — сравнивает ARM Tokenizer с GPT-2 Tokenizer
83
+ - **`test_gemma-2.py`** — сравнивает ARM Tokenizer с Gemma-2 Tokenizer
84
+
85
+ Оба скрипта читают из папки `sample/`:
86
+
87
+ - `sample/gutenberg_sample.txt` — 5000 английских текстов из Project Gutenberg
88
+ - `sample/ru_books_sample.txt` — 5000 русских текстов из RuHeritage-Corpus
89
+
90
+ ### Создать тестовые данные
91
+
92
+ ```bash
93
+ python build_test_data.py
arm_tokenizer/build_test_data.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ from pathlib import Path
4
+ from datasets import load_dataset
5
+
6
+ GUTENBERG = "D:/gutenberg_en.txt"
7
+ RU_BOOKS = "D:/ru_books.txt"
8
+
9
+ SCRIPT_DIR = Path(__file__).parent
10
+ OUT_DIR = SCRIPT_DIR / "sample"
11
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
12
+
13
+ OUT_EN = OUT_DIR / "gutenberg_sample.txt"
14
+ OUT_RU = OUT_DIR / "ru_books_sample.txt"
15
+
16
+ N_SAMPLES = 5000
17
+ MIN_LEN = 100
18
+ MAX_LEN = 2000
19
+ MAX_SCAN = 2_000_000
20
+
21
+
22
+ def download_gutenberg():
23
+ print("downloading gutenberg...")
24
+ ds = load_dataset("AdhyanshVerma/pg-en", split="train", streaming=True)
25
+ with open(GUTENBERG, "w", encoding="utf-8") as f:
26
+ n = 0
27
+ for s in ds:
28
+ t = s.get("text", "").strip()
29
+ if t:
30
+ f.write(t + "\n")
31
+ n += 1
32
+ if n >= 500_000:
33
+ break
34
+ print(f"gutenberg: {n} lines")
35
+
36
+
37
+ def download_ru_books():
38
+ print("downloading ru books...")
39
+ ds = load_dataset("maxzt/RuHeritage-Corpus", split="train", streaming=True)
40
+ with open(RU_BOOKS, "w", encoding="utf-8") as f:
41
+ n = 0
42
+ for s in ds:
43
+ t = s.get("text", "").strip()
44
+ if t:
45
+ f.write(t + "\n")
46
+ n += 1
47
+ if n >= 500_000:
48
+ break
49
+ print(f"ru books: {n} lines")
50
+
51
+
52
+ def make_sample(src_path, dst_path, n_samples, min_len, max_len):
53
+ if not os.path.exists(src_path):
54
+ print(f"missing: {src_path}")
55
+ return 0
56
+
57
+ candidates = []
58
+ total = 0
59
+
60
+ with open(src_path, "r", encoding="utf-8", errors="ignore") as f:
61
+ for line in f:
62
+ total += 1
63
+ line = line.strip()
64
+ if min_len <= len(line) <= max_len:
65
+ candidates.append(line)
66
+ if total >= MAX_SCAN:
67
+ break
68
+
69
+ if not candidates:
70
+ return 0
71
+
72
+ random.shuffle(candidates)
73
+ selected = candidates[:n_samples]
74
+
75
+ with open(dst_path, "w", encoding="utf-8") as f:
76
+ for line in selected:
77
+ f.write(line + "\n")
78
+
79
+ return len(selected)
80
+
81
+
82
+ if __name__ == "__main__":
83
+ random.seed(42)
84
+
85
+ if not os.path.exists(GUTENBERG):
86
+ download_gutenberg()
87
+
88
+ if not os.path.exists(RU_BOOKS):
89
+ download_ru_books()
90
+
91
+ en = make_sample(GUTENBERG, OUT_EN, N_SAMPLES, MIN_LEN, MAX_LEN)
92
+ ru = make_sample(RU_BOOKS, OUT_RU, N_SAMPLES, MIN_LEN, MAX_LEN)
93
+
94
+ print(f"en: {en}")
95
+ print(f"ru: {ru}")
arm_tokenizer/sample/gutenberg_sample.txt ADDED
The diff for this file is too large to render. See raw diff
 
arm_tokenizer/sample/ru_books_sample.txt ADDED
The diff for this file is too large to render. See raw diff
 
arm_tokenizer/test_gemma-2.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ from tokenizers import Tokenizer
4
+ from transformers import AutoTokenizer
5
+
6
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
7
+ SAMPLE_DIR = os.path.join(SCRIPT_DIR, "sample")
8
+
9
+ GUTENBERG = os.path.join(SAMPLE_DIR, "gutenberg_sample.txt")
10
+ RU_BOOKS = os.path.join(SAMPLE_DIR, "ru_books_sample.txt")
11
+
12
+ TOKENIZER_PATH = os.path.join(SCRIPT_DIR, "tokenizer.json")
13
+
14
+ N = 500
15
+ MIN_LEN = 100
16
+ MAX_LEN = 2000
17
+
18
+ arm = Tokenizer.from_file(TOKENIZER_PATH)
19
+ gemma = AutoTokenizer.from_pretrained("google/gemma-2-2b", trust_remote_code=True)
20
+
21
+
22
+ def read(path, n):
23
+ if not os.path.exists(path):
24
+ print(f"missing: {path}")
25
+ return []
26
+ s = []
27
+ with open(path, "r", encoding="utf-8") as f:
28
+ for line in f:
29
+ line = line.strip()
30
+ if MIN_LEN <= len(line) <= MAX_LEN:
31
+ s.append(line)
32
+ random.shuffle(s)
33
+ return s[:n]
34
+
35
+
36
+ random.seed(42)
37
+
38
+ en = read(GUTENBERG, N)
39
+ ru = read(RU_BOOKS, N)
40
+
41
+ samples = [(t, "en") for t in en] + [(t, "ru") for t in ru]
42
+
43
+ print(f"en: {len(en)}")
44
+ print(f"ru: {len(ru)}")
45
+ print(f"total: {len(samples)}")
46
+
47
+ total_arm = 0
48
+ total_gemma = 0
49
+ arm_wins = 0
50
+ gemma_wins = 0
51
+ ties = 0
52
+
53
+ by_lang = {
54
+ "en": {"arm": 0, "gemma": 0, "chars": 0, "n": 0},
55
+ "ru": {"arm": 0, "gemma": 0, "chars": 0, "n": 0},
56
+ }
57
+
58
+ for text, lang in samples:
59
+ a = len(arm.encode(text).ids)
60
+ g = len(gemma.encode(text))
61
+
62
+ total_arm += a
63
+ total_gemma += g
64
+
65
+ by_lang[lang]["arm"] += a
66
+ by_lang[lang]["gemma"] += g
67
+ by_lang[lang]["chars"] += len(text)
68
+ by_lang[lang]["n"] += 1
69
+
70
+ if a < g:
71
+ arm_wins += 1
72
+ elif a > g:
73
+ gemma_wins += 1
74
+ else:
75
+ ties += 1
76
+
77
+ print("=" * 60)
78
+ print(f"ARM: {total_arm:,}")
79
+ print(f"Gemma: {total_gemma:,}")
80
+
81
+ print("=" * 60)
82
+ for lang, d in by_lang.items():
83
+ if d["n"] == 0:
84
+ continue
85
+ ar = d["arm"] / d["chars"]
86
+ gr = d["gemma"] / d["chars"]
87
+ diff = d["arm"] - d["gemma"]
88
+ print(f"{lang}: ARM={d['arm']:,} Gemma={d['gemma']:,} tok/char ARM={ar:.4f} Gemma={gr:.4f} delta={diff:+,}")
89
+
90
+ print("=" * 60)
91
+ print(f"ARM wins: {arm_wins}")
92
+ print(f"Gemma wins: {gemma_wins}")
93
+ print(f"ties: {ties}")
94
+
95
+ diff = total_arm - total_gemma
96
+ pct = abs(diff) / max(total_arm, total_gemma) * 100
97
+
98
+ print("=" * 60)
99
+ if diff < 0:
100
+ print(f"WINNER: ARM by {pct:.2f}%")
101
+ elif diff > 0:
102
+ print(f"WINNER: Gemma by {pct:.2f}%")
103
+ else:
104
+ print("WINNER: TIE")
arm_tokenizer/test_gpt-2.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ from tokenizers import Tokenizer
4
+ from transformers import GPT2TokenizerFast
5
+
6
+ GUTENBERG = "sample/gutenberg_sample.txt"
7
+ RU_BOOKS = "sample/ru_books_sample.txt"
8
+
9
+ N = 500
10
+ MIN_LEN = 100
11
+ MAX_LEN = 2000
12
+
13
+ arm = Tokenizer.from_file("tokenizer.json")
14
+ gpt2 = GPT2TokenizerFast.from_pretrained("gpt2")
15
+
16
+
17
+ def read(path, n):
18
+ if not os.path.exists(path):
19
+ return []
20
+ s = []
21
+ with open(path, "r", encoding="utf-8") as f:
22
+ for line in f:
23
+ line = line.strip()
24
+ if MIN_LEN <= len(line) <= MAX_LEN:
25
+ s.append(line)
26
+ random.shuffle(s)
27
+ return s[:n]
28
+
29
+
30
+ random.seed(42)
31
+
32
+ en = read(GUTENBERG, N)
33
+ ru = read(RU_BOOKS, N)
34
+
35
+ samples = [(t, "en") for t in en] + [(t, "ru") for t in ru]
36
+
37
+ print(f"en: {len(en)}")
38
+ print(f"ru: {len(ru)}")
39
+ print(f"total: {len(samples)}")
40
+
41
+ total_arm = 0
42
+ total_gpt2 = 0
43
+ arm_wins = 0
44
+ gpt2_wins = 0
45
+ ties = 0
46
+
47
+ by_lang = {
48
+ "en": {"arm": 0, "gpt2": 0, "chars": 0, "n": 0},
49
+ "ru": {"arm": 0, "gpt2": 0, "chars": 0, "n": 0},
50
+ }
51
+
52
+ for text, lang in samples:
53
+ a = len(arm.encode(text).ids)
54
+ g = len(gpt2.encode(text))
55
+
56
+ total_arm += a
57
+ total_gpt2 += g
58
+
59
+ by_lang[lang]["arm"] += a
60
+ by_lang[lang]["gpt2"] += g
61
+ by_lang[lang]["chars"] += len(text)
62
+ by_lang[lang]["n"] += 1
63
+
64
+ if a < g:
65
+ arm_wins += 1
66
+ elif a > g:
67
+ gpt2_wins += 1
68
+ else:
69
+ ties += 1
70
+
71
+ print("=" * 60)
72
+ print(f"ARM-300: {total_arm:,}")
73
+ print(f"GPT-2: {total_gpt2:,}")
74
+
75
+ print("=" * 60)
76
+ for lang, d in by_lang.items():
77
+ if d["n"] == 0:
78
+ continue
79
+ ar = d["arm"] / d["chars"]
80
+ gr = d["gpt2"] / d["chars"]
81
+ diff = d["arm"] - d["gpt2"]
82
+ print(f"{lang}: ARM={d['arm']:,} GPT2={d['gpt2']:,} tok/char ARM={ar:.4f} GPT2={gr:.4f} delta={diff:+,}")
83
+
84
+ print("=" * 60)
85
+ print(f"ARM wins: {arm_wins}")
86
+ print(f"GPT2 wins: {gpt2_wins}")
87
+ print(f"ties: {ties}")
88
+
89
+ diff = total_arm - total_gpt2
90
+ pct = abs(diff) / max(total_arm, total_gpt2) * 100
91
+
92
+ print("=" * 60)
93
+ if diff < 0:
94
+ print(f"WINNER: ARM-300 by {pct:.2f}%")
95
+ elif diff > 0:
96
+ print(f"WINNER: GPT-2 by {pct:.2f}%")
97
+ else:
98
+ print("WINNER: TIE")
arm_tokenizer/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff