Skip to content

MLX: keep GRPO/KTO/CPO loss_type defaults and export helpers notebooks import - #18069

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
Lyxot:mlx-notebook-shims
Nov 17, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
Lyxot:mlx-notebook-shims

Conversation

@Lyxot

@Lyxot Lyxot commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Summary

Two MLX fixes so more Unsloth notebooks run unchanged on Apple Silicon:

  1. Fix: trl.GRPOConfig / KTOConfig / CPOConfig on MLX lost their own loss_type default. Since unsloth-zoo added an SFT loss_type="nll" field to MLXTrainingConfig, GRPOConfig(...) without an explicit loss_type raises ValueError: Unsloth MLX GRPO: loss_type='nll' is not one of grpo, bnpo, dr_grpo, dapo, and KTOConfig / CPOConfig silently train with loss_type='nll' instead of kto / sigmoid. Most GRPO notebooks don't set loss_type, so they all fail at the config cell.
  2. Export what notebooks import from unsloth on MLX: check_python_modules, create_locked_down_function, execute_with_time_limit, Benchmarker, is_port_open, launch_openenv (the same unsloth_zoo.rl_environments list the CUDA path exports), to_sharegpt, and the architecture-specific FastLlamaModel / FastMistralModel / FastGraniteModel / FastQwen2Model / FastQwen3Model / FastQwen3MoeModel / FastFalconH1Model names. These raised ImportError on MLX.

Root cause

The MLX trl.XConfig classes are built with dataclasses.make_dataclass(bases=(_MLXTRLConfig, zoo_config)). Dataclass fields are collected along the reversed MRO, so UnslothTrainingArguments' inherited copy of every MLXTrainingConfig field is applied after the zoo config subclass and hides any default the zoo config overrides. This was latent until MLXTrainingConfig gained a field (loss_type) that the preference/RL configs override. The fix re-declares every zoo config field whose default differs from MLXTrainingConfig's, so the whole class is covered rather than only loss_type.

The architecture-specific Fast*Model names alias FastLanguageModel, as FastModel / FastTextModel already do on MLX: the MLX loader dispatches on the checkpoint config, not the class.

Out of scope

  • vLLM-style notebook calls (from vllm import SamplingParams, model.fast_generate(..., sampling_params=, lora_request=), save_lora / load_lora, use_vllm, vllm_sampling_params) are handled separately.
  • GRPO chat_template_kwargs / max_tool_calling_iterations stay refused: the MLX GRPO trainer has no config-level support for them.

Validation

tests/test_mlx_trl_lazy_all.py: 18 passed (Apple Silicon, unsloth-zoo main)
  • Reverting the config fix fails test_trl_config_defaults_match_trl, test_trl_trainers_zoo_implements_are_mapped and test_hf_argument_parser_builds_the_same_trl_configs (the same three fail on current main). Removing an rl_environments export, mis-aliasing FastQwen2Model, or breaking to_sharegpt each fail test_trl_trainers_zoo_implements_are_mapped.
  • Real 3-step runs through from trl import ... on Qwen/Qwen3-0.6B (4-bit + LoRA): GRPO resolves loss_type='dapo', KTO kto, CPO sigmoid; all train to completion.
  • tests/python/test_mlx_public_trainer_api.py::test_mlx_trainer_accepts_trl_style_positional_args and ::test_mlx_torch_cuda_compatibility_shim fail identically on main and are unrelated.

…_type

The MLX trl configs are built with make_dataclass over (_MLXTRLConfig, zoo config). Dataclass fields are collected along the reversed MRO, so UnslothTrainingArguments' copy of every MLXTrainingConfig field hid the zoo config's own default. Since MLXTrainingConfig gained loss_type='nll', GRPOConfig without loss_type raises and KTOConfig / CPOConfig silently train with loss_type='nll'. Re-declare every zoo field whose default differs from MLXTrainingConfig's.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner November 17, 2026 03:57
@Lyxot Lyxot added the MLX label Nov 17, 2026
@Lyxot

