mlx-lm-lora 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. mlx_lm_lora-0.1.1/LICENSE +201 -0
  2. mlx_lm_lora-0.1.1/MANIFEST.in +2 -0
  3. mlx_lm_lora-0.1.1/PKG-INFO +459 -0
  4. mlx_lm_lora-0.1.1/README.md +423 -0
  5. mlx_lm_lora-0.1.1/mlx_lm_lora/__init__.py +11 -0
  6. mlx_lm_lora-0.1.1/mlx_lm_lora/__main__.py +21 -0
  7. mlx_lm_lora-0.1.1/mlx_lm_lora/_version.py +3 -0
  8. mlx_lm_lora-0.1.1/mlx_lm_lora/evaluate.py +415 -0
  9. mlx_lm_lora-0.1.1/mlx_lm_lora/fuse.py +126 -0
  10. mlx_lm_lora-0.1.1/mlx_lm_lora/py.typed +1 -0
  11. mlx_lm_lora-0.1.1/mlx_lm_lora/tokenizer_utils.py +387 -0
  12. mlx_lm_lora-0.1.1/mlx_lm_lora/train.py +579 -0
  13. mlx_lm_lora-0.1.1/mlx_lm_lora/trainer/__init__.py +6 -0
  14. mlx_lm_lora-0.1.1/mlx_lm_lora/trainer/callbacks.py +41 -0
  15. mlx_lm_lora-0.1.1/mlx_lm_lora/trainer/datasets.py +580 -0
  16. mlx_lm_lora-0.1.1/mlx_lm_lora/trainer/dora.py +228 -0
  17. mlx_lm_lora-0.1.1/mlx_lm_lora/trainer/dpo_trainer.py +431 -0
  18. mlx_lm_lora-0.1.1/mlx_lm_lora/trainer/grpo_reward_functions.py +102 -0
  19. mlx_lm_lora-0.1.1/mlx_lm_lora/trainer/grpo_trainer.py +834 -0
  20. mlx_lm_lora-0.1.1/mlx_lm_lora/trainer/lora.py +285 -0
  21. mlx_lm_lora-0.1.1/mlx_lm_lora/trainer/orpo_trainer.py +397 -0
  22. mlx_lm_lora-0.1.1/mlx_lm_lora/trainer/sft_trainer.py +333 -0
  23. mlx_lm_lora-0.1.1/mlx_lm_lora/trainer/utils.py +283 -0
  24. mlx_lm_lora-0.1.1/mlx_lm_lora.egg-info/PKG-INFO +459 -0
  25. mlx_lm_lora-0.1.1/mlx_lm_lora.egg-info/SOURCES.txt +31 -0
  26. mlx_lm_lora-0.1.1/mlx_lm_lora.egg-info/dependency_links.txt +1 -0
  27. mlx_lm_lora-0.1.1/mlx_lm_lora.egg-info/entry_points.txt +4 -0
  28. mlx_lm_lora-0.1.1/mlx_lm_lora.egg-info/requires.txt +14 -0
  29. mlx_lm_lora-0.1.1/mlx_lm_lora.egg-info/top_level.txt +1 -0
  30. mlx_lm_lora-0.1.1/pyproject.toml +3 -0
  31. mlx_lm_lora-0.1.1/requirements.txt +10 -0
  32. mlx_lm_lora-0.1.1/setup.cfg +4 -0
  33. mlx_lm_lora-0.1.1/setup.py +37 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ include requirements.txt
