Distillflow 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. distillflow/common/__init__.py +10 -0
  2. distillflow/common/common.py +98 -0
  3. distillflow/common/logger.py +101 -0
  4. distillflow/config/__init__.py +6 -0
  5. distillflow/config/config.py +26 -0
  6. distillflow/config/validator.py +38 -0
  7. distillflow/datasets/__init__.py +6 -0
  8. distillflow/datasets/args.py +99 -0
  9. distillflow/datasets/loader.py +191 -0
  10. distillflow/datasets/template/__init__.py +12 -0
  11. distillflow/datasets/template/alpaca.py +85 -0
  12. distillflow/datasets/template/args.py +56 -0
  13. distillflow/datasets/template/role.py +10 -0
  14. distillflow/datasets/template/sharegpt.py +84 -0
  15. distillflow/datasets/template/template.py +6 -0
  16. distillflow/evaluation/__init__.py +0 -0
  17. distillflow/evaluation/rouge.py +30 -0
  18. distillflow/model/__init__.py +0 -0
  19. distillflow/model/adapter.py +257 -0
  20. distillflow/model/args.py +173 -0
  21. distillflow/model/checkpoint.py +146 -0
  22. distillflow/model/finetuning_args.py +132 -0
  23. distillflow/model/generating_args.py +72 -0
  24. distillflow/model/liger_kernel.py +46 -0
  25. distillflow/model/loader.py +286 -0
  26. distillflow/model/quantization.py +193 -0
  27. distillflow/model/tokenizer.py +55 -0
  28. distillflow/model/unsloth.py +92 -0
  29. distillflow/trainer/AdaptationLayer.py +82 -0
  30. distillflow/trainer/__init__.py +0 -0
  31. distillflow/trainer/args.py +56 -0
  32. distillflow/trainer/attention_distillation.py +113 -0
  33. distillflow/trainer/fine_tuning.py +51 -0
  34. distillflow/trainer/layers_distillation.py +106 -0
  35. distillflow/trainer/logits_distillation.py +96 -0
  36. distillflow-0.2.0.dist-info/LICENSE +201 -0
  37. distillflow-0.2.0.dist-info/METADATA +162 -0
  38. distillflow-0.2.0.dist-info/RECORD +39 -0
  39. distillflow-0.2.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,106 @@
