sarasa 0.0.2__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.
sarasa/utils.py ADDED
@@ -0,0 +1,163 @@
1
+ import contextlib
2
+ import gc
3
+ import os
4
+ import sys
5
+ import time
6
+ from datetime import timedelta
7
+ from functools import cache
8
+
9
+ import torch
10
+ from loguru import logger
11
+ from torch import distributed as dist
12
+ from torch import nn
13
+
14
+
15
+ def setup_logger(config) -> None:
16
+ logger.remove()
17
+ if config.debug:
18
+ logger_format = f"<blue>RANK={rank()}</blue> | " + (
19
+ "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
20
+ "<level>{level: <8}</level> | "
21
+ "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
22
+ "<level>{message}</level>"
23
+ )
24
+ logger.add(
25
+ sys.stderr,
26
+ format=logger_format,
27
+ backtrace=True,
28
+ diagnose=True,
29
+ level="DEBUG",
30
+ )
31
+ else:
32
+ # log to stderr only for rank 0
33
+ logger.add(sys.stderr, backtrace=True, diagnose=True, level="INFO" if rank() == 0 else "ERROR")
34
+
35
+
36
+ @contextlib.contextmanager
37
+ def set_dtype(
38
+ dtype: torch.dtype,
39
+ ) -> None:
40
+ old_dtype = torch.get_default_dtype()
41
+ torch.set_default_dtype(dtype)
42
+ try:
43
+ yield
44
+ finally:
45
+ torch.set_default_dtype(old_dtype)
46
+
47
+
48
+ class GarbageCollector:
49
+ def __init__(
50
+ self,
51
+ gc_freq: int,
52
+ ) -> None:
53
+ self.gc_freq = gc_freq
54
+ if self.gc_freq > 0:
55
+ # manually manage gc
56
+ gc.disable()
57
+
58
+ def collect(
59
+ self,
60
+ step: int,
61
+ ) -> None:
62
+ if self.gc_freq <= 0:
63
+ # auto gc, nothing to do
64
+ return
65
+
66
+ if step % self.gc_freq == 0:
67
+ begin = time.perf_counter()
68
+ gc.collect(generation=1)
69
+ end = time.perf_counter()
70
+ logger.info(f"Garbage collection at step {step} took {end - begin:.4f} seconds")
71
+
72
+
73
+ # distributed utils
74
+
75
+
76
+ @cache
77
+ def world_size() -> int:
78
+ if "WORLD_SIZE" in os.environ:
79
+ return int(os.environ["WORLD_SIZE"])
80
+
81
+ if not dist.is_initialized():
82
+ return 1
83
+ return dist.get_world_size()
84
+
85
+
86
+ @cache
87
+ def rank() -> int:
88
+ if "RANK" in os.environ:
89
+ return int(os.environ["RANK"])
90
+
91
+ if not dist.is_initialized():
92
+ return 0
93
+ return dist.get_rank()
94
+
95
+
96
+ @cache
97
+ def local_rank() -> int:
98
+ if not dist.is_initialized():
99
+ return 0
100
+ return dist.get_local_rank()
101
+
102
+
103
+ def init_distributed(
104
+ backend: str,
105
+ init_timeout_seconds: int,
106
+ ) -> None:
107
+ if "RANK" in os.environ:
108
+ # run with torchrun
109
+ dist.init_process_group(
110
+ backend=backend,
111
+ timeout=timedelta(seconds=init_timeout_seconds),
112
+ )
113
+ logger.info("Initialized distributed process group")
114
+ else:
115
+ logger.info("Skipping distributed initialization")
116
+
117
+
118
+ def update_timeout(
119
+ timeout_seconds: int,
120
+ device: torch.device,
121
+ ) -> None:
122
+ logger.info(f"Updating distributed timeout to {timeout_seconds} seconds")
123
+ torch.distributed.barrier(device_ids=[torch.accelerator.current_device_index()])
124
+ torch.accelerator.synchronize(device)
125
+
126
+ # at the moment, default process group is the only one supported (None)
127
+ torch.distributed.distributed_c10d._set_pg_timeout(timedelta(seconds=timeout_seconds), None)
128
+
129
+
130
+ def apply_distributed(
131
+ config,
132
+ model: nn.Module,
133
+ device: torch.device,
134
+ compile: bool,
135
+ ) -> None:
136
+ mesh = dist.device_mesh.init_device_mesh(device.type, (world_size(),))
137
+
138
+ if config.name == "ddp":
139
+ from torch.distributed._composable.replicate import replicate
140
+
141
+ if compile:
142
+ torch._dynamo.config.optimize_ddp = "ddp_optimizer"
143
+
144
+ replicate(model, device_mesh=mesh, bucket_cap_mb=100)
145
+ logger.info("Applied DDP to the model")
146
+
147
+ elif config.name == "fsdp":
148
+ from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard
149
+
150
+ # todo: make dtypes configurable
151
+ mp_policy = MixedPrecisionPolicy(
152
+ param_dtype=torch.bfloat16,
153
+ reduce_dtype=torch.float32,
154
+ )
155
+
156
+ for block in model.blocks:
157
+ fully_shard(block, mesh=mesh, mp_policy=mp_policy, reshard_after_forward=config.reshard_after_forward)
158
+ fully_shard(model, mesh=mesh, mp_policy=mp_policy, reshard_after_forward=config.reshard_after_forward)
159
+
160
+ logger.info(
161
+ f"Applied FSDP to the model (param_dtype={mp_policy.param_dtype}, "
162
+ f"reduce_dtype={mp_policy.reduce_dtype}, reshard_after_forward={config.reshard_after_forward})"
163
+ )
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: sarasa
3
+ Version: 0.0.2
4
+ Summary: Add your description here
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.13
7
+ Requires-Dist: datasets>=4.5.0
8
+ Requires-Dist: loguru>=0.7.3
9
+ Requires-Dist: numpy>=2.4.1
10
+ Requires-Dist: rich>=14.2.0
11
+ Requires-Dist: tensorboard>=2.20.0
12
+ Requires-Dist: tokenizers>=0.22.2
13
+ Requires-Dist: tyro>=1.0.5
14
+ Provides-Extra: cpu
15
+ Requires-Dist: torch>=2.10.0; extra == 'cpu'
16
+ Provides-Extra: cu128
17
+ Requires-Dist: torch>=2.10.0; extra == 'cu128'
18
+ Provides-Extra: cu130
19
+ Requires-Dist: torch>=2.10.0; extra == 'cu130'
20
+ Provides-Extra: flash-attn
21
+ Requires-Dist: flash-attn-cute; extra == 'flash-attn'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # sarasa
25
+
26
+ A minimum LLM training framework built on pure PyTorch with simplicity and extensibility.
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ uv sync [--extra cpu|cu128|cu130] [--extra flash_attn]
32
+ ```
33
+
34
+ or
35
+
36
+ ```bash
37
+ uv add sarasa[cpu|cu128|cu130]
38
+ ```
39
+
40
+ ## Features
41
+
42
+ - Pure PyTorch implementation
43
+ - Flexible configuration system with command-line overrides
44
+ - Support from a single GPU to multiple GPUs (simple DDP and FSDP for now)
45
+ - Selective activation checkpointing (SAC) for memory efficiency
46
+ - Async distributed checkpoint saving
47
+
48
+ - [ ] Checkpoint loading
49
+
50
+ ## Usage
51
+
52
+ It's (almost) ready to use.
53
+ First, set up tokenizer, e.g.,
54
+
55
+ ```bash
56
+ mkdir tokenizer
57
+ cd tokenizer
58
+ uvx hf download --local-dir . --include "tokenizer*" "meta-llama/Llama-3.1-8B"
59
+ ```
60
+
61
+ Then, the following command starts training of a GPT model on FineWeb-edu with a single or multiple GPUs.
62
+
63
+ ```bash
64
+ uv run torchrun --nproc_per_node="gpu" main.py \
65
+ --config-file configs/example.py \
66
+ [--train.local-batch-size 8 ...] # override config options as needed
67
+ ```
68
+
69
+ ### Extending with Custom Components
70
+
71
+ Extending Sarasa is as simple as defining your own configuration dataclasses with `create` methods for custom models, optimizers, data loaders, etc.
72
+ Here's an example of using a custom optimizer:
73
+
74
+ ```python
75
+ from sarasa import Trainer, Config
76
+
77
+ class CustomOptimizer(torch.optim.Optimizer):
78
+ ...
79
+
80
+ class CustomOptim:
81
+ lr: float = ...
82
+
83
+ def create(self,
84
+ model: torch.nn.Module
85
+ ) -> torch.optim.Optimizer:
86
+ return CustomOptimizer(model.parameters(), lr=self.lr, ...)
87
+
88
+ class CustomOptim2:
89
+ lr: float = ...
90
+
91
+ def create(self,
92
+ model: torch.nn.Module
93
+ ) -> torch.optim.Optimizer:
94
+ return CustomOptimizer(model.parameters(), lr=self.lr, ...)
95
+
96
+
97
+ if __name__ == "__main__":
98
+ config = Config.from_cli(optim_type=CustomOptim | CustomOptim2)
99
+ trainer = Trainer(config)
100
+ trainer.train()
101
+ ```
102
+
103
+ From the command line, you can specify which custom optimizer to use:
104
+
105
+ ```bash
106
+ python script.py optim:custom_optim --optim.lr 0.001 ...
107
+ ```
108
+
109
+ ### Config File Example
110
+
111
+ It's very simple. IDE autocompletion will help you.
112
+
113
+ ```python
114
+ from sarasa.config import Config, Data, LRScheduler, Model, Train, LRScheduler
115
+ from custom_optim import CustomOptim
116
+
117
+ # only one Config instance should be defined in each config file
118
+ config = Config.create(
119
+ model=Model(num_layers=12),
120
+ train=Train(
121
+ local_batch_size=16,
122
+ global_batch_size=256,
123
+ dtype="bfloat16",
124
+ ),
125
+ optim=CustomOptim(lr=0.001),
126
+ lr_scheduler=LRScheduler(
127
+ decay_type="linear",
128
+ warmup_steps=1000,
129
+ total_steps=100000,
130
+ ),
131
+ data=Data(tokenizer_path="./tokenizer"),
132
+ seed=12,
133
+ )
134
+ ```
135
+
136
+ ## Acknowledgements
137
+
138
+ This project is heavily inspired by and borrows code from `torchtitan`.
@@ -0,0 +1,21 @@
1
+ sarasa/__init__.py,sha256=PrMUKyqcTKgKR3R3VMTzfuQ9EwMNVyw7qRl84Dz3d28,77
2
+ sarasa/activation_checkpoint.py,sha256=iGib3e2GFxBLOtgcPLQZnzw0Ru6Gd_yFqWZmUw0Cfa4,3056
3
+ sarasa/checkpoint.py,sha256=nZNo-qv3hvtzZuN0xw4SsCP4QmIM7E5nqGBxGfGYZo0,3616
4
+ sarasa/config.py,sha256=7flyQPS_Ati0xk9qP4opUJTn1wxssZpLh4DbplUFP8k,8570
5
+ sarasa/metrics.py,sha256=OzTuK3Oed-I_2FC7rrE9FYi3NgTdKsDsVkWlGgJGh0M,10636
6
+ sarasa/trainer.py,sha256=0wK2QRZuwtmOA-gxD-nmAUY-sEA0C0aAmSjlufxP7HE,9212
7
+ sarasa/utils.py,sha256=iPteVmAWmEzvriAeUL36d3MKvp27m2oJO2yFNOO_ufk,4398
8
+ sarasa/data/__init__.py,sha256=I0JOb9QrHEj9zXUX8kLir6ONAyiozeagzApig0WcSt8,1150
9
+ sarasa/data/hf_datasets.py,sha256=DUlCpBOcDtZNEGrx4AtZTPW5IMtxIXMX_pKfnQEqzEg,3966
10
+ sarasa/data/tokenizer.py,sha256=JhUOl9USJRM-DVPY02ouiaNUhAu1w2LLGquMnAyyA68,1752
11
+ sarasa/models/__init__.py,sha256=w9p4lZ0oEH2kRMxPh88Ogphwqx_o_Ik8Upfv9SrW7hA,3223
12
+ sarasa/models/attention.py,sha256=rWm6NurkS5wdnzP_LPonCMJt_gQulySQDPFpVZtpGWU,3006
13
+ sarasa/models/llama3.py,sha256=jGrrC2AQJvdyo_YvbGC4vmy23k-19Itsj_fSHUY2QTc,4509
14
+ sarasa/models/nanochat_gpt.py,sha256=cpyoXwlWhqeUtgYSQ673AW6lh9BQ-64_9G9XURfZ1MY,8721
15
+ sarasa/models/utils.py,sha256=_0F8yFVB2ZVClr8YppBhPOWtpNF0dSkmaElCYCkO_co,1111
16
+ sarasa/optimizers/__init__.py,sha256=TH7CV-dexzVIm_NJKpo3VxnzwLvUjPyckD_oXMT48xo,1844
17
+ sarasa/optimizers/utils.py,sha256=yI1_yHllJFyGbFW8jdMbvLfa5k7zUXjdgkvbr64mFOI,705
18
+ sarasa-0.0.2.dist-info/METADATA,sha256=oLIgc94HZ54wJTLmb1f6BhcTL4wy8TFtz-CCW0G7ji8,3452
19
+ sarasa-0.0.2.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
20
+ sarasa-0.0.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
21
+ sarasa-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.