Run this model with HF Jobs

Run OpenTensorLab/Qwen4-35B-A3B-GPTQ on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/OpenTensorLab/Qwen4-35B-A3B-GPTQ. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/OpenTensorLab/Qwen4-35B-A3B-GPTQ on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/OpenTensorLab/Qwen4-35B-A3B-GPTQ. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
File size: 14,766 Bytes
fb012f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
"""Tokenizer used for the Qwen4 chat encoding protocol."""

from __future__ import annotations

import logging
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Literal, cast

import tiktoken
from tiktoken.load import load_tiktoken_bpe
from tokenizers import AddedToken
from transformers.convert_slow_tokenizer import bytes_to_unicode
from transformers.tokenization_utils import PreTrainedTokenizer

from .encoding_qwen4 import Qwen4ChatEncoder

logger = logging.getLogger(__name__)

VOCAB_FILES_NAMES = {"vocab_file": "tiktoken.model"}

class Qwen4Tokenizer(PreTrainedTokenizer):
    """Qwen3.8 BPE plus Qwen4's Python-rendered message encoding protocol."""

    vocab_files_names = VOCAB_FILES_NAMES
    model_input_names = ("input_ids", "attention_mask")

    # 248044 base tokens + 276 special/reserved slots = config vocab_size.
    num_reserved_special_tokens = 276

    pat_str = (
        r"(?i:'s|'t|'re|'ve|'m|'ll|'d)"
        r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+"
        r"|\p{N}"
        r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*"
        r"|\s*[\r\n]+"
        r"|\s+(?!\S)"
        r"|\s+"
    )

    def __init__(

        self,

        vocab_file: str,

        bos_token: str | AddedToken | None = None,

        eos_token: str | AddedToken | None = "<|im_end|>",

        unk_token: str | AddedToken | None = None,

        pad_token: str | AddedToken | None = "<|endoftext|>",

        additional_special_tokens: list[str] | None = None,

        added_tokens_decoder: dict | None = None,

        **kwargs,

    ):
        if not os.path.isfile(vocab_file):
            raise ValueError(f"missing vocabulary file: {vocab_file}")

        known_specials: dict[int, str] = {}
        for token_id, token in (added_tokens_decoder or {}).items():
            content = token.content if hasattr(token, "content") else str(token)
            known_specials[int(token_id)] = content

        self.vocab_file = vocab_file
        mergeable_ranks = load_tiktoken_bpe(vocab_file)
        self.num_base_tokens = len(mergeable_ranks)
        first_special = self.num_base_tokens
        final_vocab_size = first_special + self.num_reserved_special_tokens
        self.special_tokens: dict[str, int] = {
            known_specials.get(token_id, f"<|reserved_token_{token_id}|>"): token_id
            for token_id in range(first_special, final_vocab_size)
        }

        self.model = tiktoken.Encoding(
            name=Path(vocab_file).name,
            pat_str=self.pat_str,
            mergeable_ranks=mergeable_ranks,
            special_tokens=self.special_tokens,
        )
        self.n_words = self.model.n_vocab
        if self.n_words != 248320:
            # hardcoded
            raise ValueError(f"unexpected Qwen4 vocabulary size: {self.n_words}")

        self.bos_id = self.special_tokens.get(str(bos_token)) if bos_token is not None else None
        self.eos_id = self.special_tokens.get(str(eos_token)) if eos_token is not None else None
        self.pad_id = self.special_tokens.get(str(pad_token)) if pad_token is not None else None
        self.unk_id = self.special_tokens.get(str(unk_token)) if unk_token is not None else None

        self.byte_encoder = bytes_to_unicode()
        self.byte_decoder = {value: key for key, value in self.byte_encoder.items()}
        self.decoder: dict[int, str] = {}
        for token_id in range(self.n_words):
            raw = self.model.decode_single_token_bytes(token_id)
            self.decoder[token_id] = "".join(self.byte_encoder[byte] for byte in raw)
        self.encoder = {token: token_id for token_id, token in self.decoder.items()}

        super().__init__(
            bos_token=bos_token,
            eos_token=eos_token,
            unk_token=unk_token,
            pad_token=pad_token,
            additional_special_tokens=additional_special_tokens,
            added_tokens_decoder=added_tokens_decoder,
            **kwargs,
        )
        self.all_special_ids_set = set(self.all_special_ids)

    def init_xgrammar(self) -> tuple[Any, list[int]]:
        """Build XGrammar's TokenizerInfo straight from the tiktoken ranks.



        SGLang's ``XGrammarGrammarBackend`` calls this hook when the tokenizer

        defines it, and falls back to ``TokenizerInfo.from_huggingface`` otherwise.

        That fallback is wrong for us: ``get_vocab`` deliberately returns the

        GPT-2 byte-escaped surface forms (``byte_encoder``, needed for

        ``PreTrainedTokenizer`` compatibility), so XGrammar reads ``0xA1`` as the

        two-character string ``"\u00c2\u00a1"`` and re-encodes it to ``b"\xc2\xa1"``.

        It silently mis-builds every grammar mask; the model then samples a token the

        grammar rejects and ``accept_token`` raises mid-generation.



        Handing XGrammar the raw tiktoken byte strings avoids the round trip.

        Mirrors ``sglang/srt/tokenizer/tiktoken_tokenizer.py``.

        """
        from xgrammar import TokenizerInfo

        token_items = sorted(
            {**self.model._mergeable_ranks, **self.model._special_tokens}.items(),
            key=lambda item: item[1],
        )
        token_ids = [token_id for _, token_id in token_items]
        if token_ids != list(range(self.n_words)):
            raise ValueError("Qwen4 vocabulary token IDs must be contiguous")

        encoded_vocab = [token for token, _ in token_items]
        # XGrammar's raw-vocab convention reads a leading b"\x00" as "this is one of
        # my own special tokens", so the byte token b"\x00" (id 188)
        # lands in ``special_token_ids`` and gets masked out. Leave it that way. An
        # earlier revision renamed the slot to a placeholder string to keep
        # ``special_token_ids`` empty, but a placeholder is ordinary *text*: measured
        # against {"type": "string"} after the opening quote, the mask then allowed
        # id 188 and ``accept_token(188)`` succeeded, so the grammar believed it had
        # emitted text while the output carried a bare NUL and JSON parsing failed.
        # Masking the token only costs us NUL bytes inside grammar-constrained output.
        nul_prefixed = {
            token_id
            for token, token_id in token_items
            if isinstance(token, bytes) and token.startswith(b"\x00")
        }

        override_stop_tokens = list(
            dict.fromkeys(
                token_id
                for token_id in (self.pad_token_id, self.eos_token_id)
                if token_id is not None
            )
        )
        tokenizer_info = TokenizerInfo(
            encoded_vocab, stop_token_ids=override_stop_tokens
        )
        if tokenizer_info.vocab_size != self.n_words:
            raise ValueError(
                f"XGrammar vocabulary size mismatch: {tokenizer_info.vocab_size} "
                f"!= {self.n_words}"
            )
        # Only the b"\x00"-prefixed byte tokens may be reclassified as XGrammar
        # specials; anything else means XGrammar reinterpreted a token of ours, which
        # is the silent mask corruption this hook exists to prevent.
        unexpected = sorted(set(tokenizer_info.special_token_ids) - nul_prefixed)
        if unexpected:
            raise ValueError(f"Unexpected XGrammar special token IDs: {unexpected}")
        return tokenizer_info, override_stop_tokens

    def _encode_text_piece(self, text: str, *, allow_special: bool) -> list[int]:
        if allow_special:
            return self.model.encode(text, allowed_special="all")
        else:
            return self.model.encode(text, disallowed_special=())

    def tokenize_segment(self, text: str, *, allow_special: bool = False) -> list[int]:
        if not isinstance(text, str):
            raise TypeError(f"text must be str, got {type(text).__name__}")
        return self._encode_text_piece(text, allow_special=allow_special)

    def encode(self, text: str, allow_special_tokens: bool = True, **kwargs) -> list[int]:
        if not kwargs:
            return self._encode_text_piece(text, allow_special=allow_special_tokens)
        if allow_special_tokens:
            return super().encode(text, **kwargs)

        # Encode literal text first; HF then handles padding, truncation and tensors.
        ids = self._encode_text_piece(text, allow_special=False)
        text_pair = kwargs.pop("text_pair", None)
        pair_ids = None
        if text_pair is not None:
            pair_ids = self._encode_text_piece(text_pair, allow_special=False)

        kwargs.setdefault("truncation", None)  # Match HF encode's default.
        return self.prepare_for_model(
            ids, pair_ids=pair_ids, prepend_batch_axis=True, **kwargs
        )["input_ids"]

    def decode(self, token_ids: int | list[int], **kwargs) -> str:
        if kwargs:
            return super().decode(token_ids, **kwargs)
        values = [token_ids] if isinstance(token_ids, int) else token_ids
        return self.model.decode(cast(list[int], values))

    @property
    def vocab_size(self) -> int:
        return self.n_words

    def get_vocab(self) -> dict[str, int]:
        return dict(self.encoder)

    def _tokenize(self, text: str, **kwargs) -> list[str]:
        return [self.decoder[token_id] for token_id in self._encode_text_piece(text, allow_special=True)]

    def _convert_token_to_id(self, token: str) -> int | None:
        return self.encoder.get(token, self.unk_id)

    def _convert_id_to_token(self, index: int) -> str | None:
        return self.decoder.get(index)

    def convert_tokens_to_string(self, tokens: list[str]) -> str:
        text = "".join(tokens)
        return bytearray(self.byte_decoder[character] for character in text).decode("utf-8", "replace")

    @staticmethod
    def clean_up_tokenization(out_string: str) -> str:
        return out_string

    def save_vocabulary(

        self,

        save_directory: str,

        filename_prefix: str | None = None,

    ) -> tuple[str]:
        if not os.path.isdir(save_directory):
            raise ValueError(f"vocabulary path must be a directory: {save_directory}")
        filename = (f"{filename_prefix}-" if filename_prefix else "") + "tiktoken.model"
        destination = os.path.join(save_directory, filename)
        if os.path.abspath(self.vocab_file) != os.path.abspath(destination):
            copyfile(self.vocab_file, destination)
        return (destination,)

    def _encode_chat_segments(self, segments):
        token_ids: list[int] = []
        for segment in segments:
            if segment.text:
                token_ids.extend(
                    self.tokenize_segment(segment.text, allow_special=segment.allow_special)
                )
        return token_ids

    @staticmethod
    def _is_batched_conversation(conversation: Any) -> bool:
        return bool(
            isinstance(conversation, (list, tuple))
            and conversation
            and isinstance(conversation[0], (list, tuple))
        )

    @staticmethod
    def _truncate(ids: list[int], truncation: bool, max_length: int | None) -> list[int]:
        return ids[:max_length] if truncation and max_length is not None else ids

    def _format_chat_token_output(

        self,

        encoded_inputs: list[list[int]],

        *,

        is_batched: bool,

        padding=False,

        truncation: bool = False,

        max_length: int | None = None,

        return_tensors=None,

        return_dict: bool = False,

    ):
        encoded_inputs = [
            self._truncate(ids, truncation=truncation, max_length=max_length)
            for ids in encoded_inputs
        ]
        needs_batch = is_batched or bool(padding) or return_tensors is not None or return_dict
        if needs_batch:
            features = [
                {"input_ids": ids, "attention_mask": [1] * len(ids)}
                for ids in encoded_inputs
            ]
            batch = self.pad(
                features,
                padding=padding,
                max_length=max_length if padding else None,
                return_attention_mask=True,
                return_tensors=return_tensors,
            )
            if return_dict:
                result = batch
            elif is_batched or return_tensors is not None:
                result = batch["input_ids"]
            else:
                result = batch["input_ids"][0]
        else:
            result = encoded_inputs[0]
        
        return result

    def apply_chat_template(

        self,

        conversation,

        tools: list[dict] | None = None,

        add_generation_prompt: bool = True,

        tokenize: bool = False,

        padding=False,

        truncation: bool = False,

        max_length: int | None = None,

        return_tensors=None,

        return_dict: bool = False,

        enable_thinking: bool | None = None,

        reasoning_effort: Literal["xhigh", "high", "low", "off"] | None = None,

        preserve_thinking: bool | None = True,

        **kwargs,

    ):
        """Render and tokenize a conversation."""
        if kwargs:
            unknown = ", ".join(sorted(kwargs))
            logger.warning("Ignoring unsupported apply_chat_template arguments: %s", unknown)
        
        is_batched = self._is_batched_conversation(conversation)
        conversations = list(conversation) if is_batched else [conversation]
        encoder = Qwen4ChatEncoder(self)
        segment_batches = [
            encoder.encode(
                list(messages),
                tools=tools,
                add_generation_prompt=add_generation_prompt,
                enable_thinking=enable_thinking,
                reasoning_effort=reasoning_effort,
                preserve_thinking=preserve_thinking,
            )
            for messages in conversations
        ]
        if not tokenize:
            # this is the not the expected way to use this tokenizer
            rendered = ["".join(segment.text for segment in segments) for segments in segment_batches]
            return rendered if is_batched else rendered[0]

        encoded_inputs = [self._encode_chat_segments(segments) for segments in segment_batches]
        return self._format_chat_token_output(
            encoded_inputs,
            is_batched=is_batched,
            padding=padding,
            truncation=truncation,
            max_length=max_length,
            return_tensors=return_tensors,
            return_dict=return_dict,
        )