Alignment-Lab-AI commited on
Commit
1bad0bb
·
verified ·
1 Parent(s): 81aa678

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.Config.yml.swp ADDED
File without changes
.bandit ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [bandit]
2
+ exclude = tests
3
+ skips = B101
.config.yml.swp ADDED
File without changes
.editorconfig ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ root = true
2
+
3
+ [*]
4
+ end_of_line = lf
5
+ insert_final_newline = true
6
+ trim_trailing_whitespace = true
7
+
8
+ [*.py]
9
+ indent_style = space
10
+ indent_size = 4
11
+
12
+ [**.yml]
13
+ indent_style = space
14
+ indent_size = 2
.flake8 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [flake8]
2
+ max-line-length = 88
3
+
4
+ select = C,E,F,W,B,B950
5
+ extend-ignore = E203, E501, W503
.gitattributes CHANGED
@@ -53,3 +53,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
53
  *.jpg filter=lfs diff=lfs merge=lfs -text
54
  *.jpeg filter=lfs diff=lfs merge=lfs -text
55
  *.webp filter=lfs diff=lfs merge=lfs -text
 
 
 
 
53
  *.jpg filter=lfs diff=lfs merge=lfs -text
54
  *.jpeg filter=lfs diff=lfs merge=lfs -text
55
  *.webp filter=lfs diff=lfs merge=lfs -text
