py-tokenizer-ansh 0.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. py_tokenizer_ansh-0.0.3/.github/workflows/build.yml +38 -0
  2. py_tokenizer_ansh-0.0.3/.github/workflows/publish.yml +32 -0
  3. py_tokenizer_ansh-0.0.3/.gitignore +47 -0
  4. py_tokenizer_ansh-0.0.3/CMakeLists.txt +64 -0
  5. py_tokenizer_ansh-0.0.3/MANIFEST.in +19 -0
  6. py_tokenizer_ansh-0.0.3/MIT +17 -0
  7. py_tokenizer_ansh-0.0.3/PKG-INFO +187 -0
  8. py_tokenizer_ansh-0.0.3/README.md +166 -0
  9. py_tokenizer_ansh-0.0.3/engine/basic_engine.cpp +33 -0
  10. py_tokenizer_ansh-0.0.3/engine/basic_engine.h +18 -0
  11. py_tokenizer_ansh-0.0.3/engine/engine.cpp +42 -0
  12. py_tokenizer_ansh-0.0.3/engine/engine.h +23 -0
  13. py_tokenizer_ansh-0.0.3/example/basic_engine_example.py +7 -0
  14. py_tokenizer_ansh-0.0.3/example/engine_example.py +10 -0
  15. py_tokenizer_ansh-0.0.3/file_info.json +12 -0
  16. py_tokenizer_ansh-0.0.3/include/tokenizer/freq_finder.h +29 -0
  17. py_tokenizer_ansh-0.0.3/include/tokenizer/json.hpp +25526 -0
  18. py_tokenizer_ansh-0.0.3/include/tokenizer/loader.h +27 -0
  19. py_tokenizer_ansh-0.0.3/include/tokenizer/merger.h +21 -0
  20. py_tokenizer_ansh-0.0.3/include/tokenizer/provider.h +14 -0
  21. py_tokenizer_ansh-0.0.3/include/tokenizer/splitter.h +36 -0
  22. py_tokenizer_ansh-0.0.3/main.cpp +8 -0
  23. py_tokenizer_ansh-0.0.3/pyproject.toml +57 -0
  24. py_tokenizer_ansh-0.0.3/src/binding.cpp +30 -0
  25. py_tokenizer_ansh-0.0.3/src/freq_finder.cpp +35 -0
  26. py_tokenizer_ansh-0.0.3/src/loader.cpp +64 -0
  27. py_tokenizer_ansh-0.0.3/src/merger.cpp +63 -0
  28. py_tokenizer_ansh-0.0.3/src/provider.cpp +81 -0
  29. py_tokenizer_ansh-0.0.3/src/splitter.cpp +162 -0
  30. py_tokenizer_ansh-0.0.3/tokenizer +0 -0
  31. py_tokenizer_ansh-0.0.3/vocabulary.json +70 -0