Lyxot commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T05:51:04.420101Z f38b7fb Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 3d52907e6d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Source lint (Python + shell + YAML + JSON + safety nets) fails on this PR in the import-hoist check (scripts/verify_import_hoist.py), with six blockers in unsloth/__init__.py:

[BLOCKER] unsloth/__init__.py: HOISTED-IMPORT-UNUSED 'check_python_modules' (['from:unsloth_zoo.rl_environments:check_python_modules']) added but unused
... same for create_locked_down_function, execute_with_time_limit, Benchmarker, is_port_open, launch_openenv

These are re-exports for the notebooks, so they are meant to be unused inside the module. The check exempts a re-export in a package __init__.py only when the name is listed in that module's __all__ (around line 597 of scripts/verify_import_hoist.py). Adding the six names to an __all__ in unsloth/__init__.py should clear it. If unsloth/__init__.py has no __all__ of its own yet, extending one only by these names would also limit from unsloth import * to them, so it may be simpler to re-export them from a submodule that already defines __all__.

…nsloth

GRPO and RL-environment notebooks import check_python_modules, create_locked_down_function and execute_with_time_limit from unsloth, and some notebooks use to_sharegpt or FastQwen2Model. On MLX these raised ImportError. Export the same unsloth_zoo.rl_environments helpers the CUDA path does, a lazy to_sharegpt, and the architecture-specific Fast*Model names as FastLanguageModel aliases, since the MLX loader dispatches on the checkpoint config.
@Lyxot
Lyxot force-pushed the mlx-notebook-shims branch from 3d52907 to f38b7fb Compare November 17, 2026 05:46
@Lyxot

Lyxot commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, fixed in f38b7fb46b7 (folded into the export commit). The MLX branch of unsloth/__init__.py has no __all__, so I didn't add one: a new __all__ would narrow from unsloth import * on MLX to just these names. Instead it imports the module (from unsloth_zoo import rl_environments as _rl_environments) and binds the six names as plain assignments. They stay the same objects the CUDA path exports, and scripts/verify_import_hoist.py --before 971c16b9e9c --after HEAD now reports OVERALL: PASS. tests/test_mlx_trl_lazy_all.py still passes (18 passed on Apple Silicon).

@Lyxot

Lyxot commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: f38b7fb46b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen danielhanchen self-assigned this Nov 17, 2026
@danielhanchen
danielhanchen merged commit 4371ee0 into unslothai:main Nov 17, 2026
danielhanchen added a commit that referenced this pull request Nov 17, 2026
… fixed 0.1 s sleep (#18103)

`studio/backend/tests/test_anthropic_admission.py` fails intermittently
in the Studio `a-f` shard on unrelated PRs (#18045, #18006, #18069,
#18075):

```
test_non_streaming_queued_then_admitted
E   AssertionError: assert 0 == 1
E    +  where 0 = LlamaAdmissionSnapshot(..., capacity=1, active=1, queued=0, ...).queued
test_capacity_enforced_from_effective_parallel_slots
E   AssertionError: assert (3 == 3 and 3 == 3 and 0 == 1)
```

## Cause

Each of these tests occupies every slot, starts a request as a task,
sleeps a fixed 0.1 s and then expects the request to be in the admission
queue. On a loaded runner the handler sometimes has not reached the
queue within 0.1 s, so the snapshot still shows `queued=0`. The
admission code is not at fault; the test raced it.

## Fix

`_until_queued(task)` polls the queue snapshot every 10 ms until the
request is queued, for up to 5 s. It still fails if the request finishes
without ever queueing (`task.done()`) or never queues within the
deadline, so a request that skips admission is still caught. It replaces
the fixed sleep at all five sites that assert `queued == 1` right after
starting the task. The assertions themselves are unchanged.

## Verification

- `tests/test_anthropic_admission.py`: 39 passed, twice.
- Slow handler simulated locally (`await asyncio.sleep(0.25)` at the top
of `anthropic_messages`, not committed):
- main: the five queued checks fail (plus
`test_uncontended_hot_path_is_fast`, which is meant to catch a slow
handler).
  - this branch: only `test_uncontended_hot_path_is_fast` fails.
@Lyxot

Lyxot commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Review and CI summary for head f38b7fb46b7:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants