forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_chat_template.py
More file actions
276 lines (200 loc) · 9.58 KB
/
Copy pathtest_chat_template.py
File metadata and controls
276 lines (200 loc) · 9.58 KB
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
"""Tests for chat-template hardening (v0.36.0 Part C).
Replaces sft.py's silent ``f"{role}: {content}"`` fallback (which produced
garbage training data on tokenizers without ``chat_template``) with a hard
error and an explicit ``DataConfig.chat_template`` field for overrides.
"""
from __future__ import annotations
import pytest
# ---------------------------------------------------------------------------
# Schema field
# ---------------------------------------------------------------------------
class TestSchemaField:
def test_chat_template_default_none(self):
from soup_cli.config.schema import DataConfig
cfg = DataConfig(train="data.jsonl")
assert cfg.chat_template is None
def test_chat_template_accepts_registered_name(self):
from soup_cli.config.schema import DataConfig
cfg = DataConfig(train="data.jsonl", chat_template="chatml")
assert cfg.chat_template == "chatml"
def test_chat_template_accepts_jinja_string(self):
from soup_cli.config.schema import DataConfig
jinja = "{% for m in messages %}{{ m.role }}: {{ m.content }}{% endfor %}"
cfg = DataConfig(train="data.jsonl", chat_template=jinja)
assert cfg.chat_template == jinja
def test_chat_template_rejects_null_byte(self):
from soup_cli.config.schema import DataConfig
with pytest.raises(ValueError):
DataConfig(train="data.jsonl", chat_template="bad\x00template")
def test_chat_template_rejects_oversize(self):
from soup_cli.config.schema import DataConfig
# Cap at 64KB to prevent template-injection DoS payloads.
with pytest.raises(ValueError):
DataConfig(train="data.jsonl", chat_template="x" * 100_000)
# ---------------------------------------------------------------------------
# Registry
# ---------------------------------------------------------------------------
class TestRegistry:
def test_lists_known_templates(self):
from soup_cli.data.chat_templates import list_template_names
names = list_template_names()
# At minimum: the 7 declared in v0.36.0 Part C.
for required in (
"chatml", "llama3", "qwen2.5", "gemma3", "phi4", "deepseek-r1", "mistral",
):
assert required in names
def test_chatml_is_jinja_string(self):
from soup_cli.data.chat_templates import get_template
tmpl = get_template("chatml")
assert isinstance(tmpl, str)
assert "{%" in tmpl
# ChatML signature markers.
assert "<|im_start|>" in tmpl
assert "<|im_end|>" in tmpl
def test_unknown_name_raises(self):
from soup_cli.data.chat_templates import get_template
with pytest.raises(KeyError, match="not registered"):
get_template("not-a-real-template")
def test_resolve_returns_jinja_for_known_name(self):
from soup_cli.data.chat_templates import resolve_chat_template
out = resolve_chat_template("chatml")
assert "<|im_start|>" in out
def test_resolve_returns_passthrough_for_jinja(self):
from soup_cli.data.chat_templates import resolve_chat_template
jinja = "{% for m in messages %}<x>{{ m.content }}</x>{% endfor %}"
out = resolve_chat_template(jinja)
assert out == jinja
def test_resolve_none_returns_none(self):
from soup_cli.data.chat_templates import resolve_chat_template
assert resolve_chat_template(None) is None
def test_resolve_empty_returns_none(self):
from soup_cli.data.chat_templates import resolve_chat_template
assert resolve_chat_template("") is None
def test_resolve_unknown_name_raises(self):
"""Public surface: bad name through resolve_chat_template."""
from soup_cli.data.chat_templates import resolve_chat_template
with pytest.raises(KeyError, match="not registered"):
resolve_chat_template("not-a-real-template")
# ---------------------------------------------------------------------------
# Schema rejects Jinja directives that touch the filesystem
# ---------------------------------------------------------------------------
class TestJinjaDirectiveBlocking:
@pytest.mark.parametrize(
"bad",
[
"{% include 'config.yaml' %}",
"{%- include 'config.yaml' %}",
"{% import 'os' as os %}",
"{% from 'os' import system %}",
"{% macro evil() %}{% endmacro %}",
"{% extends 'base.j2' %}",
],
)
def test_schema_rejects_filesystem_directives(self, bad):
from soup_cli.config.schema import DataConfig
with pytest.raises(ValueError, match="directive"):
DataConfig(train="data.jsonl", chat_template=bad)
def test_schema_accepts_for_loop(self):
"""Standard control flow must still work."""
from soup_cli.config.schema import DataConfig
ok = "{% for m in messages %}{{ m.content }}{% endfor %}"
cfg = DataConfig(train="data.jsonl", chat_template=ok)
assert cfg.chat_template == ok
def test_schema_accepts_if_else(self):
from soup_cli.config.schema import DataConfig
ok = "{% if true %}x{% else %}y{% endif %}"
cfg = DataConfig(train="data.jsonl", chat_template=ok)
assert cfg.chat_template == ok
def test_schema_empty_string_normalised_to_none(self):
from soup_cli.config.schema import DataConfig
cfg = DataConfig(train="data.jsonl", chat_template="")
assert cfg.chat_template is None
# ---------------------------------------------------------------------------
# apply_chat_template_override
# ---------------------------------------------------------------------------
class TestApplyOverride:
def test_sets_tokenizer_chat_template(self):
from soup_cli.data.chat_templates import apply_chat_template_override
class _T:
chat_template = None
tok = _T()
apply_chat_template_override(tok, "chatml")
assert tok.chat_template is not None
assert "<|im_start|>" in tok.chat_template
def test_none_leaves_tokenizer_alone(self):
from soup_cli.data.chat_templates import apply_chat_template_override
class _T:
chat_template = "existing"
tok = _T()
apply_chat_template_override(tok, None)
assert tok.chat_template == "existing"
def test_empty_leaves_tokenizer_alone(self):
from soup_cli.data.chat_templates import apply_chat_template_override
class _T:
chat_template = "existing"
tok = _T()
apply_chat_template_override(tok, "")
assert tok.chat_template == "existing"
def test_override_emits_save_pretrained_warning(self):
"""v0.36.0 review fix: warn when overriding so users know push will
persist the new template into tokenizer_config.json."""
from io import StringIO
from rich.console import Console
from soup_cli.data.chat_templates import apply_chat_template_override
class _T:
chat_template = None
buf = StringIO()
console = Console(file=buf, force_terminal=False)
applied = apply_chat_template_override(_T(), "chatml", console=console)
assert applied is True
assert "save_pretrained" in buf.getvalue() or "soup push" in buf.getvalue()
def test_override_returns_false_when_noop(self):
from soup_cli.data.chat_templates import apply_chat_template_override
class _T:
chat_template = "existing"
applied = apply_chat_template_override(_T(), None)
assert applied is False
# ---------------------------------------------------------------------------
# Hard error in sft_format when no chat_template AND no override
# ---------------------------------------------------------------------------
class TestHardError:
def test_no_template_no_override_raises(self):
"""The legacy `f"{role}: {content}"` silent fallback is now an error."""
from soup_cli.config.schema import DataConfig
from soup_cli.data.sft_format import build_format_row
class _NoTemplate:
chat_template = None
def apply_chat_template(self, *args, **kwargs):
raise AssertionError("must not be reached")
cfg = DataConfig(
train="data.jsonl",
train_on_responses_only=False, # legacy path
train_on_messages_with_train_field=False,
chat_template=None,
)
fn = build_format_row(_NoTemplate(), cfg, console=None)
with pytest.raises(ValueError, match="chat_template"):
fn({"messages": [{"role": "user", "content": "hi"}]})
def test_override_applies_to_legacy_path(self):
"""When user passes chat_template override, build_format_row works."""
from soup_cli.config.schema import DataConfig
from soup_cli.data.sft_format import build_format_row
class _T:
chat_template = None
applied = []
def apply_chat_template(
self, messages, tokenize=False, add_generation_prompt=False, **kwargs
):
self.applied.append(messages)
return "RENDERED"
tok = _T()
cfg = DataConfig(
train="data.jsonl",
train_on_responses_only=False,
train_on_messages_with_train_field=False,
chat_template="chatml",
)
fn = build_format_row(tok, cfg, console=None)
out = fn({"messages": [{"role": "user", "content": "hi"}]})
assert out["text"] == "RENDERED"
assert tok.chat_template is not None # override was applied