Commit ·
6bd4371
0
Parent(s):
Training, Optuna search and Norma evaluation code
Browse files- .gitattributes +35 -0
- .gitignore +7 -0
- LICENSE +674 -0
- README.md +83 -0
- evaluate.py +58 -0
- hpo.py +139 -0
- model.py +140 -0
- norma.py +248 -0
- predict.py +98 -0
- prepare_data.py +137 -0
- requirements.txt +9 -0
- slurm/smoke.slurm +80 -0
- tokenizer.py +297 -0
- train.py +254 -0
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
.cache/
|
| 3 |
+
cache/
|
| 4 |
+
runs/
|
| 5 |
+
logs/
|
| 6 |
+
results/
|
| 7 |
+
__pycache__/
|
LICENSE
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 29 June 2007
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
| 5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
| 6 |
+
of this license document, but changing it is not allowed.
|
| 7 |
+
|
| 8 |
+
Preamble
|
| 9 |
+
|
| 10 |
+
The GNU General Public License is a free, copyleft license for
|
| 11 |
+
software and other kinds of works.
|
| 12 |
+
|
| 13 |
+
The licenses for most software and other practical works are designed
|
| 14 |
+
to take away your freedom to share and change the works. By contrast,
|
| 15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
| 16 |
+
share and change all versions of a program--to make sure it remains free
|
| 17 |
+
software for all its users. We, the Free Software Foundation, use the
|
| 18 |
+
GNU General Public License for most of our software; it applies also to
|
| 19 |
+
any other work released this way by its authors. You can apply it to
|
| 20 |
+
your programs, too.
|
| 21 |
+
|
| 22 |
+
When we speak of free software, we are referring to freedom, not
|
| 23 |
+
price. Our General Public Licenses are designed to make sure that you
|
| 24 |
+
have the freedom to distribute copies of free software (and charge for
|
| 25 |
+
them if you wish), that you receive source code or can get it if you
|
| 26 |
+
want it, that you can change the software or use pieces of it in new
|
| 27 |
+
free programs, and that you know you can do these things.
|
| 28 |
+
|
| 29 |
+
To protect your rights, we need to prevent others from denying you
|
| 30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
| 31 |
+
certain responsibilities if you distribute copies of the software, or if
|
| 32 |
+
you modify it: responsibilities to respect the freedom of others.
|
| 33 |
+
|
| 34 |
+
For example, if you distribute copies of such a program, whether
|
| 35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
| 36 |
+
freedoms that you received. You must make sure that they, too, receive
|
| 37 |
+
or can get the source code. And you must show them these terms so they
|
| 38 |
+
know their rights.
|
| 39 |
+
|
| 40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
| 41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
| 42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
| 43 |
+
|
| 44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
| 45 |
+
that there is no warranty for this free software. For both users' and
|
| 46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
| 47 |
+
changed, so that their problems will not be attributed erroneously to
|
| 48 |
+
authors of previous versions.
|
| 49 |
+
|
| 50 |
+
Some devices are designed to deny users access to install or run
|
| 51 |
+
modified versions of the software inside them, although the manufacturer
|
| 52 |
+
can do so. This is fundamentally incompatible with the aim of
|
| 53 |
+
protecting users' freedom to change the software. The systematic
|
| 54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
| 55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
| 56 |
+
have designed this version of the GPL to prohibit the practice for those
|
| 57 |
+
products. If such problems arise substantially in other domains, we
|
| 58 |
+
stand ready to extend this provision to those domains in future versions
|
| 59 |
+
of the GPL, as needed to protect the freedom of users.
|
| 60 |
+
|
| 61 |
+
Finally, every program is threatened constantly by software patents.
|
| 62 |
+
States should not allow patents to restrict development and use of
|
| 63 |
+
software on general-purpose computers, but in those that do, we wish to
|
| 64 |
+
avoid the special danger that patents applied to a free program could
|
| 65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
| 66 |
+
patents cannot be used to render the program non-free.
|
| 67 |
+
|
| 68 |
+
The precise terms and conditions for copying, distribution and
|
| 69 |
+
modification follow.
|
| 70 |
+
|
| 71 |
+
TERMS AND CONDITIONS
|
| 72 |
+
|
| 73 |
+
0. Definitions.
|
| 74 |
+
|
| 75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
| 76 |
+
|
| 77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
| 78 |
+
works, such as semiconductor masks.
|
| 79 |
+
|
| 80 |
+
"The Program" refers to any copyrightable work licensed under this
|
| 81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
| 82 |
+
"recipients" may be individuals or organizations.
|
| 83 |
+
|
| 84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
| 85 |
+
in a fashion requiring copyright permission, other than the making of an
|
| 86 |
+
exact copy. The resulting work is called a "modified version" of the
|
| 87 |
+
earlier work or a work "based on" the earlier work.
|
| 88 |
+
|
| 89 |
+
A "covered work" means either the unmodified Program or a work based
|
| 90 |
+
on the Program.
|
| 91 |
+
|
| 92 |
+
To "propagate" a work means to do anything with it that, without
|
| 93 |
+
permission, would make you directly or secondarily liable for
|
| 94 |
+
infringement under applicable copyright law, except executing it on a
|
| 95 |
+
computer or modifying a private copy. Propagation includes copying,
|
| 96 |
+
distribution (with or without modification), making available to the
|
| 97 |
+
public, and in some countries other activities as well.
|
| 98 |
+
|
| 99 |
+
To "convey" a work means any kind of propagation that enables other
|
| 100 |
+
parties to make or receive copies. Mere interaction with a user through
|
| 101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
| 102 |
+
|
| 103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
| 104 |
+
to the extent that it includes a convenient and prominently visible
|
| 105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
| 106 |
+
tells the user that there is no warranty for the work (except to the
|
| 107 |
+
extent that warranties are provided), that licensees may convey the
|
| 108 |
+
work under this License, and how to view a copy of this License. If
|
| 109 |
+
the interface presents a list of user commands or options, such as a
|
| 110 |
+
menu, a prominent item in the list meets this criterion.
|
| 111 |
+
|
| 112 |
+
1. Source Code.
|
| 113 |
+
|
| 114 |
+
The "source code" for a work means the preferred form of the work
|
| 115 |
+
for making modifications to it. "Object code" means any non-source
|
| 116 |
+
form of a work.
|
| 117 |
+
|
| 118 |
+
A "Standard Interface" means an interface that either is an official
|
| 119 |
+
standard defined by a recognized standards body, or, in the case of
|
| 120 |
+
interfaces specified for a particular programming language, one that
|
| 121 |
+
is widely used among developers working in that language.
|
| 122 |
+
|
| 123 |
+
The "System Libraries" of an executable work include anything, other
|
| 124 |
+
than the work as a whole, that (a) is included in the normal form of
|
| 125 |
+
packaging a Major Component, but which is not part of that Major
|
| 126 |
+
Component, and (b) serves only to enable use of the work with that
|
| 127 |
+
Major Component, or to implement a Standard Interface for which an
|
| 128 |
+
implementation is available to the public in source code form. A
|
| 129 |
+
"Major Component", in this context, means a major essential component
|
| 130 |
+
(kernel, window system, and so on) of the specific operating system
|
| 131 |
+
(if any) on which the executable work runs, or a compiler used to
|
| 132 |
+
produce the work, or an object code interpreter used to run it.
|
| 133 |
+
|
| 134 |
+
The "Corresponding Source" for a work in object code form means all
|
| 135 |
+
the source code needed to generate, install, and (for an executable
|
| 136 |
+
work) run the object code and to modify the work, including scripts to
|
| 137 |
+
control those activities. However, it does not include the work's
|
| 138 |
+
System Libraries, or general-purpose tools or generally available free
|
| 139 |
+
programs which are used unmodified in performing those activities but
|
| 140 |
+
which are not part of the work. For example, Corresponding Source
|
| 141 |
+
includes interface definition files associated with source files for
|
| 142 |
+
the work, and the source code for shared libraries and dynamically
|
| 143 |
+
linked subprograms that the work is specifically designed to require,
|
| 144 |
+
such as by intimate data communication or control flow between those
|
| 145 |
+
subprograms and other parts of the work.
|
| 146 |
+
|
| 147 |
+
The Corresponding Source need not include anything that users
|
| 148 |
+
can regenerate automatically from other parts of the Corresponding
|
| 149 |
+
Source.
|
| 150 |
+
|
| 151 |
+
The Corresponding Source for a work in source code form is that
|
| 152 |
+
same work.
|
| 153 |
+
|
| 154 |
+
2. Basic Permissions.
|
| 155 |
+
|
| 156 |
+
All rights granted under this License are granted for the term of
|
| 157 |
+
copyright on the Program, and are irrevocable provided the stated
|
| 158 |
+
conditions are met. This License explicitly affirms your unlimited
|
| 159 |
+
permission to run the unmodified Program. The output from running a
|
| 160 |
+
covered work is covered by this License only if the output, given its
|
| 161 |
+
content, constitutes a covered work. This License acknowledges your
|
| 162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
| 163 |
+
|
| 164 |
+
You may make, run and propagate covered works that you do not
|
| 165 |
+
convey, without conditions so long as your license otherwise remains
|
| 166 |
+
in force. You may convey covered works to others for the sole purpose
|
| 167 |
+
of having them make modifications exclusively for you, or provide you
|
| 168 |
+
with facilities for running those works, provided that you comply with
|
| 169 |
+
the terms of this License in conveying all material for which you do
|
| 170 |
+
not control copyright. Those thus making or running the covered works
|
| 171 |
+
for you must do so exclusively on your behalf, under your direction
|
| 172 |
+
and control, on terms that prohibit them from making any copies of
|
| 173 |
+
your copyrighted material outside their relationship with you.
|
| 174 |
+
|
| 175 |
+
Conveying under any other circumstances is permitted solely under
|
| 176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
| 177 |
+
makes it unnecessary.
|
| 178 |
+
|
| 179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 180 |
+
|
| 181 |
+
No covered work shall be deemed part of an effective technological
|
| 182 |
+
measure under any applicable law fulfilling obligations under article
|
| 183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
| 184 |
+
similar laws prohibiting or restricting circumvention of such
|
| 185 |
+
measures.
|
| 186 |
+
|
| 187 |
+
When you convey a covered work, you waive any legal power to forbid
|
| 188 |
+
circumvention of technological measures to the extent such circumvention
|
| 189 |
+
is effected by exercising rights under this License with respect to
|
| 190 |
+
the covered work, and you disclaim any intention to limit operation or
|
| 191 |
+
modification of the work as a means of enforcing, against the work's
|
| 192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
| 193 |
+
technological measures.
|
| 194 |
+
|
| 195 |
+
4. Conveying Verbatim Copies.
|
| 196 |
+
|
| 197 |
+
You may convey verbatim copies of the Program's source code as you
|
| 198 |
+
receive it, in any medium, provided that you conspicuously and
|
| 199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
| 200 |
+
keep intact all notices stating that this License and any
|
| 201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
| 202 |
+
keep intact all notices of the absence of any warranty; and give all
|
| 203 |
+
recipients a copy of this License along with the Program.
|
| 204 |
+
|
| 205 |
+
You may charge any price or no price for each copy that you convey,
|
| 206 |
+
and you may offer support or warranty protection for a fee.
|
| 207 |
+
|
| 208 |
+
5. Conveying Modified Source Versions.
|
| 209 |
+
|
| 210 |
+
You may convey a work based on the Program, or the modifications to
|
| 211 |
+
produce it from the Program, in the form of source code under the
|
| 212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
| 213 |
+
|
| 214 |
+
a) The work must carry prominent notices stating that you modified
|
| 215 |
+
it, and giving a relevant date.
|
| 216 |
+
|
| 217 |
+
b) The work must carry prominent notices stating that it is
|
| 218 |
+
released under this License and any conditions added under section
|
| 219 |
+
7. This requirement modifies the requirement in section 4 to
|
| 220 |
+
"keep intact all notices".
|
| 221 |
+
|
| 222 |
+
c) You must license the entire work, as a whole, under this
|
| 223 |
+
License to anyone who comes into possession of a copy. This
|
| 224 |
+
License will therefore apply, along with any applicable section 7
|
| 225 |
+
additional terms, to the whole of the work, and all its parts,
|
| 226 |
+
regardless of how they are packaged. This License gives no
|
| 227 |
+
permission to license the work in any other way, but it does not
|
| 228 |
+
invalidate such permission if you have separately received it.
|
| 229 |
+
|
| 230 |
+
d) If the work has interactive user interfaces, each must display
|
| 231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
| 232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
| 233 |
+
work need not make them do so.
|
| 234 |
+
|
| 235 |
+
A compilation of a covered work with other separate and independent
|
| 236 |
+
works, which are not by their nature extensions of the covered work,
|
| 237 |
+
and which are not combined with it such as to form a larger program,
|
| 238 |
+
in or on a volume of a storage or distribution medium, is called an
|
| 239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
| 240 |
+
used to limit the access or legal rights of the compilation's users
|
| 241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
| 242 |
+
in an aggregate does not cause this License to apply to the other
|
| 243 |
+
parts of the aggregate.
|
| 244 |
+
|
| 245 |
+
6. Conveying Non-Source Forms.
|
| 246 |
+
|
| 247 |
+
You may convey a covered work in object code form under the terms
|
| 248 |
+
of sections 4 and 5, provided that you also convey the
|
| 249 |
+
machine-readable Corresponding Source under the terms of this License,
|
| 250 |
+
in one of these ways:
|
| 251 |
+
|
| 252 |
+
a) Convey the object code in, or embodied in, a physical product
|
| 253 |
+
(including a physical distribution medium), accompanied by the
|
| 254 |
+
Corresponding Source fixed on a durable physical medium
|
| 255 |
+
customarily used for software interchange.
|
| 256 |
+
|
| 257 |
+
b) Convey the object code in, or embodied in, a physical product
|
| 258 |
+
(including a physical distribution medium), accompanied by a
|
| 259 |
+
written offer, valid for at least three years and valid for as
|
| 260 |
+
long as you offer spare parts or customer support for that product
|
| 261 |
+
model, to give anyone who possesses the object code either (1) a
|
| 262 |
+
copy of the Corresponding Source for all the software in the
|
| 263 |
+
product that is covered by this License, on a durable physical
|
| 264 |
+
medium customarily used for software interchange, for a price no
|
| 265 |
+
more than your reasonable cost of physically performing this
|
| 266 |
+
conveying of source, or (2) access to copy the
|
| 267 |
+
Corresponding Source from a network server at no charge.
|
| 268 |
+
|
| 269 |
+
c) Convey individual copies of the object code with a copy of the
|
| 270 |
+
written offer to provide the Corresponding Source. This
|
| 271 |
+
alternative is allowed only occasionally and noncommercially, and
|
| 272 |
+
only if you received the object code with such an offer, in accord
|
| 273 |
+
with subsection 6b.
|
| 274 |
+
|
| 275 |
+
d) Convey the object code by offering access from a designated
|
| 276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
| 277 |
+
Corresponding Source in the same way through the same place at no
|
| 278 |
+
further charge. You need not require recipients to copy the
|
| 279 |
+
Corresponding Source along with the object code. If the place to
|
| 280 |
+
copy the object code is a network server, the Corresponding Source
|
| 281 |
+
may be on a different server (operated by you or a third party)
|
| 282 |
+
that supports equivalent copying facilities, provided you maintain
|
| 283 |
+
clear directions next to the object code saying where to find the
|
| 284 |
+
Corresponding Source. Regardless of what server hosts the
|
| 285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
| 286 |
+
available for as long as needed to satisfy these requirements.
|
| 287 |
+
|
| 288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
| 289 |
+
you inform other peers where the object code and Corresponding
|
| 290 |
+
Source of the work are being offered to the general public at no
|
| 291 |
+
charge under subsection 6d.
|
| 292 |
+
|
| 293 |
+
A separable portion of the object code, whose source code is excluded
|
| 294 |
+
from the Corresponding Source as a System Library, need not be
|
| 295 |
+
included in conveying the object code work.
|
| 296 |
+
|
| 297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
| 298 |
+
tangible personal property which is normally used for personal, family,
|
| 299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
| 300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
| 301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
| 302 |
+
product received by a particular user, "normally used" refers to a
|
| 303 |
+
typical or common use of that class of product, regardless of the status
|
| 304 |
+
of the particular user or of the way in which the particular user
|
| 305 |
+
actually uses, or expects or is expected to use, the product. A product
|
| 306 |
+
is a consumer product regardless of whether the product has substantial
|
| 307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
| 308 |
+
the only significant mode of use of the product.
|
| 309 |
+
|
| 310 |
+
"Installation Information" for a User Product means any methods,
|
| 311 |
+
procedures, authorization keys, or other information required to install
|
| 312 |
+
and execute modified versions of a covered work in that User Product from
|
| 313 |
+
a modified version of its Corresponding Source. The information must
|
| 314 |
+
suffice to ensure that the continued functioning of the modified object
|
| 315 |
+
code is in no case prevented or interfered with solely because
|
| 316 |
+
modification has been made.
|
| 317 |
+
|
| 318 |
+
If you convey an object code work under this section in, or with, or
|
| 319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
| 320 |
+
part of a transaction in which the right of possession and use of the
|
| 321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
| 322 |
+
fixed term (regardless of how the transaction is characterized), the
|
| 323 |
+
Corresponding Source conveyed under this section must be accompanied
|
| 324 |
+
by the Installation Information. But this requirement does not apply
|
| 325 |
+
if neither you nor any third party retains the ability to install
|
| 326 |
+
modified object code on the User Product (for example, the work has
|
| 327 |
+
been installed in ROM).
|
| 328 |
+
|
| 329 |
+
The requirement to provide Installation Information does not include a
|
| 330 |
+
requirement to continue to provide support service, warranty, or updates
|
| 331 |
+
for a work that has been modified or installed by the recipient, or for
|
| 332 |
+
the User Product in which it has been modified or installed. Access to a
|
| 333 |
+
network may be denied when the modification itself materially and
|
| 334 |
+
adversely affects the operation of the network or violates the rules and
|
| 335 |
+
protocols for communication across the network.
|
| 336 |
+
|
| 337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
| 338 |
+
in accord with this section must be in a format that is publicly
|
| 339 |
+
documented (and with an implementation available to the public in
|
| 340 |
+
source code form), and must require no special password or key for
|
| 341 |
+
unpacking, reading or copying.
|
| 342 |
+
|
| 343 |
+
7. Additional Terms.
|
| 344 |
+
|
| 345 |
+
"Additional permissions" are terms that supplement the terms of this
|
| 346 |
+
License by making exceptions from one or more of its conditions.
|
| 347 |
+
Additional permissions that are applicable to the entire Program shall
|
| 348 |
+
be treated as though they were included in this License, to the extent
|
| 349 |
+
that they are valid under applicable law. If additional permissions
|
| 350 |
+
apply only to part of the Program, that part may be used separately
|
| 351 |
+
under those permissions, but the entire Program remains governed by
|
| 352 |
+
this License without regard to the additional permissions.
|
| 353 |
+
|
| 354 |
+
When you convey a copy of a covered work, you may at your option
|
| 355 |
+
remove any additional permissions from that copy, or from any part of
|
| 356 |
+
it. (Additional permissions may be written to require their own
|
| 357 |
+
removal in certain cases when you modify the work.) You may place
|
| 358 |
+
additional permissions on material, added by you to a covered work,
|
| 359 |
+
for which you have or can give appropriate copyright permission.
|
| 360 |
+
|
| 361 |
+
Notwithstanding any other provision of this License, for material you
|
| 362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
| 363 |
+
that material) supplement the terms of this License with terms:
|
| 364 |
+
|
| 365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
| 366 |
+
terms of sections 15 and 16 of this License; or
|
| 367 |
+
|
| 368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
| 369 |
+
author attributions in that material or in the Appropriate Legal
|
| 370 |
+
Notices displayed by works containing it; or
|
| 371 |
+
|
| 372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
| 373 |
+
requiring that modified versions of such material be marked in
|
| 374 |
+
reasonable ways as different from the original version; or
|
| 375 |
+
|
| 376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
| 377 |
+
authors of the material; or
|
| 378 |
+
|
| 379 |
+
e) Declining to grant rights under trademark law for use of some
|
| 380 |
+
trade names, trademarks, or service marks; or
|
| 381 |
+
|
| 382 |
+
f) Requiring indemnification of licensors and authors of that
|
| 383 |
+
material by anyone who conveys the material (or modified versions of
|
| 384 |
+
it) with contractual assumptions of liability to the recipient, for
|
| 385 |
+
any liability that these contractual assumptions directly impose on
|
| 386 |
+
those licensors and authors.
|
| 387 |
+
|
| 388 |
+
All other non-permissive additional terms are considered "further
|
| 389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
| 390 |
+
received it, or any part of it, contains a notice stating that it is
|
| 391 |
+
governed by this License along with a term that is a further
|
| 392 |
+
restriction, you may remove that term. If a license document contains
|
| 393 |
+
a further restriction but permits relicensing or conveying under this
|
| 394 |
+
License, you may add to a covered work material governed by the terms
|
| 395 |
+
of that license document, provided that the further restriction does
|
| 396 |
+
not survive such relicensing or conveying.
|
| 397 |
+
|
| 398 |
+
If you add terms to a covered work in accord with this section, you
|
| 399 |
+
must place, in the relevant source files, a statement of the
|
| 400 |
+
additional terms that apply to those files, or a notice indicating
|
| 401 |
+
where to find the applicable terms.
|
| 402 |
+
|
| 403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
| 404 |
+
form of a separately written license, or stated as exceptions;
|
| 405 |
+
the above requirements apply either way.
|
| 406 |
+
|
| 407 |
+
8. Termination.
|
| 408 |
+
|
| 409 |
+
You may not propagate or modify a covered work except as expressly
|
| 410 |
+
provided under this License. Any attempt otherwise to propagate or
|
| 411 |
+
modify it is void, and will automatically terminate your rights under
|
| 412 |
+
this License (including any patent licenses granted under the third
|
| 413 |
+
paragraph of section 11).
|
| 414 |
+
|
| 415 |
+
However, if you cease all violation of this License, then your
|
| 416 |
+
license from a particular copyright holder is reinstated (a)
|
| 417 |
+
provisionally, unless and until the copyright holder explicitly and
|
| 418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
| 419 |
+
holder fails to notify you of the violation by some reasonable means
|
| 420 |
+
prior to 60 days after the cessation.
|
| 421 |
+
|
| 422 |
+
Moreover, your license from a particular copyright holder is
|
| 423 |
+
reinstated permanently if the copyright holder notifies you of the
|
| 424 |
+
violation by some reasonable means, this is the first time you have
|
| 425 |
+
received notice of violation of this License (for any work) from that
|
| 426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
| 427 |
+
your receipt of the notice.
|
| 428 |
+
|
| 429 |
+
Termination of your rights under this section does not terminate the
|
| 430 |
+
licenses of parties who have received copies or rights from you under
|
| 431 |
+
this License. If your rights have been terminated and not permanently
|
| 432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
| 433 |
+
material under section 10.
|
| 434 |
+
|
| 435 |
+
9. Acceptance Not Required for Having Copies.
|
| 436 |
+
|
| 437 |
+
You are not required to accept this License in order to receive or
|
| 438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
| 439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
| 440 |
+
to receive a copy likewise does not require acceptance. However,
|
| 441 |
+
nothing other than this License grants you permission to propagate or
|
| 442 |
+
modify any covered work. These actions infringe copyright if you do
|
| 443 |
+
not accept this License. Therefore, by modifying or propagating a
|
| 444 |
+
covered work, you indicate your acceptance of this License to do so.
|
| 445 |
+
|
| 446 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 447 |
+
|
| 448 |
+
Each time you convey a covered work, the recipient automatically
|
| 449 |
+
receives a license from the original licensors, to run, modify and
|
| 450 |
+
propagate that work, subject to this License. You are not responsible
|
| 451 |
+
for enforcing compliance by third parties with this License.
|
| 452 |
+
|
| 453 |
+
An "entity transaction" is a transaction transferring control of an
|
| 454 |
+
organization, or substantially all assets of one, or subdividing an
|
| 455 |
+
organization, or merging organizations. If propagation of a covered
|
| 456 |
+
work results from an entity transaction, each party to that
|
| 457 |
+
transaction who receives a copy of the work also receives whatever
|
| 458 |
+
licenses to the work the party's predecessor in interest had or could
|
| 459 |
+
give under the previous paragraph, plus a right to possession of the
|
| 460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
| 461 |
+
the predecessor has it or can get it with reasonable efforts.
|
| 462 |
+
|
| 463 |
+
You may not impose any further restrictions on the exercise of the
|
| 464 |
+
rights granted or affirmed under this License. For example, you may
|
| 465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
| 466 |
+
rights granted under this License, and you may not initiate litigation
|
| 467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
| 468 |
+
any patent claim is infringed by making, using, selling, offering for
|
| 469 |
+
sale, or importing the Program or any portion of it.
|
| 470 |
+
|
| 471 |
+
11. Patents.
|
| 472 |
+
|
| 473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
| 474 |
+
License of the Program or a work on which the Program is based. The
|
| 475 |
+
work thus licensed is called the contributor's "contributor version".
|
| 476 |
+
|
| 477 |
+
A contributor's "essential patent claims" are all patent claims
|
| 478 |
+
owned or controlled by the contributor, whether already acquired or
|
| 479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
| 480 |
+
by this License, of making, using, or selling its contributor version,
|
| 481 |
+
but do not include claims that would be infringed only as a
|
| 482 |
+
consequence of further modification of the contributor version. For
|
| 483 |
+
purposes of this definition, "control" includes the right to grant
|
| 484 |
+
patent sublicenses in a manner consistent with the requirements of
|
| 485 |
+
this License.
|
| 486 |
+
|
| 487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
| 488 |
+
patent license under the contributor's essential patent claims, to
|
| 489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
| 490 |
+
propagate the contents of its contributor version.
|
| 491 |
+
|
| 492 |
+
In the following three paragraphs, a "patent license" is any express
|
| 493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
| 494 |
+
(such as an express permission to practice a patent or covenant not to
|
| 495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
| 496 |
+
party means to make such an agreement or commitment not to enforce a
|
| 497 |
+
patent against the party.
|
| 498 |
+
|
| 499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
| 500 |
+
and the Corresponding Source of the work is not available for anyone
|
| 501 |
+
to copy, free of charge and under the terms of this License, through a
|
| 502 |
+
publicly available network server or other readily accessible means,
|
| 503 |
+
then you must either (1) cause the Corresponding Source to be so
|
| 504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
| 505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
| 506 |
+
consistent with the requirements of this License, to extend the patent
|
| 507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
| 508 |
+
actual knowledge that, but for the patent license, your conveying the
|
| 509 |
+
covered work in a country, or your recipient's use of the covered work
|
| 510 |
+
in a country, would infringe one or more identifiable patents in that
|
| 511 |
+
country that you have reason to believe are valid.
|
| 512 |
+
|
| 513 |
+
If, pursuant to or in connection with a single transaction or
|
| 514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
| 515 |
+
covered work, and grant a patent license to some of the parties
|
| 516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
| 517 |
+
or convey a specific copy of the covered work, then the patent license
|
| 518 |
+
you grant is automatically extended to all recipients of the covered
|
| 519 |
+
work and works based on it.
|
| 520 |
+
|
| 521 |
+
A patent license is "discriminatory" if it does not include within
|
| 522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
| 523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
| 524 |
+
specifically granted under this License. You may not convey a covered
|
| 525 |
+
work if you are a party to an arrangement with a third party that is
|
| 526 |
+
in the business of distributing software, under which you make payment
|
| 527 |
+
to the third party based on the extent of your activity of conveying
|
| 528 |
+
the work, and under which the third party grants, to any of the
|
| 529 |
+
parties who would receive the covered work from you, a discriminatory
|
| 530 |
+
patent license (a) in connection with copies of the covered work
|
| 531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
| 532 |
+
for and in connection with specific products or compilations that
|
| 533 |
+
contain the covered work, unless you entered into that arrangement,
|
| 534 |
+
or that patent license was granted, prior to 28 March 2007.
|
| 535 |
+
|
| 536 |
+
Nothing in this License shall be construed as excluding or limiting
|
| 537 |
+
any implied license or other defenses to infringement that may
|
| 538 |
+
otherwise be available to you under applicable patent law.
|
| 539 |
+
|
| 540 |
+
12. No Surrender of Others' Freedom.
|
| 541 |
+
|
| 542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
| 543 |
+
otherwise) that contradict the conditions of this License, they do not
|
| 544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
| 545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
| 546 |
+
License and any other pertinent obligations, then as a consequence you may
|
| 547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
| 548 |
+
to collect a royalty for further conveying from those to whom you convey
|
| 549 |
+
the Program, the only way you could satisfy both those terms and this
|
| 550 |
+
License would be to refrain entirely from conveying the Program.
|
| 551 |
+
|
| 552 |
+
13. Use with the GNU Affero General Public License.
|
| 553 |
+
|
| 554 |
+
Notwithstanding any other provision of this License, you have
|
| 555 |
+
permission to link or combine any covered work with a work licensed
|
| 556 |
+
under version 3 of the GNU Affero General Public License into a single
|
| 557 |
+
combined work, and to convey the resulting work. The terms of this
|
| 558 |
+
License will continue to apply to the part which is the covered work,
|
| 559 |
+
but the special requirements of the GNU Affero General Public License,
|
| 560 |
+
section 13, concerning interaction through a network will apply to the
|
| 561 |
+
combination as such.
|
| 562 |
+
|
| 563 |
+
14. Revised Versions of this License.
|
| 564 |
+
|
| 565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
| 566 |
+
the GNU General Public License from time to time. Such new versions will
|
| 567 |
+
be similar in spirit to the present version, but may differ in detail to
|
| 568 |
+
address new problems or concerns.
|
| 569 |
+
|
| 570 |
+
Each version is given a distinguishing version number. If the
|
| 571 |
+
Program specifies that a certain numbered version of the GNU General
|
| 572 |
+
Public License "or any later version" applies to it, you have the
|
| 573 |
+
option of following the terms and conditions either of that numbered
|
| 574 |
+
version or of any later version published by the Free Software
|
| 575 |
+
Foundation. If the Program does not specify a version number of the
|
| 576 |
+
GNU General Public License, you may choose any version ever published
|
| 577 |
+
by the Free Software Foundation.
|
| 578 |
+
|
| 579 |
+
If the Program specifies that a proxy can decide which future
|
| 580 |
+
versions of the GNU General Public License can be used, that proxy's
|
| 581 |
+
public statement of acceptance of a version permanently authorizes you
|
| 582 |
+
to choose that version for the Program.
|
| 583 |
+
|
| 584 |
+
Later license versions may give you additional or different
|
| 585 |
+
permissions. However, no additional obligations are imposed on any
|
| 586 |
+
author or copyright holder as a result of your choosing to follow a
|
| 587 |
+
later version.
|
| 588 |
+
|
| 589 |
+
15. Disclaimer of Warranty.
|
| 590 |
+
|
| 591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
| 592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
| 593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
| 594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
| 595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
| 597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
| 598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 599 |
+
|
| 600 |
+
16. Limitation of Liability.
|
| 601 |
+
|
| 602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
| 603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
| 604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
| 605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
| 606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
| 607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
| 608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
| 609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
| 610 |
+
SUCH DAMAGES.
|
| 611 |
+
|
| 612 |
+
17. Interpretation of Sections 15 and 16.
|
| 613 |
+
|
| 614 |
+
If the disclaimer of warranty and limitation of liability provided
|
| 615 |
+
above cannot be given local legal effect according to their terms,
|
| 616 |
+
reviewing courts shall apply local law that most closely approximates
|
| 617 |
+
an absolute waiver of all civil liability in connection with the
|
| 618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
| 619 |
+
copy of the Program in return for a fee.
|
| 620 |
+
|
| 621 |
+
END OF TERMS AND CONDITIONS
|
| 622 |
+
|
| 623 |
+
How to Apply These Terms to Your New Programs
|
| 624 |
+
|
| 625 |
+
If you develop a new program, and you want it to be of the greatest
|
| 626 |
+
possible use to the public, the best way to achieve this is to make it
|
| 627 |
+
free software which everyone can redistribute and change under these terms.
|
| 628 |
+
|
| 629 |
+
To do so, attach the following notices to the program. It is safest
|
| 630 |
+
to attach them to the start of each source file to most effectively
|
| 631 |
+
state the exclusion of warranty; and each file should have at least
|
| 632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
| 633 |
+
|
| 634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 635 |
+
Copyright (C) <year> <name of author>
|
| 636 |
+
|
| 637 |
+
This program is free software: you can redistribute it and/or modify
|
| 638 |
+
it under the terms of the GNU General Public License as published by
|
| 639 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 640 |
+
(at your option) any later version.
|
| 641 |
+
|
| 642 |
+
This program is distributed in the hope that it will be useful,
|
| 643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 645 |
+
GNU General Public License for more details.
|
| 646 |
+
|
| 647 |
+
You should have received a copy of the GNU General Public License
|
| 648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 649 |
+
|
| 650 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 651 |
+
|
| 652 |
+
If the program does terminal interaction, make it output a short
|
| 653 |
+
notice like this when it starts in an interactive mode:
|
| 654 |
+
|
| 655 |
+
<program> Copyright (C) <year> <name of author>
|
| 656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
| 657 |
+
This is free software, and you are welcome to redistribute it
|
| 658 |
+
under certain conditions; type `show c' for details.
|
| 659 |
+
|
| 660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
| 661 |
+
parts of the General Public License. Of course, your program's commands
|
| 662 |
+
might be different; for a GUI interface, you would use an "about box".
|
| 663 |
+
|
| 664 |
+
You should also get your employer (if you work as a programmer) or school,
|
| 665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
| 666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
| 667 |
+
<https://www.gnu.org/licenses/>.
|
| 668 |
+
|
| 669 |
+
The GNU General Public License does not permit incorporating your program
|
| 670 |
+
into proprietary programs. If your program is a subroutine library, you
|
| 671 |
+
may consider it more useful to permit linking proprietary applications with
|
| 672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
| 673 |
+
Public License instead of this License. But first, please read
|
| 674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: gpl-3.0
|
| 3 |
+
language:
|
| 4 |
+
- grc
|
| 5 |
+
tags:
|
| 6 |
+
- ancient-greek
|
| 7 |
+
- vowel-length
|
| 8 |
+
- macronization
|
| 9 |
+
- code
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# oga-macronizer-char-code
|
| 13 |
+
|
| 14 |
+
Training, hyperparameter search and evaluation code for the char-level
|
| 15 |
+
Ancient Greek macronizer
|
| 16 |
+
([Ericu950/oga-macronizer-char](https://huggingface.co/Ericu950/oga-macronizer-char)),
|
| 17 |
+
as revised for the reviewed version of *Automatic Annotation of Ancient Greek
|
| 18 |
+
Vowel Length* (Thörn Cleland & Cullhed).
|
| 19 |
+
|
| 20 |
+
Compared to the original code in
|
| 21 |
+
[grc-macronizer/macron_model](https://github.com/Urdatorn/grc-macronizer/tree/oga-macronization-improvements/macron_model)
|
| 22 |
+
(commit `456c970`):
|
| 23 |
+
|
| 24 |
+
- **Decontaminated training data:** training uses
|
| 25 |
+
[Urdatorn/oga-macronized-no-norma](https://huggingface.co/datasets/Urdatorn/oga-macronized-no-norma),
|
| 26 |
+
from which every sentence overlapping the benchmark has been removed.
|
| 27 |
+
- **Current Norma layout:** evaluation reads the jsonl version of
|
| 28 |
+
[Urdatorn/norma](https://huggingface.co/datasets/Urdatorn/norma)
|
| 29 |
+
(`data/test.jsonl`, `data/validation.jsonl`) and reports the metrics of the
|
| 30 |
+
paper's Table 1 (per-label accuracy, P, R, F1 and coverage) and per-position
|
| 31 |
+
predictions for error analysis.
|
| 32 |
+
- **Model selection on gold data:** Norma validation, which is gold-annotated,
|
| 33 |
+
is scored at every evaluation and can drive checkpoint selection, early
|
| 34 |
+
stopping and hyperparameter search. The test split is used only in the final
|
| 35 |
+
evaluation.
|
| 36 |
+
- **Hyperparameter search:** an Optuna search over learning rate and weight
|
| 37 |
+
decay, with dropout optional.
|
| 38 |
+
- **Faster training input:** the corpus is encoded once into flat arrays, and
|
| 39 |
+
padding and diacritic masking are vectorized.
|
| 40 |
+
|
| 41 |
+
`model.py` and `tokenizer.py` are unchanged from the original, so checkpoints
|
| 42 |
+
are compatible both ways.
|
| 43 |
+
|
| 44 |
+
## Files
|
| 45 |
+
|
| 46 |
+
| file | purpose |
|
| 47 |
+
|---|---|
|
| 48 |
+
| `model.py`, `tokenizer.py` | model and char-plane tokenizer (unchanged) |
|
| 49 |
+
| `prepare_data.py` | encode the silver corpus into `cache/` (fixed 90/10 split, `--data_seed 0`) |
|
| 50 |
+
| `train.py` | train one model, logging silver-val and Norma-val metrics at every evaluation |
|
| 51 |
+
| `hpo.py` | Optuna study shared by several slurm workers through a journal file |
|
| 52 |
+
| `evaluate.py` | score checkpoints (local or Hub) on Norma, writing metrics and per-position jsonl |
|
| 53 |
+
| `norma.py` | Norma loading and scoring |
|
| 54 |
+
| `predict.py` | batched inference (`MacronPredictor`) |
|
| 55 |
+
| `slurm/` | jobs for the Arrhenius GH200 nodes |
|
| 56 |
+
|
| 57 |
+
## Usage
|
| 58 |
+
|
| 59 |
+
```sh
|
| 60 |
+
pip install -r requirements.txt
|
| 61 |
+
python prepare_data.py --out cache/oga-no-norma
|
| 62 |
+
python train.py --cache cache/oga-no-norma --output_dir runs/seed1 --seed 1
|
| 63 |
+
python evaluate.py --models runs/seed1/best --splits test validation --out results/seed1
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
## Scoring
|
| 67 |
+
|
| 68 |
+
The scored positions are the gold-marked dichrona in open syllables. In test,
|
| 69 |
+
openness comes from the parallel syllabify lines, giving 1,916 positions. In
|
| 70 |
+
validation, which has no syllabify lines, every gold mark is scored, giving
|
| 71 |
+
2,498 positions.
|
| 72 |
+
|
| 73 |
+
- **Accuracy:** an unmarked position counts as wrong.
|
| 74 |
+
- **Per label:** accuracy equals recall; precision is computed over that
|
| 75 |
+
label's predictions.
|
| 76 |
+
- **Mixed (micro-averaged):** recall = accuracy; precision = correct / marked
|
| 77 |
+
positions; F1 is their harmonic mean. This reproduces Table 1.
|
| 78 |
+
- **Defaults-to-short accuracy:** an unmarked position counts as "short".
|
| 79 |
+
This is the metric reported on the model cards.
|
| 80 |
+
|
| 81 |
+
## License
|
| 82 |
+
|
| 83 |
+
GNU GPL v3.
|
evaluate.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Score one or more checkpoints (local dirs or HF repo ids) on Norma.
|
| 3 |
+
|
| 4 |
+
python evaluate.py --models Ericu950/oga-macronizer-char runs/final/seed1/best \
|
| 5 |
+
--splits test validation --out results/eval
|
| 6 |
+
|
| 7 |
+
For each model and split it prints the Table 1 metrics and the per-source
|
| 8 |
+
scores, and writes:
|
| 9 |
+
- <out>/<name>.<split>.metrics.json
|
| 10 |
+
- <out>/<name>.<split>.positions.jsonl: one row per scored position
|
| 11 |
+
(source, line, char, word, gold, pred), for the error analysis.
|
| 12 |
+
'''
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import time
|
| 18 |
+
|
| 19 |
+
from norma import format_table, load_split, metrics, score
|
| 20 |
+
from predict import MacronPredictor
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main():
|
| 24 |
+
ap = argparse.ArgumentParser()
|
| 25 |
+
ap.add_argument("--models", nargs="+", required=True)
|
| 26 |
+
ap.add_argument("--splits", nargs="+", default=["test"])
|
| 27 |
+
ap.add_argument("--norma_repo", default="Urdatorn/norma")
|
| 28 |
+
ap.add_argument("--norma_revision", default=None)
|
| 29 |
+
ap.add_argument("--out", default=None)
|
| 30 |
+
ap.add_argument("--device", default=None)
|
| 31 |
+
ap.add_argument("--batch_size", type=int, default=256,
|
| 32 |
+
help="1 = one line at a time without padding, as the original predict.py")
|
| 33 |
+
a = ap.parse_args()
|
| 34 |
+
data = {s: load_split(s, a.norma_repo, a.norma_revision) for s in a.splits}
|
| 35 |
+
all_metrics = {}
|
| 36 |
+
for m in a.models:
|
| 37 |
+
t = time.time()
|
| 38 |
+
pred = MacronPredictor(m, device=a.device)
|
| 39 |
+
name = m.strip("/").replace("/", "__") + ("" if a.batch_size != 1 else ".unbatched")
|
| 40 |
+
for s, recs in data.items():
|
| 41 |
+
outputs = pred.macronize_lines([r.plain for r in recs], batch_size=a.batch_size)
|
| 42 |
+
pos = score(recs, outputs)
|
| 43 |
+
met = metrics(pos)
|
| 44 |
+
all_metrics[(m, s)] = met
|
| 45 |
+
print(f"\n=== {m} on Norma {s} ({len(recs)} lines, {met['n']} positions, "
|
| 46 |
+
f"{time.time()-t:.1f}s) ===", flush=True)
|
| 47 |
+
print(format_table(met), flush=True)
|
| 48 |
+
if a.out:
|
| 49 |
+
os.makedirs(a.out, exist_ok=True)
|
| 50 |
+
with open(os.path.join(a.out, f"{name}.{s}.metrics.json"), "w") as f:
|
| 51 |
+
json.dump(met, f, indent=2)
|
| 52 |
+
with open(os.path.join(a.out, f"{name}.{s}.positions.jsonl"), "w", encoding="utf-8") as f:
|
| 53 |
+
for p in pos:
|
| 54 |
+
f.write(json.dumps(p, ensure_ascii=False) + "\n")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
if __name__ == "__main__":
|
| 58 |
+
main()
|
hpo.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Optuna search over learning rate and weight decay (optionally dropout).
|
| 3 |
+
|
| 4 |
+
One study lives in a journal file that several GPU workers (a slurm array)
|
| 5 |
+
share:
|
| 6 |
+
|
| 7 |
+
python hpo.py init --study_dir runs/hpo # creates the study, queues the paper's config
|
| 8 |
+
python hpo.py worker --study_dir runs/hpo --cache cache/oga-no-norma --n_trials 5 --worker_id 0
|
| 9 |
+
python hpo.py report --study_dir runs/hpo
|
| 10 |
+
|
| 11 |
+
Every trial is a normal train.py run (same arguments; anything not tuned
|
| 12 |
+
comes from --train_args) with Optuna's median pruner applied at each
|
| 13 |
+
evaluation. The objective is train.py's --select_metric, maximized.
|
| 14 |
+
'''
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import shlex
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
import optuna
|
| 23 |
+
from optuna.storages import JournalStorage
|
| 24 |
+
from optuna.storages.journal import JournalFileBackend
|
| 25 |
+
|
| 26 |
+
import train as train_mod
|
| 27 |
+
|
| 28 |
+
PAPER = {"lr": 3e-4, "weight_decay": 0.01}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def storage(study_dir):
|
| 32 |
+
return JournalStorage(JournalFileBackend(os.path.join(study_dir, "journal.log")))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def log(msg):
|
| 36 |
+
print(f"[{time.strftime('%Y-%m-%dT%H:%M:%S')}] {msg}", flush=True)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def space(trial, cfg):
|
| 40 |
+
p = {"lr": trial.suggest_float("lr", cfg["lr_min"], cfg["lr_max"], log=True),
|
| 41 |
+
"weight_decay": trial.suggest_float("weight_decay", cfg["wd_min"], cfg["wd_max"], log=True)}
|
| 42 |
+
if cfg["tune_dropout"]:
|
| 43 |
+
p["dropout"] = trial.suggest_float("dropout", 0.0, 0.2)
|
| 44 |
+
return p
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def write_report(study, study_dir):
|
| 48 |
+
df = study.trials_dataframe()
|
| 49 |
+
df.to_csv(os.path.join(study_dir, "trials.csv"), index=False)
|
| 50 |
+
done = [t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE]
|
| 51 |
+
if done:
|
| 52 |
+
b = study.best_trial
|
| 53 |
+
with open(os.path.join(study_dir, "best.json"), "w") as f:
|
| 54 |
+
json.dump(dict(number=b.number, value=b.value, params=b.params,
|
| 55 |
+
n_complete=len(done), n_total=len(study.trials)), f, indent=2)
|
| 56 |
+
return df
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def cmd_init(a):
|
| 60 |
+
os.makedirs(a.study_dir, exist_ok=True)
|
| 61 |
+
cfg = dict(lr_min=a.lr_min, lr_max=a.lr_max, wd_min=a.wd_min, wd_max=a.wd_max,
|
| 62 |
+
tune_dropout=a.tune_dropout, train_args=a.train_args,
|
| 63 |
+
pruner_startup_trials=a.pruner_startup_trials, pruner_warmup_evals=a.pruner_warmup_evals)
|
| 64 |
+
with open(os.path.join(a.study_dir, "config.json"), "w") as f:
|
| 65 |
+
json.dump(cfg, f, indent=2)
|
| 66 |
+
study = optuna.create_study(study_name="macronizer", storage=storage(a.study_dir),
|
| 67 |
+
direction="maximize", load_if_exists=True)
|
| 68 |
+
if not study.trials:
|
| 69 |
+
study.enqueue_trial(dict(PAPER, **({"dropout": 0.1} if a.tune_dropout else {})))
|
| 70 |
+
log(f"queued the paper's config {PAPER}")
|
| 71 |
+
log(f"study ready in {a.study_dir}: {json.dumps(cfg)}")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def cmd_worker(a):
|
| 75 |
+
with open(os.path.join(a.study_dir, "config.json")) as f:
|
| 76 |
+
cfg = json.load(f)
|
| 77 |
+
sampler = optuna.samplers.TPESampler(seed=1000 + a.worker_id, n_startup_trials=a.tpe_startup_trials)
|
| 78 |
+
pruner = optuna.pruners.MedianPruner(n_startup_trials=cfg["pruner_startup_trials"],
|
| 79 |
+
n_warmup_steps=cfg["pruner_warmup_evals"])
|
| 80 |
+
study = optuna.load_study(study_name="macronizer", storage=storage(a.study_dir),
|
| 81 |
+
sampler=sampler, pruner=pruner)
|
| 82 |
+
base = shlex.split(cfg["train_args"])
|
| 83 |
+
|
| 84 |
+
def objective(trial):
|
| 85 |
+
params = space(trial, cfg)
|
| 86 |
+
out = os.path.join(a.study_dir, f"trial_{trial.number:03d}")
|
| 87 |
+
argv = base + ["--cache", a.cache, "--output_dir", out]
|
| 88 |
+
for k, v in params.items():
|
| 89 |
+
argv += [f"--{k}", repr(v)]
|
| 90 |
+
args = train_mod.build_parser().parse_args(argv)
|
| 91 |
+
log(f"TRIAL {trial.number} START worker {a.worker_id} params {params}")
|
| 92 |
+
try:
|
| 93 |
+
summary = train_mod.run(args, trial=trial)
|
| 94 |
+
except optuna.TrialPruned:
|
| 95 |
+
log(f"TRIAL {trial.number} PRUNED")
|
| 96 |
+
raise
|
| 97 |
+
trial.set_user_attr("best_eval", summary["best_eval"])
|
| 98 |
+
trial.set_user_attr("minutes", summary["minutes"])
|
| 99 |
+
log(f"TRIAL {trial.number} DONE value {summary['best_value']:.4%} params {params}")
|
| 100 |
+
return summary["best_value"]
|
| 101 |
+
|
| 102 |
+
def after(study, trial):
|
| 103 |
+
write_report(study, a.study_dir)
|
| 104 |
+
done = [t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE]
|
| 105 |
+
if done:
|
| 106 |
+
b = study.best_trial
|
| 107 |
+
log(f"STUDY {len(done)} complete / {len(study.trials)} total; best #{b.number} "
|
| 108 |
+
f"{b.value:.4%} {b.params}")
|
| 109 |
+
|
| 110 |
+
study.optimize(objective, n_trials=a.n_trials, callbacks=[after], gc_after_trial=True)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def cmd_report(a):
|
| 114 |
+
study = optuna.load_study(study_name="macronizer", storage=storage(a.study_dir))
|
| 115 |
+
df = write_report(study, a.study_dir)
|
| 116 |
+
cols = [c for c in df.columns if c in ("number", "state", "value", "params_lr",
|
| 117 |
+
"params_weight_decay", "params_dropout", "duration")]
|
| 118 |
+
print(df[cols].sort_values("value", ascending=False).to_string(index=False))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
if __name__ == "__main__":
|
| 122 |
+
ap = argparse.ArgumentParser()
|
| 123 |
+
ap.add_argument("cmd", choices=["init", "worker", "report"])
|
| 124 |
+
ap.add_argument("--study_dir", required=True)
|
| 125 |
+
ap.add_argument("--cache")
|
| 126 |
+
ap.add_argument("--worker_id", type=int, default=0)
|
| 127 |
+
ap.add_argument("--n_trials", type=int, default=5)
|
| 128 |
+
ap.add_argument("--tpe_startup_trials", type=int, default=6)
|
| 129 |
+
ap.add_argument("--lr_min", type=float, default=1e-4)
|
| 130 |
+
ap.add_argument("--lr_max", type=float, default=3e-3)
|
| 131 |
+
ap.add_argument("--wd_min", type=float, default=1e-4)
|
| 132 |
+
ap.add_argument("--wd_max", type=float, default=0.3)
|
| 133 |
+
ap.add_argument("--tune_dropout", action="store_true")
|
| 134 |
+
ap.add_argument("--pruner_startup_trials", type=int, default=4)
|
| 135 |
+
ap.add_argument("--pruner_warmup_evals", type=int, default=2)
|
| 136 |
+
ap.add_argument("--train_args", default="--seed 1 --epochs 6",
|
| 137 |
+
help="extra train.py arguments shared by every trial")
|
| 138 |
+
a = ap.parse_args()
|
| 139 |
+
{"init": cmd_init, "worker": cmd_worker, "report": cmd_report}[a.cmd](a)
|
model.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
A small char-level transformer that tags each character position with a macron class
|
| 3 |
+
(none / short / long). Input is two factored embedding "planes" per position -- the base
|
| 4 |
+
letter (25 = 24 Greek letters + space, plus an <other>/<pad> bucket) and the diacritic
|
| 5 |
+
combination on that letter -- summed with a learned positional embedding. This is a plain
|
| 6 |
+
transformers.PreTrainedModel/PretrainedConfig subclass so it saves/loads/push_to_hub's like
|
| 7 |
+
any other HF model.
|
| 8 |
+
'''
|
| 9 |
+
|
| 10 |
+
import math
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch import nn
|
| 14 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
| 15 |
+
from transformers.modeling_outputs import TokenClassifierOutput
|
| 16 |
+
|
| 17 |
+
from tokenizer import PLANE1_VOCAB_SIZE, LABEL_IGNORE_INDEX
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class MacronizerConfig(PretrainedConfig):
|
| 21 |
+
model_type = "grc-macronizer-char"
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
plane1_vocab_size=PLANE1_VOCAB_SIZE,
|
| 26 |
+
plane2_vocab_size=64,
|
| 27 |
+
hidden_size=128,
|
| 28 |
+
num_hidden_layers=4,
|
| 29 |
+
num_attention_heads=4,
|
| 30 |
+
intermediate_size=512,
|
| 31 |
+
max_position_embeddings=512,
|
| 32 |
+
dropout=0.1,
|
| 33 |
+
num_labels=3,
|
| 34 |
+
pad_token_id=0,
|
| 35 |
+
**kwargs,
|
| 36 |
+
):
|
| 37 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
| 38 |
+
self.plane1_vocab_size = plane1_vocab_size
|
| 39 |
+
self.plane2_vocab_size = plane2_vocab_size
|
| 40 |
+
self.hidden_size = hidden_size
|
| 41 |
+
self.num_hidden_layers = num_hidden_layers
|
| 42 |
+
self.num_attention_heads = num_attention_heads
|
| 43 |
+
self.intermediate_size = intermediate_size
|
| 44 |
+
self.max_position_embeddings = max_position_embeddings
|
| 45 |
+
self.dropout = dropout
|
| 46 |
+
self.num_labels = num_labels
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class MacronizerModel(PreTrainedModel):
|
| 50 |
+
config_class = MacronizerConfig
|
| 51 |
+
base_model_prefix = "macronizer"
|
| 52 |
+
main_input_name = "plane1_ids"
|
| 53 |
+
|
| 54 |
+
def __init__(self, config):
|
| 55 |
+
super().__init__(config)
|
| 56 |
+
h = config.hidden_size
|
| 57 |
+
|
| 58 |
+
self.plane1_embed = nn.Embedding(config.plane1_vocab_size, h, padding_idx=config.pad_token_id)
|
| 59 |
+
self.plane2_embed = nn.Embedding(config.plane2_vocab_size, h, padding_idx=config.pad_token_id)
|
| 60 |
+
self.position_embed = nn.Embedding(config.max_position_embeddings, h)
|
| 61 |
+
|
| 62 |
+
self.embed_layernorm = nn.LayerNorm(h)
|
| 63 |
+
self.embed_dropout = nn.Dropout(config.dropout)
|
| 64 |
+
|
| 65 |
+
encoder_layer = nn.TransformerEncoderLayer(
|
| 66 |
+
d_model=h,
|
| 67 |
+
nhead=config.num_attention_heads,
|
| 68 |
+
dim_feedforward=config.intermediate_size,
|
| 69 |
+
dropout=config.dropout,
|
| 70 |
+
activation="gelu",
|
| 71 |
+
batch_first=True,
|
| 72 |
+
norm_first=True,
|
| 73 |
+
)
|
| 74 |
+
self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=config.num_hidden_layers)
|
| 75 |
+
|
| 76 |
+
self.classifier_dropout = nn.Dropout(config.dropout)
|
| 77 |
+
self.classifier = nn.Linear(h, config.num_labels)
|
| 78 |
+
|
| 79 |
+
self.post_init()
|
| 80 |
+
|
| 81 |
+
def _init_weights(self, module):
|
| 82 |
+
if isinstance(module, nn.Linear):
|
| 83 |
+
module.weight.data.normal_(mean=0.0, std=0.02)
|
| 84 |
+
if module.bias is not None:
|
| 85 |
+
module.bias.data.zero_()
|
| 86 |
+
elif isinstance(module, nn.Embedding):
|
| 87 |
+
module.weight.data.normal_(mean=0.0, std=0.02)
|
| 88 |
+
if module.padding_idx is not None:
|
| 89 |
+
module.weight.data[module.padding_idx].zero_()
|
| 90 |
+
elif isinstance(module, nn.LayerNorm):
|
| 91 |
+
module.bias.data.zero_()
|
| 92 |
+
module.weight.data.fill_(1.0)
|
| 93 |
+
|
| 94 |
+
def forward(
|
| 95 |
+
self,
|
| 96 |
+
plane1_ids,
|
| 97 |
+
plane2_ids,
|
| 98 |
+
attention_mask=None,
|
| 99 |
+
labels=None,
|
| 100 |
+
**kwargs,
|
| 101 |
+
):
|
| 102 |
+
bsz, seq_len = plane1_ids.shape
|
| 103 |
+
device = plane1_ids.device
|
| 104 |
+
|
| 105 |
+
positions = torch.arange(seq_len, device=device).unsqueeze(0).expand(bsz, seq_len)
|
| 106 |
+
hidden = self.plane1_embed(plane1_ids) + self.plane2_embed(plane2_ids) + self.position_embed(positions)
|
| 107 |
+
hidden = self.embed_dropout(self.embed_layernorm(hidden))
|
| 108 |
+
|
| 109 |
+
key_padding_mask = None
|
| 110 |
+
if attention_mask is not None:
|
| 111 |
+
key_padding_mask = attention_mask == 0 # True where padded, per nn.Transformer convention
|
| 112 |
+
|
| 113 |
+
hidden = self.encoder(hidden, src_key_padding_mask=key_padding_mask)
|
| 114 |
+
logits = self.classifier(self.classifier_dropout(hidden))
|
| 115 |
+
|
| 116 |
+
loss = None
|
| 117 |
+
if labels is not None:
|
| 118 |
+
loss_fct = nn.CrossEntropyLoss(ignore_index=LABEL_IGNORE_INDEX)
|
| 119 |
+
loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
|
| 120 |
+
|
| 121 |
+
return TokenClassifierOutput(loss=loss, logits=logits, hidden_states=None, attentions=None)
|
| 122 |
+
|
| 123 |
+
def num_parameters_readable(self):
|
| 124 |
+
n = sum(p.numel() for p in self.parameters())
|
| 125 |
+
return f"{n / 1e6:.2f}M"
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
if __name__ == "__main__":
|
| 129 |
+
cfg = MacronizerConfig(plane2_vocab_size=20)
|
| 130 |
+
model = MacronizerModel(cfg)
|
| 131 |
+
print(model.num_parameters_readable(), "parameters")
|
| 132 |
+
|
| 133 |
+
plane1 = torch.randint(0, cfg.plane1_vocab_size, (2, 10))
|
| 134 |
+
plane2 = torch.randint(0, cfg.plane2_vocab_size, (2, 10))
|
| 135 |
+
labels = torch.randint(0, 3, (2, 10))
|
| 136 |
+
labels[:, :3] = LABEL_IGNORE_INDEX
|
| 137 |
+
|
| 138 |
+
out = model(plane1_ids=plane1, plane2_ids=plane2, labels=labels)
|
| 139 |
+
print("loss:", out.loss.item())
|
| 140 |
+
print("logits shape:", out.logits.shape)
|
norma.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Norma Syllabarum Graecarum loading and scoring, for the HF dataset layout
|
| 3 |
+
(https://huggingface.co/datasets/Urdatorn/norma: data/test.jsonl and
|
| 4 |
+
data/validation.jsonl, one {"text", "source", "task"} record per line).
|
| 5 |
+
|
| 6 |
+
Scored positions are the gold-marked (^ or _) dichrona in open syllables,
|
| 7 |
+
as in the original eval_norma.py:
|
| 8 |
+
|
| 9 |
+
- test: every source ships a "macronize" and a "syllabify" version of each
|
| 10 |
+
line, in the same order. The syllabify line gives syllable openness, which
|
| 11 |
+
is carried over to the macronize line with a difflib alignment.
|
| 12 |
+
- validation: there are no syllabify lines, so every gold mark is scored.
|
| 13 |
+
|
| 14 |
+
The bracket-tiling, open-syllable and alignment helpers are taken from
|
| 15 |
+
grc-macronizer/macron_model/eval_norma.py (commit 456c970).
|
| 16 |
+
|
| 17 |
+
Metrics (`metrics()`), following Table 1 of the paper:
|
| 18 |
+
- per label (long "_", short "^"): accuracy = recall = correct / gold
|
| 19 |
+
positions with that label; precision = correct / predictions of that
|
| 20 |
+
label; F1; coverage = share of those gold positions that got any mark.
|
| 21 |
+
- mixed (micro-averaged): accuracy = recall = correct / all positions,
|
| 22 |
+
with an unmarked position counted as wrong; precision = correct / marked
|
| 23 |
+
positions; F1 is their harmonic mean; coverage = marked / all positions.
|
| 24 |
+
This reproduces every mixed row of Table 1 from its per-label counts.
|
| 25 |
+
- default_short_accuracy: like mixed accuracy, but an unmarked position
|
| 26 |
+
counts as a "short" guess (the model cards' headline number).
|
| 27 |
+
'''
|
| 28 |
+
|
| 29 |
+
import collections
|
| 30 |
+
import difflib
|
| 31 |
+
import json
|
| 32 |
+
import re
|
| 33 |
+
import unicodedata
|
| 34 |
+
from dataclasses import dataclass
|
| 35 |
+
from typing import Dict, List, Optional
|
| 36 |
+
|
| 37 |
+
from grc_utils import vowel
|
| 38 |
+
from huggingface_hub import hf_hub_download
|
| 39 |
+
|
| 40 |
+
DEFAULT_REPO = "Urdatorn/norma"
|
| 41 |
+
MARK_CHARS = "^_"
|
| 42 |
+
SHORT, LONG = "^", "_"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def nfc(s):
|
| 46 |
+
return unicodedata.normalize("NFC", s)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# ---------------------------------------------------------------------------
|
| 50 |
+
# Helpers from eval_norma.py
|
| 51 |
+
# ---------------------------------------------------------------------------
|
| 52 |
+
|
| 53 |
+
_BETWEEN_BRACKETS_RE = re.compile(r'([\]\}])([^\[\]\{\}]+)([\[\{])')
|
| 54 |
+
_TRAILING_RE = re.compile(r'([\]\}])([^\[\]\{\}]+)$')
|
| 55 |
+
_LEADING_RE = re.compile(r'^([^\[\{]+)([\[\{])')
|
| 56 |
+
_BRACKET_RE = re.compile(r'([\[\{])([^\[\]\{\}]*)([\]\}])')
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _move_text_into_brackets(line):
|
| 60 |
+
prev = None
|
| 61 |
+
while prev != line:
|
| 62 |
+
prev = line
|
| 63 |
+
line = _BETWEEN_BRACKETS_RE.sub(
|
| 64 |
+
lambda m: m.group(1)[:-1] + m.group(2) + m.group(1)[-1] + m.group(3), line)
|
| 65 |
+
m = _TRAILING_RE.search(line)
|
| 66 |
+
if m:
|
| 67 |
+
line = line[: m.start()] + m.group(1)[:-1] + m.group(2) + m.group(1)[-1]
|
| 68 |
+
m = _LEADING_RE.match(line)
|
| 69 |
+
if m:
|
| 70 |
+
line = m.group(2) + m.group(1) + line[m.end():]
|
| 71 |
+
return line
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _syllable_is_open(content):
|
| 75 |
+
core = content
|
| 76 |
+
while core and not core[-1].isalpha():
|
| 77 |
+
core = core[:-1]
|
| 78 |
+
return bool(core) and vowel(core[-1])
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def parse_syllabify_line(line):
|
| 82 |
+
chars, opens = [], []
|
| 83 |
+
for m in _BRACKET_RE.finditer(_move_text_into_brackets(line)):
|
| 84 |
+
content = m.group(2)
|
| 85 |
+
is_open = _syllable_is_open(content)
|
| 86 |
+
chars.extend(content)
|
| 87 |
+
opens.extend([is_open] * len(content))
|
| 88 |
+
return "".join(chars), opens
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def parse_marked_line(line):
|
| 92 |
+
plain, marks = [], []
|
| 93 |
+
i, n = 0, len(line)
|
| 94 |
+
while i < n:
|
| 95 |
+
ch = line[i]
|
| 96 |
+
if ch in MARK_CHARS:
|
| 97 |
+
i += 1
|
| 98 |
+
continue
|
| 99 |
+
nxt = line[i + 1] if i + 1 < n else ""
|
| 100 |
+
if nxt and nxt in MARK_CHARS:
|
| 101 |
+
plain.append(ch)
|
| 102 |
+
marks.append(nxt)
|
| 103 |
+
i += 2
|
| 104 |
+
else:
|
| 105 |
+
plain.append(ch)
|
| 106 |
+
marks.append(None)
|
| 107 |
+
i += 1
|
| 108 |
+
return "".join(plain), marks
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _align_flags(src_text, src_flags, dst_text):
|
| 112 |
+
out = [None] * len(dst_text)
|
| 113 |
+
sm = difflib.SequenceMatcher(None, src_text, dst_text, autojunk=False)
|
| 114 |
+
for tag, i1, i2, j1, j2 in sm.get_opcodes():
|
| 115 |
+
if tag == "equal":
|
| 116 |
+
for k in range(i2 - i1):
|
| 117 |
+
out[j1 + k] = src_flags[i1 + k]
|
| 118 |
+
return out
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _map_output_onto_reference(output_plain, ref_plain):
|
| 122 |
+
ref_to_out = [None] * len(ref_plain)
|
| 123 |
+
sm = difflib.SequenceMatcher(None, output_plain.lower(), ref_plain.lower(), autojunk=False)
|
| 124 |
+
for tag, i1, i2, j1, j2 in sm.get_opcodes():
|
| 125 |
+
if tag == "equal":
|
| 126 |
+
for k in range(i2 - i1):
|
| 127 |
+
ref_to_out[j1 + k] = i1 + k
|
| 128 |
+
return ref_to_out
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ---------------------------------------------------------------------------
|
| 132 |
+
# Loading
|
| 133 |
+
# ---------------------------------------------------------------------------
|
| 134 |
+
|
| 135 |
+
@dataclass
|
| 136 |
+
class LineRecord:
|
| 137 |
+
source: str
|
| 138 |
+
line_idx: int # index within this source's macronize lines
|
| 139 |
+
plain: str # input text, marks stripped
|
| 140 |
+
gold_marks: List[Optional[str]]
|
| 141 |
+
scored: List[bool] # position is part of the evaluation set
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def load_split(split, repo_id=DEFAULT_REPO, revision=None, path=None):
|
| 145 |
+
if path is None:
|
| 146 |
+
path = hf_hub_download(repo_id, f"data/{split}.jsonl", repo_type="dataset",
|
| 147 |
+
revision=revision)
|
| 148 |
+
mac, syl = collections.defaultdict(list), collections.defaultdict(list)
|
| 149 |
+
with open(path, encoding="utf-8") as fh:
|
| 150 |
+
for line in fh:
|
| 151 |
+
r = json.loads(line)
|
| 152 |
+
(mac if r["task"] == "macronize" else syl)[r["source"]].append(nfc(r["text"]))
|
| 153 |
+
|
| 154 |
+
records = []
|
| 155 |
+
for source, lines in mac.items():
|
| 156 |
+
slines = syl.get(source)
|
| 157 |
+
if slines is not None and len(slines) != len(lines):
|
| 158 |
+
raise ValueError(f"{split}/{source}: {len(lines)} macronize vs {len(slines)} syllabify lines")
|
| 159 |
+
for k, mline in enumerate(lines):
|
| 160 |
+
plain, marks = parse_marked_line(mline)
|
| 161 |
+
if slines is not None:
|
| 162 |
+
sp_text, sp_opens = parse_syllabify_line(slines[k])
|
| 163 |
+
opens = _align_flags(sp_text, sp_opens, plain)
|
| 164 |
+
else:
|
| 165 |
+
opens = [True] * len(plain)
|
| 166 |
+
scored = [bool(o) and m is not None for o, m in zip(opens, marks)]
|
| 167 |
+
records.append(LineRecord(source, k, plain, marks, scored))
|
| 168 |
+
return records
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
# ---------------------------------------------------------------------------
|
| 172 |
+
# Scoring
|
| 173 |
+
# ---------------------------------------------------------------------------
|
| 174 |
+
|
| 175 |
+
def _word_at(text, j):
|
| 176 |
+
s = text.rfind(" ", 0, j) + 1
|
| 177 |
+
e = text.find(" ", j)
|
| 178 |
+
return text[s: e if e != -1 else len(text)]
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def score(records, outputs):
|
| 182 |
+
'''Returns one dict per scored position: source, line, char, word, gold, pred.'''
|
| 183 |
+
assert len(records) == len(outputs)
|
| 184 |
+
positions = []
|
| 185 |
+
for rec, out in zip(records, outputs):
|
| 186 |
+
out_plain, out_marks = parse_marked_line(nfc(out))
|
| 187 |
+
ref_to_out = _map_output_onto_reference(out_plain, rec.plain)
|
| 188 |
+
for j, is_scored in enumerate(rec.scored):
|
| 189 |
+
if not is_scored:
|
| 190 |
+
continue
|
| 191 |
+
oi = ref_to_out[j]
|
| 192 |
+
positions.append(dict(
|
| 193 |
+
source=rec.source, line=rec.line_idx, char=j, word=_word_at(rec.plain, j),
|
| 194 |
+
gold=rec.gold_marks[j], pred=out_marks[oi] if oi is not None else None,
|
| 195 |
+
))
|
| 196 |
+
return positions
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _label_stats(positions, label):
|
| 200 |
+
gold = [p for p in positions if p["gold"] == label]
|
| 201 |
+
n_pred = sum(p["pred"] == label for p in positions)
|
| 202 |
+
tp = sum(p["pred"] == label for p in gold)
|
| 203 |
+
r = tp / len(gold) if gold else 0.0
|
| 204 |
+
pr = tp / n_pred if n_pred else 0.0
|
| 205 |
+
f1 = 2 * pr * r / (pr + r) if pr + r else 0.0
|
| 206 |
+
cov = sum(p["pred"] is not None for p in gold) / len(gold) if gold else 0.0
|
| 207 |
+
return dict(n=len(gold), accuracy=r, precision=pr, recall=r, f1=f1, coverage=cov)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def metrics(positions, by_source=True):
|
| 211 |
+
n = len(positions)
|
| 212 |
+
out = {"n": n}
|
| 213 |
+
if not n:
|
| 214 |
+
return out
|
| 215 |
+
lab = {"long": _label_stats(positions, LONG), "short": _label_stats(positions, SHORT)}
|
| 216 |
+
out.update(lab)
|
| 217 |
+
correct = sum(p["pred"] == p["gold"] for p in positions)
|
| 218 |
+
n_pred = sum(p["pred"] is not None for p in positions)
|
| 219 |
+
mp, mr = (correct / n_pred if n_pred else 0.0), correct / n
|
| 220 |
+
out["mixed"] = dict( # micro-averaged over the two labels, as in Table 1
|
| 221 |
+
n=n, accuracy=mr, precision=mp, recall=mr,
|
| 222 |
+
f1=2 * mp * mr / (mp + mr) if mp + mr else 0.0,
|
| 223 |
+
coverage=n_pred / n,
|
| 224 |
+
)
|
| 225 |
+
out["default_short_accuracy"] = sum((p["pred"] or SHORT) == p["gold"] for p in positions) / n
|
| 226 |
+
out["constant_short_accuracy"] = sum(p["gold"] == SHORT for p in positions) / n
|
| 227 |
+
if by_source:
|
| 228 |
+
per = collections.defaultdict(list)
|
| 229 |
+
for p in positions:
|
| 230 |
+
per[p["source"]].append(p)
|
| 231 |
+
out["per_source"] = {s: metrics(ps, by_source=False) for s, ps in sorted(per.items())}
|
| 232 |
+
return out
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def format_table(m):
|
| 236 |
+
rows = ["label n Acc P R F1 Cov"]
|
| 237 |
+
for k in ("long", "short", "mixed"):
|
| 238 |
+
s = m[k]
|
| 239 |
+
rows.append(f"{k:<8} {s['n']:<6} {100*s['accuracy']:6.1f} {100*s['precision']:6.1f} "
|
| 240 |
+
f"{100*s['recall']:6.1f} {100*s['f1']:6.1f} {100*s['coverage']:6.1f}")
|
| 241 |
+
rows.append(f"defaults-to-short accuracy: {100*m['default_short_accuracy']:.2f} "
|
| 242 |
+
f"constant-short: {100*m['constant_short_accuracy']:.2f}")
|
| 243 |
+
if "per_source" in m:
|
| 244 |
+
rows.append("source n mixed-Acc mixed-F1 Cov")
|
| 245 |
+
for s, ms in m["per_source"].items():
|
| 246 |
+
rows.append(f" {s:<14} {ms['n']:<5} {100*ms['mixed']['accuracy']:8.1f} "
|
| 247 |
+
f"{100*ms['mixed']['f1']:8.1f} {100*ms['mixed']['coverage']:5.1f}")
|
| 248 |
+
return "\n".join(rows)
|
predict.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Batched inference for a MacronizerModel. Same behaviour as the original
|
| 3 |
+
grc-macronizer/macron_model/predict.py (inputs chunked at
|
| 4 |
+
max_position_embeddings, marks only emitted at genuine dichrona), but lines
|
| 5 |
+
are run in padded batches so that scoring Norma during training is cheap.
|
| 6 |
+
|
| 7 |
+
from predict import MacronPredictor
|
| 8 |
+
p = MacronPredictor("Ericu950/oga-macronizer-char") # or a local checkpoint dir
|
| 9 |
+
p.macronize("ανθρωπος ανηρ")
|
| 10 |
+
'''
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from huggingface_hub import hf_hub_download
|
| 19 |
+
|
| 20 |
+
from model import MacronizerModel
|
| 21 |
+
from tokenizer import DiacriticVocab, decode, encode_plain, MACRON_SHORT, MACRON_LONG
|
| 22 |
+
|
| 23 |
+
PAD_ID = 0
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def load_vocab(model_dir):
|
| 27 |
+
if os.path.isdir(model_dir):
|
| 28 |
+
path = os.path.join(model_dir, "diacritic_vocab.json")
|
| 29 |
+
if not os.path.exists(path):
|
| 30 |
+
path = os.path.join(os.path.dirname(os.path.normpath(model_dir)), "diacritic_vocab.json")
|
| 31 |
+
else:
|
| 32 |
+
path = hf_hub_download(repo_id=model_dir, filename="diacritic_vocab.json")
|
| 33 |
+
with open(path, encoding="utf-8") as f:
|
| 34 |
+
return DiacriticVocab.from_dict(json.load(f))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class MacronPredictor:
|
| 38 |
+
def __init__(self, model, vocab=None, device=None):
|
| 39 |
+
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 40 |
+
if isinstance(model, MacronizerModel):
|
| 41 |
+
self.model, self.vocab = model, vocab
|
| 42 |
+
else:
|
| 43 |
+
self.model = MacronizerModel.from_pretrained(model).to(self.device)
|
| 44 |
+
self.vocab = load_vocab(model)
|
| 45 |
+
self.max_len = self.model.config.max_position_embeddings
|
| 46 |
+
|
| 47 |
+
@torch.no_grad()
|
| 48 |
+
def macronize_lines(self, lines, batch_size=256):
|
| 49 |
+
was_training = self.model.training
|
| 50 |
+
self.model.eval()
|
| 51 |
+
encs = [encode_plain(l, self.vocab, fit=False) if l.strip() else None for l in lines]
|
| 52 |
+
chunks = [] # (line index, start, plane1, plane2)
|
| 53 |
+
for i, e in enumerate(encs):
|
| 54 |
+
if e is None or not e["plane1"]:
|
| 55 |
+
continue
|
| 56 |
+
for s in range(0, len(e["plane1"]), self.max_len):
|
| 57 |
+
chunks.append((i, s, e["plane1"][s:s + self.max_len], e["plane2"][s:s + self.max_len]))
|
| 58 |
+
preds = {i: [0] * len(e["plane1"]) for i, e in enumerate(encs) if e is not None}
|
| 59 |
+
for b in range(0, len(chunks), batch_size):
|
| 60 |
+
batch = chunks[b:b + batch_size]
|
| 61 |
+
L = max(len(c[2]) for c in batch)
|
| 62 |
+
p1 = torch.full((len(batch), L), PAD_ID, dtype=torch.long)
|
| 63 |
+
p2 = torch.full((len(batch), L), PAD_ID, dtype=torch.long)
|
| 64 |
+
am = torch.zeros((len(batch), L), dtype=torch.long)
|
| 65 |
+
for k, (_, _, a, c) in enumerate(batch):
|
| 66 |
+
p1[k, :len(a)] = torch.tensor(a)
|
| 67 |
+
p2[k, :len(c)] = torch.tensor(c)
|
| 68 |
+
am[k, :len(a)] = 1
|
| 69 |
+
# a single unpadded chunk is run without a mask, exactly as the original predict.py
|
| 70 |
+
mask = None if len(batch) == 1 else am.to(self.device)
|
| 71 |
+
logits = self.model(plane1_ids=p1.to(self.device), plane2_ids=p2.to(self.device),
|
| 72 |
+
attention_mask=mask).logits
|
| 73 |
+
arg = logits.argmax(-1).cpu().tolist()
|
| 74 |
+
for k, (i, s, a, _) in enumerate(batch):
|
| 75 |
+
preds[i][s:s + len(a)] = arg[k][:len(a)]
|
| 76 |
+
if was_training:
|
| 77 |
+
self.model.train()
|
| 78 |
+
out = []
|
| 79 |
+
for i, (line, e) in enumerate(zip(lines, encs)):
|
| 80 |
+
if e is None or not e["plane1"]:
|
| 81 |
+
out.append(line)
|
| 82 |
+
continue
|
| 83 |
+
labels = [lab if elig and lab in (MACRON_SHORT, MACRON_LONG) else 0
|
| 84 |
+
for lab, elig in zip(preds[i], e["dichrona_mask"])]
|
| 85 |
+
out.append(decode(e["chars"], labels))
|
| 86 |
+
return out
|
| 87 |
+
|
| 88 |
+
def macronize(self, text):
|
| 89 |
+
return "\n".join(self.macronize_lines(text.split("\n")))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
if __name__ == "__main__":
|
| 93 |
+
ap = argparse.ArgumentParser()
|
| 94 |
+
ap.add_argument("--model_dir", required=True)
|
| 95 |
+
ap.add_argument("--text")
|
| 96 |
+
a = ap.parse_args()
|
| 97 |
+
p = MacronPredictor(a.model_dir)
|
| 98 |
+
print(p.macronize(a.text if a.text else sys.stdin.read()))
|
prepare_data.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Encode the silver corpus once into flat numpy arrays, so that every training
|
| 3 |
+
run and Optuna trial reads the same cached tensors.
|
| 4 |
+
|
| 5 |
+
python prepare_data.py --out cache/oga-no-norma
|
| 6 |
+
|
| 7 |
+
Steps, matching the original train.py:
|
| 8 |
+
1. Read the `macronized` column of the HF dataset (default
|
| 9 |
+
Urdatorn/oga-macronized-no-norma).
|
| 10 |
+
2. Fit the diacritic vocabulary on the first --vocab_fit_lines lines.
|
| 11 |
+
3. Shuffle the lines with --data_seed and hold out --val_fraction for
|
| 12 |
+
validation. The split is fixed independently of the training seed, so
|
| 13 |
+
every trial and every seed sees the same split.
|
| 14 |
+
4. Encode each line and cut it into chunks of at most --max_len characters.
|
| 15 |
+
Lines and chunks with no label are dropped.
|
| 16 |
+
|
| 17 |
+
Output files in --out:
|
| 18 |
+
- {train,val}.npz: plane1 (uint8), plane2 (uint8), labels (int8, -100 =
|
| 19 |
+
ignored) concatenated, plus offsets (int64, one more than the number of
|
| 20 |
+
examples).
|
| 21 |
+
- diacritic_vocab.json
|
| 22 |
+
- meta.json
|
| 23 |
+
'''
|
| 24 |
+
|
| 25 |
+
import argparse
|
| 26 |
+
import glob
|
| 27 |
+
import json
|
| 28 |
+
import os
|
| 29 |
+
import random
|
| 30 |
+
import time
|
| 31 |
+
from multiprocessing import Pool
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
import pyarrow.parquet as pq
|
| 35 |
+
from huggingface_hub import snapshot_download
|
| 36 |
+
|
| 37 |
+
from tokenizer import DiacriticVocab, encode_macronized, LABEL_IGNORE_INDEX
|
| 38 |
+
|
| 39 |
+
_vocab = _max_len = None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _init(vocab, max_len):
|
| 43 |
+
global _vocab, _max_len
|
| 44 |
+
_vocab, _max_len = vocab, max_len
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _encode(line):
|
| 48 |
+
enc = encode_macronized(line, _vocab, fit=False)
|
| 49 |
+
out = []
|
| 50 |
+
if not enc["plane1"] or all(l == LABEL_IGNORE_INDEX for l in enc["labels"]):
|
| 51 |
+
return out
|
| 52 |
+
for s in range(0, len(enc["plane1"]), _max_len):
|
| 53 |
+
lab = enc["labels"][s:s + _max_len]
|
| 54 |
+
if any(l != LABEL_IGNORE_INDEX for l in lab):
|
| 55 |
+
out.append((np.asarray(enc["plane1"][s:s + _max_len], np.uint8),
|
| 56 |
+
np.asarray(enc["plane2"][s:s + _max_len], np.uint8),
|
| 57 |
+
np.asarray(lab, np.int8)))
|
| 58 |
+
return out
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def encode_split(lines, vocab, max_len, workers):
|
| 62 |
+
p1, p2, lab, lens = [], [], [], []
|
| 63 |
+
with Pool(workers, initializer=_init, initargs=(vocab, max_len)) as pool:
|
| 64 |
+
for i, chunks in enumerate(pool.imap(_encode, lines, chunksize=2000)):
|
| 65 |
+
for a, b, c in chunks:
|
| 66 |
+
p1.append(a); p2.append(b); lab.append(c); lens.append(len(a))
|
| 67 |
+
if (i + 1) % 200_000 == 0:
|
| 68 |
+
print(f" encoded {i+1:,}/{len(lines):,} lines -> {len(lens):,} examples", flush=True)
|
| 69 |
+
offsets = np.zeros(len(lens) + 1, np.int64)
|
| 70 |
+
np.cumsum(lens, out=offsets[1:])
|
| 71 |
+
labels = np.concatenate(lab)
|
| 72 |
+
return dict(plane1=np.concatenate(p1), plane2=np.concatenate(p2), labels=labels,
|
| 73 |
+
offsets=offsets), labels
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def main():
|
| 77 |
+
ap = argparse.ArgumentParser()
|
| 78 |
+
ap.add_argument("--dataset", default="Urdatorn/oga-macronized-no-norma")
|
| 79 |
+
ap.add_argument("--revision", default=None)
|
| 80 |
+
ap.add_argument("--out", required=True)
|
| 81 |
+
ap.add_argument("--val_fraction", type=float, default=0.10)
|
| 82 |
+
ap.add_argument("--data_seed", type=int, default=0)
|
| 83 |
+
ap.add_argument("--max_len", type=int, default=384)
|
| 84 |
+
ap.add_argument("--vocab_fit_lines", type=int, default=200_000)
|
| 85 |
+
ap.add_argument("--max_lines", type=int, default=None, help="for quick tests only")
|
| 86 |
+
ap.add_argument("--workers", type=int, default=os.cpu_count())
|
| 87 |
+
a = ap.parse_args()
|
| 88 |
+
t0 = time.time()
|
| 89 |
+
os.makedirs(a.out, exist_ok=True)
|
| 90 |
+
|
| 91 |
+
from huggingface_hub import HfApi
|
| 92 |
+
a.revision = HfApi().dataset_info(a.dataset, revision=a.revision).sha # pin and record the commit
|
| 93 |
+
print(f"dataset {a.dataset} @ {a.revision}", flush=True)
|
| 94 |
+
local = snapshot_download(a.dataset, repo_type="dataset", revision=a.revision,
|
| 95 |
+
allow_patterns=["data/*.parquet"])
|
| 96 |
+
files = sorted(glob.glob(os.path.join(local, "data", "*.parquet")))
|
| 97 |
+
lines = []
|
| 98 |
+
for f in files:
|
| 99 |
+
lines.extend(s for s in pq.read_table(f, columns=["macronized"]).column(0).to_pylist()
|
| 100 |
+
if s and s.strip())
|
| 101 |
+
if a.max_lines:
|
| 102 |
+
lines = lines[: a.max_lines]
|
| 103 |
+
print(f"{len(lines):,} non-empty lines from {a.dataset} ({len(files)} files)", flush=True)
|
| 104 |
+
|
| 105 |
+
vocab = DiacriticVocab()
|
| 106 |
+
for line in lines[: a.vocab_fit_lines]:
|
| 107 |
+
encode_macronized(line, vocab, fit=True)
|
| 108 |
+
vocab.freeze()
|
| 109 |
+
print(f"diacritic vocab: {len(vocab)} entries", flush=True)
|
| 110 |
+
with open(os.path.join(a.out, "diacritic_vocab.json"), "w", encoding="utf-8") as f:
|
| 111 |
+
json.dump(vocab.to_dict(), f, ensure_ascii=False, indent=2)
|
| 112 |
+
|
| 113 |
+
idx = list(range(len(lines)))
|
| 114 |
+
random.Random(a.data_seed).shuffle(idx)
|
| 115 |
+
n_val = max(1, int(len(idx) * a.val_fraction))
|
| 116 |
+
splits = {"val": [lines[i] for i in sorted(idx[:n_val])],
|
| 117 |
+
"train": [lines[i] for i in sorted(idx[n_val:])]}
|
| 118 |
+
del lines
|
| 119 |
+
|
| 120 |
+
meta = dict(vars(a), n_vocab=len(vocab))
|
| 121 |
+
for name, sl in splits.items():
|
| 122 |
+
print(f"encoding {name}: {len(sl):,} lines", flush=True)
|
| 123 |
+
arrays, labels = encode_split(sl, vocab, a.max_len, a.workers)
|
| 124 |
+
np.savez(os.path.join(a.out, f"{name}.npz"), **arrays)
|
| 125 |
+
meta[name] = dict(lines=len(sl), examples=len(arrays["offsets"]) - 1,
|
| 126 |
+
chars=int(len(arrays["plane1"])),
|
| 127 |
+
labels={k: int((labels == v).sum()) for k, v in
|
| 128 |
+
(("none", 0), ("short", 1), ("long", 2))})
|
| 129 |
+
print(f" {name}: {json.dumps(meta[name])}", flush=True)
|
| 130 |
+
meta["seconds"] = round(time.time() - t0, 1)
|
| 131 |
+
with open(os.path.join(a.out, "meta.json"), "w") as f:
|
| 132 |
+
json.dump(meta, f, indent=2)
|
| 133 |
+
print(f"done in {meta['seconds']}s -> {a.out}", flush=True)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.6
|
| 2 |
+
transformers>=4.49,<5
|
| 3 |
+
safetensors
|
| 4 |
+
optuna>=4.5,<5
|
| 5 |
+
pandas
|
| 6 |
+
numpy
|
| 7 |
+
pyarrow
|
| 8 |
+
huggingface_hub>=0.30
|
| 9 |
+
grc_utils==0.2.2
|
slurm/smoke.slurm
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
#SBATCH --job-name=macron-smoke
|
| 3 |
+
#SBATCH --account=naiss2026-3-353-gpu
|
| 4 |
+
#SBATCH --partition=gpu
|
| 5 |
+
#SBATCH --nodes=1
|
| 6 |
+
#SBATCH --ntasks=1
|
| 7 |
+
#SBATCH --cpus-per-task=32
|
| 8 |
+
#SBATCH --gpus=1
|
| 9 |
+
#SBATCH --mem=128G
|
| 10 |
+
#SBATCH --time=02:00:00
|
| 11 |
+
#SBATCH --output=logs/%x-%j.out
|
| 12 |
+
#SBATCH --error=logs/%x-%j.out
|
| 13 |
+
|
| 14 |
+
# Smoke test:
|
| 15 |
+
# 1. build/check the venv;
|
| 16 |
+
# 2. score the published checkpoints on Norma (test + validation) to check
|
| 17 |
+
# the scorer against Table 1 of the paper;
|
| 18 |
+
# 3. encode the decontaminated silver corpus into cache/oga-no-norma;
|
| 19 |
+
# 4. 400 training steps with the paper's settings, to measure throughput;
|
| 20 |
+
# 5. a two-trial Optuna study with tiny trials, to test the HPO pipeline.
|
| 21 |
+
|
| 22 |
+
set -Eeuo pipefail
|
| 23 |
+
trap 'status=$?; printf "[%s] ERROR line=%s command=%q status=%s\n" "$(date --iso-8601=seconds)" "$LINENO" "$BASH_COMMAND" "$status"; exit "$status"' ERR
|
| 24 |
+
|
| 25 |
+
repo=/nobackup/proj/flash/dionysus/personal/cleland/oga-macronizer-char-code
|
| 26 |
+
cd "$repo"
|
| 27 |
+
mkdir -p logs runs results cache
|
| 28 |
+
stamp() { printf '[%s] %s\n' "$(date --iso-8601=seconds)" "$*"; }
|
| 29 |
+
|
| 30 |
+
stamp "job_start id=${SLURM_JOB_ID} host=$(hostname)"
|
| 31 |
+
module purge
|
| 32 |
+
module load GPU/Python/3.13.5-bare-gcc-2025b-eb
|
| 33 |
+
nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv
|
| 34 |
+
|
| 35 |
+
export PYTHONUNBUFFERED=1
|
| 36 |
+
export PIP_CACHE_DIR="$repo/.cache/pip"
|
| 37 |
+
export HF_HUB_CACHE="$repo/.cache/hf"
|
| 38 |
+
export HF_HUB_DISABLE_PROGRESS_BARS=1
|
| 39 |
+
venv="$repo/.venv"
|
| 40 |
+
if [[ ! -x "$venv/bin/python" ]]; then
|
| 41 |
+
stamp "creating venv $venv"
|
| 42 |
+
python -m venv "$venv"
|
| 43 |
+
"$venv/bin/python" -m pip install -q --upgrade pip
|
| 44 |
+
"$venv/bin/python" -m pip install -q -r requirements.txt
|
| 45 |
+
fi
|
| 46 |
+
py="$venv/bin/python"
|
| 47 |
+
"$py" - <<'PY'
|
| 48 |
+
import torch, transformers, optuna, pyarrow, numpy, grc_utils, importlib.metadata as md
|
| 49 |
+
print(f"deps torch={torch.__version__} cuda={torch.cuda.is_available()} transformers={transformers.__version__} "
|
| 50 |
+
f"optuna={optuna.__version__} pyarrow={pyarrow.__version__} numpy={numpy.__version__} "
|
| 51 |
+
f"grc_utils={md.version('grc_utils')}", flush=True)
|
| 52 |
+
assert torch.cuda.is_available()
|
| 53 |
+
PY
|
| 54 |
+
"$py" -m pip freeze > "logs/pip-freeze-${SLURM_JOB_ID}.txt"
|
| 55 |
+
|
| 56 |
+
stamp "STEP 2: published checkpoints on Norma"
|
| 57 |
+
"$py" evaluate.py --splits test validation --out results/published \
|
| 58 |
+
--models Ericu950/oga-macronizer-char Ericu950/oga-macronizer-char-seed13 Ericu950/oga-macronizer-char-seed17
|
| 59 |
+
stamp "paper Table 1 (transformer): long acc 64.7 P 85.0 F1 73.5 | short acc 97.6 P 93.4 F1 95.4 | mixed acc 92.0 P 92.3 F1 92.2 cov 99.7 (n=1916)"
|
| 60 |
+
|
| 61 |
+
stamp "STEP 3: encode silver data"
|
| 62 |
+
if [[ ! -f cache/oga-no-norma/meta.json ]]; then
|
| 63 |
+
"$py" prepare_data.py --out cache/oga-no-norma --workers "$SLURM_CPUS_PER_TASK"
|
| 64 |
+
else
|
| 65 |
+
stamp "cache exists, skipping"
|
| 66 |
+
fi
|
| 67 |
+
cat cache/oga-no-norma/meta.json
|
| 68 |
+
|
| 69 |
+
stamp "STEP 4: throughput run (400 steps, paper settings, seed 1)"
|
| 70 |
+
"$py" train.py --cache cache/oga-no-norma --output_dir runs/smoke-train --seed 1 \
|
| 71 |
+
--max_steps 400 --eval_every_steps 200 --log_every_steps 25
|
| 72 |
+
|
| 73 |
+
stamp "STEP 5: Optuna pipeline (2 tiny trials)"
|
| 74 |
+
rm -rf runs/smoke-hpo
|
| 75 |
+
"$py" hpo.py init --study_dir runs/smoke-hpo \
|
| 76 |
+
--train_args "--seed 1 --max_steps 60 --schedule_steps 60 --eval_every_steps 30 --log_every_steps 10"
|
| 77 |
+
"$py" hpo.py worker --study_dir runs/smoke-hpo --cache cache/oga-no-norma --n_trials 2 --worker_id 0
|
| 78 |
+
"$py" hpo.py report --study_dir runs/smoke-hpo
|
| 79 |
+
|
| 80 |
+
stamp "job_complete"
|
tokenizer.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Char-level tokenizer for the macron-tagging model.
|
| 3 |
+
|
| 4 |
+
Every input character position is encoded as two small categorical "planes":
|
| 5 |
+
- plane 1 (letter): which of the 24 Greek letters (sigma/final-sigma folded together)
|
| 6 |
+
it is, or SPACE, or OTHER (punctuation, digits, digamma, Latin, ...)
|
| 7 |
+
- plane 2 (diacritic): which combination of accent/breathing/diaeresis/subscript-iota
|
| 8 |
+
it carries (built dynamically from data; OTHER-plane positions
|
| 9 |
+
always get the "none" diacritic)
|
| 10 |
+
|
| 11 |
+
The target is a third plane, macron status, but that's never fed in as an input feature —
|
| 12 |
+
it is only ever the training label (NONE / SHORT / LONG), used at positions whose plane-1
|
| 13 |
+
letter is alpha, iota or upsilon and which grc_utils considers a "real" (ambiguous) dichronon.
|
| 14 |
+
|
| 15 |
+
Training text comes from grc_macronizer output, e.g. "νεα_νί^α_ς", where an ^ or _
|
| 16 |
+
immediately follows a disambiguated dichronon's base letter + any diacritics
|
| 17 |
+
(see grc_macronizer/format_macrons.py). A macronized sentence alone is enough to build
|
| 18 |
+
one training example: the plain form (marks stripped) is the model input, and the
|
| 19 |
+
mark positions give the labels.
|
| 20 |
+
'''
|
| 21 |
+
|
| 22 |
+
import unicodedata
|
| 23 |
+
|
| 24 |
+
from grc_utils import DICHRONA
|
| 25 |
+
from grc_utils.filter_dichrona import is_diphthong, has_iota_adscriptum
|
| 26 |
+
|
| 27 |
+
PAD, SPACE, OTHER = 0, 1, 2
|
| 28 |
+
GREEK_LETTERS = "αβγδεζηθικλμνξοπρστυφχψω" # 24 letters, sigma covers both σ and ς
|
| 29 |
+
LETTER_VOCAB = [None, ' ', None] + list(GREEK_LETTERS) # index 0/2 are placeholders, see below
|
| 30 |
+
PLANE1_ITOS = ["<pad>", "<space>", "<other>"] + list(GREEK_LETTERS)
|
| 31 |
+
PLANE1_STOI = {ch: i for i, ch in enumerate(PLANE1_ITOS)}
|
| 32 |
+
PLANE1_VOCAB_SIZE = len(PLANE1_ITOS)
|
| 33 |
+
|
| 34 |
+
DICHRONA_LETTERS = {"α", "ι", "υ"}
|
| 35 |
+
|
| 36 |
+
MACRON_NONE, MACRON_SHORT, MACRON_LONG = 0, 1, 2
|
| 37 |
+
MACRON_LABEL_NAMES = ["none", "short", "long"]
|
| 38 |
+
|
| 39 |
+
LABEL_IGNORE_INDEX = -100 # standard HF convention: loss ignores these positions
|
| 40 |
+
|
| 41 |
+
SHORT_MARK, LONG_MARK = "^", "_"
|
| 42 |
+
|
| 43 |
+
FINAL_SIGMA = "ς"
|
| 44 |
+
SIGMA = "σ"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _base_letter(nfd_char):
|
| 48 |
+
'''Fold final sigma to sigma; return None if not a lowercase Greek letter a-w.'''
|
| 49 |
+
if nfd_char == FINAL_SIGMA:
|
| 50 |
+
return SIGMA
|
| 51 |
+
if nfd_char in GREEK_LETTERS:
|
| 52 |
+
return nfd_char
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def is_dichronon(base_letter):
|
| 57 |
+
return base_letter in DICHRONA_LETTERS
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def real_dichrona_mask(chars):
|
| 61 |
+
'''
|
| 62 |
+
True eligibility mask: char is a genuine ambiguous dichronon (in grc_utils.DICHRONA --
|
| 63 |
+
i.e. not circumflexed, not iota-subscript, not a bare unaccented capital) AND does not
|
| 64 |
+
form a diphthong or iota-adscriptum with its immediate neighbour. Mirrors
|
| 65 |
+
grc_utils.filter_dichrona.word_with_real_dichrona but returns a per-position mask
|
| 66 |
+
instead of a single bool, so training/inference eligibility exactly matches what the
|
| 67 |
+
rule-based macronizer (and the Norma benchmark) consider markable.
|
| 68 |
+
|
| 69 |
+
`chars` should be the NFC-composed grapheme-cluster list produced by encode_plain /
|
| 70 |
+
encode_macronized. Falls back to a context-free DICHRONA-membership check if any
|
| 71 |
+
cluster didn't collapse to a single codepoint under NFC (rare combining-mark combo).
|
| 72 |
+
'''
|
| 73 |
+
joined = "".join(chars)
|
| 74 |
+
if len(joined) != len(chars):
|
| 75 |
+
return [c in DICHRONA for c in chars]
|
| 76 |
+
n = len(joined)
|
| 77 |
+
mask = []
|
| 78 |
+
for i, ch in enumerate(joined):
|
| 79 |
+
if ch not in DICHRONA:
|
| 80 |
+
mask.append(False)
|
| 81 |
+
continue
|
| 82 |
+
prev_pair = joined[i - 1:i + 1] if i > 0 else ''
|
| 83 |
+
next_pair = joined[i:i + 2] if i < n - 1 else ''
|
| 84 |
+
if (prev_pair and (is_diphthong(prev_pair) or has_iota_adscriptum(prev_pair))) or \
|
| 85 |
+
(next_pair and (is_diphthong(next_pair) or has_iota_adscriptum(next_pair))):
|
| 86 |
+
mask.append(False)
|
| 87 |
+
else:
|
| 88 |
+
mask.append(True)
|
| 89 |
+
return mask
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class DiacriticVocab:
|
| 93 |
+
'''
|
| 94 |
+
Built from data: maps a (sorted) combining-mark-string -> small integer id.
|
| 95 |
+
id 0 is reserved for "<pad>", id 1 for "<none>" (no diacritics -- also what
|
| 96 |
+
positions get when diacritics are masked out during training), id 2 for "<unk>"
|
| 97 |
+
(an unseen combination at inference time).
|
| 98 |
+
'''
|
| 99 |
+
|
| 100 |
+
PAD, NONE, UNK = 0, 1, 2
|
| 101 |
+
|
| 102 |
+
def __init__(self):
|
| 103 |
+
self.itos = ["<pad>", "<none>", "<unk>"]
|
| 104 |
+
self.stoi = {"<pad>": self.PAD, "<none>": self.NONE, "<unk>": self.UNK}
|
| 105 |
+
self.frozen = False
|
| 106 |
+
|
| 107 |
+
def fit(self, marks_iterable):
|
| 108 |
+
for marks in marks_iterable:
|
| 109 |
+
self._get_or_add(marks)
|
| 110 |
+
|
| 111 |
+
def freeze(self):
|
| 112 |
+
self.frozen = True
|
| 113 |
+
|
| 114 |
+
def _get_or_add(self, marks):
|
| 115 |
+
if marks == "":
|
| 116 |
+
return self.NONE
|
| 117 |
+
if marks in self.stoi:
|
| 118 |
+
return self.stoi[marks]
|
| 119 |
+
if self.frozen:
|
| 120 |
+
return self.UNK
|
| 121 |
+
idx = len(self.itos)
|
| 122 |
+
self.itos.append(marks)
|
| 123 |
+
self.stoi[marks] = idx
|
| 124 |
+
return idx
|
| 125 |
+
|
| 126 |
+
def encode(self, marks):
|
| 127 |
+
if marks == "":
|
| 128 |
+
return self.NONE
|
| 129 |
+
return self.stoi.get(marks, self.UNK if self.frozen else self._get_or_add(marks))
|
| 130 |
+
|
| 131 |
+
def __len__(self):
|
| 132 |
+
return len(self.itos)
|
| 133 |
+
|
| 134 |
+
def to_dict(self):
|
| 135 |
+
return {"itos": self.itos}
|
| 136 |
+
|
| 137 |
+
@classmethod
|
| 138 |
+
def from_dict(cls, d):
|
| 139 |
+
v = cls()
|
| 140 |
+
v.itos = list(d["itos"])
|
| 141 |
+
v.stoi = {s: i for i, s in enumerate(v.itos)}
|
| 142 |
+
v.frozen = True
|
| 143 |
+
return v
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _decompose(text):
|
| 147 |
+
'''NFD-decompose, then walk it grouping each base letter with its trailing combining marks.
|
| 148 |
+
Returns a list of (base_char, combining_marks_str, is_mark_char) -- non-letters are their
|
| 149 |
+
own "cluster" with empty marks.
|
| 150 |
+
'''
|
| 151 |
+
nfd = unicodedata.normalize("NFD", text)
|
| 152 |
+
clusters = []
|
| 153 |
+
i = 0
|
| 154 |
+
n = len(nfd)
|
| 155 |
+
while i < n:
|
| 156 |
+
ch = nfd[i]
|
| 157 |
+
if unicodedata.category(ch).startswith("M"):
|
| 158 |
+
# Stray combining mark with no preceding base in this cluster view (shouldn't
|
| 159 |
+
# normally happen at the start of a cluster) -- attach to previous cluster if any.
|
| 160 |
+
if clusters:
|
| 161 |
+
base, marks = clusters[-1]
|
| 162 |
+
clusters[-1] = (base, marks + ch)
|
| 163 |
+
i += 1
|
| 164 |
+
continue
|
| 165 |
+
marks = ""
|
| 166 |
+
i += 1
|
| 167 |
+
while i < n and unicodedata.category(nfd[i]).startswith("M"):
|
| 168 |
+
marks += nfd[i]
|
| 169 |
+
i += 1
|
| 170 |
+
clusters.append((ch, marks))
|
| 171 |
+
return clusters
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def encode_plain(text, diacritic_vocab, fit=False):
|
| 175 |
+
'''
|
| 176 |
+
Encode a PLAIN (no ^/_ marks) macronized-or-not string into parallel arrays.
|
| 177 |
+
|
| 178 |
+
Returns dict with:
|
| 179 |
+
chars: list[str] -- the base+diacritics grapheme cluster as it should be rendered
|
| 180 |
+
(NFC), one per position -- used to reconstruct output text
|
| 181 |
+
plane1: list[int] -- letter-plane ids
|
| 182 |
+
plane2: list[int] -- diacritic-plane ids
|
| 183 |
+
dichrona_mask: list[bool] -- True where plane1 letter is alpha/iota/upsilon (candidate
|
| 184 |
+
positions; caller further filters "real" dichrona if desired)
|
| 185 |
+
'''
|
| 186 |
+
clusters = _decompose(text)
|
| 187 |
+
chars, plane1, plane2 = [], [], []
|
| 188 |
+
for base, marks in clusters:
|
| 189 |
+
lower = base.lower()
|
| 190 |
+
letter = _base_letter(lower)
|
| 191 |
+
if letter is not None:
|
| 192 |
+
plane1.append(PLANE1_STOI[letter])
|
| 193 |
+
did = diacritic_vocab._get_or_add(marks) if fit else diacritic_vocab.encode(marks)
|
| 194 |
+
plane2.append(did)
|
| 195 |
+
elif base == " " or base == "\n" or base == "\t":
|
| 196 |
+
plane1.append(PLANE1_STOI["<space>"])
|
| 197 |
+
plane2.append(diacritic_vocab.NONE)
|
| 198 |
+
else:
|
| 199 |
+
plane1.append(PLANE1_STOI["<other>"])
|
| 200 |
+
plane2.append(diacritic_vocab.NONE)
|
| 201 |
+
chars.append(unicodedata.normalize("NFC", base + marks))
|
| 202 |
+
return {
|
| 203 |
+
"chars": chars,
|
| 204 |
+
"plane1": plane1,
|
| 205 |
+
"plane2": plane2,
|
| 206 |
+
"dichrona_mask": real_dichrona_mask(chars),
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def strip_marks(text):
|
| 211 |
+
return text.replace(SHORT_MARK, "").replace(LONG_MARK, "")
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def encode_macronized(text, diacritic_vocab, fit=False):
|
| 215 |
+
'''
|
| 216 |
+
Encode a MACRONIZED string (base letters with trailing ^/_ markup, cf.
|
| 217 |
+
grc_macronizer/format_macrons.py's macron_unicode_to_markup convention) into the
|
| 218 |
+
same per-position arrays as encode_plain, PLUS a macron_label array (NONE/SHORT/LONG,
|
| 219 |
+
LABEL_IGNORE_INDEX at non-dichrona positions and at dichrona positions with no mark).
|
| 220 |
+
'''
|
| 221 |
+
nfd = unicodedata.normalize("NFD", text)
|
| 222 |
+
clusters = []
|
| 223 |
+
i, n = 0, len(nfd)
|
| 224 |
+
while i < n:
|
| 225 |
+
ch = nfd[i]
|
| 226 |
+
if unicodedata.category(ch).startswith("M"):
|
| 227 |
+
if clusters:
|
| 228 |
+
base, marks, mark_sym = clusters[-1]
|
| 229 |
+
clusters[-1] = (base, marks + ch, mark_sym)
|
| 230 |
+
i += 1
|
| 231 |
+
continue
|
| 232 |
+
marks = ""
|
| 233 |
+
i += 1
|
| 234 |
+
while i < n and unicodedata.category(nfd[i]).startswith("M"):
|
| 235 |
+
marks += nfd[i]
|
| 236 |
+
i += 1
|
| 237 |
+
mark_sym = ""
|
| 238 |
+
if i < n and nfd[i] in (SHORT_MARK, LONG_MARK):
|
| 239 |
+
mark_sym = nfd[i]
|
| 240 |
+
i += 1
|
| 241 |
+
clusters.append((ch, marks, mark_sym))
|
| 242 |
+
|
| 243 |
+
chars, plane1, plane2, mark_syms = [], [], [], []
|
| 244 |
+
for base, marks, mark_sym in clusters:
|
| 245 |
+
lower = base.lower()
|
| 246 |
+
letter = _base_letter(lower)
|
| 247 |
+
if letter is not None:
|
| 248 |
+
plane1.append(PLANE1_STOI[letter])
|
| 249 |
+
did = diacritic_vocab._get_or_add(marks) if fit else diacritic_vocab.encode(marks)
|
| 250 |
+
plane2.append(did)
|
| 251 |
+
elif base == " " or base == "\n" or base == "\t":
|
| 252 |
+
plane1.append(PLANE1_STOI["<space>"])
|
| 253 |
+
plane2.append(diacritic_vocab.NONE)
|
| 254 |
+
else:
|
| 255 |
+
plane1.append(PLANE1_STOI["<other>"])
|
| 256 |
+
plane2.append(diacritic_vocab.NONE)
|
| 257 |
+
chars.append(unicodedata.normalize("NFC", base + marks))
|
| 258 |
+
mark_syms.append(mark_sym)
|
| 259 |
+
|
| 260 |
+
eligible = real_dichrona_mask(chars)
|
| 261 |
+
labels = []
|
| 262 |
+
for eligible_i, mark_sym in zip(eligible, mark_syms):
|
| 263 |
+
if not eligible_i:
|
| 264 |
+
labels.append(LABEL_IGNORE_INDEX)
|
| 265 |
+
elif mark_sym == SHORT_MARK:
|
| 266 |
+
labels.append(MACRON_SHORT)
|
| 267 |
+
elif mark_sym == LONG_MARK:
|
| 268 |
+
labels.append(MACRON_LONG)
|
| 269 |
+
else:
|
| 270 |
+
labels.append(LABEL_IGNORE_INDEX) # dichronon left unmarked -> ignore in loss
|
| 271 |
+
|
| 272 |
+
return {
|
| 273 |
+
"chars": chars,
|
| 274 |
+
"plane1": plane1,
|
| 275 |
+
"plane2": plane2,
|
| 276 |
+
"labels": labels,
|
| 277 |
+
"dichrona_mask": eligible,
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def decode(chars, pred_labels):
|
| 282 |
+
'''Rebuild a macronized string from rendered chars + predicted label per position.'''
|
| 283 |
+
out = []
|
| 284 |
+
for ch, lab in zip(chars, pred_labels):
|
| 285 |
+
out.append(ch)
|
| 286 |
+
if lab == MACRON_SHORT:
|
| 287 |
+
out.append(SHORT_MARK)
|
| 288 |
+
elif lab == MACRON_LONG:
|
| 289 |
+
out.append(LONG_MARK)
|
| 290 |
+
return "".join(out)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def mask_diacritics(plane2_ids, none_id, p):
|
| 294 |
+
'''Return a copy of plane2_ids with each entry replaced by `none_id` independently
|
| 295 |
+
with probability p (a lightweight stand-in for "input lacks accentuation").'''
|
| 296 |
+
import random
|
| 297 |
+
return [none_id if (v != none_id and random.random() < p) else v for v in plane2_ids]
|
train.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Train the char-level macronizer on a cache made by prepare_data.py.
|
| 3 |
+
|
| 4 |
+
python train.py --cache cache/oga-no-norma --output_dir runs/seed1 --seed 1
|
| 5 |
+
|
| 6 |
+
The defaults are the paper's settings: AdamW (lr 3e-4, weight decay 0.01),
|
| 7 |
+
one-cycle schedule with 5% warmup, batch size 2048, patience of 8
|
| 8 |
+
evaluations, architecture 4x128 (4 heads, intermediate size 512),
|
| 9 |
+
dropout 0.1, diacritic masking p=0.3.
|
| 10 |
+
|
| 11 |
+
Differences from the original train.py:
|
| 12 |
+
- data comes from the cache (fixed silver split) instead of re-encoding;
|
| 13 |
+
- batches are padded with numpy and the diacritic masking is done on the
|
| 14 |
+
GPU, instead of in a per-example Python collate function;
|
| 15 |
+
- every evaluation also scores Norma validation (gold); --select_metric
|
| 16 |
+
chooses what checkpoint selection, early stopping and Optuna use.
|
| 17 |
+
'''
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import json
|
| 21 |
+
import math
|
| 22 |
+
import os
|
| 23 |
+
import random
|
| 24 |
+
import shutil
|
| 25 |
+
import time
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import torch
|
| 29 |
+
|
| 30 |
+
from model import MacronizerConfig, MacronizerModel
|
| 31 |
+
from norma import load_split, metrics as norma_metrics, score as norma_score
|
| 32 |
+
from predict import MacronPredictor
|
| 33 |
+
from tokenizer import DiacriticVocab, LABEL_IGNORE_INDEX, MACRON_LABEL_NAMES
|
| 34 |
+
|
| 35 |
+
SELECT_METRICS = ("norma_val_acc", "norma_val_f1", "silver_val_acc")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def build_parser():
|
| 39 |
+
ap = argparse.ArgumentParser()
|
| 40 |
+
ap.add_argument("--cache", required=True)
|
| 41 |
+
ap.add_argument("--output_dir", required=True)
|
| 42 |
+
ap.add_argument("--seed", type=int, default=1)
|
| 43 |
+
ap.add_argument("--lr", type=float, default=3e-4)
|
| 44 |
+
ap.add_argument("--weight_decay", type=float, default=0.01)
|
| 45 |
+
ap.add_argument("--dropout", type=float, default=0.1)
|
| 46 |
+
ap.add_argument("--batch_size", type=int, default=2048)
|
| 47 |
+
ap.add_argument("--epochs", type=int, default=30)
|
| 48 |
+
ap.add_argument("--max_steps", type=int, default=None,
|
| 49 |
+
help="stop after this many steps (the schedule still spans --epochs unless "
|
| 50 |
+
"--schedule_steps is given)")
|
| 51 |
+
ap.add_argument("--schedule_steps", type=int, default=None)
|
| 52 |
+
ap.add_argument("--pct_start", type=float, default=0.05)
|
| 53 |
+
ap.add_argument("--diacritic_mask_p", type=float, default=0.3)
|
| 54 |
+
ap.add_argument("--hidden_size", type=int, default=128)
|
| 55 |
+
ap.add_argument("--num_hidden_layers", type=int, default=4)
|
| 56 |
+
ap.add_argument("--num_attention_heads", type=int, default=4)
|
| 57 |
+
ap.add_argument("--intermediate_size", type=int, default=512)
|
| 58 |
+
ap.add_argument("--eval_every_steps", type=int, default=1000,
|
| 59 |
+
help="evaluate every N steps and at the end of every epoch")
|
| 60 |
+
ap.add_argument("--log_every_steps", type=int, default=100)
|
| 61 |
+
ap.add_argument("--patience", type=int, default=8)
|
| 62 |
+
ap.add_argument("--select_metric", choices=SELECT_METRICS, default="norma_val_acc")
|
| 63 |
+
ap.add_argument("--norma_repo", default="Urdatorn/norma")
|
| 64 |
+
ap.add_argument("--norma_revision", default=None)
|
| 65 |
+
ap.add_argument("--tf32", action="store_true", help="allow TF32 matmuls (off: plain fp32)")
|
| 66 |
+
ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
|
| 67 |
+
return ap
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def log(msg):
|
| 71 |
+
print(f"[{time.strftime('%Y-%m-%dT%H:%M:%S')}] {msg}", flush=True)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class FlatData:
|
| 75 |
+
def __init__(self, path):
|
| 76 |
+
z = np.load(path)
|
| 77 |
+
self.p1, self.p2, self.lab, self.off = z["plane1"], z["plane2"], z["labels"], z["offsets"]
|
| 78 |
+
self.n = len(self.off) - 1
|
| 79 |
+
|
| 80 |
+
def batch(self, idx):
|
| 81 |
+
idx = np.sort(idx)
|
| 82 |
+
start = self.off[idx]
|
| 83 |
+
lens = self.off[idx + 1] - start
|
| 84 |
+
L = int(lens.max())
|
| 85 |
+
pos = np.arange(L)
|
| 86 |
+
mask = pos[None, :] < lens[:, None]
|
| 87 |
+
src = np.where(mask, start[:, None] + pos[None, :], 0)
|
| 88 |
+
p1 = np.where(mask, self.p1[src], 0).astype(np.int64)
|
| 89 |
+
p2 = np.where(mask, self.p2[src], 0).astype(np.int64)
|
| 90 |
+
lab = np.where(mask, self.lab[src], LABEL_IGNORE_INDEX).astype(np.int64)
|
| 91 |
+
return (torch.from_numpy(p1), torch.from_numpy(p2), torch.from_numpy(lab),
|
| 92 |
+
torch.from_numpy(mask.astype(np.int64)))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def to_dev(b, device):
|
| 96 |
+
return [t.to(device, non_blocking=True) for t in b]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@torch.no_grad()
|
| 100 |
+
def eval_silver(model, data, batch_size, device):
|
| 101 |
+
model.eval()
|
| 102 |
+
loss_sum, n_batches = 0.0, 0
|
| 103 |
+
correct, total = [0, 0, 0], [0, 0, 0]
|
| 104 |
+
for s in range(0, data.n, batch_size):
|
| 105 |
+
p1, p2, lab, am = to_dev(data.batch(np.arange(s, min(s + batch_size, data.n))), device)
|
| 106 |
+
out = model(plane1_ids=p1, plane2_ids=p2, attention_mask=am, labels=lab)
|
| 107 |
+
loss_sum += out.loss.item(); n_batches += 1
|
| 108 |
+
pred = out.logits.argmax(-1)
|
| 109 |
+
for c in range(3):
|
| 110 |
+
m = lab == c
|
| 111 |
+
total[c] += int(m.sum()); correct[c] += int((pred[m] == c).sum())
|
| 112 |
+
model.train()
|
| 113 |
+
n = sum(total)
|
| 114 |
+
return dict(loss=loss_sum / max(n_batches, 1), acc=sum(correct) / n if n else 0.0,
|
| 115 |
+
per_class_acc={MACRON_LABEL_NAMES[c]: (correct[c] / total[c] if total[c] else None)
|
| 116 |
+
for c in range(3)},
|
| 117 |
+
n=n)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def eval_norma(model, vocab, records, device):
|
| 121 |
+
pred = MacronPredictor(model, vocab, device=device)
|
| 122 |
+
outputs = pred.macronize_lines([r.plain for r in records])
|
| 123 |
+
return norma_metrics(norma_score(records, outputs), by_source=False)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def run(args, trial=None):
|
| 127 |
+
'''Trains one model. Returns a summary dict. Raises optuna.TrialPruned if
|
| 128 |
+
`trial` says so.'''
|
| 129 |
+
random.seed(args.seed); np.random.seed(args.seed); torch.manual_seed(args.seed)
|
| 130 |
+
torch.backends.cuda.matmul.allow_tf32 = args.tf32
|
| 131 |
+
torch.backends.cudnn.allow_tf32 = args.tf32
|
| 132 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 133 |
+
with open(os.path.join(args.output_dir, "args.json"), "w") as f:
|
| 134 |
+
json.dump(vars(args), f, indent=2)
|
| 135 |
+
|
| 136 |
+
t_load = time.time()
|
| 137 |
+
train, val = FlatData(os.path.join(args.cache, "train.npz")), FlatData(os.path.join(args.cache, "val.npz"))
|
| 138 |
+
vocab_path = os.path.join(args.cache, "diacritic_vocab.json")
|
| 139 |
+
with open(vocab_path, encoding="utf-8") as f:
|
| 140 |
+
vocab = DiacriticVocab.from_dict(json.load(f))
|
| 141 |
+
shutil.copy(vocab_path, os.path.join(args.output_dir, "diacritic_vocab.json"))
|
| 142 |
+
norma_val = load_split("validation", args.norma_repo, args.norma_revision)
|
| 143 |
+
log(f"loaded cache in {time.time()-t_load:.1f}s: train {train.n:,} examples, val {val.n:,}; "
|
| 144 |
+
f"Norma validation {len(norma_val)} lines")
|
| 145 |
+
|
| 146 |
+
config = MacronizerConfig(
|
| 147 |
+
plane2_vocab_size=len(vocab), hidden_size=args.hidden_size,
|
| 148 |
+
num_hidden_layers=args.num_hidden_layers, num_attention_heads=args.num_attention_heads,
|
| 149 |
+
intermediate_size=args.intermediate_size, max_position_embeddings=512, dropout=args.dropout)
|
| 150 |
+
model = MacronizerModel(config).to(args.device)
|
| 151 |
+
log(f"model {model.num_parameters_readable()} params on {args.device} "
|
| 152 |
+
f"({torch.cuda.get_device_name() if args.device == 'cuda' else 'cpu'}); "
|
| 153 |
+
f"lr={args.lr:.3g} wd={args.weight_decay:.3g} dropout={args.dropout} seed={args.seed} "
|
| 154 |
+
f"select={args.select_metric}")
|
| 155 |
+
|
| 156 |
+
steps_per_epoch = train.n // args.batch_size
|
| 157 |
+
total_steps = args.schedule_steps or steps_per_epoch * args.epochs
|
| 158 |
+
last_step = min(total_steps, args.max_steps or total_steps)
|
| 159 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
|
| 160 |
+
scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=args.lr, total_steps=total_steps,
|
| 161 |
+
pct_start=args.pct_start)
|
| 162 |
+
log(f"{steps_per_epoch} steps/epoch, schedule {total_steps} steps, running up to {last_step}")
|
| 163 |
+
|
| 164 |
+
gen = np.random.default_rng(args.seed)
|
| 165 |
+
metrics_path = os.path.join(args.output_dir, "metrics.jsonl")
|
| 166 |
+
open(metrics_path, "w").close()
|
| 167 |
+
best, best_rec, bad_evals, n_evals = -math.inf, None, 0, 0
|
| 168 |
+
step, t0, seen_chars, run_loss, run_n = 0, time.time(), 0, 0.0, 0
|
| 169 |
+
stop = False
|
| 170 |
+
|
| 171 |
+
def evaluate(epoch, tag):
|
| 172 |
+
nonlocal best, best_rec, bad_evals, n_evals, stop
|
| 173 |
+
te = time.time()
|
| 174 |
+
sv = eval_silver(model, val, args.batch_size, args.device)
|
| 175 |
+
nv = eval_norma(model, vocab, norma_val, args.device)
|
| 176 |
+
rec = dict(step=step, epoch=epoch, tag=tag, elapsed_s=round(time.time() - t0, 1),
|
| 177 |
+
silver_val_loss=sv["loss"], silver_val_acc=sv["acc"],
|
| 178 |
+
silver_val_per_class=sv["per_class_acc"],
|
| 179 |
+
norma_val_acc=nv["mixed"]["accuracy"], norma_val_f1=nv["mixed"]["f1"],
|
| 180 |
+
norma_val_long_acc=nv["long"]["accuracy"], norma_val_short_acc=nv["short"]["accuracy"],
|
| 181 |
+
norma_val_cov=nv["mixed"]["coverage"], norma_val_default_short=nv["default_short_accuracy"])
|
| 182 |
+
with open(metrics_path, "a") as f:
|
| 183 |
+
f.write(json.dumps(rec) + "\n")
|
| 184 |
+
value = rec[args.select_metric]
|
| 185 |
+
improved = value > best
|
| 186 |
+
if improved:
|
| 187 |
+
best, best_rec, bad_evals = value, rec, 0
|
| 188 |
+
model.save_pretrained(os.path.join(args.output_dir, "best"))
|
| 189 |
+
shutil.copy(os.path.join(args.output_dir, "diacritic_vocab.json"),
|
| 190 |
+
os.path.join(args.output_dir, "best", "diacritic_vocab.json"))
|
| 191 |
+
else:
|
| 192 |
+
bad_evals += 1
|
| 193 |
+
log(f"EVAL {tag} step {step} ep {epoch}: silver loss {sv['loss']:.4f} acc {sv['acc']:.4%} | "
|
| 194 |
+
f"norma-val acc {rec['norma_val_acc']:.2%} f1 {rec['norma_val_f1']:.2%} "
|
| 195 |
+
f"long {rec['norma_val_long_acc']:.2%} short {rec['norma_val_short_acc']:.2%} | "
|
| 196 |
+
f"{args.select_metric}={value:.4%} {'NEW BEST' if improved else f'(no gain {bad_evals}/{args.patience})'} "
|
| 197 |
+
f"best={best:.4%} [{time.time()-te:.1f}s]")
|
| 198 |
+
if trial is not None:
|
| 199 |
+
import optuna
|
| 200 |
+
trial.report(value, n_evals)
|
| 201 |
+
if trial.should_prune():
|
| 202 |
+
log(f"PRUNED at eval {n_evals}")
|
| 203 |
+
raise optuna.TrialPruned()
|
| 204 |
+
n_evals += 1
|
| 205 |
+
if args.patience and bad_evals >= args.patience:
|
| 206 |
+
log(f"early stop: no gain for {bad_evals} evals")
|
| 207 |
+
stop = True
|
| 208 |
+
|
| 209 |
+
model.train()
|
| 210 |
+
for epoch in range(args.epochs):
|
| 211 |
+
order = gen.permutation(train.n)
|
| 212 |
+
for b in range(steps_per_epoch):
|
| 213 |
+
p1, p2, lab, am = to_dev(train.batch(order[b * args.batch_size:(b + 1) * args.batch_size]), args.device)
|
| 214 |
+
if args.diacritic_mask_p > 0:
|
| 215 |
+
drop = (torch.rand(p2.shape, device=p2.device) < args.diacritic_mask_p) & (p2 > 1)
|
| 216 |
+
p2 = torch.where(drop, torch.ones_like(p2), p2)
|
| 217 |
+
loss = model(plane1_ids=p1, plane2_ids=p2, attention_mask=am, labels=lab).loss
|
| 218 |
+
optimizer.zero_grad(set_to_none=True)
|
| 219 |
+
loss.backward()
|
| 220 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 221 |
+
optimizer.step(); scheduler.step()
|
| 222 |
+
step += 1
|
| 223 |
+
seen_chars += int(am.sum()); run_loss += loss.item(); run_n += 1
|
| 224 |
+
if step % args.log_every_steps == 0:
|
| 225 |
+
el = time.time() - t0
|
| 226 |
+
log(f"step {step}/{last_step} ep {epoch} loss {run_loss/run_n:.4f} "
|
| 227 |
+
f"lr {scheduler.get_last_lr()[0]:.2e} {step/el:.2f} it/s {seen_chars/el/1e6:.2f}M char/s "
|
| 228 |
+
f"elapsed {el/60:.1f}m eta {(last_step-step)/(step/el)/60:.1f}m"
|
| 229 |
+
+ (f" mem {torch.cuda.max_memory_allocated()/2**30:.1f}G" if args.device == "cuda" else ""))
|
| 230 |
+
run_loss, run_n = 0.0, 0
|
| 231 |
+
if step % args.eval_every_steps == 0:
|
| 232 |
+
evaluate(epoch, "step")
|
| 233 |
+
if stop or step >= last_step:
|
| 234 |
+
break
|
| 235 |
+
if stop or step >= last_step:
|
| 236 |
+
if step % args.eval_every_steps:
|
| 237 |
+
evaluate(epoch, "final")
|
| 238 |
+
break
|
| 239 |
+
evaluate(epoch, "epoch_end")
|
| 240 |
+
if stop:
|
| 241 |
+
break
|
| 242 |
+
|
| 243 |
+
summary = dict(best_value=best, select_metric=args.select_metric, best_eval=best_rec,
|
| 244 |
+
steps=step, minutes=round((time.time() - t0) / 60, 2),
|
| 245 |
+
steps_per_epoch=steps_per_epoch)
|
| 246 |
+
with open(os.path.join(args.output_dir, "summary.json"), "w") as f:
|
| 247 |
+
json.dump(summary, f, indent=2)
|
| 248 |
+
log(f"DONE best {args.select_metric}={best:.4%} at step {best_rec['step'] if best_rec else '-'}; "
|
| 249 |
+
f"{step} steps in {summary['minutes']} min -> {args.output_dir}/best")
|
| 250 |
+
return summary
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
if __name__ == "__main__":
|
| 254 |
+
run(build_parser().parse_args())
|