2
+ recursive-include mlx_lm_lora/ *.py
@@ -0,0 +1,459 @@
1
+ Metadata-Version: 2.4
2
+ Name: mlx-lm-lora
3
+ Version: 0.1.1
4
+ Summary: Train LLMs on Apple silicon with MLX and the Hugging Face Hub
5
+ Home-page: https://github.com/Goekdeniz-Guelmez/mlx-lm-lora.git
6
+ Author: Gökdeniz Gülmez
7
+ Author-email: goekdenizguelmez@gmail.com
8
+ License: MIT
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: mlx>=0.25.0
13
+ Requires-Dist: mlx_lm
14
+ Requires-Dist: numpy
15
+ Requires-Dist: transformers[sentencepiece]>=4.39.3
16
+ Requires-Dist: protobuf
17
+ Requires-Dist: pyyaml
18
+ Requires-Dist: jinja2
19
+ Requires-Dist: tqdm
20
+ Requires-Dist: wandb
21
+ Requires-Dist: datasets
22
+ Provides-Extra: evaluate
23
+ Requires-Dist: lm-eval; extra == "evaluate"
24
+ Requires-Dist: tqdm; extra == "evaluate"
25
+ Dynamic: author
26
+ Dynamic: author-email
27
+ Dynamic: description
28
+ Dynamic: description-content-type
29
+ Dynamic: home-page
30
+ Dynamic: license
31
+ Dynamic: license-file
32
+ Dynamic: provides-extra
33
+ Dynamic: requires-dist
34
+ Dynamic: requires-python
35
+ Dynamic: summary
36
+
37
+ # mlx-lm-lora
38
+ Train Large Language Models localy on Apple Silicon using MLX. Fine-tuning works with all the model that are supported with MLX-LM, for example:
39
+
40
+ - Llama, 3, 4
41
+ - Phi2, 3
42
+ - Mistral
43
+ - Mixtral
44
+ - Qwen2, 2.5, 3
45
+ - Qwen3 MoE
46
+ - Gemma1, 2, 3
47
+ - OLMo, OLMoE
48
+ - MiniCPM, MiniCPM3
49
+ - and more ...
50
+
51
+ ## Contents
52
+
53
+ - [Run](#Run)
54
+ - [LoRA or Full-Precision](#Lora-or-Full-Precision)
55
+ - [SFT](#SFT-Training)
56
+ - [ORPO-Training](#ORPO-Training)
57
+ - [DPO-Training](#DPO-Training)
58
+ - [GRPO-Training](#GRPO-Training)
59
+ - [Evaluate](#Evaluate)
60
+ - [Generate](#Generate)
61
+ - [Fuse](#Fuse)
62
+ - [Memory Issues](#Memory-Issues)
63
+
64
+ --
65
+
66
+ ## Run
67
+
68
+ The main command is `mlx_lm_lora.train`. To see a full list of command-line options run:
69
+
70
+ ```shell
71
+ mlx_lm_lora.train --help
72
+ ```
73
+
74
+ Note, in the following the `--model` argument can be any compatible Hugging
75
+ Face repo or a local path to a converted model.
76
+
77
+ You can also specify a YAML config with `-c`/`--config`. For more on the format see the
78
+ [example YAML](examples/lora_config.yaml). For example:
79
+
80
+ ```shell
81
+ mlx_lm_lora.train --config /path/to/config.yaml
82
+ ```
83
+
84
+ If command-line flags are also used, they will override the corresponding
85
+ values in the config.
86
+
87
+ ---
88
+
89
+ ### LoRA or Full-Precision
90
+
91
+ To fine-tune a model use:
92
+
93
+ ```shell
94
+ mlx_lm_lora.train \
95
+ --model <path_to_model> \
96
+ --train \
97
+ --data <path_to_data> \
98
+ --iters 600
99
+ ```
100
+
101
+ To fine-tune the full model weights, add the `--train-type full` flag.
102
+ Currently supported training types are `lora` (default), `dora`, and `full`.
103
+
104
+ The `--data` argument must specify a path to a `train.jsonl`, `valid.jsonl`
105
+ when using `--train` and a path to a `test.jsonl` when using `--test`. For more
106
+
107
+ If `--model` points to a quantized model, then the training will use QLoRA,
108
+ otherwise it will use regular LoRA.
109
+
110
+ By default, the adapter config and learned weights are saved in `adapters/`.
111
+ You can specify the output location with `--adapter-path`.
112
+
113
+ You can resume fine-tuning with an existing adapter with
114
+ `--resume-adapter-file <path_to_adapters.safetensors>`.
115
+
116
+ ---
117
+
118
+ ### SFT-Training
119
+
120
+ Supervised Fine-Tuning (SFT) trains a model using pairs of prompts and expected completions. This is the most common form of instruction tuning.
121
+
122
+ To run SFT:
123
+
124
+ mlx_lm_lora.train \
125
+ --model <path_to_model> \
126
+ --train \
127
+ --data <path_to_data>
128
+
129
+ You can set the training type explicitly using --train-type lora, dora, or full. By default, LoRA is used.
130
+
131
+ Data Format
132
+
133
+ The data should be in JSONL format with one of the following structures:
134
+
135
+ Chat-style (preferred for chat models):
136
+
137
+ {
138
+ "messages": [
139
+ {"role": "system", "content": "You are a helpful assistant."},
140
+ {"role": "user", "content": "What is the capital of France?"},
141
+ {"role": "assistant", "content": "Paris."}
142
+ ]
143
+ }
144
+
145
+ Prompt-completion style:
146
+
147
+ {"prompt": "What is the capital of France?", "completion": "Paris."}
148
+
149
+ You can mix system messages or use multi-turn chat formatting depending on the target model’s capabilities.
150
+
151
+ Additional Options
152
+ • --use-chat-template: Format messages using the model’s chat template (default: False)
153
+ • --mask-prompt: Apply loss only on the assistant’s output instead of the full sequence
154
+ • --train-type: Choose lora, dora, or full for LoRA, DoRA, or full-weight fine-tuning
155
+ • --resume-adapter-file: Resume training from a previously saved adapter
156
+
157
+ Example with chat template and prompt masking:
158
+
159
+ mlx_lm_lora.train \
160
+ --model <path_to_model> \
161
+ --train \
162
+ --data <path_to_data> \
163
+ --use-chat-template True \
164
+ --mask-prompt
165
+
166
+ ---
167
+
168
+ ### ORPO-Training
169
+
170
+ Odds Ratio Preference Optimization (ORPO) training fine-tunes models using human preference data. Usage:
171
+
172
+ ```shell
173
+ mlx_lm_lora.train \
174
+ --model <path_to_model> \
175
+ --train \
176
+ --train-mode orpo \
177
+ --data <path_to_data> \
178
+ --beta 0.1
179
+ ```
180
+
181
+ Parameters:
182
+
183
+ - `--beta`: Temperature for logistic function (default: 0.1)
184
+
185
+ Data format (JSONL):
186
+
187
+ ```jsonl
188
+ # Basic format with string responses
189
+ {"prompt": "User prompt", "chosen": "Preferred response", "rejected": "Less preferred response"}
190
+
191
+ # With custom preference score
192
+ {"prompt": "User prompt", "chosen": "Preferred response", "rejected": "Less preferred response", "preference_score": 8.0}
193
+
194
+ # With system message
195
+ {"prompt": "User prompt", "chosen": "Preferred response", "rejected": "Less preferred response", "system": "System instruction"}
196
+
197
+ # With full conversation objects
198
+ {
199
+ "prompt": "User prompt",
200
+ "chosen": {
201
+ "messages": [
202
+ {"role": "system", "content": "System instruction"},
203
+ {"role": "user", "content": "User message"},
204
+ {"role": "assistant", "content": "Assistant response"}
205
+ ]
206
+ },
207
+ "rejected": {
208
+ "messages": [
209
+ {"role": "system", "content": "System instruction"},
210
+ {"role": "user", "content": "User message"},
211
+ {"role": "assistant", "content": "Assistant response"}
212
+ ]
213
+ }
214
+ }
215
+ ```
216
+
217
+ The trainer assigns binary rewards (1.0 chosen, 0.0 rejected) if no explicit rewards provided via `preference_score`.
218
+
219
+ ---
220
+
221
+ ### DPO-Training
222
+
223
+ Direct Preference Optimization (DPO) training allows you to fine-tune models using human preference data. To use DPO training, set the training mode to 'dpo':
224
+
225
+ ```shell
226
+ mlx_lm.lora \
227
+ --model <path_to_model> \
228
+ --train \
229
+ --train-mode dpo \
230
+ --data <path_to_data> \
231
+ --beta 0.1
232
+ ```
233
+
234
+ The DPO training accepts the following additional parameters:
235
+
236
+ - `--beta`: Controls the strength of the DPO loss (default: 0.1)
237
+ - `--dpo-loss-type`: Choose between "sigmoid" (default), "hinge", "ipo", or "dpop" loss functions
238
+ - `--delta`: Margin parameter for hinge loss (default: 50.0)
239
+ - `--reference-model-path`: Path to a reference model for DPO training
240
+
241
+ For DPO training, the data should be in JSONL format with the following structure:
242
+
243
+ ```jsonl
244
+ {"prompt": "User prompt", "chosen": "Preferred response", "rejected": "Less preferred response"}
245
+ ```
246
+
247
+ if the Prompt template accept a system message, you can extend the Dataset with a additional "system" field.
248
+
249
+ ```jsonl
250
+ {"system": "You are a helpfull assistant", "prompt": "User prompt", "chosen": "Preferred response", "rejected": "Less preferred response"}
251
+ ```
252
+
253
+ ---
254
+
255
+ ### GRPO-Training
256
+ #### Overview
257
+
258
+ Group Relative Policy Optimization (GRPO) is a fine-tuning method that optimizes language models by generating multiple responses per prompt and learning from their relative quality. This approach helps improve response quality through comparative learning.
259
+
260
+ #### Dataset Format
261
+
262
+ GRPO requires a dataset in JSONL format (one JSON object per line) with the following structure:
263
+
264
+ ```json
265
+ {"prompt": "Your question or instruction here", "answer": "The expected response"}
266
+ ```
267
+
268
+ Each entry must contain:
269
+ - `prompt`: The input text for the model to respond to
270
+ - `answer`: The target/reference response
271
+
272
+ Optional fields:
273
+ - `system`: A system message providing context or instructions for the model
274
+
275
+ Example entries:
276
+ ```json
277
+ {"prompt": "Gerald spends $100 a month on baseball supplies. His season is 4 months long. He wants to use the months he's not playing baseball to save up by raking, shoveling, and mowing lawns. He charges $10 for each. How many chores does he need to average a month to save up for his supplies?", "answer": "5"}
278
+ {"prompt": "Ann is cutting fabric to make curtains. She cuts a 4 foot by 6 foot rectangle for the living room, and a 2 foot by 4 foot rectangle for the bedroom. If the bolt of fabric is 16 feet by 12 feet, how much fabric is left in square feet?", "answer": "160"}
279
+ {"prompt": "Arnel had ten boxes of pencils with the same number of pencils in each box. He kept ten pencils and shared the remaining pencils equally with his five friends. If his friends got eight pencils each, how many pencils are in each box?", "answer": "5", "system": "You are a helpful math tutor."}
280
+ ```
281
+
282
+ #### Usage
283
+
284
+ To fine-tune a model using GRPO:
285
+
286
+ ```shell
287
+ mlx_lm.lora \
288
+ --model <path_to_model> \
289
+ --train \
290
+ --data <path_to_data> \
291
+ --fine-tune-type grpo \
292
+ --group-size 4
293
+ ```
294
+
295
+ #### GRPO-Specific Arguments
296
+
297
+ - `--group-size`: Number of responses generated per prompt (default: 4)
298
+ - `--beta`: KL penalty coefficient for policy optimization (default: 0.1)
299
+ - `--epsilon`: Small constant for numerical stability (default: 1e-4)
300
+ - `--max-completion-length`: Maximum length of generated completions (default: 512)
301
+ - `--reference-model-path`: Path to reference model weights. If not specified, uses the same model
302
+ - `--temperature`: Sampling temperature for generations. Higher values increase randomness (default: 1.0)
303
+ - `--reward-weights`: Optional list of weights for multiple reward functions. Must match number of reward functions. If not specified, all rewards weighted equally with 1.0
304
+ - `--use-chat-template`: Whether to use the model's chat template for formatting prompts (default: False)
305
+ - `--use-prompt`: Whether to use the prompt as part of the input for generation (default: False)
306
+
307
+ #### Training Process
308
+
309
+ During GRPO training, the model:
310
+ 1. Takes each prompt from the dataset
311
+ 2. Generates multiple responses (specified by `--group-size`)
312
+ 3. Evaluates these responses against the reference answer
313
+ 4. Optimizes the policy based on the relative quality of the responses
314
+
315
+ #### Resource Considerations
316
+
317
+ GRPO requires more compute resources than standard LoRA training since it generates multiple responses per prompt. Consider:
318
+ - Reducing batch size
319
+ - Using gradient checkpointing
320
+ - Adjusting `--group-size` to balance between quality and resource usage
321
+
322
+ If running into memory issues, you can also try:
323
+ - Reducing `--max-completion-length`
324
+ - Using a smaller model for initial experiments
325
+
326
+ #### Example Command with Full Options
327
+
328
+ ```shell
329
+ mlx_lm.lora \
330
+ --model <path_to_model> \
331
+ --train \
332
+ --data <path_to_data> \
333
+ --fine-tune-type grpo \
334
+ --group-size 4 \
335
+ --beta 0.1 \
336
+ --epsilon 1e-4 \
337
+ --max-completion-length 512 \
338
+ --reference-model-path <optional_path_to_reference_model> \
339
+ --temperature 1.0 \
340
+ --reward-weights 1.0 1.0 \
341
+ --use-chat-template False \
342
+ --use-prompt False \
343
+ --batch-size 4 \
344
+ --learning-rate 1e-5 \
345
+ --num-epochs 3
346
+ ```
347
+
348
+ ---
349
+
350
+ ### Evaluate
351
+
352
+ To compute test set perplexity use:
353
+
354
+ ```shell
355
+ mlx_lm_lora.train \
356
+ --model <path_to_model> \
357
+ --adapter-path <path_to_adapters> \
358
+ --data <path_to_data> \
359
+ --test
360
+ ```
361
+
362
+ ### Generate
363
+
364
+ For generation use `mlx-lm` with `mlx_lm.generate`:
365
+
366
+ ```shell
367
+ mlx_lm.generate \
368
+ --model <path_to_model> \
369
+ --adapter-path <path_to_adapters> \
370
+ --prompt "<your_model_prompt>"
371
+ ```
372
+
373
+ #### Prompt Masking
374
+
375
+ The default training computes a loss for every token in the sample. You can
376
+ ignore the prompt and compute loss for just the completion by passing
377
+ `--mask-prompt`. Note this is only supported for `chat` and `completion`
378
+ datasets. For `chat` datasets the final message in the message list is
379
+ considered the completion.
380
+
381
+ ---
382
+
383
+ ## Fuse
384
+
385
+ You can generate a model fused with the low-rank adapters using the
386
+ `mlx_lm_lora.fuse` command. This command also allows you to optionally:
387
+
388
+ - Upload the fused model to the Hugging Face Hub.
389
+ - Export the fused model to GGUF. Note GGUF support is limited to Mistral,
390
+ Mixtral, and Llama style models in fp16 precision.
391
+
392
+ To see supported options run:
393
+
394
+ ```shell
395
+ mlx_lm_lora.fuse --help
396
+ ```
397
+
398
+ To generate the fused model run:
399
+
400
+ ```shell
401
+ mlx_lm_lora.fuse --model <path_to_model>
402
+ ```
403
+
404
+ This will by default load the adapters from `adapters/`, and save the fused
405
+ model in the path `fused_model/`. All of these are configurable.
406
+
407
+ To upload a fused model, supply the `--upload-repo` and `--hf-path` arguments
408
+ to `mlx_lm_lora.fuse`. The latter is the repo name of the original model, which is
409
+ useful for the sake of attribution and model versioning.
410
+
411
+ For example, to fuse and upload a model derived from Mistral-7B-v0.1, run:
412
+
413
+ ```shell
414
+ mlx_lm_lora.fuse \
415
+ --model mistralai/Mistral-7B-v0.1 \
416
+ --upload-repo mlx-community/my-lora-mistral-7b \
417
+ --hf-path mistralai/Mistral-7B-v0.1
418
+ ```
419
+
420
+ To export a fused model to GGUF, run:
421
+
422
+ ```shell
423
+ mlx_lm_lora.fuse \
424
+ --model mistralai/Mistral-7B-v0.1 \
425
+ --export-gguf
426
+ ```
427
+
428
+ This will save the GGUF model in `fused_model/ggml-model-f16.gguf`. You
429
+ can specify the file name with `--gguf-path`.
430
+
431
+ ---
432
+
433
+ ## Memory Issues
434
+
435
+ Fine-tuning a large model with LoRA requires a machine with a decent amount
436
+ of memory. Here are some tips to reduce memory use should you need to do so:
437
+
438
+ 1. Try quantization (QLoRA). You can use QLoRA by generating a quantized model
439
+ with `convert.py` and the `-q` flag. See the [Setup](#setup) section for
440
+ more details.
441
+
442
+ 2. Try using a smaller batch size with `--batch-size`. The default is `4` so
443
+ setting this to `2` or `1` will reduce memory consumption. This may slow
444
+ things down a little, but will also reduce the memory use.
445
+
446
+ 3. Reduce the number of layers to fine-tune with `--num-layers`. The default
447
+ is `16`, so you can try `8` or `4`. This reduces the amount of memory
448
+ needed for back propagation. It may also reduce the quality of the
449
+ fine-tuned model if you are fine-tuning with a lot of data.
450
+
451
+ 4. Longer examples require more memory. If it makes sense for your data, one thing
452
+ you can do is break your examples into smaller
453
+ sequences when making the `{train, valid, test}.jsonl` files.
454
+
455
+ 5. Gradient checkpointing lets you trade-off memory use (less) for computation
456
+ (more) by recomputing instead of storing intermediate values needed by the
457
+ backward pass. You can use gradient checkpointing by passing the
458
+ `--grad-checkpoint` flag. Gradient checkpointing will be more helpful for
459
+ larger batch sizes or sequence lengths with smaller or quantized models.