-
Notifications
You must be signed in to change notification settings - Fork 304
Expand file tree
/
Copy pathtest_mlx_trainer_internals.py
More file actions
2120 lines (1674 loc) · 72.2 KB
/
Copy pathtest_mlx_trainer_internals.py
File metadata and controls
2120 lines (1674 loc) · 72.2 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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Unsloth Zoo - Utilities for Unsloth
# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Deeper MLX component exercises: trainer, compile discovery,
cce backward, and quantization helpers, beyond just imports.
If a test fails, the failing component identifies the next gap.
"""
from __future__ import annotations
import dataclasses
import types
import pytest
import torch
@pytest.fixture(autouse=True, scope="module")
def _install_shim():
import sys
shim_prefixes = ("mlx", "mlx_lm", "mlx_vlm")
real_mlx_modules = {
name: module
for name, module in sys.modules.items()
if any(name == prefix or name.startswith(f"{prefix}.") for prefix in shim_prefixes)
}
from mlx_simulation import simulate_mlx_on_torch
from mlx_simulation.mlx_stub import _MLXFinder
simulate_mlx_on_torch()
for name in list(sys.modules):
if name == "unsloth_zoo.mlx" or name.startswith("unsloth_zoo.mlx."):
sys.modules.pop(name, None)
yield
for name in list(sys.modules):
if (
name == "unsloth_zoo.mlx" or name.startswith("unsloth_zoo.mlx.")
or any(name == prefix or name.startswith(f"{prefix}.") for prefix in shim_prefixes)
):
sys.modules.pop(name, None)
sys.meta_path[:] = [
finder for finder in sys.meta_path
if not isinstance(finder, _MLXFinder)
]
sys.modules.update(real_mlx_modules)
# ---------------------------------------------------------------------------
# 1. MLXTrainingConfig: full surface check.
# ---------------------------------------------------------------------------
def test_mlx_training_config_is_dataclass_with_all_fields():
from unsloth_zoo.mlx.trainer import MLXTrainingConfig
assert dataclasses.is_dataclass(MLXTrainingConfig)
field_names = [f.name for f in dataclasses.fields(MLXTrainingConfig)]
fields = set(field_names)
# Required SFT-compat fields
for must_have in (
"per_device_train_batch_size",
"gradient_accumulation_steps",
"max_steps",
"warmup_ratio",
"learning_rate",
"lr_scheduler_type",
"optim",
"weight_decay",
"max_grad_norm",
"max_grad_leaf_norm",
"seed",
"logging_steps",
"output_dir",
"max_seq_length",
"use_cce",
"compile",
"gradient_checkpointing",
"dataset_order",
"preserve_dataset_order",
"completion_only_loss",
"assistant_only_loss",
):
assert must_have in fields, f"missing field: {must_have}"
# dataset_text_field follows the eval block; newer eval knobs (eg load_best_model_at_end)
# may sit between them, so assert relative order rather than strict adjacency.
assert field_names.index("dataset_text_field") > field_names.index("eval_steps")
assert field_names[field_names.index("append_eos") + 1] == "train_on_completions"
assert field_names.index("per_device_eval_batch_size") > field_names.index("vlm_chat_template")
assert field_names.index("image_size") > field_names.index("vlm_chat_template")
def test_mlx_training_config_exposes_completion_only_loss():
from unsloth_zoo.mlx.trainer import (
MLXTrainingConfig,
_text_assistant_only_loss_arg,
_text_completion_only_loss_arg,
)
assert _text_completion_only_loss_arg(
MLXTrainingConfig(completion_only_loss=False)
) is False
assert _text_completion_only_loss_arg(
MLXTrainingConfig(completion_only_loss=True)
) is True
assert _text_completion_only_loss_arg(
MLXTrainingConfig(train_on_completions=True)
) is True
assert _text_assistant_only_loss_arg(
MLXTrainingConfig(assistant_only_loss=True)
) is True
assert _text_assistant_only_loss_arg(MLXTrainingConfig()) is False
def test_mlx_trainer_distributed_defaults_world_size_one():
from unsloth_zoo.mlx.trainer import MLXTrainer, MLXTrainingConfig
class DummyModel:
def trainable_parameters(self): return {}
trainer = MLXTrainer(DummyModel(), None, [], args=MLXTrainingConfig())
assert trainer._distributed_initialized is False
assert trainer.distributed_rank == 0
assert trainer.distributed_world_size == 1
assert trainer.is_main_process is True
assert trainer._distributed_result_fields() == {
"distributed_world_size": 1,
"distributed_rank": 0,
"distributed_is_main_process": True,
}
def test_mlx_trainer_distributed_state_uses_cached_group(monkeypatch):
import unsloth_zoo.mlx.trainer as trainer_mod
class FakeWorld:
def rank(self): return 1
def size(self): return 2
calls = []
def fake_init():
calls.append("init")
return FakeWorld()
monkeypatch.setattr(trainer_mod.mx.distributed, "init", fake_init)
trainer = trainer_mod.MLXTrainer.__new__(trainer_mod.MLXTrainer)
assert trainer.distributed_world is trainer.distributed_world
assert calls == ["init"]
assert trainer.distributed_rank == 1
assert trainer.distributed_world_size == 2
assert trainer.is_main_process is False
assert trainer._distributed_result_fields() == {
"distributed_world_size": 2,
"distributed_rank": 1,
"distributed_is_main_process": False,
}
@pytest.mark.parametrize("accepts_backend", [True, False])
def test_mlx_trainer_distributed_state_selects_jaccl_backend(monkeypatch, accepts_backend):
import unsloth_zoo.mlx.trainer as trainer_mod
class FakeWorld:
def rank(self): return 1
def size(self): return 2
calls = []
def fake_init(**kwargs):
calls.append(kwargs)
if kwargs and not accepts_backend:
raise TypeError("init() got an unexpected keyword argument 'backend'")
return FakeWorld()
monkeypatch.setenv("MLX_JACCL_COORDINATOR", "127.0.0.1:12345")
monkeypatch.setenv("MLX_IBV_DEVICES", "/tmp/mlx-devices.json")
monkeypatch.setattr(trainer_mod.mx.distributed, "init", fake_init)
trainer = trainer_mod.MLXTrainer.__new__(trainer_mod.MLXTrainer)
assert trainer.distributed_world is trainer.distributed_world
assert trainer.distributed_rank == 1
assert trainer.distributed_world_size == 2
if accepts_backend:
assert calls == [{"backend": "jaccl"}]
else:
assert calls == [{"backend": "jaccl"}, {}]
def test_distributed_text_batches_use_tokenizer_pad_without_global_rng():
import numpy as np
from unsloth_zoo.mlx.utils import _create_distributed_text_batches
class FakeWorld:
def rank(self): return 0
def size(self): return 2
class Tokenizer:
pad_token_id = 99
# Shortest row has 2 tokens so it survives the sub-two-token filter while
# still being padded out to the block length, exercising the pad id path.
dataset = [([5, 6], 0), ([7, 8, 9], 0)]
np.random.seed(123)
expected = np.random.random(3)
np.random.seed(123)
batches = _create_distributed_text_batches(
dataset,
batch_size=2,
max_seq_length=8,
seed=7,
comm_group=FakeWorld(),
tokenizer=Tokenizer(),
)
assert np.random.random(3) == pytest.approx(expected)
rows = batches[0][0].tolist()
assert rows[0][:2] == [5, 6]
assert rows[0][2:] == [99] * (len(rows[0]) - 2)
def test_distributed_text_batches_filter_sub_two_token_rows():
from unsloth_zoo.mlx.utils import _create_distributed_text_batches
class FakeWorld:
def rank(self): return 0
def size(self): return 2
class Tokenizer:
pad_token_id = 99
# The length-1 row (token 5) has no causal target and must be filtered, so
# every batch is drawn only from the length-2 row (tokens 6, 7).
dataset = [([5], 0), ([6, 7], 0)]
batches = _create_distributed_text_batches(
dataset,
batch_size=2,
max_seq_length=8,
num_batches=3,
seed=7,
comm_group=FakeWorld(),
tokenizer=Tokenizer(),
)
assert len(batches) == 3
for batch in batches:
for row in batch[0].tolist():
content = [tok for tok in row if tok != 99]
assert content == [6, 7]
def test_distributed_text_batches_use_token_length_not_cache_itemlen(monkeypatch):
# Regression: real mlx_lm CacheDataset.itemlen returns len(raw_row); for the
# {"text": ...} rows _prepare_dataset builds that is the dict key count (1),
# so an itemlen-based sub-two-token filter would drop every row and raise.
# The filter must measure the processed token length instead.
import sys
from unsloth_zoo.mlx.utils import _create_distributed_text_batches
class FakeWorld:
def rank(self): return 0
def size(self): return 2
class Tokenizer:
pad_token_id = 99
class CacheDataset:
def __init__(self, rows):
self._rows = rows
self._proc = {}
def __len__(self):
return len(self._rows)
def itemlen(self, idx):
# Matches real mlx_lm: length of the RAW row (dict key count == 1).
return len(self._rows[idx])
def __getitem__(self, idx):
if idx not in self._proc:
self._proc[idx] = (self._rows[idx]["ids"], 0)
return self._proc[idx]
monkeypatch.setattr(
sys.modules["mlx_lm.tuner.datasets"], "CacheDataset", CacheDataset
)
dataset = CacheDataset([{"ids": [5, 6]}, {"ids": [7, 8, 9]}])
# itemlen reports 1 for each row; an itemlen-based filter would drop both.
assert dataset.itemlen(0) == 1
batches = _create_distributed_text_batches(
dataset,
batch_size=2,
max_seq_length=8,
num_batches=2,
seed=7,
comm_group=FakeWorld(),
tokenizer=Tokenizer(),
)
assert len(batches) == 2
content = {
tuple(tok for tok in row if tok != 99)
for batch in batches
for row in batch[0].tolist()
}
# Rows survived the >=2-token filter (token length, not itemlen).
assert (5, 6) in content or (7, 8, 9) in content
@pytest.mark.parametrize("optim_name", ["adamw", "adam", "sgd", "adafactor"])
def test_mlx_training_config_each_optim(optim_name):
"""Every supported optim string constructs cleanly in config."""
from unsloth_zoo.mlx.trainer import MLXTrainingConfig
cfg = MLXTrainingConfig(optim=optim_name)
assert cfg.optim == optim_name
def test_trainer_drives_dynamic_lr_outside_optimizer_scheduler():
from unsloth_zoo.mlx.trainer import (
MLXTrainer,
MLXTrainingConfig,
)
trainer = MLXTrainer.__new__(MLXTrainer)
trainer.args = MLXTrainingConfig(
learning_rate=5e-5,
lr_scheduler_type="linear",
warmup_steps=5,
)
schedule = trainer._build_schedule(total_steps=8)
def value_at(step):
value = schedule(step)
return value.item() if hasattr(value, "item") else float(value)
assert value_at(0) == pytest.approx(0.0)
assert value_at(1) > value_at(0)
assert value_at(4) < trainer.args.learning_rate
assert value_at(5) == pytest.approx(trainer.args.learning_rate)
trainer.model = object()
optimizer = trainer._build_optimizer(total_steps=8)
assert not callable(optimizer.learning_rate)
first_lr = float(optimizer.learning_rate)
trainer._set_optimizer_lr_for_step(optimizer, 1)
second_lr = float(optimizer.learning_rate)
assert second_lr > first_lr
ratio_trainer = MLXTrainer.__new__(MLXTrainer)
ratio_trainer.args = MLXTrainingConfig(
learning_rate=5e-5,
lr_scheduler_type="linear",
warmup_ratio=0.1,
)
ratio_schedule = ratio_trainer._build_schedule(total_steps=8)
assert ratio_trainer._resolve_warmup_steps(total_steps=8) == 1
assert ratio_schedule(0).item() < ratio_trainer.args.learning_rate
assert ratio_schedule(1).item() == pytest.approx(
ratio_trainer.args.learning_rate,
)
copied_ratio_trainer = MLXTrainer.__new__(MLXTrainer)
copied_ratio_trainer.args = dataclasses.replace(
MLXTrainingConfig(learning_rate=5e-5, lr_scheduler_type="linear"),
warmup_ratio=0.1,
)
assert copied_ratio_trainer._resolve_warmup_steps(total_steps=100) == 10
explicit_default_trainer = MLXTrainer.__new__(MLXTrainer)
explicit_default_trainer.args = MLXTrainingConfig(
learning_rate=5e-5,
lr_scheduler_type="linear",
warmup_steps=5,
warmup_ratio=0.1,
)
assert explicit_default_trainer._resolve_warmup_steps(total_steps=8) == 5
clamped_trainer = MLXTrainer.__new__(MLXTrainer)
clamped_trainer.args = MLXTrainingConfig(
learning_rate=5e-5,
lr_scheduler_type="linear",
warmup_ratio=2.0,
)
assert clamped_trainer._resolve_warmup_steps(total_steps=8) == 8
# Explicit warmup_steps=0 must not disable a positive warmup_ratio (HF parity):
# a zero step count means "use the ratio", not "no warmup".
zero_steps_ratio_trainer = MLXTrainer.__new__(MLXTrainer)
zero_steps_ratio_trainer.args = MLXTrainingConfig(
learning_rate=5e-5,
lr_scheduler_type="linear",
warmup_steps=0,
warmup_ratio=0.1,
)
assert zero_steps_ratio_trainer._resolve_warmup_steps(total_steps=100) == 10
def test_adamw_weight_decay_uses_hf_bias_norm_filter():
from unsloth_zoo.mlx.trainer import MLXTrainer, MLXTrainingConfig
class DummyModel:
def trainable_parameters(self):
return {}
trainer = MLXTrainer.__new__(MLXTrainer)
trainer.model = DummyModel()
trainer.args = MLXTrainingConfig(
optim="adamw",
weight_decay=0.1,
)
optimizer = trainer._build_optimizer(total_steps=8)
assert trainer._manual_weight_decay == pytest.approx(0.1)
if hasattr(optimizer, "_kw"):
assert optimizer._kw["weight_decay"] == 0.0
assert MLXTrainer._should_apply_weight_decay("layers.0.mlp.down_proj.weight")
assert not MLXTrainer._should_apply_weight_decay("layers.0.mlp.down_proj.bias")
assert not MLXTrainer._should_apply_weight_decay("layers.0.input_layernorm.weight")
assert not MLXTrainer._should_apply_weight_decay("vision.blocks.0.norm1.weight")
@pytest.mark.parametrize("optim_name", ["muon", "lion"])
def test_decoupled_optimizers_use_hf_parity_manual_decay(optim_name):
"""Muon and Lion mirror the AdamW pattern: zero out the optimizer's
built-in `weight_decay` and let `_apply_manual_weight_decay` own the
decoupled decay so bias and norm params are excluded."""
from unsloth_zoo.mlx.trainer import MLXTrainer, MLXTrainingConfig
class DummyModel:
def trainable_parameters(self):
return {}
trainer = MLXTrainer.__new__(MLXTrainer)
trainer.model = DummyModel()
trainer.args = MLXTrainingConfig(
optim=optim_name,
weight_decay=0.05,
)
optimizer = trainer._build_optimizer(total_steps=4)
assert trainer._manual_weight_decay == pytest.approx(0.05)
assert trainer._coupled_weight_decay == pytest.approx(0.0)
if hasattr(optimizer, "_kw"):
assert optimizer._kw["weight_decay"] == 0.0
def test_sgd_weight_decay_is_coupled_not_decoupled():
"""SGD must use coupled decay (folded into the gradient before momentum)
to match HF/PyTorch SGD, not the AdamW-style decoupled parameter shrink."""
from unsloth_zoo.mlx.trainer import MLXTrainer, MLXTrainingConfig
class DummyModel:
def trainable_parameters(self):
return {}
trainer = MLXTrainer.__new__(MLXTrainer)
trainer.model = DummyModel()
trainer.args = MLXTrainingConfig(optim="sgd", weight_decay=0.05)
optimizer = trainer._build_optimizer(total_steps=4)
assert trainer._coupled_weight_decay == pytest.approx(0.05)
assert trainer._manual_weight_decay == pytest.approx(0.0)
if hasattr(optimizer, "_kw"):
assert optimizer._kw["weight_decay"] == 0.0
def test_norm_clip_dtype_restore_keeps_lora_and_norms_promotable():
from unsloth_zoo.mlx.trainer import MLXTrainer
def should_restore_original_dtype(name):
return (
not MLXTrainer._is_norm_parameter_name(name)
and not MLXTrainer._is_lora_parameter_name(name)
)
assert should_restore_original_dtype("model.layers.0.mlp.down_proj.weight")
assert not should_restore_original_dtype("model.layers.0.self_attn.q_proj.lora_a")
assert not should_restore_original_dtype("model.layers.0.self_attn.q_proj.lora_b")
assert not should_restore_original_dtype("model.layers.0.input_layernorm.weight")
assert not should_restore_original_dtype("vision.blocks.0.norm1.weight")
def test_global_norm_clip_reduces_in_float32():
import inspect
from unsloth_zoo.mlx.trainer import _clip_grad_norm_fp32
source = inspect.getsource(_clip_grad_norm_fp32)
assert "g.astype(mx.float32)" in source
assert "scale.astype(g.dtype)" in source
assert "tree_reduce" in source
@pytest.mark.parametrize(
("scheduler", "warmup"),
[
("linear", 0),
("linear", 5),
("cosine", 0),
("cosine", 5),
("constant", 0),
("constant", 5),
],
)
def test_scheduler_lr_matches_expected_optimizer_update_steps(scheduler, warmup):
from unsloth_zoo.mlx.trainer import MLXTrainer, MLXTrainingConfig
total_steps = 8
trainer = MLXTrainer.__new__(MLXTrainer)
trainer.args = MLXTrainingConfig(
learning_rate=5e-5,
lr_scheduler_type=scheduler,
warmup_steps=warmup,
)
schedule = trainer._build_schedule(total_steps=total_steps)
if callable(schedule):
raw_values = [schedule(step) for step in range(total_steps)]
else:
raw_values = [schedule] * total_steps
values = [
value.item() if hasattr(value, "item") else float(value)
for value in raw_values
]
if scheduler == "linear" and warmup == 0:
# Match `transformers.get_scheduler("linear", num_warmup_steps=0,
# num_training_steps=total_steps)` as seen by optimizer steps across
# Transformers 4.56.1 through 5.5.0: step 1 uses base LR, then decays.
lr = trainer.args.learning_rate
expected = [lr * (total_steps - step) / total_steps for step in range(total_steps)]
assert values == pytest.approx(expected)
elif warmup > 0:
assert values[0] == pytest.approx(0.0)
assert all(value > 0.0 for value in values[1:])
else:
assert all(value > 0.0 for value in values)
def test_mlx_text_dataset_does_not_append_eos(monkeypatch):
"""Studio formatting owns EOS decisions; MLX batching must not add one."""
import sys
class CacheDataset:
def __init__(self, data):
self._data = data
self._cache = {}
def __len__(self):
return len(self._data)
def __getitem__(self, idx):
if idx not in self._cache:
self._cache[idx] = self._data.process(self._data[idx])
return self._cache[idx]
def itemlen(self, idx):
return len(self[idx][0])
monkeypatch.setattr(sys.modules["mlx_lm.tuner.datasets"], "CacheDataset", CacheDataset)
from unsloth_zoo.mlx.utils import _prepare_dataset
class Tokenizer:
eos_token_id = 99
chat_template = None
def encode(self, text):
assert text == "hello"
return [1, 2, 3]
# append_eos=False is what Studio passes (chat-template renders EOS).
dataset = _prepare_dataset([{"text": "hello"}], Tokenizer(), append_eos=False)
assert dataset[0] == ([1, 2, 3], 0)
# Default (mlx-lm parity for direct MLX text fine-tuning callers)
# appends the tokenizer EOS so a raw `{"text": str}` row still
# trains the model to predict EOS.
dataset_default = _prepare_dataset([{"text": "hello"}], Tokenizer())
assert dataset_default[0] == ([1, 2, 3, 99], 0)
def test_encode_mlx_text_keeps_raw_text_bos_when_template_has_bos():
from unsloth_zoo.mlx.utils import encode_mlx_text
class Tokenizer:
bos_token = "<s>"
chat_template = "{{ bos_token }}{{ messages }}"
def __init__(self):
self.add_special_tokens_seen = []
def encode(self, text, add_special_tokens=True):
self.add_special_tokens_seen.append(add_special_tokens)
return [1, 2, 3]
tokenizer = Tokenizer()
encode_mlx_text(tokenizer, "raw text")
encode_mlx_text(tokenizer, "<s>rendered text")
assert tokenizer.add_special_tokens_seen == [True, False]
def _make_mlx_text_trainer(**config_kwargs):
"""Build the smallest MLXTrainer shell needed for data-routing tests."""
from unsloth_zoo.mlx.trainer import MLXTrainer, MLXTrainingConfig
class Tokenizer:
chat_template = None
def encode(self, text, add_special_tokens=True):
return [1, 2]
trainer = MLXTrainer.__new__(MLXTrainer)
trainer.args = MLXTrainingConfig(**config_kwargs)
trainer.model = types.SimpleNamespace(_config={})
trainer.tokenizer = Tokenizer()
trainer.train_dataset = []
trainer.formatting_func = None
trainer._batches = None
return MLXTrainer, trainer
def test_text_prompt_completion_create_batches_masks_prompt_labels_and_eos():
from unsloth_zoo.mlx.utils import create_batches
tokenizer = types.SimpleNamespace(
chat_template=None,
eos_token_id=99,
encode=lambda text, add_special_tokens=True: [
int(part) for part in str(text).split()
],
)
batch, _, labels = create_batches(
dataset=[{"prompt": "1 2", "completion": " 3 4"}],
tokenizer=tokenizer,
batch_size=1,
max_seq_length=8,
seed=0,
)[0]
assert batch.tolist() == [[1, 2, 3, 4, 99]]
assert labels.tolist() == [[-100, -100, 3, 4, 99]]
def test_text_conversational_prompt_completion_uses_generation_boundary():
from unsloth_zoo.mlx.utils import create_batches
class BatchEncoding(dict): pass
class Tokenizer:
chat_template = "{{ messages }}"
eos_token_id = 99
def apply_chat_template(
self,
messages,
tokenize=False,
add_generation_prompt=False,
return_dict=False,
tools=None,
extra_token=0,
):
ids = ([30] if tools else []) + ([extra_token] if extra_token else [])
for message in messages:
ids.append(10 if message["role"] == "user" else 20)
ids.extend(int(part) for part in message["content"].split())
if add_generation_prompt:
ids.append(20)
return BatchEncoding(input_ids=ids) if return_dict else ids
batch, _, labels = create_batches(
dataset=[
{
"prompt": [{"role": "user", "content": "1 2"}],
"completion": [{"role": "assistant", "content": "3 4"}],
"tools": [{"type": "function"}],
"chat_template_kwargs": {"extra_token": 5},
}
],
tokenizer=Tokenizer(),
batch_size=1,
max_seq_length=10,
seed=0,
append_eos=False,
)[0]
assert batch.tolist() == [[30, 5, 10, 1, 2, 20, 3, 4]]
assert labels.tolist() == [[-100, -100, -100, -100, -100, -100, 3, 4]]
class _AssistantMaskTokenizer:
chat_template = "{{ messages }}"
eos_token_id = None
pad_token_id = 7
def apply_chat_template(
self,
messages,
tokenize=False,
return_dict=False,
return_assistant_tokens_mask=False,
tools=None,
add_generation_prompt=False,
**_kwargs,
):
ids = []
masks = []
if tools:
ids.append(30)
masks.append(0)
for message in messages:
is_assistant = message["role"] == "assistant"
ids.append(20 if is_assistant else 10)
masks.append(0)
ids.extend(int(part) for part in message["content"].split())
masks.extend([1 if is_assistant else 0] * len(message["content"].split()))
output = {"input_ids": ids}
if return_assistant_tokens_mask:
output["assistant_masks"] = masks
return output if return_dict else ids
class _NoAssistantMaskTokenizer(_AssistantMaskTokenizer):
def apply_chat_template(self, *args, **kwargs):
kwargs["return_assistant_tokens_mask"] = False
return super().apply_chat_template(*args, **kwargs)
@pytest.mark.parametrize(
("dataset", "extra_kwargs"),
[
(
[
{
"messages": [
{"role": "user", "content": "1"},
{"role": "assistant", "content": "2 3"},
],
}
],
{},
),
(
[
{
"prompt": [{"role": "user", "content": "1"}],
"completion": [{"role": "assistant", "content": "2 3"}],
}
],
{"append_eos": False},
),
],
)
def test_text_assistant_only_loss_masks_non_assistant_tokens(dataset, extra_kwargs):
from unsloth_zoo.mlx.utils import create_batches
batch, _, labels = create_batches(
dataset=dataset,
tokenizer=_AssistantMaskTokenizer(),
batch_size=1,
max_seq_length=8,
assistant_only_loss=True,
completion_only_loss=False,
**extra_kwargs,
)[0]
assert batch.tolist() == [[10, 1, 20, 2, 3]]
assert labels.tolist() == [[-100, -100, -100, 2, 3]]
@pytest.mark.parametrize(
("dataset", "tokenizer", "match"),
[
([{"prompt": "Question: ", "completion": "Answer"}], _AssistantMaskTokenizer(), "not conversational"),
(
[
{
"messages": [
{"role": "user", "content": "1"},
{"role": "assistant", "content": "2"},
],
},
{"text": "plain text"},
],
_AssistantMaskTokenizer(),
"not conversational",
),
(
[
{
"messages": [
{"role": "user", "content": "1"},
{"role": "assistant", "content": "2"},
],
}
],
_NoAssistantMaskTokenizer(),
"no assistant tokens",
),
([{"input_ids": [1, 2, 3]}], types.SimpleNamespace(), "assistant_masks"),
],
)
def test_text_assistant_only_loss_rejects_unsupported_inputs(dataset, tokenizer, match):
from unsloth_zoo.mlx.utils import create_batches
with pytest.raises((RuntimeError, ValueError), match=match):
create_batches(
dataset=dataset,
tokenizer=tokenizer,
batch_size=1,
max_seq_length=8,
assistant_only_loss=True,
completion_only_loss=False,
)
def test_text_pretokenized_assistant_masks_build_labels():
from unsloth_zoo.mlx.utils import create_batches
_, _, labels = create_batches(
dataset=[
{
"input_ids": [1, 2, 3, 4],
"assistant_masks": [0, 1, 0, 1],
}
],
tokenizer=types.SimpleNamespace(),
batch_size=1,
max_seq_length=8,
assistant_only_loss=True,
completion_only_loss=False,
)[0]
assert labels.tolist() == [[-100, 2, -100, 4]]
def test_text_completion_probe_keeps_one_shot_iterables_reusable():
from unsloth_zoo.mlx.utils import _ensure_reiterable_text_dataset
def rows():
yield {"text": "1 2"}
dataset = _ensure_reiterable_text_dataset(rows())
assert list(dataset) == [{"text": "1 2"}]
assert list(dataset) == [{"text": "1 2"}]
def test_text_pretokenized_create_batches_preserves_input_ids():
from unsloth_zoo.mlx.utils import create_batches
def formatting_func(_item):
raise AssertionError("formatting_func should be ignored for input_ids rows")
tokenizer = types.SimpleNamespace(
pad_token_id=9,
encode=lambda *_args, **_kwargs: pytest.fail("should not tokenize input_ids")
)
batch, lengths, labels = create_batches(
dataset=[
{"input_ids": [1, 2, 3]},
{"input_ids": [4, 5]},
],
tokenizer=tokenizer,
batch_size=2,
max_seq_length=8,
completion_only_loss=False,
formatting_func=formatting_func,
)[0]
assert batch.tolist() == [[4, 5, 9], [1, 2, 3]]
assert lengths.tolist() == [[0, 2], [0, 3]]
assert labels is None
def test_text_pretokenized_rejects_mixed_raw_rows():
from unsloth_zoo.mlx.utils import create_batches
with pytest.raises(ValueError, match="cannot be mixed"):
create_batches(
dataset=[
{"input_ids": [1, 2, 3]},
{"text": "4 5 6"},
],
tokenizer=types.SimpleNamespace(),
batch_size=1,
max_seq_length=8,
completion_only_loss=False,
)
def test_text_pretokenized_rejects_mixed_label_presence():
from unsloth_zoo.mlx.utils import create_batches
with pytest.raises(ValueError, match="must not be mixed"):
create_batches(
dataset=[
{"input_ids": [1, 2, 3]},
{"input_ids": [4, 5, 6], "labels": [-100, 5, 6]},
],
tokenizer=types.SimpleNamespace(),
batch_size=2,
max_seq_length=8,
completion_only_loss=False,
)
def test_text_pretokenized_completion_mask_requires_completion_only_loss():
from unsloth_zoo.mlx.utils import create_batches
tokenizer = types.SimpleNamespace()
kwargs = dict(tokenizer=tokenizer, batch_size=1, max_seq_length=8)
row = {
"input_ids": [1, 2, 3, 4],
"labels": [11, 12, 13, 14],
"completion_mask": [0, 1, 0, 1],
}
_, _, default_labels = create_batches(dataset=[row], **kwargs)[0]
batch, _, masked_labels = create_batches(
dataset=[row],
completion_only_loss=True,
**kwargs,
)[0]
assert batch.tolist() == [[1, 2, 3, 4]]
assert default_labels.tolist() == [[11, 12, 13, 14]]
assert masked_labels.tolist() == [[-100, 12, -100, 14]]
def test_text_pretokenized_ordered_and_streaming_batches_emit_labels():
from unsloth_zoo.mlx.utils import create_ordered_batches, iterate_training_batches
tokenizer = types.SimpleNamespace(pad_token_id=7)
dataset = [
{"input_ids": [1, 2], "labels": [-100, 2]},
{"input_ids": [3, 4, 5], "labels": [-100, 4, 5]},
]
batches = [
create_ordered_batches(
dataset=dataset,
tokenizer=tokenizer,
batch_size=2,
max_seq_length=8,
dataset_order="sequential",
)[0],
next(
iterate_training_batches(
dataset=dataset,
tokenizer=tokenizer,
batch_size=2,
max_seq_length=8,
seed=0,
)
),
]
for batch, _, labels in batches:
assert batch.tolist() == [[1, 2, 7], [3, 4, 5]]
assert labels.tolist() == [[-100, 2, -100], [-100, 4, 5]]
def test_text_prepare_data_passes_completion_only_loss_to_create_batches(monkeypatch):
from unsloth_zoo.mlx import trainer as mlx_trainer
received = {}
def fake_create_batches(**kwargs):
received.update(kwargs)
return [("batch", "lengths", "labels")]
monkeypatch.setattr(mlx_trainer, "create_batches", fake_create_batches)
MLXTrainer, trainer = _make_mlx_text_trainer(
max_steps=1,
completion_only_loss=True,
assistant_only_loss=True,
)
batches, _ = MLXTrainer._prepare_data(trainer, is_vlm=False)
assert batches == [("batch", "lengths", "labels")]
assert received["completion_only_loss"] is True