1
+ from accelerate import Accelerator
2
+ from datasets import IterableDataset
3
+ from transformers import PreTrainedModel, PreTrainedTokenizerBase
4
+ import torch
5
+ from torch.nn import functional as F
6
+ from trl import SFTTrainer
7
+
8
+ from .AdaptationLayer import AdaptationLayer
9
+ from .args import DistillArgs
10
+ from ..common import get_current_device
11
+ from ..datasets.loader import DatasetModule
12
+
13
+ class LayersTrainer(SFTTrainer):
14
+ def __init__(self,
15
+ accelerator: Accelerator,
16
+ distill_args: DistillArgs,
17
+ teacher_model: PreTrainedModel,
18
+ model: PreTrainedModel,
19
+ dataset_module: DatasetModule,
20
+ tokenizer: PreTrainedTokenizerBase
21
+ ):
22
+ self.teacher_model = teacher_model
23
+ self.distill_args = distill_args
24
+ train_dataset = dataset_module["train_dataset"]
25
+ eval_dataset = dataset_module["eval_dataset"]
26
+ self.device = get_current_device()
27
+
28
+ self.adaptation_layer = AdaptationLayer(
29
+ model.config.hidden_size,
30
+ teacher_model.config.hidden_size,
31
+ model.config.num_hidden_layers,
32
+ teacher_model.config.num_hidden_layers,
33
+ dtype=torch.float16,
34
+ strategy=distill_args.strategy,
35
+ selection_indices=distill_args.selection_indices,
36
+ weights=distill_args.weights
37
+ ).to(self.device)
38
+
39
+ if isinstance(train_dataset, IterableDataset) and distill_args.sft_config.max_steps == -1:
40
+ raise ValueError("max steps should be specified when using dataset with streaming mode enabled.")
41
+
42
+ distill_args.sft_config.max_length = distill_args.max_seq_length
43
+ distill_args.sft_config.dataset_text_field = distill_args.dataset_text_field
44
+
45
+ super().__init__(model=model, args=distill_args.sft_config, train_dataset=train_dataset,
46
+ eval_dataset=eval_dataset, processing_class=tokenizer)
47
+
48
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
49
+ model_inputs = {
50
+ "input_ids": inputs["input_ids"],
51
+ "attention_mask": inputs["attention_mask"],
52
+ }
53
+ labels = inputs["labels"]
54
+ student_outputs = model(**model_inputs, labels=labels, output_hidden_states=True)
55
+ original_loss = student_outputs.loss
56
+
57
+ self.teacher_model = self.teacher_model.to(inputs['labels'].device) if self.device.type == "mps" else self.teacher_model
58
+
59
+ teacher_model = self.teacher_model.module if hasattr(self.teacher_model, 'module') else self.teacher_model
60
+
61
+ with torch.no_grad():
62
+ teacher_outputs = teacher_model(**model_inputs, output_hidden_states=True)
63
+
64
+ custom_loss = self.distillation_loss(student_outputs, teacher_outputs, inputs, original_loss) / self.args.gradient_accumulation_steps
65
+ return (custom_loss, student_outputs) if return_outputs else custom_loss
66
+
67
+ def distillation_loss(self, student_outputs, teacher_outputs, inputs, original_loss):
68
+ student_hidden_states = student_outputs.hidden_states
69
+ teacher_hidden_states = teacher_outputs.hidden_states
70
+
71
+ self.adaptation_layer = self.adaptation_layer.to(self.device)
72
+ adapted_student_hidden_states = self.adaptation_layer(student_hidden_states)
73
+
74
+ total_loss_kd = 0
75
+ for student_hidden, teacher_idx in self.adaptation_layer.layer_mapping.items():
76
+ if self.distill_args.strategy == "weighted":
77
+ teacher_hidden = torch.zeros_like(teacher_hidden_states[0])
78
+ for idx, weight in teacher_idx.items():
79
+ teacher_hidden = weight * teacher_hidden_states[idx]
80
+ else:
81
+ teacher_hidden = teacher_hidden_states[teacher_idx]
82
+
83
+ if adapted_student_hidden_states[student_hidden].shape != teacher_hidden.shape:
84
+ raise ValueError(
85
+ f"Shape mismatch: student {adapted_student_hidden_states[student_hidden].shape} vs teacher {teacher_hidden.shape}")
86
+
87
+ student_probs = F.softmax(
88
+ adapted_student_hidden_states[student_hidden] / self.distill_args.temperature, dim=-1)
89
+ teacher_probs = F.softmax(teacher_hidden / self.distill_args.temperature, dim=-1)
90
+
91
+ loss_kd = F.kl_div(
92
+ F.log_softmax(adapted_student_hidden_states[student_hidden] / self.distill_args.temperature,
93
+ dim=-1),
94
+ teacher_probs,
95
+ reduction='batchmean'
96
+ ) * (self.distill_args.temperature ** 2)
97
+
98
+ total_loss_kd += loss_kd
99
+
100
+ avg_loss_kd = total_loss_kd / len(self.adaptation_layer.layer_mapping)
101
+ hidden_dim = adapted_student_hidden_states[0].size(-1)
102
+ scaled_loss_kd = avg_loss_kd / hidden_dim
103
+
104
+ total_loss = self.distill_args.alpha * scaled_loss_kd + (
105
+ 1 - self.distill_args.alpha) * original_loss
106
+ return total_loss
@@ -0,0 +1,96 @@
1
+ from accelerate import Accelerator
2
+ from datasets import IterableDataset
3
+ from transformers import PreTrainedModel, PreTrainedTokenizerBase
4
+ from trl import SFTTrainer
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+ from .args import DistillArgs
9
+ from ..common import get_current_device
10
+ from ..datasets.loader import DatasetModule
11
+
12
+ class LogitsTrainer(SFTTrainer):
13
+ def __init__(self,
14
+ accelerator: Accelerator,
15
+ distill_args: DistillArgs,
16
+ teacher_model: PreTrainedModel,
17
+ model: PreTrainedModel,
18
+ dataset_module: DatasetModule,
19
+ tokenizer: PreTrainedTokenizerBase
20
+ ):
21
+ self.accelerator = accelerator
22
+ self.distill_args = distill_args
23
+ self.teacher_model = teacher_model
24
+ train_dataset = dataset_module["train_dataset"]
25
+ eval_dataset = dataset_module["eval_dataset"]
26
+ self.device = get_current_device()
27
+ if self.device.type == 'mps' and not distill_args.sft_config.use_cpu:
28
+ # Explicitly place the models on device since accelerate prepare does not work on MPS.
29
+ self.teacher_model = self.teacher_model.to(self.device)
30
+ model = model.to(self.device)
31
+
32
+ #TODO: remove excess code.
33
+ # if self.accelerator is not None:
34
+ # self.is_deepspeed_enabled = getattr(self.accelerator.state, "deepspeed_plugin", None) is not None
35
+ # if self.is_deepspeed_enabled:
36
+ # if not (
37
+ # getattr(teacher_model.pretrained_model, "is_loaded_in_8bit", False)
38
+ # or getattr(teacher_model.pretrained_model, "is_loaded_in_4bit", False)
39
+ # ): # quantized models are already set on the correct device
40
+ # self.teacher_model = self._prepare_deepspeed(self.teacher_model)
41
+
42
+ if isinstance(train_dataset, IterableDataset) and distill_args.sft_config.max_steps == -1:
43
+ raise ValueError("max steps should be specified when using dataset with streaming mode enabled.")
44
+
45
+ distill_args.sft_config.max_length = distill_args.max_seq_length
46
+ distill_args.sft_config.dataset_text_field = distill_args.dataset_text_field
47
+
48
+ super().__init__(model=model, args=distill_args.sft_config, train_dataset=train_dataset,
49
+ eval_dataset=eval_dataset, processing_class=tokenizer)
50
+
51
+ def pad_logits(self, student_logits, teacher_logits):
52
+ student_size, teacher_size = student_logits.size(-1), teacher_logits.size(-1)
53
+ if student_size != teacher_size:
54
+ pad_size = abs(student_size - teacher_size)
55
+ pad_tensor = torch.zeros((*teacher_logits.shape[:-1], pad_size), dtype=teacher_logits.dtype,
56
+ device=teacher_logits.device)
57
+ return (
58
+ torch.cat([student_logits, pad_tensor], dim=-1), teacher_logits) if student_size < teacher_size else (
59
+ student_logits, torch.cat([teacher_logits, pad_tensor], dim=-1))
60
+ return student_logits, teacher_logits
61
+
62
+ def output(self, model, inputs, no_grad):
63
+ if no_grad:
64
+ with torch.no_grad():
65
+ return model(**inputs)
66
+ else:
67
+ return model(**inputs)
68
+
69
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
70
+ student_model = model.module if hasattr(model, 'module') else model
71
+ teacher_model = self.teacher_model.module if hasattr(self.teacher_model, 'module') else self.teacher_model
72
+
73
+ teacher_outputs = self.output(teacher_model, inputs, True)
74
+ student_outputs = self.output(student_model, inputs, False)
75
+
76
+ custom_loss = self.distillation_loss(student_outputs.logits, teacher_outputs.logits,
77
+ inputs, student_outputs.loss)
78
+
79
+ custom_loss = custom_loss / self.args.gradient_accumulation_steps
80
+
81
+ return (custom_loss, student_outputs) if return_outputs else custom_loss
82
+
83
+ def distillation_loss(self, student_logits, teacher_logits, inputs, original_loss):
84
+ student_logits, teacher_logits = student_logits.to(inputs['labels'].device), teacher_logits.to(inputs['labels'].device)
85
+ student_logits, teacher_logits = self.pad_logits(student_logits, teacher_logits)
86
+
87
+ student_logits_scaled = student_logits / self.distill_args.temperature
88
+ teacher_logits_scaled = teacher_logits / self.distill_args.temperature
89
+
90
+ loss_kd = F.kl_div(
91
+ F.log_softmax(student_logits_scaled, dim=-1),
92
+ F.softmax(teacher_logits_scaled, dim=-1),
93
+ reduction='batchmean'
94
+ ) * (self.distill_args.temperature ** 2) / self.distill_args.max_seq_length
95
+
96
+ return self.distill_args.alpha * loss_kd + (1 - self.distill_args.alpha) * original_loss
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,162 @@
1
+ Metadata-Version: 2.3
2
+ Name: Distillflow
3
+ Version: 0.2.0
4
+ Summary:
5
+ Author: Horus Labs
6
+ Author-email: hello@horusailabs.com
7
+ Requires-Python: >=3.12,<3.14
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Requires-Dist: accelerate (>=1.2)
12
+ Requires-Dist: bitsandbytes (>=0.44) ; sys_platform == "linux"
13
+ Requires-Dist: boto3 (>=1.35)
14
+ Requires-Dist: config (>=0.5)
15
+ Requires-Dist: datasets (>=3.0)
16
+ Requires-Dist: deepspeed (>=0.15) ; sys_platform == "linux"
17
+ Requires-Dist: evaluate (>=0.4)
18
+ Requires-Dist: google-cloud-compute (>=1.23)
19
+ Requires-Dist: huggingface-hub (>=0.26)
20
+ Requires-Dist: liger-kernel (>=0.5) ; sys_platform == "linux"
21
+ Requires-Dist: numpy (>=2.0)
22
+ Requires-Dist: pandas (>=2.2)
23
+ Requires-Dist: peft (>=0.14)
24
+ Requires-Dist: pydantic (>=2.7)
25
+ Requires-Dist: pyyaml (>=6.0)
26
+ Requires-Dist: runpod (>=1.7)
27
+ Requires-Dist: safetensors (>=0.4)
28
+ Requires-Dist: setuptools (>=75.0)
29
+ Requires-Dist: tiktoken (>=0.9)
30
+ Requires-Dist: tokenizers (>=0.20)
31
+ Requires-Dist: torch (>=2.5)
32
+ Requires-Dist: tqdm (>=4.66)
33
+ Requires-Dist: transformers (>=4.50)
34
+ Requires-Dist: triton (>=3.0) ; sys_platform == "linux"
35
+ Requires-Dist: trl (>=0.13)
36
+ Requires-Dist: unsloth (>=2024.11) ; sys_platform == "linux"
37
+ Description-Content-Type: text/x-rst
38
+
39
+ .. image:: https://s3.us-west-2.amazonaws.com/www.horusailabs.com/distillflow.png
40
+ :target: https://horusailabs.com/
41
+ :align: center
42
+
43
+ DistillFlow
44
+ ===========
45
+
46
+ Overview
47
+ ========
48
+
49
+ DistillFlow is an open-source toolkit designed to simplify and scale the distillation of large language models (LLMs) into smaller, more efficient models. It provides a flexible pipeline for distillation, fine-tuning, and experimentation across multiple GPUs, with support for dynamic resource allocation and easy integration of custom techniques.
50
+
51
+ **What is distillation?**
52
+
53
+ Distillation is the process of transferring knowledge from large machine learning models to small models. The large model is often called the teacher model while the smaller model is called the student model.
54
+
55
+ DistillFlow is maintained by HorusAILabs_.
56
+
57
+ .. _HorusAILabs: https://www.horusailabs.com/
58
+
59
+ Architecture
60
+ ============
61
+ DistillFlow lets you build a fully configurable pipeline, to help with your Distillation.
62
+ Once the data is available, choose a teacher model, and the student model and your dataset
63
+ and finally run the distillation.
64
+
65
+ .. image:: https://s3.us-west-2.amazonaws.com/www.horusailabs.com/distillflow_arch.png
66
+ :align: center
67
+ :height: 600
68
+
69
+ Key Features
70
+ ============
71
+ - **Multi-Strategy Distillation:** Supports multiple distillation techniques such as logits, attention and layers based distillation.
72
+ - **Dynamic Resource Allocation:** Automatically distributes tasks across GPUs or nodes based on available memory.
73
+ - **Fine-Tuning Support:** Allows for domain-specific and downstream fine-tuning of distilled models.
74
+ - **Model Loading Optimizations:** Supports optimized model loading using Unsloth, Liger Kernel, Flash Attention etc.
75
+ - **Easy Integration:** Compatible with popular libraries like Hugging Face Transformers, PyTorch, and DeepSpeed.
76
+
77
+ Requirements
78
+ ============
79
+
80
+ * Python 3.12+
81
+ * Works on Linux, macOS
82
+
83
+ Install
84
+ =======
85
+
86
+ Clone the repository:
87
+
88
+ .. code-block:: bash
89
+
90
+ git clone git@github.com:horus-ai-labs/DistillFlow.git
91
+ cd DistillFlow
92
+ pip3 install poetry
93
+ poetry install
94
+
95
+ Data
96
+ ======
97
+ We support any HuggingFace dataset in ShareGPT or Alpaca formats.
98
+
99
+ Quick Start
100
+ ===========
101
+ Here's a quick example to get started with DistillFlow:
102
+
103
+ Create a training config, specifying your teacher model, student model,
104
+ huggingface dataset and the distillation type.
105
+
106
+ Use one of the existing test configs in `config` folder. The `local_distill.yaml`
107
+ works for Mac.
108
+
109
+ Here is a quick config to get started:
110
+
111
+ .. code-block:: yaml
112
+
113
+ student_model:
114
+ model_name_or_path: Qwen/Qwen2-1.5B
115
+ teacher_model:
116
+ model_name_or_path: Qwen/Qwen2-7B
117
+ data:
118
+ text_field: "text"
119
+ train_datasets:
120
+ - path: mlabonne/FineTome-100k
121
+ template: sharegpt
122
+ distill:
123
+ type: logits
124
+ max_seq_length: 1024
125
+ sft_config:
126
+ output_dir: './results'
127
+ num_train_epochs: 3
128
+ per_device_train_batch_size: 1
129
+ gradient_accumulation_steps: 8
130
+ eval_strategy: steps
131
+ eval_steps: 100
132
+ save_steps: 2000
133
+ learning_rate: 2.0e-5
134
+ weight_decay: 0.05
135
+ warmup_ratio: 0.1
136
+ lr_scheduler_type: 'cosine'
137
+ max_grad_norm: 1.0
138
+ group_by_length: False
139
+ distillation_args:
140
+ temperature: 2.0
141
+ alpha: 0.5
142
+
143
+ Run the command:
144
+
145
+ .. code-block:: bash
146
+
147
+ accelerate launch src/trainer.py --config <your_config_path>
148
+
149
+ Acknowledgement
150
+ ===============
151
+ The repo structure is inspired by `LLamaFactory <https://github.com/hiyouga/LLaMA-Factory>`_.
152
+ The distillation training techniques are inspired by the works of `DistillKit <https://github.com/arcee-ai/DistillKit>`_.
153
+
154
+
155
+ License
156
+ =======
157
+ Distributed under the Apache-2.0 License. See `LICENSE <https://github.com/horus-ai-labs/DistillFlow/blob/main/LICENSE>`_ for more information.
158
+
159
+ Community and Support
160
+ =====================
161
+ - Join the discussion on our `GitHub Discussions <https://github.com/horus-ai-labs/DistillFlow/discussions>`_.
162
+ - Report issues and request features using our `Issue Tracker <https://github.com/horus-ai-labs/DistillFlow/issues>`_.
@@ -0,0 +1,39 @@
1
+ distillflow/common/__init__.py,sha256=J_4Tn9M3rZ_LM9-UpOdYJ764KZjY8EymNUMsSCMCCKY,259
2
+ distillflow/common/common.py,sha256=B9IKrkFbn2kju3ZRVmf9blmL7bl25hUcIIRiWOFfKI8,3547
3
+ distillflow/common/logger.py,sha256=Cf7u5i6cgsXVx694ZtgkWI04T4CS0d-6FbQ7JY9lCpM,3079
4
+ distillflow/config/__init__.py,sha256=Rq-01X1Xkd9TW8mMYa9uDvrmT898FZgYSl7MbDq2hso,55
5
+ distillflow/config/config.py,sha256=5y9EYmu6oiZL05jKCN18Hd4QzKzZsTe6rp9wzAUEnvU,735
6
+ distillflow/config/validator.py,sha256=3rjtjGCkTHEh8Zp_zVOgYEkKvBzEVLyO_HrpGnEfvi4,1283
7
+ distillflow/datasets/__init__.py,sha256=w_qwAByaNV2Hnuagwd2vrvN0rR6S4E2Rzq76467xy28,84
8
+ distillflow/datasets/args.py,sha256=Yglc_sbRBdifXiSGPwzI6T44jtcWxCDhGbic-0bTtLw,3520
9
+ distillflow/datasets/loader.py,sha256=1xsulKeVoDJYtFIGLL3xIh9sc_BnlE4iVnChHq1virg,8025
10
+ distillflow/datasets/template/__init__.py,sha256=pesUOqMSjmU9pADSLs4Zd06dsM2DZLkvTfhA2O3GpjY,205
11
+ distillflow/datasets/template/alpaca.py,sha256=0oNCtHnx-k1ZBiGNaLaD9fH-4Uj4inWxGw4DP4o6ubU,3315
12
+ distillflow/datasets/template/args.py,sha256=E5RVnP-t0aDo4gAPBFCnMVScCbqSCHvYcXSG67B4Atc,1993
13
+ distillflow/datasets/template/role.py,sha256=LL67hoL1A56yhHYoyE9BKVNcW3EA7wYiUM3P4lukKuY,188
14
+ distillflow/datasets/template/sharegpt.py,sha256=4HSU_qGRuD20PPW2UTFXw4V9FwsaCRzscREUD_ypCP0,3117
15
+ distillflow/datasets/template/template.py,sha256=0gr_QUeXqBo38108HtKLJGFn_dPy8w3YEYJKmTAURw0,194
16
+ distillflow/evaluation/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
+ distillflow/evaluation/rouge.py,sha256=gseHcKXhK3SL_fwvwpcDhY5t_8tXTBhL8tFhIe6ysmc,964
18
+ distillflow/model/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ distillflow/model/adapter.py,sha256=KHjiWCBE76GDG1bs0Ue5DWQ8RzBhRXPJaDu35bRnFyU,10881
20
+ distillflow/model/args.py,sha256=HjsMzOTBjZOOxbXdXj-B93JLJWe6Eqo8ph5wtfxX8wg,6306
21
+ distillflow/model/checkpoint.py,sha256=drJ0Gi3cMHpYAIot3f85B9WDDABrFTA3FZsK_wo6kYI,6215
22
+ distillflow/model/finetuning_args.py,sha256=HYchmRqwlSsERBv5hO94VVGP3knhTgyb54CmOnt6W_8,4758
23
+ distillflow/model/generating_args.py,sha256=Z-hwCp15imAgjnquoAiiU2UNCFp2R-nNPuRxenXnmzU,2532
24
+ distillflow/model/liger_kernel.py,sha256=ETJvbiDztz6MbCQX8NbwIgDUyWN45ap-L3weLodZ4tk,1952
25
+ distillflow/model/loader.py,sha256=8bylLKwR83nPtYOUuOxr8PZyRWgwEIn4SbF7u0fAIRI,12442
26
+ distillflow/model/quantization.py,sha256=rNjjjT33V8MBqjYyaxTRRbfsg2tJT7bo4AN22zJSMEg,8797
27
+ distillflow/model/tokenizer.py,sha256=gZmaN6RHoxG6SBvbxHagpS9tGUvE6NlOxBs9N6OT8R4,2041
28
+ distillflow/model/unsloth.py,sha256=c_p-weT295CReZriKMv_1XhYwBdOXUPcuClgqnRKGhQ,2998
29
+ distillflow/trainer/AdaptationLayer.py,sha256=KCHhU7gMcJzyqiuYdomelrHMDKlKBHG0EGivAxy-ETU,3805
30
+ distillflow/trainer/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
31
+ distillflow/trainer/args.py,sha256=aE59TDGFlrS-dWnqLPIxVckYEZ1onZIid3eeZuCGy0k,2225
32
+ distillflow/trainer/attention_distillation.py,sha256=ru4_EmGJ_nqvjS909zx1XuCnY-LFSzh84RAV3jGt8j4,4820
33
+ distillflow/trainer/fine_tuning.py,sha256=Rrf08s86laVtdl7QFtgiYK1ndAkDPazBO0F4Kq4XcZg,2097
34
+ distillflow/trainer/layers_distillation.py,sha256=uny1M6sJhLDhyueSh-3Pznpl8zwGs6lJKNB52R9El9U,4960
35
+ distillflow/trainer/logits_distillation.py,sha256=I1awfj2raqnefhCFG5tZzfvZdVrB-X64C1PqRgxj7pM,4836
36
+ distillflow-0.2.0.dist-info/LICENSE,sha256=KD6mzCmXoacNoASeCa35MXu2DKG1Enm2UZa4OmnhmWs,11323
37
+ distillflow-0.2.0.dist-info/METADATA,sha256=BjCXykZq8ujotzISV0YgHSZLcLY8YAWHH8q4YjAdxC8,5497
38
+ distillflow-0.2.0.dist-info/WHEEL,sha256=XbeZDeTWKc1w7CSIyre5aMDU_-PohRwTQceYnisIYYY,88
39
+ distillflow-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.1.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any