Text Generation
English
code
File size: 11,006 Bytes
dae52e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
"""
=====================================
 Shulker Code β€” Tokenizer
 BPE tokenizer optimized for code
 Developed by @kopeedev / CyeroX
=====================================

This tokenizer is specifically designed for programming languages:
- Preserves indentation (important for Python!)
- Handles special tokens: <code>, </code>, <lang:python>, etc.
- Supports 50+ programming languages
- BPE (Byte Pair Encoding) vocabulary
"""

import os
import json
import regex as re
from typing import List, Optional, Dict, Union
from pathlib import Path


# ─────────────────────────────────────────────
# Special tokens used by Shulker Code
# ─────────────────────────────────────────────
SPECIAL_TOKENS = {
    "<pad>":      0,
    "<bos>":      1,
    "<eos>":      2,
    "<unk>":      3,
    "<sep>":      4,
    "<mask>":     5,
    # Code-specific tokens
    "<code>":     6,
    "</code>":    7,
    "<comment>":  8,
    "</comment>": 9,
    # Language markers
    "<lang:py>":  10,
    "<lang:js>":  11,
    "<lang:cpp>": 12,
    "<lang:java>":13,
    "<lang:ts>":  14,
    "<lang:go>":  15,
    "<lang:rs>":  16,
    "<lang:cs>":  17,
    # Task markers
    "<task:gen>": 18,
    "<task:fix>": 19,
    "<task:explain>": 20,
    "<task:optimize>": 21,
}

# Language extension to token mapping
LANG_TOKENS = {
    ".py":   "<lang:py>",
    ".js":   "<lang:js>",
    ".ts":   "<lang:ts>",
    ".cpp":  "<lang:cpp>",
    ".cc":   "<lang:cpp>",
    ".java": "<lang:java>",
    ".go":   "<lang:go>",
    ".rs":   "<lang:rs>",
    ".cs":   "<lang:cs>",
    ".rb":   "<lang:rb>",
    ".php":  "<lang:php>",
}


