Initialize optimizer research workspace with official baselines and history-free coverage

Vendor pinned MeZO, AGZO, LOZO and LoREN sources with independent environments. Add direct in-place fix/adjust/node training, derived history-free basis gradients, development-best checkpoints and experiment tooling. Keep models, datasets, caches and credentials outside Git.

Validation: 93 project tests passed; 521 vendored author files verified.
This commit is contained in:
gloamxun committed 2026-11-12 23:32:33 +08:00
commit e0feabec8f
596 files changed
+87356

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
# Python
__pycache__/
*.py[cod]
# Logs
*.log
*.out
# Virtual environment
venv/
# Jupyter Notebook
.ipynb_checkpoints
# System Files
.DS_Store
# Machine-specific files
.idea
*.iml
.vscode
# Temporary files
*.tmp
*.temp
# Build artifacts
build/
dist/
*.egg-info/
# Python caches and test caches
.cache/
.pytest_cache/
# Experiment/ML outputs
log/
logs/
result/
results/
checkpoints/
outputs/
runs/
wandb/
*.wandb
# Model weights/artifacts
*.pt
*.pth
*.ckpt
*.bin
*.safetensors
# Environment files
.env
.env.*
.venv/
env/
# Jupyter checkpoints (ensure directory form)
.ipynb_checkpoints/
# OS specific
Thumbs.db
# Shell outputs
nohup.out
# profiler
export_only_prof_dir/
train_profile.json
kernel_meta/
.modelscope_cache/
+1
View File
@@ -0,0 +1 @@
3.11.15
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
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.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
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.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
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.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
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.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
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.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
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.
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.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
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.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
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>.
+73
View File
@@ -0,0 +1,73 @@
ActivationGuidedZO-NPU: Activation-Guided Zeroth-Order Optimization for LLM Fine-Tuning(NPU)
=================================================
[License: GPL v3](https://www.gnu.org/licenses/gpl-3.0) \
[License: OPENPANGU MODEL LICENSE AGREEMENT VERSION 1.0](/openPangu%20LICENSE)
This repository is built to benchmark ActivationGuidedZO/ZO-LLM performance on openPangu-embedeb-1B. It extends the ZO-LLM benchmark with Activation-Guided Zeroth-Order optimization (ActivationGuidedZO). It remains under GPLv3: any distribution or modification must keep GPLv3 terms and notices. The training loop and README were forked from ZO-LLM (https://github.com/ZO-Bench/ZO-LLM); ActivationGuidedZO logic was added in [zo-bench/trainer.py](zo-bench/trainer.py), and this README was rewritten accordingly.
Table of Contents
-----------------
1. Overview
2. ActivationGuidedZO at a Glance
3. What's New in This Fork
4. Repository Layout
5. Setup
6. Root Scripts
7. Licenses and Attribution
8. Citation
## 1) Overview
This fork builds on the "Revisiting Zeroth-Order Optimization for Memory-Efficient LLM Fine-Tuning: A Benchmark" codebase to deliver Activation-Guided Zeroth-Order Optimization (ActivationGuidedZO). ZO-LLM benchmarks backpropagation-free, memory-efficient fine-tuning across OPT, LLaMA/Vicuna, Mistral, and RoBERTa families on classification and reasoning tasks. ActivationGuidedZO aligns perturbations with activation subspaces via lightweight power iteration, improving gradient direction quality without increasing memory beyond near-inference levels.
## 2) ActivationGuidedZO at a Glance
- Guided basis: For each linear layer, a forward hook captures activations, reshapes to (batch*seq, hidden), and runs a few power-iteration steps to approximate the top activation direction.
- Rank-1 perturbation: Builds $P_l = r_l u_l^T$ with a regenerated random vector $r_l$ and stored direction $u_l$, keeping storage minimal.
- Two-point estimate: Evaluates $L_+$ and $L_-$ with $\pm \epsilon P$ and forms the projected gradient $(L_+ - L_-)/(2\epsilon)$.
- Memory-saving tricks: Uses a single random seed to reconstruct $r_l$ in-place and discards activations after the basis is computed; only $u_l$ vectors are kept.
## 3) What's New in This Fork
- ActivationGuidedZO trainer with configurable `agzo_power_iter_steps` and activation hooks that store only principal directions.
- Rank-1 perturbation path integrated into the training loop with the same LR scheduling as other ZO optimizers.
- Experiment tagging that records ActivationGuidedZO settings for sweeps.
- Scripts targeting NPU runs (see run_*_pangu-1b.sh) plus updated documentation.
## 4) Repository Layout
- [zo-bench/run.py](zo-bench/run.py): Entry point for training and evaluation.
- [zo-bench/trainer.py](zo-bench/trainer.py): Optimizers and training loop; ActivationGuidedZO implementation lives here.
- [zo-bench/tasks.py](zo-bench/tasks.py) and [zo-bench/templates.py](zo-bench/templates.py): Task definitions and prompt templates.
- [zo-bench/sweeps](zo-bench/sweeps): Hyperparameter sweeps organized by task, model, optimizer, and tuning scheme.
## 5) Setup
```bash
conda create -n zollm python=3.10
conda activate zollm
pip install -r requirements.txt
```
## 6) Root Scripts
- `run_agzo_pangu-1b.sh`: ActivationGuidedZO training/eval entry tailored for Pangu-1B NPUs.
- `run_fo_pangu-1b.sh`: Forward-gradient baseline on Pangu-1B.
- `run_lozo_pangu-1b.sh`: Low-Rank ZO (LOZO) baseline on Pangu-1B.
- `run_zo_sgd_pangu-1b.sh`: ZO-SGD baseline on Pangu-1B.
- `run_icl_pangu-1b.sh`: In-context learning routines on Pangu-1B.
- `run_zeroshot_pangu-1b.sh`: Zero-shot pipeline that can also be used for direct inference without fine-tuning.
## 7) Licenses and Attribution
- Code license: GPLv3 (see LICENSE). Redistributions and derivatives must retain GPLv3 terms and notices.
- Model license: OPENPANGU MODEL LICENSE AGREEMENT VERSION 1.0 applies to model assets (see link above).
- Upstream origin: Forked from ZO-LLM (https://github.com/ZO-Bench/ZO-LLM). The baseline training loop in [zo-bench/trainer.py](zo-bench/trainer.py) and this README were derived from the upstream project and modified here to add ActivationGuidedZO.
## 8) Citation
If you use this work, please cite the original ActivationGuidedZO paper:
```
@misc{lin2026agzoactivationguidedzerothorderoptimization,
title={AGZO: Activation-Guided Zeroth-Order Optimization for LLM Fine-Tuning},
author={Wei Lin and Yining Jiang and Qingyu Song and Qiao Xiang and Hong Xu},
year={2026},
eprint={2601.17261},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2601.17261},
}
```
+81
View File
@@ -0,0 +1,81 @@
# AGZO:独立环境、入口与排障
官方来源:https://github.com/Yining-Jiang/ActivationGuidedZO-NPU.git;锁定提交:`623e09a5a7dfdee697a603ec1e7aa01e3f5e6290`。
官方文件保留原样;此目录新增 pyproject.toml、uv.lock、native.py、run_compatible.py 和本文。
原仓库 Git 历史存放在被忽略的 `.upstream-git/`,防止主项目意外把整个目录当成 gitlink。
查看上游版本:`git --git-dir=.upstream-git --work-tree=. rev-parse HEAD`。
不要在这个目录执行普通 git commit/push;主项目尚未提交。
## 安装与版本
在 WSL 中执行(不需要激活根目录环境):
```bash
cd ~/experiments_codebase
source scripts/env.sh
cd baselines/agzo
uv sync --locked
uv run --locked python native.py --help
```
此目录 `.venv` 独立,Python 3.11,torch 2.13.0,原生 Transformers 4.53.2。
直接依赖精确版本写在 pyproject.toml,全部间接依赖和 wheel 哈希写在 uv.lock。
`uv sync --locked` 默认 native;`uv sync --locked --no-default-groups --group modern` 切换到 Transformers 4.57.1。
两组互斥,使用同一个本库 `.venv`,不会激活其他方法的环境。不要使用 `uv pip install -U` 绕开锁。
## 官方入口及命令
原入口 `zo-bench/run.py`。本地资源包装入口 `native.py` 仅设置共享路径、提供本地 Dataset 和启动参数,然后运行原始程序。
`--asset-model`、`--asset-task`、`--asset-out` 是包装参数,其余参数透传官方入口;以 `--help` 为准。
MeZO/LOZO/AGZO包装器默认固定 train_set_seed=42,并将result_file显式指向共享输出;否则原版会因num_dev配合空采样seed触发断言,或因相对result目录缺失在训练完成后报错。用户后置同名参数可覆盖这些默认值。
```bash
uv run --locked python native.py --asset-model facebook/opt-1.3b --asset-task sst2 --max_steps 2 --num_train 16 --num_dev 4 --num_eval 4 --per_device_train_batch_size 2 --learning_rate 2e-6 --zo_eps 1e-3 --agzo_rank 1 --agzo_power_iter_steps 5 --eval_strategy no --save_strategy no --logging_steps 1
```
调参请使用官方参数:学习率 `--learning_rate`,差分半径 `--zo_eps`,batch `--per_device_train_batch_size`。
参数覆盖:MeZO/LOZO/AGZO 默认 full(不传 LoRA/prefix/head-only 开关);LOREN 包装器显式传 `--full_parameter`。
全参数覆盖不等于无结构全维搜索;LOZO/AGZO 仍使用结构化扰动。
## Qwen3 / DROP 与统一比较入口
```bash
uv run --locked --no-default-groups --group modern python run_compatible.py --model Qwen/Qwen3-0.6B --task sst2 --budget 12 --train-samples 16 --dev-samples 4 --eval-samples 4 --batch-size 2 --eval-batch-size 2 --calibration-samples 2 --no-save-checkpoint
# DROP:将 --task 改为 drop,并合理增加 --max-length(短冒烟可以先用128)。
```
兼容层 `../../src/experiments_codebase/official.py` 从本库源码编译官方数值函数;不导入旧 Trainer,也不另写一套公式。
通用数据协议和计账在 `../../src/experiments_codebase/task.py`、`runner.py`。
此入口统一 SST2 为两 verbalizer 的交叉熵、DROP 为答案 token 的 teacher-forced CE;它与部分官方任务目标不同,日志会标记 task adapter。
预算为总 main forward,而非更新步数;检测和基提取前向不免费。评估前向另列。
不支持从兼容检查点续训;可用 `--action evaluate --checkpoint ...` 或 `--action generate --checkpoint ... --prompt ...` 推理。
## 核心位置
- 核心算法:`zo-bench/trainer.py: agzo_collect_basis / _agzo_power_iteration / agzo_step`。
- 模型/数据:`zo-bench/run.py: Framework; zo-bench/tasks.py / templates.py; npu_compat.py`。
- 官方超参数原型:入口中的参数 dataclass/parser 与原始 shell 脚本;与本站兼容入口参数不是同一命名空间。
## 系统组件与常见问题
官方仓库针对昇腾 NPU/Pangu,其 npu_compat.py 的 CUDA 回退不完整,run.py 还直接调用 torch.npu.manual_seed_all。native.py 在内存中将种子/设备计数改为CUDA,并为设备信息、显存、设备选择提供CUDA回调;不更改磁盘上的官方文件或优化器公式。每次运行保存 compatibility_changes.json。本环境不装 torch_npu。原脚本有 Pangu 路径,不能直接当 OPT/Qwen 的实验配置。agzo_collect_basis 是额外一次前向,统一计账时每更新通常为 3 次而非 2 次。原生Trainer的默认optim可能为adamw,若要AGZO+SGD需显式传 --optim sgd;实际启动参数以日志为准。
WSL 必须能看到 NVIDIA 驱动:先运行 `nvidia-smi`。RTX 5070 Ti 是 Blackwell;原论文旧版 torch/CUDA wheel 不支持其架构。
本机选用支持当前显卡的 torch 2.13.0,不声称完全复刻论文年代的二进制环境。
CUDA runtime 随 wheel 安装,普通运行无需 nvcc;自编译第三方扩展才需要 CUDA toolkit、gcc/g++、make、Python headers。
Fedora 常见系统依赖:`git curl ca-certificates libgomp libstdc++`;缺库先用 `ldd` 核查,不要盲目替换驱动。
uv 会下载 Python 3.11,不依赖系统 Python 3.14;保持 `.python-version`。
如果 WSL 解析到 198.18.* 且直连超时,可在未跟踪的根 `.env` 配置你现有代理,再 `source ../../scripts/env.sh`;不要把代理/token 写入源码。
本次用临时 HTTP(S)_PROXY 沿用主机代理;未修改系统网络配置。
`huggingface-hub` 不能随意升到2.x:Transformers 4.x 需要 <1.0。已锁0.36.0。
新版setuptools移除了pkg_resources,旧Trainer/accelerate仍导入它;锁80.9.0同时满足torch要求的>=77.0.3。LOREN官方requirements漏列loguru,本环境已补0.7.3。
旧 datasets/pyarrow/numpy 有 ABI 约束,三者必须遵守 uv.lock;不能拿现代 `.venv` 的 site-packages 混入原生环境。
共享DROP不能用datasets5.x的List元数据序列化后直接给2.x/3.x读;请在根锁定环境datasets3.6执行prepare_assets,工具可从原始parquet重建不兼容资产。
E盘必须真实挂载。Assets默认位于 `/mnt/e/Experiments/Assets`,包装器在写入前检查 mountpoint。
模型和数据只从本地共享目录读取;资产缺失先在根环境运行 `scripts/prepare_assets.py --download-missing`。
Qwen的词表较大,长序列或大 batch 会增显存;先减batch/长度,不要把OOM归因于优化算法。
## 验证状态
以根目录 `reports/validation_report.json` 和 `reports/validation.log` 为准,区分安装、导入、短步训练、模型任务矩阵。
`--help` 通过不代表训练通过,短步通过也不代表论文精度复现。未完成项目会明确记录。
+71
View File
@@ -0,0 +1,71 @@
"""Run the original entry point with shared local assets. No optimizer rewrite."""
import argparse
from datetime import datetime,timezone
import json
import os
from pathlib import Path
import runpy
import sys
HERE=Path(__file__).resolve().parent
ROOT=HERE.parents[1]
sys.path.insert(0,str(ROOT/'src'))
from experiments_codebase.paths import paths,model_path,save
def main():
p=argparse.ArgumentParser(description=__doc__,add_help=False)
p.add_argument('--asset-model',default='facebook/opt-1.3b')
p.add_argument('--asset-task',choices=['sst2','drop'],default='sst2')
p.add_argument('--asset-out',type=Path)
args,rest=p.parse_known_args();method=HERE.name
roots=paths();os.environ.setdefault('WANDB_MODE','disabled');os.environ['WANDB_DIR']=str(roots['results']/'wandb')
out=(args.asset_out or roots['results']/f'native_{method}_{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}').resolve()
if not out.is_relative_to(roots['results'].resolve()):raise ValueError('Output must be under shared results')
# Both local datasets are supplied through the HF Dataset API expected by authors.
import datasets
original=datasets.load_dataset
def local_dataset(name,*pos,**kw):
config=pos[0] if pos else kw.get('name')
alias='sst2' if (name in ('glue','nyu-mll/glue') and config=='sst2') or name=='sst2' else ('drop' if name in ('drop','ucinlp/drop') else None)
if alias:
ds=datasets.load_from_disk(str(roots['data']/alias))
split=kw.get('split');return ds[split] if split else ds
return original(name,*pos,**kw)
datasets.load_dataset=local_dataset
model=str(model_path(args.asset_model))
if method=='loren':
if args.asset_task=='drop':raise ValueError('Official LOREN has no DROP task; use run_compatible.py with the modern group for a labeled task extension')
if 'Qwen' in args.asset_model:raise ValueError('Official LOREN has no Qwen model branch; use the modern compatibility entry')
entry=HERE/'main.py'
defaults=['--model_name',model,'--task',args.asset_task,'--algorithm','LOREN','--results',str(out),'--full_parameter']
else:
work=HERE/('zo-bench' if method=='agzo' else 'large_models')
entry=work/('run_lozo.py' if method=='lozo' else 'run.py')
task='SST2' if args.asset_task=='sst2' else 'DROP'
defaults=['--model_name',model,'--task_name',task,'--output_dir',str(out),'--trainer',{'mezo':'zo','lozo':'LOZO','agzo':'agzo'}[method],
'--report_to','none','--train_set_seed','42','--train_as_classification',str(task=='SST2'),'--lr_scheduler_type','constant']
defaults+=['--result_file',str(out/'result.json')]
# User's original HF/author flags appear last and override wrapper defaults.
if '--help' not in rest:
out.mkdir(parents=True,exist_ok=False)
save(out/'launch.json',dict(method=method,entry=str(entry),argv=defaults+rest,executable=sys.executable,adapter='Local assets and paths only; original Trainer/optimizer',pid=os.getpid()))
sys.path.insert(0,str(entry.parent));os.chdir(out if out.exists() else HERE)
sys.argv=[str(entry),*defaults,*rest]
if method=='agzo':
import torch
if torch.cuda.is_available() and not hasattr(torch,'npu'):
# The author's NPU helper has incomplete CUDA branches. Only device
# plumbing is adapted; trainer.py and AGZO numerical methods are intact.
import npu_compat as devices
devices.device_count=torch.cuda.device_count
devices.mem_get_info=torch.cuda.mem_get_info
devices.get_active_device_info=lambda:('cuda',torch.cuda.current_device(),torch.cuda.get_device_properties(0).total_memory/2**30,torch.cuda.get_device_name())
devices.safe_set_device=lambda index:(torch.cuda.set_device(int(index or 0)) or int(index or 0),torch.cuda.device_count())
devices.to_device=lambda tensor:tensor.cuda()
source=entry.read_text().replace('torch.npu.manual_seed_all(seed)','torch.cuda.manual_seed_all(seed)').replace('torch.npu.device_count()','torch.cuda.device_count()')
if out.exists():save(out/'compatibility_changes.json',{'scope':'CUDA device plumbing only','source_modified_on_disk':False,'numerical_optimizer_modified':False,'changes':['NPU seed -> CUDA seed','NPU device count -> CUDA count','device helper memory/info/count/set/to_device CUDA callbacks']})
exec(compile(source,str(entry),'exec'),dict(__name__='__main__',__file__=str(entry)))
return
runpy.run_path(str(entry),run_name='__main__')
if __name__=='__main__':main()
+34
View File
@@ -0,0 +1,34 @@
OPENPANGU MODEL LICENSE AGREEMENT VERSION 1.0
This OPENPANGU MODEL LICENSE AGREEMENT VERSION 1.0 (the "Agreement") is a legal agreement between You and Huawei Technologies Co., Ltd. ("Huawei", "We" or "Us"), and it governs Your reproducing, use, modification, and distribution of openPangu as made available by Huawei under this Agreement.
By using, reproducing, modifying, distributing, performing or displaying any portion or element of openPangu, or otherwise accepting the terms of this Agreement, You agree to be bound by this Agreement.
1. Definitions.
1.1. “openPangu” or “Model” means openPangu large language models and software, including trained model weights, parameters (including optimizer states), accompanying source code and scripts released under this Agreement.
1.2. “Derivative Model” means all (1) modifications to the Model, (2) works based on the Model, and (3) any other derivative works of the Model. For clarity, information or content results from operating or otherwise using the Model is not a Derivative Model.
1.3. “You” or “Your” means an individual or Legal Entity exercising permissions granted by this Agreement and/or using the Model for any purpose.
1.4. “Third Party” or “Third Parties” means individuals or legal entities that are not under common control with Us or You.
2. License Grant. Subject to Your full compliance with the terms and conditions of this Agreement, We hereby grant to You a perpetual, worldwide, non-exclusive, non-transferable, no-charge, royalty-free license (except as stated in Section 3) to use, reproduce, modify, and distribute the Model.
3. Conditions for License Grant. You represent and warrant that You will not, access, download, install, run, deploy, integrate, modify, or otherwise use the Model, directly or indirectly, within the European Union.
4. Redistribution.
4.1. If You distribute the Model or Derivative Model, You shall retain in Your distribution (1) a copy of this agreement, and (2) all copyright notices and other notices of origin included in the Model that are applicable to Your distribution.
4.2. Further, if You distribute or make available to Third Parties a product or service (including another AI model) based on the Model, You are required to (1) display the acknowledgement “Powered by openPangu” and (2) include a trademark notice “openPangu is a trademark of Huawei Technologies Co., Ltd.” on related webpages, user manuals, product documentations or other advertising materials mentioning features of the Model.
4.3. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for Derivative Model made by You as a whole, provided Your use, reproduction, and distribution of the Model otherwise complies with the terms and conditions of this Agreement.
5. Ownership. We do not claim ownership to any information or content generated using the Model or Derivative Model that are made by You. You are solely responsible for evaluating the accuracy and appropriateness of such information or content for Your use case.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of Huawei, except as required for complying with Section 4.2.
7. Indemnity. You will indemnify and hold harmless Huawei from and against any claim by any third party arising out of or related to Your use or distribution of the Model or Derivative Model made by You (e.g. a violation against Section 3). For avoidance of doubt, “third party” in this clause include supervisory authorities.
8. THE MODEL IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NONINFRINGEMENT, ACCURACY, OR THE ABSENCE OF LATENT OR OTHER DEFECTS OR ERRORS, WHETHER OR NOT DISCOVERABLE, ALL TO THE GREATEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW.
9. IN NO EVENT SHALL WE BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE MODEL, IN WHOLE OR IN PART, NO MATTER HOW IT’S CAUSED OR THE LEGAL THEORY IT IS BASED ON, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF THE TERMS AND CONDITIONS
+14
View File
@@ -0,0 +1,14 @@
[project]
name = "official-agzo-experiment"
version = "0.1.0"
requires-python = ">=3.11,<3.12"
dependencies = ["torch==2.13.0", "setuptools==80.9.0", "numpy==1.26.4", "matplotlib==3.10.7", "psutil==7.1.3", "scikit-learn==1.7.2", "sentencepiece==0.2.1", "wandb==0.23.1", "rouge==1.0.1", "nltk==3.9.2", "einops==0.8.1"]
[dependency-groups]
native = ["transformers==4.53.2", "datasets==2.21.0", "pyarrow==17.0.0", "accelerate==1.12.0", "huggingface-hub==0.36.0"]
modern = ["transformers==4.57.1", "datasets==3.6.0", "pyarrow==20.0.0", "accelerate==1.12.0", "huggingface-hub==0.36.0"]
[tool.uv]
package = false
default-groups = ["native"]
conflicts = [[{group="native"}, {group="modern"}]]
+71
View File
@@ -0,0 +1,71 @@
absl-py==2.3.1
accelerate==1.12.0
aiohttp==3.9.1
aiosignal==1.3.1
appdirs==1.4.4
async-timeout==4.0.3
attrs==23.1.0
certifi==2023.11.17
cffi==2.0.0
charset-normalizer==3.3.2
click==8.1.7
Cython==3.2.2
datasets==2.16.0
decorator==5.2.1
dill==0.3.7
docker-pycreds==0.4.0
einops==0.8.1
filelock==3.13.1
frozenlist==1.8.0
fsspec==2023.10.0
gitdb==4.0.11
GitPython==3.1.40
gmpy2==2.1.2
hf-xet==1.2.0
huggingface-hub==0.36.0
idna==3.6
Jinja2==3.1.2
joblib==1.3.2
llvmlite==0.41.1
MarkupSafe==2.1.3
modelscope==1.32.0
mpmath==1.3.0
multidict==6.0.4
multiprocess==0.70.15
networkx==3.4.2
numba==0.58.1
numpy==1.24.0
packaging==23.2
pandas==2.3.3
pathlib2==2.3.7.post1
protobuf==3.20.0
psutil==5.9.7
pyarrow==14.0.2
pyarrow-hotfix==0.6
pycparser==2.23
python-dateutil==2.8.2
pytz==2023.3.post1
PyYAML==6.0.1
regex==2023.12.25
requests==2.31.0
safetensors==0.7.0
scikit-learn==1.3.2
scipy==1.15.3
sentencepiece==0.2.1
sentry-sdk==1.39.1
setproctitle==1.3.3
six==1.16.0
smmap==5.0.1
sympy==1.13.1
threadpoolctl==3.2.0
tokenizers==0.21.4
torch==2.6.0
torch_npu==2.6.0
tqdm==4.66.1
transformers==4.53.2
typing_extensions==4.15.0
tzdata==2023.3
urllib3==2.1.0
wandb==0.23.1
xxhash==3.4.1
yarl==1.9.4
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
source /usr/local/Ascend/ascend-toolkit/set_env.sh
set -euo pipefail
TASK_NAME="SST2" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE.
SCRIPT_DIR="" # where the ZOLLM-npu repo is located
LOG_DIR="${SCRIPT_DIR}/log"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
LOG_FILE="${LOG_DIR}/${TIMESTAMP}_agzo_${TASK_NAME}_pangu-1b.log"
export NPU_ID=0 # the NPU ID to use
export ASCEND_DEVICE_ID=${NPU_ID}
export ASCEND_VISIBLE_DEVICES=${NPU_ID}
export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID}
export NPU_VISIBLE_DEVICES=${NPU_ID}
mkdir -p "${LOG_DIR}"
source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path
conda activate zollm
cd "${SCRIPT_DIR}"
nohup python zo-bench/run.py \
--trainer=agzo \
--model_name=FreedomIntelligence/openPangu-Embedded-1B \
--task_name=${TASK_NAME} \
--train_as_classification \
--perturbation_mode=two_side \
--zo_eps=1e-7 \
--learning_rate=1e-7 \
--num_train_epochs=5 \
--per_device_train_batch_size=16 \
--eval_strategy=steps \
--eval_steps=500 \
--save_steps=500 \
--max_steps=20000 \
--logging_steps=10 \
--num_eval=1000 \
--num_train=1000 \
--num_dev=500 \
--train_set_seed=0 \
--lr_scheduler_type=constant \
--output_dir=result/${TASK_NAME}-agzo-pangu-1b \
> "${LOG_FILE}" 2>&1 &
echo "已启动agzo训练,日志存储于: ${LOG_FILE}"
+7
View File
@@ -0,0 +1,7 @@
"""Modern task adapter calling pinned official numerical methods; not the original Trainer."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'src'))
from experiments_codebase.runner import main
if __name__ == '__main__':
main(forced_method='agzo')
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
source /usr/local/Ascend/ascend-toolkit/set_env.sh
set -euo pipefail
TASK_NAME="WIC" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE.
SCRIPT_DIR="" # where the ZOLLM-npu repo is located
LOG_DIR="${SCRIPT_DIR}/log"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
LOG_FILE="${LOG_DIR}/${TIMESTAMP}_fo_${TASK_NAME}_pangu-1b.log"
export NPU_ID=0 # the NPU ID to use
export ASCEND_DEVICE_ID=${NPU_ID}
export ASCEND_VISIBLE_DEVICES=${NPU_ID}
export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID}
export NPU_VISIBLE_DEVICES=${NPU_ID}
mkdir -p "${LOG_DIR}"
source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path
conda activate zollm
cd "${SCRIPT_DIR}"
nohup python zo-bench/run.py \
--trainer=sgd \
--model_name=FreedomIntelligence/openPangu-Embedded-1B \
--task_name=${TASK_NAME} \
--train_as_classification \
--num_train_epochs=5 \
--per_device_train_batch_size=8 \
--learning_rate=5e-6 \
--weight_decay=0 \
--lr_scheduler_type=constant \
--eval_strategy=steps \
--eval_steps=25 \
--max_steps=1000 \
--logging_steps=10 \
--num_eval=638 \
--num_train=1000 \
--num_dev=500 \
--train_set_seed=0 \
--output_dir=result/${TASK_NAME}-fo-sgd-pangu-1b \
> "${LOG_FILE}" 2>&1 &
echo "已启动fo训练,日志存储于: ${LOG_FILE}"
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
source /usr/local/Ascend/ascend-toolkit/set_env.sh
set -euo pipefail
TASK_NAME="Copa" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE.
SCRIPT_DIR="" # where the ZOLLM-npu repo is located
LOG_DIR="${SCRIPT_DIR}/log"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
LOG_FILE="${LOG_DIR}/${TIMESTAMP}_icl5_${TASK_NAME}_pangu-1b.log"
export NPU_ID=1 # the NPU ID to use
export ASCEND_DEVICE_ID=${NPU_ID}
export ASCEND_VISIBLE_DEVICES=${NPU_ID}
export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID}
export NPU_VISIBLE_DEVICES=${NPU_ID}
mkdir -p "${LOG_DIR}"
source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path
conda activate zollm
cd "${SCRIPT_DIR}"
nohup python zo-bench/run.py \
--trainer=none \
--model_name=FreedomIntelligence/openPangu-Embedded-1B \
--task_name=${TASK_NAME} \
--train_as_classification \
--num_train=5 \
--num_eval=1000 \
--train_set_seed=0 \
--output_dir=result/${TASK_NAME}-icl5-pangu-1b \
> "${LOG_FILE}" 2>&1 &
echo "已启动 5-shot ICL 评测,日志存储于: ${LOG_FILE}"
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
source /usr/local/Ascend/ascend-toolkit/set_env.sh
set -euo pipefail
TASK_NAME="SST2" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE.
SCRIPT_DIR="" # where the ZOLLM-npu repo is located
LOG_DIR="${SCRIPT_DIR}/log"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
LOG_FILE="${LOG_DIR}/${TIMESTAMP}_lozo_${TASK_NAME}_pangu-1b.log"
export NPU_ID=0 # the NPU ID to use
export ASCEND_DEVICE_ID=${NPU_ID}
export ASCEND_VISIBLE_DEVICES=${NPU_ID}
export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID}
export NPU_VISIBLE_DEVICES=${NPU_ID}
mkdir -p "${LOG_DIR}"
source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path
conda activate zollm
cd "${SCRIPT_DIR}"
nohup python zo-bench/run.py \
--trainer=lozo \
--lozo_rank=1 \
--model_name=FreedomIntelligence/openPangu-Embedded-1B \
--task_name=${TASK_NAME} \
--train_as_classification \
--perturbation_mode=two_side \
--zo_eps=1e-7 \
--learning_rate=5e-7 \
--num_train_epochs=5 \
--per_device_train_batch_size=16 \
--max_steps=20000 \
--logging_steps=10 \
--eval_strategy=steps \
--eval_steps=500 \
--num_eval=1000 \
--num_train=1000 \
--num_dev=500 \
--train_set_seed=0 \
--lr_scheduler_type=constant \
--output_dir=result/${TASK_NAME}-lozo-pangu-1b \
> "${LOG_FILE}" 2>&1 &
echo "已启动lozo训练,日志存储于: ${LOG_FILE}"
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
source /usr/local/Ascend/ascend-toolkit/set_env.sh
set -euo pipefail
TASK_NAME="Copa" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE.
SCRIPT_DIR="" # where the ZOLLM-npu repo is located
LOG_DIR="${SCRIPT_DIR}/log"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
LOG_FILE="${LOG_DIR}/${TIMESTAMP}_zeroshot_${TASK_NAME}_pangu-1b.log"
export NPU_ID=0 # the NPU ID to use
export ASCEND_DEVICE_ID=${NPU_ID}
export ASCEND_VISIBLE_DEVICES=${NPU_ID}
export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID}
export NPU_VISIBLE_DEVICES=${NPU_ID}
mkdir -p "${LOG_DIR}"
source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path
conda activate zollm
cd "${SCRIPT_DIR}"
nohup python zo-bench/run.py \
--trainer=none \
--model_name=FreedomIntelligence/openPangu-Embedded-1B \
--task_name=${TASK_NAME} \
--train_as_classification \
--num_train=0 \
--num_eval=1000 \
--train_set_seed=0 \
--output_dir=result/${TASK_NAME}-zeroshot-pangu-1b \
> "${LOG_FILE}" 2>&1 &
echo "已启动 zero-shot 评测,日志存储于: ${LOG_FILE}"
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env bash
source /usr/local/Ascend/ascend-toolkit/set_env.sh
set -euo pipefail
TASK_NAME="Copa" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE.
SCRIPT_DIR="" # where the ZOLLM-npu repo is located
LOG_DIR="${SCRIPT_DIR}/log"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
LOG_FILE="${LOG_DIR}/${TIMESTAMP}_zosgd_${TASK_NAME}_pangu-1b.log"
export NPU_ID=0 # the NPU ID to use
export ASCEND_DEVICE_ID=${NPU_ID}
export ASCEND_VISIBLE_DEVICES=${NPU_ID}
export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID}
export NPU_VISIBLE_DEVICES=${NPU_ID}
mkdir -p "${LOG_DIR}"
source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path
conda activate zollm
cd "${SCRIPT_DIR}"
nohup python zo-bench/run.py \
--trainer=zo_sgd \
--model_name=FreedomIntelligence/openPangu-Embedded-1B \
--task_name=${TASK_NAME} \
--train_as_classification \
--perturbation_mode=two_side \
--zo_eps=1e-7 \
--learning_rate=1e-7 \
--num_train_epochs=5 \
--per_device_train_batch_size=16 \
--max_steps=20000 \
--logging_steps=10 \
--eval_strategy=steps \
--eval_steps=500 \
--num_eval=1000 \
--num_train=300 \
--num_dev=100 \
--train_set_seed=0 \
--lr_scheduler_type=constant \
--output_dir=result/${TASK_NAME}-zo-sgd-pangu-1b \
> "${LOG_FILE}" 2>&1 &
echo "已启动zo_sgd训练,日志存储于: ${LOG_FILE}"
+1682
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
null
@@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
# @Author: pingzhili
# @Time: 2024/1/17
@@ -0,0 +1,71 @@
# -*- coding: utf-8 -*-
# @Author: pingzhili
# @Time: 2024/1/18
from typing import Dict
import torch
from transformers import PreTrainedModel
@torch.no_grad()
def random_mask_like(tensor, nonzero_ratio, generator=None):
"""
Return a random mask with the same shape as the input tensor, where the fraction of True is equal to the sparsity.
Examples
--------
>>> random_mask_like(torch.randn(10, 10), 0.1).count_nonzero()
tensor(10)
"""
mask = torch.zeros_like(tensor)
mask.view(-1)[torch.randperm(mask.numel(), generator=generator)[:int(nonzero_ratio * mask.numel())]] = 1
return mask.bool()
@torch.no_grad()
def fast_random_mask_like(tensor, nonzero_ratio, generator=None):
"""
A much faster version of random_zero_mask_like, but the sparsity is not guaranteed.
Examples
--------
>>> fast_random_mask_like(torch.randn(10, 10), 0.1).count_nonzero() < 20
tensor(True)
"""
mask = torch.empty_like(tensor).normal_(generator=generator) < nonzero_ratio
return mask.bool()
@torch.no_grad()
def estimate_pretrained_model_magnitude_pruning_threshold(
model: PreTrainedModel,
global_sparsity: float,
) -> float:
"""
Compute the magnitude threshold for pruning based on the global sparsity requirement.
"""
all_weights = []
for param in model.parameters():
all_weights.append(
param.view(-1).abs().clone().detach().cpu()
)
all_weights = torch.cat(all_weights)
# subsample 102400 elements to estimate the threshold
sample_size = int(min(1e7, all_weights.numel()))
print(f"[Sparse gradient] Subsampling {sample_size} elements to estimate the threshold.")
sub_weights = all_weights[torch.randperm(all_weights.numel())[:sample_size]]
return torch.quantile(sub_weights.float(), global_sparsity).item()
@torch.no_grad()
def compute_named_parameters_to_sparsity(
model: PreTrainedModel,
threshold: float,
) -> Dict[str, float]:
"""
Compute the sparsity of each named parameter in the model.
"""
named_parameters_to_sparsity = {}
for name, param in model.named_parameters():
named_parameters_to_sparsity[name] = param.abs().le(threshold).float().mean().item()
return named_parameters_to_sparsity
@@ -0,0 +1,60 @@
# -*- coding: utf-8 -*-
# @Author: pingzhili
# @Time: 2024/1/17
"""WANDA: Pruning by Weights and activations (https://arxiv.org/pdf/2306.11695.pdf)"""
from dataclasses import dataclass
from typing import Optional
import torch
from transformers import PreTrainedModel
@dataclass
class WandaPruningConfig:
sparsity: Optional[float] = 0.5
comparison_group: Optional[str] = "model" # model, layer, linear
scaler_device: Optional[str] = "cuda"
class WandaPruner:
def __init__(
self,
config: WandaPruningConfig,
model: PreTrainedModel,
):
self.model = model
self.config = config
self.linear_module_scaler_dict = {}
self.linear_module_num_samples_dict = {}
self.linear_module_hook_dict = {}
self._init_hooks_and_scaler()
def _init_hooks_and_scaler(self):
device = self.config.scaler_device
def _get_forward_hook(name, input_dim):
def _forward_hook(module, input, output):
input = input.reshape(-1, input_dim)
num_prev_samples = self.linear_module_num_samples_dict[name]
num_curr_samples = input.shape[0]
self.linear_module_scaler_dict[name] *= (num_prev_samples / (num_prev_samples + num_curr_samples))
self.linear_module_num_samples_dict[name] += num_curr_samples
self.linear_module_scaler_dict[name] += torch.norm(
input, dim=0, p=2
) / (num_prev_samples + num_curr_samples)
return _forward_hook
for name, module in self.model.named_modules():
if isinstance(module, torch.nn.Linear):
self.linear_module_num_samples_dict[name] = 0
self.linear_module_scaler_dict[name] = torch.ones(module.weight.shape[1], device=device)
_hook = module.register_forward_hook(_get_forward_hook(name, module.weight.shape[1]))
self.linear_module_hook_dict[name] = _hook
def remove_hooks(self):
for name, hook in self.linear_module_hook_dict.items():
hook.remove()
+204
View File
@@ -0,0 +1,204 @@
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
import torch
from torch import nn
from torch.nn import functional as F
import math
def find_module(root_module: nn.Module, key: str):
"""
Find a module with a specific name in a Transformer model
From OpenDelta https://github.com/thunlp/OpenDelta
"""
sub_keys = key.split(".")
parent_module = root_module
for sub_key in sub_keys[:-1]:
parent_module = getattr(parent_module, sub_key)
module = getattr(parent_module, sub_keys[-1])
return parent_module, sub_keys[-1], module
class LoRALinear(nn.Linear):
"""
LoRA implemented in a dense layer
From https://github.com/microsoft/LoRA/blob/main/loralib/layers.py
"""
def __init__(
self,
in_features: int,
out_features: int,
r: int = 0,
lora_alpha: int = 1,
lora_dropout: float = 0.,
fan_in_fan_out: bool = False,
# Set this to True if the layer to replace stores weight like (fan_in, fan_out)
merge_weights: bool = False,
# Not sure if this will affect saving/loading models so just set it to be False
**kwargs
):
nn.Linear.__init__(self, in_features, out_features, **kwargs)
self.r = r
self.lora_alpha = lora_alpha
# Optional dropout
if lora_dropout > 0.:
self.lora_dropout = nn.Dropout(p=lora_dropout)
else:
self.lora_dropout = lambda x: x
# Mark the weight as unmerged
self.merged = False
self.merge_weights = merge_weights
self.fan_in_fan_out = fan_in_fan_out
# Actual trainable parameters
if r > 0:
self.lora_A = nn.Parameter(self.weight.new_zeros((r, in_features)))
self.lora_B = nn.Parameter(self.weight.new_zeros((out_features, r)))
self.scaling = self.lora_alpha / self.r
# Freezing the pre-trained weight matrix
self.weight.requires_grad = False
self.reset_parameters()
if fan_in_fan_out:
self.weight.data = self.weight.data.transpose(0, 1)
def reset_parameters(self):
nn.Linear.reset_parameters(self)
if hasattr(self, 'lora_A'):
# initialize A the same way as the default for nn.Linear and B to zero
nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
nn.init.zeros_(self.lora_B)
def train(self, mode: bool = True):
def T(w):
return w.transpose(0, 1) if self.fan_in_fan_out else w
nn.Linear.train(self, mode)
if mode:
if self.merge_weights and self.merged:
# Make sure that the weights are not merged
if self.r > 0:
self.weight.data -= T(self.lora_B @ self.lora_A) * self.scaling
self.merged = False
else:
if self.merge_weights and not self.merged:
# Merge the weights and mark it
if self.r > 0:
self.weight.data += T(self.lora_B @ self.lora_A) * self.scaling
self.merged = True
def forward(self, x: torch.Tensor):
def T(w):
return w.transpose(0, 1) if self.fan_in_fan_out else w
if self.r > 0 and not self.merged:
result = F.linear(x, T(self.weight), bias=self.bias)
if self.r > 0:
result += (self.lora_dropout(x) @ self.lora_A.transpose(0, 1) @ self.lora_B.transpose(0,
1)) * self.scaling
return result
else:
return F.linear(x, T(self.weight), bias=self.bias)
class LoRA:
def __init__(self, model, r, alpha, float16):
"""
Input:
r, alpha: LoRA hyperparameters
float16: Whether the model parameters are float16 or not
"""
self.model = model
self.hidden_dim = model.config.hidden_size
self.float16 = float16
if model.config.model_type == "opt":
attention_name = "attn"
elif model.config.model_type == "roberta":
attention_name = "attention"
elif model.config.model_type in ["llama", "mistral"]:
attention_name = "self_attn"
else:
raise NotImplementedError
# Insert LoRA
for key, _ in model.named_modules():
if key[-len(attention_name):] == attention_name:
logger.info(f"Inject lora to: {key}")
_, _, attn = find_module(model, key)
if model.config.model_type == "opt":
original_q_weight = attn.q_proj.weight.data
original_q_bias = attn.q_proj.bias.data
original_v_weight = attn.v_proj.weight.data
original_v_bias = attn.v_proj.bias.data
attn.q_proj = LoRALinear(model.config.hidden_size, model.config.hidden_size, r=r, lora_alpha=alpha,
bias=model.config.enable_bias).to(original_q_weight.device)
attn.v_proj = LoRALinear(model.config.hidden_size, model.config.hidden_size, r=r, lora_alpha=alpha,
bias=model.config.enable_bias).to(original_v_weight.device)
if float16:
attn.q_proj.half()
attn.v_proj.half()
attn.q_proj.weight.data = original_q_weight
attn.q_proj.bias.data = original_q_bias
attn.v_proj.weight.data = original_v_weight
attn.v_proj.bias.data = original_v_bias
elif model.config.model_type == "llama":
# in early version of transformers, llama attention bias is hard coded to False
attention_bias = False if not hasattr(model.config, "attention_bias") else model.config.attention_bias
original_q_weight = attn.q_proj.weight.data
original_v_weight = attn.v_proj.weight.data
original_q_bias = attn.q_proj.bias.data if attention_bias else None
original_v_bias = attn.v_proj.bias.data if attention_bias else None
attn.q_proj = LoRALinear(
model.config.hidden_size,
model.config.hidden_size,
r=r, lora_alpha=alpha, bias=attention_bias
).to(original_q_weight.device)
attn.v_proj = LoRALinear(
model.config.hidden_size,
model.config.hidden_size,
r=r, lora_alpha=alpha, bias=attention_bias
).to(original_v_weight.device)
if float16:
attn.q_proj.half()
attn.v_proj.half()
attn.q_proj.weight.data = original_q_weight
attn.v_proj.weight.data = original_v_weight
if attention_bias:
attn.q_proj.bias.data = original_q_bias
attn.v_proj.bias.data = original_v_bias
elif model.config.model_type == "mistral":
# in early version of transformers, llama attention bias is hard coded to False
config = model.config
original_q_weight = attn.q_proj.weight.data
original_v_weight = attn.v_proj.weight.data
head_dim = config.hidden_size // config.num_attention_heads
attn.q_proj = LoRALinear(
config.hidden_size,
config.hidden_size,
r=r, lora_alpha=alpha
).to(original_q_weight.device)
attn.v_proj = LoRALinear(
config.hidden_size,
config.num_key_value_heads * head_dim,
r=r, lora_alpha=alpha
).to(original_v_weight.device)
if float16:
attn.q_proj.half()
attn.v_proj.half()
attn.q_proj.weight.data = original_q_weight
attn.v_proj.weight.data = original_v_weight
else:
raise NotImplementedError
# Freeze non-LoRA parameters
for n, p in model.named_parameters():
if "lora" not in n:
p.requires_grad = False
+78
View File
@@ -0,0 +1,78 @@
import numpy as np
import collections
import re
import string
from collections import Counter
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
return re.sub(r'\b(a|an|the)\b', ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def calculate_metric(predictions, metric_name):
if metric_name == "accuracy":
if isinstance(predictions[0].correct_candidate, list):
return np.mean([pred.predicted_candidate in pred.correct_candidate for pred in predictions])
else:
return np.mean([pred.correct_candidate == pred.predicted_candidate for pred in predictions])
elif metric_name == "em":
# For question answering
return np.mean([any([normalize_answer(ans) == normalize_answer(pred.predicted_candidate) for ans in pred.correct_candidate]) for pred in predictions])
elif metric_name == "f1":
# For question answering
f1 = []
for pred in predictions:
all_f1s = []
if pred.correct_candidate[0] == "CANNOTANSWER" or pred.correct_candidate[0] == "no answer":
f1.append(int(normalize_answer(pred.correct_candidate[0]) == normalize_answer(pred.predicted_candidate)))
else:
for ans in pred.correct_candidate:
prediction_tokens = normalize_answer(pred.predicted_candidate).split()
ground_truth_tokens = normalize_answer(ans).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
all_f1s.append(0)
else:
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
all_f1s.append((2 * precision * recall) / (precision + recall))
f1.append(max(all_f1s))
return np.mean(f1)
def f1(pred, gold):
"""
This separate F1 function is used as non-differentiable metric for SQuAD
"""
if gold[0] == "CANNOTANSWER" or gold[0] == "no answer":
return int(normalize_answer(gold[0]) == normalize_answer(pred))
else:
all_f1s = []
for ans in gold:
prediction_tokens = normalize_answer(pred).split()
ground_truth_tokens = normalize_answer(ans).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
all_f1s.append(0)
else:
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
all_f1s.append((2 * precision * recall) / (precision + recall))
return np.max(all_f1s)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,8 @@
from .configuration_mistral import MistralConfig, MISTRAL_PRETRAINED_CONFIG_ARCHIVE_MAP
from .modeling_mistral import (
MistralModel,
MistralForCausalLM,
MistralForSequenceClassification,
MistralPreTrainedModel,
MistralForCausalLMWithHeadTuning
)
@@ -0,0 +1,152 @@
# coding=utf-8
# Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# 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
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Mistral model configuration"""
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import logging
logger = logging.get_logger(__name__)
MISTRAL_PRETRAINED_CONFIG_ARCHIVE_MAP = {
"mistralai/Mistral-7B-v0.1": "https://huggingface.co/mistralai/Mistral-7B-v0.1/resolve/main/config.json",
"mistralai/Mistral-7B-Instruct-v0.1": "https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1/resolve/main/config.json",
}
class MistralConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`MistralModel`]. It is used to instantiate an
Mistral model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the Mistral-7B-v0.1 or Mistral-7B-Instruct-v0.1.
[mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1)
[mistralai/Mistral-7B-Instruct-v0.1](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1)
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 32000):
Vocabulary size of the Mistral model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`MistralModel`]
hidden_size (`int`, *optional*, defaults to 4096):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 14336):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 32):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer encoder.
num_key_value_heads (`int`, *optional*, defaults to 8):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details checkout [this
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
The maximum sequence length that this model might ever be used with. Mistral's sliding window attention
allows sequence of up to 4096*32 tokens.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the rms normalization layers.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
pad_token_id (`int`, *optional*):
The id of the padding token.
bos_token_id (`int`, *optional*, defaults to 1):
The id of the "beginning-of-sequence" token.
eos_token_id (`int`, *optional*, defaults to 2):
The id of the "end-of-sequence" token.
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether the model's input and output word embeddings should be tied.
rope_theta (`float`, *optional*, defaults to 10000.0):
The base period of the RoPE embeddings.
sliding_window (`int`, *optional*, defaults to 4096):
Sliding window attention window size. If not specified, will default to `4096`.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
```python
>>> from transformers import MistralModel, MistralConfig
>>> # Initializing a Mistral 7B style configuration
>>> configuration = MistralConfig()
>>> # Initializing a model from the Mistral 7B style configuration
>>> model = MistralModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "mistral"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
vocab_size=32000,
hidden_size=4096,
intermediate_size=14336,
num_hidden_layers=32,
num_attention_heads=32,
num_key_value_heads=8,
hidden_act="silu",
max_position_embeddings=4096 * 32,
initializer_range=0.02,
rms_norm_eps=1e-6,
use_cache=True,
pad_token_id=None,
bos_token_id=1,
eos_token_id=2,
tie_word_embeddings=False,
rope_theta=10000.0,
sliding_window=4096,
attention_dropout=0.0,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.sliding_window = sliding_window
# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.attention_dropout = attention_dropout
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+488
View File
@@ -0,0 +1,488 @@
"""用于统一 NPU/CUDA 调用的兼容性辅助函数。
该模块提供了一组在仓库中复用的轻量函数,优先使用 `torch.npu` 或
`torch_npu`(如果可用)的 NPU 能力;若无则回退到 CUDA;再无则使用 CPU。
仅提供小而明确的辅助,避免对现有代码做大规模侵入式改动。
"""
from __future__ import annotations
import contextlib
import typing
import torch
import importlib
import warnings
import os
_HAS_TORCH_NPU = False
try:
# 部分 NPU 发行版直接提供 `torch.npu`,或通过独立的 `torch_npu` 包暴露接口。
if hasattr(torch, "npu"):
_HAS_TORCH_NPU = True
else:
# 在导入 torch_npu 时屏蔽常见的冗余告警
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
category=ImportWarning,
module=r"torch_npu\.contrib\.transfer_to_npu",
)
warnings.filterwarnings(
"ignore",
category=RuntimeWarning,
message=r".*torch\.jit\.script.*",
)
importlib.import_module("torch_npu")
_HAS_TORCH_NPU = True
except Exception:
_HAS_TORCH_NPU = False
def is_npu_available() -> bool:
"""返回 NPU 运行时是否可用。"""
if _HAS_TORCH_NPU and hasattr(torch, "npu"):
try:
return torch.npu.is_available()
except Exception:
return True
return False
# 返回可用设备数量(优先 NPU)
def device_count() -> int:
if is_npu_available() and hasattr(torch, "npu"):
try:
return torch.npu.device_count()
except Exception:
return 0
# 查询当前设备的可用/总内存,优先 NPU
def mem_get_info() -> typing.Tuple[int, int]:
"""返回当前设备的 (free, total) 内存信息(字节)。
"""
# 若存在 torch.npu 且提供 mem_get_info 风格的接口则优先使用
if is_npu_available() and hasattr(torch, "npu"):
try:
if hasattr(torch.npu, "mem_get_info"):
return torch.npu.mem_get_info()
except Exception:
pass
# 尝试 torch_npu 包(许多发行版在此暴露 NPU 辅助接口)
try:
tn = importlib.import_module("torch_npu")
# 常见位置:torch_npu.npu.memory_stats / memory_stats_as_nested_dict
npu_mod = getattr(tn, "npu", None)
# 从统计字典中抽取 free/total 的辅助函数
def _extract_free_total(stats) -> typing.Optional[typing.Tuple[int, int]]:
# 非字典则直接放弃
if not isinstance(stats, dict):
return None
# 直接键命中
if "total" in stats and "free" in stats:
try:
return int(stats["free"]), int(stats["total"])
except Exception:
pass
# 常见模式:total 与 used/allocated -> free = total - used
if "total" in stats and ("used" in stats or "allocated" in stats):
try:
used = int(stats.get("used", stats.get("allocated")))
total = int(stats["total"])
return max(total - used, 0), total
except Exception:
pass
# reserved/allocated 模式
if "reserved" in stats and "allocated" in stats:
try:
total = int(stats.get("reserved"))
allocated = int(stats.get("allocated"))
return max(total - allocated, 0), total
except Exception:
pass
# 展平嵌套字典并搜索可能的键
def _walk(d):
for k, v in d.items():
if isinstance(v, dict):
for sub in _walk(v):
yield sub
else:
yield (k, v)
flat = dict(_walk(stats))
# 尝试找到数值候选项
nums = {k: v for k, v in flat.items() if isinstance(v, (int, float))}
if not nums:
return None
# 启发式:优先包含 'total' 与 'free'/'avail'/'used' 的键
total_key = None
free_key = None
for k in nums:
lk = k.lower()
if "total" in lk or "reserved" in lk:
total_key = k
break
for k in nums:
lk = k.lower()
if "free" in lk or "avail" in lk or "available" in lk:
free_key = k
break
if total_key and free_key:
try:
return int(nums[free_key]), int(nums[total_key])
except Exception:
pass
# 回退:若有 total 与任一 allocated/used,则计算 free
if total_key:
for k in nums:
lk = k.lower()
if "used" in lk or "alloc" in lk:
try:
return max(int(nums[total_key]) - int(nums[k]), 0), int(nums[total_key])
except Exception:
pass
return None
# 若可用,优先使用 npu.memory_stats
if npu_mod is not None:
try:
if hasattr(npu_mod, "memory_stats"):
stats = npu_mod.memory_stats(device=None)
got = _extract_free_total(stats)
if got:
return got
if hasattr(npu_mod, "memory_stats_as_nested_dict"):
stats = npu_mod.memory_stats_as_nested_dict(device=None)
got = _extract_free_total(stats)
if got:
return got
# 尝试其他辅助接口
if hasattr(npu_mod, "memory_summary"):
# memory_summary 返回字符串,为安全起见不解析
pass
except Exception:
pass
# 最后尝试 torch_npu 顶层的相关辅助
for name in ["memory_stats", "memory_stats_as_nested_dict", "memory_snapshot", "memory_summary"]:
fn = getattr(tn, name, None)
if callable(fn):
try:
stats = fn() if name != "memory_summary" else None
if stats is not None:
got = _extract_free_total(stats)
if got:
return got
except Exception:
pass
except Exception:
pass
# NPU/CUDA 内存接口均不可用:返回安全默认值
try:
import warnings
warnings.warn("npu_compat.mem_get_info: no NPU mem API found and CUDA unavailable; returning (0,0)")
except Exception:
pass
return (0, 0)
# 获取设备的峰值已分配显存(优先 NPU)
def max_memory_allocated(device: typing.Optional[int] = None) -> int:
if is_npu_available() and hasattr(torch, "npu"):
try:
if device is None:
return torch.npu.max_memory_allocated()
return torch.npu.max_memory_allocated(device)
except Exception:
pass
# 重置峰值已分配显存统计(优先 NPU)
def reset_max_memory_allocated(device: typing.Optional[int] = None):
if is_npu_available() and hasattr(torch, "npu"):
try:
if device is None:
return torch.npu.reset_max_memory_allocated()
return torch.npu.reset_max_memory_allocated(device)
except Exception:
pass
# 重置峰值显存统计(优先 NPU)
def reset_peak_memory_stats():
if is_npu_available() and hasattr(torch, "npu"):
try:
return torch.npu.reset_peak_memory_stats()
except Exception:
pass
# 清理缓存显存(优先 NPU)
def empty_cache():
if is_npu_available() and hasattr(torch, "npu"):
try:
return torch.npu.empty_cache()
except Exception:
pass
# 为所有设备设置随机种子(优先 NPU)
def manual_seed_all(seed: int):
if is_npu_available():
torch.npu.manual_seed_all(seed)
else:
logging.warning("manual_seed_all: NPU not available, falling back to CUDA if available")
# 设备同步(优先 NPU,再到 CUDA)
def synchronize():
"""同步设备;优先 NPU,再到 CUDA,尽力而为。"""
if is_npu_available() and hasattr(torch, "npu"):
try:
if hasattr(torch.npu, "synchronize"):
return torch.npu.synchronize()
except Exception:
pass
# 返回自动混合精度上下文应使用的设备类型
def manual_device_type() -> str:
"""返回自动混合精度/上下文优选的设备类型字符串:'npu'|'cpu'。"""
if is_npu_available():
return "npu"
return "cpu"
# 设置当前活动设备(优先 NPU)
def set_device(index: int) -> None:
"""按索引选择 NPU 的活动设备。
- NPU:优先 `torch.npu.set_device(index)`,若用户已设置 `ASCEND_VISIBLE_DEVICES` 亦尊重。
- CPU:不执行任何操作。
可在模型创建前的程序启动阶段安全调用。
"""
try:
if index is None:
return
# Normalize index to int
idx = int(index)
except Exception:
return
# Prefer NPU if available
if is_npu_available() and hasattr(torch, "npu"):
try:
# If the environment already constrains visible devices, we still set current device
if hasattr(torch.npu, "set_device"):
torch.npu.set_device(idx)
return
except Exception:
pass
# Fallback: some distros may expose set_device under torch_npu.npu
try:
tn = importlib.import_module("torch_npu")
if hasattr(tn, "npu") and hasattr(tn.npu, "set_device"):
tn.npu.set_device(idx)
return
except Exception:
pass
# CPU: nothing to do
return
def safe_set_device(index: typing.Optional[int]) -> int:
"""安全设置活动设备索引,并返回最终生效的索引。
- 将传入索引规范化为 `int`;若无效则回退为 0。
- 使用 `device_count()` 对索引进行边界裁剪,避免越界或负值。
- 调用 `set_device()` 应用设备选择(优先 NPU,回退 CUDA)。
- 返回最终使用的设备索引。
"""
try:
idx = int(index) if index is not None else 0
except Exception:
idx = 0
try:
visible = device_count()
except Exception:
visible = None
if visible and (idx < 0 or idx >= visible):
idx = 0
set_device(idx)
return idx,visible
# 将张量移动到可用设备(优先 NPU)
def to_device(t: torch.Tensor) -> torch.Tensor:
"""若有 NPU 则迁移到 NPU,否则若有 CUDA 则迁移到 CUDA,否则保持不变。"""
if is_npu_available():
try:
return t.npu()
except Exception:
return t.to("npu")
return t
# 获取自动混合精度的 GradScaler(优先 NPU)
def amp_grad_scaler(enabled: bool = True):
"""返回可用设备的 AMP GradScaler(优先 NPU)。"""
# 若存在 torch.npu.amp 则优先
if is_npu_available() and hasattr(torch, "npu") and hasattr(torch, "amp") and hasattr(torch.amp, "GradScaler"):
try:
# Some NPU distributions expose amp under torch.amp
return torch.amp.GradScaler(enabled=enabled)
except Exception:
pass
# 根据优选设备类型封装 autocast 上下文
@contextlib.contextmanager
def autocast(dtype=torch.float16, enabled=True):
"""为优选设备类型封装 torch.autocast 的上下文管理器。"""
device_type = manual_device_type()
if device_type == "cpu":
# CPU 不支持或无需 autocast:直接空操作
yield
else:
# torch.autocast 支持 device_type 字符串
with torch.autocast(device_type=device_type, dtype=dtype, enabled=enabled):
yield
# 设备名称查询(优先 NPU,再到 CUDA)
def get_device_name(index: typing.Optional[int] = None) -> typing.Optional[str]:
"""返回指定设备索引的设备名称/芯片型号。
- NPU:优先使用 `torch.npu.get_device_name`,回退到 `torch_npu.get_device_name`
或 `torch_npu.npu.get_device_name`(若可用)。
- CPU:返回 None。
"""
try:
idx = int(index) if index is not None else None
except Exception:
idx = None
if is_npu_available() and hasattr(torch, "npu"):
try:
if hasattr(torch.npu, "get_device_name"):
return str(torch.npu.get_device_name(idx if idx is not None else 0))
except Exception:
pass
try:
tn = importlib.import_module("torch_npu")
if hasattr(tn, "get_device_name"):
return str(tn.get_device_name(idx if idx is not None else 0))
if hasattr(tn, "npu") and hasattr(tn.npu, "get_device_name"):
return str(tn.npu.get_device_name(idx if idx is not None else 0))
except Exception:
pass
return None
def current_device_index() -> typing.Optional[int]:
"""返回当前活动设备索引(优先 NPU,再到 CUDA)。若不可用则返回 None。"""
if is_npu_available() and hasattr(torch, "npu"):
try:
if hasattr(torch.npu, "current_device"):
return int(torch.npu.current_device())
except Exception:
pass
return 0
return None
def get_active_device_info() -> typing.Tuple[typing.Optional[str], typing.Optional[int], typing.Optional[int], typing.Optional[str]]:
"""返回当前活跃设备信息 (dev_type, dev_idx, total_gb, device_name)。
- dev_type: 'npu' | None(CPU/未知)
- dev_idx: 设备索引(若未知则 0,CPU 则 None)
- total_gb: 设备总显存(GB,若不可得则 None)
- device_name: 设备名称/芯片型号(若不可得则 None)
"""
dev_type: typing.Optional[str] = None
dev_idx: typing.Optional[int] = None
total_gb: typing.Optional[int] = None
device_name: typing.Optional[str] = None
try:
if is_npu_available():
dev_type = "npu"
try:
dev_idx = current_device_index()
if dev_idx is None:
dev_idx = 0
except Exception:
dev_idx = 0
try:
_, total_b = mem_get_info()
total_gb = int(total_b / 1024 ** 3) if total_b else None
except Exception:
total_gb = None
try:
device_name = get_device_name(dev_idx)
except Exception:
device_name = None
except Exception:
logging.warning("get_active_device_info: failed to get device info", exc_info=True)
return dev_type, dev_idx, total_gb, device_name
def collect_npu_memory_metrics() -> dict:
"""收集设备显存指标(优先 NPU,回退 CUDA),返回用于日志的字典。
指标包括:
- npu_mem_free_gb / npu_mem_used_gb / npu_mem_total_gb
- npu_mem_peak_gb(所有设备峰值分配总和)
- 以及可选的 allocated/reserved 当前/峰值(若 torch_npu.memory_stats 可用)
"""
metrics: dict = {}
# 基础 free/total/used
try:
free_bytes, total_bytes = mem_get_info()
used_bytes = max((total_bytes or 0) - (free_bytes or 0), 0)
if total_bytes:
metrics["npu_mem_free_gb"] = free_bytes / 1024 ** 3
metrics["npu_mem_used_gb"] = used_bytes / 1024 ** 3
metrics["npu_mem_total_gb"] = total_bytes / 1024 ** 3
except Exception:
pass
# 峰值统计(汇总所有设备)
try:
peak_bytes = 0
for device_id in range(device_count()):
peak_bytes += max_memory_allocated(device_id)
if peak_bytes:
metrics["npu_mem_peak_gb"] = peak_bytes / 1024 ** 3
except Exception:
pass
# 详细统计(若 torch_npu 可用)
try:
tn = importlib.import_module("torch_npu") # 可选依赖
stats = None
if hasattr(tn, "npu") and hasattr(tn.npu, "memory_stats"):
stats = tn.npu.memory_stats()
elif hasattr(tn, "memory_stats"):
stats = tn.memory_stats()
if isinstance(stats, dict):
current_alloc = stats.get("allocated_bytes.all.current")
peak_alloc = stats.get("allocated_bytes.all.peak")
reserved_alloc = stats.get("reserved_bytes.all.current")
if current_alloc is not None:
metrics["npu_mem_allocated_gb"] = current_alloc / 1024 ** 3
if peak_alloc is not None:
metrics["npu_mem_allocated_peak_gb"] = peak_alloc / 1024 ** 3
if reserved_alloc is not None:
metrics["npu_mem_reserved_gb"] = reserved_alloc / 1024 ** 3
except Exception:
pass
return metrics
+213
View File
@@ -0,0 +1,213 @@
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
import torch
from torch import nn
import npu_compat as npu
def find_module(root_module: nn.Module, key: str):
"""
Find a module with a specific name in a Transformer model
From OpenDelta https://github.com/thunlp/OpenDelta
"""
sub_keys = key.split(".")
parent_module = root_module
for sub_key in sub_keys[:-1]:
parent_module = getattr(parent_module, sub_key)
module = getattr(parent_module, sub_keys[-1])
return parent_module, sub_keys[-1], module
def attn_forward_hook(self, *args, **kwargs):
"""
Replace the original attention forward with this to enable prefix
"""
def _expand_bsz(x, bsz):
x = x.reshape(x.size(0), self.num_heads, -1).transpose(0,
1) # (num_prefix, hidden) -> (num_head, num_prefix, hidden/num_head)
x = x.unsqueeze(0).expand(bsz, *x.shape) # -> (bsz, num_head, num_prefix, hidden/num_head)
return x
if "hidden_states" in kwargs:
hidden_states = kwargs["hidden_states"]
else:
hidden_states = args[0]
bsz = hidden_states.size(0)
if 'past_key_value' not in kwargs or kwargs['past_key_value'] is None:
if self.reparam:
prefix_keys = self.prefix_mlp_keys(self.prefix_input_embeds)
prefix_values = self.prefix_mlp_values(self.prefix_input_embeds)
else:
prefix_keys, prefix_values = self.prefix_keys, self.prefix_values
kwargs['past_key_value'] = (_expand_bsz(prefix_keys, bsz), _expand_bsz(prefix_values, bsz))
if 'attention_mask' in kwargs and kwargs['attention_mask'] is not None:
am = kwargs['attention_mask']
kwargs['attention_mask'] = torch.cat(
[-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1)
elif len(args) > 1: # attention mask is passed via positional argument
am = args[1]
am = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am],
dim=-1)
args = (args[0], am) + args[2:]
return self.original_forward(*args, **kwargs)
def prepare_inputs_for_generation(
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs):
"""
Replace the original "prepare_inputs_for_generation" with this to pass prefix correctly
"""
original_input_len = input_ids.size(-1)
if past_key_values:
input_ids = input_ids[:, -1:]
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
if inputs_embeds is not None and past_key_values is None:
model_inputs = {"inputs_embeds": inputs_embeds}
else:
model_inputs = {"input_ids": input_ids}
if past_key_values is not None:
# Check if we should add extra to attention mask
if past_key_values[0][0].size(2) != attention_mask.size(1) - 1:
num_prefix = past_key_values[0][0].size(2) - (attention_mask.size(1) - 1)
attention_mask = torch.cat([torch.ones((attention_mask.size(0), num_prefix), dtype=attention_mask.dtype,
device=attention_mask.device), attention_mask], dim=-1)
model_inputs.update(
{
"past_key_values": past_key_values,
"use_cache": kwargs.get("use_cache"),
"attention_mask": attention_mask,
}
)
return model_inputs
class PrefixTuning:
def __init__(self, model, num_prefix, reparam=True, embed_dim=512, mid_dim=512, float16=False,
init_by_real_act=False):
"""
Inputs:
num_prefix: number of prefix tokens
reparam: use reparameterization trick (not used in MeZO)
embed_dim, mid_dim: hyperparameters for reparameterization trick (not used in MeZO)
float15: whether the model parameters are float15
init_by_real_act: init prefix tokens by real activations
"""
self.model = model
self.num_prefix = num_prefix
self.hidden_dim = model.config.hidden_size
self.float16 = float16
# Reparameterization
self.reparam = reparam
self.embed_dim = embed_dim
self.mid_dim = mid_dim
input_embeds = None # For reparameterization
if model.config.model_type == "opt":
attention_name = "attn"
first_layer_name = "layers.0"
layer_name = "layers."
elif model.config.model_type == "roberta":
attention_name = "attention"
first_layer_name = "layer.0"
layer_name = "layer."
elif model.config.model_type in ["llama", "mistral"]:
attention_name = "self_attn"
first_layer_name = "layers.0"
layer_name = "layers."
else:
raise NotImplementedError
if init_by_real_act:
# Initialize prefix with real words' activations
assert not reparam
# Randomly sample input tokens
input_tokens = npu.to_device(torch.randint(low=0, high=model.config.vocab_size, size=(1, num_prefix),
dtype=torch.long))
if model.config.model_type in ["opt", "llama", "mistral"]:
with torch.no_grad():
# Get the real activations
real_key_values = model(input_ids=input_tokens, use_cache=True).past_key_values
else:
raise NotImplementedError
# Insert prefix
for key, _ in model.named_modules():
if key[-len(attention_name):] == attention_name:
layer_id = int(key.split(layer_name)[1].split(".")[0])
logger.info(f"Inject prefix to: {key}")
_, _, attn = find_module(model, key)
# Replace the old forward functions
attn.original_forward = attn.forward
attn.forward = attn_forward_hook.__get__(attn, type(attn))
if not hasattr(attn, "num_heads"):
attn.num_heads = model.config.num_attention_heads
first = first_layer_name in key
self.add_prefix(attn, first=first, input_embeds=input_embeds)
if first and self.reparam:
input_embeds = attn.prefix_input_embeds
if init_by_real_act:
logger.info(f"Reinitialize with actual activation: {key} (layer {layer_id})")
keys = real_key_values[layer_id][0].squeeze(0).transpose(0, 1).reshape(num_prefix, -1)
values = real_key_values[layer_id][1].squeeze(0).transpose(0, 1).reshape(num_prefix, -1)
attn.prefix_keys.data = keys.to(attn.prefix_keys.data.device)
attn.prefix_values.data = values.to(attn.prefix_values.data.device)
# Freeze non-prefix parameters
for n, p in model.named_parameters():
if "prefix" not in n:
p.requires_grad = False
# Replace the old prepare_inputs_for_generation function
model.prepare_inputs_for_generation = prepare_inputs_for_generation.__get__(model, type(model))
def add_prefix(self, module, first, input_embeds=None):
device = module.k_proj.weight.data.device
module.num_prefix = self.num_prefix
module.reparam = self.reparam
if self.reparam:
if first:
# For the first layer we inject the embeddings
logger.info("For prefix+reparameterization, inject the embeddings in the first layer.")
module.prefix_input_embeds = nn.Parameter(
torch.randn(self.num_prefix, self.embed_dim, device=device, dtype=self.model.dtype),
requires_grad=True)
else:
assert input_embeds is not None
module.prefix_input_embeds = input_embeds
module.prefix_mlp_keys = nn.Sequential(
nn.Linear(self.embed_dim, self.mid_dim),
nn.Tanh(),
nn.Linear(self.mid_dim, self.hidden_dim)
).to(device)
module.prefix_mlp_values = nn.Sequential(
nn.Linear(self.embed_dim, self.mid_dim),
nn.Tanh(),
nn.Linear(self.mid_dim, self.hidden_dim)
).to(device)
if self.float16:
module.prefix_mlp_keys = module.prefix_mlp_keys.half()
module.prefix_mlp_values = module.prefix_mlp_values.half()
else:
module.prefix_keys = nn.Parameter(
torch.randn(self.num_prefix, self.hidden_dim, device=device, dtype=self.model.dtype),
requires_grad=True)
module.prefix_values = nn.Parameter(
torch.randn(self.num_prefix, self.hidden_dim, device=device, dtype=self.model.dtype),
requires_grad=True)
+218
View File
@@ -0,0 +1,218 @@
import logging
from functools import partial
from typing import Optional, Callable
import torch
from torch import nn
from transformers import PreTrainedModel
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class PromptEmbedding(nn.Module):
def __init__(
self,
num_virtual_tokens: int,
token_dim: int,
init_by_real_text: bool,
word_embeddings: Optional[nn.Module] = None,
vocab_size: Optional[int] = None,
):
super().__init__()
self.num_virtual_tokens = num_virtual_tokens
self.embedding = torch.nn.Embedding(num_virtual_tokens, token_dim)
if init_by_real_text:
init_token_ids = torch.randint(
low=0, high=vocab_size,
size=(num_virtual_tokens,), dtype=torch.long
).to(word_embeddings.weight.device)
word_embedding_weights = word_embeddings(init_token_ids).detach().clone()
word_embedding_weights = word_embedding_weights.to(torch.float32)
self.embedding.weight = nn.Parameter(word_embedding_weights)
def forward(self, indices):
# Just get embeddings
prompt_embeddings = self.embedding(indices)
return prompt_embeddings
def _get_batch_size(input_ids: Optional[torch.Tensor], inputs_embeds: Optional[torch.Tensor]) -> int:
if (input_ids is None) and (inputs_embeds is None):
raise ValueError("You have to provide either input_ids or inputs_embeds")
if input_ids is not None:
batch_size = input_ids.shape[0]
else:
batch_size = inputs_embeds.shape[0]
return batch_size
def _model_forward_hook(
self,
embedding_module: Callable,
embedding_module_device_refer,
hide_virtual_token_logits: bool,
input_ids=None,
attention_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
**kwargs,
):
batch_size = _get_batch_size(input_ids, inputs_embeds)
num_virtual_tokens = self.prompt_encoder.num_virtual_tokens
if attention_mask is not None:
# concat prompt attention mask
prefix_attention_mask = torch.ones(batch_size, num_virtual_tokens).to(attention_mask.device)
attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1)
if kwargs.get("position_ids", None) is not None:
warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.")
kwargs["position_ids"] = None
kwargs.update(
{
"attention_mask": attention_mask,
"output_attentions": output_attentions,
"output_hidden_states": output_hidden_states,
"return_dict": return_dict,
}
)
if labels is not None:
if len(labels.shape) == 1:
# if sequence classification task, labels do not have to be padded
kwargs["labels"] = labels
elif len(labels.shape) == 2:
# suppose to be language modeling task, labels have to be padded with -100
kwargs["labels"] = torch.cat(
(
-100 * torch.ones(batch_size, num_virtual_tokens).to(labels.device).long(),
labels,
),
dim=1,
)
else:
raise NotImplementedError("Not implemented for labels with shape {}".format(labels.shape))
if kwargs.get("token_type_ids", None) is not None:
kwargs["token_type_ids"] = torch.cat(
(
torch.zeros(batch_size, num_virtual_tokens).to(kwargs["token_type_ids"].device),
kwargs["token_type_ids"],
),
dim=1,
).long()
if kwargs.get("mask_pos", None) is not None:
kwargs["mask_pos"] = num_virtual_tokens + kwargs["mask_pos"]
input_device = input_ids.device if input_ids is not None else inputs_embeds.device
if inputs_embeds is None:
inputs_embeds = embedding_module(input_ids.to(embedding_module_device_refer.device))
inputs_embeds = inputs_embeds.to(input_device)
prompts = torch.arange(num_virtual_tokens).unsqueeze(0).expand(batch_size, -1).to(
self.prompt_encoder.embedding.weight.device)
prompts = self.prompt_encoder(prompts).to(dtype=inputs_embeds.dtype, device=input_device)
inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1)
outputs = self.prompt_tuning_original_forward(inputs_embeds=inputs_embeds, **kwargs)
if hide_virtual_token_logits and hasattr(outputs, "logits"):
outputs.logits = outputs.logits[..., num_virtual_tokens:, :]
return outputs
class PromptTuning:
def __init__(
self,
model: PreTrainedModel,
num_virtual_tokens: int,
init_by_real_tokens: Optional[bool] = False,
hide_virtual_token_logits: Optional[bool] = True,
):
"""
Prompt tuning model initializer.
Parameters
----------
model: PreTrainedModel, required
The model to be tuned.
num_virtual_tokens: int, required
The number of virtual tokens to be added.
init_by_real_tokens: bool, optional, default=False
Whether to initialize the virtual tokens by real tokens.
"""
hidden_dim = model.config.hidden_size
if model.config.model_type == "opt":
embedding_module = model.get_input_embeddings()
embedding_module_device_refer = embedding_module.weight
elif model.config.model_type == "roberta":
if hasattr(model, "roberta"): # is RoBERTaForMaskedLM etc.
embedding_module = partial(model.roberta.embeddings, past_key_values_length=num_virtual_tokens)
embedding_module_device_refer = model.roberta.embeddings.word_embeddings.weight
elif hasattr(model, "embeddings"): # is RoBERTa base model
embedding_module = partial(model.embeddings, past_key_values_length=num_virtual_tokens)
embedding_module_device_refer = model.embeddings.word_embeddings.weight
else:
raise ValueError(f"Cannot find embedding module in {model.__class__.__name__}")
elif model.config.model_type in ["llama", "mistral"]:
embedding_module = model.get_input_embeddings()
embedding_module_device_refer = embedding_module.weight
else:
raise NotImplementedError
model.prompt_encoder = PromptEmbedding(
num_virtual_tokens, hidden_dim, init_by_real_tokens,
model.get_input_embeddings(), model.config.vocab_size
)
model.prompt_tuning_original_forward = model.forward
if not hasattr(embedding_module_device_refer, "device"):
raise ValueError(f"Cannot find device attribute in {embedding_module_device_refer.__class__.__name__}")
forward_hook_kwargs = {
"embedding_module": embedding_module,
"embedding_module_device_refer": embedding_module_device_refer,
"hide_virtual_token_logits": hide_virtual_token_logits,
}
model.forward = partial(
_model_forward_hook.__get__(model, type(model)),
**forward_hook_kwargs
)
for n, p in model.named_parameters():
if "prompt_encoder" not in n:
p.requires_grad = False
def test_roberta():
from transformers import AutoTokenizer, RobertaModel
model = RobertaModel.from_pretrained("roberta-base")
tokenizer = AutoTokenizer.from_pretrained("roberta-base")
PromptTuning(model, num_virtual_tokens=5, init_by_real_tokens=True)
inputs = tokenizer("in heissem Liebesstreben", return_tensors="pt")
outputs = model(**inputs)
def test_opt():
from transformers import AutoTokenizer, OPTModel
model = OPTModel.from_pretrained("facebook/opt-125m")
tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m")
PromptTuning(model, num_virtual_tokens=5, init_by_real_tokens=True)
inputs = tokenizer("werd ich entschweben", return_tensors="pt")
outputs = model(**inputs)
if __name__ == "__main__":
test_roberta()
test_opt()
+939
View File
@@ -0,0 +1,939 @@
import warnings
# Suppress NPU import-time warnings before any imports that may trigger them
# 1) Hide the long ImportWarning from torch_npu.contrib.transfer_to_npu
warnings.filterwarnings("ignore", category=ImportWarning, message=".*torch_npu.*")
# 2) Hide RuntimeWarning regarding torch.jit being disabled by transfer_to_npu
warnings.filterwarnings(
"ignore",
category=RuntimeWarning,
message=r".*torch\.jit\.script.*",
)
import argparse
import os
import random
import wandb
import torch
from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
from torch.utils.data import Dataset
from tqdm import tqdm
import types
import sys as _sys
from transformers import (
AutoConfig,
AutoTokenizer,
AutoModelForCausalLM,
AutoModel,
HfArgumentParser,
TrainingArguments,
DataCollatorForTokenClassification
)
from metrics import calculate_metric
from modeling_mistral import (
MistralForCausalLM,
MistralConfig
)
from tasks import get_task
from trainer import OurTrainer
from utils import *
# NPU/CUDA compat helpers
import npu_compat as DeviceLoader
os.environ["TRANSFORMERS_CACHE"] = "./cache"
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# (warnings filters are configured at the very top to catch import-time emissions)
def _ensure_transformers_masking_utils():
"""Provide a shim for `transformers.masking_utils.create_causal_mask` when absent.
Some external models (e.g., ModelScope Pangu Embedded) import
`transformers.masking_utils.create_causal_mask`. Newer Transformers versions
may not expose this module, causing ModuleNotFoundError. We inject a minimal
compatible implementation at runtime.
"""
try:
import transformers.masking_utils # type: ignore
return
except Exception:
pass
try:
import torch
mod = types.ModuleType("transformers.masking_utils")
def create_causal_mask(input_ids_shape=None, dtype=torch.float32, device=None, past_key_values_length=0, *args, **kwargs):
# Support both signatures: (input_shape, dtype, past_len) or (bsz, tgt_len,...)
try:
if input_ids_shape is None:
return None
if isinstance(input_ids_shape, (tuple, list)):
if len(input_ids_shape) >= 2:
bsz, tgt_len = int(input_ids_shape[0]), int(input_ids_shape[1])
else:
# fallback assume (tgt_len,)
bsz, tgt_len = 1, int(input_ids_shape[0])
else:
# unknown, fallback to scalar length
bsz, tgt_len = 1, int(input_ids_shape)
except Exception:
bsz, tgt_len = 1, 1
dev = device if device is not None else (torch.npu.current_device() if hasattr(torch, "npu") and hasattr(torch.npu, "current_device") else (torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")))
# Build upper-triangular mask: allow current and past positions, mask future with -inf
attn_shape = (bsz, 1, tgt_len, tgt_len + int(past_key_values_length))
mask = torch.zeros(attn_shape, dtype=dtype, device=dev)
# Positions to mask (future): indices where j > i + past
future = torch.triu(torch.ones((tgt_len, tgt_len + int(past_key_values_length)), device=dev), diagonal=1 + int(past_key_values_length))
future = future.bool()
mask[:, :, :, :] = mask[:, :, :, :].masked_fill(future.expand(bsz, 1, tgt_len, tgt_len + int(past_key_values_length)), float("-inf"))
return mask
mod.create_causal_mask = create_causal_mask
# Register under sys.modules so import works for remote code
_sys.modules["transformers.masking_utils"] = mod
logger.info("Injected shim for transformers.masking_utils.create_causal_mask")
except Exception as e:
logger.warning(f"Failed to inject masking_utils shim: {e}")
try:
AutoConfig.register("mistral", MistralConfig)
except ValueError:
pass
try:
AutoModelForCausalLM.register(MistralConfig, MistralForCausalLM)
except ValueError:
pass
@dataclass
class OurArguments(TrainingArguments):
# dataset and sampling strategy
task_name: str = "SST2" # task name should match the string before Dataset in the Dataset class name. We support the following task_name: SST2, RTE, CB, BoolQ, WSC, WIC, MultiRC, Copa, ReCoRD, SQuAD, DROP
# Number of examples
num_train: int = 0 # ICL mode: number of demonstrations; training mode: number of training samples
num_dev: int = None # (only enabled with training) number of development samples
num_eval: int = None # number of evaluation samples
num_train_sets: int = None # how many sets of training samples/demos to sample; if None and train_set_seed is None, then we will sample one set for each evaluation sample
train_set_seed: int = 0 # designated seed to sample training samples/demos
result_file: str = None # file name for saving performance; if None, then use the task name, model name, and config
# Model loading
model_name: str = "FreedomIntelligence/openPangu-Embedded-1B" # HuggingFace model name
load_float16: bool = False # load model parameters as float16
load_bfloat16: bool = True # load model parameters as bfloat16
load_int8: bool = False # load model parameters as int8
max_length: int = 2048 # max length the model can take
no_auto_device: bool = False # do not load model by auto device; should turn this on when using FSDP
# Calibration
sfc: bool = False # whether to use SFC calibration
icl_sfc: bool = False # whether to use SFC calibration for ICL samples
template_ver: int = 0 # template. For some tasks (SST2, RTE, Copa), we add template ver=1 as the empty template.
# Training
trainer: str = "none"
## options
## - none: no training -- for zero-shot or in-context learning (ICL)
## - regular: regular huggingface trainer -- for fine-tuning
## - zo_sgd: zeroth-order SGD (MeZO) training
## - zo_conserv: zeroth-order SGD conservative training
## - zo_adam: zeroth-order Adam training
## - zo_sign_opt: zeroth-order sign sgd training
## - agzo: activation-guided zeroth-order training # AGZO: 新增trainer选项
## - lozo: low-rank zeroth-order training with adjustable rank r # LOZO: 新增trainer选项
## - forward_grad: forward gradient
optimizer: str = "adamw"
## options
## - sgd
## - adam
## - adamw # this is huggingface default
only_train_option: bool = True # whether to only train the option part of the input
train_as_classification: bool = False # take the log likelihood of all options and train as classification
momentum: float = 0.0 # only work for SGD optimizer
# MeZO
zo_eps: float = 1e-3 # eps in MeZO
perturbation_mode: str = "two_side"
q: int = 1 # number of Gaussian samples for zeroth-order trainers
# Prefix tuning
prefix_tuning: bool = False # whether to use prefix tuning
num_prefix: int = 5 # number of prefixes to use
no_reparam: bool = True # do not use reparameterization trick
prefix_init_by_real_act: bool = True # initialize prefix by real activations of random words
# prompt tuning hyperparameters
prompt_tuning: bool = False # whether to use prompt tuning
num_virtual_tokens: int = 10 # number of prompt tokens to use
prompt_init_by_real_tokens: bool = False # whether to sample random tokens from Embedding layer
# LoRA
lora: bool = False # whether to use LoRA
lora_alpha: int = 16 # alpha in LoRA
lora_r: int = 8 # r in LoRA
# Generation
sampling: bool = False # whether to use sampling
temperature: float = 1.0 # temperature for generation
num_beams: int = 1 # number of beams for generation
top_k: int = None # top-k for generation
top_p: float = 0.95 # top-p for generation
max_new_tokens: int = 50 # max number of new tokens to generate
eos_token: str = "\n" # end of sentence token
# Saving
save_model: bool = False # whether to save the model
no_eval: bool = False # whether to skip evaluation
tag: str = "" # saving tag
# Linear probing
linear_probing: bool = False # whether to do linear probing
lp_early_stopping: bool = False # whether to do early stopping in linear probing
head_tuning: bool = False # head tuning: only tune the LM head
# Untie emb/lm_head weights
untie_emb: bool = False # untie the embeddings and LM head
# Display
verbose: bool = False # verbose output
# Non-diff objective
non_diff: bool = False # use non-differentiable objective (only support F1 for SQuAD for now)
# Auto saving when interrupted
save_on_interrupt: bool = False # save model when interrupted (useful for long training)
clean_model_at_end: bool = True # remove everthing at the end.
# sparse gradient pruning
gradient_sparsity: float = None
sparse_gradient_resample_steps: int = 1
sparse_gradient_group: str = "layer"
"""
Options
## - global: global sparsity will assign different sparsity to each layer, based on the pretrained weight magnitude
## - layer: each layer has the same sparsity
"""
# module-wise perturbation
module_wise_perturbation: bool = False
perturbed_module_level: str = "transformer-block"
coordinate_perturbation: bool = True # If True, will update weight right after the gradient is computed
"""
Options
## - transformer-block: perturb one transformer block at a time
## - mlp-attn: perturb one mlp/attention layer at a time
## - linear: perturb one linear layer at a time
"""
# AGZO: power iteration steps for computing activation principal direction
agzo_power_iter_steps: int = 5
# AGZO: number of guided directions (rank) per layer
agzo_rank: int = 1
# AGZO: empty CUDA cache every N steps (0=disable)
agzo_empty_cache_steps: int = 1
# AGZO: debug flag to log per-layer memory usage during basis collection
agzo_debug_memory: bool = False
# LOZO: rank (r) for low-rank perturbation; r<=min(out_dim,in_dim)
lozo_rank: int = 4
# Device selection
npu_device: Optional[int] = 0 # which npu to use
# Save-best options
save_best: bool = True # whether to save the best model during training
best_metric_name: str = "accuracy" # metric name to compare (default: accuracy)
best_split: str = "val" # prefer validation set (val); fallback to test if no validation set
def parse_args():
parser = argparse.ArgumentParser()
parser = HfArgumentParser(OurArguments)
args = parser.parse_args_into_dataclasses()[0]
print(args)
return args
def set_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.npu.manual_seed_all(seed)
class Framework:
def __init__(self, args, task):
self.args = args
self.task = task
self.model, self.tokenizer = self.load_model()
def load_model(self):
"""
Load HuggingFace models
"""
model_name = self.args.model_name
dev_type = None
dev_idx = None
total_gb = None
device_name = None
# 从 npu_compat 统一获取设备信息
dev_type, dev_idx, total_gb, device_name = DeviceLoader.get_active_device_info()
if self.args.load_float16:
dtype = torch.float16
elif self.args.load_bfloat16:
dtype = torch.bfloat16
elif self.args.load_int8:
dtype = torch.int8
else:
dtype = torch.float32
# 显示模型以及加载模型的设备
# Print MODEL and DEVICE on separate, clearly marked lines
if model_name:
logger.info(f"=== MODEL === {model_name}")
if dev_type is not None:
dev_line = f"=== DEVICE === {dev_type}:{dev_idx}"
if total_gb is not None:
dev_line += f" total_mem={total_gb}GB"
if device_name:
dev_line += f" chip={device_name}"
logger.info(dev_line)
with count_time(f"Loading model with {dtype}"):
free_in_GB = int(DeviceLoader.mem_get_info()[0] / 1024 ** 3)
max_memory_gb = max(1, free_in_GB - 5)
logging.info(f"Free memory per device: {free_in_GB} GB, setting max_memory to {max_memory_gb} GB per device.")
model_name_lower = self.args.model_name.lower()
is_qwen = "qwen" in model_name_lower
is_pangu_emb = "openpangu-embedded" in model_name_lower
# # If using ModelScope-only model, download snapshot first
# base_model_path = self.args.model_name
# if is_pangu_emb:
# try:
# from modelscope.hub.snapshot_download import snapshot_download
# base_model_path = snapshot_download(
# model_id=self.args.model_name,
# cache_dir=os.path.join(os.path.dirname(__file__), "..", ".modelscope_cache"),
# )
# logging.info(f"ModelScope snapshot downloaded to: {base_model_path}")
# # Ensure remote code can import masking_utils
# _ensure_transformers_masking_utils()
# except Exception as e:
# print(f"Warning: ModelScope snapshot_download failed: {e}. Fallback to using {self.args.model_name} directly.")
# base_model_path = self.args.model_name
config_kwargs = {}
if is_pangu_emb or is_qwen:
config_kwargs["trust_remote_code"] = True
config = AutoConfig.from_pretrained(self.args.model_name, **config_kwargs)
else:
config = AutoConfig.from_pretrained(self.args.model_name, **config_kwargs)
if self.args.untie_emb:
# Untie embeddings/LM head
logger.warn("Untie embeddings and LM head")
config.tie_word_embeddings = False
if self.args.head_tuning:
if is_qwen or is_pangu_emb:
raise NotImplementedError("Head tuning is not supported for Qwen and Pangumodels yet.")
torch_dtype = torch.float32
if self.args.load_float16:
torch_dtype = torch.float16
elif self.args.load_bfloat16:
torch_dtype = torch.bfloat16
# Head tuning
if "opt" in model_name_lower:
from modeling_opt import OPTForCausalLM
model = OPTForCausalLM.from_pretrained(
self.args.model_name,
config=config,
device_map='auto',
torch_dtype=torch_dtype,
max_memory={i: f'{max_memory_gb}GB' for i in
range(torch.npu.device_count())},
)
elif "llama" in model_name_lower:
from modeling_llama import LlamaForCausalLMWithHeadTuning
model = LlamaForCausalLMWithHeadTuning.from_pretrained(
self.args.model_name,
config=config,
device_map='auto',
torch_dtype=torch_dtype,
max_memory={i: f'{max_memory_gb}GB' for i in
range(torch.npu.device_count())},
)
elif "mistral" in model_name_lower:
from modeling_mistral import MistralForCausalLMWithHeadTuning
model = MistralForCausalLMWithHeadTuning.from_pretrained(
self.args.model_name,
config=config,
device_map='auto',
torch_dtype=torch_dtype,
max_memory={i: f'{max_memory_gb}GB' for i in
range(torch.npu.device_count())},
)
else:
raise NotImplementedError(f"Head tuning is not supported for {self.args.model_name}")
elif self.args.no_auto_device:
# No auto device (use for FSDP)
model = AutoModelForCausalLM.from_pretrained(
self.args.model_name,
config=config,
trust_remote_code=is_qwen or is_pangu_emb,
)
else:
# Auto device loading
torch_dtype = torch.float32
if self.args.load_float16:
torch_dtype = torch.float16
elif self.args.load_bfloat16:
torch_dtype = torch.bfloat16
model = AutoModelForCausalLM.from_pretrained(
self.args.model_name,
config=config,
device_map='auto' if DeviceLoader.is_npu_available() else None,
torch_dtype=torch_dtype,
max_memory={i: f'{max_memory_gb}GB' for i in range(DeviceLoader.device_count())},
load_in_8bit=self.args.load_int8,
trust_remote_code=is_qwen or is_pangu_emb,
)
DeviceLoader.safe_set_device(self.args.npu_device)
model.eval()
# Load tokenizer
# In mezo, use_fast is set to False. But TypeError will occur when running SQuaD. Setting to be True can fix.
tokenizer_kwargs = {"use_fast": True}
if is_qwen or is_pangu_emb:
tokenizer_kwargs["trust_remote_code"] = True
tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, **tokenizer_kwargs)
# HF tokenizer bug fix
if "opt" in self.args.model_name:
tokenizer.bos_token_id = 0
if ("llama" in self.args.model_name) or ("mistral" in self.args.model_name.lower()):
# LLaMA padding token
tokenizer.pad_token_id = 0 # technically <unk>
if is_qwen:
if tokenizer.pad_token is None and tokenizer.eos_token is not None:
tokenizer.pad_token = tokenizer.eos_token
if tokenizer.pad_token_id is None:
tokenizer.pad_token_id = tokenizer.eos_token_id
# Prefix tuning/LoRA
if self.args.prefix_tuning:
from prefix_tuning import PrefixTuning
PrefixTuning(model, num_prefix=self.args.num_prefix, reparam=not self.args.no_reparam,
float16=self.args.load_float16, init_by_real_act=self.args.prefix_init_by_real_act)
if self.args.lora:
from lora import LoRA
LoRA(model, r=self.args.lora_r, alpha=self.args.lora_alpha, float16=self.args.load_float16)
if self.args.prompt_tuning:
from prompt_tuning import PromptTuning
print("Adding Prompt Tuning to model...")
PromptTuning(
model,
num_virtual_tokens=self.args.num_virtual_tokens,
init_by_real_tokens=self.args.prompt_init_by_real_tokens,
hide_virtual_token_logits=True, # a workaround for the other loss/prediction functions
)
print("Total/Trainable number of parameters: {}/{}".format(
sum(p.numel() for p in model.parameters()),
sum(p.numel() for p in model.parameters() if p.requires_grad),
))
if self.args.head_tuning:
if model.config.model_type in ["opt", "llama", "mistral"]:
head_name = "lm_head" if self.args.untie_emb else "embed_tokens"
else:
raise NotImplementedError
for n, p in model.named_parameters():
if head_name not in n:
p.requires_grad = False
else:
logger.info(f"Only tuning {n}")
return model, tokenizer
def forward(self, input_ids, option_len=None, generation=False):
"""
Given input_ids and the length of the option, return the log-likelihood of each token in the option.
For generation tasks, return the generated text.
This function is only for inference
"""
input_ids = torch.tensor([input_ids]).to(self.model.device)
if generation:
args = self.args
# Autoregressive generation
outputs = self.model.generate(input_ids, do_sample=args.sampling, temperature=args.temperature,
num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k,
max_new_tokens=min(args.max_new_tokens, args.max_length - input_ids.size(1)),
num_return_sequences=1,
eos_token_id=[
self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1],
self.tokenizer.eos_token_id], )
# For generation, directly return the text output
output_text = self.tokenizer.decode(outputs[0][input_ids.size(1):], skip_special_tokens=True).strip()
return output_text
else:
with torch.inference_mode():
self.model.eval()
logits = self.model(input_ids=input_ids).logits
labels = input_ids[0, 1:]
logits = logits[0, :-1]
log_probs = F.log_softmax(logits, dim=-1)
selected_log_probs = log_probs[torch.arange(len(labels)).to(labels.device), labels]
selected_log_probs = selected_log_probs.cpu().detach()
# Only return the option (candidate) part
return selected_log_probs[-option_len:]
def one_step_pred(self, train_samples, eval_sample, verbose=False):
"""
Return the prediction on the eval sample. In ICL, use train_samples as demonstrations
"""
verbose = verbose or self.args.verbose
# if verbose:
# logger.info("========= Example =========")
# logger.info(f"Candidate: {eval_sample.candidates}")
# logger.info(f"Correct candidate: {eval_sample.correct_candidate}")
# Encode (add prompt and tokenize) the sample; if multiple-choice/classification, encode all candidates (options)
encoded_candidates, option_lens = encode_prompt(self.task,
self.task.get_template(template_version=self.args.template_ver),
train_samples, eval_sample,
self.tokenizer, max_length=self.args.max_length,
generation=self.task.generation,
max_new_tokens=self.args.max_new_tokens)
# Calibration
if self.args.sfc or self.args.icl_sfc:
sfc_encoded_candidates, sfc_option_lens = encode_prompt(self.task, self.task.get_template(
template_version=self.args.template_ver), train_samples,
eval_sample, self.tokenizer,
max_length=self.args.max_length, sfc=self.args.sfc,
icl_sfc=self.args.icl_sfc,
generation=self.task.generation,
max_new_tokens=self.args.max_new_tokens)
outputs = []
if self.task.generation:
# For generation tasks, return the autoregressively-generated text
output_text = self.forward(encoded_candidates[0], generation=True)
# if verbose:
# logger.info("=== Prompt ===")
# logger.info(self.tokenizer.decode(encoded_candidates[0]))
# logger.info(f"Output: {output_text}")
return Prediction(correct_candidate=eval_sample.correct_candidate, predicted_candidate=output_text)
else:
# For classification/multiple-choice, calculate the probabilities of all candidates
for candidate_id, encoded_candidate in enumerate(encoded_candidates):
selected_log_probs = self.forward(encoded_candidate, option_len=option_lens[candidate_id])
if verbose:
# if candidate_id == 0:
# logger.info("=== Candidate %d ===" % candidate_id)
# logger.info(self.tokenizer.decode(encoded_candidate))
# else:
# logger.info("=== Candidate %d (without context)===" % candidate_id)
# logger.info(self.tokenizer.decode(encoded_candidate).split(self.task.train_sep)[-1])
logger.info(f"Log probabilities of the option tokens: {selected_log_probs}")
if self.args.sfc or self.args.icl_sfc:
sfc_selected_log_probs = self.forward(sfc_encoded_candidates[candidate_id],
option_len=sfc_option_lens[
candidate_id]) # if verbose: # logger.info("=== Candidate %d (without context) SFC ===" % candidate_id) # logger.info( # self.tokenizer.decode(sfc_encoded_candidates[candidate_id]).split(self.task.train_sep)[-1]) # logger.info(f"Log probabilities of the option tokens: {sfc_selected_log_probs}")
outputs.append({"log_probs": selected_log_probs,
"sfc_log_probs": sfc_selected_log_probs if self.args.sfc or self.args.icl_sfc else None})
if self.args.sfc or self.args.icl_sfc:
# Calibrated probabilities (surface form competition; https://arxiv.org/pdf/2104.08315.pdf)
# log p(candidate | input) = log p_lm(candidate | input) - log p_lm(candidate | sfc prompt)
scores = [x['log_probs'].sum().item() - x['sfc_log_probs'].sum().item() for x in outputs]
else:
# (Default) length-normalized log probabilities
# log p(candidate | input) = log p_lm(candidate | input) / |candidate #tokens|
scores = [x['log_probs'].mean().item() for x in outputs]
if verbose:
logger.info(f"Prediction scores: {scores}")
if isinstance(eval_sample.correct_candidate, list):
# For some datasets there are multiple correct answers
correct_candidate_id = [eval_sample.candidates.index(c) for c in eval_sample.correct_candidate]
else:
correct_candidate_id = eval_sample.candidates.index(eval_sample.correct_candidate)
return Prediction(correct_candidate=correct_candidate_id, predicted_candidate=int(np.argmax(scores)))
def evaluate(self, train_samples, eval_samples, one_train_set_per_eval_sample=False, description=None):
"""
Evaluate function.
Here, train_samples are used for demonstrations for ICL.
If one_train_set_per_eval_sample is True, then each eval sample has its own training (demonstration) set.
Otherwise, the same training set is used for all eval samples.
"""
if one_train_set_per_eval_sample:
logger.info(f"There are {len(eval_samples)} validation samples and one train set per eval sample")
else:
logger.info(f"There are {len(train_samples)} training samples and {len(eval_samples)} validation samples")
# Prediction loop
predictions = []
for eval_id, eval_sample in enumerate(tqdm(eval_samples, desc=description)):
predictions.append(
self.one_step_pred(train_samples[eval_id] if one_train_set_per_eval_sample else train_samples,
eval_sample, verbose=False))
# Calculate metrics
metric_name = getattr(self.task, "metric_name", "accuracy")
metrics = {metric_name: calculate_metric(predictions, metric_name)}
return metrics
def train(self, train_samples, dev_samples, eval_samples):
"""
Training function
if self.num_dev is not None, eval_samples are dev_samples
"""
logger.info(f"Eval sample length is {len(eval_samples)}")
# Set tokenizer to left padding (so that all the options are right aligned)
self.tokenizer.padding_side = "left"
class HFDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx]
def _convert(samples):
"""
Convert samples to HF-compatible dataset
"""
data = []
for sample in samples:
encoded_candidates, option_lens = encode_prompt(self.task, self.task.get_template(
template_version=self.args.template_ver), [], sample,
self.tokenizer, max_length=self.args.max_length,
generation=self.task.generation,
generation_with_gold=True,
max_new_tokens=self.args.max_new_tokens)
if self.task.generation:
correct_candidate_id = 0
elif isinstance(sample.correct_candidate, list):
correct_candidate_id = sample.candidates.index(sample.correct_candidate[0])
else:
correct_candidate_id = sample.candidates.index(sample.correct_candidate)
if self.args.non_diff:
# For non-differentiable objective, there is no teacher forcing thus the
# current answer part is removed
encoded_candidates[correct_candidate_id] = encoded_candidates[correct_candidate_id][
:-option_lens[correct_candidate_id]]
if self.args.train_as_classification:
# For classification, we provide the label as the correct candidate id
data.append([{"input_ids": encoded_candidates[_i], "labels": correct_candidate_id,
"option_len": option_lens[_i], "num_options": len(sample.candidates)} for _i in
range(len(encoded_candidates))])
elif self.args.only_train_option:
# Otherwise, it is just LM-style teacher forcing
if self.args.non_diff:
# For non-differentiable objective, we need to provide the gold answer to calculate F1/acc
data.append({"input_ids": encoded_candidates[correct_candidate_id],
"labels": encoded_candidates[correct_candidate_id],
"option_len": option_lens[correct_candidate_id], "gold": sample.correct_candidate})
else:
data.append({"input_ids": encoded_candidates[correct_candidate_id],
"labels": encoded_candidates[correct_candidate_id],
"option_len": option_lens[correct_candidate_id]})
else:
data.append({"input_ids": encoded_candidates[correct_candidate_id],
"labels": encoded_candidates[correct_candidate_id]})
return data
with count_time("Tokenizing training samples"):
train_dataset = HFDataset(_convert(train_samples))
eval_dataset = HFDataset(_convert(eval_samples))
dev_dataset = HFDataset(_convert(dev_samples))
if self.args.only_train_option and not self.args.non_diff:
# If --only_train_option and not with a non-differentiable objective, we wrap the forward function
self.model.original_forward = self.model.forward
self.model.forward = forward_wrap_with_option_len.__get__(self.model, type(self.model))
if self.args.non_diff:
collator = NondiffCollator
else:
collator = DataCollatorForTokenClassification
if self.args.gradient_sparsity is not None:
logger.info(
f"[Sparse gradient] sparsity is {self.args.gradient_sparsity}, resampling per {self.args.sparse_gradient_resample_steps} steps"
)
if self.args.sparse_gradient_group == "global":
logger.info(f"[Sparse gradient] global-ratio random pruning is enabled, "
f"sparsity of each layer is computed based on the pretrained weight magnitude.")
elif self.args.sparse_gradient_group == "layer":
logger.info(f"[Sparse gradient] layer-wise random pruning is enabled, "
f"sparsity of each layer is the same.")
else:
raise NotImplementedError(f"Unknown sparse gradient group: {self.args.sparse_gradient_group}")
perturb_module_regex = None
if self.args.module_wise_perturbation:
if "opt" in self.args.model_name:
assert self.args.perturbed_module_level in OPT_PERTURBATION_LEVEL_TO_REGEX.keys(), f"Unknown perturbed module group {self.args.perturbed_module_level}"
perturb_module_regex = OPT_PERTURBATION_LEVEL_TO_REGEX[self.args.perturbed_module_level]
else:
raise NotImplementedError(f"Unimplemented model {self.args.model_name} for module-wise perturbation")
trainer = OurTrainer(model=self.model,
args=self.args,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
tokenizer=self.tokenizer,
data_collator=DataCollatorWithPaddingAndNesting(self.tokenizer,
pad_to_multiple_of=8) if self.args.train_as_classification else collator(
self.tokenizer, pad_to_multiple_of=8),
eval_samples=eval_samples,
dev_samples=dev_samples,
evaluate_func=self.evaluate,
perturb_module_regex=perturb_module_regex,
)
if self.args.save_on_interrupt:
trainer.add_callback(SIGUSR1Callback())
# Resume training from a last checkpoint
last_checkpoint = None
from transformers.trainer_utils import get_last_checkpoint
if os.path.isdir(self.args.output_dir) and not self.args.overwrite_output_dir:
last_checkpoint = get_last_checkpoint(self.args.output_dir)
if last_checkpoint is not None and self.args.resume_from_checkpoint is None:
logger.info(f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch.")
if self.args.resume_from_checkpoint is not None:
last_checkpoint = self.args.resume_from_checkpoint
# This calls the trainer._inner_training_loop()
trainer.train(resume_from_checkpoint=last_checkpoint)
# Explicitly save the model
if self.args.save_model:
logger.info("Save model..")
trainer.save_model()
# FSDP compatibility
self.model = trainer.model
# Reset the forward function for evaluation
if self.args.only_train_option and not self.args.non_diff:
if type(self.model) == FSDP:
logger.info("This is an FSDP model now. Be careful when assigning back the original forward function")
self.model._fsdp_wrapped_module.forward = self.model._fsdp_wrapped_module.original_forward
else:
self.model.forward = self.model.original_forward
def delete_checkpoints(self):
import shutil
print(f"\nWARNING: Removing everything at end: {self.args.output_dir}")
deleted_folders = [folder for folder in os.listdir(self.args.output_dir)
if os.path.isdir(os.path.join(self.args.output_dir, folder))
and folder.startswith("checkpoint-")]
for f in deleted_folders:
shutil.rmtree(os.path.join(self.args.output_dir, f))
print(f"deleted folders: ", deleted_folders)
def result_file_tag(args):
"""
Get the result file tag
"""
save_model_name = args.model_name.split("/")[-1]
sfc_tag = "-sfc" if args.sfc else ""
icl_sfc_tag = "-icl_sfc" if args.icl_sfc else ""
sample_eval_tag = "-sampleeval%d" % args.num_eval if args.num_eval is not None else ""
sample_train_tag = "-ntrain%d" % args.num_train if args.num_train > 0 else ""
sample_dev_tag = "-ndev%d" % args.num_dev if args.num_dev is not None else ""
customized_tag = f"-{args.tag}" if len(args.tag) > 0 else ""
return f"{args.task_name}-{save_model_name}" + sfc_tag + icl_sfc_tag + sample_eval_tag + sample_train_tag + sample_dev_tag + customized_tag
def main():
args = parse_args()
if args.prefix_tuning:
args.mode = "prefix"
elif args.lora:
args.mode = "lora"
elif args.prompt_tuning:
args.mode = "prompt"
else:
args.mode = "ft"
args.tag = f"{args.trainer}-{args.task_name}-{args.template_ver}-{args.model_name.split('/')[-1]}-OPTIM_{args.mode}-STEP{args.max_steps}-{args.optimizer}-LR{args.learning_rate}-{args.lr_scheduler_type}-ZOEPS{args.zo_eps}-Q{args.q}"
if args.trainer == "agzo":
args.tag += f"-AGZO_PI{args.agzo_power_iter_steps}" # AGZO: 记录power iteration次数
if getattr(args, "agzo_rank", 1) > 1:
args.tag += f"-AGZO_R{args.agzo_rank}"
if args.agzo_empty_cache_steps > 0:
args.tag += f"-AGZO_EC{args.agzo_empty_cache_steps}" # AGZO: 记录缓存清理频率
if args.agzo_debug_memory:
args.tag += "-AGZO_DBG"
args.tag = "momen" + args.tag if args.momentum > 0 else args.tag
args.tag = f"sparse_grad-{args.gradient_sparsity}-{args.sparse_gradient_group}-{args.sparse_gradient_resample_steps}-" + args.tag if args.gradient_sparsity is not None else args.tag
args.tag = f"module_perturb-{args.perturbed_module_level}-" + args.tag if args.module_wise_perturbation else args.tag
args.run_name = args.tag
args.output_dir = f"result/{args.tag}"
args.result_file = f"result/{args.tag}/results.json"
os.makedirs(args.output_dir, exist_ok=True)
args.logging_dir = os.path.join(args.output_dir, "logs")
os.makedirs(args.logging_dir, exist_ok=True)
# If user only needs metrics, disable checkpoint saving
args.save_strategy = "no" # user requests no checkpoints to save disk usage
args.save_model = False
args.save_total_limit = 0
args.load_best_model_at_end = False
try:
wandb.init(project='zo-bench', name=args.tag, config=args)
except Exception as e:
# If running in a non-interactive environment without WANDB API key,
# wandb raises a UsageError prompting for an API key. Fall back to
# offline mode so the script can continue.
logger.warning("W&B init failed (%s). Falling back to offline mode.", e)
os.environ.setdefault("WANDB_MODE", "offline")
try:
wandb.init(project='zo-bench', name=args.tag, config=args, mode="offline")
except Exception:
# If still failing, continue without wandb (user can disable reporting via args)
logger.warning("W&B offline init also failed; continuing without wandb.")
set_seed(args.seed)
task = get_task(args.task_name)
# This function samples both training and validation samples. The validation (dev) samples are also stored in "train_sets"
# Later the train_samples and dev_samples are separated
train_sets = task.sample_train_sets(num_train=args.num_train, num_dev=args.num_dev, num_eval=args.num_eval,
num_train_sets=args.num_train_sets, seed=args.train_set_seed)
# Initialize trainer and load model
framework = Framework(args, task)
# ZO-Bench Added
# We add these parameters to evaluate the model during the training.
# These two parameters will be used in the training loop
# args.task = task
# args.framework = framework
metrics = {}
if args.train_set_seed is not None or args.num_train_sets is not None:
# Training goes to this way
# Eval samples share one (or multiple) training set(s)
for train_set_id, train_samples in enumerate(train_sets):
train_set_seed = train_set_id if args.train_set_seed is None else args.train_set_seed
# Sample eval samples
if args.num_eval is not None:
eval_samples = task.sample_subset(data_split="valid", seed=train_set_seed, num=args.num_eval)
else:
eval_samples = task.valid_samples
metrics = {}
if args.trainer != "none":
# Here the training samples are seperated
if args.num_dev is not None:
# Dev samples
# assert args.num_dev + args.num_train <= len(train_samples), f"num_dev({args.num_dev})+num_train({args.num_train}) is more than actual num of training samples ({len(train_samples)})."
dev_samples = train_samples[-args.num_dev:]
train_samples = train_samples[:-args.num_dev]
logger.info("Dev samples: %d" % len(dev_samples))
logger.info("Train samples: %d" % len(train_samples))
else:
dev_samples = None
logger.info("Train samples: %d" % len(train_samples))
logger.info("No dev samples")
args.dev_samples = dev_samples
args.eval_samples = eval_samples
# Training
framework.train(train_samples, dev_samples if dev_samples is not None else eval_samples, eval_samples)
if not args.no_eval: # This is True
metrics = framework.evaluate([], eval_samples, description="Evaluating on the Test Set")
_keys = list(metrics.keys())
for m in _keys:
metrics["test_" + m] = metrics[m]
if dev_samples is not None:
dev_metrics = framework.evaluate(
[], dev_samples, description="Evaluating on the Validation Set"
)
_keys = list(dev_metrics.keys())
for m in _keys:
metrics["val_" + m] = dev_metrics[m]
else:
assert args.num_dev is None
# Zero-shot / in-context learning
metrics = framework.evaluate(train_samples, eval_samples)
logger.info(metrics)
wandb.log(
metrics,
step=framework.trainer.state.global_step if hasattr(framework, "trainer") else None,
)
if not args.no_eval:
logger.info("===== Train set %d =====" % train_set_seed)
logger.info(metrics)
wandb.log(metrics, step=framework.trainer.state.global_step if hasattr(framework, "trainer") else None)
if args.local_rank <= 0:
write_metrics_to_file(metrics, "result/" + result_file_tag(
args) + f"-trainset{train_set_id}.json" if args.result_file is None else args.result_file)
if args.trainer != "none" and args.clean_model_at_end:
framework.delete_checkpoints()
else:
# For each eval sample, there is a training set. no training is allowed
# This is for in-context learning (ICL)
assert args.trainer == "none"
if args.num_eval is not None:
eval_samples = task.sample_subset(data_split="valid", seed=0, num=args.num_eval)
else:
eval_samples = task.valid_samples
metrics = framework.evaluate(train_sets, eval_samples, one_train_set_per_eval_sample=True)
logger.info(metrics)
wandb.log(metrics, step=framework.trainer.state.global_step if hasattr(framework, "trainer") else None)
if args.local_rank <= 0:
write_metrics_to_file(metrics, "result/" + result_file_tag(
args) + "-onetrainpereval.json" if args.result_file is None else args.result_file)
if __name__ == "__main__":
main()
@@ -0,0 +1,56 @@
name: adam_copa_ft
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=epoch"
- "--save_strategy=epoch"
- "--save_total_limit=1"
- "--eval_steps=500"
# - "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
- "--save_model"
- "--fp16"
- "--per device train batch size=8"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
#- 1e-4
#- 1e-5
- 1e-6
- 1e-7
# - 1e-8
zo_eps:
values:
- 1e-3
# - 1e-4
# - 1e-5
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: adam_copa_lora
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
# - "--max_steps=20000"
- "--load_float16"
- "--per device train batch size=8"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,53 @@
name: adam_copa_prefix
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
# - "--max_steps=20000"
- "--fp16"
- "--per device train batch size=8"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: adam_copa_prompt
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
# - "--max_steps=20000"
- "--fp16"
- "--per device train batch size=8"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,47 @@
name: forward_grad_copa_ft
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=forward_grad"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
- "--optimizer=sgd"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,49 @@
name: forward_grad_copa_lora
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=forward_grad"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--optimizer=sgd"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,50 @@
name: forward_grad_copa_prefix
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=forward_grad"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--optimizer=sgd"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,49 @@
name: forward_grad_copa_prompt
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=forward_grad"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--optimizer=sgd"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,56 @@
name: sgd_copa_ft
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=epoch"
- "--save_strategy=epoch"
- "--save_total_limit=1"
- "--eval_steps=500"
# - "--max_steps=20000"
- "--fp16"
- "--per device train batch size=8"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
# - 1e-8
zo_eps:
values:
- 1e-3
# - 1e-4
# - 1e-5
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: sgd_copa_lora
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
# - "--max_steps=20000"
- "--fp16"
- "--per device train batch size=8"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,53 @@
name: sgd_copa_prefix
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=500"
# - "--max_steps=20000"
- "--fp16"
- "--per device train batch size=8"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: sgd_copa_prompt
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
# - "--max_steps=20000"
- "--fp16"
- "--per device train batch size=8"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: sign_opt_copa_ft
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=300"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sign_opt"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,51 @@
name: zo_sign_sgd_copa_lora
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sign_opt"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: sign_sgd_copa_prefix
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sign_opt"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-3
- 1e-4
- 1e-5
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: sign_sgd_copa_prompt
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sign_opt"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-3
- 1e-4
- 1e-5
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: zo_adam_copa_ft
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: zo_adam_copa_lora
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,55 @@
name: zo_adam_copa_prefix
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: zo_adam_copa_prompt
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: zo_sgd_copa_ft
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: zo_sgd_copa_lora
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,55 @@
name: zo_sgd_copa_prefix
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: zo_sgd_copa_prompt
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: zo_sgd_conserv_copa_ft
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_conserv"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: zo_sgd_conserv_copa_lora
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_conserv"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: zo_sgd_conserv_copa_prefix
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_conserv"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-3
- 1e-4
- 1e-5
- 1e-6
- 1e-7
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: zo_sgd_conserv_copa_prompt
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_conserv"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-3
- 1e-4
- 1e-5
- 1e-6
- 1e-7
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,55 @@
name: zo_sgd_momen_copa_ft
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-momen_$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=300"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
momentum:
values:
- 0.9
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: zo_sgd_momen_copa_lora
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
momentum:
values:
- 0.9
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,57 @@
name: zo_sgd_momen_copa_prefix
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-3
- 1e-4
- 1e-5
- 1e-6
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
momentum:
values:
- 0.9
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,56 @@
name: zo_sgd_momen_copa_prompt
project: zo_bench_Copa_llama-2-13b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-13b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-3
- 1e-4
- 1e-5
- 1e-6
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
momentum:
values:
- 0.9
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: adam_copa_ft
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=epoch"
- "--save_strategy=epoch"
- "--save_total_limit=1"
- "--eval_steps=500"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
#- 1e-4
#- 1e-5
- 1e-6
- 1e-7
# - 1e-8
zo_eps:
values:
- 1e-3
# - 1e-4
# - 1e-5
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: adam_copa_lora
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,51 @@
name: adam_copa_prefix
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,50 @@
name: adam_copa_prompt
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,47 @@
name: forward_grad_copa_ft
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=forward_grad"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
- "--optimizer=sgd"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,48 @@
name: forward_grad_copa_lora
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=forward_grad"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--optimizer=sgd"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,50 @@
name: forward_grad_copa_prefix
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=forward_grad"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--optimizer=sgd"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,49 @@
name: forward_grad_copa_prompt
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=forward_grad"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--optimizer=sgd"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: sgd_copa_ft
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=epoch"
- "--save_strategy=epoch"
- "--save_total_limit=1"
- "--eval_steps=500"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
# - 1e-8
zo_eps:
values:
- 1e-3
# - 1e-4
# - 1e-5
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: sgd_copa_lora
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,51 @@
name: sgd_copa_prefix
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=500"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,50 @@
name: sgd_copa_prompt
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: sign_opt_copa_ft
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=300"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sign_opt"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,51 @@
name: zo_sign_sgd_copa_lora
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sign_opt"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: sign_sgd_copa_prefix
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sign_opt"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-3
- 1e-4
- 1e-5
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: sign_sgd_copa_prompt
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sign_opt"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-3
- 1e-4
- 1e-5
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: zo_adam_copa_ft
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,51 @@
name: zo_adam_copa_lora
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,55 @@
name: zo_adam_copa_prefix
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: zo_adam_copa_prompt
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: zo_sgd_copa_ft
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: zo_sgd_copa_lora
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,55 @@
name: zo_sgd_copa_prefix
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: zo_sgd_copa_prompt
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-4
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,52 @@
name: zo_sgd_conserv_copa_ft
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_conserv"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_bfloat16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,51 @@
name: zo_sgd_conserv_copa_lora
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_conserv"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: zo_sgd_conserv_copa_prefix
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_conserv"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-3
- 1e-4
- 1e-5
- 1e-6
- 1e-7
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: zo_sgd_conserv_copa_prompt
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_conserv"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-3
- 1e-4
- 1e-5
- 1e-6
- 1e-7
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,55 @@
name: zo_sgd_momen_copa_ft
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-momen_$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=300"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-5
- 1e-6
- 1e-7
- 1e-8
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
momentum:
values:
- 0.9
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,54 @@
name: zo_sgd_momen_copa_lora
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-lora-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--save_model"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 5e-3
- 1e-4
- 5e-5
- 1e-5
zo_eps:
values:
- 1e-2
- 1e-3
momentum:
values:
- 0.9
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,57 @@
name: zo_sgd_momen_copa_prefix
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-3
- 1e-4
- 1e-5
- 1e-6
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
momentum:
values:
- 0.9
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,56 @@
name: zo_sgd_momen_copa_prompt
project: zo_bench_Copa_llama-2-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=meta-llama/Llama-2-7b-hf"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=1000"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=zo_sgd"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--eval_steps=500"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-3
- 1e-4
- 1e-5
- 1e-6
zo_eps:
values:
- 1e-2
- 1e-3
- 1e-4
momentum:
values:
- 0.9
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,47 @@
name: adam_copa_ft
project: zo_bench_copa_mistral-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--model_name=mistralai/Mistral-7B-v0.1"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--no_reparam"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=500"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--save_steps=500"
- "--load_float16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-3
- 1e-4
- 1e-5
- 1e-6
- 1e-7
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,46 @@
name: adam_copa_lora
project: zo_bench_copa_mistral-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--lora"
- "--model_name=mistralai/Mistral-7B-v0.1"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=500"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--save_steps=500"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,50 @@
name: adam_copa_prefix
project: zo_bench_copa_mistral-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prefix_tuning"
- "--num_prefix=5"
- "--no_reparam"
- "--prefix_init_by_real_act"
- "--model_name=mistralai/Mistral-7B-v0.1"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=500"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--save_steps=500"
- "--load_bfloat16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
@@ -0,0 +1,49 @@
name: adam_copa_prompt
project: zo_bench_copa_mistral-7b
command:
- ${interpreter}
- ${program}
- ${args}
- "--prompt_tuning"
- "--num_virtual_tokens=10"
- "--prompt_init_by_real_tokens"
- "--model_name=mistralai/Mistral-7B-v0.1"
- "--task_name=Copa"
- "--output_dir=result/Copa-ft-$TAG"
- "--num_train_epochs=5"
- "--per_device_train_batch_size=16"
- "--load_best_model_at_end"
- "--evaluation_strategy=steps"
- "--save_strategy=steps"
- "--save_total_limit=1"
- "--eval_steps=500"
- "--max_steps=20000"
- "--logging_steps=10"
- "--num_eval=1000"
- "--num_train=1000"
- "--num_dev=100"
- "--train_as_classification=False"
- "--perturbation_mode=two_side"
- "--trainer=regular"
- "--optimizer=adam"
- "--train_set_seed=0"
- "--lr_scheduler_type=constant"
- "--save_steps=500"
- "--load_bfloat16"
method: grid
metric:
goal: maximize
name: test_acc
parameters:
learning_rate:
values:
- 1e-2
- 1e-3
- 1e-4
- 1e-5
- 1e-6
weight_decay:
values:
- 0
program: run.py
Loaded 100 of 596 files, more files were not shown because too many files have changed in this diff. Show more