56
+ wandb/run-20240512_103207-vfqtzg1a/logs/debug-internal.log filter=lfs diff=lfs merge=lfs -text
57
+ wandb/run-20240512_103207-vfqtzg1a/run-vfqtzg1a.wandb filter=lfs diff=lfs merge=lfs -text
58
+ wandb/run-20240515_132302-ky6h7dv9/run-ky6h7dv9.wandb filter=lfs diff=lfs merge=lfs -text
.isort.cfg ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [settings]
2
+ profile=black
3
+ known_third_party=wandb
.mypy.ini ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [mypy]
2
+ plugins = pydantic.mypy
3
+ exclude = venv
4
+
5
+ [mypy-alpaca_lora_4bit.*]
6
+ ignore_missing_imports = True
7
+
8
+ [mypy-axolotl.monkeypatch.*]
9
+ ignore_errors = True
10
+
11
+ [mypy-axolotl.models.mixtral.*]
12
+ ignore_errors = True
13
+
14
+ [mypy-axolotl.models.phi.*]
15
+ ignore_errors = True
16
+
17
+ [mypy-flash_attn.*]
18
+ ignore_missing_imports = True
19
+
20
+ [mypy-huggingface_hub]
21
+ ignore_missing_imports = True
22
+
23
+ [mypy-transformers.*]
24
+ ignore_missing_imports = True
25
+
26
+ [mypy-peft]
27
+ ignore_missing_imports = True
28
+
29
+ [mypy-wandb]
30
+ ignore_missing_imports = True
31
+
32
+ [mypy-bitsandbytes]
33
+ ignore_missing_imports = True
34
+
35
+ [mypy-requests]
36
+ ignore_missing_imports = True
37
+
38
+ [mypy-datasets]
39
+ ignore_missing_imports = True
40
+
41
+ [mypy-fire]
42
+ ignore_missing_imports = True
43
+
44
+ [mypy-setuptools]
45
+ ignore_missing_imports = True
46
+
47
+ [mypy-addict]
48
+ ignore_missing_imports = True
49
+
50
+ [mypy-xformers.*]
51
+ ignore_missing_imports = True
.pre-commit-config.yaml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ default_language_version:
2
+ python: python3
3
+
4
+ repos:
5
+ - repo: https://github.com/pre-commit/pre-commit-hooks
6
+ rev: v4.4.0
7
+ hooks:
8
+ - id: check-yaml
9
+ - id: end-of-file-fixer
10
+ - id: trailing-whitespace
11
+ - repo: https://github.com/psf/black
12
+ rev: 23.3.0
13
+ hooks:
14
+ - id: black
15
+ - repo: https://github.com/pycqa/isort
16
+ rev: 5.12.0
17
+ hooks:
18
+ - id: isort
19
+ - repo: https://github.com/PyCQA/flake8
20
+ rev: 6.0.0
21
+ hooks:
22
+ - id: flake8
23
+ - repo: https://github.com/PyCQA/pylint
24
+ rev: v2.17.4
25
+ hooks:
26
+ - id: pylint
27
+ - repo: https://github.com/pre-commit/mirrors-mypy
28
+ rev: v1.3.0
29
+ hooks:
30
+ - id: mypy
31
+ additional_dependencies:
32
+ [
33
+ 'types-PyYAML',
34
+ 'pydantic>=2.5.3',
35
+ ]
36
+ - repo: https://github.com/PyCQA/bandit
37
+ rev: 1.7.5
38
+ hooks:
39
+ - id: bandit
40
+ args: [
41
+ '--ini',
42
+ '.bandit',
43
+ ]
.pylintrc ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [MASTER]
2
+ init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"
3
+
4
+ [TYPECHECK]
5
+
6
+ # List of members which are set dynamically and missed by Pylint inference
7
+ # system, and so shouldn't trigger E1101 when accessed.
8
+ generated-members=numpy.*, torch.*
9
+
10
+
11
+ [pylint.messages_control]
12
+ disable=missing-function-docstring, line-too-long, import-error,
13
+ too-many-arguments, too-many-locals, too-many-statements, too-many-branches, too-few-public-methods,
14
+ too-many-instance-attributes, fixme, import-outside-toplevel, logging-fstring-interpolation,
.vscode/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ See [docs/debugging.md](../docs/debugging.md) for guidance on how to modify these files to debug axolotl with VSCode.
.vscode/launch.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ // Use IntelliSense to learn about possible attributes.
3
+ // Hover to view descriptions of existing attributes.
4
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+ "version": "0.2.0",
6
+ "configurations": [
7
+ {
8
+ "name": "Debug axolotl prompt - sharegpt",
9
+ "type": "python",
10
+ "module": "accelerate.commands.launch",
11
+ "request": "launch",
12
+ "args": [
13
+ "-m", "axolotl.cli.train", "dev_sharegpt.yml",
14
+ // The flags below simplify debugging by overriding the axolotl config
15
+ // with the debugging tips above. Modify as needed.
16
+ "--dataset_processes=1", // limits data preprocessing to one process
17
+ "--max_steps=1", // limits training to just one step
18
+ "--batch_size=1", // minimizes batch size
19
+ "--micro_batch_size=1", // minimizes batch size
20
+ "--val_set_size=0", // disables validation
21
+ "--sample_packing=False", // disables sample packing which is necessary for small datasets
22
+ "--eval_sample_packing=False",// disables sample packing on eval set
23
+ "--dataset_prepared_path=temp_debug/axolotl_outputs/data", // send data outputs to a temp folder
24
+ "--output_dir=temp_debug/axolotl_outputs/model" // send model outputs to a temp folder
25
+ ],
26
+ "console": "integratedTerminal", // show output in the integrated terminal
27
+ "cwd": "${workspaceFolder}/devtools", // set working directory to devtools from the root of the project
28
+ "justMyCode": true, // step through only axolotl code
29
+ "env": {"CUDA_VISIBLE_DEVICES": "0", // Since we aren't doing distributed training, we need to limit to one GPU
30
+ "HF_HOME": "${workspaceFolder}/devtools/temp_debug/.hf-cache"}, // send HF cache to a temp folder
31
+ "preLaunchTask": "cleanup-for-dataprep", // delete temp folders (see below)
32
+ }
33
+ ]
34
+ }
.vscode/tasks.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //this file is used by launch.json
2
+ {
3
+ "version": "2.0.0",
4
+ "tasks": [
5
+ // this task changes into the devtools directory and deletes the temp_debug/axolotl_outputs folder
6
+ {
7
+ "label": "delete-outputs",
8
+ "type": "shell",
9
+ "command": "rm -rf temp_debug/axolotl_outputs",
10
+ "options":{ "cwd": "${workspaceFolder}/devtools"},
11
+ "problemMatcher": []
12
+ },
13
+ // this task changes into the devtools directory and deletes the `temp_debug/.hf-cache/datasets` folder
14
+ {
15
+ "label": "delete-temp-hf-dataset-cache",
16
+ "type": "shell",
17
+ "command": "rm -rf temp_debug/.hf-cache/datasets",
18
+ "options":{ "cwd": "${workspaceFolder}/devtools"},
19
+ "problemMatcher": []
20
+ },
21
+ // this task combines the two tasks above
22
+ {
23
+ "label": "cleanup-for-dataprep",
24
+ "dependsOn": ["delete-outputs", "delete-temp-hf-dataset-cache"],
25
+ }
26
+ ]
27
+ }
Config.yml ADDED
File without changes
FAQS.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # FAQs
2
+
3
+ - Can you train StableLM with this? Yes, but only with a single GPU atm. Multi GPU support is coming soon! Just waiting on this [PR](https://github.com/huggingface/transformers/pull/22874)
4
+ - Will this work with Deepspeed? That's still a WIP, but setting `export ACCELERATE_USE_DEEPSPEED=true` should work in some cases
5
+ - `Error invalid argument at line 359 in file /workspace/bitsandbytes/csrc/pythonInterface.c`
6
+ `/arrow/cpp/src/arrow/filesystem/s3fs.cc:2598: arrow::fs::FinalizeS3 was not called even though S3 was initialized.`
7
+ This could lead to a segmentation fault at exit. Try reinstalling bitsandbytes and transformers from source.
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Axolotl
2
+
3
+ Axolotl is a tool designed to streamline the fine-tuning of various AI models, offering support for multiple configurations and architectures.
4
+
5
+ Features:
6
+ - Train various Huggingface models such as llama, pythia, falcon, mpt
7
+ - Supports fullfinetune, lora, qlora, relora, and gptq
8
+ - Customize configurations using a simple yaml file or CLI overwrite
9
+ - Load different dataset formats, use custom formats, or bring your own tokenized datasets
10
+ - Integrated with xformer, flash attention, rope scaling, and multipacking
11
+ - Works with single GPU or multiple GPUs via FSDP or Deepspeed
12
+ - Easily run with Docker locally or on the cloud
13
+ - Log results and optionally checkpoints to wandb or mlflow
14
+ - And more!
15
+
16
+ <a href="https://www.phorm.ai/query?projectId=e315ba4a-4e14-421f-ab05-38a1f9076f25">
17
+ <img alt="phorm.ai" src="https://img.shields.io/badge/Phorm-Ask_AI-%23F2777A.svg?&logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNSIgaGVpZ2h0PSI0IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxwYXRoIGQ9Ik00LjQzIDEuODgyYTEuNDQgMS40NCAwIDAgMS0uMDk4LjQyNmMtLjA1LjEyMy0uMTE1LjIzLS4xOTIuMzIyLS4wNzUuMDktLjE2LjE2NS0uMjU1LjIyNmExLjM1MyAxLjM1MyAwIDAgMS0uNTk1LjIxMmMtLjA5OS4wMTItLjE5Mi4wMTQtLjI3OS4wMDZsLTEuNTkzLS4xNHYtLjQwNmgxLjY1OGMuMDkuMDAxLjE3LS4xNjkuMjQ2LS4xOTFhLjYwMy42MDMgMCAwIDAgLjItLjEwNi41MjkuNTI5IDAgMCAwIC4xMzgtLjE3LjY1NC42NTQgMCAwIDAgLjA2NS0uMjRsLjAyOC0uMzJhLjkzLjkzIDAgMCAwLS4wMzYtLjI0OS41NjcuNTY3IDAgMCAwLS4xMDMtLjIuNTAyLjUwMiAwIDAgMC0uMTY4LS4xMzguNjA4LjYwOCAwIDAgMC0uMjQtLjA2N0wyLjQzNy43MjkgMS42MjUuNjcxYS4zMjIuMzIyIDAgMCAwLS4yMzIuMDU4LjM3NS4zNzUgMCAwIDAtLjExNi4yMzJsLS4xMTYgMS40NS0uMDU4LjY5Ny0uMDU4Ljc1NEwuNzA1IDRsLS4zNTctLjA3OUwuNjAyLjkwNkMuNjE3LjcyNi42NjMuNTc0LjczOS40NTRhLjk1OC45NTggMCAwIDEgLjI3NC0uMjg1Ljk3MS45NzEgMCAwIDEgLjMzNy0uMTRjLjExOS0uMDI2LjIyNy0uMDM0LjMyNS0uMDI2TDMuMjMyLjE2Yy4xNTkuMDE0LjMzNi4wMy40NTkuMDgyYTEuMTczIDEuMTczIDAgMCAxIC41NDUuNDQ3Yy4wNi4wOTQuMTA5LjE5Mi4xNDQuMjkzYTEuMzkyIDEuMzkyIDAgMCAxIC4wNzguNThsLS4wMjkuMzJaIiBmaWxsPSIjRjI3NzdBIi8+CiAgPHBhdGggZD0iTTQuMDgyIDIuMDA3YTEuNDU1IDEuNDU1IDAgMCAxLS4wOTguNDI3Yy0uMDUuMTI0LS4xMTQuMjMyLS4xOTIuMzI0YTEuMTMgMS4xMyAwIDAgMS0uMjU0LjIyNyAxLjM1MyAxLjM1MyAwIDAgMS0uNTk1LjIxNGMtLjEuMDEyLS4xOTMuMDE0LS4yOC4wMDZsLTEuNTYtLjEwOC4wMzQtLjQwNi4wMy0uMzQ4IDEuNTU5LjE1NGMuMDkgMCAuMTczLS4wMS4yNDgtLjAzM2EuNjAzLjYwMyAwIDAgMCAuMi0uMTA2LjUzMi41MzIgMCAwIDAgLjEzOS0uMTcyLjY2LjY2IDAgMCAwIC4wNjQtLjI0MWwuMDI5LS4zMjFhLjk0Ljk0IDAgMCAwLS4wMzYtLjI1LjU3LjU3IDAgMCAwLS4xMDMtLjIwMi41MDIuNTAyIDAgMCAwLS4xNjgtLjEzOC42MDUuNjA1IDAgMCAwLS4yNC0uMDY3TDEuMjczLjgyN2MtLjA5NC0uMDA4LS4xNjguMDEtLjIyMS4wNTUtLjA1My4wNDUtLjA4NC4xMTQtLjA5Mi4yMDZMLjcwNSA0IDAgMy45MzhsLjI1NS0yLjkxMUExLjAxIDEuMDEgMCAwIDEgLjM5My41NzIuOTYyLjk2MiAwIDAgMSAuNjY2LjI4NmEuOTcuOTcgMCAwIDEgLjMzOC0uMTRDMS4xMjIuMTIgMS4yMy4xMSAxLjMyOC4xMTlsMS41OTMuMTRjLjE2LjAxNC4zLjA0Ny40MjMuMWExLjE3IDEuMTcgMCAwIDEgLjU0NS40NDhjLjA2MS4wOTUuMTA5LjE5My4xNDQuMjk1YTEuNDA2IDEuNDA2IDAgMCAxIC4wNzcuNTgzbC0uMDI4LjMyMloiIGZpbGw9IndoaXRlIi8+CiAgPHBhdGggZD0iTTQuMDgyIDIuMDA3YTEuNDU1IDEuNDU1IDAgMCAxLS4wOTguNDI3Yy0uMDUuMTI0LS4xMTQuMjMyLS4xOTIuMzI0YTEuMTMgMS4xMyAwIDAgMS0uMjU0LjIyNyAxLjM1MyAxLjM1MyAwIDAgMS0uNTk1LjIxNGMtLjEuMDEyLS4xOTMuMDE0LS4yOC4wMDZsLTEuNTYtLjEwOC4wMzQtLjQwNi4wMy0uMzQ4IDEuNTU5LjE1NGMuMDkgMCAuMTczLS4wMS4yNDgtLjAzM2EuNjAzLjYwMyAwIDAgMCAuMi0uMTA2LjUzMi41MzIgMCAwIDAgLjEzOS0uMTcyLjY2LjY2IDAgMCAwIC4wNjQtLjI0MWwuMDI5LS4zMjFhLjk0Ljk0IDAgMCAwLS4wMzYtLjI1LjU3LjU3IDAgMCAwLS4xMDMtLjIwMi41MDIuNTAyIDAgMCAwLS4xNjgtLjEzOC42MDUuNjA1IDAgMCAwLS4yNC0uMDY3TDEuMjczLjgyN2MtLjA5NC0uMDA4LS4xNjguMDEtLjIyMS4wNTUtLjA1My4wNDUtLjA4NC4xMTQtLjA5Mi4yMDZMLjcwNSA0IDAgMy45MzhsLjI1NS0yLjkxMUExLjAxIDEuMDEgMCAwIDEgLjM5My41NzIuOTYyLjk2MiAwIDAgMSAuNjY2LjI4NmEuOTcuOTcgMCAwIDEgLjMzOC0uMTRDMS4xMjIuMTIgMS4yMy4xMSAxLjMyOC4xMTlsMS41OTMuMTRjLjE2LjAxNC4zLjA0Ny40MjMuMWExLjE3IDEuMTcgMCAwIDEgLjU0NS40NDhjLjA2MS4wOTUuMTA5LjE5My4xNDQuMjk1YTEuNDA2IDEuNDA2IDAgMCAxIC4wNzcuNTgzbC0uMDI4LjMyMloiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=">
18
+ </a>
19
+
20
+ <table>
21
+ <tr>
22
+ <td>
23
+
24
+ ## Table of Contents
25
+ - [Introduction](#axolotl)
26
+ - [Supported Features](#axolotl-supports)
27
+ - [Quickstart](#quickstart-)
28
+ - [Environment](#environment)
29
+ - [Docker](#docker)
30
+ - [Conda/Pip venv](#condapip-venv)
31
+ - [Cloud GPU](#cloud-gpu) - Latitude.sh, JarvisLabs, RunPod
32
+ - [Bare Metal Cloud GPU](#bare-metal-cloud-gpu)
33
+ - [Windows](#windows)
34
+ - [Mac](#mac)
35
+ - [Google Colab](#google-colab)
36
+ - [Launching on public clouds via SkyPilot](#launching-on-public-clouds-via-skypilot)
37
+ - [Launching on public clouds via dstack](#launching-on-public-clouds-via-dstack)
38
+ - [Dataset](#dataset)
39
+ - [Config](#config)
40
+ - [Train](#train)
41
+ - [Inference](#inference-playground)
42
+ - [Merge LORA to Base](#merge-lora-to-base)
43
+ - [Special Tokens](#special-tokens)
44
+ - [All Config Options](#all-config-options)
45
+ - Advanced Topics
46
+ - [Multipack](./docs/multipack.qmd)<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9" class="icon_svg-stroke" stroke="#666" stroke-width="1.5" fill="none" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="round"></path></svg>
47
+ - [RLHF & DPO](./docs/rlhf.qmd)<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9" class="icon_svg-stroke" stroke="#666" stroke-width="1.5" fill="none" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="round"></path></svg>
48
+ - [Dataset Pre-Processing](./docs/dataset_preprocessing.qmd)<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9" class="icon_svg-stroke" stroke="#666" stroke-width="1.5" fill="none" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="round"></path></svg>
49
+ - [Common Errors](#common-errors-)
50
+ - [Tokenization Mismatch b/w Training & Inference](#tokenization-mismatch-bw-inference--training)
51
+ - [Debugging Axolotl](#debugging-axolotl)
52
+ - [Need Help?](#need-help-)
53
+ - [Badge](#badge-)
54
+ - [Community Showcase](#community-showcase)
55
+ - [Contributing](#contributing-)
56
+ - [Sponsors](#sponsors-)
57
+
58
+ </td>
59
+ <td>
60
+
61
+ <div align="center">
62
+ <img src="image/axolotl.png" alt="axolotl" width="160">
63
+ <div>
64
+ <p>
65
+ <b>Axolotl provides a unified repository for fine-tuning <br />a variety of AI models with ease</b>
66
+ </p>
67
+ <p>
68
+ Go ahead and Axolotl questions!!
69
+ </p>
70
+ <img src="https://github.com/OpenAccess-AI-Collective/axolotl/actions/workflows/pre-commit.yml/badge.svg?branch=main" alt="pre-commit">
71
+ <img alt="PyTest Status" src="https://github.com/OpenAccess-AI-Collective/axolotl/actions/workflows/tests.yml/badge.svg?branch=main">
72
+ </div>
73
+ </div>
74
+
75
+ </td>
76
+ </tr>
77
+ </table>
78
+
79
+ ## Axolotl supports
80
+
81
+ | | fp16/fp32 | lora | qlora | gptq | gptq w/flash attn | flash attn | xformers attn |
82
+ |-------------|:----------|:-----|-------|------|-------------------|------------|--------------|
83
+ | llama | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
84
+ | Mistral | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
85
+ | Mixtral-MoE | ✅ | ✅ | ✅ | ❓ | ❓ | ❓ | ❓ |
86
+ | Mixtral8X22 | ✅ | ✅ | ✅ | ❓ | ❓ | ❓ | ❓ |
87
+ | Pythia | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❓ |
88
+ | cerebras | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❓ |
89
+ | btlm | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❓ |
90
+ | mpt | ✅ | ❌ | ❓ | ❌ | ❌ | ❌ | ❓ |
91
+ | falcon | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❓ |
92
+ | gpt-j | ✅ | ✅ | ✅ | ❌ | ❌ | ❓ | ❓ |
93
+ | XGen | ✅ | ❓ | ✅ | ❓ | ❓ | ❓ | ✅ |
94
+ | phi | ✅ | ✅ | ✅ | ❓ | ❓ | ❓ | ❓ |
95
+ | RWKV | ✅ | ❓ | ❓ | ❓ | ❓ | ❓ | ❓ |
96
+ | Qwen | ✅ | ✅ | ✅ | ❓ | ❓ | ❓ | ❓ |
97
+ | Gemma | ✅ | ✅ | ✅ | ❓ | ❓ | ✅ | ❓ |
98
+
99
+ ✅: supported
100
+ ❌: not supported
101
+ ❓: untested
102
+
103
+ ## Quickstart ⚡
104
+
105
+ Get started with Axolotl in just a few steps! This quickstart guide will walk you through setting up and running a basic fine-tuning task.
106
+
107
+ **Requirements**: Python >=3.10 and Pytorch >=2.1.1.
108
+
109
+ ```bash
110
+ git clone https://github.com/OpenAccess-AI-Collective/axolotl
111
+ cd axolotl
112
+
113
+ pip3 install packaging ninja
114
+ pip3 install -e '.[flash-attn,deepspeed]'
115
+ ```
116
+
117
+ ### Usage
118
+ ```bash
119
+ # preprocess datasets - optional but recommended
120
+ CUDA_VISIBLE_DEVICES="" python -m axolotl.cli.preprocess examples/openllama-3b/lora.yml
121
+
122
+ # finetune lora
123
+ accelerate launch -m axolotl.cli.train examples/openllama-3b/lora.yml
124
+
125
+ # inference
126
+ accelerate launch -m axolotl.cli.inference examples/openllama-3b/lora.yml \
127
+ --lora_model_dir="./lora-out"
128
+
129
+ # gradio
130
+ accelerate launch -m axolotl.cli.inference examples/openllama-3b/lora.yml \
131
+ --lora_model_dir="./lora-out" --gradio
132
+
133
+ # remote yaml files - the yaml config can be hosted on a public URL
134
+ # Note: the yaml config must directly link to the **raw** yaml
135
+ accelerate launch -m axolotl.cli.train https://raw.githubusercontent.com/OpenAccess-AI-Collective/axolotl/main/examples/openllama-3b/lora.yml
136
+ ```
137
+
138
+ ## Advanced Setup
139
+
140
+ ### Environment
141
+
142
+ #### Docker
143
+
144
+ ```bash
145
+ docker run --gpus '"all"' --rm -it winglian/axolotl:main-latest
146
+ ```
147
+
148
+ Or run on the current files for development:
149
+
150
+ ```sh
151
+ docker compose up -d
152
+ ```
153
+
154
+ >[!Tip]
155
+ > If you want to debug axolotl or prefer to use Docker as your development environment, see the [debugging guide's section on Docker](docs/debugging.qmd#debugging-with-docker).
156
+
157
+ <details>
158
+
159
+ <summary>Docker advanced</summary>
160
+
161
+ A more powerful Docker command to run would be this:
162
+
163
+ ```bash
164
+ docker run --privileged --gpus '"all"' --shm-size 10g --rm -it --name axolotl --ipc=host --ulimit memlock=-1 --ulimit stack=67108864 --mount type=bind,src="${PWD}",target=/workspace/axolotl -v ${HOME}/.cache/huggingface:/root/.cache/huggingface winglian/axolotl:main-latest
165
+ ```
166
+
167
+ It additionally:
168
+ * Prevents memory issues when running e.g. deepspeed (e.g. you could hit SIGBUS/signal 7 error) through `--ipc` and `--ulimit` args.
169
+ * Persists the downloaded HF data (models etc.) and your modifications to axolotl code through `--mount`/`-v` args.
170
+ * The `--name` argument simply makes it easier to refer to the container in vscode (`Dev Containers: Attach to Running Container...`) or in your terminal.
171
+ * The `--privileged` flag gives all capabilities to the container.
172
+ * The `--shm-size 10g` argument increases the shared memory size. Use this if you see `exitcode: -7` errors using deepspeed.
173
+
174
+ [More information on nvidia website](https://docs.nvidia.com/deeplearning/frameworks/user-guide/index.html#setincshmem)
175
+
176
+ </details>
177
+
178
+ #### Conda/Pip venv
179
+ 1. Install python >=**3.10**
180
+
181
+ 2. Install pytorch stable https://pytorch.org/get-started/locally/
182
+
183
+ 3. Install Axolotl along with python dependencies
184
+ ```bash
185
+ pip3 install packaging
186
+ pip3 install -e '.[flash-attn,deepspeed]'
187
+ ```
188
+ 4. (Optional) Login to Huggingface to use gated models/datasets.
189
+ ```bash
190
+ huggingface-cli login
191
+ ```
192
+ Get the token at huggingface.co/settings/tokens
193
+
194
+ #### Cloud GPU
195
+
196
+ For cloud GPU providers that support docker images, use [`winglian/axolotl-cloud:main-latest`](https://hub.docker.com/r/winglian/axolotl-cloud/tags)
197
+
198
+ - on Latitude.sh use this [direct link](https://latitude.sh/blueprint/989e0e79-3bf6-41ea-a46b-1f246e309d5c)
199
+ - on JarvisLabs.ai use this [direct link](https://jarvislabs.ai/templates/axolotl)
200
+ - on RunPod use this [direct link](https://runpod.io/gsc?template=v2ickqhz9s&ref=6i7fkpdz)
201
+
202
+ #### Bare Metal Cloud GPU
203
+
204
+ ##### LambdaLabs
205
+
206
+ <details>
207
+
208
+ <summary>Click to Expand</summary>
209
+
210
+ 1. Install python
211
+ ```bash
212
+ sudo apt update
213
+ sudo apt install -y python3.10
214
+
215
+ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.10 1
216
+ sudo update-alternatives --config python # pick 3.10 if given option
217
+ python -V # should be 3.10
218
+
219
+ ```
220
+
221
+ 2. Install pip
222
+ ```bash
223
+ wget https://bootstrap.pypa.io/get-pip.py
224
+ python get-pip.py
225
+ ```
226
+
227
+ 3. Install Pytorch https://pytorch.org/get-started/locally/
228
+
229
+ 4. Follow instructions on quickstart.
230
+
231
+ 5. Run
232
+ ```bash
233
+ pip3 install protobuf==3.20.3
234
+ pip3 install -U --ignore-installed requests Pillow psutil scipy
235
+ ```
236
+
237
+ 6. Set path
238
+ ```bash
239
+ export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH
240
+ ```
241
+ </details>
242
+
243
+ ##### GCP
244
+
245
+ <details>
246
+
247
+ <summary>Click to Expand</summary>
248
+
249
+ Use a Deeplearning linux OS with cuda and pytorch installed. Then follow instructions on quickstart.
250
+
251
+ Make sure to run the below to uninstall xla.
252
+ ```bash
253
+ pip uninstall -y torch_xla[tpu]
254
+ ```
255
+
256
+ </details>
257
+
258
+ #### Windows
259
+ Please use WSL or Docker!
260
+
261
+ #### Mac
262
+
263
+ Use the below instead of the install method in QuickStart.
264
+ ```
265
+ pip3 install -e '.'
266
+ ```
267
+ More info: [mac.md](/docs/mac.qmd)
268
+
269
+ #### Google Colab
270
+
271
+ Please use this example [notebook](examples/colab-notebooks/colab-axolotl-example.ipynb).
272
+
273
+ #### Launching on public clouds via SkyPilot
274
+ To launch on GPU instances (both on-demand and spot instances) on 7+ clouds (GCP, AWS, Azure, OCI, and more), you can use [SkyPilot](https://skypilot.readthedocs.io/en/latest/index.html):
275
+
276
+ ```bash
277
+ pip install "skypilot-nightly[gcp,aws,azure,oci,lambda,kubernetes,ibm,scp]" # choose your clouds
278
+ sky check
279
+ ```
280
+
281
+ Get the [example YAMLs](https://github.com/skypilot-org/skypilot/tree/master/llm/axolotl) of using Axolotl to finetune `mistralai/Mistral-7B-v0.1`:
282
+ ```
283
+ git clone https://github.com/skypilot-org/skypilot.git
284
+ cd skypilot/llm/axolotl
285
+ ```
286
+
287
+ Use one command to launch:
288
+ ```bash
289
+ # On-demand
290
+ HF_TOKEN=xx sky launch axolotl.yaml --env HF_TOKEN
291
+
292
+ # Managed spot (auto-recovery on preemption)
293
+ HF_TOKEN=xx BUCKET=<unique-name> sky spot launch axolotl-spot.yaml --env HF_TOKEN --env BUCKET
294
+ ```
295
+
296
+ #### Launching on public clouds via dstack
297
+ To launch on GPU instance (both on-demand and spot instances) on public clouds (GCP, AWS, Azure, Lambda Labs, TensorDock, Vast.ai, and CUDO), you can use [dstack](https://dstack.ai/).
298
+
299
+ Write a job description in YAML as below:
300
+
301
+ ```yaml
302
+ # dstack.yaml
303
+ type: task
304
+
305
+ image: winglian/axolotl-cloud:main-20240429-py3.11-cu121-2.2.2
306
+
307
+ env:
308
+ - HUGGING_FACE_HUB_TOKEN
309
+ - WANDB_API_KEY
310
+
311
+ commands:
312
+ - accelerate launch -m axolotl.cli.train config.yaml
313
+
314
+ ports:
315
+ - 6006
316
+
317
+ resources:
318
+ gpu:
319
+ memory: 24GB..
320
+ count: 2
321
+ ```
322
+
323
+ then, simply run the job with `dstack run` command. Append `--spot` option if you want spot instance. `dstack run` command will show you the instance with cheapest price across multi cloud services:
324
+
325
+ ```bash
326
+ pip install dstack
327
+ HUGGING_FACE_HUB_TOKEN=xxx WANDB_API_KEY=xxx dstack run . -f dstack.yaml # --spot
328
+ ```
329
+
330
+ For further and fine-grained use cases, please refer to the official [dstack documents](https://dstack.ai/docs/) and the detailed description of [axolotl example](https://github.com/dstackai/dstack/tree/master/examples/fine-tuning/axolotl) on the official repository.
331
+
332
+ ### Dataset
333
+
334
+ Axolotl supports a variety of dataset formats. It is recommended to use a JSONL. The schema of the JSONL depends upon the task and the prompt template you wish to use. Instead of a JSONL, you can also use a HuggingFace dataset with columns for each JSONL field.
335
+
336
+ See [these docs](https://openaccess-ai-collective.github.io/axolotl/docs/dataset-formats/) for more information on how to use different dataset formats.
337
+
338
+ ### Config
339
+
340
+ See [examples](examples) for quick start. It is recommended to duplicate and modify to your needs. The most important options are:
341
+
342
+ - model
343
+ ```yaml
344
+ base_model: ./llama-7b-hf # local or huggingface repo
345
+ ```
346
+ Note: The code will load the right architecture.
347
+
348
+ - dataset
349
+ ```yaml
350
+ datasets:
351
+ # huggingface repo
352
+ - path: vicgalle/alpaca-gpt4
353
+ type: alpaca
354
+
355
+ # huggingface repo with specific configuration/subset
356
+ - path: EleutherAI/pile
357
+ name: enron_emails
358
+ type: completion # format from earlier
359
+ field: text # Optional[str] default: text, field to use for completion data
360
+
361
+ # huggingface repo with multiple named configurations/subsets
362
+ - path: bigcode/commitpackft
363
+ name:
364
+ - ruby
365
+ - python
366
+ - typescript
367
+ type: ... # unimplemented custom format
368
+
369
+ # fastchat conversation
370
+ # See 'conversation' options: https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
371
+ - path: ...
372
+ type: sharegpt
373
+ conversation: chatml # default: vicuna_v1.1
374
+
375
+ # local
376
+ - path: data.jsonl # or json
377
+ ds_type: json # see other options below
378
+ type: alpaca
379
+
380
+ # dataset with splits, but no train split
381
+ - path: knowrohit07/know_sql
382
+ type: context_qa.load_v2
383
+ train_on_split: validation
384
+
385
+ # loading from s3 or gcs
386
+ # s3 creds will be loaded from the system default and gcs only supports public access
387
+ - path: s3://path_to_ds # Accepts folder with arrow/parquet or file path like above. Supports s3, gcs.
388
+ ...
389
+
390
+ # Loading Data From a Public URL
391
+ # - The file format is `json` (which includes `jsonl`) by default. For different formats, adjust the `ds_type` option accordingly.
392
+ - path: https://some.url.com/yourdata.jsonl # The URL should be a direct link to the file you wish to load. URLs must use HTTPS protocol, not HTTP.
393
+ ds_type: json # this is the default, see other options below.
394
+ ```
395
+
396
+ - loading
397
+ ```yaml
398
+ load_in_4bit: true
399
+ load_in_8bit: true
400
+
401
+ bf16: auto # require >=ampere, auto will detect if your GPU supports this and choose automatically.
402
+ fp16: # leave empty to use fp16 when bf16 is 'auto'. set to false if you want to fallback to fp32
403
+ tf32: true # require >=ampere
404
+
405
+ bfloat16: true # require >=ampere, use instead of bf16 when you don't want AMP (automatic mixed precision)
406
+ float16: true # use instead of fp16 when you don't want AMP
407
+ ```
408
+ Note: Repo does not do 4-bit quantization.
409
+
410
+ - lora
411
+ ```yaml
412
+ adapter: lora # 'qlora' or leave blank for full finetune
413
+ lora_r: 8
414
+ lora_alpha: 16
415
+ lora_dropout: 0.05
416
+ lora_target_modules:
417
+ - q_proj
418
+ - v_proj
419
+ ```
420
+
421
+ #### All Config Options
422
+
423
+ See [these docs](docs/config.qmd) for all config options.
424
+
425
+ ### Train
426
+
427
+ Run
428
+ ```bash
429
+ accelerate launch -m axolotl.cli.train your_config.yml
430
+ ```
431
+
432
+ > [!TIP]
433
+ > You can also reference a config file that is hosted on a public URL, for example `accelerate launch -m axolotl.cli.train https://yourdomain.com/your_config.yml`
434
+
435
+ #### Preprocess dataset
436
+
437
+ You can optionally pre-tokenize dataset with the following before finetuning.
438
+ This is recommended for large datasets.
439
+
440
+ - Set `dataset_prepared_path:` to a local folder for saving and loading pre-tokenized dataset.
441
+ - (Optional): Set `push_dataset_to_hub: hf_user/repo` to push it to Huggingface.
442
+ - (Optional): Use `--debug` to see preprocessed examples.
443
+
444
+ ```bash
445
+ python -m axolotl.cli.preprocess your_config.yml
446
+ ```
447
+
448
+ #### Multi-GPU
449
+
450
+ Below are the options available in axolotl for training with multiple GPUs. Note that DeepSpeed
451
+ is the recommended multi-GPU option currently because FSDP may experience
452
+ [loss instability](https://github.com/huggingface/transformers/issues/26498).
453
+
454
+ ##### DeepSpeed
455
+
456
+ Deepspeed is an optimization suite for multi-gpu systems allowing you to train much larger models than you
457
+ might typically be able to fit into your GPU's VRAM. More information about the various optimization types
458
+ for deepspeed is available at https://huggingface.co/docs/accelerate/main/en/usage_guides/deepspeed#what-is-integrated
459
+
460
+ We provide several default deepspeed JSON configurations for ZeRO stage 1, 2, and 3.
461
+
462
+ ```yaml
463
+ deepspeed: deepspeed_configs/zero1.json
464
+ ```
465
+
466
+ ```shell
467
+ accelerate launch -m axolotl.cli.train examples/llama-2/config.yml --deepspeed deepspeed_configs/zero1.json
468
+ ```
469
+
470
+ ##### FSDP
471
+
472
+ - llama FSDP
473
+ ```yaml
474
+ fsdp:
475
+ - full_shard
476
+ - auto_wrap
477
+ fsdp_config:
478
+ fsdp_offload_params: true
479
+ fsdp_state_dict_type: FULL_STATE_DICT
480
+ fsdp_transformer_layer_cls_to_wrap: LlamaDecoderLayer
481
+ ```
482
+
483
+ ##### FSDP + QLoRA
484
+
485
+ Axolotl supports training with FSDP and QLoRA, see [these docs](docs/fsdp_qlora.qmd) for more information.
486
+
487
+ ##### Weights & Biases Logging
488
+
489
+ Make sure your `WANDB_API_KEY` environment variable is set (recommended) or you login to wandb with `wandb login`.
490
+
491
+ - wandb options
492
+ ```yaml
493
+ wandb_mode:
494
+ wandb_project:
495
+ wandb_entity:
496
+ wandb_watch:
497
+ wandb_name:
498
+ wandb_log_model:
499
+ ```
500
+
501
+ ##### Special Tokens
502
+
503
+ It is important to have special tokens like delimiters, end-of-sequence, beginning-of-sequence in your tokenizer's vocabulary. This will help you avoid tokenization issues and help your model train better. You can do this in axolotl like this:
504
+
505
+ ```yml
506
+ special_tokens:
507
+ bos_token: "<s>"
508
+ eos_token: "</s>"
509
+ unk_token: "<unk>"
510
+ tokens: # these are delimiters
511
+ - "<|im_start|>"
512
+ - "<|im_end|>"
513
+ ```
514
+
515
+ When you include these tokens in your axolotl config, axolotl adds these tokens to the tokenizer's vocabulary.
516
+
517
+ ### Inference Playground
518
+
519
+ Axolotl allows you to load your model in an interactive terminal playground for quick experimentation.
520
+ The config file is the same config file used for training.
521
+
522
+ Pass the appropriate flag to the inference command, depending upon what kind of model was trained:
523
+
524
+ - Pretrained LORA:
525
+ ```bash
526
+ python -m axolotl.cli.inference examples/your_config.yml --lora_model_dir="./lora-output-dir"
527
+ ```
528
+ - Full weights finetune:
529
+ ```bash
530
+ python -m axolotl.cli.inference examples/your_config.yml --base_model="./completed-model"
531
+ ```
532
+ - Full weights finetune w/ a prompt from a text file:
533
+ ```bash
534
+ cat /tmp/prompt.txt | python -m axolotl.cli.inference examples/your_config.yml \
535
+ --base_model="./completed-model" --prompter=None --load_in_8bit=True
536
+ ```
537
+ -- With gradio hosting
538
+ ```bash
539
+ python -m axolotl.cli.inference examples/your_config.yml --gradio
540
+ ```
541
+
542
+ Please use `--sample_packing False` if you have it on and receive the error similar to below:
543
+
544
+ > RuntimeError: stack expects each tensor to be equal size, but got [1, 32, 1, 128] at entry 0 and [1, 32, 8, 128] at entry 1
545
+
546
+ ### Merge LORA to base
547
+
548
+ The following command will merge your LORA adapater with your base model. You can optionally pass the argument `--lora_model_dir` to specify the directory where your LORA adapter was saved, otherwhise, this will be inferred from `output_dir` in your axolotl config file. The merged model is saved in the sub-directory `{lora_model_dir}/merged`.
549
+
550
+ ```bash
551
+ python3 -m axolotl.cli.merge_lora your_config.yml --lora_model_dir="./completed-model"
552
+ ```
553
+
554
+ You may need to use the `gpu_memory_limit` and/or `lora_on_cpu` config options to avoid running out of memory. If you still run out of CUDA memory, you can try to merge in system RAM with
555
+
556
+ ```bash
557
+ CUDA_VISIBLE_DEVICES="" python3 -m axolotl.cli.merge_lora ...
558
+ ```
559
+
560
+ although this will be very slow, and using the config options above are recommended instead.
561
+
562
+ ## Common Errors 🧰
563
+
564
+ See also the [FAQ's](./docs/faq.qmd) and [debugging guide](docs/debugging.qmd).
565
+
566
+ > If you encounter a 'Cuda out of memory' error, it means your GPU ran out of memory during the training process. Here's how to resolve it:
567
+
568
+ Please reduce any below
569
+ - `micro_batch_size`
570
+ - `eval_batch_size`
571
+ - `gradient_accumulation_steps`
572
+ - `sequence_len`
573
+
574
+ If it does not help, try running without deepspeed and without accelerate (replace "accelerate launch" with "python") in the command.
575
+
576
+ Using adamw_bnb_8bit might also save you some memory.
577
+
578
+ > `failed (exitcode: -9)`
579
+
580
+ Usually means your system has run out of system memory.
581
+ Similarly, you should consider reducing the same settings as when you run out of VRAM.
582
+ Additionally, look into upgrading your system RAM which should be simpler than GPU upgrades.
583
+
584
+ > RuntimeError: expected scalar type Float but found Half
585
+
586
+ Try set `fp16: true`
587
+
588
+ > NotImplementedError: No operator found for `memory_efficient_attention_forward` ...
589
+
590
+ Try to turn off xformers.
591
+
592
+ > accelerate config missing
593
+
594
+ It's safe to ignore it.
595
+
596
+ > NCCL Timeouts during training
597
+
598
+ See the [NCCL](docs/nccl.qmd) guide.
599
+
600
+
601
+ ### Tokenization Mismatch b/w Inference & Training
602
+
603
+ For many formats, Axolotl constructs prompts by concatenating token ids _after_ tokenizing strings. The reason for concatenating token ids rather than operating on strings is to maintain precise accounting for attention masks.
604
+
605
+ If you decode a prompt constructed by axolotl, you might see spaces between tokens (or lack thereof) that you do not expect, especially around delimiters and special tokens. When you are starting out with a new format, you should always do the following:
606
+
607
+ 1. Materialize some data using `python -m axolotl.cli.preprocess your_config.yml --debug`, and then decode the first few rows with your model's tokenizer.
608
+ 2. During inference, right before you pass a tensor of token ids to your model, decode these tokens back into a string.
609
+ 3. Make sure the inference string from #2 looks **exactly** like the data you fine tuned on from #1, including spaces and new lines. If they aren't the same, adjust your inference server accordingly.
610
+ 4. As an additional troubleshooting step, you can look at the token ids between 1 and 2 to make sure they are identical.
611
+
612
+ Having misalignment between your prompts during training and inference can cause models to perform very poorly, so it is worth checking this. See [this blog post](https://hamel.dev/notes/llm/05_tokenizer_gotchas.html) for a concrete example.
613
+
614
+ ## Debugging Axolotl
615
+
616
+ See [this debugging guide](docs/debugging.qmd) for tips on debugging Axolotl, along with an example configuration for debugging with VSCode.
617
+
618
+ ## Need help? 🙋
619
+
620
+ Join our [Discord server](https://discord.gg/HhrNrHJPRb) where we our community members can help you.
621
+
622
+ Need dedicated support? Please contact us at [✉️[email protected]](mailto:[email protected]) for dedicated support options.
623
+
624
+ ## Badge ❤🏷️
625
+
626
+ Building something cool with Axolotl? Consider adding a badge to your model card.
627
+
628
+ ```markdown
629
+ [<img src="https://raw.githubusercontent.com/OpenAccess-AI-Collective/axolotl/main/image/axolotl-badge-web.png" alt="Built with Axolotl" width="200" height="32"/>](https://github.com/OpenAccess-AI-Collective/axolotl)
630
+ ```
631
+
632
+ [<img src="https://raw.githubusercontent.com/OpenAccess-AI-Collective/axolotl/main/image/axolotl-badge-web.png" alt="Built with Axolotl" width="200" height="32"/>](https://github.com/OpenAccess-AI-Collective/axolotl)
633
+
634
+ ## Community Showcase
635
+
636
+ Check out some of the projects and models that have been built using Axolotl! Have a model you'd like to add to our Community Showcase? Open a PR with your model.
637
+
638
+ Open Access AI Collective
639
+ - [Minotaur 13b](https://huggingface.co/openaccess-ai-collective/minotaur-13b-fixed)
640
+ - [Manticore 13b](https://huggingface.co/openaccess-ai-collective/manticore-13b)
641
+ - [Hippogriff 30b](https://huggingface.co/openaccess-ai-collective/hippogriff-30b-chat)
642
+
643
+ PocketDoc Labs
644
+ - [Dan's PersonalityEngine 13b LoRA](https://huggingface.co/PocketDoc/Dans-PersonalityEngine-13b-LoRA)
645
+
646
+ ## Contributing 🤝
647
+
648
+ Please read the [contributing guide](./.github/CONTRIBUTING.md)
649
+
650
+ Bugs? Please check the [open issues](https://github.com/OpenAccess-AI-Collective/axolotl/issues/bug) else create a new Issue.
651
+
652
+ PRs are **greatly welcome**!
653
+
654
+ Please run the quickstart instructions followed by the below to setup env:
655
+ ```bash
656
+ pip3 install -r requirements-dev.txt -r requirements-tests.txt
657
+ pre-commit install
658
+
659
+ # test
660
+ pytest tests/
661
+
662
+ # optional: run against all files
663
+ pre-commit run --all-files
664
+ ```
665
+
666
+ Thanks to all of our contributors to date. Help drive open source AI progress forward by contributing to Axolotl.
667
+
668
+ <a href="https://github.com/openaccess-ai-collective/axolotl/graphs/contributors">
669
+ <img src="https://contrib.rocks/image?repo=openaccess-ai-collective/axolotl" alt="contributor chart by https://contrib.rocks"/>
670
+ </a>
671
+
672
+ ## Sponsors 🤝❤
673
+
674
+ OpenAccess AI Collective is run by volunteer contributors such as [winglian](https://github.com/winglian),
675
+ [NanoCode012](https://github.com/NanoCode012), [tmm1](https://github.com/tmm1),
676
+ [mhenrichsen](https://github.com/mhenrichsen), [casper-hansen](https://github.com/casper-hansen),
677
+ [hamelsmu](https://github.com/hamelsmu) and many more who help us accelerate forward by fixing bugs, answering
678
+ community questions and implementing new features. Axolotl needs donations from sponsors for the compute needed to
679
+ run our unit & integration tests, troubleshooting community issues, and providing bounties. If you love axolotl,
680
+ consider sponsoring the project via [GitHub Sponsors](https://github.com/sponsors/OpenAccess-AI-Collective),
681
+ [Ko-fi](https://ko-fi.com/axolotl_ai) or reach out directly to
682
683
+
684
+ ---
685
+
686
+ #### 💎 Diamond Sponsors - [Contact directly](mailto:[email protected])
687
+
688
+ ---
689
+
690
+ #### 🥇 Gold Sponsors - $5000/mo
691
+
692
+ ---
693
+
694
+ #### 🥈 Silver Sponsors - $1000/mo
695
+
696
+ ---
697
+
698
+ #### 🥉 Bronze Sponsors - $500/mo
699
+
700
+ - [JarvisLabs.ai](https://jarvislabs.ai)
701
+
702
+ ---
TODO.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # todo list
2
+
3
+ - [] Validation of parameters for combinations that won't work
4
+
5
+
6
+
7
+ ## things that are known not to work
8
+
9
+ - FSDP offload and gradient_checkpointing - https://github.com/pytorch/pytorch/issues/82203
10
+ - adamw_bnb_8bit doesn't play well with FSDP offload
_quarto.yml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ project:
2
+ type: website
3
+
4
+ website:
5
+ title: "Axolotl"
6
+ description: "Fine-tuning"
7
+ favicon: favicon.jpg
8
+ navbar:
9
+ title: Axolotl
10
+ background: dark
11
+ pinned: false
12
+ collapse: false
13
+ tools:
14
+ - icon: twitter
15
+ href: https://twitter.com/axolotl_ai
16
+ - icon: github
17
+ href: https://github.com/OpenAccess-AI-Collective/axolotl/
18
+ - icon: discord
19
+ href: https://discord.gg/7m9sfhzaf3
20
+
21
+ sidebar:
22
+ pinned: true
23
+ collapse-level: 2
24
+ style: docked
25
+ contents:
26
+ - text: Home
27
+ href: index.qmd
28
+ - section: "How-To Guides"
29
+ contents:
30
+ # TODO Edit folder structure after we have more docs.
31
+ - docs/debugging.qmd
32
+ - docs/multipack.qmd
33
+ - docs/fsdp_qlora.qmd
34
+ - docs/input_output.qmd
35
+ - docs/rlhf.qmd
36
+ - docs/nccl.qmd
37
+ - docs/mac.qmd
38
+ - docs/multi-node.qmd
39
+ - section: "Dataset Formats"
40
+ contents: docs/dataset-formats/*
41
+ - section: "Reference"
42
+ contents:
43
+ - docs/config.qmd
44
+ - docs/faq.qmd
45
+
46
+
47
+ format:
48
+ html:
49
+ theme: materia
50
+ css: styles.css
51
+ toc: true
cicd/Dockerfile.jinja ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM winglian/axolotl-base:{{ BASE_TAG }}
2
+
3
+ ENV TORCH_CUDA_ARCH_LIST="7.0 7.5 8.0 8.6+PTX"
4
+ ENV AXOLOTL_EXTRAS="{{ AXOLOTL_EXTRAS }}"
5
+ ENV AXOLOTL_ARGS="{{ AXOLOTL_ARGS }}"
6
+ ENV CUDA="{{ CUDA }}"
7
+ ENV BNB_CUDA_VERSION="{{ CUDA }}"
8
+ ENV PYTORCH_VERSION="{{ PYTORCH_VERSION }}"
9
+ ENV GITHUB_REF="{{ GITHUB_REF }}"
10
+ ENV GITHUB_SHA="{{ GITHUB_SHA }}"
11
+
12
+ RUN apt-get update && \
13
+ apt-get install -y --allow-change-held-packages vim curl nano libnccl2 libnccl-dev
14
+
15
+ WORKDIR /workspace
16
+
17
+ RUN git clone --depth=1 https://github.com/OpenAccess-AI-Collective/axolotl.git
18
+
19
+ WORKDIR /workspace/axolotl
20
+
21
+ RUN git fetch origin +$GITHUB_REF && \
22
+ git checkout FETCH_HEAD
23
+
24
+ # If AXOLOTL_EXTRAS is set, append it in brackets
25
+ RUN pip install causal_conv1d
26
+ RUN if [ "$AXOLOTL_EXTRAS" != "" ] ; then \
27
+ pip install -e .[deepspeed,flash-attn,mamba-ssm,galore,$AXOLOTL_EXTRAS] $AXOLOTL_ARGS; \
28
+ else \
29
+ pip install -e .[deepspeed,flash-attn,mamba-ssm,galore] $AXOLOTL_ARGS; \
30
+ fi
31
+
32
+ # So we can test the Docker image
33
+ RUN pip install pytest
34
+
35
+ # fix so that git fetch/pull from remote works
36
+ RUN git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*" && \
37
+ git config --get remote.origin.fetch
38
+
39
+ # helper for huggingface-login cli
40
+ RUN git config --global credential.helper store
cicd/cicd.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ pytest --ignore=tests/e2e/ /workspace/axolotl/tests/
4
+ pytest /workspace/axolotl/tests/e2e/patched/
5
+ pytest --ignore=tests/e2e/patched/ /workspace/axolotl/tests/e2e/
cicd/tests.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ modal application to run axolotl gpu tests in Modal
3
+ """
4
+ import os
5
+ import pathlib
6
+ import tempfile
7
+
8
+ import jinja2
9
+ import modal
10
+ from jinja2 import select_autoescape
11
+ from modal import Image, Stub
12
+
13
+ cicd_path = pathlib.Path(__file__).parent.resolve()
14
+
15
+ template_loader = jinja2.FileSystemLoader(searchpath=cicd_path)
16
+ template_env = jinja2.Environment(
17
+ loader=template_loader, autoescape=select_autoescape()
18
+ )
19
+ df_template = template_env.get_template("Dockerfile.jinja")
20
+
21
+ df_args = {
22
+ "AXOLOTL_EXTRAS": os.environ.get("AXOLOTL_EXTRAS", ""),
23
+ "AXOLOTL_ARGS": os.environ.get("AXOLOTL_ARGS", ""),
24
+ "PYTORCH_VERSION": os.environ.get("PYTORCH_VERSION", "2.0.1"),
25
+ "BASE_TAG": os.environ.get("BASE_TAG", "main-base-py3.10-cu118-2.0.1"),
26
+ "CUDA": os.environ.get("CUDA", "118"),
27
+ "GITHUB_REF": os.environ.get("GITHUB_REF", "refs/heads/main"),
28
+ "GITHUB_SHA": os.environ.get("GITHUB_SHA", ""),
29
+ }
30
+
31
+ dockerfile_contents = df_template.render(**df_args)
32
+
33
+ temp_dir = tempfile.mkdtemp()
34
+ with open(pathlib.Path(temp_dir) / "Dockerfile", "w", encoding="utf-8") as f:
35
+ f.write(dockerfile_contents)
36
+
37
+ cicd_image = (
38
+ Image.from_dockerfile(
39
+ pathlib.Path(temp_dir) / "Dockerfile",
40
+ force_build=True,
41
+ gpu="A10G",
42
+ )
43
+ .env(df_args)
44
+ .pip_install("fastapi==0.110.0", "pydantic==2.6.3")
45
+ )
46
+
47
+ stub = Stub("Axolotl CI/CD", secrets=[])
48
+
49
+
50
+ N_GPUS = int(os.environ.get("N_GPUS", 1))
51
+ GPU_CONFIG = modal.gpu.A10G(count=N_GPUS)
52
+
53
+
54
+ def run_cmd(cmd: str, run_folder: str):
55
+ import subprocess # nosec
56
+
57
+ # Propagate errors from subprocess.
58
+ if exit_code := subprocess.call(cmd.split(), cwd=run_folder): # nosec
59
+ exit(exit_code) # pylint: disable=consider-using-sys-exit
60
+
61
+
62
+ @stub.function(
63
+ image=cicd_image,
64
+ gpu=GPU_CONFIG,
65
+ timeout=45 * 60,
66
+ cpu=8.0,
67
+ memory=131072,
68
+ )
69
+ def cicd_pytest():
70
+ run_cmd("./cicd/cicd.sh", "/workspace/axolotl")
71
+
72
+
73
+ @stub.local_entrypoint()
74
+ def main():
75
+ cicd_pytest.remote()
config.yml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ base_model: PygmalionAI/pyggel-ckpt-2947
2
+ load_in_8bit: false
3
+ load_in_4bit: false
4
+ strict: false
5
+
6
+ datasets:
7
+ - path: PygmalionAI/unified-rp-dataset
8
+ type: sharegpt
9
+
10
+ chat_template: llama3
11
+ dataset_prepared_path: ./datasetstuff3
12
+ hub_model_id: Alignment-Lab-AI/pygmalion-3-1m-2.4
13
+ wandb_project: pyg-1-m-2.3
14
+ hf_use_auth_token: true
15
+ output_dir: ./pyg1m2.3
16
+
17
+ wandb_watch: all
18
+ hub_private_repo: true
19
+ hub_strategy: all_checkpoints
20
+ push_to_hub: true
21
+ hf_use_auth_token: true
22
+ output_dir: ./pyggel
23
+ max_grad_norm: 0.6
24
+ sequence_len: 8192
25
+ sample_packing: true
26
+ pad_to_sequence_len: true
27
+ micro_batch_size: 1
28
+ gradient_accumulation_steps: 1
29
+ num_epochs: 3
30
+ learning_rate: 0.0001
31
+ optimizer: adamw_bnb_8bit
32
+ optim_args:
33
+ amsgrad: true
34
+ lr_scheduler: cosine
35
+ train_on_inputs: true
36
+ group_by_length: false
37
+ bfloat16: false
38
+ fp16:
39
+ tf32: false
40
+ neftune_noise_alpha: 15
41
+ gradient_checkpointing: unsloth
42
+ gradient_checkpointing_kwargs:
43
+ use_reentrant: true
44
+ logging_steps: 1
45
+ xformers_attention:
46
+ flash_attention: true
47
+ unsloth_cross_entropy_loss: true
48
+ #unsloth_lora_mlp: true
49
+ #unsloth_lora_qkv: true
50
+ #unsloth_lora_o: true
51
+ flash_attn_cross_entropy: false
52
+ flash_attn_rms_norm: true
53
+ flash_attn_fuse_qkv: false
54
+ flash_attn_fuse_mlp: true
55
+ warmup_ratio: 0.5
56
+ evals_per_step: 0.025
57
+ eval_table_size:
58
+ saves_per_epoch: 15
59
+ debug:
60
+ torch_compile: true
61
+ rank:
62
+ deepspeed: deepspeed_configs/zero1.json
63
+ weight_decay: 0.01
64
+ special_tokens:
65
+ eos_token: "<|eot_id|>"
66
+ pad_token: "<|end_of_text|>"
deepspeed_configs/zero1.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "zero_optimization": {
3
+ "stage": 1,
4
+ "overlap_comm": true
5
+ },
6
+ "bf16": {
7
+ "enabled": "auto"
8
+ },
9
+ "fp16": {
10
+ "enabled": "auto",
11
+ "auto_cast": false,
12
+ "loss_scale": 0,
13
+ "initial_scale_power": 32,
14
+ "loss_scale_window": 1000,
15
+ "hysteresis": 2,
16
+ "min_loss_scale": 1
17
+ },
18
+ "gradient_accumulation_steps": "auto",
19
+ "gradient_clipping": "auto",
20
+ "train_batch_size": "auto",
21
+ "train_micro_batch_size_per_gpu": "auto",
22
+ "wall_clock_breakdown": false
23
+ }
deepspeed_configs/zero2.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "zero_optimization": {
3
+ "stage": 2,
4
+ "offload_optimizer": {
5
+ "device": "cpu"
6
+ },
7
+ "contiguous_gradients": true,
8
+ "overlap_comm": true
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "fp16": {
14
+ "enabled": "auto",
15
+ "auto_cast": false,
16
+ "loss_scale": 0,
17
+ "initial_scale_power": 32,
18
+ "loss_scale_window": 1000,
19
+ "hysteresis": 2,
20
+ "min_loss_scale": 1
21
+ },
22
+ "gradient_accumulation_steps": "auto",
23
+ "gradient_clipping": "auto",
24
+ "train_batch_size": "auto",
25
+ "train_micro_batch_size_per_gpu": "auto",
26
+ "wall_clock_breakdown": false
27
+ }
deepspeed_configs/zero3.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "zero_optimization": {
3
+ "stage": 3,
4
+ "overlap_comm": true,
5
+ "contiguous_gradients": true,
6
+ "sub_group_size": 0,
7
+ "reduce_bucket_size": "auto",
8
+ "stage3_prefetch_bucket_size": "auto",
9
+ "stage3_param_persistence_threshold": "auto",
10
+ "stage3_max_live_parameters": 0,
11
+ "stage3_max_reuse_distance": 0,
12
+ "stage3_gather_16bit_weights_on_model_save": true
13
+ },
14
+ "bf16": {
15
+ "enabled": "auto"
16
+ },
17
+ "fp16": {
18
+ "enabled": "auto",
19
+ "auto_cast": false,
20
+ "loss_scale": 0,
21
+ "initial_scale_power": 32,
22
+ "loss_scale_window": 1000,
23
+ "hysteresis": 2,
24
+ "min_loss_scale": 1
25
+ },
26
+ "gradient_accumulation_steps": "auto",
27
+ "gradient_clipping": "auto",
28
+ "train_batch_size": "auto",
29
+ "train_micro_batch_size_per_gpu": "auto",
30
+ "wall_clock_breakdown": false
31
+ }
deepspeed_configs/zero3_bf16.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "zero_optimization": {
3
+ "stage": 3,
4
+ "overlap_comm": true,
5
+ "contiguous_gradients": true,
6
+ "sub_group_size": 0,
7
+ "reduce_bucket_size": "auto",
8
+ "stage3_prefetch_bucket_size": "auto",
9
+ "stage3_param_persistence_threshold": "auto",
10
+ "stage3_max_live_parameters": 0,
11
+ "stage3_max_reuse_distance": 0,
12
+ "stage3_gather_16bit_weights_on_model_save": true
13
+ },
14
+ "bf16": {
15
+ "enabled": true
16
+ },
17
+ "fp16": {
18
+ "enabled": "auto",
19
+ "auto_cast": false,
20
+ "loss_scale": 0,
21
+ "initial_scale_power": 32,
22
+ "loss_scale_window": 1000,
23
+ "hysteresis": 2,
24
+ "min_loss_scale": 1
25
+ },
26
+ "gradient_accumulation_steps": "auto",
27
+ "gradient_clipping": "auto",
28
+ "train_batch_size": "auto",
29
+ "train_micro_batch_size_per_gpu": "auto",
30
+ "wall_clock_breakdown": false
31
+ }
deepspeed_configs/zero3_bf16_cpuoffload_all.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "zero_force_ds_cpu_optimizer": false,
3
+ "zero_allow_untested_optimizer": true,
4
+ "zero_optimization": {
5
+ "stage": 3,
6
+ "offload_optimizer": {
7
+ "device": "cpu",
8
+ "pin_memory": true
9
+ },
10
+ "offload_param": {
11
+ "device": "cpu",
12
+ "pin_memory": true
13
+ },
14
+ "overlap_comm": true,
15
+ "contiguous_gradients": true,
16
+ "sub_group_size": 0,
17
+ "reduce_bucket_size": "auto",
18
+ "stage3_prefetch_bucket_size": "auto",
19
+ "stage3_param_persistence_threshold": "auto",
20
+ "stage3_max_live_parameters": 0,
21
+ "stage3_max_reuse_distance": 0,
22
+ "stage3_gather_16bit_weights_on_model_save": true
23
+ },
24
+ "bf16": {
25
+ "enabled": true
26
+ },
27
+ "fp16": {
28
+ "enabled": "auto",
29
+ "auto_cast": false,
30
+ "loss_scale": 0,
31
+ "initial_scale_power": 32,
32
+ "loss_scale_window": 1000,
33
+ "hysteresis": 2,
34
+ "min_loss_scale": 1
35
+ },
36
+ "gradient_accumulation_steps": "auto",
37
+ "gradient_clipping": "auto",
38
+ "train_batch_size": "auto",
39
+ "train_micro_batch_size_per_gpu": "auto",
40
+ "wall_clock_breakdown": false
41
+ }
deepspeed_configs/zero3_bf16_cpuoffload_params.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "zero_force_ds_cpu_optimizer": false,
3
+ "zero_allow_untested_optimizer": true,
4
+ "zero_optimization": {
5
+ "stage": 3,
6
+ "offload_param": {
7
+ "device": "cpu",
8
+ "pin_memory": true
9
+ },
10
+ "overlap_comm": true,
11
+ "contiguous_gradients": true,
12
+ "sub_group_size": 0,
13
+ "reduce_bucket_size": "auto",
14
+ "stage3_prefetch_bucket_size": "auto",
15
+ "stage3_param_persistence_threshold": "auto",
16
+ "stage3_max_live_parameters": 0,
17
+ "stage3_max_reuse_distance": 0,
18
+ "stage3_gather_16bit_weights_on_model_save": true
19
+ },
20
+ "bf16": {
21
+ "enabled": true
22
+ },
23
+ "fp16": {
24
+ "enabled": "auto",
25
+ "auto_cast": false,
26
+ "loss_scale": 0,
27
+ "initial_scale_power": 32,
28
+ "loss_scale_window": 1000,
29
+ "hysteresis": 2,
30
+ "min_loss_scale": 1
31
+ },
32
+ "gradient_accumulation_steps": "auto",
33
+ "gradient_clipping": "auto",
34
+ "train_batch_size": "auto",
35
+ "train_micro_batch_size_per_gpu": "auto",
36
+ "wall_clock_breakdown": false
37
+ }
devtools/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ This directory contains example config files that might be useful for debugging. Please see [docs/debugging.qmd](../docs/debugging.qmd) for more information.
devtools/dev_sharegpt.yml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Example config for debugging the sharegpt prompt format
2
+ base_model: TinyLlama/TinyLlama-1.1B-Chat-v1.0
3
+ model_type: LlamaForCausalLM
4
+ tokenizer_type: LlamaTokenizer
5
+
6
+ load_in_8bit: true
7
+ load_in_4bit: false
8
+
9
+ datasets:
10
+ - path: philschmid/guanaco-sharegpt-style
11
+ type: sharegpt
12
+ shards: 10
13
+ val_set_size: 0
14
+ output_dir: temp_debug/axolotl_outputs/model
15
+ dataset_prepared_path: temp_debug/axolotl_outputs/data
16
+ dataset_processes: 1
17
+
18
+ sequence_len: 4096
19
+ sample_packing: false
20
+ pad_to_sequence_len: true
21
+
22
+ adapter: lora
23
+ lora_model_dir:
24
+ lora_r: 32
25
+ lora_alpha: 16
26
+ lora_dropout: 0.05
27
+ lora_target_linear: true
28
+ lora_fan_in_fan_out:
29
+
30
+ micro_batch_size: 1
31
+ num_epochs: 1
32
+ max_steps: 10
33
+ optimizer: adamw_bnb_8bit
34
+ lr_scheduler: cosine
35
+ learning_rate: 0.0002
36
+
37
+ train_on_inputs: false
38
+ group_by_length: false
39
+ bf16: false
40
+ fp16: true
41
+ tf32: false
42
+
43
+ gradient_checkpointing: true
44
+ logging_steps: 1
45
+ flash_attention: true
46
+
47
+ warmup_steps: 10
48
+ weight_decay: 0.0
docker-compose.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # version: '3.8'
2
+ services:
3
+ axolotl:
4
+ build:
5
+ context: .
6
+ dockerfile: ./docker/Dockerfile
7
+ volumes:
8
+ - .:/workspace/axolotl
9
+ - ~/.cache/huggingface/:/root/.cache/huggingface/
10
+ # set environment variables
11
+ environment:
12
+ # Set environment variables
13
+ - GIT_AUTHOR_NAME=${GIT_AUTHOR_NAME}
14
+ - GIT_AUTHOR_EMAIL=${GIT_AUTHOR_EMAIL}
15
+ - GIT_COMMITTER_NAME=${GIT_COMMITTER_NAME}
16
+ - GIT_COMMITTER_EMAIL=${GIT_COMMITTER_EMAIL}
17
+ - WANDB_API_KEY=${WANDB_API_KEY}
18
+ deploy:
19
+ resources:
20
+ reservations:
21
+ devices:
22
+ - driver: nvidia
23
+ # count: 1
24
+ capabilities: [gpu]
25
+ command: tail -f /dev/null
docker/Dockerfile ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG BASE_TAG=main-base
2
+ FROM winglian/axolotl-base:$BASE_TAG
3
+
4
+ ARG TORCH_CUDA_ARCH_LIST="7.0 7.5 8.0 8.6+PTX"
5
+ ARG AXOLOTL_EXTRAS=""
6
+ ARG AXOLOTL_ARGS=""
7
+ ARG CUDA="118"
8
+ ENV BNB_CUDA_VERSION=$CUDA
9
+ ARG PYTORCH_VERSION="2.1.2"
10
+
11
+ ENV PYTORCH_VERSION=$PYTORCH_VERSION
12
+
13
+ RUN apt-get update && \
14
+ apt-get install -y --allow-change-held-packages vim curl nano libnccl2 libnccl-dev rsync s3fs
15
+
16
+ WORKDIR /workspace
17
+
18
+ RUN git clone --depth=1 https://github.com/OpenAccess-AI-Collective/axolotl.git
19
+
20
+ WORKDIR /workspace/axolotl
21
+
22
+ # If AXOLOTL_EXTRAS is set, append it in brackets
23
+ RUN pip install causal_conv1d
24
+ RUN if [ "$AXOLOTL_EXTRAS" != "" ] ; then \
25
+ pip install -e .[deepspeed,flash-attn,mamba-ssm,galore,$AXOLOTL_EXTRAS] $AXOLOTL_ARGS; \
26
+ else \
27
+ pip install -e .[deepspeed,flash-attn,mamba-ssm,galore] $AXOLOTL_ARGS; \
28
+ fi
29
+
30
+ # So we can test the Docker image
31
+ RUN pip install pytest
32
+
33
+ # fix so that git fetch/pull from remote works
34
+ RUN git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*" && \
35
+ git config --get remote.origin.fetch
36
+
37
+ # helper for huggingface-login cli
38
+ RUN git config --global credential.helper store
docker/Dockerfile-base ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG CUDA_VERSION="11.8.0"
2
+ ARG CUDNN_VERSION="8"
3
+ ARG UBUNTU_VERSION="22.04"
4
+ ARG MAX_JOBS=4
5
+
6
+ FROM nvidia/cuda:$CUDA_VERSION-cudnn$CUDNN_VERSION-devel-ubuntu$UBUNTU_VERSION as base-builder
7
+
8
+ ENV PATH="/root/miniconda3/bin:${PATH}"
9
+
10
+ ARG PYTHON_VERSION="3.10"
11
+ ARG PYTORCH_VERSION="2.1.2"
12
+ ARG CUDA="118"
13
+ ARG TORCH_CUDA_ARCH_LIST="7.0 7.5 8.0 8.6 9.0+PTX"
14
+
15
+ ENV PYTHON_VERSION=$PYTHON_VERSION
16
+ ENV TORCH_CUDA_ARCH_LIST=$TORCH_CUDA_ARCH_LIST
17
+
18
+ RUN apt-get update \
19
+ && apt-get install -y wget git build-essential ninja-build git-lfs libaio-dev && rm -rf /var/lib/apt/lists/* \
20
+ && wget \
21
+ https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh \
22
+ && mkdir /root/.conda \
23
+ && bash Miniconda3-latest-Linux-x86_64.sh -b \
24
+ && rm -f Miniconda3-latest-Linux-x86_64.sh \
25
+ && conda create -n "py${PYTHON_VERSION}" python="${PYTHON_VERSION}"
26
+
27
+ ENV PATH="/root/miniconda3/envs/py${PYTHON_VERSION}/bin:${PATH}"
28
+
29
+ WORKDIR /workspace
30
+
31
+ RUN python3 -m pip install --upgrade pip && pip3 install packaging && \
32
+ python3 -m pip install --no-cache-dir -U torch==${PYTORCH_VERSION}+cu${CUDA} --extra-index-url https://download.pytorch.org/whl/cu$CUDA
33
+
34
+ RUN git lfs install --skip-repo && \
35
+ pip3 install awscli && \
36
+ # The base image ships with `pydantic==1.8.2` which is not working
37
+ pip3 install -U --no-cache-dir pydantic==1.10.10
docker/Dockerfile-cloud ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG BASE_TAG=main
2
+ FROM winglian/axolotl:$BASE_TAG
3
+
4
+ ENV HF_DATASETS_CACHE="/workspace/data/huggingface-cache/datasets"
5
+ ENV HUGGINGFACE_HUB_CACHE="/workspace/data/huggingface-cache/hub"
6
+ ENV TRANSFORMERS_CACHE="/workspace/data/huggingface-cache/hub"
7
+ ENV HF_HOME="/workspace/data/huggingface-cache/hub"
8
+ ENV HF_HUB_ENABLE_HF_TRANSFER="1"
9
+
10
+ EXPOSE 8888
11
+ EXPOSE 22
12
+
13
+ COPY scripts/cloud-entrypoint.sh /root/cloud-entrypoint.sh
14
+ COPY scripts/motd /etc/motd
15
+
16
+ RUN pip install jupyterlab notebook ipywidgets && \
17
+ jupyter lab clean
18
+ RUN apt install --yes --no-install-recommends openssh-server tmux && \
19
+ mkdir -p ~/.ssh && \
20
+ chmod 700 ~/.ssh && \
21
+ printf "\n[[ -z \"\$TMUX\" ]] && { tmux attach-session -t ssh_tmux || tmux new-session -s ssh_tmux; exit; }\n" >> ~/.bashrc && \
22
+ printf "[ ! -z \"\$TERM\" -a -r /etc/motd ] && cat /etc/motd\n" >> ~/.bashrc && \
23
+ chmod +x /workspace/axolotl/scripts/cloud-entrypoint.sh && \
24
+ chmod +x /root/cloud-entrypoint.sh
25
+
26
+ ENTRYPOINT ["/root/cloud-entrypoint.sh"]
27
+ CMD ["sleep", "infinity"]
docker/Dockerfile-cloud-no-tmux ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG BASE_TAG=main
2
+ FROM winglian/axolotl:$BASE_TAG
3
+
4
+ ENV HF_DATASETS_CACHE="/workspace/data/huggingface-cache/datasets"
5
+ ENV HUGGINGFACE_HUB_CACHE="/workspace/data/huggingface-cache/hub"
6
+ ENV TRANSFORMERS_CACHE="/workspace/data/huggingface-cache/hub"
7
+ ENV HF_HOME="/workspace/data/huggingface-cache/hub"
8
+ ENV HF_HUB_ENABLE_HF_TRANSFER="1"
9
+
10
+ EXPOSE 8888
11
+ EXPOSE 22
12
+
13
+ COPY scripts/cloud-entrypoint.sh /root/cloud-entrypoint.sh
14
+ COPY scripts/motd /etc/motd
15
+
16
+ RUN pip install jupyterlab notebook ipywidgets && \
17
+ jupyter lab clean
18
+ RUN apt install --yes --no-install-recommends openssh-server tmux && \
19
+ mkdir -p ~/.ssh && \
20
+ chmod 700 ~/.ssh && \
21
+ printf "[ ! -z \"\$TERM\" -a -r /etc/motd ] && cat /etc/motd\n" >> ~/.bashrc && \
22
+ chmod +x /workspace/axolotl/scripts/cloud-entrypoint.sh && \
23
+ chmod +x /root/cloud-entrypoint.sh
24
+
25
+ ENTRYPOINT ["/root/cloud-entrypoint.sh"]
26
+ CMD ["sleep", "infinity"]
docker/Dockerfile-tests ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG BASE_TAG=main-base
2
+ FROM winglian/axolotl-base:$BASE_TAG
3
+
4
+ ARG TORCH_CUDA_ARCH_LIST="7.0 7.5 8.0 8.6+PTX"
5
+ ARG AXOLOTL_EXTRAS=""
6
+ ARG AXOLOTL_ARGS=""
7
+ ARG CUDA="118"
8
+ ENV BNB_CUDA_VERSION=$CUDA
9
+ ARG PYTORCH_VERSION="2.1.2"
10
+ ARG GITHUB_REF="main"
11
+
12
+ ENV PYTORCH_VERSION=$PYTORCH_VERSION
13
+
14
+ RUN apt-get update && \
15
+ apt-get install -y --allow-change-held-packages vim curl nano libnccl2 libnccl-dev
16
+
17
+ WORKDIR /workspace
18
+
19
+ RUN git clone --depth=1 https://github.com/OpenAccess-AI-Collective/axolotl.git
20
+
21
+ WORKDIR /workspace/axolotl
22
+
23
+ RUN git fetch origin +$GITHUB_REF && \
24
+ git checkout FETCH_HEAD
25
+
26
+ # If AXOLOTL_EXTRAS is set, append it in brackets
27
+ RUN if [ "$AXOLOTL_EXTRAS" != "" ] ; then \
28
+ pip install -e .[deepspeed,flash-attn,mamba-ssm,$AXOLOTL_EXTRAS] $AXOLOTL_ARGS; \
29
+ else \
30
+ pip install -e .[deepspeed,flash-attn,mamba-ssm] $AXOLOTL_ARGS; \
31
+ fi
32
+
33
+ # So we can test the Docker image
34
+ RUN pip install pytest
35
+
36
+ # fix so that git fetch/pull from remote works
37
+ RUN git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*" && \
38
+ git config --get remote.origin.fetch
39
+
40
+ # helper for huggingface-login cli
41
+ RUN git config --global credential.helper store
docs/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ /.quarto/
2
+ _site/
docs/batch_vs_grad.qmd ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Batch size vs Gradient accumulation
3
+ description: Understanding of batch size and gradient accumulation steps
4
+ ---
5
+
6
+ Gradient accumulation means accumulating gradients over several mini-batches and updating the model weights afterward. When the samples in each batch are diverse, this technique doesn't significantly impact learning.
7
+
8
+ This method allows for effective training with larger effective batch sizes without needing proportionally larger memory. Here's why:
9
+
10
+ 1. **Memory Consumption with Batch Size**: The primary reason increasing the batch size impacts memory is due to the storage requirements for intermediate activations. When you forward propagate a batch through a network, you have to store the activations at each layer for each sample in the batch, because these activations are used during backpropagation to compute gradients. Therefore, larger batches mean more activations, leading to greater GPU memory consumption.
11
+
12
+ 2. **Gradient Accumulation**: With gradient accumulation, you're effectively simulating a larger batch size by accumulating gradients over several smaller batches (or micro-batches). However, at any given time, you're only forward and backward propagating a micro-batch. This means you only store activations for the micro-batch, not the full accumulated batch. As a result, you can simulate the effect of a larger batch size without the memory cost of storing activations for a large batch.
13
+
14
+ **Example 1:**
15
+ Micro batch size: 3
16
+ Gradient accumulation steps: 2
17
+ Number of GPUs: 3
18
+ Total batch size = 3 * 2 * 3 = 18
19
+
20
+ ```
21
+ | GPU 1 | GPU 2 | GPU 3 |
22
+ |----------------|----------------|----------------|
23
+ | S1, S2, S3 | S4, S5, S6 | S7, S8, S9 |
24
+ | e1, e2, e3 | e4, e5, e6 | e7, e8, e9 |
25
+ |----------------|----------------|----------------|
26
+ | → (accumulate) | → (accumulate) | → (accumulate) |
27
+ |----------------|----------------|----------------|
28
+ | S10, S11, S12 | S13, S14, S15 | S16, S17, S18 |
29
+ | e10, e11, e12 | e13, e14, e15 | e16, e17, e18 |
30
+ |----------------|----------------|----------------|
31
+ | → (apply) | → (apply) | → (apply) |
32
+
33
+ Accumulated gradient for the weight w1 after the second iteration (considering all GPUs):
34
+ Total gradient for w1 = e1 + e2 + e3 + e4 + e5 + e6 + e7 + e8 + e9 + e10 + e11 + e12 + e13 + e14 + e15 + e16 + e17 + e18
35
+
36
+ Weight update for w1:
37
+ w1_new = w1_old - learning rate x (Total gradient for w1 / 18)
38
+ ```
39
+
40
+ **Example 2:**
41
+ Micro batch size: 2
42
+ Gradient accumulation steps: 1
43
+ Number of GPUs: 3
44
+ Total batch size = 2 * 1 * 3 = 6
45
+
46
+ ```
47
+ | GPU 1 | GPU 2 | GPU 3 |
48
+ |-----------|-----------|-----------|
49
+ | S1, S2 | S3, S4 | S5, S6 |
50
+ | e1, e2 | e3, e4 | e5, e6 |
51
+ |-----------|-----------|-----------|
52
+ | → (apply) | → (apply) | → (apply) |
53
+
54
+ Accumulated gradient for the weight w1 (considering all GPUs):
55
+ Total gradient for w1 = e1 + e2 + e3 + e4 + e5 + e6
56
+
57
+ Weight update for w1:
58
+ w1_new = w1_old - learning rate × (Total gradient for w1 / 6)
59
+ ```
docs/config.qmd ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Config options
3
+ description: A complete list of all configuration options.
4
+ ---
5
+
6
+ ```yaml
7
+ # This is the huggingface model that contains *.pt, *.safetensors, or *.bin files
8
+ # This can also be a relative path to a model on disk
9
+ base_model: ./llama-7b-hf
10
+ # You can specify an ignore pattern if the model repo contains more than 1 model type (*.pt, etc)
11
+ base_model_ignore_patterns:
12
+ # If the base_model repo on hf hub doesn't include configuration .json files,
13
+ # You can set that here, or leave this empty to default to base_model
14
+ base_model_config: ./llama-7b-hf
15
+ # You can specify to choose a specific model revision from huggingface hub
16
+ revision_of_model:
17
+ # Optional tokenizer configuration path in case you want to use a different tokenizer
18
+ # than the one defined in the base model
19
+ tokenizer_config:
20
+ # If you want to specify the type of model to load, AutoModelForCausalLM is a good choice too
21
+ model_type: AutoModelForCausalLM
22
+ # Corresponding tokenizer for the model AutoTokenizer is a good choice
23
+ tokenizer_type: AutoTokenizer
24
+ # Trust remote code for untrusted source
25
+ trust_remote_code:
26
+ # use_fast option for tokenizer loading from_pretrained, default to True
27
+ tokenizer_use_fast:
28
+ # Whether to use the legacy tokenizer setting, defaults to True
29
+ tokenizer_legacy:
30
+ # Resize the model embeddings when new tokens are added to multiples of 32
31
+ # This is reported to improve training speed on some models
32
+ resize_token_embeddings_to_32x:
33
+
34
+ # (Internal use only)
35
+ # Used to identify which the model is based on
36
+ is_falcon_derived_model:
37
+ is_llama_derived_model:
38
+ is_qwen_derived_model:
39
+ # Please note that if you set this to true, `padding_side` will be set to "left" by default
40
+ is_mistral_derived_model:
41
+
42
+ # optional overrides to the base model configuration
43
+ overrides_of_model_config:
44
+ # RoPE Scaling https://github.com/huggingface/transformers/pull/24653
45
+ rope_scaling:
46
+ type: # linear | dynamic
47
+ factor: # float
48
+
49
+ # optional overrides to the bnb 4bit quantization configuration
50
+ # https://huggingface.co/docs/transformers/main/main_classes/quantization#transformers.BitsAndBytesConfig
51
+ bnb_config_kwargs:
52
+ # These are default values
53
+ llm_int8_has_fp16_weight: false
54
+ bnb_4bit_quant_type: nf4
55
+ bnb_4bit_use_double_quant: true
56
+
57
+
58
+ # Whether you are training a 4-bit GPTQ quantized model
59
+ gptq: true
60
+
61
+ # This will attempt to quantize the model down to 8 bits and use adam 8 bit optimizer
62
+ load_in_8bit: true
63
+ # Use bitsandbytes 4 bit
64
+ load_in_4bit:
65
+
66
+ # Use CUDA bf16
67
+ bf16: true # bool or 'full' for `bf16_full_eval`. require >=ampere
68
+ # Use CUDA fp16
69
+ fp16: true
70
+ # Use CUDA tf32
71
+ tf32: true # require >=ampere
72
+
73
+ # No AMP (automatic mixed precision)
74
+ bfloat16: true # require >=ampere
75
+ float16: true
76
+
77
+ # Limit the memory for all available GPUs to this amount (if an integer, expressed in gigabytes); default: unset
78
+ gpu_memory_limit: 20GiB
79
+ # Do the LoRA/PEFT loading on CPU -- this is required if the base model is so large it takes up most or all of the available GPU VRAM, e.g. during a model and LoRA merge
80
+ lora_on_cpu: true
81
+
82
+ # A list of one or more datasets to finetune the model with
83
+ datasets:
84
+ # HuggingFace dataset repo | s3://,gs:// path | "json" for local dataset, make sure to fill data_files
85
+ - path: vicgalle/alpaca-gpt4
86
+ # The type of prompt to use for training. [alpaca, sharegpt, gpteacher, oasst, reflection]
87
+ type: alpaca # format | format:<prompt_style> (chat/instruct) | <prompt_strategies>.load_<load_fn>
88
+ ds_type: # Optional[str] (json|arrow|parquet|text|csv) defines the datatype when path is a file
89
+ data_files: # Optional[str] path to source data files
90
+ shards: # Optional[int] number of shards to split data into
91
+ name: # Optional[str] name of dataset configuration to load
92
+ train_on_split: train # Optional[str] name of dataset split to load from
93
+
94
+ # Optional[str] fastchat conversation type, only used with type: sharegpt
95
+ conversation: # Options (see Conversation 'name'): https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
96
+ field_human: # Optional[str]. Human key to use for conversation.
97
+ field_model: # Optional[str]. Assistant key to use for conversation.
98
+ # Add additional keys from your dataset as input or output roles
99
+ roles:
100
+ input: # Optional[List[str]]. These will be masked based on train_on_input
101
+ output: # Optional[List[str]].
102
+
103
+ # Custom user instruction prompt
104
+ - path: repo
105
+ type:
106
+ # The below are defaults. only set what's needed if you use a different column name.
107
+ system_prompt: ""
108
+ system_format: "{system}"
109
+ field_system: system
110
+ field_instruction: instruction
111
+ field_input: input
112
+ field_output: output
113
+
114
+ # Customizable to be single line or multi-line
115
+ # Use {instruction}/{input} as key to be replaced
116
+ # 'format' can include {input}
117
+ format: |-
118
+ User: {instruction} {input}
119
+ Assistant:
120
+ # 'no_input_format' cannot include {input}
121
+ no_input_format: "{instruction} "
122
+
123
+ # For `completion` datsets only, uses the provided field instead of `text` column
124
+ field:
125
+
126
+ # If false, the datasets will not be shuffled and will keep their original order in `datasets`.
127
+ # The same applies to the `test_datasets` option and the `pretraining_dataset` option. Default is true.
128
+ shuffle_merged_datasets: true
129
+
130
+ # A list of one or more datasets to eval the model with.
131
+ # You can use either test_datasets, or val_set_size, but not both.
132
+ test_datasets:
133
+ - path: /workspace/data/eval.jsonl
134
+ ds_type: json
135
+ # You need to specify a split. For "json" datasets the default split is called "train".
136
+ split: train
137
+ type: completion
138
+ data_files:
139
+ - /workspace/data/eval.jsonl
140
+
141
+ # use RL training: 'dpo', 'ipo', 'kto_pair'
142
+ rl:
143
+
144
+ # Saves the desired chat template to the tokenizer_config.json for easier inferencing
145
+ # Currently supports chatml and inst (mistral/mixtral)
146
+ chat_template: chatml
147
+ # Changes the default system message
148
+ default_system_message: You are a helpful assistant. Please give a long and detailed answer. # Currently only supports chatml.
149
+ # Axolotl attempts to save the dataset as an arrow after packing the data together so
150
+ # subsequent training attempts load faster, relative path
151
+ dataset_prepared_path: data/last_run_prepared
152
+ # Push prepared dataset to hub
153
+ push_dataset_to_hub: # repo path
154
+ # The maximum number of processes to use while preprocessing your input dataset. This defaults to `os.cpu_count()`
155
+ # if not set.
156
+ dataset_processes: # defaults to os.cpu_count() if not set
157
+ # Keep dataset in memory while preprocessing
158
+ # Only needed if cached dataset is taking too much storage
159
+ dataset_keep_in_memory:
160
+ # push checkpoints to hub
161
+ hub_model_id: # private repo path to push finetuned model
162
+ # how to push checkpoints to hub
163
+ # https://huggingface.co/docs/transformers/v4.31.0/en/main_classes/trainer#transformers.TrainingArguments.hub_strategy
164
+ hub_strategy:
165
+ # Whether to use hf `use_auth_token` for loading datasets. Useful for fetching private datasets
166
+ # Required to be true when used in combination with `push_dataset_to_hub`
167
+ hf_use_auth_token: # boolean
168
+ # How much of the dataset to set aside as evaluation. 1 = 100%, 0.50 = 50%, etc. 0 for no eval.
169
+ val_set_size: 0.04
170
+ # Num shards for whole dataset
171
+ dataset_shard_num:
172
+ # Index of shard to use for whole dataset
173
+ dataset_shard_idx:
174
+
175
+ # The maximum length of an input to train with, this should typically be less than 2048
176
+ # as most models have a token/context limit of 2048
177
+ sequence_len: 2048
178
+ # Pad inputs so each step uses constant sized buffers
179
+ # This will reduce memory fragmentation and may prevent OOMs, by re-using memory more efficiently
180
+ pad_to_sequence_len:
181
+ # Use efficient multi-packing with block diagonal attention and per sequence position_ids. Recommend set to 'true'
182
+ sample_packing:
183
+ # Set to 'false' if getting errors during eval with sample_packing on.
184
+ eval_sample_packing:
185
+ # You can set these packing optimizations AFTER starting a training at least once.
186
+ # The trainer will provide recommended values for these values.
187
+ sample_packing_eff_est:
188
+ total_num_tokens:
189
+
190
+ # Passed through to transformers when loading the model when launched without accelerate
191
+ # Use `sequential` when training w/ model parallelism to limit memory
192
+ device_map:
193
+ # Defines the max memory usage per gpu on the system. Passed through to transformers when loading the model.
194
+ max_memory:
195
+
196
+ # If you want to use 'lora' or 'qlora' or leave blank to train all parameters in original model
197
+ adapter: lora
198
+ # If you already have a lora model trained that you want to load, put that here.
199
+ # This means after training, if you want to test the model, you should set this to the value of `output_dir`.
200
+ # Note that if you merge an adapter to the base model, a new subdirectory `merged` will be created under the `output_dir`.
201
+ lora_model_dir:
202
+
203
+ # LoRA hyperparameters
204
+ # For more details about the following options, see:
205
+ # https://www.anyscale.com/blog/fine-tuning-llms-lora-or-full-parameter-an-in-depth-analysis-with-llama-2
206
+ lora_r: 8
207
+ lora_alpha: 16
208
+ lora_dropout: 0.05
209
+ lora_target_modules:
210
+ - q_proj
211
+ - v_proj
212
+ # - k_proj
213
+ # - o_proj
214
+ # - gate_proj
215
+ # - down_proj
216
+ # - up_proj
217
+ lora_target_linear: # If true, will target all linear modules
218
+ peft_layers_to_transform: # The layer indices to transform, otherwise, apply to all layers
219
+
220
+ # If you added new tokens to the tokenizer, you may need to save some LoRA modules because they need to know the new tokens.
221
+ # For LLaMA and Mistral, you need to save `embed_tokens` and `lm_head`. It may vary for other models.
222
+ # `embed_tokens` converts tokens to embeddings, and `lm_head` converts embeddings to token probabilities.
223
+ # https://github.com/huggingface/peft/issues/334#issuecomment-1561727994
224
+ lora_modules_to_save:
225
+ # - embed_tokens
226
+ # - lm_head
227
+
228
+ lora_fan_in_fan_out: false
229
+
230
+ # LoRA+ hyperparameters
231
+ # For more details about the following options, see:
232
+ # https://arxiv.org/abs/2402.12354 and `src/axolotl/core/train_builder.py`
233
+ loraplus_lr_ratio: # loraplus learning rate ratio lr_B / lr_A. Recommended value is 2^4.
234
+ loraplus_lr_embedding: # loraplus learning rate for lora embedding layers. Default value is 1e-6.
235
+
236
+ peft:
237
+ # Configuration options for loftq initialization for LoRA
238
+ # https://huggingface.co/docs/peft/developer_guides/quantization#loftq-initialization
239
+ loftq_config:
240
+ loftq_bits: # typically 4 bits
241
+
242
+ # ReLoRA configuration
243
+ # Must use either 'lora' or 'qlora' adapter, and does not support fsdp or deepspeed
244
+ relora_steps: # Number of steps per ReLoRA restart
245
+ relora_warmup_steps: # Number of per-restart warmup steps
246
+ relora_anneal_steps: # Number of anneal steps for each relora cycle
247
+ relora_prune_ratio: # threshold for optimizer magnitude when pruning
248
+ relora_cpu_offload: # True to perform lora weight merges on cpu during restarts, for modest gpu memory savings
249
+
250
+ # wandb configuration if you're using it
251
+ # Make sure your `WANDB_API_KEY` environment variable is set (recommended) or you login to wandb with `wandb login`.
252
+ wandb_mode: # "offline" to save run metadata locally and not sync to the server, "disabled" to turn off wandb
253
+ wandb_project: # Your wandb project name
254
+ wandb_entity: # A wandb Team name if using a Team
255
+ wandb_watch:
256
+ wandb_name: # Set the name of your wandb run
257
+ wandb_run_id: # Set the ID of your wandb run
258
+ wandb_log_model: # "checkpoint" to log model to wandb Artifacts every `save_steps` or "end" to log only at the end of training
259
+
260
+ # mlflow configuration if you're using it
261
+ mlflow_tracking_uri: # URI to mlflow
262
+ mlflow_experiment_name: # Your experiment name
263
+ hf_mlflow_log_artifacts: # set to true to copy each saved checkpoint on each save to mlflow artifact registry
264
+
265
+ # Where to save the full-finetuned model to
266
+ output_dir: ./completed-model
267
+
268
+ # Whether to use torch.compile and which backend to use
269
+ torch_compile: # bool
270
+ torch_compile_backend: # Optional[str]
271
+
272
+ # Training hyperparameters
273
+
274
+ # If greater than 1, backpropagation will be skipped and the gradients will be accumulated for the given number of steps.
275
+ gradient_accumulation_steps: 1
276
+ # The number of samples to include in each batch. This is the number of samples sent to each GPU.
277
+ # Batch size per gpu = micro_batch_size * gradient_accumulation_steps
278
+ micro_batch_size: 2
279
+ eval_batch_size:
280
+ num_epochs: 4
281
+ warmup_steps: 100 # cannot use with warmup_ratio
282
+ warmup_ratio: 0.05 # cannot use with warmup_steps
283
+ learning_rate: 0.00003
284
+ lr_quadratic_warmup:
285
+ logging_steps:
286
+ eval_steps: # Leave empty to eval at each epoch, integers for every N steps. decimal for fraction of total steps
287
+ evals_per_epoch: # number of times per epoch to run evals, mutually exclusive with eval_steps
288
+ save_strategy: # Set to `no` to skip checkpoint saves
289
+ save_steps: # Leave empty to save at each epoch
290
+ saves_per_epoch: # number of times per epoch to save a checkpoint, mutually exclusive with save_steps
291
+ save_total_limit: # Checkpoints saved at a time
292
+ # Maximum number of iterations to train for. It precedes num_epochs which means that
293
+ # if both are set, num_epochs will not be guaranteed.
294
+ # e.g., when 1 epoch is 1000 steps => `num_epochs: 2` and `max_steps: 100` will train for 100 steps
295
+ max_steps:
296
+
297
+ eval_table_size: # Approximate number of predictions sent to wandb depending on batch size. Enabled above 0. Default is 0
298
+ eval_max_new_tokens: # Total number of tokens generated for predictions sent to wandb. Default is 128
299
+ eval_causal_lm_metrics: # HF evaluate metrics used during evaluation. Default is ["sacrebleu", "comet", "ter", chrf]
300
+
301
+ loss_watchdog_threshold: # High loss value, indicating the learning has broken down (a good estimate is ~2 times the loss at the start of training)
302
+ loss_watchdog_patience: # Number of high-loss steps in a row before the trainer aborts (default: 3)
303
+
304
+ # Save model as safetensors (require safetensors package)
305
+ save_safetensors:
306
+
307
+ # Whether to mask out or include the human's prompt from the training labels
308
+ train_on_inputs: false
309
+ # Group similarly sized data to minimize padding.
310
+ # May be slower to start, as it must download and sort the entire dataset.
311
+ # Note that training loss may have an oscillating pattern with this enabled.
312
+ group_by_length: false
313
+
314
+ # Whether to use gradient checkpointing https://huggingface.co/docs/transformers/v4.18.0/en/performance#gradient-checkpointing
315
+ gradient_checkpointing: false
316
+ # additional kwargs to pass to the trainer for gradient checkpointing
317
+ # gradient_checkpointing_kwargs:
318
+ # use_reentrant: true
319
+
320
+ # Stop training after this many evaluation losses have increased in a row
321
+ # https://huggingface.co/transformers/v4.2.2/_modules/transformers/trainer_callback.html#EarlyStoppingCallback
322
+ early_stopping_patience: 3
323
+
324
+ # Specify a scheduler and kwargs to use with the optimizer
325
+ lr_scheduler: # 'one_cycle' | 'log_sweep' | empty for cosine
326
+ lr_scheduler_kwargs:
327
+ cosine_min_lr_ratio: # decay lr to some percentage of the peak lr, e.g. cosine_min_lr_ratio=0.1 for 10% of peak lr
328
+ cosine_constant_lr_ratio: # freeze lr at some percentage of the step, e.g. cosine_constant_lr_ratio=0.8 means start cosine_min_lr at 80% of training step (https://arxiv.org/pdf/2308.04014.pdf)
329
+
330
+ # For one_cycle optim
331
+ lr_div_factor: # Learning rate div factor
332
+
333
+ # Specify optimizer
334
+ # Valid values are driven by the Transformers OptimizerNames class, see:
335
+ # https://github.com/huggingface/transformers/blob/95b374952dc27d8511541d6f5a4e22c9ec11fb24/src/transformers/training_args.py#L134
336
+ #
337
+ # Note that not all optimizers may be available in your environment, ex: 'adamw_anyprecision' is part of
338
+ # torchdistx, 'adamw_bnb_8bit' is part of bnb.optim.Adam8bit, etc. When in doubt, it is recommended to start with the optimizer used
339
+ # in the examples/ for your model and fine-tuning use case.
340
+ #
341
+ # Valid values for 'optimizer' include:
342
+ # - adamw_hf
343
+ # - adamw_torch
344
+ # - adamw_torch_fused
345
+ # - adamw_torch_xla
346
+ # - adamw_apex_fused
347
+ # - adafactor
348
+ # - adamw_anyprecision
349
+ # - sgd
350
+ # - adagrad
351
+ # - adamw_bnb_8bit
352
+ # - lion_8bit
353
+ # - lion_32bit
354
+ # - paged_adamw_32bit
355
+ # - paged_adamw_8bit
356
+ # - paged_lion_32bit
357
+ # - paged_lion_8bit
358
+ # - galore_adamw
359
+ # - galore_adamw_8bit
360
+ # - galore_adafactor
361
+ # - galore_adamw_layerwise
362
+ # - galore_adamw_8bit_layerwise
363
+ # - galore_adafactor_layerwise
364
+ optimizer:
365
+ # Dictionary of arguments to pass to the optimizer
366
+ optim_args:
367
+ # For Galore Optimizers the following optim_args are available
368
+ # rank: # type: int
369
+ # update_proj_gap # type: int
370
+ # scale # type: float
371
+ # proj_type: # type: str, default = std
372
+
373
+ # The target modules to optimize, i.e. the module names that you would like to train, right now this is used only for GaLore algorithm
374
+ optim_target_modules:
375
+ # - self_attn # for llama
376
+ # - mlp
377
+
378
+ # Specify weight decay
379
+ weight_decay:
380
+ # adamw hyperparams
381
+ adam_beta1:
382
+ adam_beta2:
383
+ adam_epsilon:
384
+ # Gradient clipping max norm
385
+ max_grad_norm:
386
+
387
+ # Augmentation techniques
388
+ # NEFT https://arxiv.org/abs/2310.05914, set this to a number (paper default is 5) to add noise to embeddings
389
+ # currently only supported on Llama and Mistral
390
+ neftune_noise_alpha:
391
+
392
+ # Whether to bettertransformers
393
+ flash_optimum:
394
+ # Whether to use xformers attention patch https://github.com/facebookresearch/xformers:
395
+ xformers_attention:
396
+ # Whether to use flash attention patch https://github.com/Dao-AILab/flash-attention:
397
+ flash_attention:
398
+ flash_attn_cross_entropy: # Whether to use flash-attention cross entropy implementation - advanced use only
399
+ flash_attn_rms_norm: # Whether to use flash-attention rms norm implementation - advanced use only
400
+ flash_attn_fuse_qkv: # Whether to fuse QKV into a single operation
401
+ flash_attn_fuse_mlp: # Whether to fuse part of the MLP into a single operation
402
+ # Whether to use scaled-dot-product attention
403
+ # https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html
404
+ sdp_attention:
405
+ # Shifted-sparse attention (only llama) - https://arxiv.org/pdf/2309.12307.pdf
406
+ s2_attention:
407
+ # Resume from a specific checkpoint dir
408
+ resume_from_checkpoint:
409
+ # If resume_from_checkpoint isn't set and you simply want it to start where it left off.
410
+ # Be careful with this being turned on between different models.
411
+ auto_resume_from_checkpoints: false
412
+
413
+ # Don't mess with this, it's here for accelerate and torchrun
414
+ local_rank:
415
+
416
+ # Add or change special tokens.
417
+ # If you add tokens here, you don't need to add them to the `tokens` list.
418
+ special_tokens:
419
+ # bos_token: "<s>"
420
+ # eos_token: "</s>"
421
+ # unk_token: "<unk>"
422
+ # pad_token: "[PAD]"
423
+
424
+ # Add extra tokens.
425
+ tokens:
426
+
427
+ # FSDP
428
+ fsdp:
429
+ fsdp_config:
430
+
431
+ # Deepspeed config path. e.g., deepspeed_configs/zero3.json
432
+ deepspeed:
433
+
434
+ # Advanced DDP Arguments
435
+ ddp_timeout:
436
+ ddp_bucket_cap_mb:
437
+ ddp_broadcast_buffers:
438
+
439
+ # Path to torch distx for optim 'adamw_anyprecision'
440
+ torchdistx_path:
441
+
442
+ # Set to HF dataset for type: 'completion' for streaming instead of pre-tokenize
443
+ pretraining_dataset:
444
+
445
+ # Debug mode
446
+ debug:
447
+
448
+ # Seed
449
+ seed:
450
+
451
+ # Allow overwrite yml config using from cli
452
+ strict:
453
+ ```
docs/dataset-formats/conversation.qmd ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Conversation
3
+ description: Conversation format for supervised fine-tuning.
4
+ order: 3
5
+ ---
6
+
7
+ ## sharegpt
8
+
9
+ conversations where `from` is `human`/`gpt`. (optional: first row with role `system` to override default system prompt)
10
+
11
+ ```{.json filename="data.jsonl"}
12
+ {"conversations": [{"from": "...", "value": "..."}]}
13
+ ```
14
+
15
+ Note: `type: sharegpt` opens special configs:
16
+ - `conversation`: enables conversions to many Conversation types. Refer to the 'name' [here](https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py) for options.
17
+ - `roles`: allows you to specify the roles for input and output. This is useful for datasets with custom roles such as `tool` etc to support masking.
18
+ - `field_human`: specify the key to use instead of `human` in the conversation.
19
+ - `field_model`: specify the key to use instead of `gpt` in the conversation.
20
+
21
+ ```yaml
22
+ datasets:
23
+ path: ...
24
+ type: sharegpt
25
+
26
+ conversation: # Options (see Conversation 'name'): https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
27
+ field_human: # Optional[str]. Human key to use for conversation.
28
+ field_model: # Optional[str]. Assistant key to use for conversation.
29
+ # Add additional keys from your dataset as input or output roles
30
+ roles:
31
+ input: # Optional[List[str]]. These will be masked based on train_on_input
32
+ output: # Optional[List[str]].
33
+ ```
34
+
35
+ ## pygmalion
36
+
37
+ ```{.json filename="data.jsonl"}
38
+ {"conversations": [{"role": "...", "value": "..."}]}
39
+ ```
40
+
41
+ ## sharegpt.load_role
42
+
43
+ conversations where `role` is used instead of `from`
44
+
45
+ ```{.json filename="data.jsonl"}
46
+ {"conversations": [{"role": "...", "value": "..."}]}
47
+ ```
48
+
49
+ ## sharegpt.load_guanaco
50
+
51
+ conversations where `from` is `prompter` `assistant` instead of default sharegpt
52
+
53
+ ```{.json filename="data.jsonl"}
54
+ {"conversations": [{"from": "...", "value": "..."}]}
55
+ ```
56
+
57
+ ## sharegpt_jokes
58
+
59
+ creates a chat where bot is asked to tell a joke, then explain why the joke is funny
60
+
61
+ ```{.json filename="data.jsonl"}
62
+ {"conversations": [{"title": "...", "text": "...", "explanation": "..."}]}
63
+ ```
docs/dataset-formats/index.qmd ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Dataset Formats
3
+ description: Supported dataset formats.
4
+ listing:
5
+ fields: [title, description]
6
+ type: table
7
+ sort-ui: false
8
+ filter-ui: false
9
+ max-description-length: 250
10
+ ---
11
+
12
+ Axolotl supports a variety of dataset formats. It is recommended to use a JSONL format. The schema of the JSONL depends upon the task and the prompt template you wish to use. Instead of a JSONL, you can also use a HuggingFace dataset with columns for each JSONL field.
13
+
14
+ Below are these various formats organized by task:
docs/dataset-formats/inst_tune.qmd ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Instruction Tuning
3
+ description: Instruction tuning formats for supervised fine-tuning.
4
+ order: 2
5
+ ---
6
+
7
+ ## alpaca
8
+
9
+ instruction; input(optional)
10
+
11
+ ```{.json filename="data.jsonl"}
12
+ {"instruction": "...", "input": "...", "output": "..."}
13
+ ```
14
+
15
+ ## jeopardy
16
+
17
+ question and answer
18
+
19
+ ```{.json filename="data.jsonl"}
20
+ {"question": "...", "category": "...", "answer": "..."}
21
+ ```
22
+
23
+ ## oasst
24
+
25
+ instruction
26
+
27
+ ```{.json filename="data.jsonl"}
28
+ {"INSTRUCTION": "...", "RESPONSE": "..."}
29
+ ```
30
+
31
+ ## gpteacher
32
+
33
+ instruction; input(optional)
34
+
35
+ ```{.json filename="data.jsonl"}
36
+ {"instruction": "...", "input": "...", "response": "..."}
37
+ ```
38
+
39
+ ## reflection
40
+
41
+ instruction with reflect; input(optional)
42
+
43
+ ```{.json filename="data.jsonl"}
44
+ {"instruction": "...", "input": "...", "output": "...", "reflection": "...", "corrected": "..."}
45
+ ```
46
+
47
+ ## explainchoice
48
+
49
+ question, choices, (solution OR explanation)
50
+
51
+ ```{.json filename="data.jsonl"}
52
+ {"question": "...", "choices": ["..."], "solution": "...", "explanation": "..."}
53
+ ```
54
+
55
+ ## concisechoice
56
+
57
+ question, choices, (solution OR explanation)
58
+
59
+ ```{.json filename="data.jsonl"}
60
+ {"question": "...", "choices": ["..."], "solution": "...", "explanation": "..."}
61
+ ```
62
+
63
+ ## summarizetldr
64
+
65
+ article and summary
66
+
67
+ ```{.json filename="data.jsonl"}
68
+ {"article": "...", "summary": "..."}
69
+ ```
70
+
71
+ ## alpaca_chat
72
+
73
+ basic instruct for alpaca chat
74
+
75
+ ```{.json filename="data.jsonl"}
76
+ {"instruction": "...", "input": "...", "response": "..."}
77
+ ```
78
+
79
+ ## alpaca_chat.load_qa
80
+
81
+ question and answer for alpaca chat
82
+
83
+ ```{.json filename="data.jsonl"}
84
+ {"question": "...", "answer": "..."}
85
+ ```
86
+
87
+ ## alpaca_chat.load_concise
88
+
89
+ question and answer for alpaca chat, for concise answers
90
+
91
+ ```{.json filename="data.jsonl"}
92
+ {"instruction": "...", "input": "...", "response": "..."}
93
+ ```
94
+
95
+ ## alpaca_chat.load_camel_ai
96
+
97
+ question and answer for alpaca chat, for load_camel_ai
98
+
99
+ ```{.json filename="data.jsonl"}
100
+ {"message_1": "...", "message_2": "..."}
101
+ ```
102
+
103
+ ## alpaca_w_system.load_open_orca
104
+
105
+ support for open orca datasets with included system prompts, instruct
106
+
107
+ ```{.json filename="data.jsonl"}
108
+ {"system_prompt": "...", "question": "...", "response": "..."}
109
+ ```
110
+
111
+ ## context_qa
112
+
113
+ in context question answering from an article
114
+
115
+ ```{.json filename="data.jsonl"}
116
+ {"article": "...", "question": "...", "answer": "..."}
117
+ ```
118
+
119
+ ## context_qa.load_v2
120
+
121
+ in context question answering (alternate)
122
+
123
+ ```{.json filename="data.jsonl"}
124
+ {"context": "...", "question": "...", "answer": "..."}
125
+ ```
126
+
127
+ ## context_qa.load_404
128
+
129
+ in context question answering from an article, with default response for no answer from context
130
+
131
+ ```{.json filename="data.jsonl"}
132
+ {"article": "...", "unanswerable_question": "..."}
133
+ ```
134
+
135
+ ## creative_acr.load_answer
136
+
137
+ instruction and revision
138
+
139
+ ```{.json filename="data.jsonl"}
140
+ {"instruction": "...", "revision": "..."}
141
+ ```
142
+
143
+ ## creative_acr.load_critique
144
+
145
+ critique
146
+
147
+ ```{.json filename="data.jsonl"}
148
+ {"scores": "...", "critiques": "...", "instruction": "...", "answer": "..."}
149
+ ```
150
+
151
+ ## creative_acr.load_revise
152
+
153
+ critique and revise
154
+
155
+ ```{.json filename="data.jsonl"}
156
+ {"scores": "...", "critiques": "...", "instruction": "...", "answer": "...", "revision": "..."}
157
+ ```
158
+
159
+ ## metharme
160
+
161
+ instruction, adds additional eos tokens
162
+
163
+ ```{.json filename="data.jsonl"}
164
+ {"prompt": "...", "generation": "..."}
165
+ ```
166
+
167
+ ## How to add custom prompt format
168
+
169
+ For a dataset that is preprocessed for instruction purposes:
170
+
171
+ ```{.json filename="data.jsonl"}
172
+ {"input": "...", "output": "..."}
173
+ ```
174
+
175
+ You can use this example in your YAML config:
176
+
177
+ ```{.yaml filename="config.yaml"}
178
+ datasets:
179
+ - path: repo
180
+ type:
181
+ system_prompt: ""
182
+ field_system: system
183
+ field_instruction: input
184
+ field_output: output
185
+ format: "[INST] {instruction} [/INST]"
186
+ no_input_format: "[INST] {instruction} [/INST]"
187
+ ```
188
+
189
+ See full config options under [here](../config.qmd).
docs/dataset-formats/pretraining.qmd ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Pre-training
3
+ description: Data format for a pre-training completion task.
4
+ order: 1
5
+ ---
6
+
7
+ For pretraining, there is no prompt template or roles. The only required field is `text`:
8
+
9
+ ```{.json filename="data.jsonl"}
10
+ {"text": "first row"}
11
+ {"text": "second row"}
12
+ ...
13
+ ```
14
+
15
+ :::{.callout-note}
16
+
17
+ ### Streaming is recommended for large datasets
18
+
19
+ Axolotl usually loads the entire dataset into memory. This will be challenging for large datasets. Use the following config to enable streaming:
20
+
21
+ ```{.yaml filename="config.yaml"}
22
+ pretraining_dataset: # hf path only
23
+ ...
24
+ ```
25
+
26
+ :::
docs/dataset-formats/template_free.qmd ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Template-Free
3
+ description: Construct prompts without a template.
4
+ order: 4
5
+ ---
6
+
7
+ See [these docs](../input_output.qmd).
docs/dataset-formats/tokenized.qmd ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Custom Pre-Tokenized Dataset
3
+ description: How to use a custom pre-tokenized dataset.
4
+ order: 5
5
+ ---
6
+
7
+ - Do not pass a `type:` in your axolotl config.
8
+ - Columns in Dataset must be exactly `input_ids`, `attention_mask`, `labels`
9
+
10
+ ```{.yaml filename="config.yml"}
11
+ - path: ...
12
+ ```
docs/dataset_preprocessing.qmd ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Dataset Preprocessing
3
+ description: How datasets are processed
4
+ ---
5
+
6
+ Dataset pre-processing is the step where Axolotl takes each dataset you've configured alongside
7
+ the (dataset format)[../dataset-formats/] and prompt strategies to:
8
+ - parse the dataset based on the *dataset format*
9
+ - transform the dataset to how you would interact with the model based on the *prompt strategy*
10
+ - tokenize the dataset based on the configured model & tokenizer
11
+ - shuffle and merge multiple datasets together if using more than one
12
+
13
+ The processing of the datasets can happen one of two ways:
14
+
15
+ 1. Before kicking off training by calling `python -m axolotl.cli.preprocess /path/to/your.yaml --debug`
16
+ 2. When training is started
17
+
18
+ What are the benefits of pre-processing? When training interactively or for sweeps
19
+ (e.g. you are restarting the trainer often), processing the datasets can oftentimes be frustratingly
20
+ slow. Pre-processing will cache the tokenized/formatted datasets according to a hash of dependent
21
+ training parameters so that it will intelligently pull from its cache when possible.
22
+
23
+ The path of the cache is controlled by `dataset_prepared_path:` and is often left blank in example
24
+ YAMLs as this leads to a more robust solution that prevents unexpectedly reusing cached data.
25
+
26
+ If `dataset_prepared_path:` is left empty, when training, the processed dataset will be cached in a
27
+ default path of `./last_run_prepared/`, but will ignore anything already cached there. By explicitly
28
+ setting `dataset_prepared_path: ./last_run_prepared`, the trainer will use whatever pre-processed
29
+ data is in the cache.
30
+
31
+ What are the edge cases? Let's say you are writing a custom prompt strategy or using a user-defined
32
+ prompt template. Because the trainer cannot readily detect these changes, we cannot change the
33
+ calculated hash value for the pre-processed dataset. If you have `dataset_prepared_path: ...` set
34
+ and change your prompt templating logic, it may not pick up the changes you made and you will be
35
+ training over the old prompt.
docs/debugging.qmd ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Debugging
3
+ description: How to debug Axolotl
4
+ ---
5
+
6
+
7
+ This document provides some tips and tricks for debugging Axolotl. It also provides an example configuration for debugging with VSCode. A good debugging setup is essential to understanding how Axolotl code works behind the scenes.
8
+
9
+ ## Table of Contents
10
+
11
+ - [General Tips](#general-tips)
12
+ - [Debugging with VSCode](#debugging-with-vscode)
13
+ - [Background](#background)
14
+ - [Configuration](#configuration)
15
+ - [Customizing your debugger](#customizing-your-debugger)
16
+ - [Video Tutorial](#video-tutorial)
17
+ - [Debugging With Docker](#debugging-with-docker)
18
+ - [Setup](#setup)
19
+ - [Attach To Container](#attach-to-container)
20
+ - [Video - Attaching To Docker On Remote Host](#video---attaching-to-docker-on-remote-host)
21
+
22
+ ## General Tips
23
+
24
+ While debugging it's helpful to simplify your test scenario as much as possible. Here are some tips for doing so:
25
+
26
+ > [!Important]
27
+ > All of these tips are incorporated into the [example configuration](#configuration) for debugging with VSCode below.
28
+
29
+ 1. **Make sure you are using the latest version of axolotl**: This project changes often and bugs get fixed fast. Check your git branch and make sure you have pulled the latest changes from `main`.
30
+ 1. **Eliminate concurrency**: Restrict the number of processes to 1 for both training and data preprocessing:
31
+ - Set `CUDA_VISIBLE_DEVICES` to a single GPU, ex: `export CUDA_VISIBLE_DEVICES=0`.
32
+ - Set `dataset_processes: 1` in your axolotl config or run the training command with `--dataset_processes=1`.
33
+ 2. **Use a small dataset**: Construct or use a small dataset from HF Hub. When using a small dataset, you will often have to make sure `sample_packing: False` and `eval_sample_packing: False` to avoid errors. If you are in a pinch and don't have time to construct a small dataset but want to use from the HF Hub, you can shard the data (this will still tokenize the entire dataset, but will only use a fraction of the data for training. For example, to shard the dataset into 20 pieces, add the following to your axolotl config):
34
+ ```yaml
35
+ dataset:
36
+ ...
37
+ shards: 20
38
+ ```
39
+ 3. **Use a small model**: A good example of a small model is [TinyLlama/TinyLlama-1.1B-Chat-v1.0](https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0).
40
+ 4. **Minimize iteration time**: Make sure the training loop finishes as fast as possible, with these settings.
41
+ - `micro_batch_size: 1`
42
+ - `max_steps: 1`
43
+ - `val_set_size: 0`
44
+ 5. **Clear Caches:** Axolotl caches certain steps and so does the underlying HuggingFace trainer. You may want to clear some of these caches when debugging.
45
+ - Data preprocessing: When debugging data preprocessing, which includes prompt template formation, you may want to delete the directory set in `dataset_prepared_path:` in your axolotl config. If you didn't set this value, the default is `last_run_prepared`.
46
+ - HF Hub: If you are debugging data preprocessing, you should clear the relevant HF cache [HuggingFace cache](https://huggingface.co/docs/datasets/cache), by deleting the appropriate `~/.cache/huggingface/datasets/...` folder(s).
47
+ - **The recommended approach is to redirect all outputs and caches to a temporary folder and delete selected subfolders before each run. This is demonstrated in the example configuration below.**
48
+
49
+
50
+ ## Debugging with VSCode
51
+
52
+ ### Background
53
+
54
+ The below example shows how to configure VSCode to debug data preprocessing of the `sharegpt` format. This is the format used when you have the following in your axolotl config:
55
+
56
+ ```yaml
57
+ datasets:
58
+ - path: <path to your sharegpt formatted dataset> # example on HF Hub: philschmid/guanaco-sharegpt-style
59
+ type: sharegpt
60
+ ```
61
+
62
+ >[!Important]
63
+ > If you are already familiar with advanced VSCode debugging, you can skip the below explanation and look at the files [.vscode/launch.json](../.vscode/launch.json) and [.vscode/tasks.json](../.vscode/tasks.json) for an example configuration.
64
+
65
+ >[!Tip]
66
+ > If you prefer to watch a video, rather than read, you can skip to the [video tutorial](#video-tutorial) below (but doing both is recommended).
67
+
68
+ ### Setup
69
+
70
+ Make sure you have an [editable install](https://setuptools.pypa.io/en/latest/userguide/development_mode.html) of Axolotl, which ensures that changes you make to the code are reflected at runtime. Run the following commands from the root of this project:
71
+
72
+ ```bash
73
+ pip3 install packaging
74
+ pip3 install -e '.[flash-attn,deepspeed]'
75
+ ```
76
+
77
+ #### Remote Hosts
78
+
79
+ If you developing on a remote host, you can easily use VSCode to debug remotely. To do so, you will need to follow this [remote - SSH guide](https://code.visualstudio.com/docs/remote/ssh). You can also see the video below on [Docker and Remote SSH debugging](#video---attaching-to-docker-on-remote-host).
80
+
81
+
82
+ ### Configuration
83
+
84
+ The easiest way to get started is to modify the [.vscode/launch.json](../.vscode/launch.json) file in this project. This is just an example configuration, so you may need to modify or copy it to suit your needs.
85
+
86
+ For example, to mimic the command `cd devtools && CUDA_VISIBLE_DEVICES=0 accelerate launch -m axolotl.cli.train dev_sharegpt.yml`, you would use the below configuration[^1]. Note that we add additional flags that override the axolotl config and incorporate the tips above (see the comments). We also set the working directory to `devtools` and set the `env` variable `HF_HOME` to a temporary folder that is later partially deleted. This is because we want to delete the HF dataset cache before each run in order to ensure that the data preprocessing code is run from scratch.
87
+
88
+ ```jsonc
89
+ // .vscode/launch.json
90
+ {
91
+ "version": "0.2.0",
92
+ "configurations": [
93
+ {
94
+ "name": "Debug axolotl prompt - sharegpt",
95
+ "type": "python",
96
+ "module": "accelerate.commands.launch",
97
+ "request": "launch",
98
+ "args": [
99
+ "-m", "axolotl.cli.train", "dev_sharegpt.yml",
100
+ // The flags below simplify debugging by overriding the axolotl config
101
+ // with the debugging tips above. Modify as needed.
102
+ "--dataset_processes=1", // limits data preprocessing to one process
103
+ "--max_steps=1", // limits training to just one step
104
+ "--batch_size=1", // minimizes batch size
105
+ "--micro_batch_size=1", // minimizes batch size
106
+ "--val_set_size=0", // disables validation
107
+ "--sample_packing=False", // disables sample packing which is necessary for small datasets
108
+ "--eval_sample_packing=False",// disables sample packing on eval set
109
+ "--dataset_prepared_path=temp_debug/axolotl_outputs/data", // send data outputs to a temp folder
110
+ "--output_dir=temp_debug/axolotl_outputs/model" // send model outputs to a temp folder
111
+ ],
112
+ "console": "integratedTerminal", // show output in the integrated terminal
113
+ "cwd": "${workspaceFolder}/devtools", // set working directory to devtools from the root of the project
114
+ "justMyCode": true, // step through only axolotl code
115
+ "env": {"CUDA_VISIBLE_DEVICES": "0", // Since we aren't doing distributed training, we need to limit to one GPU
116
+ "HF_HOME": "${workspaceFolder}/devtools/temp_debug/.hf-cache"}, // send HF cache to a temp folder
117
+ "preLaunchTask": "cleanup-for-dataprep", // delete temp folders (see below)
118
+ }
119
+ ]
120
+ }
121
+ ```
122
+
123
+ **Additional notes about this configuration:**
124
+
125
+ - The argument `justMyCode` is set to `true` such that you step through only the axolotl code. If you want to step into dependencies, set this to `false`.
126
+ - The `preLaunchTask`: `cleanup-for-dataprep` is defined in [.vscode/tasks.json](../.vscode/tasks.json) and is used to delete the following folders before debugging, which is essential to ensure that the data pre-processing code is run from scratch:
127
+ - `./devtools/temp_debug/axolotl_outputs`
128
+ - `./devtools/temp_debug/.hf-cache/datasets`
129
+
130
+ >[!Tip]
131
+ > You may not want to delete these folders. For example, if you are debugging model training instead of data pre-processing, you may NOT want to delete the cache or output folders. You may also need to add additional tasks to the `tasks.json` file depending on your use case.
132
+
133
+ Below is the [./vscode/tasks.json](../.vscode/tasks.json) file that defines the `cleanup-for-dataprep` task. This task is run before each debugging session when you use the above configuration. Note how there are two tasks that delete the two folders mentioned above. The third task `cleanup-for-dataprep` is a composite task that combines the two tasks. A composite task is necessary because VSCode does not allow you to specify multiple tasks in the `preLaunchTask` argument of the `launch.json` file.
134
+
135
+ ```jsonc
136
+ // .vscode/tasks.json
137
+ // this file is used by launch.json
138
+ {
139
+ "version": "2.0.0",
140
+ "tasks": [
141
+ // this task changes into the devtools directory and deletes the temp_debug/axolotl_outputs folder
142
+ {
143
+ "label": "delete-outputs",
144
+ "type": "shell",
145
+ "command": "rm -rf temp_debug/axolotl_outputs",
146
+ "options":{ "cwd": "${workspaceFolder}/devtools"},
147
+ "problemMatcher": []
148
+ },
149
+ // this task changes into the devtools directory and deletes the `temp_debug/.hf-cache/datasets` folder
150
+ {
151
+ "label": "delete-temp-hf-dataset-cache",
152
+ "type": "shell",
153
+ "command": "rm -rf temp_debug/.hf-cache/datasets",
154
+ "options":{ "cwd": "${workspaceFolder}/devtools"},
155
+ "problemMatcher": []
156
+ },
157
+ // this task combines the two tasks above
158
+ {
159
+ "label": "cleanup-for-dataprep",
160
+ "dependsOn": ["delete-outputs", "delete-temp-hf-dataset-cache"],
161
+ }
162
+ ]
163
+ }
164
+ ```
165
+
166
+ ### Customizing your debugger
167
+
168
+ Your debugging use case may differ from the example above. The easiest thing to do is to put your own axolotl config in the `devtools` folder and modify the `launch.json` file to use your config. You may also want to modify the `preLaunchTask` to delete different folders or not delete anything at all.
169
+
170
+ ### Video Tutorial
171
+
172
+ The following video tutorial walks through the above configuration and demonstrates how to debug with VSCode, (click the image below to watch):
173
+
174
+ <div style="text-align: center; line-height: 0;">
175
+
176
+ <a href="https://youtu.be/xUUB11yeMmc" target="_blank"
177
+ title="How to debug Axolotl (for fine tuning LLMs)"><img
178
+ src="https://i.ytimg.com/vi/xUUB11yeMmc/maxresdefault.jpg"
179
+ style="border-radius: 10px; display: block; margin: auto;" width="560" height="315" /></a>
180
+
181
+ <figcaption style="font-size: smaller;"><a href="https://hamel.dev">Hamel Husain's</a> tutorial: <a href="https://www.youtube.com/watch?v=xUUB11yeMmc">Debugging Axolotl w/VSCode</a></figcaption>
182
+
183
+ </div>
184
+ <br>
185
+
186
+ ## Debugging With Docker
187
+
188
+ Using [official Axolotl Docker images](https://hub.docker.com/r/winglian/axolotl/tags) is a great way to debug your code, and is a very popular way to use Axolotl. Attaching VSCode to Docker takes a few more steps.
189
+
190
+ ### Setup
191
+
192
+ On the host that is running axolotl (ex: if you are using a remote host), clone the axolotl repo and change your current directory to the root:
193
+
194
+ ```bash
195
+ git clone https://github.com/OpenAccess-AI-Collective/axolotl
196
+ cd axolotl
197
+ ```
198
+
199
+ >[!Tip]
200
+ > If you already have axolotl cloned on your host, make sure you have the latest changes and change into the root of the project.
201
+
202
+ Next, run the desired docker image and mount the current directory. Below is a docker command you can run to do this:[^2]
203
+
204
+ ```bash
205
+ docker run --privileged --gpus '"all"' --shm-size 10g --rm -it --name axolotl --ipc=host --ulimit memlock=-1 --ulimit stack=67108864 --mount type=bind,src="${PWD}",target=/workspace/axolotl -v ${HOME}/.cache/huggingface:/root/.cache/huggingface winglian/axolotl:main-py3.10-cu118-2.0.1
206
+ ```
207
+
208
+ >[!Tip]
209
+ > To understand which containers are available, see the [Docker section of the README](../README.md#docker) and the [DockerHub repo](https://hub.docker.com/r/winglian/axolotl/tags). For details of how the Docker containers are built, see axolotl's [Docker CI builds](../.github/workflows/main.yml).
210
+
211
+ You will now be in the container. Next, perform an editable install of Axolotl:
212
+
213
+ ```bash
214
+ pip3 install packaging
215
+ pip3 install -e '.[flash-attn,deepspeed]'
216
+ ```
217
+
218
+ ### Attach To Container
219
+
220
+ Next, if you are using a remote host, [Remote into this host with VSCode](https://code.visualstudio.com/docs/remote/ssh). If you are using a local host, you can skip this step.
221
+
222
+ Next, select `Dev Containers: Attach to Running Container...` using the command palette (`CMD + SHIFT + P`) in VSCode. You will be prompted to select a container to attach to. Select the container you just created. You will now be in the container with a working directory that is at the root of the project. Any changes you make to the code will be reflected both in the container and on the host.
223
+
224
+ Now you are ready to debug as described above (see [Debugging with VSCode](#debugging-with-vscode)).
225
+
226
+ ### Video - Attaching To Docker On Remote Host
227
+
228
+ Here is a short video that demonstrates how to attach to a Docker container on a remote host:
229
+
230
+ <div style="text-align: center; line-height: 0;">
231
+
232
+ <a href="https://youtu.be/0AuoR7QnHR0" target="_blank"
233
+ title="Debugging Axolotl Part 2: Attaching to Docker on a Remote Host"><img
234
+ src="https://i.ytimg.com/vi/0AuoR7QnHR0/hqdefault.jpg"
235
+ style="border-radius: 10px; display: block; margin: auto;" width="560" height="315" /></a>
236
+
237
+ <figcaption style="font-size: smaller;"><a href="https://hamel.dev">Hamel Husain's</a> tutorial: <a href="https://youtu.be/0AuoR7QnHR0">Debugging Axolotl Part 2: Attaching to Docker on a Remote Host
238
+ </a></figcaption>
239
+
240
+ </div>
241
+ <br>
242
+
243
+ [^1]: The config actually mimics the command `CUDA_VISIBLE_DEVICES=0 python -m accelerate.commands.launch -m axolotl.cli.train devtools/sharegpt.yml`, but this is the same thing.
244
+
245
+ [^2]: Many of the below flags are recommended best practices by Nvidia when using nvidia-container-toolkit. You can read more about these flags [here](https://docs.nvidia.com/deeplearning/frameworks/user-guide/index.html).
docs/faq.qmd ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: FAQ
3
+ description: Frequently asked questions
4
+ ---
5
+
6
+
7
+ **Q: The trainer stopped and hasn't progressed in several minutes.**
8
+
9
+ > A: Usually an issue with the GPUs communicating with each other. See the [NCCL doc](nccl.qmd)
10
+
11
+ **Q: Exitcode -9**
12
+
13
+ > A: This usually happens when you run out of system RAM.
14
+
15
+ **Q: Exitcode -7 while using deepspeed**
16
+
17
+ > A: Try upgrading deepspeed w: `pip install -U deepspeed`
18
+
19
+ **Q: AttributeError: 'DummyOptim' object has no attribute 'step'**
20
+
21
+ > A: You may be using deepspeed with single gpu. Please don't set `deepspeed:` in yaml or cli.
docs/fsdp_qlora.qmd ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: "FDSP + QLoRA"
3
+ description: Use FSDP with QLoRA to fine-tune large LLMs on consumer GPUs.
4
+ format:
5
+ html:
6
+ toc: true
7
+ ---
8
+
9
+ ## Background
10
+
11
+ Using FSDP with QLoRA is essential for **fine-tuning larger (70b+ parameter) LLMs on consumer GPUs.** For example, you can use FSDP + QLoRA to train a 70b model on two 24GB GPUs[^1].
12
+
13
+ Below, we describe how to use this feature in Axolotl.
14
+
15
+ ## Usage
16
+
17
+ To enable `QLoRA` with `FSDP`, you need to perform the following steps:
18
+
19
+ > ![Tip]
20
+ > See the [example config](#example-config) file in addition to reading these instructions.
21
+
22
+ 1. Set `adapter: qlora` in your axolotl config file.
23
+ 2. Enable FSDP in your axolotl config, as [described here](https://github.com/OpenAccess-AI-Collective/axolotl?tab=readme-ov-file#fsdp).
24
+ 3. Use one of the supported model types: `llama`, `mistral` or `mixtral`.
25
+
26
+ ## Example Config
27
+
28
+ [examples/llama-2/qlora-fsdp.yml](../examples/llama-2/qlora-fsdp.yml) contains an example of how to enable QLoRA + FSDP in axolotl.
29
+
30
+ ## References
31
+
32
+ - [PR #1378](https://github.com/OpenAccess-AI-Collective/axolotl/pull/1378) enabling QLoRA in FSDP in Axolotl.
33
+ - [Blog Post](https://www.answer.ai/posts/2024-03-06-fsdp-qlora.html) from the [Answer.AI](https://www.answer.ai/) team describing the work that enabled QLoRA in FSDP.
34
+ - Related HuggingFace PRs Enabling FDSP + QLoRA:
35
+ - Accelerate [PR#2544](https://github.com/huggingface/accelerate/pull/2544 )
36
+ - Transformers [PR#29587](https://github.com/huggingface/transformers/pull/29587)
37
+ - TRL [PR#1416](https://github.com/huggingface/trl/pull/1416)
38
+ - PEFT [PR#1550](https://github.com/huggingface/peft/pull/1550)
39
+
40
+
41
+
42
+
43
+ [^1]: This was enabled by [this work](https://www.answer.ai/posts/2024-03-06-fsdp-qlora.html) from the Answer.AI team.