riktoken 0.0.1
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.
- checksums.yaml +7 -0
- data/.rubocop.yml +10 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +205 -0
- data/Rakefile +24 -0
- data/lib/riktoken/bpe.rb +139 -0
- data/lib/riktoken/encoding.rb +52 -0
- data/lib/riktoken/encodings/cl100k_base.rb +35 -0
- data/lib/riktoken/encodings/o200k_base.rb +40 -0
- data/lib/riktoken/encodings/p50k_base.rb +31 -0
- data/lib/riktoken/encodings/p50k_edit.rb +35 -0
- data/lib/riktoken/encodings/r50k_base.rb +31 -0
- data/lib/riktoken/encodings.rb +28 -0
- data/lib/riktoken/tiktoken_file.rb +42 -0
- data/lib/riktoken/version.rb +5 -0
- data/lib/riktoken.rb +155 -0
- data/renovate.json +6 -0
- data/sig/generated/riktoken/bpe.rbs +55 -0
- data/sig/generated/riktoken/encoding.rbs +34 -0
- data/sig/generated/riktoken/encodings/cl100k_base.rbs +15 -0
- data/sig/generated/riktoken/encodings/o200k_base.rbs +15 -0
- data/sig/generated/riktoken/encodings/p50k_base.rbs +15 -0
- data/sig/generated/riktoken/encodings/p50k_edit.rbs +17 -0
- data/sig/generated/riktoken/encodings/r50k_base.rbs +15 -0
- data/sig/generated/riktoken/encodings.rbs +18 -0
- data/sig/generated/riktoken/tiktoken_file.rbs +15 -0
- data/sig/generated/riktoken/version.rbs +5 -0
- data/sig/generated/riktoken.rbs +55 -0
- metadata +87 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 553fe61b162a538778cfd8eb9704b83853871c644fbf0234f5d426a54ab84f88
|
|
4
|
+
data.tar.gz: 83a685a9091cd2c5d82d85104c412d9de48bf837bee8777e3522ee59f7251890
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: a5bea804b921f364c1b0e26a428c40f342daf31472ed34035131450436e154c55018dfe8bb8f57bfc0038c5e6d37a9ed0017dc89436b2d864399f49f9900f5da
|
|
7
|
+
data.tar.gz: 82abf0e0df5d50a843ef3c8319d52a7b0d2d0190f843ed97be57182c1f4e476869ef40105484e813292cf4f6916d5298dac6eb27693b12a051020f911cdd8dcd
|
data/.rubocop.yml
ADDED
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
|
2
|
+
|
|
3
|
+
## Our Pledge
|
|
4
|
+
|
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
|
10
|
+
identity and orientation.
|
|
11
|
+
|
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
|
13
|
+
diverse, inclusive, and healthy community.
|
|
14
|
+
|
|
15
|
+
## Our Standards
|
|
16
|
+
|
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
|
18
|
+
community include:
|
|
19
|
+
|
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
|
24
|
+
and learning from the experience
|
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
|
26
|
+
community
|
|
27
|
+
|
|
28
|
+
Examples of unacceptable behavior include:
|
|
29
|
+
|
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
|
31
|
+
any kind
|
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
|
33
|
+
* Public or private harassment
|
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
|
35
|
+
without their explicit permission
|
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
|
37
|
+
professional setting
|
|
38
|
+
|
|
39
|
+
## Enforcement Responsibilities
|
|
40
|
+
|
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
|
44
|
+
or harmful.
|
|
45
|
+
|
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
|
49
|
+
decisions when appropriate.
|
|
50
|
+
|
|
51
|
+
## Scope
|
|
52
|
+
|
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
|
54
|
+
an individual is officially representing the community in public spaces.
|
|
55
|
+
Examples of representing our community include using an official email address,
|
|
56
|
+
posting via an official social media account, or acting as an appointed
|
|
57
|
+
representative at an online or offline event.
|
|
58
|
+
|
|
59
|
+
## Enforcement
|
|
60
|
+
|
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
|
62
|
+
reported to the community leaders responsible for enforcement at
|
|
63
|
+
[INSERT CONTACT METHOD].
|
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
|
65
|
+
|
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
|
67
|
+
reporter of any incident.
|
|
68
|
+
|
|
69
|
+
## Enforcement Guidelines
|
|
70
|
+
|
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
|
73
|
+
|
|
74
|
+
### 1. Correction
|
|
75
|
+
|
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
|
77
|
+
unprofessional or unwelcome in the community.
|
|
78
|
+
|
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
|
82
|
+
|
|
83
|
+
### 2. Warning
|
|
84
|
+
|
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
|
86
|
+
actions.
|
|
87
|
+
|
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
|
93
|
+
ban.
|
|
94
|
+
|
|
95
|
+
### 3. Temporary Ban
|
|
96
|
+
|
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
|
98
|
+
sustained inappropriate behavior.
|
|
99
|
+
|
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
|
101
|
+
communication with the community for a specified period of time. No public or
|
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
|
104
|
+
Violating these terms may lead to a permanent ban.
|
|
105
|
+
|
|
106
|
+
### 4. Permanent Ban
|
|
107
|
+
|
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
|
111
|
+
|
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
|
113
|
+
community.
|
|
114
|
+
|
|
115
|
+
## Attribution
|
|
116
|
+
|
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
|
118
|
+
version 2.1, available at
|
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
|
120
|
+
|
|
121
|
+
Community Impact Guidelines were inspired by
|
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
|
123
|
+
|
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
|
127
|
+
|
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Taiki Kawakami (a.k.a moznion) https://moznion.net
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
# Riktoken
|
|
2
|
+
|
|
3
|
+
A pure Ruby partial implementation of OpenAI's tiktoken library for BPE (Byte Pair Encoding) tokenization. Riktoken enables you to encode and decode text using the same tokenizers as OpenAI's models like GPT-4, GPT-3.5, and others.
|
|
4
|
+
|
|
5
|
+
Most of the code is ported from [openai/tiktoken](https://github.com/openai/tiktoken).
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- Pure Ruby implementation (no native dependencies) <= **this is one of the main motivations for this library**
|
|
10
|
+
- No any dependencies
|
|
11
|
+
- Compatible with OpenAI's tiktoken encodings (partial)
|
|
12
|
+
- Supports all major OpenAI model encodings (cl100k_base, o200k_base, p50k_base, etc.)
|
|
13
|
+
- Special token handling
|
|
14
|
+
- Model-to-encoding mapping
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
Add this line to your application's Gemfile:
|
|
19
|
+
|
|
20
|
+
```ruby
|
|
21
|
+
gem 'riktoken'
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
And then execute:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
bundle install
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Or install it yourself as:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
gem install riktoken
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Quick Start
|
|
37
|
+
|
|
38
|
+
### Setting Up .tiktoken Files
|
|
39
|
+
|
|
40
|
+
You have to download the official `.tiktoken` files from OpenAI and locate them to arbitrary directory in advance:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
# Create base directory as you like (`~/.riktoken` is the default location)
|
|
44
|
+
mkdir -p ~/.riktoken
|
|
45
|
+
|
|
46
|
+
# Download encoding files
|
|
47
|
+
curl -o ~/.riktoken/cl100k_base.tiktoken \
|
|
48
|
+
https://raw.githubusercontent.com/openai/tiktoken/main/tiktoken/assets/cl100k_base.tiktoken
|
|
49
|
+
|
|
50
|
+
curl -o ~/.riktoken/o200k_base.tiktoken \
|
|
51
|
+
https://raw.githubusercontent.com/openai/tiktoken/main/tiktoken/assets/o200k_base.tiktoken
|
|
52
|
+
|
|
53
|
+
# Add other encodings as needed...
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The library will search for `.tiktoken` files in the given directory as a parameter `tiktoken_base_dir` (default is `ENV[TIKTOKEN_BASE_DIR] || #{ENV['HOME']}/.riktoken/`).
|
|
57
|
+
|
|
58
|
+
**NOTE: If no `.tiktoken` file is found, the library will raise an error on loading; it does not fall back to built-in encodings and/or downloads the file automatically. i.e. the user must guarantee that the `.tiktoken` files are available in the specified directory.**
|
|
59
|
+
|
|
60
|
+
```ruby
|
|
61
|
+
require 'riktoken'
|
|
62
|
+
|
|
63
|
+
# Get encoding by name
|
|
64
|
+
# You have to prepare `.tiktoken` files in the specified directory in advance.
|
|
65
|
+
encoding = Riktoken.get_encoding("cl100k_base", tiktoken_base_dir: "#{ENV['HOME']}/.riktoken")
|
|
66
|
+
|
|
67
|
+
# Or get encoding for a specific model
|
|
68
|
+
# Once `tiktoken_base_dir` is omitted, it will use the directory `ENV[TIKTOKEN_BASE_DIR] || #{ENV['HOME']}/.riktoken/` as default.
|
|
69
|
+
encoding = Riktoken.encoding_for_model("gpt-4")
|
|
70
|
+
|
|
71
|
+
# Encode text to tokens
|
|
72
|
+
tokens = encoding.encode("Hello, world!")
|
|
73
|
+
# => [9906, 11, 1917, 0]
|
|
74
|
+
|
|
75
|
+
# Decode tokens back to text
|
|
76
|
+
text = encoding.decode(tokens)
|
|
77
|
+
# => "Hello, world!"
|
|
78
|
+
|
|
79
|
+
# Count tokens
|
|
80
|
+
token_count = encoding.encode("Your text here").length
|
|
81
|
+
# => 3
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Supported Encodings
|
|
85
|
+
|
|
86
|
+
| Encoding | Models | tiktoken file name |
|
|
87
|
+
|----------|--------|------------------------|
|
|
88
|
+
| `cl100k_base` | GPT-4, GPT-3.5-turbo, text-embedding-ada-002, text-embedding-3-small, text-embedding-3-large | `cl100k_base.tiktoken` |
|
|
89
|
+
| `o200k_base` | GPT-4o, GPT-4o-mini | `o200k_base.tiktoken` |
|
|
90
|
+
| `p50k_base` | text-davinci-003, text-davinci-002, code-davinci-002 | `p50k_base.tiktoken` |
|
|
91
|
+
| `p50k_edit` | text-davinci-edit-001, code-davinci-edit-001 | `p50k_base.tiktoken` |
|
|
92
|
+
| `r50k_base` | text-davinci-001, text-curie-001, text-babbage-001, text-ada-001 | `r50k_base.tiktoken` |
|
|
93
|
+
|
|
94
|
+
## Usage Examples
|
|
95
|
+
|
|
96
|
+
### Token Counting for API Cost Estimation
|
|
97
|
+
|
|
98
|
+
```ruby
|
|
99
|
+
encoding = Riktoken.encoding_for_model("gpt-4")
|
|
100
|
+
text = "Your prompt here..."
|
|
101
|
+
token_count = encoding.encode(text).length
|
|
102
|
+
|
|
103
|
+
# Estimate API cost (example rates)
|
|
104
|
+
input_cost_per_1k = 0.03 # $0.03 per 1K tokens
|
|
105
|
+
estimated_cost = (token_count / 1000.0) * input_cost_per_1k
|
|
106
|
+
puts "Token count: #{token_count}"
|
|
107
|
+
puts "Estimated cost: $#{'%.4f' % estimated_cost}"
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### Handling Special Tokens
|
|
111
|
+
|
|
112
|
+
```ruby
|
|
113
|
+
encoding = Riktoken.get_encoding("cl100k_base")
|
|
114
|
+
|
|
115
|
+
# By default, special tokens raise an error
|
|
116
|
+
begin
|
|
117
|
+
tokens = encoding.encode("Hello <|endoftext|> world")
|
|
118
|
+
rescue Riktoken::Encoding::DisallowedSpecialTokenError
|
|
119
|
+
puts "Special tokens not allowed!"
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Allow specific special tokens
|
|
123
|
+
tokens = encoding.encode("Hello <|endoftext|> world", allowed_special: ["<|endoftext|>"])
|
|
124
|
+
|
|
125
|
+
# Allow all special tokens
|
|
126
|
+
tokens = encoding.encode("Hello <|endoftext|> world", allowed_special: "all")
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Splitting Text by Token Limit
|
|
130
|
+
|
|
131
|
+
```ruby
|
|
132
|
+
def split_by_tokens(text, max_tokens, encoding)
|
|
133
|
+
tokens = encoding.encode(text)
|
|
134
|
+
chunks = []
|
|
135
|
+
|
|
136
|
+
tokens.each_slice(max_tokens) do |chunk|
|
|
137
|
+
chunks << encoding.decode(chunk)
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
chunks
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# Example: Split text into 100-token chunks
|
|
144
|
+
encoding = Riktoken.get_encoding("cl100k_base")
|
|
145
|
+
chunks = split_by_tokens("Your long text here...", 100, encoding)
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### List Available Encodings and Models
|
|
149
|
+
|
|
150
|
+
```ruby
|
|
151
|
+
# List all available encodings
|
|
152
|
+
puts Riktoken.list_encoding_names
|
|
153
|
+
# => ["cl100k_base", "o200k_base", "p50k_base", "p50k_edit", "r50k_base"]
|
|
154
|
+
|
|
155
|
+
# List all supported models
|
|
156
|
+
puts Riktoken.list_model_names
|
|
157
|
+
# => ["gpt-4", "gpt-3.5-turbo", "text-davinci-003", ...]
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Advanced Usage
|
|
161
|
+
|
|
162
|
+
### Custom Encodings
|
|
163
|
+
|
|
164
|
+
```ruby
|
|
165
|
+
# Make a custom encoding
|
|
166
|
+
encoding = Riktoken.make_encoding(
|
|
167
|
+
name: "my_custom_encoding",
|
|
168
|
+
ranks: {"hello" => 0, "world" => 1},
|
|
169
|
+
special_tokens: {"<|custom|>" => 100},
|
|
170
|
+
pattern: /\w+/
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
tokens = encoding.encode('hello, world')
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### Loading from Custom .tiktoken File
|
|
177
|
+
|
|
178
|
+
```ruby
|
|
179
|
+
encoding = Riktoken.encoding_from_file(
|
|
180
|
+
path: "path/to/custom.tiktoken",
|
|
181
|
+
name: "custom_encoding",
|
|
182
|
+
special_tokens: {"<|special|>" => 50000},
|
|
183
|
+
pattern: /'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?+\p{L}++|\p{N}{1,3}+| ?[^\s\p{L}\p{N}]++[\r\n]*+|\s++$|\s*[\r\n]|\s+(?!\S)|\s/
|
|
184
|
+
)
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
## Precedents
|
|
188
|
+
|
|
189
|
+
[IAPark/tiktoken_ruby](https://github.com/IAPark/tiktoken_ruby) is a Ruby port of OpenAI's tiktoken library uses native extensions.
|
|
190
|
+
This would be a good choice if you need a faster implementation with native performance.
|
|
191
|
+
|
|
192
|
+
## Development
|
|
193
|
+
|
|
194
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
|
195
|
+
|
|
196
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
|
197
|
+
|
|
198
|
+
## Contributing
|
|
199
|
+
|
|
200
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/moznion/riktoken. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/moznion/riktoken/blob/main/CODE_OF_CONDUCT.md).
|
|
201
|
+
|
|
202
|
+
## License
|
|
203
|
+
|
|
204
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
|
205
|
+
|
data/Rakefile
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "bundler/gem_tasks"
|
|
4
|
+
require "minitest/test_task"
|
|
5
|
+
|
|
6
|
+
Minitest::TestTask.create
|
|
7
|
+
|
|
8
|
+
require "rubocop/rake_task"
|
|
9
|
+
|
|
10
|
+
RuboCop::RakeTask.new
|
|
11
|
+
|
|
12
|
+
task default: %i[test rubocop]
|
|
13
|
+
|
|
14
|
+
desc "Run tests with code coverage"
|
|
15
|
+
task :coverage do
|
|
16
|
+
ENV["COVERAGE"] = "true"
|
|
17
|
+
Rake::Task["test"].invoke
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
namespace :rbs do
|
|
21
|
+
task gen: %i[] do
|
|
22
|
+
sh "rbs-inline --output --opt-out lib"
|
|
23
|
+
end
|
|
24
|
+
end
|
data/lib/riktoken/bpe.rb
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Riktoken
|
|
4
|
+
class BPE
|
|
5
|
+
class TextEncodingError < StandardError; end
|
|
6
|
+
|
|
7
|
+
attr_reader :encoder #: Hash[String, rank] -- parameter like parsed *.tiktoken file
|
|
8
|
+
attr_reader :decoder #: Hash[rank, String]
|
|
9
|
+
attr_reader :special_tokens_encoder #: Hash[String, rank]
|
|
10
|
+
attr_reader :special_tokens_decoder #: Hash[rank, String]
|
|
11
|
+
attr_reader :regex #: Regexp
|
|
12
|
+
attr_reader :special_regex #: Regexp
|
|
13
|
+
|
|
14
|
+
# @rbs encoder: Hash[String, rank]
|
|
15
|
+
# @rbs regex: Regexp
|
|
16
|
+
# @rbs special_tokens_encoder: Hash[String, rank]
|
|
17
|
+
# @rbs return: BPE
|
|
18
|
+
def initialize(encoder:, regex:, special_tokens_encoder:)
|
|
19
|
+
@encoder = encoder
|
|
20
|
+
@regex = regex
|
|
21
|
+
@special_tokens_encoder = special_tokens_encoder
|
|
22
|
+
@special_regex = Regexp.union(special_tokens_encoder.keys)
|
|
23
|
+
@decoder = encoder.map { |k, v| [v, k] }.to_h
|
|
24
|
+
@special_tokens_decoder = special_tokens_encoder.map { |k, v| [v, k] }.to_h
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# @rbs return: Set[String]
|
|
28
|
+
def special_tokens
|
|
29
|
+
Set.new(@special_tokens_encoder.keys)
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Encode given text into tokens using the BPE encoding, allowing for given special tokens.
|
|
33
|
+
# @rbs text: String
|
|
34
|
+
# @rbs allowed_special_tokens: Set[String]
|
|
35
|
+
# @rbs return: tuple[Array[rank], Integer]
|
|
36
|
+
def encode(text, allowed_special_tokens: Set.new)
|
|
37
|
+
tokens = []
|
|
38
|
+
start = 0
|
|
39
|
+
last_piece_token_len = 0
|
|
40
|
+
|
|
41
|
+
loop do
|
|
42
|
+
next_special = nil
|
|
43
|
+
start_find = start
|
|
44
|
+
while start_find < text.length
|
|
45
|
+
m = @special_regex.match(text, start_find)
|
|
46
|
+
if m.nil?
|
|
47
|
+
break
|
|
48
|
+
elsif allowed_special_tokens.include?(m[0])
|
|
49
|
+
next_special = m
|
|
50
|
+
break
|
|
51
|
+
else
|
|
52
|
+
start_find = m.begin(0) + 1
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
end_pos = next_special ? next_special.begin(0) : text.length
|
|
57
|
+
|
|
58
|
+
segment = text[start...end_pos]
|
|
59
|
+
segment.scan(@regex) do |m|
|
|
60
|
+
piece = m.is_a?(Array) ? m[0] : m
|
|
61
|
+
if @encoder.key?(piece)
|
|
62
|
+
last_piece_token_len = 1
|
|
63
|
+
tokens << @encoder[piece]
|
|
64
|
+
else
|
|
65
|
+
bpe_tokens = self.class.byte_pair_encode(piece, @encoder)
|
|
66
|
+
last_piece_token_len = bpe_tokens.size
|
|
67
|
+
tokens.concat(bpe_tokens)
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
break unless next_special
|
|
72
|
+
|
|
73
|
+
piece = next_special[0]
|
|
74
|
+
token = @special_tokens_encoder[piece]
|
|
75
|
+
tokens << token
|
|
76
|
+
start = next_special.end(0)
|
|
77
|
+
last_piece_token_len = 0
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
[tokens, last_piece_token_len]
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Encode given text into tokens using the BPE encoding without considering special tokens.
|
|
84
|
+
# @rbs text: String
|
|
85
|
+
# @rbs return: Array[rank]
|
|
86
|
+
def encode_ordinary(text)
|
|
87
|
+
encode(text)[0]
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# Encode given text into tokens using the BPE encoding, allowing for all special tokens.
|
|
91
|
+
# @rbs text: String
|
|
92
|
+
# @rbs return: tuple[Array[rank], Integer]
|
|
93
|
+
def encode_with_special_tokens(text)
|
|
94
|
+
encode(text, allowed_special_tokens: special_tokens)
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# Decode given tokens back into text encoded as UTF-8.
|
|
98
|
+
# @rbs tokens: Array[rank]
|
|
99
|
+
# @rbs return: String
|
|
100
|
+
def decode(tokens)
|
|
101
|
+
return "" if tokens.empty?
|
|
102
|
+
encoded = tokens.map { |t| @decoder[t] || @special_tokens_decoder[t] }.join.force_encoding("UTF-8")
|
|
103
|
+
if encoded.valid_encoding?
|
|
104
|
+
encoded
|
|
105
|
+
else
|
|
106
|
+
raise TextEncodingError, "failed to apply the text encoding to decoded tokens as valid UTF-8"
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
# @rbs piece: String
|
|
111
|
+
# @rbs ranks: Hash[String, rank]
|
|
112
|
+
# @rbs return: Array[rank]
|
|
113
|
+
def self.byte_pair_encode(piece, ranks)
|
|
114
|
+
return [ranks[piece]] if ranks[piece]
|
|
115
|
+
|
|
116
|
+
chars = piece.bytes.map(&:chr)
|
|
117
|
+
|
|
118
|
+
loop do
|
|
119
|
+
# Find the pair with the smallest rank among all adjacent pairs in ranks
|
|
120
|
+
min_rank = nil
|
|
121
|
+
min_pair_pos = nil
|
|
122
|
+
(0...chars.size - 1).each do |i|
|
|
123
|
+
pair = chars[i] + chars[i + 1]
|
|
124
|
+
if ranks.key?(pair) && (min_rank.nil? || ranks[pair] < min_rank)
|
|
125
|
+
min_rank = ranks[pair]
|
|
126
|
+
min_pair_pos = i
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
break unless min_pair_pos
|
|
130
|
+
|
|
131
|
+
# merge: `min_pair_pos` and `min_pair_pos+1`
|
|
132
|
+
chars = chars[0...min_pair_pos] + [chars[min_pair_pos] + chars[min_pair_pos + 1]] + chars[(min_pair_pos + 2)..]
|
|
133
|
+
# after merging, it attempts re-searching from the start to maximize the merging unit
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
chars.map { |c| ranks[c] }
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
end
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "bpe"
|
|
4
|
+
|
|
5
|
+
module Riktoken
|
|
6
|
+
class Encoding
|
|
7
|
+
class DisallowedSpecialTokenError < StandardError; end
|
|
8
|
+
|
|
9
|
+
class InvalidTokenError < StandardError; end
|
|
10
|
+
|
|
11
|
+
attr_reader :name
|
|
12
|
+
|
|
13
|
+
# @rbs @special_tokens: Hash[String, rank]
|
|
14
|
+
# @rbs @bpe: BPE
|
|
15
|
+
|
|
16
|
+
# @rbs name: String
|
|
17
|
+
# @rbs ranks: Hash[String, rank]
|
|
18
|
+
# @rbs special_tokens: Hash[String, rank]
|
|
19
|
+
# @rbs pattern: Regexp
|
|
20
|
+
# @rbs return: Encoding
|
|
21
|
+
def initialize(name:, ranks:, pattern:, special_tokens: {})
|
|
22
|
+
@name = name
|
|
23
|
+
@special_tokens = special_tokens
|
|
24
|
+
@bpe = BPE.new(encoder: ranks, regex: pattern, special_tokens_encoder: special_tokens)
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# @rbs text: String
|
|
28
|
+
# @rbs allowed_special: Set[String]|"all"
|
|
29
|
+
# @rbs disallowed_special: Set[String]|"all"
|
|
30
|
+
# @rbs return: Array[rank]
|
|
31
|
+
def encode(text, allowed_special: Set.new, disallowed_special: "all")
|
|
32
|
+
allowed_special = Set.new(@special_tokens.keys) if allowed_special == "all"
|
|
33
|
+
disallowed_special = Set.new(@special_tokens.keys) - allowed_special if disallowed_special == "all"
|
|
34
|
+
|
|
35
|
+
unless disallowed_special.empty?
|
|
36
|
+
found = text.scan(Regexp.union(disallowed_special.to_a)).uniq
|
|
37
|
+
found_disallowed = found & disallowed_special.to_a
|
|
38
|
+
unless found_disallowed.empty?
|
|
39
|
+
raise DisallowedSpecialTokenError, "Disallowed special token(s) found: #{found_disallowed.join(", ")}"
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
@bpe.encode(text, allowed_special_tokens: allowed_special)[0]
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# @rbs tokens: Array[rank]
|
|
47
|
+
# @rbs return: String
|
|
48
|
+
def decode(tokens)
|
|
49
|
+
@bpe.decode(tokens)
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../encodings"
|
|
4
|
+
|
|
5
|
+
module Riktoken
|
|
6
|
+
module Encodings
|
|
7
|
+
module Cl100kBase
|
|
8
|
+
include Riktoken::Encodings
|
|
9
|
+
|
|
10
|
+
ENCODING_NAME = "cl100k_base"
|
|
11
|
+
private_constant :ENCODING_NAME
|
|
12
|
+
|
|
13
|
+
# @rbs tiktoken_base_dir: String -- the directory where tiktoken files are stored
|
|
14
|
+
# @rbs return: Riktoken::Encoding
|
|
15
|
+
def self.load_encoding(tiktoken_base_dir:)
|
|
16
|
+
ranks = TiktokenFile.new.load(find_tiktoken_file(name: ENCODING_NAME, base_dir: tiktoken_base_dir))
|
|
17
|
+
special_tokens = {
|
|
18
|
+
"<|endoftext|>" => 100257,
|
|
19
|
+
"<|fim_prefix|>" => 100258,
|
|
20
|
+
"<|fim_middle|>" => 100259,
|
|
21
|
+
"<|fim_suffix|>" => 100260,
|
|
22
|
+
"<|endofprompt|>" => 100276
|
|
23
|
+
}
|
|
24
|
+
pattern = /'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?+\p{L}++|\p{N}{1,3}+| ?[^\s\p{L}\p{N}]++[\r\n]*+|\s++$|\s*[\r\n]|\s+(?!\S)|\s/
|
|
25
|
+
|
|
26
|
+
Riktoken::Encoding.new(
|
|
27
|
+
name: ENCODING_NAME,
|
|
28
|
+
ranks: ranks,
|
|
29
|
+
special_tokens: special_tokens,
|
|
30
|
+
pattern: pattern
|
|
31
|
+
)
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../encodings"
|
|
4
|
+
|
|
5
|
+
module Riktoken
|
|
6
|
+
module Encodings
|
|
7
|
+
module O200kBase
|
|
8
|
+
include Riktoken::Encodings
|
|
9
|
+
|
|
10
|
+
ENCODING_NAME = "o200k_base"
|
|
11
|
+
private_constant :ENCODING_NAME
|
|
12
|
+
|
|
13
|
+
# @rbs tiktoken_base_dir: String -- the directory where tiktoken files are stored
|
|
14
|
+
# @rbs return: Riktoken::Encoding
|
|
15
|
+
def self.load_encoding(tiktoken_base_dir:)
|
|
16
|
+
ranks = TiktokenFile.new.load(find_tiktoken_file(name: ENCODING_NAME, base_dir: tiktoken_base_dir))
|
|
17
|
+
special_tokens = {
|
|
18
|
+
"<|endoftext|>" => 199999,
|
|
19
|
+
"<|endofprompt|>" => 200018
|
|
20
|
+
}
|
|
21
|
+
pattern = Regexp.union([
|
|
22
|
+
/[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?/,
|
|
23
|
+
/[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?/,
|
|
24
|
+
/\p{N}{1,3}/,
|
|
25
|
+
/ ?[^\s\p{L}\p{N}]+[\r\n\/]*/,
|
|
26
|
+
/\s*[\r\n]+/,
|
|
27
|
+
/\s+(?!\S)/,
|
|
28
|
+
/\s+/
|
|
29
|
+
])
|
|
30
|
+
|
|
31
|
+
Riktoken::Encoding.new(
|
|
32
|
+
name: ENCODING_NAME,
|
|
33
|
+
ranks: ranks,
|
|
34
|
+
special_tokens: special_tokens,
|
|
35
|
+
pattern: pattern
|
|
36
|
+
)
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|