@mlx-node/trl
GRPO and SFT training in TypeScript on Apple Silicon.
Install
npm install @mlx-node/trl
What can be trained
Qwen3 and the Qwen3.5 family: Qwen3.5, 3.6 and 3.8 dense, and Qwen3.5 and 3.6 MoE. Every other model is inference only. Training runs on Apple Silicon. It has not been tested on CUDA.
Get a dataset
mlx download dataset
This downloads openai/gsm8k and writes data/openai-gsm8k/train.jsonl and test.jsonl in the current folder. loadLocalGsm8kDataset reads the same path, so run both from one folder.
GRPO
import { homedir } from 'node:os';
import { join } from 'node:path';
import { GRPOTrainer, loadLocalGsm8kDataset } from '@mlx-node/trl';
import { extractGsm8kAnswer, extractXmlAnswer } from '@mlx-node/trl';
// 1 when the <answer> tag holds the dataset's answer ("$" signs ignored), else 0.
function score(text: string, answer: string | null) {
return extractXmlAnswer(text)?.replaceAll('$', '') === answer ? 1 : 0;
}
const trainer = await GRPOTrainer.create({
modelPath: join(homedir(), '.mlx-node', 'models', 'qwen3-0.6b'),
outputDir: 'outputs/grpo',
groupSize: 4,
lossType: 'grpo',
enableThinking: false,
rewardFunction: (outputs, answer: string | null) => {
return outputs.map(({ completion }) => score(completion.text, answer));
},
});
for (const { prompt, metadata } of await loadLocalGsm8kDataset('train', { limit: 100 })) {
const answer = extractGsm8kAnswer(String(metadata?.raw_answer));
const { step, meanReward } = await trainer.trainStep([prompt], answer);
console.log({ step, meanReward });
}
await trainer.saveCheckpoint('final');
Each step takes one GSM8K question. The model writes four answers, the reward scores them, and the weights move toward the answers that scored higher. When all four rewards are equal, the step has nothing to learn from.
trainStep(prompts, context)passescontextto the reward function as its second argument. Here it is the dataset's answer:loadLocalGsm8kDatasetkeeps the answer text inmetadata.raw_answer, andextractGsm8kAnswertakes the text after####.- The prompts of
loadLocalGsm8kDatasetask for<reasoning>and<answer>tags, so the reward reads the answer withextractXmlAnswer.enableThinking: falsekeeps Qwen3 from spending its 256 completion tokens on thinking. - The loop prints the step and its mean reward.
saveCheckpoint('final')writes the weights and the AdamW state tooutputs/grpo/final, about 6 GB for this model. trainer.train(dataset)runs the whole loop and saves checkpoints for you, but it calls the reward function with no context, so it suits a reward that does not need the answer.- Loss types:
grpo,dapo,dr_grpoandbnpo. Set one withlossType. - A reward function gets an array of outputs and the context. Each output has the
promptand acompletionwithtextandtoolCalls. ThegroupSizeoutputs of one prompt come one after another. It returns one number per output. - Built-in rewards for tool use, XML format, JSON format and length run in Rust. Add one with
trainer.registerBuiltinReward(config). A reward model is not supported yet. - The optimizer is AdamW by default.
optimizerType: 'sgd'gives plain SGD.
SFT
import { homedir } from 'node:os';
import { join } from 'node:path';
import { SFTTrainer } from '@mlx-node/trl';
const trainer = await SFTTrainer.create({
modelName: join(homedir(), '.mlx-node', 'models', 'qwen3-0.6b'),
outputDir: 'outputs/sft',
numEpochs: 1,
});
await trainer.train('data/sft.jsonl');
Each row of the JSONL file is {"messages":[...]} or {"prompt":[...],"completion":{...}}, and all rows of one file use the same shape. modelName is the path of the model folder.
Other config keys: learningRate, batchSize, gradientAccumulationSteps, maxSeqLength, completionOnly, gradientCheckpointing and resumeFromCheckpoint.
Main exports
| Name | What it is |
|---|---|
GRPOTrainer |
create(config), trainStep(prompts, context), train(dataset), saveCheckpoint(name) |
SFTTrainer |
create(config), train(file) |
loadLocalGsm8kDataset(split, options) |
Read the downloaded GSM8K files |
extractGsm8kAnswer(text) |
The text after ####, or null |
extractXmlAnswer(text) |
The text in the <answer> tag, or null |