Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82d22c5742 | ||
|
|
96744ac2d2 | ||
|
|
2331713fde | ||
|
|
c74fbf84b7 | ||
|
|
5a8c442315 | ||
|
|
c7d0448822 | ||
|
|
1d43a1785e | ||
|
|
5713b55500 | ||
|
|
b53e10aac4 | ||
|
|
dff58468d6 | ||
|
|
8a8d6369bc | ||
|
|
80e17418b4 | ||
|
|
6089a12cef | ||
|
|
b17cc6a6fb | ||
|
|
a33d086883 | ||
|
|
e9f42ec8b1 | ||
|
|
582d4ae9a7 | ||
|
|
0ca4871e80 | ||
|
|
99ef8fda71 | ||
|
|
dbd57e30e5 | ||
|
|
a5869d89ba | ||
|
|
7a9b9d0659 | ||
|
|
75758ead46 | ||
|
|
7dfa5cc0ac | ||
|
|
9dab96c31f | ||
|
|
ff5c8a71f5 | ||
|
|
4da70785b5 | ||
|
|
d407962ffa | ||
|
|
3d8047fa1b | ||
|
|
d21682f97a | ||
|
|
eba99e1f5e | ||
|
|
fd7ee2895a | ||
|
|
cfa3cf7daa | ||
|
|
7623b1e5fd | ||
|
|
573f041c51 | ||
|
|
eab7a51bb6 | ||
|
|
3ac38a7ebc | ||
|
|
831933fb66 | ||
|
|
701fb9bf78 | ||
|
|
d882f65579 | ||
|
|
a30ddca517 | ||
|
|
8e975017d3 | ||
|
|
fed4d64cea | ||
|
|
110efd2a21 | ||
|
|
530fb50352 | ||
|
|
c86e573195 | ||
|
|
0093ba7bb8 | ||
|
|
c934210066 | ||
|
|
c98b175cd5 | ||
|
|
82e65ccc21 | ||
|
|
d52685facd | ||
|
|
d31137a2db | ||
|
|
6270415590 | ||
|
|
08c5a52dc8 | ||
|
|
ac1fefb363 | ||
|
|
8b20982933 | ||
|
|
d5cc9f065d | ||
|
|
db53cc5001 | ||
|
|
3ee84b31a0 | ||
|
|
567c55685e | ||
|
|
1f5cba889b | ||
|
|
019bfe4e05 | ||
|
|
36b410384b | ||
|
|
09963a3beb | ||
|
|
5daf63a7a4 | ||
|
|
fb85aaf6a6 | ||
|
|
6fb6a15e81 | ||
|
|
d9ff662e3a | ||
|
|
e12ed0a72b | ||
|
|
3bf2468905 | ||
|
|
3c7ed84516 | ||
|
|
1c3a693d79 | ||
|
|
e99ef9d6d8 | ||
|
|
4c289e974a |
@@ -0,0 +1,17 @@
|
|||||||
|
name: Spell Check
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
spellcheck:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Check spelling in specific files
|
||||||
|
uses: codespell-project/actions-codespell@v2
|
||||||
|
with:
|
||||||
|
check_filenames: true
|
||||||
|
only_warn: false
|
||||||
|
path: "**/*.{md, py}"
|
||||||
+10
-11
@@ -1,13 +1,12 @@
|
|||||||
# cache
|
# Ignore everything
|
||||||
__pycache__
|
*
|
||||||
.pytest_cache
|
|
||||||
|
|
||||||
# params
|
# Allow directories to be traversed
|
||||||
params/*
|
!*/
|
||||||
|
|
||||||
# vscode file
|
# Allow specific file types and root files
|
||||||
.vscode
|
!*.py
|
||||||
|
!*.md
|
||||||
# build file
|
!*.png
|
||||||
build
|
!LICENSE
|
||||||
*.egg-info
|
!pyproject.toml
|
||||||
@@ -1,201 +1,674 @@
|
|||||||
Apache License
|
GNU GENERAL PUBLIC LICENSE
|
||||||
Version 2.0, January 2004
|
Version 3, 29 June 2007
|
||||||
http://www.apache.org/licenses/
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
1. Definitions.
|
Preamble
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction,
|
The GNU General Public License is a free, copyleft license for
|
||||||
and distribution as defined by Sections 1 through 9 of this document.
|
software and other kinds of works.
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by
|
The licenses for most software and other practical works are designed
|
||||||
the copyright owner that is granting the License.
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all
|
When we speak of free software, we are referring to freedom, not
|
||||||
other entities that control, are controlled by, or are under common
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
control with that entity. For the purposes of this definition,
|
have the freedom to distribute copies of free software (and charge for
|
||||||
"control" means (i) the power, direct or indirect, to cause the
|
them if you wish), that you receive source code or can get it if you
|
||||||
direction or management of such entity, whether by contract or
|
want it, that you can change the software or use pieces of it in new
|
||||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
free programs, and that you know you can do these things.
|
||||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity
|
To protect your rights, we need to prevent others from denying you
|
||||||
exercising permissions granted by this License.
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications,
|
For example, if you distribute copies of such a program, whether
|
||||||
including but not limited to software source code, documentation
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
source, and configuration files.
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
transformation or translation of a Source form, including but
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
not limited to compiled object code, generated documentation,
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
and conversions to other media types.
|
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
Object form, made available under the License, as indicated by a
|
that there is no warranty for this free software. For both users' and
|
||||||
copyright notice that is included in or attached to the work
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
(an example is provided in the Appendix below).
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object
|
Some devices are designed to deny users access to install or run
|
||||||
form, that is based on (or derived from) the Work and for which the
|
modified versions of the software inside them, although the manufacturer
|
||||||
editorial revisions, annotations, elaborations, or other modifications
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
represent, as a whole, an original work of authorship. For the purposes
|
protecting users' freedom to change the software. The systematic
|
||||||
of this License, Derivative Works shall not include works that remain
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
separable from, or merely link (or bind by name) to the interfaces of,
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
the Work and Derivative Works thereof.
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including
|
Finally, every program is threatened constantly by software patents.
|
||||||
the original version of the Work and any modifications or additions
|
States should not allow patents to restrict development and use of
|
||||||
to that Work or Derivative Works thereof, that is intentionally
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
avoid the special danger that patents applied to a free program could
|
||||||
or by an individual or Legal Entity authorized to submit on behalf of
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
the copyright owner. For the purposes of this definition, "submitted"
|
patents cannot be used to render the program non-free.
|
||||||
means any form of electronic, verbal, or written communication sent
|
|
||||||
to the Licensor or its representatives, including but not limited to
|
|
||||||
communication on electronic mailing lists, source code control systems,
|
|
||||||
and issue tracking systems that are managed by, or on behalf of, the
|
|
||||||
Licensor for the purpose of discussing and improving the Work, but
|
|
||||||
excluding communication that is conspicuously marked or otherwise
|
|
||||||
designated in writing by the copyright owner as "Not a Contribution."
|
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
The precise terms and conditions for copying, distribution and
|
||||||
on behalf of whom a Contribution has been received by Licensor and
|
modification follow.
|
||||||
subsequently incorporated within the Work.
|
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
TERMS AND CONDITIONS
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
copyright license to reproduce, prepare Derivative Works of,
|
|
||||||
publicly display, publicly perform, sublicense, and distribute the
|
|
||||||
Work and such Derivative Works in Source or Object form.
|
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of
|
0. Definitions.
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
(except as stated in this section) patent license to make, have made,
|
|
||||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
||||||
where such license applies only to those patent claims licensable
|
|
||||||
by such Contributor that are necessarily infringed by their
|
|
||||||
Contribution(s) alone or by combination of their Contribution(s)
|
|
||||||
with the Work to which such Contribution(s) was submitted. If You
|
|
||||||
institute patent litigation against any entity (including a
|
|
||||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
||||||
or a Contribution incorporated within the Work constitutes direct
|
|
||||||
or contributory patent infringement, then any patent licenses
|
|
||||||
granted to You under this License for that Work shall terminate
|
|
||||||
as of the date such litigation is filed.
|
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
Work or Derivative Works thereof in any medium, with or without
|
|
||||||
modifications, and in Source or Object form, provided that You
|
|
||||||
meet the following conditions:
|
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
Derivative Works a copy of this License; and
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
stating that You changed the files; and
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
that You distribute, all copyright, patent, trademark, and
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
attribution notices from the Source form of the Work,
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
excluding those notices that do not pertain to any part of
|
earlier work or a work "based on" the earlier work.
|
||||||
the Derivative Works; and
|
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its
|
A "covered work" means either the unmodified Program or a work based
|
||||||
distribution, then any Derivative Works that You distribute must
|
on the Program.
|
||||||
include a readable copy of the attribution notices contained
|
|
||||||
within such NOTICE file, excluding those notices that do not
|
|
||||||
pertain to any part of the Derivative Works, in at least one
|
|
||||||
of the following places: within a NOTICE text file distributed
|
|
||||||
as part of the Derivative Works; within the Source form or
|
|
||||||
documentation, if provided along with the Derivative Works; or,
|
|
||||||
within a display generated by the Derivative Works, if and
|
|
||||||
wherever such third-party notices normally appear. The contents
|
|
||||||
of the NOTICE file are for informational purposes only and
|
|
||||||
do not modify the License. You may add Your own attribution
|
|
||||||
notices within Derivative Works that You distribute, alongside
|
|
||||||
or as an addendum to the NOTICE text from the Work, provided
|
|
||||||
that such additional attribution notices cannot be construed
|
|
||||||
as modifying the License.
|
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and
|
To "propagate" a work means to do anything with it that, without
|
||||||
may provide additional or different license terms and conditions
|
permission, would make you directly or secondarily liable for
|
||||||
for use, reproduction, or distribution of Your modifications, or
|
infringement under applicable copyright law, except executing it on a
|
||||||
for any such Derivative Works as a whole, provided Your use,
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
reproduction, and distribution of the Work otherwise complies with
|
distribution (with or without modification), making available to the
|
||||||
the conditions stated in this License.
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
To "convey" a work means any kind of propagation that enables other
|
||||||
any Contribution intentionally submitted for inclusion in the Work
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
by You to the Licensor shall be under the terms and conditions of
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
this License, without any additional terms or conditions.
|
|
||||||
Notwithstanding the above, nothing herein shall supersede or modify
|
|
||||||
the terms of any separate license agreement you may have executed
|
|
||||||
with Licensor regarding such Contributions.
|
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
names, trademarks, service marks, or product names of the Licensor,
|
to the extent that it includes a convenient and prominently visible
|
||||||
except as required for reasonable and customary use in describing the
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
origin of the Work and reproducing the content of the NOTICE file.
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
1. Source Code.
|
||||||
agreed to in writing, Licensor provides the Work (and each
|
|
||||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
||||||
implied, including, without limitation, any warranties or conditions
|
|
||||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
||||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
||||||
appropriateness of using or redistributing the Work and assume any
|
|
||||||
risks associated with Your exercise of permissions under this License.
|
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory,
|
The "source code" for a work means the preferred form of the work
|
||||||
whether in tort (including negligence), contract, or otherwise,
|
for making modifications to it. "Object code" means any non-source
|
||||||
unless required by applicable law (such as deliberate and grossly
|
form of a work.
|
||||||
negligent acts) or agreed to in writing, shall any Contributor be
|
|
||||||
liable to You for damages, including any direct, indirect, special,
|
|
||||||
incidental, or consequential damages of any character arising as a
|
|
||||||
result of this License or out of the use or inability to use the
|
|
||||||
Work (including but not limited to damages for loss of goodwill,
|
|
||||||
work stoppage, computer failure or malfunction, or any and all
|
|
||||||
other commercial damages or losses), even if such Contributor
|
|
||||||
has been advised of the possibility of such damages.
|
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing
|
A "Standard Interface" means an interface that either is an official
|
||||||
the Work or Derivative Works thereof, You may choose to offer,
|
standard defined by a recognized standards body, or, in the case of
|
||||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
interfaces specified for a particular programming language, one that
|
||||||
or other liability obligations and/or rights consistent with this
|
is widely used among developers working in that language.
|
||||||
License. However, in accepting such obligations, You may act only
|
|
||||||
on Your own behalf and on Your sole responsibility, not on behalf
|
|
||||||
of any other Contributor, and only if You agree to indemnify,
|
|
||||||
defend, and hold each Contributor harmless for any liability
|
|
||||||
incurred by, or claims asserted against, such Contributor by reason
|
|
||||||
of your accepting any such warranty or additional liability.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
APPENDIX: How to apply the Apache License to your work.
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
To apply the Apache License to your work, attach the following
|
The Corresponding Source need not include anything that users
|
||||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
can regenerate automatically from other parts of the Corresponding
|
||||||
replaced with your own identifying information. (Don't include
|
Source.
|
||||||
the brackets!) The text should be enclosed in the appropriate
|
|
||||||
comment syntax for the file format. We also recommend that a
|
|
||||||
file or class name and description of purpose be included on the
|
|
||||||
same "printed page" as the copyright notice for easier
|
|
||||||
identification within third-party archives.
|
|
||||||
|
|
||||||
Copyright [yyyy] [name of copyright owner]
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
2. Basic Permissions.
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
You may make, run and propagate covered works that you do not
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
convey, without conditions so long as your license otherwise remains
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
in force. You may convey covered works to others for the sole purpose
|
||||||
See the License for the specific language governing permissions and
|
of having them make modifications exclusively for you, or provide you
|
||||||
limitations under the License.
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
@@ -12,39 +12,39 @@
|
|||||||
|
|
||||||
<h2 id="english">English Version</h2>
|
<h2 id="english">English Version</h2>
|
||||||
|
|
||||||
This is a Chinese-English bilingual Transformer model supporting both languages. It contains model configurations and training workflows, completing training by loading parameters defined in `param_path/config.json`. The training script `train.py` parses command-line arguments, including dataset root directory, number of training epochs, batch size, checkpoint interval, and checkpoint directory.
|
A training and inference framework for autoregressive Transformer language models.
|
||||||
|
|
||||||
**Model Download Options (Choose One):**
|
**Model Download Options (choose one):**
|
||||||
|
|
||||||
1. Visit [HuggingFace](https://huggingface.co/ViperEk/KHAOSZ) to access **Files and versions**
|
1. Visit [HuggingFace](https://huggingface.co/ViperEk/KHAOSZ) and check **Files and versions**
|
||||||
2. Run `scripts/download.py` to download parameters
|
2. Run `scripts/download.py` to download model parameters
|
||||||
|
|
||||||
**Demo Video:** [bilibili](https://www.bilibili.com/video/BV1z5RPYHEkd)
|
**Demo Video:** [bilibili](https://www.bilibili.com/video/BV1z5RPYHEkd)
|
||||||
|
|
||||||
Training dataset sources are listed in the **Model Card** section of the HuggingFace download link.
|
For training data sources, please refer to the **Model Card** section on the HuggingFace download page.
|
||||||
|
|
||||||
**License:** Code follows Apache-2.0 protocol. Please credit the source code when used.
|
**License:** The code follows the GPL-3.0 license. Please provide attribution when using it.
|
||||||
|
|
||||||
|
- **📊 Device Selection:** Uses CUDA for training by default
|
||||||
|
- **🌐 Performance Optimization:** Enable `dtype=torch.bfloat16` to accelerate training and reduce memory usage. Ensure your hardware supports this feature
|
||||||
|
- **🤖 Language Support:** The model supports training in Chinese and English. Since the BBPE tokenizer hasn't been trained on multilingual text, OOV (Out-of-Vocabulary) issues are minimal for Chinese and English, but may exist for other languages
|
||||||
|
|
||||||
- **📊 Device Selection:** Code defaults to CUDA training
|
|
||||||
- **🌐 Performance Optimization:** `dtype=torch.bfloat16` is enabled to accelerate training and reduce memory usage. Ensure hardware supports this feature.
|
|
||||||
- **🤖 Language Support:** Model supports Chinese and English training. The BBPE tokenizer was trained without multilingual text, so OOV (out-of-vocabulary) issues are minimized for these languages but may exist for others.
|
|
||||||
|
|
||||||
### 📌 Training Guide
|
### 📌 Training Guide
|
||||||
|
|
||||||
To train this Transformer model, follow these steps:
|
To train this Transformer model, follow these steps:
|
||||||
|
|
||||||
**(1). Prepare Dataset:**
|
**(1). Prepare the Dataset:**
|
||||||
|
|
||||||
Place datasets in the designated root directory. Files should be text documents in Chinese, English, or mixed. Format should align with model input requirements - preferably pre-tokenized token_ids stored as `torch.Tensor` (using `torch.Tensor` saves memory compared to Python lists, which default to 64-bit precision).
|
Place the dataset in the specified root directory. This system uses the BBPE tokenizer for tokenization and requires training with pre-tokenized segments (stored as *.h5 format files).
|
||||||
|
|
||||||
**(2). Install Dependencies:**
|
**(2). Install Dependencies:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install -r requirements.txt
|
pip install -e .
|
||||||
pip install .
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**(3). Run Training Script:**
|
**(3). Run the Training Script:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python train.py \
|
python train.py \
|
||||||
@@ -55,29 +55,29 @@ python train.py \
|
|||||||
--batch_size=8 \
|
--batch_size=8 \
|
||||||
--max_lr=2e-4 \
|
--max_lr=2e-4 \
|
||||||
--checkpoint_interval=10000 \
|
--checkpoint_interval=10000 \
|
||||||
--checkpoint_dir=checkpoints
|
--checkpoint_dir=checkpoints
|
||||||
```
|
```
|
||||||
|
|
||||||
**Parameters Explanation:**
|
**Parameter Explanation:**
|
||||||
- `--train_type`: Training type (seq, sft, dpo)
|
- `--train_type`: Training type (seq, sft, dpo)
|
||||||
- `--data_root_path`: Root directory of the dataset
|
- `--data_root_path`: Dataset root directory
|
||||||
- `--param_path`: Path to the model training parameters
|
- `--param_path`: Path to model training parameters
|
||||||
- `--n_epoch`: Total number of training epochs
|
- `--n_epoch`: Total number of training epochs
|
||||||
- `--batch_size`: Batch size
|
- `--batch_size`: Batch size
|
||||||
- `--accumulation_steps`: Number of batches per training step
|
- `--accumulation_steps`: Number of batches per training step
|
||||||
- `--warmup_steps`: Number of warmup steps
|
- `--warmup_steps`: Warmup steps
|
||||||
- `--max_lr`: Maximum learning rate (using warmup + cosine decay)
|
- `--max_lr`: Maximum learning rate (using warmup + cosine decay)
|
||||||
- `--checkpoint_interval`: Checkpoint saving interval
|
- `--checkpoint_interval`: Checkpoint saving interval
|
||||||
- `--checkpoint_dir`: Directory to save checkpoints
|
- `--checkpoint_dir`: Checkpoint saving directory
|
||||||
- `--resume_dir`: Resume training from the specified path
|
- `--resume_dir`: Resume training from specified path
|
||||||
|
|
||||||
|
|
||||||
Training logs will be saved in `train_log.txt`. Checkpoints will be saved in the specified directory for resuming training or evaluation.
|
|
||||||
|
|
||||||
### 👉 Usage Guide
|
### 👉 Usage Guide
|
||||||
|
|
||||||
**(1). Chatting with the Model:**
|
**(1). Chat with the Model:**
|
||||||
|
|
||||||
Open `chat.py` or use streaming/non-streaming interfaces:
|
Open `chat.py` or use the streaming/non-streaming interfaces:
|
||||||
|
|
||||||
**Streaming Output:**
|
**Streaming Output:**
|
||||||
```python
|
```python
|
||||||
@@ -129,7 +129,7 @@ while True:
|
|||||||
print(response)
|
print(response)
|
||||||
```
|
```
|
||||||
|
|
||||||
**(2) Retrieval-Augmented Generation (RAG):**
|
**(2). Retrieval-Augmented Generation (RAG):**
|
||||||
|
|
||||||
```python
|
```python
|
||||||
import torch
|
import torch
|
||||||
@@ -148,29 +148,8 @@ retrieved_content = model.retrieve_generate(
|
|||||||
print(retrieved_content)
|
print(retrieved_content)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 📌 Model Specifications
|
|
||||||
|
|
||||||
This model is based on a 24-layer Transformer with parameters defined in `config.json`, totaling approximately 1.0 billion (1.0B) parameters.
|
|
||||||
|
|
||||||
**Key Design Choices:**
|
|
||||||
- Weight tying between embedding and final linear layers (standard for small models to save parameters)
|
|
||||||
- Embedding layer optimization: Without weight tying, a 10,000-word vocabulary would consume ~102M parameters (0.1B)
|
|
||||||
|
|
||||||
**Limitations:**
|
|
||||||
- May struggle with complex language phenomena due to smaller parameter size
|
|
||||||
- Prone to overfitting on specialized datasets
|
|
||||||
- Limited multilingual capabilities
|
|
||||||
|
|
||||||
**Advantages:**
|
|
||||||
- Runs efficiently on lower-spec hardware
|
|
||||||
- Shorter training time compared to larger models
|
|
||||||
|
|
||||||
**Training Pipeline:**
|
|
||||||
The model has completed pre-training + SFT (Supervised Fine-Tuning) + DPO (Direct Preference Optimization) workflows. All corresponding training code is included in the repository.
|
|
||||||
|
|
||||||
|
|
||||||
<h2 id="chinese">中文版本</h2>
|
<h2 id="chinese">中文版本</h2>
|
||||||
这是一个支持中英文双语的 Transformer 模型,能够处理两种语言。模型包含配置文件和训练流程,通过加载 `param_path/config.json` 中定义的参数完成训练。训练脚本 `train.py` 支持命令行参数解析,包括数据集根目录、训练轮数(epochs)、批量大小(batch size)、检查点保存间隔、检查点目录等。
|
这是一个支持基于自回归模式的 Transfomer 语言模型训练以及推理框架
|
||||||
|
|
||||||
**模型下载选项(任选其一):**
|
**模型下载选项(任选其一):**
|
||||||
|
|
||||||
@@ -181,30 +160,28 @@ The model has completed pre-training + SFT (Supervised Fine-Tuning) + DPO (Direc
|
|||||||
|
|
||||||
训练数据来源请参见 HuggingFace 下载页面中的 **Model Card** 部分。
|
训练数据来源请参见 HuggingFace 下载页面中的 **Model Card** 部分。
|
||||||
|
|
||||||
**许可证:** 代码遵循 Apache-2.0 协议,使用时请注明出处。
|
**许可证:** 代码遵循 GPL-3.0 协议,使用时请注明出处。
|
||||||
|
|
||||||
- **📊 设备选择:** 默认使用 CUDA 进行训练
|
- **📊 设备选择:** 默认使用 CUDA 进行训练
|
||||||
- **🌐 性能优化:** 启用 `dtype=torch.bfloat16` 以加速训练并减少内存占用,请确保硬件支持该特性
|
- **🌐 性能优化:** 启用 `dtype=torch.bfloat16` 以加速训练并减少内存占用,请确保硬件支持该特性
|
||||||
- **🤖 语言支持:** 模型支持中文和英文训练。由于 BBPE 分词器未使用多语言文本训练,因此中英文的 OOV(未登录词)问题较少,其他语言可能存在 OOV 问题
|
- **🤖 语言支持:** 模型支持中文和英文训练。由于 BBPE 分词器未使用多语言文本训练,因此中英文的 OOV(未登录词)问题较少,其他语言可能存在 OOV 问题
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### 📌 训练指南
|
### 📌 训练指南
|
||||||
|
|
||||||
要训练该 Transformer 模型,请按照以下步骤操作:
|
要训练该 Transformer 模型,请按照以下步骤操作:
|
||||||
|
|
||||||
#### **(1). 准备数据集:**
|
**(1). 准备数据集:**
|
||||||
|
|
||||||
将数据集放置在指定的根目录下。文件应为包含中文、英文或混合文本的文本文档。格式应符合模型输入要求——建议使用预分词后的 `token_ids` 并以 `torch.Tensor` 格式保存(使用 `torch.Tensor` 相比 Python 列表更节省内存,列表默认为 64 位精度)。
|
将数据集放置在指定的根目录下, 本系统采用 BBPE 分词器进行分词,并且要求使用已经经过分词的 token 分段训练(分段存储为 *.h5 格式)
|
||||||
|
|
||||||
#### **(2). 安装依赖:**
|
**(2). 安装依赖:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install -r requirements.txt
|
pip install -e .
|
||||||
pip install .
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### **(3). 运行训练脚本:**
|
**(3). 运行训练脚本:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python train.py \
|
python train.py \
|
||||||
@@ -231,13 +208,11 @@ python train.py \
|
|||||||
- `--checkpoint_dir`: 检查点保存目录
|
- `--checkpoint_dir`: 检查点保存目录
|
||||||
- `--resume_dir`: 从指定路径恢复训练
|
- `--resume_dir`: 从指定路径恢复训练
|
||||||
|
|
||||||
训练日志将保存在 `train_log.txt` 中。检查点将保存在指定目录,用于恢复训练或评估。
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### 👉 使用指南
|
### 👉 使用指南
|
||||||
|
|
||||||
#### **(1). 与模型对话:**
|
**(1). 与模型对话:**
|
||||||
|
|
||||||
打开 `chat.py` 或使用流式/非流式接口:
|
打开 `chat.py` 或使用流式/非流式接口:
|
||||||
|
|
||||||
@@ -291,7 +266,7 @@ while True:
|
|||||||
print(response)
|
print(response)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### **(2). 基于检索的生成(RAG):**
|
**(2). 基于检索的生成(RAG):**
|
||||||
|
|
||||||
```python
|
```python
|
||||||
import torch
|
import torch
|
||||||
@@ -308,26 +283,4 @@ retrieved_content = model.retrieve_generate(
|
|||||||
top_p=0.95
|
top_p=0.95
|
||||||
)
|
)
|
||||||
print(retrieved_content)
|
print(retrieved_content)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### 📌 模型规格说明(重复部分)
|
|
||||||
|
|
||||||
该模型基于一个 24 层的 Transformer 架构,参数配置定义在 `config.json` 中,总参数量约为 10 亿(1.0B)。
|
|
||||||
|
|
||||||
**关键设计选择:**
|
|
||||||
- 在嵌入层(embedding)与最终线性层之间进行权重绑定(weight tying),这是小型模型中常见的节省参数量的做法
|
|
||||||
- 嵌入层优化:若不进行权重绑定,一个包含 10,000 个词的词汇表将消耗约 1.02 亿(0.1B)参数
|
|
||||||
|
|
||||||
**局限性:**
|
|
||||||
- 由于参数规模较小,可能在处理复杂语言现象时表现受限
|
|
||||||
- 在特定领域的数据集上容易出现过拟合
|
|
||||||
- 多语言能力有限
|
|
||||||
|
|
||||||
**优势:**
|
|
||||||
- 可在低配置硬件上高效运行
|
|
||||||
- 相较于大型模型,训练时间更短
|
|
||||||
|
|
||||||
**训练流程:**
|
|
||||||
该模型已完成预训练(pre-training)+ 监督微调(SFT, Supervised Fine-Tuning)+ 直接偏好优化(DPO, Direct Preference Optimization)的全流程。所有相关的训练代码均已包含在代码库中。
|
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
## 1. 为什么我要做这个项目?
|
||||||
|
|
||||||
|
现在市面上有很多大模型,比如GPT、LLaMA这些,动不动就是几十亿甚至上千亿参数。但说实话,这些模型对硬件要求太高了,普通开发者根本玩不起。我就想:**能不能做一个既好用又能在普通电脑上跑起来的模型呢?** 这其实也是目前大部分人的期望, 能有一个可以本地部署的ai小型项目,实现完全私有化并且有一定的智能能力。
|
||||||
|
|
||||||
|
于是就有了这个KHAOSZ项目,1B参数,中英双语,支持对话、文本生成、RAG检索,而且训练代码都是开源的!
|
||||||
|
|
||||||
|
## 2. 系统架构
|
||||||
|
|
||||||
|
系统分为以下板块
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph LR
|
||||||
|
%% 样式定义
|
||||||
|
classDef config fill:#e1f5fe,stroke:#01579b;
|
||||||
|
classDef trainer fill:#f3e5f5,stroke:#4a148c;
|
||||||
|
classDef data fill:#e8f5e8,stroke:#1b5e20;
|
||||||
|
classDef model fill:#fff3e0,stroke:#e65100;
|
||||||
|
classDef inference fill:#fce4ec,stroke:#880e4f;
|
||||||
|
classDef parallel fill:#e0f2f1,stroke:#004d40;
|
||||||
|
|
||||||
|
%% 配置模块
|
||||||
|
subgraph Config["Config(配置模块)"]
|
||||||
|
C1[model_config.py]
|
||||||
|
C2[train_config.py]
|
||||||
|
C3[scheduler_config.py]
|
||||||
|
end
|
||||||
|
class Config config;
|
||||||
|
|
||||||
|
%% 训练器模块
|
||||||
|
subgraph Trainer["Trainer(训练器模块)"]
|
||||||
|
T1[trainer.py]
|
||||||
|
T2[train_content.py]
|
||||||
|
T3[schedule.py]
|
||||||
|
T4[strategy.py]
|
||||||
|
T5[train_callback.py]
|
||||||
|
end
|
||||||
|
class Trainer trainer;
|
||||||
|
|
||||||
|
%% 数据模块
|
||||||
|
subgraph Data["Data(数据模块)"]
|
||||||
|
D1[dataset.py]
|
||||||
|
D2[sampler.py]
|
||||||
|
D3[mmap.py]
|
||||||
|
D4[tokenizer.py]
|
||||||
|
D5[checkpoint.py]
|
||||||
|
end
|
||||||
|
class Data data;
|
||||||
|
|
||||||
|
%% 模型模块
|
||||||
|
subgraph Model["Model(模型模块)"]
|
||||||
|
M1[transformer.py]
|
||||||
|
M2[module.py]
|
||||||
|
end
|
||||||
|
class Model model;
|
||||||
|
|
||||||
|
%% 推理模块
|
||||||
|
subgraph Inference["Inference(推理模块)"]
|
||||||
|
I1[generator.py]
|
||||||
|
I2[core.py]
|
||||||
|
end
|
||||||
|
class Inference inference;
|
||||||
|
|
||||||
|
%% 并行模块
|
||||||
|
subgraph Parallel["Parallel(并行模块)"]
|
||||||
|
P1[setup.py]
|
||||||
|
P2[module.py]
|
||||||
|
end
|
||||||
|
class Parallel parallel;
|
||||||
|
|
||||||
|
%% 配置依赖
|
||||||
|
C2 -.-> T1
|
||||||
|
C1 -.-> M1
|
||||||
|
C3 -.-> T3
|
||||||
|
|
||||||
|
%% 训练器内部依赖
|
||||||
|
T1 --> T5
|
||||||
|
T1 --> T2
|
||||||
|
T2 --> T3
|
||||||
|
T2 --> T4
|
||||||
|
|
||||||
|
%% 数据流
|
||||||
|
D1 --> D2
|
||||||
|
D1 --> D3
|
||||||
|
D1 --> D4
|
||||||
|
D1 --> D5
|
||||||
|
|
||||||
|
%% 模型依赖
|
||||||
|
M1 --> M2
|
||||||
|
|
||||||
|
%% 推理依赖
|
||||||
|
I1 --> I2
|
||||||
|
|
||||||
|
%% 跨模块依赖
|
||||||
|
T2 -.-> M1
|
||||||
|
I1 -.-> M1
|
||||||
|
T2 -.-> D1
|
||||||
|
T1 -.-> P1
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### 1. 配置管理(/config/)
|
||||||
|
- **模型配置**:定义模型结构参数(如层数、头数、维度等),通过 `ModelConfig` 统一管理。
|
||||||
|
- **训练配置**:设置训练参数(如批次大小、训练阶段 PT/SFT/DPO、优化器等),由 `TrainConfig` 加载。
|
||||||
|
- **调度配置**:控制学习率策略(如余弦退火)和训练进度。
|
||||||
|
|
||||||
|
### 2. 硬件与并行(/parallel/)
|
||||||
|
- **分布式初始化**:通过 `setup_parallel` 函数,根据配置初始化多卡/多机训练环境。
|
||||||
|
|
||||||
|
### 3. 数据处理(/data/)
|
||||||
|
- **高效加载**:使用内存映射(mmap)技术加载超大语料,避免内存溢出,实现零拷贝读取。
|
||||||
|
|
||||||
|
### 4. 模型与训练(/model/, /trainer/)
|
||||||
|
- **统一模型架构**:基于 Transformer,支持灵活配置不同规模(如7B、13B)。
|
||||||
|
- **策略化训练器**:`Trainer` 根据训练阶段(PT/SFT/DPO)自动切换训练策略,复用同一训练循环。
|
||||||
|
- **训练上下文管理**:统一管理模型、优化器、调度器和指标,支持多阶段无缝衔接。
|
||||||
|
|
||||||
|
### 5. 推理服务(/inference/, /utils/)
|
||||||
|
- **统一生成接口**:提供同步、批量、流式生成方法,适配所有训练阶段。
|
||||||
|
- **KV缓存优化**:在自回归生成中缓存 Key/Value,昇腾XPU下利用高速片上内存加速。
|
||||||
|
- **RAG支持**:结合检索器和嵌入模型,从外部知识库注入相关信息,提升回答质量。
|
||||||
|
- **智能文本分割**:
|
||||||
|
- **结构优先分割**:按标题、段落等切分;
|
||||||
|
- **语义分割**:基于句子嵌入相似度,确保片段语义完整,提升微调效果。
|
||||||
|
|
||||||
|
|
||||||
|
## 3. 训练流程
|
||||||
|
|
||||||
|
常见大语言模型(Large Language Model, LLM)的训练流程通常包含三个阶段:**预训练(Pre-training, PT)**、**监督微调(Supervised Fine-Tuning, SFT)** 以及 **基于人类反馈的强化学习(Reinforcement Learning from Human Feedback, RLHF)**。本系统设计支持全流程无缝衔接,通过模块化策略实现不同训练阶段的高效切换与状态管理,确保模型能力从通用语言理解逐步对齐至符合人类偏好的对话与指令执行。
|
||||||
|
|
||||||
|
### **2.1 预训练阶段**
|
||||||
|
|
||||||
|
预训练阶段旨在构建模型的基础语言能力与通用知识表示。该阶段在大规模、无标注的语料库(通常涵盖数百GB至数TB的文本数据)上进行自监督学习。模型架构基于标准的Transformer Decoder,通过掩码语言建模(如因果语言建模)目标进行训练,使模型能够学习词汇、语法、语义及蕴含于文本中的世界知识。
|
||||||
|
|
||||||
|
**核心公式:因果语言建模(Causal Language Modeling)**
|
||||||
|
|
||||||
|
$$
|
||||||
|
L_{\text{PT}} = - \sum_{t=1}^{T} \log P(x_t \mid x_{\lt t}; \theta)
|
||||||
|
$$
|
||||||
|
|
||||||
|
**符号说明:**
|
||||||
|
|
||||||
|
- $T$:序列长度
|
||||||
|
- $x_t$:序列中第 $ t $ 个词元(token)
|
||||||
|
- $x_{<t}$:位置 $ t $ 之前的所有词元
|
||||||
|
- $\theta$:模型参数
|
||||||
|
- $P(x_t \mid x_{<t}; \theta)$:模型在给定上文条件下预测下一个词元的概率
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
本阶段的核心在于利用分布式的并行计算资源,实现模型参数的稳定优化。训练器模块中的`PTStrategy`策略,专门负责管理预训练特有的数据采样、长序列分段与梯度累积逻辑。同时,硬件适配模块会根据运行环境(如华为昇腾NPU集群或标准GPU集群)自动选择最优的并行通信后端(如HCCL或NCCL),并进行计算图优化,以最大化硬件利用率和训练吞吐量。
|
||||||
|
|
||||||
|
另外系统通过数据模块中的高效内存映射加载器(`MmapFileHandler`),实现海量数据的零拷贝读取,以克服传统IO瓶颈。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### **2.2 监督微调阶段**
|
||||||
|
|
||||||
|
预训练模型虽具备强大的语言生成能力,但尚未对齐至遵循人类指令、进行安全有益对话的行为模式。监督微调阶段旨在弥合这一差距。该阶段使用由人工精心编写的、高质量的“指令-响应”配对数据集。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
**核心公式:序列到序列条件语言建模**
|
||||||
|
|
||||||
|
设完整序列 $S = [s_1, s_2, \ldots, s_{P+L}]$,其中:
|
||||||
|
|
||||||
|
- 前 $P$ 个token是prompt 以及对应控制token: $X = [s_1, \ldots, s_P]$
|
||||||
|
- 后 $L$ 个token是response以及对应控制token: $Y = [s_{P+1}, \ldots, s_{P+L}]$
|
||||||
|
|
||||||
|
损失函数为:
|
||||||
|
|
||||||
|
$$
|
||||||
|
L_{\text{SFT}} = - \sum_{t=P+1}^{P+L} \log P(s_t \mid s_{\lt t}; \theta)
|
||||||
|
$$
|
||||||
|
|
||||||
|
训练器模块将动态切换到`SFTStrategy`策略。此策略的核心是引入序列级的监督学习目标,例如预测给定指令下完整、正确的响应序列。训练上下文管理器(`TrainContext`)负责平滑地从PT阶段检查点加载模型状态,并初始化新的优化器和学习率调度器。本阶段不仅优化模型参数,更重要的是引导模型学习“对话”这一特定任务范式,使其输出风格、内容与格式均符合人类期望。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### **2.3 基于人类反馈的强化学习阶段**
|
||||||
|
|
||||||
|
为生成更具帮助性、无害性且符合人类偏好的高质量输出,系统进一步集成强化学习阶段。传统的RLHF流程包括**奖励模型训练**与**策略模型微调**两个核心步骤。系统支持以直接偏好优化(Direct Preference Optimization,DPO)算法为代表的策略微调,并针对稳定性与收敛性进行了多项工程优化。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#### **2.3.1 传统 RLHF(奖励模型训练)**
|
||||||
|
|
||||||
|
$$
|
||||||
|
L_{\text{RM}} = -\mathbb{E}_{(x, y_w, y_l) \sim D} \left[ \log \sigma\left( r_\phi(x, y_w) - r_\phi(x, y_l) \right) \right]
|
||||||
|
$$
|
||||||
|
|
||||||
|
**符号说明:**
|
||||||
|
|
||||||
|
- $r_\phi(x, y)$:参数为 $phi$ 的奖励模型给出的标量分数
|
||||||
|
- $y_w, y_l $:同一提示 $ x $ 下的优选和劣选回答
|
||||||
|
- $\sigma $:sigmoid 函数
|
||||||
|
- $\mathcal{D} $:人类偏好数据集
|
||||||
|
|
||||||
|
|
||||||
|
#### **2.3.2 DPO 直接偏好优化**(推荐)
|
||||||
|
|
||||||
|
$$
|
||||||
|
L_{\text{DPO}} = -E_{(x, y_w, y_l) \sim D} \left[ \log \sigma\left( \beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)} \right) \right]
|
||||||
|
$$
|
||||||
|
|
||||||
|
**符号说明:**
|
||||||
|
|
||||||
|
- $\pi_\theta(y \mid x) $:当前策略模型生成回答的概率
|
||||||
|
- $\pi_{\text{ref}}(y \mid x) $:参考模型生成回答的概率
|
||||||
|
- $\beta $:温度参数(通常设为 0.1-0.5)
|
||||||
|
- 注意:隐式学习奖励函数 $r(x, y) = \beta \log \frac{\pi_\theta(y \mid x)}{\pi_{\text{ref}}(y \mid x)} $
|
||||||
|
|
||||||
|
|
||||||
|
在本阶段,训练器模块启用`RLHFStrategy`策略(或类似的`DPOStrategy`直接偏好优化策略)。该策略管理一个复杂的训练循环,其中包含策略模型(待优化的LLM)、参考模型(通常为SFT后的模型快照)和奖励模型。系统流程如下:
|
||||||
|
|
||||||
|
1. **偏好数据收集与奖励建模**:首先,通过收集人类标注员对同一提示词下多个模型生成结果的排序偏好数据,训练一个独立的奖励模型(Reward Model, RM)。该模型学习为生成文本输出一个标量奖励分数,以量化其符合人类偏好的程度。
|
||||||
|
2. **策略优化**:随后,使用奖励模型作为优化信号,通过强化学习算法对SFT模型(作为策略)进行微调。策略优化的目标是最大化从奖励模型获得的期望累计奖励,同时通过KL散度惩罚项约束策略模型与参考模型的输出分布不过度偏离,以防止模式崩溃并保持生成多样性。训练上下文管理器在此阶段同时维护策略模型、参考模型和奖励模型(或价值函数模型)的状态,并协调复杂的多阶段梯度计算。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
通过上述三阶段的递进式训练,模型完成了从通用语言基座到专业化、高对齐度对话智能体的进化。系统通过统一的`Trainer`接口和策略模式设计,使得各阶段训练在代码层面高度复用,在流程层面清晰解耦,为大规模语言模型的研发与迭代提供了高效、灵活且可扩展的工程基础。
|
||||||
@@ -4,8 +4,8 @@
|
|||||||
|
|
||||||
$$
|
$$
|
||||||
\begin{align*}
|
\begin{align*}
|
||||||
o_i &= \sum_j s_{ij} v_{j} \\
|
o_i &= \sum_j s_{ij} v_{j} \newline
|
||||||
s_{ij} &= \text{softmax}\left( \sum_n \frac{q_{i,n} k_{j,n}}{\sqrt{d_k}} \right)
|
s_{ij} &= \text{softmax}\left( \frac{q_{i} k_{j}}{\sqrt{d_k}} \right)
|
||||||
\end{align*}
|
\end{align*}
|
||||||
$$
|
$$
|
||||||
|
|
||||||
@@ -13,15 +13,15 @@ $$
|
|||||||
|
|
||||||
$$
|
$$
|
||||||
\begin{align*}
|
\begin{align*}
|
||||||
o_n &= \sum_j s_{j}v_{j,n} \\
|
o_n &= \sum_j s_{j}v_{j} \newline
|
||||||
s_j &= \text{softmax}\left(\sum_n\frac{q_n k_{j,n}}{\sqrt{d_k}} \right)
|
s_j &= \text{softmax}\left(\frac{q_n k_{j}}{\sqrt{d_k}} \right)
|
||||||
\end{align*}
|
\end{align*}
|
||||||
$$
|
$$
|
||||||
|
|
||||||
如果我们把式子展开
|
如果我们把式子展开
|
||||||
|
|
||||||
$$
|
$$
|
||||||
o_n = \sum_j \sum_n \text{softmax}\left(\frac{q_n k_{j,n}}{\sqrt{d_k}}\right)v_{j,n}
|
o_n = \sum_j \text{softmax}\left(\frac{q_n k_{j}}{\sqrt{d_k}}\right)v_{j}
|
||||||
$$
|
$$
|
||||||
|
|
||||||
以上表达式只有k和v存在长度下标, 而 $q$ 没有, 所以计算过程中 $q$ 的输入是确定的上次输入的最后一个token, 而 $k, v$ 是需要对不同长度的部分进行缓存的,同时缓存的时候应该注意位置编码的计算应该在kvcache的计算之前进行,否则会存在位置编码的计算错误
|
以上表达式只有k和v存在长度下标, 而 $q$ 没有, 所以计算过程中 $q$ 的输入是确定的上次输入的最后一个token, 而 $k, v$ 是需要对不同长度的部分进行缓存的,同时缓存的时候应该注意位置编码的计算应该在kvcache的计算之前进行,否则会存在位置编码的计算错误
|
||||||
@@ -35,7 +35,7 @@ if __name__ == "__main__":
|
|||||||
top_k=50
|
top_k=50
|
||||||
)
|
)
|
||||||
|
|
||||||
print("retrive content:")
|
print("retrieve content:")
|
||||||
print("\n".join([f"{idx + 1}. " + text for idx, (text, _) in enumerate(retrieved)]))
|
print("\n".join([f"{idx + 1}. " + text for idx, (text, _) in enumerate(retrieved)]))
|
||||||
|
|
||||||
print("\n\nretrive generate:")
|
print("\n\nretrive generate:")
|
||||||
+1
-3
@@ -1,10 +1,9 @@
|
|||||||
__version__ = "1.3.1"
|
__version__ = "1.3.2"
|
||||||
__author__ = "ViperEkura"
|
__author__ = "ViperEkura"
|
||||||
|
|
||||||
from khaosz.api import Khaosz
|
from khaosz.api import Khaosz
|
||||||
from khaosz.config import (
|
from khaosz.config import (
|
||||||
ModelConfig,
|
ModelConfig,
|
||||||
ParameterLoader,
|
|
||||||
TrainConfig,
|
TrainConfig,
|
||||||
)
|
)
|
||||||
from khaosz.model.transformer import Transformer
|
from khaosz.model.transformer import Transformer
|
||||||
@@ -42,7 +41,6 @@ __all__ = [
|
|||||||
"PriorityTextSplitter",
|
"PriorityTextSplitter",
|
||||||
|
|
||||||
"ModelConfig",
|
"ModelConfig",
|
||||||
"ParameterLoader",
|
|
||||||
"TrainConfig",
|
"TrainConfig",
|
||||||
|
|
||||||
"DatasetLoader",
|
"DatasetLoader",
|
||||||
|
|||||||
+3
-2
@@ -9,12 +9,13 @@ from khaosz.inference.generator import (
|
|||||||
RetrievalGenerator,
|
RetrievalGenerator,
|
||||||
EmbeddingEncoder
|
EmbeddingEncoder
|
||||||
)
|
)
|
||||||
from khaosz.config.param_config import ParameterLoader
|
from khaosz.config.param_config import ModelParameter
|
||||||
|
|
||||||
|
|
||||||
class Khaosz:
|
class Khaosz:
|
||||||
def __init__(self, model_dir: str):
|
def __init__(self, model_dir: str):
|
||||||
self.parameter = ParameterLoader.load(model_dir)
|
self.parameter = ModelParameter()
|
||||||
|
self.parameter.load(model_dir)
|
||||||
|
|
||||||
def to(self, *args, **kwargs):
|
def to(self, *args, **kwargs):
|
||||||
self.parameter.to(*args, **kwargs)
|
self.parameter.to(*args, **kwargs)
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from khaosz.config.model_config import ModelConfig
|
from khaosz.config.model_config import ModelConfig
|
||||||
from khaosz.config.param_config import BaseModelIO, ModelParameter, Checkpoint, ParameterLoader
|
from khaosz.config.param_config import BaseModelIO, ModelParameter
|
||||||
from khaosz.config.schedule_config import ScheduleConfig, CosineScheduleConfig, SGDRScheduleConfig
|
from khaosz.config.schedule_config import ScheduleConfig, CosineScheduleConfig, SGDRScheduleConfig
|
||||||
from khaosz.config.train_config import TrainConfig
|
from khaosz.config.train_config import TrainConfig
|
||||||
|
|
||||||
@@ -7,8 +7,6 @@ from khaosz.config.train_config import TrainConfig
|
|||||||
__all__ = [
|
__all__ = [
|
||||||
"BaseModelIO",
|
"BaseModelIO",
|
||||||
"ModelParameter",
|
"ModelParameter",
|
||||||
"Checkpoint",
|
|
||||||
"ParameterLoader",
|
|
||||||
"ModelConfig",
|
"ModelConfig",
|
||||||
"TrainConfig",
|
"TrainConfig",
|
||||||
|
|
||||||
|
|||||||
@@ -1,37 +1,43 @@
|
|||||||
import json
|
import json
|
||||||
|
|
||||||
from dataclasses import asdict, dataclass
|
from dataclasses import asdict, dataclass
|
||||||
from typing import Any, Dict, Optional, Self
|
from typing import Optional, Self
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class ModelConfig:
|
class ModelConfig:
|
||||||
# basic config
|
# basic config
|
||||||
vocab_size: Optional[int] = None
|
vocab_size: Optional[int] = None
|
||||||
n_dim: Optional[int] = None
|
dim: Optional[int] = None
|
||||||
n_head: Optional[int] = None
|
|
||||||
n_layer: Optional[int] = None
|
n_layers: Optional[int] = None
|
||||||
m_len: Optional[int] = None
|
|
||||||
norm_eps: Optional[float] = None
|
norm_eps: Optional[float] = None
|
||||||
d_ffn: Optional[int] = None
|
dim_ffn: Optional[int] = None
|
||||||
tie_weight: Optional[bool] = None
|
tie_weight: Optional[bool] = None
|
||||||
|
|
||||||
|
# RoPE
|
||||||
|
max_len: Optional[int] = None
|
||||||
|
rope_theta: Optional[float] = None
|
||||||
|
|
||||||
# GQA
|
# GQA
|
||||||
n_kvhead: Optional[int] = None
|
n_heads: Optional[int] = None
|
||||||
|
n_kv_heads: Optional[int] = None
|
||||||
|
use_qk_norm: Optional[bool] = None
|
||||||
|
use_gated_attention: Optional[bool] = None
|
||||||
|
|
||||||
|
|
||||||
def load(self, config_path: str) -> Self:
|
def load(self, config_path: str) -> Self:
|
||||||
|
config = {}
|
||||||
with open(config_path, 'r') as f:
|
with open(config_path, 'r') as f:
|
||||||
config: Dict[str, Any] = json.load(f)
|
config.update(json.load(f))
|
||||||
|
|
||||||
for key, value in config.items():
|
for key, value in config.items():
|
||||||
if hasattr(self, key):
|
if hasattr(self, key):
|
||||||
setattr(self, key, value)
|
setattr(self, key, value)
|
||||||
|
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def save(self, config_path: str) -> None:
|
def save(self, config_path: str):
|
||||||
config_dict = asdict(self)
|
config_dict = {k: v for k, v in asdict(self).items() if v is not None}
|
||||||
config_dict = {k: v for k, v in config_dict.items() if v is not None}
|
|
||||||
with open(config_path, 'w') as f:
|
with open(config_path, 'w') as f:
|
||||||
json.dump(config_dict, f, indent=4)
|
json.dump(config_dict, f, indent=4)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+20
-184
@@ -1,30 +1,30 @@
|
|||||||
import pickle as pkl
|
|
||||||
import matplotlib.pyplot as plt
|
|
||||||
import safetensors.torch as st
|
|
||||||
import torch.nn as nn
|
import torch.nn as nn
|
||||||
import torch.optim as optim
|
import safetensors.torch as st
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Any, Dict, List, Optional, Self, Union
|
from typing import Optional, Self, Union
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from khaosz.data.tokenizer import BpeTokenizer
|
from khaosz.data.tokenizer import BpeTokenizer
|
||||||
from khaosz.config.model_config import ModelConfig
|
from khaosz.config.model_config import ModelConfig
|
||||||
from khaosz.model.transformer import Transformer
|
from khaosz.model.transformer import Transformer
|
||||||
|
|
||||||
|
@dataclass
|
||||||
class BaseModelIO:
|
class BaseModelIO:
|
||||||
"""Base class for model I/O operations."""
|
"""Base class for model I/O operations."""
|
||||||
|
|
||||||
def __init__(
|
model: Optional[nn.Module] = field(
|
||||||
self,
|
default=None,
|
||||||
model: Optional[nn.Module] = None,
|
metadata={"help": "Transformer model."}
|
||||||
tokenizer: Optional[BpeTokenizer] = None,
|
)
|
||||||
config: Optional[ModelConfig] = None
|
tokenizer: BpeTokenizer = field(
|
||||||
):
|
default_factory=BpeTokenizer,
|
||||||
self.model = model
|
metadata={"help": "Tokenizer for the model."}
|
||||||
self.tokenizer = tokenizer or BpeTokenizer()
|
)
|
||||||
self.config = config or ModelConfig()
|
config: ModelConfig = field(
|
||||||
|
default_factory=ModelConfig,
|
||||||
|
metadata={"help": "Transformer model configuration."}
|
||||||
|
)
|
||||||
|
|
||||||
def _get_file_paths(self, directory: Union[str, Path]) -> dict[str, Path]:
|
def _get_file_paths(self, directory: Union[str, Path]) -> dict[str, Path]:
|
||||||
"""Get standardized file paths for model components."""
|
"""Get standardized file paths for model components."""
|
||||||
@@ -52,15 +52,16 @@ class BaseModelIO:
|
|||||||
self.config.load(str(paths["config"]))
|
self.config.load(str(paths["config"]))
|
||||||
self.tokenizer.load(str(paths["tokenizer"]))
|
self.tokenizer.load(str(paths["tokenizer"]))
|
||||||
|
|
||||||
|
if self.model is None:
|
||||||
|
self.model = Transformer(self.config)
|
||||||
|
|
||||||
if paths["model"].exists():
|
if paths["model"].exists():
|
||||||
state_dict = st.load_file(str(paths["model"]))
|
state_dict = st.load_file(str(paths["model"]))
|
||||||
if self.model is None:
|
|
||||||
self.model = Transformer(self.config)
|
|
||||||
self.model.load_state_dict(state_dict)
|
self.model.load_state_dict(state_dict)
|
||||||
|
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def to(self, *args, **kwargs) -> Self:
|
def to(self, *args, **kwargs) -> "BaseModelIO":
|
||||||
"""Move model to device."""
|
"""Move model to device."""
|
||||||
if self.model is not None:
|
if self.model is not None:
|
||||||
self.model.to(*args, **kwargs)
|
self.model.to(*args, **kwargs)
|
||||||
@@ -71,174 +72,9 @@ class BaseModelIO:
|
|||||||
class ModelParameter(BaseModelIO):
|
class ModelParameter(BaseModelIO):
|
||||||
"""Container for model parameters with serialization capabilities."""
|
"""Container for model parameters with serialization capabilities."""
|
||||||
|
|
||||||
model: Optional[nn.Module] = field(
|
|
||||||
default=None,
|
|
||||||
metadata={"help": "Transformer model."}
|
|
||||||
)
|
|
||||||
tokenizer: BpeTokenizer = field(
|
|
||||||
default_factory=BpeTokenizer,
|
|
||||||
metadata={"help": "Tokenizer for the model."}
|
|
||||||
)
|
|
||||||
config: ModelConfig = field(
|
|
||||||
default_factory=ModelConfig,
|
|
||||||
metadata={"help": "Transformer model configuration."}
|
|
||||||
)
|
|
||||||
|
|
||||||
def save(self, save_dir: Union[str, Path]):
|
def save(self, save_dir: Union[str, Path]):
|
||||||
self.save_components(save_dir)
|
self.save_components(save_dir)
|
||||||
|
|
||||||
def load(self, load_dir: Union[str, Path]) -> Self:
|
def load(self, load_dir: Union[str, Path]) -> "ModelParameter":
|
||||||
return self.load_components(load_dir)
|
return self.load_components(load_dir)
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class Checkpoint(BaseModelIO):
|
|
||||||
"""Extended model parameters with training state."""
|
|
||||||
|
|
||||||
model: Optional[nn.Module] = field(
|
|
||||||
default=None,
|
|
||||||
metadata={"help": "Transformer model."}
|
|
||||||
)
|
|
||||||
tokenizer: BpeTokenizer = field(
|
|
||||||
default_factory=BpeTokenizer,
|
|
||||||
metadata={"help": "Tokenizer for the model."}
|
|
||||||
)
|
|
||||||
config: ModelConfig = field(
|
|
||||||
default_factory=ModelConfig,
|
|
||||||
metadata={"help": "Transformer model configuration."}
|
|
||||||
)
|
|
||||||
optimizer_state: Dict[str, Any] = field(
|
|
||||||
default=None,
|
|
||||||
metadata={"help": "Optimizer state."}
|
|
||||||
)
|
|
||||||
scheduler_state: Dict[str, Any] = field(
|
|
||||||
default=None,
|
|
||||||
metadata={"help": "Sampler state."}
|
|
||||||
)
|
|
||||||
loss_list: List[float] = field(
|
|
||||||
default_factory=list,
|
|
||||||
metadata={"help": "List of training losses."}
|
|
||||||
)
|
|
||||||
epoch: int = field(
|
|
||||||
default=0,
|
|
||||||
metadata={"help": "Current epoch."}
|
|
||||||
)
|
|
||||||
batch_iter: int = field(
|
|
||||||
default=0,
|
|
||||||
metadata={"help": "Current iteration."}
|
|
||||||
)
|
|
||||||
|
|
||||||
def _get_training_paths(self, directory: Union[str, Path]) -> dict[str, Path]:
|
|
||||||
paths = self._get_file_paths(directory)
|
|
||||||
paths.update({
|
|
||||||
"loss_list": paths["model"].parent / "loss.pkl",
|
|
||||||
"loss_plot": paths["model"].parent / "loss.png",
|
|
||||||
"optimizer_state": paths["model"].parent / "optimizer_state.pkl",
|
|
||||||
"sampler_state": paths["model"].parent / "sampler_state.pkl"
|
|
||||||
})
|
|
||||||
return paths
|
|
||||||
|
|
||||||
def save_training_state(self, save_dir: Union[str, Path]):
|
|
||||||
paths = self._get_training_paths(save_dir)
|
|
||||||
|
|
||||||
# Save loss plot
|
|
||||||
self._plot_loss(str(paths["loss_plot"]))
|
|
||||||
|
|
||||||
# Save loss list
|
|
||||||
with open(str(paths["loss_list"]), "wb") as f:
|
|
||||||
pkl.dump(self.loss_list, f)
|
|
||||||
|
|
||||||
# Save optimizer state
|
|
||||||
with open(str(paths["optimizer_state"]), "wb") as f:
|
|
||||||
pkl.dump(self.optimizer_state, f)
|
|
||||||
|
|
||||||
# Save sampler state
|
|
||||||
with open(str(paths["sampler_state"]), "wb") as f:
|
|
||||||
pkl.dump(self.scheduler_state, f)
|
|
||||||
|
|
||||||
def load_training_state(self, load_dir: Union[str, Path]) -> Self:
|
|
||||||
paths = self._get_training_paths(load_dir)
|
|
||||||
|
|
||||||
# Load loss list
|
|
||||||
if paths["loss_list"].exists():
|
|
||||||
with open(str(paths["loss_list"]), "rb") as f:
|
|
||||||
self.loss_list = pkl.load(f)
|
|
||||||
|
|
||||||
# Load optimizer state
|
|
||||||
if paths["optimizer_state"].exists():
|
|
||||||
with open(str(paths["optimizer_state"]), "rb") as f:
|
|
||||||
self.optimizer_state = pkl.load(f)
|
|
||||||
|
|
||||||
# Load sampler state
|
|
||||||
if paths["sampler_state"].exists():
|
|
||||||
with open(str(paths["sampler_state"]), "rb") as f:
|
|
||||||
self.scheduler_state = pkl.load(f)
|
|
||||||
|
|
||||||
return self
|
|
||||||
|
|
||||||
def _plot_loss(self, save_path: str):
|
|
||||||
"""Plot and save loss curve."""
|
|
||||||
if not self.loss_list:
|
|
||||||
return
|
|
||||||
|
|
||||||
batch_iter = len(self.loss_list)
|
|
||||||
|
|
||||||
plt.figure(figsize=(10, 6))
|
|
||||||
plt.plot(self.loss_list)
|
|
||||||
plt.title(f"Training Loss - Iteration {batch_iter}")
|
|
||||||
plt.xlabel("Batch")
|
|
||||||
plt.ylabel("Loss")
|
|
||||||
plt.grid(True)
|
|
||||||
plt.savefig(save_path, dpi=300, bbox_inches="tight")
|
|
||||||
plt.close()
|
|
||||||
|
|
||||||
def save(self, save_dir: Union[str, Path]):
|
|
||||||
"""Save complete checkpoint."""
|
|
||||||
self.save_components(save_dir)
|
|
||||||
self.save_training_state(save_dir)
|
|
||||||
|
|
||||||
def load(self, load_dir: Union[str, Path]) -> Self:
|
|
||||||
"""Load complete checkpoint."""
|
|
||||||
self.load_components(load_dir)
|
|
||||||
self.load_training_state(load_dir)
|
|
||||||
return self
|
|
||||||
|
|
||||||
|
|
||||||
class ParameterLoader:
|
|
||||||
"""Factory class for loading model parameters or checkpoints."""
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def load(load_dir: Union[str, Path]) -> Union[ModelParameter, Checkpoint]:
|
|
||||||
"""Load either ModelParameter or Checkpoint based on directory contents."""
|
|
||||||
load_dir = Path(load_dir)
|
|
||||||
|
|
||||||
# Check for training-specific files
|
|
||||||
loss_file = load_dir / "loss.pkl"
|
|
||||||
has_training_data = loss_file.exists()
|
|
||||||
|
|
||||||
# Create appropriate instance
|
|
||||||
if has_training_data:
|
|
||||||
checkpoint = Checkpoint()
|
|
||||||
checkpoint.load(str(load_dir))
|
|
||||||
return checkpoint
|
|
||||||
else:
|
|
||||||
params = ModelParameter()
|
|
||||||
params.load(str(load_dir))
|
|
||||||
return params
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def create_checkpoint(
|
|
||||||
model: nn.Module,
|
|
||||||
tokenizer: BpeTokenizer,
|
|
||||||
config: ModelConfig,
|
|
||||||
loss_list: Optional[list[float]] = None,
|
|
||||||
optimizer: Optional[optim.Optimizer] = None,
|
|
||||||
) -> Checkpoint:
|
|
||||||
"""Convenience method to create a training checkpoint."""
|
|
||||||
return Checkpoint(
|
|
||||||
model=model,
|
|
||||||
tokenizer=tokenizer,
|
|
||||||
config=config,
|
|
||||||
loss_list=loss_list or [],
|
|
||||||
optimizer_state=optimizer
|
|
||||||
)
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
from typing import Any, Literal, Dict
|
from typing import Any, Dict
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
@@ -39,7 +39,10 @@ class CosineScheduleConfig(ScheduleConfig):
|
|||||||
default=None,
|
default=None,
|
||||||
metadata={"help": "Total training steps for cosine schedule."}
|
metadata={"help": "Total training steps for cosine schedule."}
|
||||||
)
|
)
|
||||||
schedule_type: Literal["cosine"] = "cosine"
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
self.schedule_type = "cosine"
|
||||||
|
self.validate()
|
||||||
|
|
||||||
def get_kwargs(self) -> Dict[str, Any]:
|
def get_kwargs(self) -> Dict[str, Any]:
|
||||||
if self.total_steps is None:
|
if self.total_steps is None:
|
||||||
@@ -68,7 +71,10 @@ class SGDRScheduleConfig(ScheduleConfig):
|
|||||||
default=2,
|
default=2,
|
||||||
metadata={"help": "Multiplier for cycle length growth."}
|
metadata={"help": "Multiplier for cycle length growth."}
|
||||||
)
|
)
|
||||||
schedule_type: Literal["sgdr"] = "sgdr"
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
self.schedule_type = "sgdr"
|
||||||
|
self.validate()
|
||||||
|
|
||||||
def get_kwargs(self) -> Dict[str, Any]:
|
def get_kwargs(self) -> Dict[str, Any]:
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
from dataclasses import dataclass, field
|
import torch.nn as nn
|
||||||
from typing import Optional, TYPE_CHECKING
|
|
||||||
from torch.utils.data import Dataset
|
from torch.utils.data import Dataset
|
||||||
from torch.optim import Optimizer
|
from torch.optim import Optimizer
|
||||||
|
from torch.optim.lr_scheduler import LRScheduler
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
from dataclasses import dataclass, field
|
||||||
from khaosz.trainer.strategy import BaseStrategy
|
from typing import Callable, List, Optional
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class TrainConfig:
|
class TrainConfig:
|
||||||
|
# basic setting
|
||||||
strategy: "BaseStrategy" = field(
|
model: nn.Module = field(
|
||||||
|
default=None,
|
||||||
|
metadata={"help": "Model for training."}
|
||||||
|
)
|
||||||
|
strategy: str = field(
|
||||||
default=None,
|
default=None,
|
||||||
metadata={"help": "Training strategy."}
|
metadata={"help": "Training strategy."}
|
||||||
)
|
)
|
||||||
@@ -18,13 +22,13 @@ class TrainConfig:
|
|||||||
default=None,
|
default=None,
|
||||||
metadata={"help": "Dataset for training."}
|
metadata={"help": "Dataset for training."}
|
||||||
)
|
)
|
||||||
optimizer: Optimizer = field(
|
optimizer_fn: Callable[[nn.Module], Optimizer] = field(
|
||||||
default=None,
|
default=None,
|
||||||
metadata={"help": "Optimizer for training."}
|
metadata={"help": "Optimizer factory for training."}
|
||||||
)
|
)
|
||||||
checkpoint_dir: str = field(
|
scheduler_fn: Callable[[Optimizer], LRScheduler] = field(
|
||||||
default="./checkpoint",
|
default=None,
|
||||||
metadata={"help": "Checkpoint directory."}
|
metadata={"help": "Scheduler factory for training."}
|
||||||
)
|
)
|
||||||
n_epoch: int = field(
|
n_epoch: int = field(
|
||||||
default=1,
|
default=1,
|
||||||
@@ -34,18 +38,6 @@ class TrainConfig:
|
|||||||
default=4,
|
default=4,
|
||||||
metadata={"help": "Batch size for training."}
|
metadata={"help": "Batch size for training."}
|
||||||
)
|
)
|
||||||
start_epoch: int = field(
|
|
||||||
default=0,
|
|
||||||
metadata={"help": "Start epoch for training."}
|
|
||||||
)
|
|
||||||
start_batch: int = field(
|
|
||||||
default=0,
|
|
||||||
metadata={"help": "Start batch iteration for training."}
|
|
||||||
)
|
|
||||||
checkpoint_interval: int = field(
|
|
||||||
default=5000,
|
|
||||||
metadata={"help": "Number of iterations between checkpoints."}
|
|
||||||
)
|
|
||||||
accumulation_steps: int = field(
|
accumulation_steps: int = field(
|
||||||
default=1,
|
default=1,
|
||||||
metadata={"help": "Number of iterations between steps."}
|
metadata={"help": "Number of iterations between steps."}
|
||||||
@@ -54,6 +46,26 @@ class TrainConfig:
|
|||||||
default=1.0,
|
default=1.0,
|
||||||
metadata={"help": "Maximum gradient norm."}
|
metadata={"help": "Maximum gradient norm."}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# checkpoint setting
|
||||||
|
start_epoch: int = field(
|
||||||
|
default=0,
|
||||||
|
metadata={"help": "Start epoch for training."}
|
||||||
|
)
|
||||||
|
start_batch: int = field(
|
||||||
|
default=0,
|
||||||
|
metadata={"help": "Start batch iteration for training."}
|
||||||
|
)
|
||||||
|
checkpoint_dir: str = field(
|
||||||
|
default="./checkpoint",
|
||||||
|
metadata={"help": "Checkpoint directory."}
|
||||||
|
)
|
||||||
|
checkpoint_interval: int = field(
|
||||||
|
default=5000,
|
||||||
|
metadata={"help": "Number of iterations between checkpoints."}
|
||||||
|
)
|
||||||
|
|
||||||
|
# dataloader setting
|
||||||
random_seed: int = field(
|
random_seed: int = field(
|
||||||
default=3407,
|
default=3407,
|
||||||
metadata={"help": "Random seed."}
|
metadata={"help": "Random seed."}
|
||||||
@@ -69,4 +81,56 @@ class TrainConfig:
|
|||||||
pin_memory: bool = field(
|
pin_memory: bool = field(
|
||||||
default=False,
|
default=False,
|
||||||
metadata={"help": "Pin memory for dataloader."}
|
metadata={"help": "Pin memory for dataloader."}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# distributed training
|
||||||
|
nprocs: int = field(
|
||||||
|
default=1,
|
||||||
|
metadata={"help": "Number of processes for distributed training."}
|
||||||
|
)
|
||||||
|
backend: str = field(
|
||||||
|
default="nccl",
|
||||||
|
metadata={"help": "Distributed training backend."}
|
||||||
|
)
|
||||||
|
master_addr: str = field(
|
||||||
|
default="localhost",
|
||||||
|
metadata={"help": "Master address for distributed training."}
|
||||||
|
)
|
||||||
|
master_port: str = field(
|
||||||
|
default="29500",
|
||||||
|
metadata={"help": "Master port for distributed training."}
|
||||||
|
)
|
||||||
|
parallel_wrapper: Optional[Callable] = field(
|
||||||
|
default=None,
|
||||||
|
metadata={"help": "Parallel function for training."}
|
||||||
|
)
|
||||||
|
state_dict_fn: Optional[Callable] = field(
|
||||||
|
default=None,
|
||||||
|
metadata={"help": "Parallel function for state dict saving."}
|
||||||
|
)
|
||||||
|
|
||||||
|
# others
|
||||||
|
device_ids: Optional[List[int]] = field(
|
||||||
|
default=None,
|
||||||
|
metadata={"help": "Device ids for distributed training."}
|
||||||
|
)
|
||||||
|
device_type: str = field(
|
||||||
|
default="cuda",
|
||||||
|
metadata={"help": "Device type for distributed training."}
|
||||||
|
)
|
||||||
|
extra_kwargs: dict = field(
|
||||||
|
default_factory=dict,
|
||||||
|
metadata={"help": "Other arguments."}
|
||||||
|
)
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
self.validate()
|
||||||
|
|
||||||
|
def validate(self):
|
||||||
|
required_fields = ["model", "strategy", "dataset", "optimizer_fn", "scheduler_fn"]
|
||||||
|
|
||||||
|
for field_name in required_fields:
|
||||||
|
if getattr(self, field_name) is None:
|
||||||
|
raise ValueError(f"{field_name} is required.")
|
||||||
|
|
||||||
|
|
||||||
@@ -1,16 +1,15 @@
|
|||||||
from khaosz.data.data_util import (
|
from khaosz.data.dataset import (
|
||||||
BaseDataset,
|
BaseDataset,
|
||||||
SeqDataset,
|
SeqDataset,
|
||||||
DpoDataset,
|
DpoDataset,
|
||||||
SftDataset,
|
SftDataset,
|
||||||
PpoDataset,
|
PpoDataset,
|
||||||
MutiSegmentFetcher,
|
MultiSegmentFetcher,
|
||||||
ResumeableRandomSampler,
|
DatasetLoader
|
||||||
DatasetLoader,
|
|
||||||
load_pkl_files,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
from khaosz.data.tokenizer import BpeTokenizer
|
from khaosz.data.tokenizer import BpeTokenizer
|
||||||
|
from khaosz.data.sampler import ResumableDistributedSampler
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"BaseDataset",
|
"BaseDataset",
|
||||||
@@ -18,9 +17,8 @@ __all__ = [
|
|||||||
"DpoDataset",
|
"DpoDataset",
|
||||||
"SftDataset",
|
"SftDataset",
|
||||||
"PpoDataset",
|
"PpoDataset",
|
||||||
"MutiSegmentFetcher",
|
"MultiSegmentFetcher",
|
||||||
"ResumeableRandomSampler",
|
|
||||||
"DatasetLoader",
|
"DatasetLoader",
|
||||||
"load_pkl_files",
|
"BpeTokenizer",
|
||||||
"BpeTokenizer"
|
"ResumableDistributedSampler"
|
||||||
]
|
]
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import json
|
||||||
|
import torch
|
||||||
|
import torch.distributed as dist
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Dict, Any
|
||||||
|
from khaosz.parallel.setup import get_rank
|
||||||
|
|
||||||
|
|
||||||
|
class Checkpoint:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
state_dict: Dict[str, Any],
|
||||||
|
epoch: int = 0,
|
||||||
|
iteration: int = 0,
|
||||||
|
):
|
||||||
|
self.state_dict = state_dict
|
||||||
|
self.epoch = epoch
|
||||||
|
self.iteration = iteration
|
||||||
|
|
||||||
|
def save(
|
||||||
|
self,
|
||||||
|
save_dir: str,
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
save_path = Path(save_dir)
|
||||||
|
save_path.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
rank = get_rank()
|
||||||
|
if rank == 0:
|
||||||
|
meta = {
|
||||||
|
"epoch": self.epoch,
|
||||||
|
"iteration": self.iteration,
|
||||||
|
}
|
||||||
|
with open(save_path / "meta.json", "w") as f:
|
||||||
|
json.dump(meta, f, indent=2)
|
||||||
|
|
||||||
|
with open(save_path / f"state_dict.pt", "wb") as f:
|
||||||
|
torch.save(self.state_dict, f)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load(
|
||||||
|
cls,
|
||||||
|
save_dir: str,
|
||||||
|
) -> "Checkpoint":
|
||||||
|
|
||||||
|
rank = get_rank()
|
||||||
|
save_path = Path(save_dir)
|
||||||
|
|
||||||
|
meta = {}
|
||||||
|
if rank == 0:
|
||||||
|
with open(Path(save_dir) / "meta.json", "r") as f:
|
||||||
|
meta = json.load(f)
|
||||||
|
|
||||||
|
if dist.is_initialized():
|
||||||
|
meta_list = [meta]
|
||||||
|
dist.broadcast_object_list(meta_list, src=0)
|
||||||
|
meta = meta_list[0]
|
||||||
|
|
||||||
|
with open(save_path / f"state_dict.pt", "rb") as f:
|
||||||
|
state_dict = torch.load(f)
|
||||||
|
|
||||||
|
return cls(
|
||||||
|
state_dict=state_dict,
|
||||||
|
epoch=meta["epoch"],
|
||||||
|
iteration=meta["iteration"],
|
||||||
|
)
|
||||||
@@ -1,40 +1,28 @@
|
|||||||
import torch
|
import torch
|
||||||
import bisect
|
import bisect
|
||||||
import pickle as pkl
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from torch import Tensor
|
from torch import Tensor
|
||||||
from torch.utils.data import Dataset, Sampler
|
from torch.utils.data import Dataset
|
||||||
|
from khaosz.data.file import load_h5
|
||||||
from typing import Callable, List, Dict, Literal, Optional, Union
|
from typing import Callable, List, Dict, Literal, Optional, Union
|
||||||
|
|
||||||
MutiSeg = Dict[str, List[Tensor]]
|
|
||||||
Seg = Dict[str, Tensor]
|
|
||||||
|
|
||||||
def load_pkl_files(paths: List[str]):
|
|
||||||
segments: MutiSeg = {}
|
|
||||||
total_samples = 0
|
|
||||||
|
|
||||||
for path in paths:
|
|
||||||
with open(path, "rb") as f:
|
|
||||||
pkl_file: Seg = pkl.load(f)
|
|
||||||
for key, value in pkl_file.items():
|
|
||||||
if key not in segments:
|
|
||||||
segments[key] = []
|
|
||||||
segments[key].append(value)
|
|
||||||
first_key = list(pkl_file.keys())[0]
|
|
||||||
total_samples += pkl_file[first_key].numel()
|
|
||||||
|
|
||||||
return segments, total_samples
|
|
||||||
|
|
||||||
|
|
||||||
class BaseSegmentFetcher:
|
class BaseSegmentFetcher:
|
||||||
def __init__(self, segments: List[Tensor]):
|
def __init__(self, segments: List[Tensor]):
|
||||||
self.segments = segments
|
self.segments = segments
|
||||||
self.cum_lengths = []
|
self.cum_lengths = []
|
||||||
|
|
||||||
total = 0
|
total = 0
|
||||||
for seg in segments:
|
for seg in segments:
|
||||||
total += len(seg)
|
total += torch.numel(seg)
|
||||||
self.cum_lengths.append(total)
|
self.cum_lengths.append(total)
|
||||||
self.total_length = total if segments else 0
|
|
||||||
|
self.total_length = total
|
||||||
|
|
||||||
|
def __len__(self) -> int:
|
||||||
|
return self.total_length
|
||||||
|
|
||||||
def fetch_data(self, begin_idx: int, end_idx: int) -> Tensor:
|
def fetch_data(self, begin_idx: int, end_idx: int) -> Tensor:
|
||||||
if not (0 <= begin_idx < self.total_length and 0 <= end_idx <= self.total_length):
|
if not (0 <= begin_idx < self.total_length and 0 <= end_idx <= self.total_length):
|
||||||
@@ -52,20 +40,25 @@ class BaseSegmentFetcher:
|
|||||||
prev_cum = self.cum_lengths[i - 1] if i > 0 else 0
|
prev_cum = self.cum_lengths[i - 1] if i > 0 else 0
|
||||||
start = max(begin_idx - prev_cum, 0)
|
start = max(begin_idx - prev_cum, 0)
|
||||||
end = min(end_idx - prev_cum, len(self.segments[i]))
|
end = min(end_idx - prev_cum, len(self.segments[i]))
|
||||||
result_segments.append(self.segments[i][start:end])
|
data = self.segments[i][start:end]
|
||||||
|
result_segments.append(data)
|
||||||
|
|
||||||
return torch.cat(result_segments, dim=0)
|
return torch.cat(result_segments, dim=0)
|
||||||
|
|
||||||
|
|
||||||
class MutiSegmentFetcher:
|
class MultiSegmentFetcher:
|
||||||
def __init__(self, muti_segments: MutiSeg):
|
def __init__(self, muti_segments: Dict):
|
||||||
self.muti_keys = list(muti_segments.keys())
|
self.muti_keys = list(muti_segments.keys())
|
||||||
self.muti_fetchers = {
|
self.muti_fetchers = {
|
||||||
key: BaseSegmentFetcher(segments)
|
key: BaseSegmentFetcher(segments)
|
||||||
for key, segments in muti_segments.items()
|
for key, segments in muti_segments.items()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def __len__(self) -> int:
|
||||||
|
len_list = [len(seg) for seg in self.muti_fetchers.values()]
|
||||||
|
return min(len_list)
|
||||||
|
|
||||||
def key_fetch(self, begin_idx: int, end_idx: int, keys: Union[str, List[str]]) -> Union[Tensor, Seg]:
|
def key_fetch(self, begin_idx: int, end_idx: int, keys: Union[str, List[str]]) -> Dict:
|
||||||
fetch_dict = {}
|
fetch_dict = {}
|
||||||
keys = [keys] if isinstance(keys, str) else keys
|
keys = [keys] if isinstance(keys, str) else keys
|
||||||
|
|
||||||
@@ -76,38 +69,28 @@ class MutiSegmentFetcher:
|
|||||||
|
|
||||||
return fetch_dict if len(keys) > 1 else fetch_dict[keys[0]]
|
return fetch_dict if len(keys) > 1 else fetch_dict[keys[0]]
|
||||||
|
|
||||||
def fetch_data(self, begin_idx: int, end_idx: int) -> Union[Tensor, Seg]:
|
def fetch_data(self, begin_idx: int, end_idx: int) -> Dict:
|
||||||
return self.key_fetch(begin_idx, end_idx, self.muti_keys)
|
return self.key_fetch(begin_idx, end_idx, self.muti_keys)
|
||||||
|
|
||||||
|
|
||||||
class BaseDataset(Dataset, ABC):
|
class BaseDataset(Dataset, ABC):
|
||||||
def __init__(self, window_size: int, stride: int):
|
def __init__(self, window_size: int, stride: int):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.segments: MutiSeg = {}
|
self.segments = {}
|
||||||
self.window_size = window_size
|
self.window_size = window_size
|
||||||
self.stride = stride
|
self.stride = stride
|
||||||
self.total_samples = None
|
self.total_samples = None
|
||||||
|
|
||||||
def save(self, save_path: str):
|
def load(self, load_path: str):
|
||||||
keys = list(self.segments.keys())
|
self.segments = load_h5(load_path)
|
||||||
if not keys:
|
self.fetcher = MultiSegmentFetcher(self.segments)
|
||||||
return
|
self.total_samples = len(self.fetcher)
|
||||||
|
|
||||||
first_item = self.segments[keys[0]]
|
|
||||||
segment_size = len(first_item)
|
|
||||||
|
|
||||||
for i in range(segment_size):
|
|
||||||
formated_segment = {key: self.segments[key][i] for key in keys}
|
|
||||||
pkl.dump(formated_segment, open(f"{save_path}_{i}.pkl", "wb"))
|
|
||||||
|
|
||||||
def load(self, load_path: Union[str, List[str]]):
|
|
||||||
paths = [load_path] if isinstance(load_path, str) else load_path
|
|
||||||
self.segments, self.total_samples = load_pkl_files(paths)
|
|
||||||
self.fetcher = MutiSegmentFetcher(self.segments)
|
|
||||||
|
|
||||||
def get_index(self, index: int) -> int:
|
def get_index(self, index: int) -> int:
|
||||||
begin_idx = min(index * self.stride, self.total_samples - self.window_size - 1)
|
assert self.total_samples > self.window_size
|
||||||
end_idx = begin_idx + self.window_size
|
|
||||||
|
begin_idx = min(index * self.stride, self.total_samples - 1 - self.window_size)
|
||||||
|
end_idx = min(begin_idx + self.window_size, self.total_samples - 1)
|
||||||
|
|
||||||
return begin_idx, end_idx
|
return begin_idx, end_idx
|
||||||
|
|
||||||
@@ -119,13 +102,13 @@ class BaseDataset(Dataset, ABC):
|
|||||||
assert self.total_samples is not None
|
assert self.total_samples is not None
|
||||||
if self.total_samples <= self.window_size:
|
if self.total_samples <= self.window_size:
|
||||||
return 0
|
return 0
|
||||||
return self.total_samples // self.stride + 1
|
return (self.total_samples - 1 - self.window_size) // self.stride + 1
|
||||||
|
|
||||||
|
|
||||||
class SeqDataset(BaseDataset):
|
class SeqDataset(BaseDataset):
|
||||||
def __init__(self, window_size: int, stride: int):
|
def __init__(self, window_size: int, stride: int):
|
||||||
super().__init__(window_size, stride)
|
super().__init__(window_size, stride)
|
||||||
self.fetcher = MutiSegmentFetcher(self.segments)
|
self.fetcher = MultiSegmentFetcher(self.segments)
|
||||||
|
|
||||||
def _fetch_data(self, begin_idx: int, end_idx: int) -> Tensor:
|
def _fetch_data(self, begin_idx: int, end_idx: int) -> Tensor:
|
||||||
return self.fetcher.key_fetch(begin_idx, end_idx, "sequence")
|
return self.fetcher.key_fetch(begin_idx, end_idx, "sequence")
|
||||||
@@ -143,7 +126,7 @@ class SeqDataset(BaseDataset):
|
|||||||
class SftDataset(BaseDataset):
|
class SftDataset(BaseDataset):
|
||||||
def __init__(self, window_size: int, stride: int):
|
def __init__(self, window_size: int, stride: int):
|
||||||
super().__init__(window_size, stride)
|
super().__init__(window_size, stride)
|
||||||
self.fetcher = MutiSegmentFetcher(self.segments)
|
self.fetcher = MultiSegmentFetcher(self.segments)
|
||||||
|
|
||||||
def _fetch_data(self, begin_idx: int, end_idx: int, key: str) -> Tensor:
|
def _fetch_data(self, begin_idx: int, end_idx: int, key: str) -> Tensor:
|
||||||
return self.fetcher.key_fetch(begin_idx, end_idx, key)
|
return self.fetcher.key_fetch(begin_idx, end_idx, key)
|
||||||
@@ -161,7 +144,7 @@ class SftDataset(BaseDataset):
|
|||||||
class DpoDataset(BaseDataset):
|
class DpoDataset(BaseDataset):
|
||||||
def __init__(self, window_size: int, stride: int):
|
def __init__(self, window_size: int, stride: int):
|
||||||
super().__init__(window_size, stride)
|
super().__init__(window_size, stride)
|
||||||
self.fetcher = MutiSegmentFetcher(self.segments)
|
self.fetcher = MultiSegmentFetcher(self.segments)
|
||||||
|
|
||||||
def _fetch_data(self, begin_idx: int, end_idx: int, key: str) -> Tensor:
|
def _fetch_data(self, begin_idx: int, end_idx: int, key: str) -> Tensor:
|
||||||
return self.fetcher.key_fetch(begin_idx, end_idx, key)
|
return self.fetcher.key_fetch(begin_idx, end_idx, key)
|
||||||
@@ -180,7 +163,7 @@ class DpoDataset(BaseDataset):
|
|||||||
class PpoDataset(BaseDataset):
|
class PpoDataset(BaseDataset):
|
||||||
def __init__(self, window_size: int, stride: int):
|
def __init__(self, window_size: int, stride: int):
|
||||||
super().__init__(window_size, stride)
|
super().__init__(window_size, stride)
|
||||||
self.fetcher = MutiSegmentFetcher(self.segments)
|
self.fetcher = MultiSegmentFetcher(self.segments)
|
||||||
|
|
||||||
def _fetch_data(self, begin_idx: int, end_idx: int, key: str) -> Tensor:
|
def _fetch_data(self, begin_idx: int, end_idx: int, key: str) -> Tensor:
|
||||||
return self.fetcher.key_fetch(begin_idx, end_idx, key)
|
return self.fetcher.key_fetch(begin_idx, end_idx, key)
|
||||||
@@ -200,10 +183,9 @@ class DatasetLoader:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def load(
|
def load(
|
||||||
train_type: Literal["seq", "sft", "dpo"],
|
train_type: Literal["seq", "sft", "dpo"],
|
||||||
load_path: Union[str, List[str]],
|
load_path: str,
|
||||||
window_size: int,
|
window_size: int,
|
||||||
stride: Optional[int] = None,
|
stride: Optional[int] = None,
|
||||||
**kwargs
|
|
||||||
) -> BaseDataset:
|
) -> BaseDataset:
|
||||||
if stride is None:
|
if stride is None:
|
||||||
stride = window_size
|
stride = window_size
|
||||||
@@ -217,40 +199,3 @@ class DatasetLoader:
|
|||||||
dataset.load(load_path)
|
dataset.load(load_path)
|
||||||
|
|
||||||
return dataset
|
return dataset
|
||||||
|
|
||||||
|
|
||||||
class ResumeableRandomSampler(Sampler[int]):
|
|
||||||
def __init__(self, data_source, start_epoch=0, start_iter=0, seed=42):
|
|
||||||
self.num_samples = len(data_source)
|
|
||||||
self.epoch = start_epoch
|
|
||||||
self.iter = start_iter
|
|
||||||
|
|
||||||
generator = torch.Generator()
|
|
||||||
generator.manual_seed(seed)
|
|
||||||
|
|
||||||
# consume previous epochs
|
|
||||||
for _ in range(start_epoch):
|
|
||||||
torch.randperm(self.num_samples, generator=generator)
|
|
||||||
|
|
||||||
self.generator = generator
|
|
||||||
self._indices = None
|
|
||||||
|
|
||||||
def _get_indices(self):
|
|
||||||
current_epoch_indices = torch.randperm(self.num_samples, generator=self.generator).tolist()
|
|
||||||
self._indices = current_epoch_indices[self.iter % self.num_samples:]
|
|
||||||
|
|
||||||
def __iter__(self):
|
|
||||||
if self._indices is None:
|
|
||||||
self._get_indices()
|
|
||||||
|
|
||||||
for i in self._indices:
|
|
||||||
self.iter += 1
|
|
||||||
yield i
|
|
||||||
|
|
||||||
self.epoch += 1
|
|
||||||
self._indices = None
|
|
||||||
|
|
||||||
def __len__(self):
|
|
||||||
if self._indices is None:
|
|
||||||
self._get_indices()
|
|
||||||
return len(self._indices)
|
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import os
|
||||||
|
import h5py
|
||||||
|
import torch
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from torch import Tensor
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
|
||||||
|
def save_h5(file_path: str, file_name: str, tensor_group: Dict[str, List[Tensor]]):
|
||||||
|
os.makedirs(file_path, exist_ok=True)
|
||||||
|
full_file_path = os.path.join(file_path, f"{file_name}.h5")
|
||||||
|
with h5py.File(full_file_path, 'w') as f:
|
||||||
|
for key, tensors in tensor_group.items():
|
||||||
|
grp = f.create_group(key)
|
||||||
|
for idx, tensor in enumerate(tensors):
|
||||||
|
arr = tensor.cpu().numpy()
|
||||||
|
grp.create_dataset(f'data_{idx}', data=arr)
|
||||||
|
|
||||||
|
def load_h5(file_path: str, share_memory=True) -> Dict[str, List[Tensor]]:
|
||||||
|
tensor_group: Dict[str, List[Tensor]] = {}
|
||||||
|
|
||||||
|
root_path = Path(file_path)
|
||||||
|
h5_files = list(root_path.rglob("*.h5")) + list(root_path.rglob("*.hdf5"))
|
||||||
|
|
||||||
|
for h5_file in h5_files:
|
||||||
|
with h5py.File(h5_file, 'r') as f:
|
||||||
|
for key in f.keys():
|
||||||
|
grp = f[key]
|
||||||
|
dsets = []
|
||||||
|
for dset_name in grp.keys():
|
||||||
|
dset = grp[dset_name]
|
||||||
|
tensor = torch.from_numpy(dset[:])
|
||||||
|
if share_memory:
|
||||||
|
tensor = tensor.share_memory_()
|
||||||
|
dsets.append(tensor)
|
||||||
|
|
||||||
|
if tensor_group.get(key) is None:
|
||||||
|
tensor_group[key] = []
|
||||||
|
tensor_group[key].extend(dsets)
|
||||||
|
|
||||||
|
return tensor_group
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import torch
|
||||||
|
import torch.distributed as dist
|
||||||
|
|
||||||
|
from torch.utils.data import Dataset, Sampler
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class ResumableDistributedSampler(Sampler[int]):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
data_source: Dataset,
|
||||||
|
start_epoch: int=0,
|
||||||
|
start_iter: int=0,
|
||||||
|
seed: int=42,
|
||||||
|
drop_last: bool=False,
|
||||||
|
shuffle: bool=True,
|
||||||
|
process_group: Optional[dist.ProcessGroup]=None,
|
||||||
|
):
|
||||||
|
self.epoch = start_epoch
|
||||||
|
self.iter = start_iter
|
||||||
|
self.seed = seed
|
||||||
|
self.num_samples = len(data_source)
|
||||||
|
|
||||||
|
if process_group is not None:
|
||||||
|
# input process group
|
||||||
|
self.rank = dist.get_rank(process_group)
|
||||||
|
self.num_replicas = dist.get_world_size(process_group)
|
||||||
|
|
||||||
|
elif dist.is_available() and dist.is_initialized():
|
||||||
|
# use default process group
|
||||||
|
process_group = dist.group.WORLD
|
||||||
|
self.rank = dist.get_rank()
|
||||||
|
self.num_replicas = dist.get_world_size()
|
||||||
|
|
||||||
|
else:
|
||||||
|
# single process
|
||||||
|
self.rank = 0
|
||||||
|
self.num_replicas = 1
|
||||||
|
|
||||||
|
self.drop_last = drop_last
|
||||||
|
self.shuffle = shuffle
|
||||||
|
|
||||||
|
offset = 0 if drop_last else self.num_replicas - 1
|
||||||
|
self.num_samples_per_replica = (self.num_samples + offset) // self.num_replicas
|
||||||
|
self.total_size = self.num_samples_per_replica * self.num_replicas
|
||||||
|
|
||||||
|
self._indices = None
|
||||||
|
|
||||||
|
def _get_indices(self):
|
||||||
|
if self.shuffle:
|
||||||
|
generator = torch.Generator()
|
||||||
|
generator.manual_seed(self.seed + self.epoch)
|
||||||
|
indices = torch.randperm(self.num_samples, generator=generator).tolist()
|
||||||
|
else:
|
||||||
|
indices = torch.arange(self.num_samples).tolist()
|
||||||
|
|
||||||
|
if not self.drop_last and self.num_samples < self.total_size:
|
||||||
|
padding_size = self.total_size - len(indices)
|
||||||
|
indices += indices[:padding_size]
|
||||||
|
|
||||||
|
local_indices = indices[self.rank:self.total_size:self.num_replicas]
|
||||||
|
|
||||||
|
self.iter = self.iter % self.num_samples_per_replica
|
||||||
|
self._indices = local_indices[self.iter:]
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
if self._indices is None:
|
||||||
|
self._get_indices()
|
||||||
|
|
||||||
|
for i in self._indices:
|
||||||
|
self.iter += 1
|
||||||
|
yield i
|
||||||
|
|
||||||
|
self.epoch += 1
|
||||||
|
self._indices = None
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return self.num_samples_per_replica
|
||||||
+17
-21
@@ -9,32 +9,28 @@ class BpeTokenizer:
|
|||||||
def __init__(self, path=None):
|
def __init__(self, path=None):
|
||||||
self._control_tokens = ["<bos>", "<eos>", "<pad>"]
|
self._control_tokens = ["<bos>", "<eos>", "<pad>"]
|
||||||
self._special_tokens = ["<|im_start|>", "<|im_end|>"]
|
self._special_tokens = ["<|im_start|>", "<|im_end|>"]
|
||||||
|
|
||||||
model = BPE()
|
model = BPE()
|
||||||
tokenizer = Tokenizer(model)
|
self._tokenizer = Tokenizer(model)
|
||||||
tokenizer.normalizer = normalizers.Sequence([
|
self._tokenizer.normalizer = normalizers.Sequence([
|
||||||
normalizers.NFC()
|
normalizers.NFC(),
|
||||||
|
normalizers.Strip()
|
||||||
])
|
])
|
||||||
tokenizer.pre_tokenizer = pre_tokenizers.Sequence([
|
|
||||||
pre_tokenizers.Punctuation(behavior="isolated"),
|
self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence([
|
||||||
pre_tokenizers.Metaspace(prepend_scheme="never"),
|
pre_tokenizers.UnicodeScripts(),
|
||||||
pre_tokenizers.Split(pattern=r"(\d+|[a-zA-Z]+|(?:'s|'t|'re|'ve|'m|'ll|'d))", behavior="isolated"),
|
pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=True)
|
||||||
pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=False)
|
|
||||||
])
|
])
|
||||||
tokenizer.decoder = decoders.Sequence([
|
|
||||||
decoders.ByteLevel(),
|
self._tokenizer.decoder = decoders.ByteLevel()
|
||||||
decoders.Metaspace(prepend_scheme="never")
|
self._tokenizer.post_processor = processors.ByteLevel(trim_offsets=True)
|
||||||
])
|
|
||||||
tokenizer.post_processor = processors.Sequence([
|
|
||||||
processors.ByteLevel(trim_offsets=False)
|
|
||||||
])
|
|
||||||
self._tokenizer = tokenizer
|
|
||||||
|
|
||||||
if path is not None:
|
if path is not None:
|
||||||
self._tokenizer = Tokenizer.from_file(path)
|
self._tokenizer = Tokenizer.from_file(path)
|
||||||
|
|
||||||
def _prepare_trainer(self, vocab_size: int, min_freq: int, reserved_token_size: int) -> tuple:
|
def _prepare_trainer(self, vocab_size: int, min_freq: int, reserved_token_size: int, max_token_length=18) -> tuple:
|
||||||
assert reserved_token_size > len(self._special_tokens)
|
assert reserved_token_size > len(self._special_tokens)
|
||||||
reserved_tokens = [f"<|rsv{i:02d}|>" for i in range(reserved_token_size - len(self._special_tokens))]
|
reserved_tokens = [f"<|reserve{i:02d}|>" for i in range(reserved_token_size - len(self._special_tokens))]
|
||||||
detail_vocab_size = vocab_size - (len(reserved_tokens) + len(self._special_tokens))
|
detail_vocab_size = vocab_size - (len(reserved_tokens) + len(self._special_tokens))
|
||||||
|
|
||||||
alphabet = pre_tokenizers.ByteLevel.alphabet()
|
alphabet = pre_tokenizers.ByteLevel.alphabet()
|
||||||
@@ -44,11 +40,11 @@ class BpeTokenizer:
|
|||||||
trainer = BpeTrainer(
|
trainer = BpeTrainer(
|
||||||
vocab_size=detail_vocab_size,
|
vocab_size=detail_vocab_size,
|
||||||
min_frequency=min_freq,
|
min_frequency=min_freq,
|
||||||
limit_alphabet=detail_vocab_size // 4,
|
limit_alphabet=detail_vocab_size // 6,
|
||||||
max_token_length=18,
|
max_token_length=max_token_length,
|
||||||
special_tokens=self._control_tokens,
|
special_tokens=self._control_tokens,
|
||||||
show_progress=True,
|
|
||||||
initial_alphabet=alphabet,
|
initial_alphabet=alphabet,
|
||||||
|
show_progress=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
return trainer, detail_vocab_size, reserved_tokens
|
return trainer, detail_vocab_size, reserved_tokens
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
# init file
|
||||||
@@ -100,7 +100,7 @@ class GeneratorCore:
|
|||||||
) -> List[int]:
|
) -> List[int]:
|
||||||
cur_cache_pos = start_pos
|
cur_cache_pos = start_pos
|
||||||
|
|
||||||
for _ in range(len(ids), self.config.m_len):
|
for _ in range(len(ids), self.config.max_len):
|
||||||
next_token_id, cache_increase = self.generate_iterator(
|
next_token_id, cache_increase = self.generate_iterator(
|
||||||
input_ids, temperature, top_k, top_p, attn_mask, kv_caches, cur_cache_pos)
|
input_ids, temperature, top_k, top_p, attn_mask, kv_caches, cur_cache_pos)
|
||||||
|
|
||||||
@@ -127,7 +127,7 @@ class EmbeddingEncoderCore:
|
|||||||
with_batch = isinstance(sentence, list)
|
with_batch = isinstance(sentence, list)
|
||||||
ids = self.tokenizer.encode(sentence)
|
ids = self.tokenizer.encode(sentence)
|
||||||
batch_ids = ids if with_batch else [ids]
|
batch_ids = ids if with_batch else [ids]
|
||||||
max_model_len = self.config.m_len
|
max_model_len = self.config.max_len
|
||||||
|
|
||||||
all_fragments = []
|
all_fragments = []
|
||||||
fragment_origin_idx = []
|
fragment_origin_idx = []
|
||||||
@@ -195,10 +195,10 @@ class KVCacheManager:
|
|||||||
self.batch_size = batch_size
|
self.batch_size = batch_size
|
||||||
self.device = device
|
self.device = device
|
||||||
self.dtype = dtype
|
self.dtype = dtype
|
||||||
self.num_layers = config.n_layer
|
self.num_layers = config.n_layers
|
||||||
self.max_len = config.m_len
|
self.max_len = config.max_len
|
||||||
self.num_heads = config.n_kvhead
|
self.num_heads = config.n_kv_heads
|
||||||
self.head_dim = config.n_dim //config.n_head
|
self.head_dim = config.dim //config.n_heads
|
||||||
|
|
||||||
self._kv_cache: Tuple[Tensor, Tensor] = None
|
self._kv_cache: Tuple[Tensor, Tensor] = None
|
||||||
self._seq_mask: Tensor = None
|
self._seq_mask: Tensor = None
|
||||||
@@ -206,11 +206,11 @@ class KVCacheManager:
|
|||||||
|
|
||||||
def _initialize(self):
|
def _initialize(self):
|
||||||
k_cache = torch.zeros(
|
k_cache = torch.zeros(
|
||||||
(self.batch_size, self.num_layers, self.max_len, self.num_heads, self.head_dim),
|
(self.batch_size, self.max_len, self.num_layers, self.num_heads, self.head_dim),
|
||||||
device=self.device, dtype=self.dtype
|
device=self.device, dtype=self.dtype
|
||||||
)
|
)
|
||||||
v_cache = torch.zeros(
|
v_cache = torch.zeros(
|
||||||
(self.batch_size, self.num_layers, self.max_len, self.num_heads, self.head_dim),
|
(self.batch_size, self.max_len, self.num_layers, self.num_heads, self.head_dim),
|
||||||
device=self.device, dtype=self.dtype
|
device=self.device, dtype=self.dtype
|
||||||
)
|
)
|
||||||
self._kv_cache = (k_cache, v_cache)
|
self._kv_cache = (k_cache, v_cache)
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import torch
|
||||||
|
from torch import Tensor
|
||||||
|
from functools import wraps
|
||||||
|
from inspect import signature
|
||||||
|
|
||||||
|
|
||||||
|
class CudaGraphWrapper:
|
||||||
|
def __init__(self, function, device="cuda", cast=False):
|
||||||
|
self.function = function
|
||||||
|
self.cast = cast
|
||||||
|
self.device = device
|
||||||
|
self.static_input = None
|
||||||
|
self.static_output = None
|
||||||
|
self.graph = None
|
||||||
|
self.signature = signature(function)
|
||||||
|
|
||||||
|
def _update_inplace(self, lhs, rhs):
|
||||||
|
if isinstance(lhs, Tensor) and isinstance(rhs, Tensor):
|
||||||
|
if lhs.shape != rhs.shape:
|
||||||
|
raise ValueError(
|
||||||
|
f"Tensor shape mismatch! "
|
||||||
|
f"Expected: {lhs.shape}, Got: {rhs.shape}. "
|
||||||
|
f"Function: {self.function}"
|
||||||
|
)
|
||||||
|
if self.cast:
|
||||||
|
if lhs.device != rhs.device:
|
||||||
|
rhs = rhs.to(device=lhs.device)
|
||||||
|
|
||||||
|
if lhs.dtype != rhs.dtype:
|
||||||
|
rhs = rhs.to(dtype=lhs.dtype)
|
||||||
|
else:
|
||||||
|
if lhs.device != rhs.device:
|
||||||
|
raise ValueError(
|
||||||
|
f"Tensor device mismatch! "
|
||||||
|
f"Expected: {lhs.device}, Got: {rhs.device}. "
|
||||||
|
f"Function: {self.function}"
|
||||||
|
)
|
||||||
|
if lhs.dtype != rhs.dtype:
|
||||||
|
raise ValueError(
|
||||||
|
f"Tensor dtype mismatch! "
|
||||||
|
f"Expected: {lhs.dtype}, Got: {rhs.dtype}. "
|
||||||
|
f"Function: {self.function}"
|
||||||
|
)
|
||||||
|
lhs.copy_(rhs)
|
||||||
|
elif isinstance(lhs, dict):
|
||||||
|
for k in lhs:
|
||||||
|
if k in rhs:
|
||||||
|
self._update_inplace(lhs[k], rhs[k])
|
||||||
|
elif isinstance(lhs, (list, tuple)):
|
||||||
|
for i in range(len(lhs)):
|
||||||
|
if i < len(rhs):
|
||||||
|
self._update_inplace(lhs[i], rhs[i])
|
||||||
|
elif isinstance(lhs, (int, float, bool, str, type(None))):
|
||||||
|
if lhs != rhs:
|
||||||
|
raise ValueError("Does not support changing control parameters.")
|
||||||
|
|
||||||
|
def _update_args(self, input_args, input_kwargs):
|
||||||
|
bound_args = self.signature.bind(*input_args, **input_kwargs)
|
||||||
|
bound_args.apply_defaults()
|
||||||
|
args_dict = bound_args.arguments
|
||||||
|
|
||||||
|
if self.static_input is None:
|
||||||
|
self.static_input = args_dict
|
||||||
|
else:
|
||||||
|
self._update_inplace(self.static_input, args_dict)
|
||||||
|
|
||||||
|
def run(self, *args, **kwargs):
|
||||||
|
self._update_args(args, kwargs)
|
||||||
|
|
||||||
|
if self.graph is None:
|
||||||
|
# warmup
|
||||||
|
_ = torch.matmul(
|
||||||
|
torch.randn(100, 100, device=self.device),
|
||||||
|
torch.randn(100, 100, device=self.device)
|
||||||
|
)
|
||||||
|
torch.cuda.synchronize()
|
||||||
|
|
||||||
|
# capture graph
|
||||||
|
self.graph = torch.cuda.CUDAGraph()
|
||||||
|
with torch.cuda.graph(self.graph):
|
||||||
|
self.static_output = self.function(**self.static_input)
|
||||||
|
|
||||||
|
self.graph.replay()
|
||||||
|
|
||||||
|
return self.static_output
|
||||||
|
|
||||||
|
|
||||||
|
def cuda_graph(device="cuda", cast=False):
|
||||||
|
def decorator(func):
|
||||||
|
wrapper = CudaGraphWrapper(func, device, cast)
|
||||||
|
|
||||||
|
@wraps(func)
|
||||||
|
def wrapped(*args, **kwargs):
|
||||||
|
return wrapper.run(*args, **kwargs)
|
||||||
|
|
||||||
|
return wrapped
|
||||||
|
|
||||||
|
return decorator
|
||||||
@@ -167,7 +167,7 @@ class StreamGenerator(GeneratorCore):
|
|||||||
self.model.eval()
|
self.model.eval()
|
||||||
kv_caches = cache_manager.get_kvcache()
|
kv_caches = cache_manager.get_kvcache()
|
||||||
|
|
||||||
for _ in range(len(ids), self.config.m_len):
|
for _ in range(len(ids), self.config.max_len):
|
||||||
next_token_id, cache_increase = self.generate_iterator(
|
next_token_id, cache_increase = self.generate_iterator(
|
||||||
input_ids, temperature, top_k, top_p, kv_caches=kv_caches, start_pos=cur_cache_pos)
|
input_ids, temperature, top_k, top_p, kv_caches=kv_caches, start_pos=cur_cache_pos)
|
||||||
|
|
||||||
@@ -219,7 +219,7 @@ class BatchGenerator(GeneratorCore):
|
|||||||
start_cache_pos = max_ids_len
|
start_cache_pos = max_ids_len
|
||||||
cur_cache_pos = 0
|
cur_cache_pos = 0
|
||||||
|
|
||||||
while max_ids_len < self.config.m_len and sum(activate_task_mask) != 0:
|
while max_ids_len < self.config.max_len and sum(activate_task_mask) != 0:
|
||||||
kv_caches = cache_manager.get_kvcache()
|
kv_caches = cache_manager.get_kvcache()
|
||||||
attn_mask =cache_manager.get_seq_mask()
|
attn_mask =cache_manager.get_seq_mask()
|
||||||
|
|
||||||
|
|||||||
+90
-59
@@ -102,70 +102,92 @@ class RotaryEmbedding(nn.Module):
|
|||||||
|
|
||||||
|
|
||||||
class Linear(nn.Module):
|
class Linear(nn.Module):
|
||||||
def __init__(self, in_dim: int, out_dim: int, bias: bool = False, weight_param=None, bias_param=None):
|
def __init__(self, in_dim: int, out_dim: int, bias: bool = False):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
weight_param = torch.empty((out_dim, in_dim)) if weight_param is None else weight_param
|
self.weight = nn.Parameter(torch.empty((out_dim, in_dim)))
|
||||||
bias_param = torch.zeros(out_dim) if bias_param is None else bias_param
|
self.bias = nn.Parameter(torch.zeros(out_dim)) if bias else None
|
||||||
|
|
||||||
self.weight = nn.Parameter(weight_param)
|
|
||||||
self.bias = nn.Parameter(bias_param) if bias else None
|
|
||||||
|
|
||||||
def forward(self, x: Tensor) -> Tensor:
|
def forward(self, x: Tensor) -> Tensor:
|
||||||
return F.linear(x, self.weight, self.bias)
|
return F.linear(x, self.weight, self.bias)
|
||||||
|
|
||||||
|
|
||||||
class RMSNorm(nn.Module):
|
class RMSNorm(nn.Module):
|
||||||
def __init__(self, n_dim, norm_eps):
|
def __init__(self, dim, norm_eps):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.weight = nn.Parameter(torch.ones(n_dim))
|
self.weight = nn.Parameter(torch.ones(dim))
|
||||||
|
self.normalized_shape = (dim, )
|
||||||
self.norm_eps = norm_eps
|
self.norm_eps = norm_eps
|
||||||
|
|
||||||
def forward(self, x: Tensor) -> Tensor:
|
def forward(self, x: Tensor) -> Tensor:
|
||||||
dtype = x.dtype
|
rms = F.rms_norm(x.float(), self.normalized_shape, self.weight, self.norm_eps)
|
||||||
x = x.float()
|
return rms.to(x.dtype)
|
||||||
mean_square = torch.mean(torch.pow(x, 2), dim=-1, keepdim=True)
|
|
||||||
norm = x * torch.rsqrt(mean_square + self.norm_eps)
|
|
||||||
norm = norm.to(dtype)
|
|
||||||
out = norm * self.weight
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
class MLP(nn.Module):
|
class MLP(nn.Module):
|
||||||
def __init__(self, n_dim: int, d_ffn: int):
|
def __init__(self, dim: int, dim_feed_forward: int):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.up = Linear(n_dim, d_ffn)
|
self.up = Linear(dim, dim_feed_forward)
|
||||||
self.gate = Linear(n_dim, d_ffn)
|
self.gate = Linear(dim, dim_feed_forward)
|
||||||
self.down = Linear(d_ffn, n_dim)
|
self.down = Linear(dim_feed_forward, dim)
|
||||||
|
|
||||||
def forward(self, x: Tensor) -> Tensor:
|
def forward(self, x: Tensor) -> Tensor:
|
||||||
gated = self.up(x) * F.silu(self.gate(x))
|
gated = self.up(x) * F.silu(self.gate(x))
|
||||||
out = self.down(gated)
|
out = self.down(gated)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
class Attention(nn.Module):
|
||||||
|
|
||||||
|
def forward(self, q: Tensor, k: Tensor, v: Tensor, mask: Optional[Tensor] = None, is_causal: bool= False):
|
||||||
|
# (bsz, seq_len, n_heads, head_dim) -> (bsz, n_heads, seq_len, head_dim)
|
||||||
|
q, k, v = q.permute(0, 2, 1, 3), k.permute(0, 2, 1, 3), v.permute(0, 2, 1, 3)
|
||||||
|
# (bsz, n_heads, seq_len, head_dim) - > (bsz, seq_len, n_heads*head_dim)
|
||||||
|
sdqa_out = F.scaled_dot_product_attention(q, k, v, mask, is_causal=is_causal).permute(0, 2, 1, 3).contiguous().flatten(2)
|
||||||
|
|
||||||
|
return sdqa_out
|
||||||
|
|
||||||
|
|
||||||
class GQA(nn.Module):
|
class GQA(nn.Module):
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
n_dim: int,
|
dim: int,
|
||||||
n_head: int,
|
n_heads: int,
|
||||||
n_kvhead: int,
|
n_kv_heads: int,
|
||||||
|
use_qk_norm: bool,
|
||||||
|
norm_eps: float,
|
||||||
|
use_gated_attention: bool,
|
||||||
layer_id: int
|
layer_id: int
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
assert n_dim % n_head == 0
|
assert dim % n_heads == 0
|
||||||
assert n_head % n_kvhead == 0
|
assert n_heads % n_kv_heads == 0
|
||||||
|
|
||||||
self.head_dim = n_dim // n_head
|
self.head_dim = dim // n_heads
|
||||||
self.layer_id = layer_id
|
self.layer_id = layer_id
|
||||||
self.n_dim = n_dim
|
self.dim = dim
|
||||||
self.n_heads = n_head
|
self.n_heads = n_heads
|
||||||
self.n_kvheads = n_kvhead
|
self.n_kv_heads = n_kv_heads
|
||||||
self.n_rep = n_head // n_kvhead
|
self.n_rep = n_heads // n_kv_heads
|
||||||
|
self.use_qk_norm = use_qk_norm
|
||||||
|
self.use_gated_attention = use_gated_attention
|
||||||
|
|
||||||
self.q_proj = Linear(n_dim, n_head * self.head_dim)
|
self.attention = Attention()
|
||||||
self.k_proj = Linear(n_dim, n_kvhead * self.head_dim)
|
|
||||||
self.v_proj = Linear(n_dim, n_kvhead * self.head_dim)
|
self.q_proj = Linear(dim, n_heads * self.head_dim)
|
||||||
self.o_proj = Linear(n_dim, n_dim)
|
self.k_proj = Linear(dim, n_kv_heads * self.head_dim)
|
||||||
|
self.v_proj = Linear(dim, n_kv_heads * self.head_dim)
|
||||||
|
self.o_proj = Linear(dim, dim)
|
||||||
|
|
||||||
|
if self.use_qk_norm:
|
||||||
|
self.q_norm = RMSNorm(self.head_dim, norm_eps)
|
||||||
|
self.k_norm = RMSNorm(self.head_dim, norm_eps)
|
||||||
|
|
||||||
|
if self.use_gated_attention:
|
||||||
|
self.gate = Linear(dim, dim)
|
||||||
|
|
||||||
|
def _split_heads(self, x: Tensor, n_heads) -> Tensor:
|
||||||
|
batch_size, seq_len, _ = x.shape
|
||||||
|
x = x.reshape(batch_size, seq_len, n_heads, self.head_dim)
|
||||||
|
return x
|
||||||
|
|
||||||
def forward(
|
def forward(
|
||||||
self,
|
self,
|
||||||
@@ -178,43 +200,53 @@ class GQA(nn.Module):
|
|||||||
bsz, seq_len, _ = x.size()
|
bsz, seq_len, _ = x.size()
|
||||||
# x(bsz, seq_len, n_heads * head_dim) -> (bsz, seq_len, n_heads, head_dim)
|
# x(bsz, seq_len, n_heads * head_dim) -> (bsz, seq_len, n_heads, head_dim)
|
||||||
q = self._split_heads(self.q_proj(x), self.n_heads)
|
q = self._split_heads(self.q_proj(x), self.n_heads)
|
||||||
k = self._split_heads(self.k_proj(x), self.n_kvheads)
|
k = self._split_heads(self.k_proj(x), self.n_kv_heads)
|
||||||
v = self._split_heads(self.v_proj(x), self.n_kvheads)
|
v = self._split_heads(self.v_proj(x), self.n_kv_heads)
|
||||||
q, k = apply_rotary_emb(q, rotary_emb), apply_rotary_emb(k, rotary_emb)
|
q, k = apply_rotary_emb(q, rotary_emb), apply_rotary_emb(k, rotary_emb)
|
||||||
|
|
||||||
|
if self.use_qk_norm:
|
||||||
|
q, k = self.q_norm(q), self.k_norm(k)
|
||||||
|
|
||||||
if kv_cache is not None:
|
if kv_cache is not None:
|
||||||
k_cache, v_cache = kv_cache
|
k_cache, v_cache = kv_cache
|
||||||
|
|
||||||
# copy to cache
|
# copy to cache
|
||||||
k_cache[:bsz, self.layer_id, start_pos:start_pos + seq_len] = k
|
k_cache[:bsz, start_pos:start_pos + seq_len, self.layer_id] = k
|
||||||
v_cache[:bsz, self.layer_id, start_pos:start_pos + seq_len] = v
|
v_cache[:bsz, start_pos:start_pos + seq_len, self.layer_id] = v
|
||||||
|
|
||||||
# get cache
|
# get cache
|
||||||
k = k_cache[:bsz, self.layer_id, :start_pos + seq_len]
|
k = k_cache[:bsz, :start_pos + seq_len, self.layer_id]
|
||||||
v = v_cache[:bsz, self.layer_id, :start_pos + seq_len]
|
v = v_cache[:bsz, :start_pos + seq_len, self.layer_id]
|
||||||
|
|
||||||
k, v = repeat_kv(k, self.n_rep), repeat_kv(v, self.n_rep)
|
k, v = repeat_kv(k, self.n_rep), repeat_kv(v, self.n_rep)
|
||||||
|
sdqa_out = self.attention(q, k, v, mask, is_causal=(mask == None))
|
||||||
|
|
||||||
# (bsz, seq_len, n_heads, head_dim) -> (bsz, n_heads, seq_len, head_dim)
|
if self.use_gated_attention:
|
||||||
q, k, v = q.permute(0, 2, 1, 3), k.permute(0, 2, 1, 3), v.permute(0, 2, 1, 3)
|
sdqa_out = sdqa_out * F.sigmoid(self.gate(x))
|
||||||
sdqa_out = F.scaled_dot_product_attention(q, k, v, mask, is_causal=(mask == None)).permute(0, 2, 1, 3)
|
|
||||||
out = self.o_proj(sdqa_out.contiguous().view(bsz, seq_len, -1))
|
out = self.o_proj(sdqa_out)
|
||||||
|
|
||||||
return out
|
return out
|
||||||
|
|
||||||
def _split_heads(self, x: Tensor, n_heads) -> Tensor:
|
|
||||||
batch_size, seq_len, _ = x.shape
|
|
||||||
x = x.reshape(batch_size, seq_len, n_heads, self.head_dim)
|
|
||||||
return x
|
|
||||||
|
|
||||||
|
|
||||||
class DecoderBlock(nn.Module):
|
class DecoderBlock(nn.Module):
|
||||||
def __init__(self, n_dim, n_head, d_ffn, n_kvhead, norm_eps, layer_id):
|
def __init__(
|
||||||
|
self,
|
||||||
|
dim: int,
|
||||||
|
n_heads: int,
|
||||||
|
dim_ffn: int,
|
||||||
|
n_kv_heads: int,
|
||||||
|
norm_eps: int,
|
||||||
|
use_qk_norm: bool,
|
||||||
|
use_gated_attention: bool,
|
||||||
|
layer_id: int
|
||||||
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.attention = GQA(n_dim, n_head, n_kvhead, layer_id)
|
self.attention = GQA(dim, n_heads, n_kv_heads,
|
||||||
self.norm_attn = RMSNorm(n_dim, norm_eps)
|
use_qk_norm, norm_eps, use_gated_attention, layer_id)
|
||||||
self.ffn = MLP(n_dim, d_ffn)
|
self.input_norm = RMSNorm(dim, norm_eps)
|
||||||
self.norm_ffn = RMSNorm(n_dim, norm_eps)
|
self.mlp = MLP(dim, dim_ffn)
|
||||||
|
self.post_attention_norm = RMSNorm(dim, norm_eps)
|
||||||
|
|
||||||
def forward(
|
def forward(
|
||||||
self,
|
self,
|
||||||
@@ -226,7 +258,7 @@ class DecoderBlock(nn.Module):
|
|||||||
) -> Tensor:
|
) -> Tensor:
|
||||||
# attention
|
# attention
|
||||||
attn_output = self.attention(
|
attn_output = self.attention(
|
||||||
self.norm_attn(x),
|
self.input_norm(x),
|
||||||
rotary_emb,
|
rotary_emb,
|
||||||
attention_mask,
|
attention_mask,
|
||||||
kv_cache,
|
kv_cache,
|
||||||
@@ -235,16 +267,15 @@ class DecoderBlock(nn.Module):
|
|||||||
x = attn_output + x
|
x = attn_output + x
|
||||||
|
|
||||||
# feed forward
|
# feed forward
|
||||||
x = self.ffn(self.norm_ffn(x)) + x
|
x = self.mlp(self.post_attention_norm(x)) + x
|
||||||
|
|
||||||
return x
|
return x
|
||||||
|
|
||||||
|
|
||||||
class Embedding(nn.Module):
|
class Embedding(nn.Module):
|
||||||
def __init__(self, vocab_size: int, embedding_dim: int, weight_param=None):
|
def __init__(self, vocab_size: int, embedding_dim: int):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
weight_param = torch.empty((vocab_size, embedding_dim)) if weight_param is None else weight_param
|
self.weight = nn.Parameter(torch.empty((vocab_size, embedding_dim)))
|
||||||
self.weight = nn.Parameter(weight_param)
|
|
||||||
|
|
||||||
def forward(self, x: Tensor) -> Tensor:
|
def forward(self, x: Tensor) -> Tensor:
|
||||||
return F.embedding(x, self.weight)
|
return F.embedding(x, self.weight)
|
||||||
@@ -59,16 +59,17 @@ class Transformer(nn.Module):
|
|||||||
def __init__(self, config: ModelConfig):
|
def __init__(self, config: ModelConfig):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.config = config
|
self.config = config
|
||||||
self.rotary_embeding = RotaryEmbedding(config.n_dim // config.n_head, config.m_len)
|
self.rotary_embeding = RotaryEmbedding(config.dim // config.n_heads, config.max_len)
|
||||||
self.embed_tokens = Embedding(config.vocab_size, config.n_dim)
|
self.embed_tokens = Embedding(config.vocab_size, config.dim)
|
||||||
|
|
||||||
self.layers = nn.ModuleList([
|
self.layers = nn.ModuleList([
|
||||||
DecoderBlock(config.n_dim, config.n_head, config.d_ffn, config.n_kvhead, config.norm_eps, layer_id)
|
DecoderBlock(config.dim, config.n_heads, config.dim_ffn, config.n_kv_heads,
|
||||||
for layer_id in range(config.n_layer)
|
config.norm_eps, config.use_qk_norm, config.use_gated_attention, layer_id)
|
||||||
|
for layer_id in range(config.n_layers)
|
||||||
])
|
])
|
||||||
|
|
||||||
self.norm = RMSNorm(config.n_dim, config.norm_eps)
|
self.norm = RMSNorm(config.dim, config.norm_eps)
|
||||||
self.lm_head = Linear(config.n_dim, config.vocab_size)
|
self.lm_head = Linear(config.dim, config.vocab_size)
|
||||||
|
|
||||||
if self.config.tie_weight == True:
|
if self.config.tie_weight == True:
|
||||||
self.lm_head.weight = self.embed_tokens.weight
|
self.lm_head.weight = self.embed_tokens.weight
|
||||||
@@ -83,8 +84,9 @@ class Transformer(nn.Module):
|
|||||||
# same tensor
|
# same tensor
|
||||||
state_dict[lm_head_key] = state_dict[embed_key]
|
state_dict[lm_head_key] = state_dict[embed_key]
|
||||||
else:
|
else:
|
||||||
# use clone to avoid sharing the same tensor
|
if lm_head_key not in state_dict and embed_key in state_dict:
|
||||||
state_dict[lm_head_key] = torch.clone(state_dict[embed_key])
|
# use clone to avoid sharing the same tensor
|
||||||
|
state_dict[lm_head_key] = torch.clone(state_dict[embed_key])
|
||||||
|
|
||||||
return super().load_state_dict(state_dict, strict, assign)
|
return super().load_state_dict(state_dict, strict, assign)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
from khaosz.parallel.setup import (
|
||||||
|
get_world_size,
|
||||||
|
get_rank,
|
||||||
|
get_current_device,
|
||||||
|
|
||||||
|
only_on_rank,
|
||||||
|
setup_parallel,
|
||||||
|
spawn_parallel_fn
|
||||||
|
)
|
||||||
|
|
||||||
|
from khaosz.parallel.module import (
|
||||||
|
RowParallelLinear,
|
||||||
|
ColumnParallelLinear
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"get_world_size",
|
||||||
|
"get_rank",
|
||||||
|
"get_current_device",
|
||||||
|
|
||||||
|
"only_on_rank",
|
||||||
|
"setup_parallel",
|
||||||
|
"spawn_parallel_fn",
|
||||||
|
|
||||||
|
"RowParallelLinear",
|
||||||
|
"ColumnParallelLinear"
|
||||||
|
]
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import torch.nn.functional as F
|
||||||
|
import torch.distributed as dist
|
||||||
|
|
||||||
|
from torch import Tensor
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
|
||||||
|
class ParallelModel(nn.Module):
|
||||||
|
def __init__(self, process_group: dist.ProcessGroup):
|
||||||
|
super().__init__()
|
||||||
|
self.process_group = process_group
|
||||||
|
self.rank = dist.get_rank(self.process_group)
|
||||||
|
self.world_size = dist.get_world_size(self.process_group)
|
||||||
|
|
||||||
|
|
||||||
|
class RowParallelLinear(ParallelModel):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
process_group: dist.ProcessGroup,
|
||||||
|
in_features: int,
|
||||||
|
out_features: int,
|
||||||
|
bias: bool = True,
|
||||||
|
reduce_results: bool = True
|
||||||
|
):
|
||||||
|
super().__init__(process_group)
|
||||||
|
|
||||||
|
self.in_features = in_features
|
||||||
|
self.out_features = out_features
|
||||||
|
self.in_features_per_rank = in_features // self.world_size
|
||||||
|
self.reduce_results = reduce_results
|
||||||
|
|
||||||
|
if in_features % self.world_size != 0:
|
||||||
|
raise ValueError(f"in_features must be divisible by world_size. Got {in_features} and {self.world_size}")
|
||||||
|
|
||||||
|
self.weight = nn.Parameter(torch.empty(out_features, self.in_features_per_rank))
|
||||||
|
self.bias = nn.Parameter(torch.zeros(out_features)) if bias else None
|
||||||
|
|
||||||
|
def forward(self, input: Tensor) -> Tensor:
|
||||||
|
output = F.linear(input, self.weight)
|
||||||
|
|
||||||
|
if self.reduce_results:
|
||||||
|
dist.all_reduce(output, op=dist.ReduceOp.SUM, group=self.process_group)
|
||||||
|
|
||||||
|
if self.bias is not None:
|
||||||
|
output += self.bias
|
||||||
|
|
||||||
|
return output
|
||||||
|
|
||||||
|
def load_state_dict(self, state_dict: Dict[str, Tensor]):
|
||||||
|
full_weight = state_dict.get('weight')
|
||||||
|
full_bias = state_dict.get('bias')
|
||||||
|
|
||||||
|
start_idx = self.rank * self.in_features_per_rank
|
||||||
|
end_idx = start_idx + self.in_features_per_rank
|
||||||
|
weight_slice = full_weight[:, start_idx:end_idx]
|
||||||
|
self.weight.data.copy_(weight_slice)
|
||||||
|
|
||||||
|
if self.bias is not None:
|
||||||
|
self.bias.data.copy_(full_bias)
|
||||||
|
|
||||||
|
|
||||||
|
class ColumnParallelLinear(ParallelModel):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
process_group: dist.ProcessGroup,
|
||||||
|
in_features: int,
|
||||||
|
out_features: int,
|
||||||
|
bias: bool = True,
|
||||||
|
gather_results: bool = True
|
||||||
|
):
|
||||||
|
super().__init__(process_group)
|
||||||
|
|
||||||
|
self.in_features = in_features
|
||||||
|
self.out_features = out_features
|
||||||
|
self.out_features_per_rank = out_features // self.world_size
|
||||||
|
self.gather_results = gather_results
|
||||||
|
|
||||||
|
if out_features % self.world_size != 0:
|
||||||
|
raise ValueError(f"out_features must be divisible by world_size. Got {out_features} and {self.world_size}")
|
||||||
|
|
||||||
|
self.weight = nn.Parameter(torch.empty(self.out_features_per_rank, self.in_features))
|
||||||
|
self.bias = nn.Parameter(torch.zeros(self.out_features_per_rank)) if bias else None
|
||||||
|
|
||||||
|
def forward(self, input: Tensor) -> Tensor:
|
||||||
|
output = F.linear(input, self.weight, self.bias)
|
||||||
|
|
||||||
|
if self.gather_results:
|
||||||
|
output_list = [torch.empty_like(output) for _ in range(self.world_size)]
|
||||||
|
dist.all_gather(output_list, output, group=self.process_group)
|
||||||
|
output = torch.cat(output_list, dim=-1)
|
||||||
|
|
||||||
|
return output
|
||||||
|
|
||||||
|
def load_state_dict(self, state_dict: Dict[str, Tensor]):
|
||||||
|
full_weight = state_dict.get('weight')
|
||||||
|
full_bias = state_dict.get('bias')
|
||||||
|
|
||||||
|
start_idx = self.rank * self.out_features_per_rank
|
||||||
|
end_idx = start_idx + self.out_features_per_rank
|
||||||
|
weight_slice = full_weight[start_idx:end_idx, :]
|
||||||
|
self.weight.data.copy_(weight_slice)
|
||||||
|
|
||||||
|
if self.bias is not None:
|
||||||
|
bias_slice = full_bias[start_idx:end_idx]
|
||||||
|
self.bias.data.copy_(bias_slice)
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import os
|
||||||
|
import torch
|
||||||
|
import torch.distributed as dist
|
||||||
|
import torch.multiprocessing as mp
|
||||||
|
|
||||||
|
from functools import wraps
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from typing import Callable, List, Optional
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_device():
|
||||||
|
return os.environ["LOCAL_DEVICE"]
|
||||||
|
|
||||||
|
def get_world_size() -> int:
|
||||||
|
if dist.is_available() and dist.is_initialized():
|
||||||
|
return dist.get_world_size()
|
||||||
|
else:
|
||||||
|
return 1
|
||||||
|
|
||||||
|
def get_rank() -> int:
|
||||||
|
if dist.is_available() and dist.is_initialized():
|
||||||
|
return dist.get_rank()
|
||||||
|
else:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def setup_parallel(
|
||||||
|
rank: int,
|
||||||
|
world_size: int,
|
||||||
|
backend: str = "nccl",
|
||||||
|
master_addr: str = "localhost",
|
||||||
|
master_port: str = "29500",
|
||||||
|
device_type: str = "cuda",
|
||||||
|
device_ids: Optional[List[int]] = None
|
||||||
|
):
|
||||||
|
|
||||||
|
if dist.is_available() and dist.is_initialized():
|
||||||
|
yield dist.group.WORLD
|
||||||
|
return
|
||||||
|
|
||||||
|
if world_size <= 1:
|
||||||
|
yield None
|
||||||
|
return
|
||||||
|
|
||||||
|
if device_ids is None:
|
||||||
|
device_ids = [i for i in range(world_size)]
|
||||||
|
|
||||||
|
rank = device_ids[rank % len(device_ids)]
|
||||||
|
device_id = torch.device(device_type, device_ids[rank])
|
||||||
|
|
||||||
|
os.environ['MASTER_ADDR'] = master_addr
|
||||||
|
os.environ['MASTER_PORT'] = master_port
|
||||||
|
|
||||||
|
os.environ['LOCAL_RANK'] = str(rank)
|
||||||
|
os.environ['WORLD_SIZE'] = str(world_size)
|
||||||
|
os.environ["LOCAL_DEVICE"] = str(device_id)
|
||||||
|
|
||||||
|
dist.init_process_group(
|
||||||
|
rank=rank,
|
||||||
|
world_size=world_size,
|
||||||
|
backend=backend,
|
||||||
|
device_id=device_id
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
if backend == "nccl" and torch.cuda.is_available():
|
||||||
|
torch.cuda.set_device(device_id)
|
||||||
|
elif backend == "ccl" and hasattr(torch, 'xpu') and torch.xpu.is_available():
|
||||||
|
torch.xpu.set_device(device_id)
|
||||||
|
|
||||||
|
yield dist.group.WORLD
|
||||||
|
finally:
|
||||||
|
if dist.is_initialized():
|
||||||
|
dist.destroy_process_group()
|
||||||
|
|
||||||
|
def only_on_rank(rank, sync=False):
|
||||||
|
"""
|
||||||
|
decorator to run a function only on a specific rank.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def decorator(func):
|
||||||
|
@wraps(func)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
if get_rank() == rank:
|
||||||
|
return func(*args, **kwargs)
|
||||||
|
if sync:
|
||||||
|
dist.barrier()
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
return decorator
|
||||||
|
|
||||||
|
def wrapper_spawn_func(
|
||||||
|
rank: int,
|
||||||
|
world_size: int,
|
||||||
|
backend: str,
|
||||||
|
master_addr: str,
|
||||||
|
master_port: str,
|
||||||
|
device_type: str,
|
||||||
|
device_ids: List[int],
|
||||||
|
func: Callable,
|
||||||
|
kwargs: dict
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
with setup_parallel(
|
||||||
|
rank=rank,
|
||||||
|
world_size=world_size,
|
||||||
|
backend=backend,
|
||||||
|
master_addr=master_addr,
|
||||||
|
master_port=master_port,
|
||||||
|
device_type=device_type,
|
||||||
|
device_ids=device_ids
|
||||||
|
):
|
||||||
|
func(**kwargs)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error in rank {rank}: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
def spawn_parallel_fn(
|
||||||
|
func: Callable,
|
||||||
|
world_size: int,
|
||||||
|
backend: str = "nccl",
|
||||||
|
master_addr: str = "localhost",
|
||||||
|
master_port: str = "29500",
|
||||||
|
device_type: str = "cuda",
|
||||||
|
device_ids: Optional[List[int]] = None,
|
||||||
|
**kwargs
|
||||||
|
):
|
||||||
|
# clear environment variables
|
||||||
|
for key in ['MASTER_ADDR', 'MASTER_PORT', 'RANK', 'WORLD_SIZE', 'LOCAL_RANK', 'LOCAL_DEVICE']:
|
||||||
|
if key in os.environ:
|
||||||
|
del os.environ[key]
|
||||||
|
|
||||||
|
if world_size == 1:
|
||||||
|
device_ids = device_ids or [0]
|
||||||
|
deice_id = torch.device(device_type, device_ids[0])
|
||||||
|
os.environ["LOCAL_DEVICE"] = str(deice_id)
|
||||||
|
|
||||||
|
func(**kwargs)
|
||||||
|
return
|
||||||
|
|
||||||
|
wrapper_spawn_func_args = (world_size, backend, master_addr, master_port,
|
||||||
|
device_type, device_ids, func, kwargs)
|
||||||
|
|
||||||
|
mp.spawn(
|
||||||
|
wrapper_spawn_func,
|
||||||
|
nprocs=world_size,
|
||||||
|
args=wrapper_spawn_func_args,
|
||||||
|
join=True
|
||||||
|
)
|
||||||
@@ -8,7 +8,7 @@ from khaosz.trainer.train_callback import (
|
|||||||
CheckpointCallback,
|
CheckpointCallback,
|
||||||
TrainCallback,
|
TrainCallback,
|
||||||
SchedulerCallback,
|
SchedulerCallback,
|
||||||
StepMonitorCallback
|
MetricLoggerCallback
|
||||||
)
|
)
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
@@ -25,5 +25,5 @@ __all__ = [
|
|||||||
"CheckpointCallback",
|
"CheckpointCallback",
|
||||||
"TrainCallback",
|
"TrainCallback",
|
||||||
"SchedulerCallback",
|
"SchedulerCallback",
|
||||||
"StepMonitorCallback"
|
"MetricLoggerCallback"
|
||||||
]
|
]
|
||||||
@@ -62,4 +62,28 @@ def grad_nan_num(model: nn.Module) -> Dict[str, int]:
|
|||||||
if param.grad:
|
if param.grad:
|
||||||
nan_num = param.grad.isnan().sum().item()
|
nan_num = param.grad.isnan().sum().item()
|
||||||
nan_nums[name] = nan_num
|
nan_nums[name] = nan_num
|
||||||
return nan_nums
|
return nan_nums
|
||||||
|
|
||||||
|
def ctx_get_loss(ctx):
|
||||||
|
return ctx.loss
|
||||||
|
|
||||||
|
def ctx_get_lr(ctx):
|
||||||
|
return ctx.optimizer.param_groups[-1]['lr']
|
||||||
|
|
||||||
|
def ctx_get_grad_norm(ctx):
|
||||||
|
return grad_norm(ctx.model)
|
||||||
|
|
||||||
|
def ctx_get_grad_std(ctx):
|
||||||
|
return grad_std(ctx.model)
|
||||||
|
|
||||||
|
def ctx_get_grad_max(ctx):
|
||||||
|
return grad_max(ctx.model)
|
||||||
|
|
||||||
|
def ctx_get_grad_min(ctx):
|
||||||
|
return grad_min(ctx.model)
|
||||||
|
|
||||||
|
def ctx_get_grad_mean(ctx):
|
||||||
|
return grad_mean(ctx.model)
|
||||||
|
|
||||||
|
def ctx_get_grad_nan_num(ctx):
|
||||||
|
return grad_nan_num(ctx.model)
|
||||||
@@ -151,8 +151,8 @@ class SchedulerFactory:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def load_scheduler(optimizer, scedule_config: ScheduleConfig) -> BaseScheduler:
|
def load(optimizer, schedule_config: ScheduleConfig) -> BaseScheduler:
|
||||||
kwargs = scedule_config.get_kwargs()
|
kwargs = schedule_config.get_kwargs()
|
||||||
schedule_type = kwargs.pop("schedule_type")
|
schedule_type = kwargs.pop("schedule_type")
|
||||||
|
|
||||||
if schedule_type == "cosine":
|
if schedule_type == "cosine":
|
||||||
|
|||||||
+13
-43
@@ -4,14 +4,19 @@ import torch.nn as nn
|
|||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
|
|
||||||
from torch import Tensor
|
from torch import Tensor
|
||||||
from typing import Any, Tuple, Callable, Dict, Union
|
from typing import Any, Callable, Dict, Union
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
|
|
||||||
|
|
||||||
def get_logprobs(model:nn.Module, input_ids: Tensor, mask: Tensor, pad_token_id: int):
|
def get_logprobs(
|
||||||
|
model: Union[nn.Module, Callable[..., Dict[str, Tensor]]],
|
||||||
|
input_ids: Tensor,
|
||||||
|
mask: Tensor,
|
||||||
|
pad_token_id: int
|
||||||
|
):
|
||||||
input_mask = input_ids.ne(pad_token_id)
|
input_mask = input_ids.ne(pad_token_id)
|
||||||
logits = model(input_ids, input_mask)["logits"]
|
logits = model(input_ids, input_mask)["logits"]
|
||||||
log_probs = torch.log_softmax(logits, dim=-1)
|
log_probs = torch.log_softmax(logits.float(), dim=-1)
|
||||||
|
|
||||||
shifted_log_probs = log_probs[:, :-1, :]
|
shifted_log_probs = log_probs[:, :-1, :]
|
||||||
shifted_input_ids = input_ids[:, 1:]
|
shifted_input_ids = input_ids[:, 1:]
|
||||||
@@ -41,7 +46,7 @@ class BaseStrategy(ABC):
|
|||||||
def compute_loss(self, batch: Dict[str, Tensor]) -> Tensor:
|
def compute_loss(self, batch: Dict[str, Tensor]) -> Tensor:
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
|
||||||
def __call__(self, batch: Tuple[Tensor, ...]) -> Tensor:
|
def __call__(self, batch: Dict[str, Tensor]) -> Tensor:
|
||||||
return self.compute_loss(batch)
|
return self.compute_loss(batch)
|
||||||
|
|
||||||
|
|
||||||
@@ -55,7 +60,7 @@ class SeqStrategy(BaseStrategy):
|
|||||||
logits = self.model(input_ids=input_ids)["logits"]
|
logits = self.model(input_ids=input_ids)["logits"]
|
||||||
|
|
||||||
loss = F.cross_entropy(
|
loss = F.cross_entropy(
|
||||||
input=logits.flatten(0, 1),
|
input=logits.flatten(0, 1).float(),
|
||||||
target=target_ids.flatten()
|
target=target_ids.flatten()
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -75,7 +80,7 @@ class SftStrategy(BaseStrategy):
|
|||||||
target_ids = target_ids.masked_fill(loss_mask == 0, ignore_index)
|
target_ids = target_ids.masked_fill(loss_mask == 0, ignore_index)
|
||||||
|
|
||||||
loss = F.cross_entropy(
|
loss = F.cross_entropy(
|
||||||
input=logits.flatten(0, 1),
|
input=logits.flatten(0, 1).float(),
|
||||||
target=target_ids.flatten(),
|
target=target_ids.flatten(),
|
||||||
ignore_index=ignore_index
|
ignore_index=ignore_index
|
||||||
)
|
)
|
||||||
@@ -94,7 +99,7 @@ class DpoStrategy(BaseStrategy):
|
|||||||
self.pad_token_id = pad_token_id
|
self.pad_token_id = pad_token_id
|
||||||
self.beta = beta
|
self.beta = beta
|
||||||
|
|
||||||
def compute_loss(self, batch: Tuple[Tensor, ...]) -> Tensor:
|
def compute_loss(self, batch: Dict[str, Tensor]) -> Tensor:
|
||||||
batch = move_to_device(batch, self.device)
|
batch = move_to_device(batch, self.device)
|
||||||
good_ids, bad_ids = batch["chosen"], batch["rejected"]
|
good_ids, bad_ids = batch["chosen"], batch["rejected"]
|
||||||
good_mask, bad_mask = batch["chosen_mask"], batch["rejected_mask"]
|
good_mask, bad_mask = batch["chosen_mask"], batch["rejected_mask"]
|
||||||
@@ -115,41 +120,6 @@ class DpoStrategy(BaseStrategy):
|
|||||||
return dpo_loss
|
return dpo_loss
|
||||||
|
|
||||||
|
|
||||||
class PpoStrategy(BaseStrategy):
|
|
||||||
def __init__(self, model, pad_token_id, epsilon):
|
|
||||||
super().__init__(model)
|
|
||||||
ref_model = copy.deepcopy(self.model)
|
|
||||||
ref_model.requires_grad_(False)
|
|
||||||
ref_model.eval()
|
|
||||||
|
|
||||||
self.ref_model = ref_model
|
|
||||||
self.pad_token_id = pad_token_id
|
|
||||||
self.epsilon = epsilon
|
|
||||||
|
|
||||||
def ppo_clip_loss_masked(
|
|
||||||
self,
|
|
||||||
log_probs: Tensor,
|
|
||||||
old_log_probs: Tensor,
|
|
||||||
advantages: Tensor,
|
|
||||||
values: Tensor,
|
|
||||||
returns: Tensor,
|
|
||||||
mask: Tensor,
|
|
||||||
clip_eps: float=0.2,
|
|
||||||
):
|
|
||||||
ratio = torch.exp(log_probs - old_log_probs)
|
|
||||||
surr1 = ratio * advantages
|
|
||||||
surr2 = torch.clamp(ratio, 1 - clip_eps, 1 + clip_eps) * advantages
|
|
||||||
policy_loss = -torch.min(surr1, surr2).masked_select(mask).mean()
|
|
||||||
|
|
||||||
value_loss = F.mse_loss(values.masked_select(mask),
|
|
||||||
returns.masked_select(mask))
|
|
||||||
|
|
||||||
entropy = -(log_probs.exp() * log_probs).masked_select(mask).mean()
|
|
||||||
entropy_loss = -entropy
|
|
||||||
return policy_loss, value_loss, entropy_loss
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class StrategyFactory:
|
class StrategyFactory:
|
||||||
|
|
||||||
def load(model, train_type, device, **kwargs):
|
def load(model, train_type, device, **kwargs):
|
||||||
@@ -157,7 +127,7 @@ class StrategyFactory:
|
|||||||
"seq": lambda: SeqStrategy(model, device),
|
"seq": lambda: SeqStrategy(model, device),
|
||||||
"sft": lambda: SftStrategy(model, device),
|
"sft": lambda: SftStrategy(model, device),
|
||||||
"dpo": lambda: DpoStrategy(
|
"dpo": lambda: DpoStrategy(
|
||||||
model,
|
model,
|
||||||
device,
|
device,
|
||||||
kwargs.get("pad_token_id"),
|
kwargs.get("pad_token_id"),
|
||||||
kwargs.get("dpo_beta")
|
kwargs.get("dpo_beta")
|
||||||
|
|||||||
+128
-122
@@ -1,26 +1,27 @@
|
|||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
|
import torch.nn as nn
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
from torch.nn.utils import clip_grad_norm_
|
from torch.nn.utils import clip_grad_norm_
|
||||||
from torch.optim.lr_scheduler import LambdaLR
|
from torch.optim.lr_scheduler import LRScheduler
|
||||||
from typing import List, Optional, Protocol, TYPE_CHECKING
|
from typing import Callable, List, Optional, Protocol
|
||||||
|
|
||||||
from khaosz.config import ScheduleConfig
|
from khaosz.parallel import only_on_rank
|
||||||
from khaosz.trainer.metric_util import (
|
from khaosz.trainer.metric_util import (
|
||||||
grad_max,
|
ctx_get_loss,
|
||||||
grad_min,
|
ctx_get_lr,
|
||||||
grad_norm,
|
ctx_get_grad_max,
|
||||||
grad_mean,
|
ctx_get_grad_min,
|
||||||
grad_std,
|
ctx_get_grad_norm,
|
||||||
grad_nan_num
|
ctx_get_grad_mean,
|
||||||
|
ctx_get_grad_std,
|
||||||
|
ctx_get_grad_nan_num
|
||||||
)
|
)
|
||||||
|
from khaosz.data.checkpoint import Checkpoint
|
||||||
if TYPE_CHECKING:
|
from khaosz.trainer.train_context import TrainContext
|
||||||
from khaosz.trainer.trainer import Trainer
|
|
||||||
from khaosz.trainer.train_context import TrainContext
|
|
||||||
|
|
||||||
|
|
||||||
class TrainCallback(Protocol):
|
class TrainCallback(Protocol):
|
||||||
@@ -28,31 +29,31 @@ class TrainCallback(Protocol):
|
|||||||
Callback interface for trainer.
|
Callback interface for trainer.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def on_train_begin(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_train_begin(self, context: TrainContext):
|
||||||
""" Called at the beginning of training. """
|
""" Called at the beginning of training. """
|
||||||
|
|
||||||
def on_train_end(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_train_end(self, context: TrainContext):
|
||||||
""" Called at the end of training. """
|
""" Called at the end of training. """
|
||||||
|
|
||||||
def on_epoch_begin(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_epoch_begin(self, context: TrainContext):
|
||||||
""" Called at the beginning of each epoch. """
|
""" Called at the beginning of each epoch. """
|
||||||
|
|
||||||
def on_epoch_end(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_epoch_end(self, context: TrainContext):
|
||||||
""" Called at the end of each epoch. """
|
""" Called at the end of each epoch. """
|
||||||
|
|
||||||
def on_step_begin(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_step_begin(self, context: TrainContext):
|
||||||
""" Called at the beginning of each step. """
|
""" Called at the beginning of each step. """
|
||||||
|
|
||||||
def on_step_end(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_step_end(self, context: TrainContext):
|
||||||
""" Called at the end of each step."""
|
""" Called at the end of each step."""
|
||||||
|
|
||||||
def on_batch_begin(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_batch_begin(self, context: TrainContext):
|
||||||
""" Called at the beginning of each batch. """
|
""" Called at the beginning of each batch. """
|
||||||
|
|
||||||
def on_batch_end(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_batch_end(self, context: TrainContext):
|
||||||
""" Called at the end of each batch. """
|
""" Called at the end of each batch. """
|
||||||
|
|
||||||
def on_error(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_error(self, context: TrainContext):
|
||||||
""" Called when an error occurs during training. """
|
""" Called when an error occurs during training. """
|
||||||
|
|
||||||
|
|
||||||
@@ -63,29 +64,27 @@ class GradientClippingCallback(TrainCallback):
|
|||||||
def __init__(self, max_grad_norm: float):
|
def __init__(self, max_grad_norm: float):
|
||||||
self.max_grad_norm = max_grad_norm
|
self.max_grad_norm = max_grad_norm
|
||||||
|
|
||||||
def on_step_begin(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_step_begin(self, context: TrainContext):
|
||||||
_ = context
|
_ = context
|
||||||
clip_grad_norm_(trainer.parameter.model.parameters(), self.max_grad_norm)
|
clip_grad_norm_(context.model.parameters(), self.max_grad_norm)
|
||||||
|
|
||||||
|
|
||||||
class SchedulerCallback(TrainCallback):
|
class SchedulerCallback(TrainCallback):
|
||||||
"""
|
"""
|
||||||
Scheduler callback for trainer.
|
Scheduler callback for trainer.
|
||||||
"""
|
"""
|
||||||
def __init__(self, schedule_config: ScheduleConfig):
|
def __init__(self):
|
||||||
self.schedule_config = schedule_config
|
self.scheduler: LRScheduler = None
|
||||||
self.scheduler: Optional[LambdaLR] = None
|
|
||||||
|
|
||||||
def on_train_begin(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_train_begin(self, context: TrainContext):
|
||||||
|
for group in context.optimizer.param_groups:
|
||||||
for group in trainer.train_config.optimizer.param_groups:
|
|
||||||
if "initial_lr" not in group:
|
if "initial_lr" not in group:
|
||||||
group["initial_lr"] = group["lr"]
|
group["initial_lr"] = group["lr"]
|
||||||
|
|
||||||
self.scheduler = context.scheduler
|
self.scheduler = context.scheduler
|
||||||
|
|
||||||
def on_batch_end(self, trainer: 'Trainer', context: 'TrainContext'):
|
def on_batch_end(self, context: TrainContext):
|
||||||
_ = trainer, context
|
_ = context
|
||||||
if self.scheduler:
|
if self.scheduler:
|
||||||
self.scheduler.step()
|
self.scheduler.step()
|
||||||
|
|
||||||
@@ -94,133 +93,140 @@ class CheckpointCallback(TrainCallback):
|
|||||||
"""
|
"""
|
||||||
Checkpoint callback for trainer.
|
Checkpoint callback for trainer.
|
||||||
"""
|
"""
|
||||||
def __init__(self, checkpoint_interval: int):
|
def __init__(
|
||||||
self.checkpoint_interval = checkpoint_interval
|
self,
|
||||||
|
save_dir: str,
|
||||||
|
interval: int,
|
||||||
|
weight_only: bool = False,
|
||||||
|
state_dict_fn: Optional[Callable[[nn.Module], dict]] = None
|
||||||
|
):
|
||||||
|
self.save_dir = save_dir
|
||||||
|
self.interval = interval
|
||||||
|
self.weight_only = weight_only
|
||||||
|
self.state_dict_fn = state_dict_fn
|
||||||
self.last_ckpt_iter = 0
|
self.last_ckpt_iter = 0
|
||||||
|
|
||||||
def _save_checkpoint(self, trainer: 'Trainer', context: 'TrainContext'):
|
@only_on_rank(0)
|
||||||
save_path = os.path.join(trainer.train_config.checkpoint_dir, f"iter_{context.batch_iter}")
|
def _save_checkpoint(self, context: TrainContext):
|
||||||
context.checkpoint.optimizer_state = context.optimizer.state_dict()
|
save_path = os.path.join(self.save_dir, f"epoch_{context.epoch}_iter_{context.iteration}")
|
||||||
context.checkpoint.scheduler_state = context.scheduler.state_dict()
|
state_dict = self.state_dict_fn(context.model) if self.state_dict_fn else context.model.state_dict()
|
||||||
context.checkpoint.epoch = context.epoch
|
|
||||||
context.checkpoint.batch_iter = context.batch_iter
|
|
||||||
context.checkpoint.save(save_path)
|
|
||||||
self.last_ckpt_iter = context.batch_iter
|
|
||||||
|
|
||||||
def on_batch_end(self, trainer: 'Trainer', context: 'TrainContext'):
|
|
||||||
context.checkpoint.loss_list.append(context.loss)
|
|
||||||
|
|
||||||
if context.batch_iter - self.last_ckpt_iter >= self.checkpoint_interval:
|
context.checkpoint = Checkpoint(
|
||||||
self._save_checkpoint(trainer, context)
|
state_dict=state_dict,
|
||||||
|
epoch=context.epoch,
|
||||||
def on_train_end(self, trainer: 'Trainer', context: 'TrainContext'):
|
iteration=context.iteration
|
||||||
if context.batch_iter != self.last_ckpt_iter:
|
)
|
||||||
self._save_checkpoint(trainer, context)
|
|
||||||
|
context.checkpoint.save(save_path)
|
||||||
|
self.last_ckpt_iter = context.iteration
|
||||||
|
|
||||||
|
def on_batch_end(self, context: TrainContext):
|
||||||
|
if context.iteration - self.last_ckpt_iter >= self.interval:
|
||||||
|
self._save_checkpoint(context)
|
||||||
|
|
||||||
|
def on_train_end(self, context: TrainContext):
|
||||||
|
if context.iteration != self.last_ckpt_iter:
|
||||||
|
self._save_checkpoint(context)
|
||||||
|
|
||||||
|
def on_error(self, context: TrainContext):
|
||||||
|
self._save_checkpoint(context)
|
||||||
|
|
||||||
|
|
||||||
class ProgressBarCallback(TrainCallback):
|
class ProgressBarCallback(TrainCallback):
|
||||||
"""
|
"""
|
||||||
Progress bar callback for trainer.
|
Progress bar callback for trainer.
|
||||||
"""
|
"""
|
||||||
def __init__(self):
|
def __init__(self, num_epoch: int):
|
||||||
|
self.num_epoch = num_epoch
|
||||||
self.progress_bar: tqdm = None
|
self.progress_bar: tqdm = None
|
||||||
|
|
||||||
def on_epoch_begin(self, trainer: 'Trainer', context: 'TrainContext'):
|
@only_on_rank(0)
|
||||||
|
def on_epoch_begin(self, context: TrainContext):
|
||||||
self.progress_bar = tqdm(
|
self.progress_bar = tqdm(
|
||||||
context.dataloader,
|
context.dataloader,
|
||||||
desc=f"Epoch {context.epoch+1}/{trainer.train_config.n_epoch}",
|
desc=f"Epoch {context.epoch+1}/{self.num_epoch}",
|
||||||
dynamic_ncols=True
|
dynamic_ncols=True
|
||||||
)
|
)
|
||||||
|
|
||||||
def on_batch_end(self, trainer: 'Trainer', context: 'TrainContext'):
|
@only_on_rank(0)
|
||||||
_ = trainer
|
def on_batch_end(self, context: TrainContext):
|
||||||
self.progress_bar.set_postfix({
|
self.progress_bar.set_postfix({
|
||||||
"loss": f"{context.loss:.4f}",
|
"loss": f"{context.loss:.4f}",
|
||||||
"lr": f"{context.optimizer.param_groups[-1]['lr']:.2e}"
|
"lr": f"{context.optimizer.param_groups[-1]['lr']:.2e}"
|
||||||
})
|
})
|
||||||
self.progress_bar.update(1)
|
self.progress_bar.update(1)
|
||||||
|
|
||||||
def on_epoch_end(self, trainer: 'Trainer', context: 'TrainContext'):
|
@only_on_rank(0)
|
||||||
_ = trainer, context
|
def on_epoch_end(self, context: TrainContext):
|
||||||
|
_ = context
|
||||||
if self.progress_bar:
|
if self.progress_bar:
|
||||||
self.progress_bar.close()
|
self.progress_bar.close()
|
||||||
|
|
||||||
|
|
||||||
class StepMonitorCallback(TrainCallback):
|
class MetricLoggerCallback(TrainCallback):
|
||||||
"""
|
|
||||||
Customizable logger callback for trainer.
|
|
||||||
|
|
||||||
This callback provides flexible logging capabilities for training metrics,
|
|
||||||
supporting multiple log formats and custom log handlers.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
log_dir: Optional[str] = None,
|
log_dir:str,
|
||||||
log_interval: int = 100,
|
save_interval:int,
|
||||||
metrics: Optional[List[str]] = None
|
log_interval:int=10,
|
||||||
|
metrics:List[str]=None
|
||||||
):
|
):
|
||||||
"""
|
self.step_num = 0
|
||||||
Args:
|
self.last_save_step = 0
|
||||||
log_dir: Directory to save log files. If None, logs won't be saved to file.
|
self.save_interval = save_interval
|
||||||
log_interval: Log every N steps
|
|
||||||
metrics: List of metrics to log. Supported: ['loss', 'lr', 'grad_norm', 'grad_std',
|
|
||||||
grad_max', 'grad_min', 'grad_mean', 'grad_nan_num']
|
|
||||||
custom_handlers: List of custom log handler functions
|
|
||||||
json_log: Whether to save logs in JSON format
|
|
||||||
"""
|
|
||||||
|
|
||||||
self.log_dir = Path(log_dir) if log_dir else Path(os.getcwd()) / "logs"
|
|
||||||
self.log_interval = log_interval
|
self.log_interval = log_interval
|
||||||
self.metrics = metrics or ['loss', 'lr']
|
self.metrics = metrics or ['loss', 'lr']
|
||||||
self.step_num = 0
|
|
||||||
|
|
||||||
|
self.log_dir = Path(log_dir) if log_dir else Path.cwd() / "logs"
|
||||||
self.log_dir.mkdir(parents=True, exist_ok=True)
|
self.log_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
def _handle_info(self, trainer: 'Trainer', context: 'TrainContext'):
|
|
||||||
""" Logs training information to console and file. """
|
|
||||||
|
|
||||||
log_data = {
|
self.log_cache = []
|
||||||
|
|
||||||
|
self._metric_funcs = {
|
||||||
|
'loss': ctx_get_loss,
|
||||||
|
'lr': ctx_get_lr,
|
||||||
|
'grad_norm': ctx_get_grad_norm,
|
||||||
|
'grad_std': ctx_get_grad_std,
|
||||||
|
'grad_max': ctx_get_grad_max,
|
||||||
|
'grad_min': ctx_get_grad_min,
|
||||||
|
'grad_mean': ctx_get_grad_mean,
|
||||||
|
'grad_nan_num': ctx_get_grad_nan_num
|
||||||
|
}
|
||||||
|
|
||||||
|
def _get_log_data(self, context: TrainContext):
|
||||||
|
return {
|
||||||
"timestamp": time.strftime('%Y-%m-%d %H:%M:%S'),
|
"timestamp": time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||||
"epoch": context.epoch,
|
"epoch": context.epoch,
|
||||||
"iter": context.batch_iter,
|
"iter": context.iteration,
|
||||||
"metrics": self.metrics,
|
**{m: self._metric_funcs[m](context) for m in self.metrics}
|
||||||
}
|
}
|
||||||
|
|
||||||
for metric in self.metrics:
|
|
||||||
if metric == 'loss':
|
|
||||||
log_data[metric] = context.loss
|
|
||||||
elif metric == 'lr':
|
|
||||||
log_data[metric] = context.optimizer.param_groups[-1]['lr']
|
|
||||||
elif metric == 'grad_norm':
|
|
||||||
log_data[metric] = grad_norm(trainer.parameter.model)
|
|
||||||
elif metric == 'grad_std':
|
|
||||||
log_data[metric] = grad_std(trainer.parameter.model)
|
|
||||||
elif metric == 'grad_max':
|
|
||||||
log_data[metric] = grad_max(trainer.parameter.model)
|
|
||||||
elif metric == 'grad_min':
|
|
||||||
log_data[metric] = grad_min(trainer.parameter.model)
|
|
||||||
elif metric == 'grad_mean':
|
|
||||||
log_data[metric] = grad_mean(trainer.parameter.model)
|
|
||||||
elif metric == 'grad_nan_num':
|
|
||||||
log_data[metric] = grad_nan_num(trainer.parameter.model)
|
|
||||||
else:
|
|
||||||
raise ValueError(f"Invalid metric: {metric}")
|
|
||||||
|
|
||||||
return log_data
|
|
||||||
|
|
||||||
def _handle_log(self, trainer: 'Trainer', context: 'TrainContext'):
|
@only_on_rank(0)
|
||||||
""" Logs training information to console and file. """
|
def _add_log(self, log_data):
|
||||||
log_data = self._handle_info(trainer, context)
|
self.log_cache.append(log_data)
|
||||||
try:
|
|
||||||
log_file = self.log_dir / f"log_epoch_{context.epoch}_iter_{context.batch_iter}.json"
|
|
||||||
with open(log_file, 'a') as f:
|
|
||||||
json.dump(log_data, f, indent=4)
|
|
||||||
except Exception:
|
|
||||||
raise
|
|
||||||
|
|
||||||
def on_step_end(self, trainer: 'Trainer', context: 'TrainContext'):
|
@only_on_rank(0)
|
||||||
|
def _save_log(self, epoch, iter):
|
||||||
|
log_file = self.log_dir / f"epoch_{epoch}_iter_{iter}_metric.jsonl"
|
||||||
|
|
||||||
|
with open(log_file, 'w') as f:
|
||||||
|
for log in self.log_cache:
|
||||||
|
f.write(json.dumps(log) + '\n')
|
||||||
|
|
||||||
|
def on_batch_end(self, context):
|
||||||
if self.step_num % self.log_interval == 0:
|
if self.step_num % self.log_interval == 0:
|
||||||
self._handle_log(trainer, context)
|
log_data = self._get_log_data(context)
|
||||||
|
self._add_log(log_data)
|
||||||
|
|
||||||
self.step_num += 1
|
if self.step_num - self.last_save_step >= self.save_interval:
|
||||||
|
self._save_log(context.epoch, context.iteration)
|
||||||
|
self.last_save_step = self.step_num
|
||||||
|
|
||||||
|
self.step_num += 1
|
||||||
|
|
||||||
|
def on_train_end(self, context):
|
||||||
|
self._save_log(context.epoch, context.iteration)
|
||||||
|
|
||||||
|
def on_error(self, context):
|
||||||
|
self._save_log(context.epoch, context.iteration)
|
||||||
|
|
||||||
@@ -1,105 +1,99 @@
|
|||||||
from dataclasses import dataclass, field, fields
|
import torch.nn as nn
|
||||||
from typing import Optional, Self, TYPE_CHECKING
|
|
||||||
from torch.optim import Optimizer
|
from torch.optim import Optimizer
|
||||||
|
from torch.optim.lr_scheduler import LRScheduler
|
||||||
from torch.utils.data import DataLoader
|
from torch.utils.data import DataLoader
|
||||||
from khaosz.config import Checkpoint
|
|
||||||
from khaosz.data import ResumeableRandomSampler
|
|
||||||
from khaosz.trainer.schedule import BaseScheduler, SchedulerFactory
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
from khaosz.data import ResumableDistributedSampler
|
||||||
from khaosz.trainer.trainer import Trainer
|
from khaosz.data.checkpoint import Checkpoint
|
||||||
|
from khaosz.trainer.strategy import StrategyFactory, BaseStrategy
|
||||||
|
from khaosz.config.train_config import TrainConfig
|
||||||
|
from khaosz.parallel.setup import get_current_device, get_world_size, get_rank
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Optional, Self
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class TrainContext:
|
class TrainContext:
|
||||||
|
model: nn.Module = field(default=None)
|
||||||
|
strategy: BaseStrategy = field(default=None)
|
||||||
dataloader: DataLoader = field(default=None)
|
dataloader: DataLoader = field(default=None)
|
||||||
optimizer: Optimizer = field(default=None)
|
optimizer: Optimizer = field(default=None)
|
||||||
scheduler: BaseScheduler = field(default=None)
|
scheduler: LRScheduler = field(default=None)
|
||||||
checkpoint: Checkpoint = field(default=None)
|
checkpoint: Checkpoint = field(default=None)
|
||||||
|
|
||||||
epoch: int = field(default=0)
|
epoch: int = field(default=0)
|
||||||
batch_iter: int = field(default=0)
|
iteration: int = field(default=0)
|
||||||
loss: float = field(default=0.0)
|
loss: float = field(default=0.0)
|
||||||
|
|
||||||
def asdict(self) -> dict:
|
world_size: int = field(default=1)
|
||||||
return {field.name: getattr(self, field.name)
|
rank: int = field(default=0)
|
||||||
for field in fields(self)}
|
kwargs: dict = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
class TrainContextBuilder:
|
class TrainContextBuilder:
|
||||||
def __init__(self, trainer: 'Trainer'):
|
def __init__(self, config: TrainConfig):
|
||||||
self.trainer = trainer
|
self.config = config
|
||||||
self._context: TrainContext = None
|
self._context = TrainContext(
|
||||||
|
model=config.model,
|
||||||
|
world_size=get_world_size(),
|
||||||
|
rank=get_rank(),
|
||||||
|
)
|
||||||
|
|
||||||
|
device = get_current_device()
|
||||||
|
self._context.model = self._context.model.to(device=device)
|
||||||
|
|
||||||
|
if self.config.nprocs > 1:
|
||||||
|
fn = self.config.parallel_wrapper
|
||||||
|
self._context.model = fn(self._context.model)
|
||||||
|
|
||||||
|
self._context.optimizer = self.config.optimizer_fn(self._context.model)
|
||||||
|
self._context.scheduler = self.config.scheduler_fn(self._context.optimizer)
|
||||||
|
|
||||||
def with_checkpoint(self, checkpoint: Optional[Checkpoint]) -> Self:
|
def with_checkpoint(self, checkpoint: Optional[Checkpoint]) -> Self:
|
||||||
self._context = TrainContext()
|
|
||||||
if checkpoint is None:
|
if checkpoint is None:
|
||||||
checkpoint = Checkpoint(
|
checkpoint = Checkpoint(
|
||||||
model=self.trainer.parameter.model,
|
state_dict=self._context.model.state_dict(),
|
||||||
tokenizer=self.trainer.parameter.tokenizer,
|
|
||||||
config=self.trainer.parameter.config,
|
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# resume from the assigned checkpoint or assigned iteration
|
# resume from the assigned checkpoint or assigned iteration
|
||||||
self._context.epoch = max(checkpoint.epoch, self.trainer.train_config.start_epoch)
|
self._context.epoch = max(checkpoint.epoch, self.config.start_epoch)
|
||||||
self._context.batch_iter = max(checkpoint.batch_iter, self.trainer.train_config.start_batch)
|
self._context.iteration = max(checkpoint.iteration, self.config.start_batch)
|
||||||
|
self._context.model.load_state_dict(checkpoint.state_dict)
|
||||||
|
|
||||||
self._context.checkpoint = checkpoint
|
self._context.checkpoint = checkpoint
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def with_optimizer(self) -> Self:
|
|
||||||
if self._context is None:
|
|
||||||
raise RuntimeError("Must call with_checkpoint() before with_optimizer()")
|
|
||||||
|
|
||||||
optimizer = self.trainer.train_config.optimizer
|
|
||||||
|
|
||||||
if self._context.checkpoint and self._context.checkpoint.optimizer_state:
|
|
||||||
optimizer.load_state_dict(self._context.checkpoint.optimizer_state)
|
|
||||||
|
|
||||||
self._context.optimizer = optimizer
|
|
||||||
|
|
||||||
if self._context.checkpoint:
|
|
||||||
self._context.checkpoint.optimizer_state = optimizer.state_dict()
|
|
||||||
|
|
||||||
return self
|
|
||||||
|
|
||||||
def with_scheduler(self) -> Self:
|
|
||||||
if not hasattr(self._context, 'optimizer') or self._context.optimizer is None:
|
|
||||||
raise RuntimeError("Must call with_optimizer() before with_scheduler()")
|
|
||||||
|
|
||||||
optimizer = self.trainer.train_config.optimizer
|
|
||||||
schedule_config = self.trainer.schedule_config
|
|
||||||
scheduler = SchedulerFactory.load_scheduler(optimizer, schedule_config)
|
|
||||||
|
|
||||||
if self._context.checkpoint and self._context.checkpoint.scheduler_state:
|
|
||||||
scheduler.load_state_dict(self._context.checkpoint.scheduler_state)
|
|
||||||
|
|
||||||
self._context.scheduler = scheduler
|
|
||||||
|
|
||||||
if self._context.checkpoint:
|
|
||||||
self._context.checkpoint.scheduler_state = scheduler.state_dict()
|
|
||||||
|
|
||||||
return self
|
|
||||||
|
|
||||||
def with_dataloader(self) -> Self:
|
def with_dataloader(self) -> Self:
|
||||||
# fix: change batch level batch_iter to sample level offset
|
# fix: change batch level iteration to sample level offset
|
||||||
sampler_offset = self._context.batch_iter * self.trainer.train_config.batch_size
|
config = self.config
|
||||||
resumeable_sampler = ResumeableRandomSampler(
|
sampler_offset = self._context.iteration * config.batch_size
|
||||||
data_source=self.trainer.train_config.dataset,
|
resumeable_sampler = ResumableDistributedSampler(
|
||||||
|
data_source=config.dataset,
|
||||||
start_epoch=self._context.epoch,
|
start_epoch=self._context.epoch,
|
||||||
start_iter=sampler_offset,
|
start_iter=sampler_offset,
|
||||||
seed=self.trainer.train_config.random_seed
|
seed=config.random_seed
|
||||||
)
|
)
|
||||||
|
|
||||||
dataloader = DataLoader(
|
dataloader = DataLoader(
|
||||||
self.trainer.train_config.dataset,
|
config.dataset,
|
||||||
batch_size=self.trainer.train_config.batch_size,
|
batch_size=config.batch_size,
|
||||||
sampler=resumeable_sampler,
|
sampler=resumeable_sampler,
|
||||||
num_workers=self.trainer.train_config.num_workers,
|
num_workers=config.num_workers,
|
||||||
pin_memory=self.trainer.train_config.pin_memory,
|
pin_memory=config.pin_memory,
|
||||||
prefetch_factor=self.trainer.train_config.prefetch_factor
|
prefetch_factor=config.prefetch_factor
|
||||||
)
|
)
|
||||||
self._context.dataloader = dataloader
|
self._context.dataloader = dataloader
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
def with_strategy(self) -> Self:
|
||||||
|
self._context.strategy = StrategyFactory.load(
|
||||||
|
model=self.config.model,
|
||||||
|
train_type=self.config.strategy,
|
||||||
|
device=get_current_device(),
|
||||||
|
**self.config.extra_kwargs
|
||||||
|
)
|
||||||
|
return self
|
||||||
|
|
||||||
def build(self) -> TrainContext:
|
def build(self) -> TrainContext:
|
||||||
return self._context
|
return self._context
|
||||||
+39
-32
@@ -1,19 +1,17 @@
|
|||||||
import logging
|
import logging
|
||||||
from typing import Optional, List
|
from typing import Optional, List
|
||||||
from khaosz.config import (
|
from khaosz.config import TrainConfig
|
||||||
ModelParameter,
|
|
||||||
Checkpoint,
|
|
||||||
ScheduleConfig,
|
|
||||||
TrainConfig
|
|
||||||
)
|
|
||||||
from khaosz.trainer.train_callback import (
|
from khaosz.trainer.train_callback import (
|
||||||
TrainCallback,
|
TrainCallback,
|
||||||
ProgressBarCallback,
|
ProgressBarCallback,
|
||||||
CheckpointCallback,
|
CheckpointCallback,
|
||||||
|
MetricLoggerCallback,
|
||||||
GradientClippingCallback,
|
GradientClippingCallback,
|
||||||
SchedulerCallback
|
SchedulerCallback
|
||||||
)
|
)
|
||||||
from khaosz.trainer.train_context import TrainContext, TrainContextBuilder
|
from khaosz.trainer.train_context import TrainContext, TrainContextBuilder
|
||||||
|
from khaosz.data.checkpoint import Checkpoint
|
||||||
|
from khaosz.parallel.setup import spawn_parallel_fn
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -21,66 +19,76 @@ logger = logging.getLogger(__name__)
|
|||||||
class Trainer:
|
class Trainer:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
parameter: ModelParameter,
|
|
||||||
train_config: TrainConfig,
|
train_config: TrainConfig,
|
||||||
schedule_config: ScheduleConfig,
|
|
||||||
callbacks: Optional[List[TrainCallback]] = None
|
callbacks: Optional[List[TrainCallback]] = None
|
||||||
):
|
):
|
||||||
self.parameter = parameter
|
|
||||||
self.train_config = train_config
|
self.train_config = train_config
|
||||||
self.schedule_config = schedule_config
|
default_callbacks = self._get_default_callbacks()
|
||||||
self.callbacks = callbacks or self._get_default_callbacks()
|
self.callbacks = default_callbacks + callbacks if callbacks else default_callbacks
|
||||||
|
|
||||||
def _get_default_callbacks(self) -> List[TrainCallback]:
|
def _get_default_callbacks(self) -> List[TrainCallback]:
|
||||||
|
train_config = self.train_config
|
||||||
return [
|
return [
|
||||||
ProgressBarCallback(),
|
ProgressBarCallback(train_config.n_epoch),
|
||||||
CheckpointCallback(self.train_config.checkpoint_interval),
|
CheckpointCallback(train_config.checkpoint_dir, train_config.checkpoint_interval),
|
||||||
GradientClippingCallback(self.train_config.max_grad_norm),
|
MetricLoggerCallback(train_config.checkpoint_dir, train_config.checkpoint_interval),
|
||||||
SchedulerCallback(self.schedule_config),
|
GradientClippingCallback(train_config.max_grad_norm),
|
||||||
|
SchedulerCallback(),
|
||||||
]
|
]
|
||||||
|
|
||||||
def _build_context(self, checkpoint: Optional[Checkpoint]) -> TrainContext:
|
def _build_context(self, checkpoint: Optional[Checkpoint]) -> TrainContext:
|
||||||
return (TrainContextBuilder(self)
|
return (TrainContextBuilder(self.train_config)
|
||||||
.with_checkpoint(checkpoint)
|
.with_checkpoint(checkpoint)
|
||||||
.with_optimizer()
|
|
||||||
.with_scheduler()
|
|
||||||
.with_dataloader()
|
.with_dataloader()
|
||||||
|
.with_strategy()
|
||||||
.build())
|
.build())
|
||||||
|
|
||||||
def _call_callbacks(self, method_name: str, context: TrainContext):
|
def _call_callbacks(self, method_name: str, context: TrainContext):
|
||||||
for callback in self.callbacks:
|
for callback in self.callbacks:
|
||||||
method = getattr(callback, method_name, None)
|
method = getattr(callback, method_name, None)
|
||||||
if method:
|
if method:
|
||||||
method(self, context)
|
method(context)
|
||||||
|
|
||||||
|
def train(self, checkpoint: Optional[Checkpoint] = None):
|
||||||
|
config = self.train_config
|
||||||
|
spawn_parallel_fn(
|
||||||
|
self._train_impl,
|
||||||
|
backend=config.backend,
|
||||||
|
world_size=config.nprocs,
|
||||||
|
master_addr=config.master_addr,
|
||||||
|
master_port=config.master_port,
|
||||||
|
checkpoint=checkpoint
|
||||||
|
)
|
||||||
|
|
||||||
def train(self, checkpoint: Optional[Checkpoint] = None) -> Checkpoint:
|
def _train_impl(self, checkpoint: Optional[Checkpoint] = None) -> Checkpoint:
|
||||||
context = self._build_context(checkpoint)
|
context = self._build_context(checkpoint)
|
||||||
self._call_callbacks('on_train_begin', context)
|
self._call_callbacks('on_train_begin', context)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.parameter.model.train()
|
context.model.train()
|
||||||
# 1.epoch
|
# 1.epoch
|
||||||
for epoch in range(context.epoch, self.train_config.n_epoch):
|
for epoch in range(context.epoch, self.train_config.n_epoch):
|
||||||
context.epoch = epoch
|
context.epoch = epoch
|
||||||
self._call_callbacks('on_epoch_begin', context)
|
self._call_callbacks('on_epoch_begin', context)
|
||||||
|
|
||||||
for batch in context.dataloader:
|
for batch in context.dataloader:
|
||||||
if context.batch_iter % self.train_config.accumulation_steps == 0:
|
if context.iteration % self.train_config.accumulation_steps == 0:
|
||||||
# 2. step
|
# 2. step
|
||||||
self._call_callbacks('on_step_begin', context)
|
self._call_callbacks('on_step_begin', context)
|
||||||
self.train_config.optimizer.step()
|
context.optimizer.step()
|
||||||
self.train_config.optimizer.zero_grad()
|
context.optimizer.zero_grad()
|
||||||
self._call_callbacks('on_step_end', context)
|
self._call_callbacks('on_step_end', context)
|
||||||
|
|
||||||
# 3. batch
|
# 3. batch
|
||||||
self._call_callbacks('on_batch_begin', context)
|
self._call_callbacks('on_batch_begin', context)
|
||||||
loss = self.train_config.strategy(batch)
|
loss = context.strategy(batch)
|
||||||
context.loss = loss.item()
|
context.loss = loss.item()
|
||||||
context.batch_iter += 1
|
context.iteration += 1
|
||||||
|
|
||||||
# to make the loss normalized by accumulation steps
|
# to make the loss normalized by accumulation steps
|
||||||
normalized_loss = loss / self.train_config.accumulation_steps
|
stand_batch = self.train_config.accumulation_steps * self.train_config.nprocs
|
||||||
normalized_loss.backward()
|
stand_loss = loss / stand_batch
|
||||||
|
stand_loss.backward()
|
||||||
|
|
||||||
self._call_callbacks('on_batch_end', context)
|
self._call_callbacks('on_batch_end', context)
|
||||||
|
|
||||||
@@ -91,5 +99,4 @@ class Trainer:
|
|||||||
self._call_callbacks('on_error', context)
|
self._call_callbacks('on_error', context)
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
self._call_callbacks('on_train_end', context)
|
self._call_callbacks('on_train_end', context)
|
||||||
return context.checkpoint
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# init file
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=64", "wheel"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
dynamic = ["version"]
|
||||||
|
name = "khaosz"
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.12"
|
||||||
|
dependencies = [
|
||||||
|
"h5py==3.15.1",
|
||||||
|
"numpy==2.3.2",
|
||||||
|
"torch==2.7.1",
|
||||||
|
"tokenizers==0.21.4",
|
||||||
|
"tqdm==4.67.1",
|
||||||
|
"safetensors==0.5.3",
|
||||||
|
"huggingface-hub==0.34.3",
|
||||||
|
"pytest==9.0.2"
|
||||||
|
]
|
||||||
|
keywords = ["nlp", "datasets", "language-models", "machine-learning"]
|
||||||
|
license = { text = "GPL-3.0" }
|
||||||
|
classifiers = [
|
||||||
|
"Programming Language :: Python :: 3",
|
||||||
|
"License :: OSI Approved :: GPL-3.0",
|
||||||
|
"Operating System :: OS Independent",
|
||||||
|
]
|
||||||
|
urls = { Homepage = "https://github.com/khaosz/khaosz" }
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
where = ["."]
|
||||||
|
|
||||||
|
[tool.pip]
|
||||||
|
extra-index-url = "https://download.pytorch.org/whl/cu126"
|
||||||
|
|
||||||
|
[tool.setuptools.dynamic]
|
||||||
|
version = { attr = "khaosz.__version__" }
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
# python=3.12
|
|
||||||
--extra-index-url https://download.pytorch.org/whl/cu126
|
|
||||||
|
|
||||||
certifi==2025.8.3
|
|
||||||
charset-normalizer==3.4.2
|
|
||||||
colorama==0.4.6
|
|
||||||
contourpy==1.3.3
|
|
||||||
cycler==0.12.1
|
|
||||||
filelock==3.13.1
|
|
||||||
fonttools==4.59.0
|
|
||||||
fsspec==2024.6.1
|
|
||||||
huggingface-hub==0.34.3
|
|
||||||
idna==3.10
|
|
||||||
Jinja2==3.1.6
|
|
||||||
kiwisolver==1.4.8
|
|
||||||
MarkupSafe==2.1.5
|
|
||||||
matplotlib==3.10.5
|
|
||||||
mpmath==1.3.0
|
|
||||||
networkx==3.3
|
|
||||||
numpy==2.3.2
|
|
||||||
packaging==25.0
|
|
||||||
pillow==11.3.0
|
|
||||||
pyparsing==3.2.3
|
|
||||||
python-dateutil==2.9.0.post0
|
|
||||||
PyYAML==6.0.2
|
|
||||||
requests==2.32.4
|
|
||||||
safetensors==0.5.3
|
|
||||||
setuptools==78.1.1
|
|
||||||
six==1.17.0
|
|
||||||
sympy==1.13.3
|
|
||||||
tokenizers==0.21.4
|
|
||||||
torch==2.7.1+cu126
|
|
||||||
tqdm==4.67.1
|
|
||||||
typing_extensions==4.12.2
|
|
||||||
urllib3==2.5.0
|
|
||||||
wheel==0.45.1
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
import re
|
|
||||||
import khaosz
|
|
||||||
from setuptools import find_packages, setup
|
|
||||||
|
|
||||||
|
|
||||||
with open("requirements.txt") as f:
|
|
||||||
required = [line for line in f.read().splitlines()
|
|
||||||
if line and re.match(r'^[^=]+==[^=]+$', line.strip())]
|
|
||||||
|
|
||||||
setup(
|
|
||||||
name="khaosz",
|
|
||||||
version=khaosz.__version__,
|
|
||||||
packages=find_packages(),
|
|
||||||
install_requires=required,
|
|
||||||
dependency_links=[
|
|
||||||
"https://download.pytorch.org/whl/cu126",
|
|
||||||
],
|
|
||||||
python_requires=">=3.12",
|
|
||||||
)
|
|
||||||
+12
-17
@@ -4,19 +4,14 @@ import numpy as np
|
|||||||
import tempfile
|
import tempfile
|
||||||
import shutil
|
import shutil
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
import matplotlib
|
|
||||||
from torch.utils.data import Dataset
|
|
||||||
|
|
||||||
|
from torch.utils.data import Dataset
|
||||||
from khaosz.config.model_config import ModelConfig
|
from khaosz.config.model_config import ModelConfig
|
||||||
from khaosz.data.tokenizer import BpeTokenizer
|
from khaosz.data.tokenizer import BpeTokenizer
|
||||||
from khaosz.model.transformer import Transformer
|
from khaosz.model.transformer import Transformer
|
||||||
|
|
||||||
|
|
||||||
matplotlib.use("Agg")
|
|
||||||
|
|
||||||
|
|
||||||
class RandomDataset(Dataset):
|
class RandomDataset(Dataset):
|
||||||
def __init__(self, length=None, max_length=64, vocab_size=1000):
|
def __init__(self, length=None, max_length=64, vocab_size=1000):
|
||||||
self.length = length or int(np.random.randint(100, 200))
|
self.length = length or int(np.random.randint(100, 200))
|
||||||
@@ -83,19 +78,19 @@ def base_test_env(request: pytest.FixtureRequest):
|
|||||||
n_dim_choices = [8, 16, 32]
|
n_dim_choices = [8, 16, 32]
|
||||||
n_head_choices = [2, 4]
|
n_head_choices = [2, 4]
|
||||||
|
|
||||||
n_dim = int(np.random.choice(n_dim_choices))
|
dim = int(np.random.choice(n_dim_choices))
|
||||||
n_head = int(np.random.choice(n_head_choices))
|
n_heads = int(np.random.choice(n_head_choices))
|
||||||
n_kvhead = n_head // 2
|
n_kv_heads = n_heads // 2
|
||||||
d_ffn = n_dim * 2
|
dim_ffn = dim * 2
|
||||||
|
|
||||||
config = {
|
config = {
|
||||||
"vocab_size": 1000,
|
"vocab_size": 1000,
|
||||||
"n_dim": n_dim,
|
"dim": dim,
|
||||||
"n_head": n_head,
|
"n_heads": n_heads,
|
||||||
"n_kvhead": n_kvhead,
|
"n_kv_heads": n_kv_heads,
|
||||||
"d_ffn": d_ffn,
|
"dim_ffn": dim_ffn,
|
||||||
"m_len": 1024,
|
"max_len": 1024,
|
||||||
"n_layer": 4,
|
"n_layers": 4,
|
||||||
"norm_eps": 1e-5
|
"norm_eps": 1e-5
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -108,7 +103,7 @@ def base_test_env(request: pytest.FixtureRequest):
|
|||||||
|
|
||||||
yield {
|
yield {
|
||||||
"device": device,
|
"device": device,
|
||||||
"test_dir": test_dir,
|
"test_dir": str(test_dir),
|
||||||
"config_path": config_path,
|
"config_path": config_path,
|
||||||
"transformer_config": transformer_config,
|
"transformer_config": transformer_config,
|
||||||
"model": model,
|
"model": model,
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import torch
|
||||||
|
import tempfile
|
||||||
|
import torch.distributed as dist
|
||||||
|
|
||||||
|
from torch.optim import AdamW
|
||||||
|
from torch.optim.lr_scheduler import CosineAnnealingLR
|
||||||
|
from khaosz.data.checkpoint import Checkpoint
|
||||||
|
from khaosz.parallel.setup import get_rank, spawn_parallel_fn
|
||||||
|
|
||||||
|
def test_single_process():
|
||||||
|
model = torch.nn.Linear(10, 5)
|
||||||
|
optimizer = AdamW(model.parameters(), lr=1e-3)
|
||||||
|
scheduler = CosineAnnealingLR(optimizer, T_max=10)
|
||||||
|
|
||||||
|
for epoch in range(3):
|
||||||
|
for iteration in range(10):
|
||||||
|
|
||||||
|
x = torch.randn(32, 10)
|
||||||
|
y = torch.randn(32, 5)
|
||||||
|
loss = model(x).mean()
|
||||||
|
loss.backward()
|
||||||
|
optimizer.step()
|
||||||
|
optimizer.zero_grad()
|
||||||
|
|
||||||
|
scheduler.step()
|
||||||
|
|
||||||
|
checkpoint = Checkpoint(
|
||||||
|
state_dict=model.state_dict(),
|
||||||
|
epoch=3,
|
||||||
|
iteration=30
|
||||||
|
)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
checkpoint.save(tmpdir)
|
||||||
|
|
||||||
|
loaded_checkpoint = Checkpoint.load(tmpdir)
|
||||||
|
|
||||||
|
assert loaded_checkpoint.epoch == 3
|
||||||
|
assert loaded_checkpoint.iteration == 30
|
||||||
|
def simple_training():
|
||||||
|
model = torch.nn.Linear(10, 5)
|
||||||
|
optimizer = AdamW(model.parameters(), lr=1e-3)
|
||||||
|
scheduler = CosineAnnealingLR(optimizer, T_max=10)
|
||||||
|
|
||||||
|
for epoch in range(2):
|
||||||
|
for iteration in range(5):
|
||||||
|
x = torch.randn(16, 10)
|
||||||
|
y = torch.randn(16, 5)
|
||||||
|
loss = model(x).mean()
|
||||||
|
loss.backward()
|
||||||
|
optimizer.step()
|
||||||
|
optimizer.zero_grad()
|
||||||
|
scheduler.step()
|
||||||
|
|
||||||
|
checkpoint = Checkpoint(
|
||||||
|
state_dict=model.state_dict(),
|
||||||
|
epoch=2,
|
||||||
|
iteration=10,
|
||||||
|
)
|
||||||
|
|
||||||
|
rank = get_rank()
|
||||||
|
|
||||||
|
if rank == 0:
|
||||||
|
shared_dir = tempfile.mkdtemp()
|
||||||
|
checkpoint.save(shared_dir)
|
||||||
|
else:
|
||||||
|
shared_dir = None
|
||||||
|
|
||||||
|
|
||||||
|
if dist.is_initialized():
|
||||||
|
dir_list = [shared_dir]
|
||||||
|
dist.broadcast_object_list(dir_list, src=0)
|
||||||
|
shared_dir = dir_list[0]
|
||||||
|
|
||||||
|
|
||||||
|
loaded = Checkpoint.load(shared_dir)
|
||||||
|
assert loaded.epoch == 2
|
||||||
|
|
||||||
|
def test_multi_process():
|
||||||
|
spawn_parallel_fn(
|
||||||
|
simple_training,
|
||||||
|
world_size=2,
|
||||||
|
backend="gloo"
|
||||||
|
)
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import torch
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from khaosz.data.file import save_h5
|
||||||
|
from khaosz.data.dataset import *
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_dataset_loader_random_paths(base_test_env):
|
||||||
|
"""Test dataset loader with multiple random paths"""
|
||||||
|
test_dir = base_test_env["test_dir"]
|
||||||
|
|
||||||
|
# Create multiple mmap dataset directories with random data
|
||||||
|
num_files = np.random.randint(2, 5)
|
||||||
|
|
||||||
|
for i in range(num_files):
|
||||||
|
seq_length = np.random.randint(200, 400)
|
||||||
|
dummy_data = {
|
||||||
|
"sequence": [torch.randint(0, 1000, (seq_length,), dtype=torch.int64) for _ in range(10)],
|
||||||
|
}
|
||||||
|
save_h5(test_dir, f"data_{i}", dummy_data)
|
||||||
|
|
||||||
|
# Test loading with multiple paths
|
||||||
|
loaded_dataset = DatasetLoader.load(
|
||||||
|
train_type="seq",
|
||||||
|
load_path=test_dir,
|
||||||
|
window_size=64,
|
||||||
|
)
|
||||||
|
assert loaded_dataset is not None
|
||||||
|
assert len(loaded_dataset) > 0
|
||||||
|
|
||||||
|
# Test that we can get items without errors
|
||||||
|
for i in range(len(loaded_dataset)):
|
||||||
|
item = loaded_dataset[i]
|
||||||
|
assert "input_ids" in item
|
||||||
|
assert "target_ids" in item
|
||||||
|
assert item["input_ids"].shape == item["target_ids"].shape
|
||||||
|
assert item["input_ids"].shape[0] == 64
|
||||||
|
|
||||||
|
|
||||||
|
def test_dpo_strategy_with_random_data(base_test_env):
|
||||||
|
"""Test DPO strategy with randomized preference data"""
|
||||||
|
test_dir = base_test_env["test_dir"]
|
||||||
|
|
||||||
|
# Create DPO-style data with memory mapping format
|
||||||
|
seq_length = np.random.randint(100, 200)
|
||||||
|
|
||||||
|
dummy_data = {
|
||||||
|
"chosen": [torch.randint(0, 1000, (seq_length,), dtype=torch.int64)],
|
||||||
|
"rejected": [torch.randint(0, 1000, (seq_length,), dtype=torch.int64)],
|
||||||
|
"chosen_mask": [torch.ones(seq_length, dtype=torch.bool)],
|
||||||
|
"rejected_mask": [torch.ones(seq_length, dtype=torch.bool)]
|
||||||
|
}
|
||||||
|
|
||||||
|
save_h5(test_dir, "dpo_data", dummy_data)
|
||||||
|
|
||||||
|
# Load DPO dataset
|
||||||
|
dpo_dataset = DatasetLoader.load(
|
||||||
|
train_type="dpo",
|
||||||
|
load_path=test_dir,
|
||||||
|
window_size=64,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert dpo_dataset is not None
|
||||||
|
assert hasattr(dpo_dataset, 'fetcher')
|
||||||
|
assert len(dpo_dataset) > 0
|
||||||
|
|
||||||
|
# Test that we can get DPO items without errors
|
||||||
|
for i in range(min(3, len(dpo_dataset))):
|
||||||
|
item = dpo_dataset[i]
|
||||||
|
assert "chosen" in item
|
||||||
|
assert "rejected" in item
|
||||||
|
assert "chosen_mask" in item
|
||||||
|
assert "rejected_mask" in item
|
||||||
|
assert item["chosen"].shape == item["rejected"].shape
|
||||||
|
assert item["chosen_mask"].shape == item["rejected_mask"].shape
|
||||||
|
|
||||||
|
|
||||||
|
def test_sft_dataset_with_random_data(base_test_env):
|
||||||
|
"""Test SFT dataset with random data"""
|
||||||
|
test_dir = base_test_env["test_dir"]
|
||||||
|
|
||||||
|
# Create SFT-style data with memory mapping format
|
||||||
|
seq_length = np.random.randint(100, 200)
|
||||||
|
|
||||||
|
dummy_data = {
|
||||||
|
"sequence": [torch.randint(0, 1000, (seq_length,), dtype=torch.int64)],
|
||||||
|
"loss_mask": [torch.ones(seq_length, dtype=torch.bool)]
|
||||||
|
}
|
||||||
|
|
||||||
|
save_h5(test_dir, "sft_data", dummy_data)
|
||||||
|
|
||||||
|
# Load SFT dataset
|
||||||
|
sft_dataset = DatasetLoader.load(
|
||||||
|
train_type="sft",
|
||||||
|
load_path=test_dir,
|
||||||
|
window_size=64,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert sft_dataset is not None
|
||||||
|
assert hasattr(sft_dataset, 'fetcher')
|
||||||
|
assert len(sft_dataset) > 0
|
||||||
|
|
||||||
|
# Test that we can get SFT items without errors
|
||||||
|
for i in range(min(3, len(sft_dataset))):
|
||||||
|
item = sft_dataset[i]
|
||||||
|
assert "input_ids" in item
|
||||||
|
assert "target_ids" in item
|
||||||
|
assert "loss_mask" in item
|
||||||
|
assert item["input_ids"].shape == item["target_ids"].shape
|
||||||
|
assert item["loss_mask"].shape[0] == 64
|
||||||
|
|
||||||
|
|
||||||
|
def test_dataset_with_custom_stride(base_test_env):
|
||||||
|
"""Test dataset with custom stride parameter"""
|
||||||
|
test_dir = base_test_env["test_dir"]
|
||||||
|
|
||||||
|
# Create test data
|
||||||
|
seq_length = 200
|
||||||
|
dummy_data = {
|
||||||
|
"sequence": [torch.randint(0, 1000, (seq_length,), dtype=torch.int64)],
|
||||||
|
}
|
||||||
|
|
||||||
|
save_h5(test_dir,"stride_test_data", dummy_data)
|
||||||
|
|
||||||
|
# Test with custom stride
|
||||||
|
custom_stride = 32
|
||||||
|
dataset = DatasetLoader.load(
|
||||||
|
train_type="seq",
|
||||||
|
load_path=test_dir,
|
||||||
|
window_size=64,
|
||||||
|
stride=custom_stride
|
||||||
|
)
|
||||||
|
|
||||||
|
assert dataset is not None
|
||||||
|
assert len(dataset) > 0
|
||||||
|
|
||||||
|
# With stride 32 and window 64 on 200 length data, we should get more samples
|
||||||
|
# than with default stride (which equals window size)
|
||||||
|
default_stride_dataset = DatasetLoader.load(
|
||||||
|
train_type="seq",
|
||||||
|
load_path=test_dir,
|
||||||
|
window_size=64,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(dataset) > len(default_stride_dataset)
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
from khaosz.trainer import *
|
from khaosz.trainer import *
|
||||||
from khaosz.data.data_util import *
|
from khaosz.data import *
|
||||||
|
|
||||||
def test_random_sampler_consistency(random_dataset):
|
def test_random_sampler_consistency(random_dataset):
|
||||||
"""Test RandomSampler produces consistent results with same seed"""
|
"""Test RandomSampler produces consistent results with same seed"""
|
||||||
dataset = random_dataset
|
dataset = random_dataset
|
||||||
|
|
||||||
# Create two samplers with same seed
|
# Create two samplers with same seed
|
||||||
sampler1 = ResumeableRandomSampler(dataset, seed=42)
|
sampler1 = ResumableDistributedSampler(dataset, seed=42)
|
||||||
sampler2 = ResumeableRandomSampler(dataset, seed=42)
|
sampler2 = ResumableDistributedSampler(dataset, seed=42)
|
||||||
|
|
||||||
indices1 = list(iter(sampler1))
|
indices1 = list(iter(sampler1))
|
||||||
indices2 = list(iter(sampler2))
|
indices2 = list(iter(sampler2))
|
||||||
@@ -19,8 +19,8 @@ def test_random_sampler_different_seeds(random_dataset):
|
|||||||
dataset = random_dataset
|
dataset = random_dataset
|
||||||
|
|
||||||
# Create two samplers with different seeds
|
# Create two samplers with different seeds
|
||||||
sampler1 = ResumeableRandomSampler(dataset, seed=42)
|
sampler1 = ResumableDistributedSampler(dataset, seed=42)
|
||||||
sampler2 = ResumeableRandomSampler(dataset, seed=123)
|
sampler2 = ResumableDistributedSampler(dataset, seed=123)
|
||||||
|
|
||||||
indices1 = list(iter(sampler1))
|
indices1 = list(iter(sampler1))
|
||||||
indices2 = list(iter(sampler2))
|
indices2 = list(iter(sampler2))
|
||||||
@@ -34,7 +34,7 @@ def test_sampler_across_epochs(random_dataset):
|
|||||||
dataset = random_dataset
|
dataset = random_dataset
|
||||||
n = len(dataset)
|
n = len(dataset)
|
||||||
|
|
||||||
sampler = ResumeableRandomSampler(dataset, seed=42)
|
sampler = ResumableDistributedSampler(dataset, seed=42)
|
||||||
|
|
||||||
# Get indices for first epoch
|
# Get indices for first epoch
|
||||||
epoch1_indices = list(iter(sampler))
|
epoch1_indices = list(iter(sampler))
|
||||||
@@ -22,12 +22,12 @@ def test_env(request: pytest.FixtureRequest):
|
|||||||
|
|
||||||
config = {
|
config = {
|
||||||
"vocab_size": 1000,
|
"vocab_size": 1000,
|
||||||
"n_dim": 128,
|
"dim": 128,
|
||||||
"n_head": 4,
|
"n_heads": 4,
|
||||||
"n_kvhead": 2,
|
"n_kv_heads": 2,
|
||||||
"d_ffn": 256,
|
"dim_ffn": 256,
|
||||||
"m_len": 64,
|
"max_len": 64,
|
||||||
"n_layer": 2,
|
"n_layers": 2,
|
||||||
"norm_eps": 1e-5
|
"norm_eps": 1e-5
|
||||||
}
|
}
|
||||||
with open(config_path, 'w') as f:
|
with open(config_path, 'w') as f:
|
||||||
@@ -51,13 +51,6 @@ def test_env(request: pytest.FixtureRequest):
|
|||||||
|
|
||||||
shutil.rmtree(test_dir)
|
shutil.rmtree(test_dir)
|
||||||
|
|
||||||
# parameter loader
|
|
||||||
def test_parameter_loader(test_env):
|
|
||||||
loaded_param = ParameterLoader.load(test_env["test_dir"])
|
|
||||||
assert loaded_param.model is not None
|
|
||||||
assert loaded_param.tokenizer is not None
|
|
||||||
assert loaded_param.config == test_env["transformer_config"]
|
|
||||||
|
|
||||||
def test_model_parameter(test_env):
|
def test_model_parameter(test_env):
|
||||||
save_dir = os.path.join(test_env["test_dir"], "save")
|
save_dir = os.path.join(test_env["test_dir"], "save")
|
||||||
model_param = ModelParameter(test_env["model"],test_env["tokenizer"] , test_env["transformer_config"])
|
model_param = ModelParameter(test_env["model"],test_env["tokenizer"] , test_env["transformer_config"])
|
||||||
@@ -71,9 +64,9 @@ def test_model_parameter(test_env):
|
|||||||
def test_transformer(test_env):
|
def test_transformer(test_env):
|
||||||
model = test_env["model"]
|
model = test_env["model"]
|
||||||
input_ids = torch.randint(0, test_env["transformer_config"].vocab_size,
|
input_ids = torch.randint(0, test_env["transformer_config"].vocab_size,
|
||||||
(4, test_env["transformer_config"].m_len))
|
(4, test_env["transformer_config"].max_len))
|
||||||
output_logits = model(input_ids)["logits"]
|
output_logits = model(input_ids)["logits"]
|
||||||
target_shape = (4, test_env["transformer_config"].m_len, test_env["transformer_config"].vocab_size)
|
target_shape = (4, test_env["transformer_config"].max_len, test_env["transformer_config"].vocab_size)
|
||||||
assert output_logits.shape == target_shape
|
assert output_logits.shape == target_shape
|
||||||
|
|
||||||
# generator
|
# generator
|
||||||
@@ -87,7 +80,7 @@ def test_embedding_encoder_core(test_env):
|
|||||||
|
|
||||||
single_emb = encoder.encode("测试文本")
|
single_emb = encoder.encode("测试文本")
|
||||||
assert isinstance(single_emb, torch.Tensor)
|
assert isinstance(single_emb, torch.Tensor)
|
||||||
assert single_emb.shape[-1] == test_env["transformer_config"].n_dim
|
assert single_emb.shape[-1] == test_env["transformer_config"].dim
|
||||||
|
|
||||||
|
|
||||||
batch_emb = encoder.encode(["测试1", "测试2"])
|
batch_emb = encoder.encode(["测试1", "测试2"])
|
||||||
@@ -16,12 +16,12 @@ def transformer_test_env():
|
|||||||
|
|
||||||
config = {
|
config = {
|
||||||
"vocab_size": 1000,
|
"vocab_size": 1000,
|
||||||
"n_dim": 128,
|
"dim": 128,
|
||||||
"n_head": 4,
|
"n_heads": 4,
|
||||||
"n_kvhead": 2,
|
"n_kv_heads": 2,
|
||||||
"d_ffn": 256,
|
"dim_ffn": 256,
|
||||||
"m_len": 64,
|
"max_len": 64,
|
||||||
"n_layer": 2,
|
"n_layers": 2,
|
||||||
"norm_eps": 1e-5
|
"norm_eps": 1e-5
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,6 +77,11 @@ def test_tie_weight_init(transformer_test_env):
|
|||||||
assert not torch.equal(model.lm_head.weight, model.embed_tokens.weight)
|
assert not torch.equal(model.lm_head.weight, model.embed_tokens.weight)
|
||||||
assert model.lm_head.weight.data_ptr() != model.embed_tokens.weight.data_ptr()
|
assert model.lm_head.weight.data_ptr() != model.embed_tokens.weight.data_ptr()
|
||||||
|
|
||||||
|
original_weight = model.embed_tokens.weight.clone()
|
||||||
|
model.embed_tokens.weight.data[0, 0] = 100.0
|
||||||
|
|
||||||
|
assert not torch.equal(model.lm_head.weight, model.embed_tokens.weight)
|
||||||
|
assert not torch.equal(model.lm_head.weight, original_weight)
|
||||||
|
|
||||||
def test_model_save_load_with_tie_weight(transformer_test_env):
|
def test_model_save_load_with_tie_weight(transformer_test_env):
|
||||||
test_dir = transformer_test_env["test_dir"]
|
test_dir = transformer_test_env["test_dir"]
|
||||||
@@ -104,16 +109,11 @@ def test_model_save_load_with_tie_weight(transformer_test_env):
|
|||||||
assert model.lm_head.weight.data_ptr() == model.embed_tokens.weight.data_ptr()
|
assert model.lm_head.weight.data_ptr() == model.embed_tokens.weight.data_ptr()
|
||||||
assert "lm_head.weight" not in model.state_dict()
|
assert "lm_head.weight" not in model.state_dict()
|
||||||
|
|
||||||
# case 2: not tie weight
|
# case 2: not tie weight (form tie-weight state dict load)
|
||||||
config_data["tie_weight"] = False
|
config_data["tie_weight"] = False
|
||||||
with open(config_path, 'w') as f:
|
with open(config_path, 'w') as f:
|
||||||
json.dump(config_data, f)
|
json.dump(config_data, f)
|
||||||
|
|
||||||
config = ModelConfig().load(config_path)
|
|
||||||
original_model = Transformer(config)
|
|
||||||
|
|
||||||
st.save_file(original_model.state_dict(), model_path)
|
|
||||||
|
|
||||||
loaded_config = ModelConfig().load(config_path)
|
loaded_config = ModelConfig().load(config_path)
|
||||||
model = Transformer(loaded_config)
|
model = Transformer(loaded_config)
|
||||||
model.load_state_dict(st.load_file(model_path))
|
model.load_state_dict(st.load_file(model_path))
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
import os
|
|
||||||
import torch
|
|
||||||
import pickle
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
from khaosz.trainer import *
|
|
||||||
from khaosz.data.data_util import *
|
|
||||||
|
|
||||||
|
|
||||||
def test_dataset_loader_random_paths(base_test_env):
|
|
||||||
"""Test dataset loader with multiple random paths"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
|
||||||
|
|
||||||
# Create multiple pkl files with random data
|
|
||||||
num_files = np.random.randint(2, 5)
|
|
||||||
pkl_paths = []
|
|
||||||
|
|
||||||
for i in range(num_files):
|
|
||||||
pkl_path = os.path.join(test_dir, f"test_data_{i}.pkl")
|
|
||||||
seq_length = np.random.randint(50, 100)
|
|
||||||
dummy_data = {
|
|
||||||
"sequence": torch.randint(0, 1000, (seq_length,)),
|
|
||||||
"chosen": torch.randint(0, 1000, (seq_length,)),
|
|
||||||
"rejected": torch.randint(0, 1000, (seq_length,)),
|
|
||||||
"chosen_mask": torch.ones(seq_length, dtype=torch.bool),
|
|
||||||
"rejected_mask": torch.ones(seq_length, dtype=torch.bool)
|
|
||||||
}
|
|
||||||
with open(pkl_path, "wb") as f:
|
|
||||||
pickle.dump(dummy_data, f)
|
|
||||||
pkl_paths.append(pkl_path)
|
|
||||||
|
|
||||||
# Test loading with multiple paths
|
|
||||||
loaded_dataset = DatasetLoader.load(
|
|
||||||
train_type="seq",
|
|
||||||
load_path=pkl_paths,
|
|
||||||
window_size=64,
|
|
||||||
)
|
|
||||||
assert loaded_dataset is not None
|
|
||||||
assert len(loaded_dataset) > 0
|
|
||||||
|
|
||||||
def test_dpo_strategy_with_random_data(base_test_env):
|
|
||||||
"""Test DPO strategy with randomized preference data"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
|
||||||
|
|
||||||
# Create DPO-style data
|
|
||||||
pkl_path = os.path.join(test_dir, "dpo_data.pkl")
|
|
||||||
seq_length = np.random.randint(40, 80)
|
|
||||||
|
|
||||||
dummy_data = {
|
|
||||||
"chosen": torch.randint(0, 1000, (seq_length,)),
|
|
||||||
"rejected": torch.randint(0, 1000, (seq_length,)),
|
|
||||||
"chosen_mask": torch.ones(seq_length, dtype=torch.bool),
|
|
||||||
"rejected_mask": torch.ones(seq_length, dtype=torch.bool)
|
|
||||||
}
|
|
||||||
|
|
||||||
with open(pkl_path, "wb") as f:
|
|
||||||
pickle.dump(dummy_data, f)
|
|
||||||
|
|
||||||
# Load DPO dataset
|
|
||||||
dpo_dataset = DatasetLoader.load(
|
|
||||||
train_type="dpo",
|
|
||||||
load_path=pkl_path,
|
|
||||||
window_size=64,
|
|
||||||
)
|
|
||||||
|
|
||||||
assert dpo_dataset is not None
|
|
||||||
assert hasattr(dpo_dataset, 'fetcher')
|
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import torch
|
||||||
|
import torch.distributed as dist
|
||||||
|
|
||||||
|
from khaosz.parallel import (
|
||||||
|
get_rank,
|
||||||
|
only_on_rank,
|
||||||
|
spawn_parallel_fn
|
||||||
|
)
|
||||||
|
|
||||||
|
@only_on_rank(0)
|
||||||
|
def _test_only_on_rank_helper():
|
||||||
|
return True
|
||||||
|
|
||||||
|
def only_on_rank():
|
||||||
|
result = _test_only_on_rank_helper()
|
||||||
|
if get_rank() == 0:
|
||||||
|
assert result is True
|
||||||
|
else:
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
def all_reduce():
|
||||||
|
x = torch.tensor([get_rank()], dtype=torch.int)
|
||||||
|
dist.all_reduce(x, op=dist.ReduceOp.SUM)
|
||||||
|
expected_sum = sum(range(dist.get_world_size()))
|
||||||
|
assert x.item() == expected_sum
|
||||||
|
|
||||||
|
def test_spawn_only_on_rank():
|
||||||
|
spawn_parallel_fn(
|
||||||
|
only_on_rank,
|
||||||
|
world_size=2,
|
||||||
|
backend="gloo"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_spawn_all_reduce():
|
||||||
|
spawn_parallel_fn(
|
||||||
|
all_reduce,
|
||||||
|
world_size=2,
|
||||||
|
backend="gloo"
|
||||||
|
)
|
||||||
@@ -5,10 +5,20 @@ from khaosz.trainer import *
|
|||||||
|
|
||||||
def test_callback_integration(base_test_env, random_dataset):
|
def test_callback_integration(base_test_env, random_dataset):
|
||||||
"""Test that all callbacks are properly integrated"""
|
"""Test that all callbacks are properly integrated"""
|
||||||
optimizer = torch.optim.AdamW(base_test_env["model"].parameters())
|
schedule_config = CosineScheduleConfig(
|
||||||
|
warmup_steps=10,
|
||||||
|
total_steps=20
|
||||||
|
)
|
||||||
|
|
||||||
|
optimizer_fn = lambda model: torch.optim.AdamW(model.parameters())
|
||||||
|
scheduler_fn = lambda optim: SchedulerFactory.load(optim, schedule_config)
|
||||||
|
|
||||||
train_config = TrainConfig(
|
train_config = TrainConfig(
|
||||||
|
model=base_test_env["model"],
|
||||||
|
strategy='seq',
|
||||||
dataset=random_dataset,
|
dataset=random_dataset,
|
||||||
optimizer=optimizer,
|
optimizer_fn=optimizer_fn,
|
||||||
|
scheduler_fn=scheduler_fn,
|
||||||
checkpoint_dir=base_test_env["test_dir"],
|
checkpoint_dir=base_test_env["test_dir"],
|
||||||
n_epoch=1,
|
n_epoch=1,
|
||||||
batch_size=2,
|
batch_size=2,
|
||||||
@@ -18,36 +28,26 @@ def test_callback_integration(base_test_env, random_dataset):
|
|||||||
random_seed=42
|
random_seed=42
|
||||||
)
|
)
|
||||||
|
|
||||||
schedule_config = CosineScheduleConfig(
|
|
||||||
warmup_steps=10,
|
|
||||||
total_steps=20
|
|
||||||
)
|
|
||||||
|
|
||||||
# Create custom callbacks to track calls
|
# Create custom callbacks to track calls
|
||||||
callback_calls = []
|
callback_calls = []
|
||||||
|
|
||||||
class TrackingCallback(TrainCallback):
|
class TrackingCallback(TrainCallback):
|
||||||
def on_train_begin(self, trainer, context):
|
def on_train_begin(self, context):
|
||||||
callback_calls.append('on_train_begin')
|
callback_calls.append('on_train_begin')
|
||||||
|
|
||||||
def on_batch_end(self, trainer, context):
|
def on_batch_end(self, context):
|
||||||
callback_calls.append('on_batch_end')
|
callback_calls.append('on_batch_end')
|
||||||
|
|
||||||
def on_epoch_end(self, trainer, context):
|
def on_epoch_end(self, context):
|
||||||
callback_calls.append('on_epoch_end')
|
callback_calls.append('on_epoch_end')
|
||||||
|
|
||||||
train_config.strategy = StrategyFactory.load(base_test_env["model"], "seq", base_test_env["device"])
|
|
||||||
model_parameter = ModelParameter(
|
|
||||||
base_test_env["model"],
|
|
||||||
base_test_env["tokenizer"],
|
|
||||||
base_test_env["transformer_config"]
|
|
||||||
)
|
|
||||||
|
|
||||||
trainer = Trainer(
|
trainer = Trainer(
|
||||||
model_parameter,
|
|
||||||
train_config,
|
train_config,
|
||||||
schedule_config,
|
callbacks=[TrackingCallback()]
|
||||||
callbacks=[TrackingCallback(), ProgressBarCallback()]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
trainer.train()
|
trainer.train()
|
||||||
@@ -1,41 +1,46 @@
|
|||||||
|
import os
|
||||||
import torch
|
import torch
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from khaosz.config import *
|
from khaosz.config import *
|
||||||
from khaosz.trainer import *
|
from khaosz.trainer import *
|
||||||
|
from khaosz.data.checkpoint import Checkpoint
|
||||||
|
|
||||||
def test_early_stopping_simulation(base_test_env, early_stopping_dataset):
|
def test_early_stopping_simulation(base_test_env, early_stopping_dataset):
|
||||||
"""Simulate early stopping behavior"""
|
"""Simulate early stopping behavior"""
|
||||||
|
|
||||||
optimizer = torch.optim.AdamW(base_test_env["model"].parameters())
|
schedule_config = CosineScheduleConfig(warmup_steps=10, total_steps=20)
|
||||||
|
|
||||||
|
optimizer_fn = lambda model: torch.optim.AdamW(model.parameters())
|
||||||
|
scheduler_fn = lambda optim: SchedulerFactory.load(optim, schedule_config)
|
||||||
|
|
||||||
train_config = TrainConfig(
|
train_config = TrainConfig(
|
||||||
|
strategy="seq",
|
||||||
|
optimizer_fn=optimizer_fn,
|
||||||
|
scheduler_fn=scheduler_fn,
|
||||||
|
model=base_test_env["model"],
|
||||||
dataset=early_stopping_dataset,
|
dataset=early_stopping_dataset,
|
||||||
optimizer=optimizer,
|
|
||||||
checkpoint_dir=base_test_env["test_dir"],
|
checkpoint_dir=base_test_env["test_dir"],
|
||||||
n_epoch=2,
|
n_epoch=2,
|
||||||
batch_size=2,
|
batch_size=2,
|
||||||
checkpoint_interval=2,
|
checkpoint_interval=1,
|
||||||
accumulation_steps=2,
|
accumulation_steps=2,
|
||||||
random_seed=np.random.randint(1e4),
|
random_seed=np.random.randint(1e4),
|
||||||
)
|
)
|
||||||
|
|
||||||
train_config.strategy = StrategyFactory.load(base_test_env["model"], "seq", base_test_env["device"])
|
trainer = Trainer(train_config)
|
||||||
model_parameter = ModelParameter(
|
|
||||||
base_test_env["model"],
|
|
||||||
base_test_env["tokenizer"],
|
|
||||||
base_test_env["transformer_config"]
|
|
||||||
)
|
|
||||||
schedule_config = CosineScheduleConfig(warmup_steps=10, total_steps=20)
|
|
||||||
trainer = Trainer(model_parameter, train_config, schedule_config)
|
|
||||||
|
|
||||||
# Should handle early stopping gracefully
|
# Should handle early stopping gracefully
|
||||||
checkpoint = None
|
checkpoint = None
|
||||||
try:
|
try:
|
||||||
checkpoint = trainer.train()
|
checkpoint = trainer.train()
|
||||||
assert len(checkpoint.loss_list) == 2
|
|
||||||
except Exception:
|
except Exception:
|
||||||
# Handle any exceptions
|
# Handle any exceptions
|
||||||
pass
|
pass
|
||||||
|
|
||||||
checkpoint = trainer.train(checkpoint)
|
load_dir = os.path.join(base_test_env["test_dir"], "epoch_0_iter_2")
|
||||||
assert len(checkpoint.loss_list) == 10
|
checkpoint = Checkpoint.load(load_dir)
|
||||||
|
trainer.train(checkpoint)
|
||||||
|
|
||||||
|
load_dir = os.path.join(base_test_env["test_dir"], "epoch_1_iter_10")
|
||||||
|
checkpoint = Checkpoint.load(load_dir)
|
||||||
|
assert checkpoint.iteration == 10
|
||||||
@@ -4,7 +4,7 @@ import pytest
|
|||||||
|
|
||||||
from khaosz.config import *
|
from khaosz.config import *
|
||||||
from khaosz.trainer.schedule import *
|
from khaosz.trainer.schedule import *
|
||||||
from khaosz.data.data_util import *
|
from khaosz.data.dataset import *
|
||||||
|
|
||||||
|
|
||||||
def test_schedule_factory_random_configs():
|
def test_schedule_factory_random_configs():
|
||||||
@@ -35,7 +35,7 @@ def test_schedule_factory_random_configs():
|
|||||||
config.validate()
|
config.validate()
|
||||||
|
|
||||||
# Create scheduler using factory
|
# Create scheduler using factory
|
||||||
scheduler = SchedulerFactory.load_scheduler(optimizer, config)
|
scheduler = SchedulerFactory.load(optimizer, config)
|
||||||
|
|
||||||
# Verify scheduler type
|
# Verify scheduler type
|
||||||
if isinstance(config, CosineScheduleConfig):
|
if isinstance(config, CosineScheduleConfig):
|
||||||
@@ -83,7 +83,7 @@ def test_schedule_factory_edge_cases():
|
|||||||
|
|
||||||
for config in edge_cases:
|
for config in edge_cases:
|
||||||
config.validate()
|
config.validate()
|
||||||
scheduler = SchedulerFactory.load_scheduler(optimizer, config)
|
scheduler = SchedulerFactory.load(optimizer, config)
|
||||||
assert scheduler is not None
|
assert scheduler is not None
|
||||||
|
|
||||||
# Test multiple steps
|
# Test multiple steps
|
||||||
@@ -97,16 +97,17 @@ def test_schedule_factory_invalid_configs():
|
|||||||
# Test invalid configurations that should raise errors
|
# Test invalid configurations that should raise errors
|
||||||
invalid_configs = [
|
invalid_configs = [
|
||||||
# Negative warmup steps
|
# Negative warmup steps
|
||||||
CosineScheduleConfig(warmup_steps=-10, total_steps=1000, min_rate=0.1),
|
{"warmup_steps": -10, "total_steps": 1000, "min_rate": 0.1},
|
||||||
# Total steps less than warmup steps
|
# Total steps less than warmup steps
|
||||||
CosineScheduleConfig(warmup_steps=500, total_steps=400, min_rate=0.1),
|
{"warmup_steps": 500, "total_steps": 400, "min_rate": 0.1},
|
||||||
# Invalid min_rate
|
# Invalid min_rate
|
||||||
CosineScheduleConfig(warmup_steps=100, total_steps=1000, min_rate=-0.1),
|
{"warmup_steps": 100, "total_steps": 1000, "min_rate": -0.1},
|
||||||
CosineScheduleConfig(warmup_steps=100, total_steps=1000, min_rate=1.1),
|
{"warmup_steps": 100, "total_steps": 1000, "min_rate": 1.1},
|
||||||
]
|
]
|
||||||
|
|
||||||
for config in invalid_configs:
|
for kwargs in invalid_configs:
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
|
config = CosineScheduleConfig(**kwargs)
|
||||||
config.validate()
|
config.validate()
|
||||||
|
|
||||||
|
|
||||||
@@ -117,7 +118,7 @@ def test_schedule_factory_state_persistence():
|
|||||||
optimizer = torch.optim.AdamW(model.parameters(), lr=0.001)
|
optimizer = torch.optim.AdamW(model.parameters(), lr=0.001)
|
||||||
|
|
||||||
config = CosineScheduleConfig(warmup_steps=100, total_steps=1000, min_rate=0.1)
|
config = CosineScheduleConfig(warmup_steps=100, total_steps=1000, min_rate=0.1)
|
||||||
scheduler = SchedulerFactory.load_scheduler(optimizer, config)
|
scheduler = SchedulerFactory.load(optimizer, config)
|
||||||
|
|
||||||
# Take a few steps
|
# Take a few steps
|
||||||
for _ in range(5):
|
for _ in range(5):
|
||||||
@@ -127,7 +128,7 @@ def test_schedule_factory_state_persistence():
|
|||||||
state_dict = scheduler.state_dict()
|
state_dict = scheduler.state_dict()
|
||||||
|
|
||||||
# Create new scheduler and load state
|
# Create new scheduler and load state
|
||||||
new_scheduler = SchedulerFactory.load_scheduler(optimizer, config)
|
new_scheduler = SchedulerFactory.load(optimizer, config)
|
||||||
new_scheduler.load_state_dict(state_dict)
|
new_scheduler.load_state_dict(state_dict)
|
||||||
|
|
||||||
# Verify states match
|
# Verify states match
|
||||||
@@ -4,17 +4,26 @@ import numpy as np
|
|||||||
|
|
||||||
from khaosz.config import *
|
from khaosz.config import *
|
||||||
from khaosz.trainer import *
|
from khaosz.trainer import *
|
||||||
from khaosz.data.data_util import *
|
from khaosz.data.dataset import *
|
||||||
|
|
||||||
def test_different_batch_sizes(base_test_env, random_dataset):
|
def test_different_batch_sizes(base_test_env, random_dataset):
|
||||||
"""Test training with different batch sizes"""
|
"""Test training with different batch sizes"""
|
||||||
batch_sizes = [1, 2, 4, 8]
|
batch_sizes = [1, 2, 4, 8]
|
||||||
|
|
||||||
for batch_size in batch_sizes:
|
for batch_size in batch_sizes:
|
||||||
optimizer = torch.optim.AdamW(base_test_env["model"].parameters())
|
schedule_config = CosineScheduleConfig(
|
||||||
|
warmup_steps=10,
|
||||||
|
total_steps=20
|
||||||
|
)
|
||||||
|
optimizer_fn = lambda model: torch.optim.AdamW(model.parameters())
|
||||||
|
scheduler_fn = lambda optim: SchedulerFactory.load(optim, schedule_config)
|
||||||
|
|
||||||
train_config = TrainConfig(
|
train_config = TrainConfig(
|
||||||
|
strategy="seq",
|
||||||
|
model=base_test_env["model"],
|
||||||
dataset=random_dataset,
|
dataset=random_dataset,
|
||||||
optimizer=optimizer,
|
optimizer_fn=optimizer_fn,
|
||||||
|
scheduler_fn=scheduler_fn,
|
||||||
checkpoint_dir=base_test_env["test_dir"],
|
checkpoint_dir=base_test_env["test_dir"],
|
||||||
n_epoch=1,
|
n_epoch=1,
|
||||||
batch_size=batch_size,
|
batch_size=batch_size,
|
||||||
@@ -31,10 +40,19 @@ def test_gradient_accumulation(base_test_env, random_dataset):
|
|||||||
accumulation_steps_list = [1, 2, 4]
|
accumulation_steps_list = [1, 2, 4]
|
||||||
|
|
||||||
for accumulation_steps in accumulation_steps_list:
|
for accumulation_steps in accumulation_steps_list:
|
||||||
optimizer = torch.optim.AdamW(base_test_env["model"].parameters())
|
schedule_config = CosineScheduleConfig(
|
||||||
|
warmup_steps=10,
|
||||||
|
total_steps=20
|
||||||
|
)
|
||||||
|
optimizer_fn = lambda model: torch.optim.AdamW(model.parameters())
|
||||||
|
scheduler_fn = lambda optim: SchedulerFactory.load(optim, schedule_config)
|
||||||
|
|
||||||
train_config = TrainConfig(
|
train_config = TrainConfig(
|
||||||
|
strategy="seq",
|
||||||
|
model=base_test_env["model"],
|
||||||
|
optimizer_fn=optimizer_fn,
|
||||||
|
scheduler_fn=scheduler_fn,
|
||||||
dataset=random_dataset,
|
dataset=random_dataset,
|
||||||
optimizer=optimizer,
|
|
||||||
checkpoint_dir=base_test_env["test_dir"],
|
checkpoint_dir=base_test_env["test_dir"],
|
||||||
n_epoch=1,
|
n_epoch=1,
|
||||||
batch_size=2,
|
batch_size=2,
|
||||||
@@ -44,18 +62,7 @@ def test_gradient_accumulation(base_test_env, random_dataset):
|
|||||||
random_seed=42
|
random_seed=42
|
||||||
)
|
)
|
||||||
|
|
||||||
schedule_config = CosineScheduleConfig(
|
trainer = Trainer(train_config)
|
||||||
warmup_steps=10,
|
|
||||||
total_steps=20
|
|
||||||
)
|
|
||||||
train_config.strategy = StrategyFactory.load(base_test_env["model"], "seq", base_test_env["device"])
|
|
||||||
model_parameter = ModelParameter(
|
|
||||||
base_test_env["model"],
|
|
||||||
base_test_env["tokenizer"],
|
|
||||||
base_test_env["transformer_config"]
|
|
||||||
)
|
|
||||||
|
|
||||||
trainer = Trainer(model_parameter, train_config, schedule_config)
|
|
||||||
trainer.train()
|
trainer.train()
|
||||||
|
|
||||||
assert train_config.accumulation_steps == accumulation_steps
|
assert train_config.accumulation_steps == accumulation_steps
|
||||||
@@ -70,10 +77,19 @@ def test_memory_efficient_training(base_test_env, random_dataset):
|
|||||||
]
|
]
|
||||||
|
|
||||||
for config in small_batch_configs:
|
for config in small_batch_configs:
|
||||||
optimizer = torch.optim.AdamW(base_test_env["model"].parameters())
|
schedule_config = CosineScheduleConfig(
|
||||||
|
warmup_steps=10,
|
||||||
|
total_steps=20
|
||||||
|
)
|
||||||
|
optimizer_fn = lambda model: torch.optim.AdamW(model.parameters())
|
||||||
|
scheduler_fn = lambda optim: SchedulerFactory.load(optim, schedule_config)
|
||||||
|
|
||||||
train_config = TrainConfig(
|
train_config = TrainConfig(
|
||||||
|
strategy="seq",
|
||||||
|
model=base_test_env["model"],
|
||||||
dataset=random_dataset,
|
dataset=random_dataset,
|
||||||
optimizer=optimizer,
|
optimizer_fn=optimizer_fn,
|
||||||
|
scheduler_fn=scheduler_fn,
|
||||||
checkpoint_dir=base_test_env["test_dir"],
|
checkpoint_dir=base_test_env["test_dir"],
|
||||||
n_epoch=1,
|
n_epoch=1,
|
||||||
batch_size=config["batch_size"],
|
batch_size=config["batch_size"],
|
||||||
@@ -28,7 +28,7 @@ class GenerationBenchmark:
|
|||||||
def _initialize_kv_cache(self, batch_size: int) -> list:
|
def _initialize_kv_cache(self, batch_size: int) -> list:
|
||||||
"""初始化KV缓存"""
|
"""初始化KV缓存"""
|
||||||
config = self.config
|
config = self.config
|
||||||
shape = (batch_size, config.n_layer, config.m_len, config.n_kvhead, config.n_dim // config.n_head)
|
shape = (batch_size, config.max_len, config.n_layers, config.n_kv_heads, config.dim // config.n_heads)
|
||||||
k_cache = torch.zeros(shape, device=self.device, dtype=self.dtype)
|
k_cache = torch.zeros(shape, device=self.device, dtype=self.dtype)
|
||||||
v_cache = torch.zeros(shape, device=self.device, dtype=self.dtype)
|
v_cache = torch.zeros(shape, device=self.device, dtype=self.dtype)
|
||||||
return (k_cache, v_cache)
|
return (k_cache, v_cache)
|
||||||
@@ -175,12 +175,12 @@ def print_benchmark_result(result: BenchmarkResult):
|
|||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
config = ModelConfig(
|
config = ModelConfig(
|
||||||
vocab_size=10000,
|
vocab_size=10000,
|
||||||
n_dim=1536,
|
dim=1536,
|
||||||
n_head=24,
|
n_heads=24,
|
||||||
n_kvhead=4,
|
n_kv_heads=4,
|
||||||
d_ffn=6912,
|
dim_ffn=6912,
|
||||||
m_len=2048,
|
max_len=2048,
|
||||||
n_layer=24,
|
n_layers=24,
|
||||||
norm_eps=1e-5,
|
norm_eps=1e-5,
|
||||||
)
|
)
|
||||||
|
|
||||||
+110
-83
@@ -1,21 +1,87 @@
|
|||||||
import os
|
import os
|
||||||
import argparse
|
import argparse
|
||||||
import torch
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import torch.optim as optim
|
||||||
|
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||||
|
|
||||||
from torch.optim import AdamW
|
from typing import List, Optional
|
||||||
from khaosz.config import ParameterLoader, Checkpoint, TrainConfig, CosineScheduleConfig
|
from functools import partial
|
||||||
from khaosz.trainer import Trainer, StrategyFactory
|
|
||||||
from khaosz.data import DatasetLoader
|
from khaosz.data import DatasetLoader
|
||||||
|
from khaosz.config import ModelParameter, TrainConfig, CosineScheduleConfig
|
||||||
|
from khaosz.trainer import Trainer, SchedulerFactory
|
||||||
|
from khaosz.parallel import get_rank
|
||||||
|
|
||||||
|
|
||||||
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
|
def parse_args() -> argparse.Namespace:
|
||||||
|
def parse_device_ids(s: Optional[str]) -> Optional[List[int]]:
|
||||||
|
if s is None or s.strip() == "":
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return [int(x.strip()) for x in s.split(",") if x.strip()]
|
||||||
|
except ValueError as e:
|
||||||
|
raise argparse.ArgumentTypeError(f"Invalid device_ids format: {s}. Expected comma-separated integers like '0,1,2'.")
|
||||||
|
|
||||||
def get_files(root_path: str) -> list[str]:
|
|
||||||
paths = []
|
|
||||||
for root, _, files in os.walk(root_path):
|
|
||||||
paths.extend([os.path.join(root, file) for file in files])
|
|
||||||
|
|
||||||
return paths
|
parser = argparse.ArgumentParser(description="Train the Transformer model.")
|
||||||
|
|
||||||
|
parser.add_argument("--train_type",choices=["seq", "sft", "dpo"], help="Train type.")
|
||||||
|
parser.add_argument("--data_root_path", type=str, required=True, help="Path to the root directory of the dataset.")
|
||||||
|
parser.add_argument("--param_path", type=str, required=True, help="Path to the model parameters or resume checkpoint.")
|
||||||
|
|
||||||
|
parser.add_argument("--n_epoch", type=int, default=1, help="Number of epochs to train.")
|
||||||
|
parser.add_argument("--batch_size", type=int, default=1, help="Batch size for training.")
|
||||||
|
parser.add_argument("--accumulation_steps", type=int, default=1, help="Number of iterations between each optimizer step.")
|
||||||
|
parser.add_argument("--warmup_steps", type=int, default=1000, help="Number of iters between warnings.")
|
||||||
|
parser.add_argument("--max_lr", type=float, default=3e-4, help="Max learning rate for training.")
|
||||||
|
parser.add_argument("--max_grad_norm", type=float, default=1.0, help="Max gradient norm for clipping.")
|
||||||
|
parser.add_argument("--adamw_beta1", type=float, default=0.9, help="Beta values for AdamW optimizer.")
|
||||||
|
parser.add_argument("--adamw_beta2", type=float, default=0.95, help="Beta values for AdamW optimizer.")
|
||||||
|
parser.add_argument("--adamw_weight_decay", type=float, default=0.01, help="Weight decay for AdamW optimizer.")
|
||||||
|
parser.add_argument("--random_seed", type=int, default=3407, help="Random seed for reproducibility.")
|
||||||
|
parser.add_argument("--num_workers", type=int, default=4, help="Number of workers for data loading.")
|
||||||
|
parser.add_argument("--no_pin_memory", action="store_false", dest="pin_memory", help="Disable pin memory")
|
||||||
|
parser.add_argument("--window_size", type=int, default=None, help="the max length of the input sequence.")
|
||||||
|
parser.add_argument("--stride", type=int, default=None, help="the step size of the input sequence.")
|
||||||
|
parser.add_argument("--dpo_beta", type=float, default=0.1, help="DPO beta value.")
|
||||||
|
|
||||||
|
parser.add_argument("--checkpoint_interval", type=int, default=5000, help="Number of iters between checkpoints.")
|
||||||
|
parser.add_argument("--checkpoint_dir", type=str, default="checkpoint", help="Directory to save checkpoints.")
|
||||||
|
parser.add_argument("--start_epoch", type=int, default=0, help="Start epoch for training.")
|
||||||
|
parser.add_argument("--start_batch", type=int, default=0, help="Start batch for training.")
|
||||||
|
|
||||||
|
parser.add_argument("--nprocs", type=int, default=1, help="Number of GPUs to use.")
|
||||||
|
parser.add_argument("--device_ids", type=parse_device_ids, default=None, help="Device IDs to use.")
|
||||||
|
parser.add_argument("--device_type", type=str, default="cuda", help="Device type to use.")
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
return args
|
||||||
|
|
||||||
|
def ddp_wrap(model: nn.Module):
|
||||||
|
local_rank = get_rank()
|
||||||
|
model = model.to(device=f"cuda:{local_rank}", dtype=torch.bfloat16)
|
||||||
|
ddp_model = DDP(
|
||||||
|
model,
|
||||||
|
device_ids=[local_rank],
|
||||||
|
output_device=local_rank,
|
||||||
|
find_unused_parameters=False
|
||||||
|
)
|
||||||
|
return ddp_model
|
||||||
|
|
||||||
|
def create_optimizer(model: nn.Module, **kwargs) -> optim.Optimizer:
|
||||||
|
return optim.AdamW(model.parameters(), **kwargs)
|
||||||
|
|
||||||
|
def create_scheduler(optimizer: optim.Optimizer, **kwargs) -> optim.lr_scheduler.LRScheduler:
|
||||||
|
return SchedulerFactory.load(optimizer, **kwargs)
|
||||||
|
|
||||||
|
def prepare_checkpoint(model: nn.Module) -> dict:
|
||||||
|
if isinstance(model, torch.nn.parallel.DistributedDataParallel):
|
||||||
|
state_dict = model.module.state_dict()
|
||||||
|
else:
|
||||||
|
state_dict = model.state_dict()
|
||||||
|
return state_dict
|
||||||
|
|
||||||
|
|
||||||
def train(
|
def train(
|
||||||
train_type: str,
|
train_type: str,
|
||||||
@@ -31,31 +97,29 @@ def train(
|
|||||||
checkpoint_interval: int,
|
checkpoint_interval: int,
|
||||||
checkpoint_dir: str,
|
checkpoint_dir: str,
|
||||||
dpo_beta: float,
|
dpo_beta: float,
|
||||||
adamw_betas: tuple,
|
adamw_beta1: float,
|
||||||
|
adamw_beta2: float,
|
||||||
adamw_weight_decay: float,
|
adamw_weight_decay: float,
|
||||||
max_grad_norm: float,
|
max_grad_norm: float,
|
||||||
embdeding_lr_rate: int,
|
|
||||||
random_seed: int,
|
random_seed: int,
|
||||||
|
num_workers: int,
|
||||||
|
pin_memory: bool,
|
||||||
window_size: int,
|
window_size: int,
|
||||||
stride: int,
|
stride: int,
|
||||||
resume_from_checkpoint: bool
|
nprocs: int,
|
||||||
|
device_ids: List[int],
|
||||||
|
device_type: str,
|
||||||
):
|
):
|
||||||
assert train_type in ["seq", "sft", "dpo"]
|
assert train_type in ["seq", "sft", "dpo"]
|
||||||
assert os.path.exists(param_path)
|
assert os.path.exists(param_path)
|
||||||
|
|
||||||
parameter = ParameterLoader.load(param_path)
|
parameter = ModelParameter()
|
||||||
checkpoint = None
|
parameter.load(param_path)
|
||||||
|
|
||||||
if isinstance(parameter, Checkpoint) and resume_from_checkpoint:
|
|
||||||
checkpoint = parameter
|
|
||||||
|
|
||||||
if window_size is None:
|
if window_size is None:
|
||||||
window_size = parameter.config.m_len
|
window_size = parameter.config.max_len
|
||||||
|
|
||||||
model = parameter.model
|
model = parameter.model
|
||||||
device = torch.device("cuda")
|
|
||||||
model = model.to(device=device, dtype=torch.bfloat16)
|
|
||||||
cache_files = get_files(data_root_path)
|
|
||||||
|
|
||||||
kwargs = {
|
kwargs = {
|
||||||
"dpo_beta": dpo_beta,
|
"dpo_beta": dpo_beta,
|
||||||
@@ -63,37 +127,30 @@ def train(
|
|||||||
"eos_token_id": parameter.tokenizer.eos_id,
|
"eos_token_id": parameter.tokenizer.eos_id,
|
||||||
"pad_token_id": parameter.tokenizer.pad_id,
|
"pad_token_id": parameter.tokenizer.pad_id,
|
||||||
}
|
}
|
||||||
|
|
||||||
strategy = StrategyFactory.load(
|
|
||||||
model,
|
|
||||||
train_type,
|
|
||||||
device,
|
|
||||||
**kwargs
|
|
||||||
)
|
|
||||||
|
|
||||||
dataset = DatasetLoader.load(
|
dataset = DatasetLoader.load(
|
||||||
train_type=train_type,
|
train_type=train_type,
|
||||||
load_path=cache_files,
|
load_path=data_root_path,
|
||||||
window_size=window_size,
|
window_size=window_size,
|
||||||
stride=stride,
|
stride=stride
|
||||||
**kwargs
|
|
||||||
)
|
)
|
||||||
|
|
||||||
param_groups = [
|
schedule_config = CosineScheduleConfig(
|
||||||
{"params": [p for n, p in model.named_parameters() if "embedding" in n], "lr": max_lr * embdeding_lr_rate},
|
warmup_steps=warmup_steps,
|
||||||
{"params": [p for n, p in model.named_parameters() if "embedding" not in n], "lr": max_lr}
|
total_steps=len(dataset) * n_epoch // (batch_size * nprocs),
|
||||||
]
|
|
||||||
|
|
||||||
optim = AdamW(
|
|
||||||
param_groups,
|
|
||||||
betas=adamw_betas,
|
|
||||||
weight_decay=adamw_weight_decay
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
optimizer_fn = partial(create_optimizer,
|
||||||
|
**{"lr": max_lr, "betas": (adamw_beta1, adamw_beta2), "weight_decay": adamw_weight_decay})
|
||||||
|
scheduler_fn = partial(create_scheduler,
|
||||||
|
**{"schedule_config": schedule_config})
|
||||||
|
|
||||||
train_config = TrainConfig(
|
train_config = TrainConfig(
|
||||||
strategy=strategy,
|
model=model,
|
||||||
|
strategy=train_type,
|
||||||
dataset=dataset,
|
dataset=dataset,
|
||||||
optimizer=optim,
|
optimizer_fn=optimizer_fn,
|
||||||
|
scheduler_fn=scheduler_fn,
|
||||||
checkpoint_dir=checkpoint_dir,
|
checkpoint_dir=checkpoint_dir,
|
||||||
n_epoch=n_epoch,
|
n_epoch=n_epoch,
|
||||||
batch_size=batch_size,
|
batch_size=batch_size,
|
||||||
@@ -103,50 +160,20 @@ def train(
|
|||||||
accumulation_steps=accumulation_steps,
|
accumulation_steps=accumulation_steps,
|
||||||
max_grad_norm=max_grad_norm,
|
max_grad_norm=max_grad_norm,
|
||||||
random_seed=random_seed,
|
random_seed=random_seed,
|
||||||
num_workers=4,
|
num_workers=num_workers,
|
||||||
pin_memory=True
|
pin_memory=pin_memory,
|
||||||
|
nprocs=nprocs,
|
||||||
|
parallel_wrapper=ddp_wrap,
|
||||||
|
state_dict_fn=prepare_checkpoint,
|
||||||
|
device_ids=device_ids,
|
||||||
|
device_type=device_type,
|
||||||
|
extra_kwargs=kwargs,
|
||||||
)
|
)
|
||||||
|
|
||||||
schedule_config = CosineScheduleConfig(
|
trainer = Trainer(train_config)
|
||||||
warmup_steps=warmup_steps,
|
trainer.train()
|
||||||
total_steps=len(dataset) * n_epoch // batch_size,
|
|
||||||
)
|
|
||||||
|
|
||||||
trainer = Trainer(
|
|
||||||
parameter=parameter,
|
|
||||||
train_config=train_config,
|
|
||||||
schedule_config=schedule_config,
|
|
||||||
)
|
|
||||||
trainer.train(checkpoint)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = argparse.ArgumentParser(description="Train the Transformer model.")
|
args = parse_args()
|
||||||
# train args
|
|
||||||
parser.add_argument("--train_type",choices=["seq", "sft", "dpo"], help="Train type.")
|
|
||||||
parser.add_argument("--data_root_path", type=str, required=True, help="Path to the root directory of the dataset.")
|
|
||||||
parser.add_argument("--param_path", type=str, required=True, help="Path to the model parameters or resume checkpoint.")
|
|
||||||
parser.add_argument("--n_epoch", type=int, default=1, help="Number of epochs to train.")
|
|
||||||
parser.add_argument("--batch_size", type=int, default=1, help="Batch size for training.")
|
|
||||||
parser.add_argument("--accumulation_steps", type=int, default=1, help="Number of iterations between each optimizer step.")
|
|
||||||
parser.add_argument("--warmup_steps", type=int, default=1000, help="Number of iters between warnings.")
|
|
||||||
parser.add_argument("--max_lr", type=float, default=3e-4, help="Max learning rate for training.")
|
|
||||||
parser.add_argument("--checkpoint_interval", type=int, default=5000, help="Number of iters between checkpoints.")
|
|
||||||
parser.add_argument("--checkpoint_dir", type=str, default="checkpoint", help="Directory to save checkpoints.")
|
|
||||||
parser.add_argument("--max_grad_norm", type=float, default=1.0, help="Max gradient norm for clipping.")
|
|
||||||
parser.add_argument("--adamw_betas", type=tuple, default=(0.9, 0.95), help="Beta values for AdamW optimizer.")
|
|
||||||
parser.add_argument("--adamw_weight_decay", type=float, default=0.01, help="Weight decay for AdamW optimizer.")
|
|
||||||
parser.add_argument("--embdeding_lr_rate", type=float, default=1.0, help="The rate between the embedding layers lr rate and the max lr rate.")
|
|
||||||
parser.add_argument("--random_seed", type=int, default=3407, help="Random seed for reproducibility.")
|
|
||||||
|
|
||||||
# other configs
|
|
||||||
parser.add_argument("--window_size", type=int, default=None, help="the max length of the input sequence.")
|
|
||||||
parser.add_argument("--stride", type=int, default=None, help="the step size of the input sequence.")
|
|
||||||
parser.add_argument("--start_epoch", type=int, default=0, help="Start epoch for training.")
|
|
||||||
parser.add_argument("--start_batch", type=int, default=0, help="Start batch for training.")
|
|
||||||
parser.add_argument("--resume_from_checkpoint", type=bool, default=False, help="train from checkpoint or not.")
|
|
||||||
parser.add_argument("--dpo_beta", type=float, default=0.1, help="DPO beta value.")
|
|
||||||
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
train(**vars(args))
|
train(**vars(args))
|
||||||
Reference in New Issue
Block a user