@@ -0,0 +1,38 @@
1
+ name: Build
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ pull_request:
8
+
9
+ jobs:
10
+ build:
11
+ strategy:
12
+ fail-fast: false # <-- Ye sabse zaroori hai, isse jobs achanak cancel nahi honge
13
+ matrix:
14
+ os: [ubuntu-latest, windows-latest, macos-latest]
15
+
16
+ runs-on: ${{ matrix.os }}
17
+
18
+ steps:
19
+ - uses: actions/checkout@v4
20
+
21
+ - uses: actions/setup-python@v5
22
+ with:
23
+ python-version: "3.12"
24
+
25
+ - name: Install dependencies
26
+ run: |
27
+ python -m pip install --upgrade pip
28
+ # C++ extension build karne ke liye zaroori tools add kiye
29
+ pip install build setuptools wheel pybind11 cmake
30
+
31
+ - name: Build wheel and sdist
32
+ run: python -m build
33
+
34
+ - name: Upload artifacts
35
+ uses: actions/upload-artifact@v4
36
+ with:
37
+ name: py_tokenizer-${{ matrix.os }}
38
+ path: dist/*
@@ -0,0 +1,32 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ build-and-publish:
9
+ runs-on: ubuntu-latest
10
+
11
+ # Note: permissions block hata diya hai kyunki hum API Token use kar rahe hain
12
+ steps:
13
+ - name: Checkout source
14
+ uses: actions/checkout@v4
15
+
16
+ - name: Set up Python
17
+ uses: actions/setup-python@v5
18
+ with:
19
+ python-version: "3.12"
20
+
21
+ - name: Install build dependencies
22
+ run: |
23
+ python -m pip install --upgrade pip
24
+ python -m pip install build scikit-build-core pybind11 cmake ninja
25
+
26
+ - name: Build package
27
+ run: python -m build --sdist
28
+
29
+ - name: Publish to PyPI
30
+ uses: pypa/gh-action-pypi-publish@release/v1
31
+ with:
32
+ password: ${{ secrets.PYPI_API_TOKEN }}
@@ -0,0 +1,47 @@
1
+ # Build directories
2
+ build/
3
+ cmake-build-*/
4
+
5
+ # CMake
6
+ CMakeCache.txt
7
+ CMakeFiles/
8
+ cmake_install.cmake
9
+ Makefile
10
+
11
+ # Compiled libraries
12
+ *.o
13
+ *.obj
14
+ *.a
15
+ *.so
16
+ *.dll
17
+ *.dylib
18
+ *.lib
19
+ *.exe
20
+
21
+ # Python
22
+ __pycache__/
23
+ *.py[cod]
24
+ *.pyo
25
+ *.pyd
26
+
27
+ # Distribution
28
+ dist/
29
+ *.egg-info/
30
+ .eggs/
31
+ wheelhouse/
32
+
33
+ # Virtual environments
34
+ .venv/
35
+ venv/
36
+ env/
37
+
38
+ # IDE
39
+ .vscode/
40
+ .idea/
41
+
42
+ # OS files
43
+ .DS_Store
44
+ Thumbs.db
45
+
46
+ # Logs
47
+ *.log
@@ -0,0 +1,64 @@
1
+ cmake_minimum_required(VERSION 3.15)
2
+
3
+ project(py_tokenizer LANGUAGES CXX)
4
+
5
+ set(CMAKE_CXX_STANDARD 17)
6
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
7
+ set(CMAKE_POSITION_INDEPENDENT_CODE ON)
8
+
9
+ include(FetchContent)
10
+
11
+ FetchContent_Declare(
12
+ pybind11
13
+ GIT_REPOSITORY https://github.com/pybind/pybind11.git
14
+ GIT_TAG v3.0.1
15
+ )
16
+
17
+ FetchContent_MakeAvailable(pybind11)
18
+
19
+ # ==========================
20
+ # Common library
21
+ # ==========================
22
+ add_library(tokenizer_core STATIC
23
+ src/provider.cpp
24
+ src/splitter.cpp
25
+ src/loader.cpp
26
+ src/merger.cpp
27
+ src/freq_finder.cpp
28
+ engine/engine.cpp
29
+ engine/basic_engine.cpp
30
+ )
31
+
32
+ target_include_directories(tokenizer_core
33
+ PUBLIC
34
+ ${CMAKE_SOURCE_DIR}
35
+ ${CMAKE_SOURCE_DIR}/include
36
+ )
37
+
38
+ target_compile_features(tokenizer_core PUBLIC cxx_std_17)
39
+
40
+ # ==========================
41
+ # Executable
42
+ # ==========================
43
+ add_executable(tokenizer
44
+ main.cpp
45
+ )
46
+
47
+ target_link_libraries(tokenizer
48
+ PRIVATE tokenizer_core
49
+ )
50
+
51
+ # ==========================
52
+ # Python module
53
+ # ==========================
54
+ pybind11_add_module(py_tokenizer
55
+ src/binding.cpp
56
+ )
57
+
58
+ target_link_libraries(py_tokenizer
59
+ PRIVATE tokenizer_core
60
+ )
61
+
62
+ install(TARGETS py_tokenizer
63
+ LIBRARY DESTINATION .
64
+ )
@@ -0,0 +1,19 @@
1
+ include README.md
2
+ include LICENSE
3
+ include CMakeLists.txt
4
+
5
+ recursive-include include *
6
+ recursive-include src *
7
+ recursive-include engine *
8
+
9
+ include vocabulary.json
10
+ include file_info.json
11
+
12
+ global-exclude *.pyc
13
+ global-exclude __pycache__
14
+ global-exclude *.o
15
+ global-exclude *.a
16
+ global-exclude *.so
17
+ global-exclude *.obj
18
+ global-exclude *.dll
19
+ global-exclude *.dylib
@@ -0,0 +1,17 @@
1
+ MIT License
2
+ Copyright (c) 2026 Ansh Raj
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+ The above copyright notice and this permission notice shall be included in all
10
+ copies or substantial portions of the Software.
11
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17
+ SOFTWARE.
@@ -0,0 +1,187 @@
1
+ Metadata-Version: 2.2
2
+ Name: py_tokenizer_ansh
3
+ Version: 0.0.3
4
+ Summary: High-performance Byte Pair Encoding (BPE) tokenizer written in modern C++ with Python bindings.
5
+ Keywords: tokenizer,bpe,byte-pair-encoding,nlp,llm,transformer,ai,machine-learning,cpp,pybind11,tokenization
6
+ Author-Email: Ansh Raj <anshraj0000000001@gmail.com>
7
+ License: MIT
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: C++
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Project-URL: Homepage, https://anshstudios.pages.dev/portfolio
16
+ Project-URL: Documentation, https://anshstudios.pages.dev/py_tokenizer
17
+ Project-URL: Repository, https://github.com/ANSH-ins/py_tokenizer
18
+ Project-URL: Issues, https://github.com/ANSH-ins/py_tokenizer/issues
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+
22
+ <div align="center">
23
+ <img src="https://res.cloudinary.com/dbmcddwjd/image/upload/v1783410838/file_00000000a2b471fba91bcdf2f3a398fb_t6gln5.png" alt="py_tokenizer Logo" width="250"/>
24
+ # py_tokenizer
25
+ **A High-Performance Byte Pair Encoding (BPE) Tokenizer for Modern AI Workflows.**
26
+ Version
27
+ Language
28
+ Python
29
+ Build
30
+ Platform
31
+ License
32
+ </div>
33
+ ## Introduction
34
+ py_tokenizer is a high-performance Byte Pair Encoding (BPE) tokenizer engineered entirely in modern C++17. It provides seamless Python bindings via pybind11, bridging the gap between low-level performance and high-level scripting convenience. Designed to be fast, memory-efficient, and highly modular, py_tokenizer is built to integrate effortlessly into advanced Artificial Intelligence and Machine Learning pipelines, specifically catering to Large Language Models (LLMs).
35
+ ## Key Features
36
+
37
+ | Feature | Description |
38
+ | :--- | :--- |
39
+ | **High Performance** | Optimized core written in C++17 for maximum throughput and minimal latency. |
40
+ | **Multi-threading** | Built-in support for concurrent processing to handle massive text corpora rapidly. |
41
+ | **Memory Efficient** | Strict resource management ensures low memory overhead during training and encoding. |
42
+ | **Python Integration** | Native Python bindings utilizing pybind11 for seamless ML framework integration. |
43
+ | **Modular Architecture** | Clean separation of concerns allows for easy extension and customization of tokenization rules. |
44
+ | **AI/LLM Ready** | Designed specifically for the stringent requirements of modern transformer architectures. |
45
+
46
+ ## Why py_tokenizer?
47
+ Tokenization is the critical first step in natural language processing. While many tokenizers exist, py_tokenizer differentiates itself by focusing on raw compute efficiency without sacrificing usability. It is developed natively on mobile/embedded environments (Android via Termux), which enforces strict memory constraints and results in a highly optimized, lean codebase. Whether you are deploying on resource-constrained devices or scaling up on Linux servers, py_tokenizer delivers consistent, robust performance.
48
+ ## Project Architecture
49
+ The project follows a standard wrapper architecture:
50
+ 1. **Core Library (C++)**: Handles all intensive computations, string manipulations, frequency counting, and merging operations.
51
+ 2. **Binding Layer (pybind11)**: Exposes the C++ classes and methods to Python, handling memory safety and type conversions natively.
52
+ 3. **Python API**: Provides a Pythonic interface, allowing users to import the tokenizer just like any native Python module.
53
+ ## Installation & Building from Source
54
+ Currently, py_tokenizer supports Linux and Android (via Termux). Windows and macOS support are planned for future releases.
55
+ ### Prerequisites
56
+ * CMake (Version 3.10 or higher)
57
+ * C++ Compiler (GCC or Clang supporting C++17)
58
+ * Python 3.x
59
+ * pybind11 headers
60
+ ### Build Instructions
61
+ 1. Clone the repository:
62
+ ```bash
63
+ git clone [https://github.com/ANSH-ins/py_tokenizer.git](https://github.com/ANSH-ins/py_tokenizer.git)
64
+ cd py_tokenizer
65
+ ```
66
+ 2. Create a build directory and compile:
67
+ ```bash
68
+ mkdir build
69
+ cd build
70
+ cmake ..
71
+ make -j$(nproc)
72
+ ```
73
+ 3. Install the Python module:
74
+ ```bash
75
+ python setup.py install
76
+ ```
77
+ ## Usage Examples
78
+ ### Python Integration
79
+ ```python
80
+ import py_tokenizer
81
+ # Initialize the BPE Tokenizer
82
+ tokenizer = py_tokenizer.BPETokenizer()
83
+ # Train the tokenizer on your dataset
84
+ tokenizer.train(
85
+ file_path="dataset.txt",
86
+ vocab_size=10000,
87
+ special_tokens=["<PAD>", "<UNK>", "<BOS>", "<EOS>"]
88
+ )
89
+ # Encode text to tokens
90
+ text = "Artificial intelligence relies on efficient tokenization."
91
+ encoded_ids = tokenizer.encode(text)
92
+ print("Encoded IDs:", encoded_ids)
93
+ # Decode tokens back to text
94
+ decoded_text = tokenizer.decode(encoded_ids)
95
+ print("Decoded Text:", decoded_text)
96
+ ```
97
+ ### C++ Integration
98
+ ```cpp
99
+ #include "py_tokenizer/bpe_tokenizer.hpp"
100
+ #include <iostream>
101
+ #include <vector>
102
+ #include <string>
103
+ int main() {
104
+ // Initialize
105
+ py_tokenizer::BPETokenizer tokenizer;
106
+ // Train
107
+ std::vector<std::string> special_tokens = {"<PAD>", "<UNK>", "<BOS>", "<EOS>"};
108
+ tokenizer.train("dataset.txt", 10000, special_tokens);
109
+ // Encode
110
+ std::string text = "Artificial intelligence relies on efficient tokenization.";
111
+ std::vector<int> encoded_ids = tokenizer.encode(text);
112
+ // Decode
113
+ std::string decoded_text = tokenizer.decode(encoded_ids);
114
+ std::cout << "Decoded: " << decoded_text << std::endl;
115
+ return 0;
116
+ }
117
+ ```
118
+ ## Constructor Arguments
119
+ When initializing or training the BPETokenizer, you can configure its behavior using the following parameters:
120
+
121
+ | Argument | Type | Default | Description |
122
+ | :--- | :--- | :--- | :--- |
123
+ | vocab_size | int | Required | The target size of the vocabulary to be generated. |
124
+ | file_path | string | Required | Path to the text corpus for training the BPE model. |
125
+ | special_tokens | list / vector | [] | List of special structural tokens (e.g., <UNK>). |
126
+ | num_threads | int | 1 | Number of threads to utilize during the training phase. |
127
+ | casing | enum | PRESERVE | Rules for handling text capitalization (LOWERCASE, PRESERVE). |
128
+
129
+ <details>
130
+ <summary><b>View Project Folder Structure</b> (Click to Expand)</summary>
131
+ ```text
132
+ py_tokenizer/
133
+ ├── CMakeLists.txt # Build configuration
134
+ ├── README.md # Project documentation
135
+ ├── setup.py # Python installation script
136
+ ├── include/ # C++ Header files
137
+ │ └── py_tokenizer/
138
+ │ ├── bpe_tokenizer.hpp
139
+ │ └── utils.hpp
140
+ ├── src/ # C++ Source files
141
+ │ ├── bpe_tokenizer.cpp
142
+ │ └── utils.cpp
143
+ ├── bindings/ # pybind11 wrapper code
144
+ │ └── bindings.cpp
145
+ ├── tests/ # Unit tests (C++ and Python)
146
+ │ ├── test_core.cpp
147
+ │ └── test_tokenizer.py
148
+ └── examples/ # Usage examples
149
+ ├── example.cpp
150
+ └── example.py
151
+ ```
152
+ </details>
153
+ <details>
154
+ <summary><b>Roadmap & Future Plans</b> (Click to Expand)</summary>
155
+ * **Version 0.03**: Introduce streaming text tokenization for continuous data feeds.
156
+ * **Platform Expansion**: Official build support and CI/CD pipelines for Windows and macOS.
157
+ * **Advanced Normalization**: Implement customizable pre-tokenization steps (Unicode normalization, regex splitting).
158
+ * **GPU Acceleration**: Research feasibility of offloading frequency counts to CUDA/OpenCL.
159
+ * **Hugging Face Hub**: Native export formats to integrate directly with the transformers library.
160
+ </details>
161
+ ## Performance Goals
162
+ 1. **Zero-Copy Serialization**: Minimizing memory duplication when passing standard library containers between C++ and Python.
163
+ 2. **Cache Locality**: Utilizing contiguous memory structures in C++ to improve CPU cache hit rates during byte-pair merges.
164
+ 3. **Scalability**: Ensuring the training complexity remains sub-quadratic relative to the vocabulary size.
165
+ ## Documentation & Website
166
+ * **Official Documentation**: py_tokenizer Docs
167
+ * **Developer Portfolio**: Ansh Studios
168
+ ## Developer Information
169
+
170
+ | Detail | Information |
171
+ | :--- | :--- |
172
+ | **Developer Name** | Ansh Raj |
173
+ | **Location** | India |
174
+ | **Education** | Class 9th |
175
+ | **Core Competency** | C++ |
176
+ | **Languages** | C++, Python, JavaScript, HTML, CSS, Kotlin, Go |
177
+ | **Environments** | Termux, Cxxdroid, Pydroid, Acode |
178
+
179
+ ## Contact & Links
180
+ * **Email**: anshraj0000000001@gmail.com
181
+ * **GitHub**: ANSH-ins
182
+ ## Contributing
183
+ Contributions to py_tokenizer are highly encouraged. Please follow standard open-source workflows: fork the repository, create a feature branch, commit your changes with clear messages, and open a Pull Request. Ensure that all tests pass and that your code adheres to modern C++ conventions.
184
+ ## Acknowledgements
185
+ Special thanks to the open-source community, the maintainers of pybind11, and the developers behind Android coding environments like Termux and Cxxdroid that made the development of this project possible on mobile devices.
186
+ ## License
187
+ This project is licensed under the **MIT License**. See the LICENSE file in the repository for full details. You are free to use, modify, and distribute this software in both open-source and commercial projects.
@@ -0,0 +1,166 @@
1
+ <div align="center">
2
+ <img src="https://res.cloudinary.com/dbmcddwjd/image/upload/v1783410838/file_00000000a2b471fba91bcdf2f3a398fb_t6gln5.png" alt="py_tokenizer Logo" width="250"/>
3
+ # py_tokenizer
4
+ **A High-Performance Byte Pair Encoding (BPE) Tokenizer for Modern AI Workflows.**
5
+ Version
6
+ Language
7
+ Python
8
+ Build
9
+ Platform
10
+ License
11
+ </div>
12
+ ## Introduction
13
+ py_tokenizer is a high-performance Byte Pair Encoding (BPE) tokenizer engineered entirely in modern C++17. It provides seamless Python bindings via pybind11, bridging the gap between low-level performance and high-level scripting convenience. Designed to be fast, memory-efficient, and highly modular, py_tokenizer is built to integrate effortlessly into advanced Artificial Intelligence and Machine Learning pipelines, specifically catering to Large Language Models (LLMs).
14
+ ## Key Features
15
+
16
+ | Feature | Description |
17
+ | :--- | :--- |
18
+ | **High Performance** | Optimized core written in C++17 for maximum throughput and minimal latency. |
19
+ | **Multi-threading** | Built-in support for concurrent processing to handle massive text corpora rapidly. |
20
+ | **Memory Efficient** | Strict resource management ensures low memory overhead during training and encoding. |
21
+ | **Python Integration** | Native Python bindings utilizing pybind11 for seamless ML framework integration. |
22
+ | **Modular Architecture** | Clean separation of concerns allows for easy extension and customization of tokenization rules. |
23
+ | **AI/LLM Ready** | Designed specifically for the stringent requirements of modern transformer architectures. |
24
+
25
+ ## Why py_tokenizer?
26
+ Tokenization is the critical first step in natural language processing. While many tokenizers exist, py_tokenizer differentiates itself by focusing on raw compute efficiency without sacrificing usability. It is developed natively on mobile/embedded environments (Android via Termux), which enforces strict memory constraints and results in a highly optimized, lean codebase. Whether you are deploying on resource-constrained devices or scaling up on Linux servers, py_tokenizer delivers consistent, robust performance.
27
+ ## Project Architecture
28
+ The project follows a standard wrapper architecture:
29
+ 1. **Core Library (C++)**: Handles all intensive computations, string manipulations, frequency counting, and merging operations.
30
+ 2. **Binding Layer (pybind11)**: Exposes the C++ classes and methods to Python, handling memory safety and type conversions natively.
31
+ 3. **Python API**: Provides a Pythonic interface, allowing users to import the tokenizer just like any native Python module.
32
+ ## Installation & Building from Source
33
+ Currently, py_tokenizer supports Linux and Android (via Termux). Windows and macOS support are planned for future releases.
34
+ ### Prerequisites
35
+ * CMake (Version 3.10 or higher)
36
+ * C++ Compiler (GCC or Clang supporting C++17)
37
+ * Python 3.x
38
+ * pybind11 headers
39
+ ### Build Instructions
40
+ 1. Clone the repository:
41
+ ```bash
42
+ git clone [https://github.com/ANSH-ins/py_tokenizer.git](https://github.com/ANSH-ins/py_tokenizer.git)
43
+ cd py_tokenizer
44
+ ```
45
+ 2. Create a build directory and compile:
46
+ ```bash
47
+ mkdir build
48
+ cd build
49
+ cmake ..
50
+ make -j$(nproc)
51
+ ```
52
+ 3. Install the Python module:
53
+ ```bash
54
+ python setup.py install
55
+ ```
56
+ ## Usage Examples
57
+ ### Python Integration
58
+ ```python
59
+ import py_tokenizer
60
+ # Initialize the BPE Tokenizer
61
+ tokenizer = py_tokenizer.BPETokenizer()
62
+ # Train the tokenizer on your dataset
63
+ tokenizer.train(
64
+ file_path="dataset.txt",
65
+ vocab_size=10000,
66
+ special_tokens=["<PAD>", "<UNK>", "<BOS>", "<EOS>"]
67
+ )
68
+ # Encode text to tokens
69
+ text = "Artificial intelligence relies on efficient tokenization."
70
+ encoded_ids = tokenizer.encode(text)
71
+ print("Encoded IDs:", encoded_ids)
72
+ # Decode tokens back to text
73
+ decoded_text = tokenizer.decode(encoded_ids)
74
+ print("Decoded Text:", decoded_text)
75
+ ```
76
+ ### C++ Integration
77
+ ```cpp
78
+ #include "py_tokenizer/bpe_tokenizer.hpp"
79
+ #include <iostream>
80
+ #include <vector>
81
+ #include <string>
82
+ int main() {
83
+ // Initialize
84
+ py_tokenizer::BPETokenizer tokenizer;
85
+ // Train
86
+ std::vector<std::string> special_tokens = {"<PAD>", "<UNK>", "<BOS>", "<EOS>"};
87
+ tokenizer.train("dataset.txt", 10000, special_tokens);
88
+ // Encode
89
+ std::string text = "Artificial intelligence relies on efficient tokenization.";
90
+ std::vector<int> encoded_ids = tokenizer.encode(text);
91
+ // Decode
92
+ std::string decoded_text = tokenizer.decode(encoded_ids);
93
+ std::cout << "Decoded: " << decoded_text << std::endl;
94
+ return 0;
95
+ }
96
+ ```
97
+ ## Constructor Arguments
98
+ When initializing or training the BPETokenizer, you can configure its behavior using the following parameters:
99
+
100
+ | Argument | Type | Default | Description |
101
+ | :--- | :--- | :--- | :--- |
102
+ | vocab_size | int | Required | The target size of the vocabulary to be generated. |
103
+ | file_path | string | Required | Path to the text corpus for training the BPE model. |
104
+ | special_tokens | list / vector | [] | List of special structural tokens (e.g., <UNK>). |
105
+ | num_threads | int | 1 | Number of threads to utilize during the training phase. |
106
+ | casing | enum | PRESERVE | Rules for handling text capitalization (LOWERCASE, PRESERVE). |
107
+
108
+ <details>
109
+ <summary><b>View Project Folder Structure</b> (Click to Expand)</summary>
110
+ ```text
111
+ py_tokenizer/
112
+ ├── CMakeLists.txt # Build configuration
113
+ ├── README.md # Project documentation
114
+ ├── setup.py # Python installation script
115
+ ├── include/ # C++ Header files
116
+ │ └── py_tokenizer/
117
+ │ ├── bpe_tokenizer.hpp
118
+ │ └── utils.hpp
119
+ ├── src/ # C++ Source files
120
+ │ ├── bpe_tokenizer.cpp
121
+ │ └── utils.cpp
122
+ ├── bindings/ # pybind11 wrapper code
123
+ │ └── bindings.cpp
124
+ ├── tests/ # Unit tests (C++ and Python)
125
+ │ ├── test_core.cpp
126
+ │ └── test_tokenizer.py
127
+ └── examples/ # Usage examples
128
+ ├── example.cpp
129
+ └── example.py
130
+ ```
131
+ </details>
132
+ <details>
133
+ <summary><b>Roadmap & Future Plans</b> (Click to Expand)</summary>
134
+ * **Version 0.03**: Introduce streaming text tokenization for continuous data feeds.
135
+ * **Platform Expansion**: Official build support and CI/CD pipelines for Windows and macOS.
136
+ * **Advanced Normalization**: Implement customizable pre-tokenization steps (Unicode normalization, regex splitting).
137
+ * **GPU Acceleration**: Research feasibility of offloading frequency counts to CUDA/OpenCL.
138
+ * **Hugging Face Hub**: Native export formats to integrate directly with the transformers library.
139
+ </details>
140
+ ## Performance Goals
141
+ 1. **Zero-Copy Serialization**: Minimizing memory duplication when passing standard library containers between C++ and Python.
142
+ 2. **Cache Locality**: Utilizing contiguous memory structures in C++ to improve CPU cache hit rates during byte-pair merges.
143
+ 3. **Scalability**: Ensuring the training complexity remains sub-quadratic relative to the vocabulary size.
144
+ ## Documentation & Website
145
+ * **Official Documentation**: py_tokenizer Docs
146
+ * **Developer Portfolio**: Ansh Studios
147
+ ## Developer Information
148
+
149
+ | Detail | Information |
150
+ | :--- | :--- |
151
+ | **Developer Name** | Ansh Raj |
152
+ | **Location** | India |
153
+ | **Education** | Class 9th |
154
+ | **Core Competency** | C++ |
155
+ | **Languages** | C++, Python, JavaScript, HTML, CSS, Kotlin, Go |
156
+ | **Environments** | Termux, Cxxdroid, Pydroid, Acode |
157
+
158
+ ## Contact & Links
159
+ * **Email**: anshraj0000000001@gmail.com
160
+ * **GitHub**: ANSH-ins
161
+ ## Contributing
162
+ Contributions to py_tokenizer are highly encouraged. Please follow standard open-source workflows: fork the repository, create a feature branch, commit your changes with clear messages, and open a Pull Request. Ensure that all tests pass and that your code adheres to modern C++ conventions.
163
+ ## Acknowledgements
164
+ Special thanks to the open-source community, the maintainers of pybind11, and the developers behind Android coding environments like Termux and Cxxdroid that made the development of this project possible on mobile devices.
165
+ ## License
166
+ This project is licensed under the **MIT License**. See the LICENSE file in the repository for full details. You are free to use, modify, and distribute this software in both open-source and commercial projects.
@@ -0,0 +1,33 @@
1
+ #include "basic_engine.h"
2
+ #include <iostream>
3
+
4
+ basic_engine::basic_engine(const std::string& sentance, bool normilize, size_t epoch): sentance(sentance),normilize(normilize), epoch(epoch){
5
+
6
+ splitter SPLITTER(sentance, normilize, false);
7
+ std::vector<std::vector<std::string>> tokens = SPLITTER.get_splited_tokens();
8
+
9
+ size_t vocab = 0;
10
+ std::unordered_map<std::pair<std::string, std::string>,uint64_t, Pairhash> best_freq_pair;
11
+ while(epoch != 0){
12
+
13
+ finder FINDER(tokens);
14
+
15
+ best_freq_pair = FINDER.get_freq_pair();
16
+
17
+ merger MERGER(best_freq_pair, tokens);
18
+ tokens.clear();
19
+ tokens = MERGER.get_merged_tokens();
20
+ vocab = MERGER.get_vocab();
21
+
22
+ epoch--;
23
+ }
24
+ std::cout<<"\nvocab size: "<<vocab<<"\n"<<std::endl;
25
+ size_t id = 0;
26
+ for(const auto& vector_box : tokens){
27
+ for(const auto& word : vector_box){
28
+ std::cout<<word<<",";
29
+ }
30
+ std::cout<<" : "<<id<<std::endl;
31
+ id++;
32
+ }
33
+ }
@@ -0,0 +1,18 @@
1
+ #pragma once
2
+ #include "tokenizer/splitter.h"
3
+ #include "tokenizer/merger.h"
4
+ #include "tokenizer/freq_finder.h"
5
+ #include <string>
6
+ #include <vector>
7
+ #include <unordered_map>
8
+
9
+
10
+ class basic_engine{
11
+ private:
12
+ std::string sentance;
13
+ bool normilize;
14
+ size_t epoch;
15
+
16
+ public:
17
+ basic_engine(const std::string& sentance, bool normilize = false, size_t epoch = 5);
18
+ };
@@ -0,0 +1,42 @@
1
+ #include "engine.h"
2
+ #include <iostream>
3
+ #include <cstdint>
4
+ #include <unordered_map>
5
+ #include <utility>
6
+
7
+ engine::engine(const std::string& file_path, const size_t chunk_size, bool get_file_info, bool normilize, size_t epoch, size_t using_cpu, bool use_thread): file_path(file_path),chunk_size(chunk_size), get_file_info(get_file_info), normilize(normilize), epoch(epoch), using_cpu(using_cpu), use_thread(use_thread){
8
+
9
+ std::vector<std::vector<std::string>> tokens;
10
+
11
+ std::unordered_map<std::pair<std::string, std::string>, uint64_t, Pairhash> best_freq_pair;
12
+
13
+ std::string sentance;
14
+
15
+ loader DataLoader(file_path, chunk_size, normilize);
16
+
17
+ sentance = DataLoader.get_sentance();
18
+
19
+ splitter SPLITTER(sentance, using_cpu,use_thread);
20
+
21
+ if(use_thread){
22
+ SPLITTER.thread_runner();
23
+ }
24
+ tokens = SPLITTER.get_splited_tokens();
25
+
26
+ std::vector<file_details> details = DataLoader.detail_provider();
27
+
28
+ while(epoch>0){
29
+ finder FINDER(tokens);
30
+ best_freq_pair = FINDER.get_freq_pair();
31
+
32
+ merger MERGER(best_freq_pair, tokens);
33
+
34
+
35
+ tokens = MERGER.get_merged_tokens();
36
+
37
+ vocab = MERGER.get_vocab();
38
+ epoch--;
39
+ }
40
+ provider PROVIDER(tokens, details, get_file_info, vocab);
41
+
42
+ };