class ShulkerTokenizer:
    """
    BPE tokenizer for Shulker Code.

    Uses the HuggingFace `tokenizers` library under the hood,
    but wraps it with code-specific pre/post processing.

    For training a tokenizer from scratch:
        tokenizer = ShulkerTokenizer.train_from_files(files, vocab_size=32000)

    For loading a pretrained tokenizer:
        tokenizer = ShulkerTokenizer.from_pretrained("path/to/tokenizer")
    """

    def __init__(self):
        self._tokenizer = None
        self.special_tokens = SPECIAL_TOKENS
        self.vocab_size = 32000

        # Code-aware pre-tokenization regex
        # Splits on whitespace, but preserves indentation
        self._code_pattern = re.compile(
            r"""(?x)
            \s+                    # whitespace (preserved for indentation)
            | [a-zA-Z_]\w*         # identifiers
            | \d+(?:\.\d+)?        # numbers
            | "(?:[^"\\]|\\.)*"    # double-quoted strings
            | '(?:[^'\\]|\\.)*'    # single-quoted strings
            | `(?:[^`\\]|\\.)*`    # backtick strings
            | (?:\/\/|#)[^\n]*     # comments
            | [+\-*/=<>!&|^~%@]+   # operators
            | [{}()\[\];:,.]       # delimiters
            | .                    # fallback
            """
        )

    @classmethod
    def train_from_files(
        cls,
        files: List[str],
        vocab_size: int = 32000,
        min_frequency: int = 2,
        save_path: Optional[str] = None,
    ) -> "ShulkerTokenizer":
        """
        Train a new BPE tokenizer from code files.

        Args:
            files: List of .py, .js, .txt, .jsonl file paths
            vocab_size: Target vocabulary size
            min_frequency: Minimum token frequency
            save_path: Optional directory to save tokenizer

        Returns:
            Trained ShulkerTokenizer instance
        """
        try:
            from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders, processors
        except ImportError:
            raise ImportError("Install tokenizers: pip install tokenizers")

        instance = cls()

        # Build BPE tokenizer
        tokenizer = Tokenizer(models.BPE(unk_token="<unk>"))

        # Code-aware pre-tokenizer: byte-level BPE
        tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)

        # BPE trainer configuration
        special_token_list = list(SPECIAL_TOKENS.keys())
        trainer = trainers.BpeTrainer(
            vocab_size=vocab_size,
            min_frequency=min_frequency,
            special_tokens=special_token_list,
            initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
            show_progress=True,
        )

        # Train on files
        print(f"πŸ”€ Training BPE tokenizer on {len(files)} files...")
        tokenizer.train(files, trainer)

        # Add byte-level decoder
        tokenizer.decoder = decoders.ByteLevel()

        # Post-processor for BOS/EOS
        tokenizer.post_processor = processors.ByteLevel(trim_offsets=False)

        instance._tokenizer = tokenizer
        instance.vocab_size = tokenizer.get_vocab_size()

        if save_path:
            instance.save(save_path)
            print(f"βœ… Tokenizer saved to {save_path}")

        print(f"βœ… Tokenizer trained: {instance.vocab_size:,} tokens")
        return instance

    @classmethod
    def from_pretrained(cls, path: str) -> "ShulkerTokenizer":
        """Load a saved tokenizer from disk."""
        try:
            from tokenizers import Tokenizer
        except ImportError:
            raise ImportError("Install tokenizers: pip install tokenizers")

        instance = cls()
        tokenizer_path = os.path.join(path, "tokenizer.json")
        instance._tokenizer = Tokenizer.from_file(tokenizer_path)
        instance.vocab_size = instance._tokenizer.get_vocab_size()

        # Load vocab size override if present
        config_path = os.path.join(path, "tokenizer_config.json")
        if os.path.exists(config_path):
            with open(config_path) as f:
                config = json.load(f)
                instance.vocab_size = config.get("vocab_size", instance.vocab_size)

        print(f"βœ… Tokenizer loaded from {path} ({instance.vocab_size:,} tokens)")
        return instance

    @classmethod
    def from_hf_pretrained(cls, model_name: str = "microsoft/codebert-base") -> "ShulkerTokenizer":
        """
        Bootstrap from a HuggingFace pretrained tokenizer.
        Useful for quick setup without training from scratch.
        """
        try:
            from transformers import AutoTokenizer
        except ImportError:
            raise ImportError("Install transformers: pip install transformers")

        instance = cls()
        hf_tokenizer = AutoTokenizer.from_pretrained(model_name)

        # Wrap HF tokenizer with our interface
        instance._hf_tokenizer = hf_tokenizer
        instance._use_hf = True
        instance.vocab_size = hf_tokenizer.vocab_size

        print(f"βœ… Using HuggingFace tokenizer: {model_name} ({instance.vocab_size:,} tokens)")
        return instance

    def encode(
        self,
        text: str,
        add_special_tokens: bool = True,
        max_length: Optional[int] = None,
        lang: Optional[str] = None,
    ) -> List[int]:
        """
        Encode text to token IDs.

        Args:
            text: Input text/code
            add_special_tokens: Wrap with <bos>/<eos>
            max_length: Truncate to this length
            lang: Optional language hint (e.g. "python", "javascript")

        Returns:
            List of integer token IDs
        """
        if hasattr(self, "_use_hf") and self._use_hf:
            result = self._hf_tokenizer.encode(
                text,
                add_special_tokens=add_special_tokens,
                max_length=max_length,
                truncation=max_length is not None,
            )
            return result

        if self._tokenizer is None:
            raise RuntimeError("Tokenizer not initialized. Call train_from_files() or from_pretrained() first.")

        encoding = self._tokenizer.encode(text)
        ids = encoding.ids

        if add_special_tokens:
            ids = [self.special_tokens["<bos>"]] + ids + [self.special_tokens["<eos>"]]

        if max_length:
            ids = ids[:max_length]

        return ids

    def decode(self, ids: List[int], skip_special_tokens: bool = True) -> str:
        """Decode token IDs back to text."""
        if hasattr(self, "_use_hf") and self._use_hf:
            return self._hf_tokenizer.decode(ids, skip_special_tokens=skip_special_tokens)

        if self._tokenizer is None:
            raise RuntimeError("Tokenizer not initialized.")

        if skip_special_tokens:
            special_ids = set(self.special_tokens.values())
            ids = [i for i in ids if i not in special_ids]

        return self._tokenizer.decode(ids)

    def encode_code(
        self,
        code: str,
        language: str = "python",
        task: str = "gen",
        max_length: Optional[int] = None,
    ) -> List[int]:
        """
        Encode code with language and task context tokens.
        Example output: [<bos>, <task:gen>, <lang:py>, ...code tokens..., <eos>]
        """
        lang_map = {
            "python": "<lang:py>", "py": "<lang:py>",
            "javascript": "<lang:js>", "js": "<lang:js>",
            "typescript": "<lang:ts>", "ts": "<lang:ts>",
            "cpp": "<lang:cpp>", "c++": "<lang:cpp>",
            "java": "<lang:java>",
            "go": "<lang:go>", "golang": "<lang:go>",
            "rust": "<lang:rs>", "rs": "<lang:rs>",
        }
        task_map = {
            "gen": "<task:gen>", "generate": "<task:gen>",
            "fix": "<task:fix>", "debug": "<task:fix>",
            "explain": "<task:explain>",
            "optimize": "<task:optimize>", "refactor": "<task:optimize>",
        }

        lang_token = lang_map.get(language.lower(), "<lang:py>")
        task_token = task_map.get(task.lower(), "<task:gen>")

        prefix = f"{task_token} {lang_token} "
        full_text = prefix + code

        return self.encode(full_text, add_special_tokens=True, max_length=max_length)

    def save(self, path: str):
        """Save tokenizer to directory."""
        os.makedirs(path, exist_ok=True)

        if hasattr(self, "_use_hf") and self._use_hf:
            self._hf_tokenizer.save_pretrained(path)
        elif self._tokenizer is not None:
            self._tokenizer.save(os.path.join(path, "tokenizer.json"))

        # Save config
        with open(os.path.join(path, "tokenizer_config.json"), "w") as f:
            json.dump({
                "vocab_size": self.vocab_size,
                "special_tokens": self.special_tokens,
                "model_type": "shulker_bpe",
            }, f, indent=2)

    @property
    def pad_token_id(self) -> int:
        return self.special_tokens["<pad>"]

    @property
    def bos_token_id(self) -> int:
        return self.special_tokens["<bos>"]

    @property
    def eos_token_id(self) -> int:
        return self.special_tokens["<eos>"]

    def __len__(self) -> int:
        return self.vocab_size