File size: 8,170 Bytes
53f0cc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Component 2: Custom code tokenizer for Python and JavaScript.

This tokenizer is code-aware:
- It preserves indentation structure using explicit tokens.
- It keeps newline boundaries using a newline token.
- It treats code operators and brackets as separate units.
- It supports prompt+code style training samples.
"""

from __future__ import annotations

import json
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Dict, Iterable, List, Optional

from tokenizers import Regex, Tokenizer
from tokenizers.decoders import BPEDecoder
from tokenizers.models import BPE
from tokenizers.normalizers import NFKC, Sequence as NormalizerSequence
from tokenizers.pre_tokenizers import Metaspace, Sequence as PreTokenizerSequence, Split
from tokenizers.processors import TemplateProcessing
from tokenizers.trainers import BpeTrainer


@dataclass
class CodeTokenizerConfig:
    # Vocabulary size controls how many distinct tokens the tokenizer learns.
    vocab_size: int = 50_000
    # Minimum frequency filters very rare fragments.
    min_frequency: int = 2
    # Sequence length is used later by training/inference components.
    model_max_length: int = 2048
    # Indent width is used to normalize tabs and format indentation markers.
    indent_width: int = 4
    # These tokens are required for code generation workflows.
    special_tokens: List[str] = None  # type: ignore[assignment]

    def __post_init__(self) -> None:
        if self.special_tokens is None:
            self.special_tokens = [
                "<PAD>",
                "<UNK>",
                "<BOS>",
                "<EOS>",
                "<NL>",
                "<INDENT>",
                "<DEDENT>",
                "<PROMPT>",
                "<CODE>",
                "<PYTHON>",
                "<JAVASCRIPT>",
            ]


class CodeTokenizer:
    # This wrapper owns one HF Tokenizers object plus code-specific helpers.

    def __init__(self, config: Optional[CodeTokenizerConfig] = None) -> None:
        self.config = config or CodeTokenizerConfig()
        self.tokenizer: Optional[Tokenizer] = None
        self.special_token_ids: Dict[str, int] = {}

    def _build_base_tokenizer(self) -> Tokenizer:
        """
        Creates a BPE tokenizer with code-oriented pre-tokenization rules.
        """
        tokenizer = Tokenizer(BPE(unk_token="<UNK>"))
        tokenizer.normalizer = NormalizerSequence([NFKC()])

        # Split multi-character operators first so they are not broken apart.
        multi_op = Regex(
            r"(==|!=|<=|>=|:=|->|=>|\+\+|--|\+=|-=|\*=|/=|//=|%=|\*\*|&&|\|\||<<|>>)"
        )
        # Split common delimiters used heavily in code.
        punct = Regex(r"([()\[\]{}.,:;])")

        tokenizer.pre_tokenizer = PreTokenizerSequence(
            [
                Split(multi_op, behavior="isolated"),
                Split(punct, behavior="isolated"),
                Metaspace(replacement="_", prepend_scheme="always", split=True),
            ]
        )
        tokenizer.decoder = BPEDecoder()
        return tokenizer

    def train(self, text_iterator: Iterable[str]) -> None:
        """
        Trains the tokenizer from a stream of preformatted text samples.
        """
        tokenizer = self._build_base_tokenizer()
        trainer = BpeTrainer(
            vocab_size=self.config.vocab_size,
            min_frequency=self.config.min_frequency,
            special_tokens=self.config.special_tokens,
            show_progress=True,
        )
        tokenizer.train_from_iterator(text_iterator, trainer=trainer, length=None)

        # Add BOS/EOS automatically around each single sequence.
        bos_id = tokenizer.token_to_id("<BOS>")
        eos_id = tokenizer.token_to_id("<EOS>")
        if bos_id is None or eos_id is None:
            raise RuntimeError("Tokenizer training failed to register BOS/EOS tokens.")
        tokenizer.post_processor = TemplateProcessing(
            single="<BOS> $A <EOS>",
            special_tokens=[("<BOS>", bos_id), ("<EOS>", eos_id)],
        )

        self.tokenizer = tokenizer
        self.special_token_ids = {
            token: tokenizer.token_to_id(token) for token in self.config.special_tokens
        }

    def save(self, output_dir: str) -> None:
        """
        Saves tokenizer JSON and config so all other components can reuse it.
        """
        if self.tokenizer is None:
            raise RuntimeError("Cannot save tokenizer before training or loading it.")
        out = Path(output_dir)
        out.mkdir(parents=True, exist_ok=True)
        self.tokenizer.save(str(out / "tokenizer.json"))
        with (out / "tokenizer_config.json").open("w", encoding="utf-8") as f:
            json.dump(asdict(self.config), f, indent=2)

    @classmethod
    def load(cls, tokenizer_dir: str) -> "CodeTokenizer":
        """
        Loads tokenizer from disk.
        """
        base = Path(tokenizer_dir)
        cfg_path = base / "tokenizer_config.json"
        tok_path = base / "tokenizer.json"
        if not cfg_path.exists() or not tok_path.exists():
            raise FileNotFoundError(
                f"Missing tokenizer files in {tokenizer_dir}. "
                "Expected tokenizer.json and tokenizer_config.json."
            )
        with cfg_path.open("r", encoding="utf-8") as f:
            cfg_data = json.load(f)
        config = CodeTokenizerConfig(**cfg_data)
        obj = cls(config=config)
        obj.tokenizer = Tokenizer.from_file(str(tok_path))
        obj.special_token_ids = {
            token: obj.tokenizer.token_to_id(token) for token in obj.config.special_tokens
        }
        return obj

    def encode(self, text: str) -> List[int]:
        """
        Encodes one preformatted text sample to token IDs.
        """
        if self.tokenizer is None:
            raise RuntimeError("Tokenizer is not ready. Train or load it first.")
        return self.tokenizer.encode(text).ids

    def decode(self, token_ids: List[int]) -> str:
        """
        Decodes token IDs to text.
        """
        if self.tokenizer is None:
            raise RuntimeError("Tokenizer is not ready. Train or load it first.")
        return self.tokenizer.decode(token_ids, skip_special_tokens=False)

    def format_training_sample(self, prompt: str, code: str, language: str) -> str:
        """
        Converts prompt + code into one structured training text sequence.
        """
        lang_token = "<PYTHON>" if language.lower() == "python" else "<JAVASCRIPT>"
        prompt_text = self._normalize_text(prompt)
        code_text = self._code_to_structure_tokens(code)
        return f"<PROMPT> {lang_token} {prompt_text} <CODE> {code_text}"

    def _normalize_text(self, text: str) -> str:
        """
        Normalizes regular text by cleaning newlines.
        """
        return text.replace("\r\n", "\n").replace("\r", "\n").strip()

    def _code_to_structure_tokens(self, code: str) -> str:
        """
        Converts raw code into a string with explicit indentation and newline markers.
        """
        code = code.replace("\r\n", "\n").replace("\r", "\n").replace("\t", " " * self.config.indent_width)
        lines = code.split("\n")
        indent_stack: List[int] = [0]
        out_tokens: List[str] = []

        for raw_line in lines:
            # Keep blank lines as newline tokens so code structure is preserved.
            if raw_line.strip() == "":
                out_tokens.append("<NL>")
                continue

            current_indent = len(raw_line) - len(raw_line.lstrip(" "))
            line_content = raw_line.lstrip(" ")

            while current_indent < indent_stack[-1]:
                indent_stack.pop()
                out_tokens.append("<DEDENT>")

            while current_indent > indent_stack[-1]:
                indent_stack.append(current_indent)
                out_tokens.append("<INDENT>")

            out_tokens.append(line_content)
            out_tokens.append("<NL>")

        while len(indent_stack) > 1:
            indent_stack.pop()
            out_tokens.append("<DEDENT>")

        return " ".join(out_tokens).strip()