lafi23333 commited on
Commit
9b1761d
1 Parent(s): 47a9f23

Upload 191 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .github/workflows/pull_format.yml +43 -0
  2. .github/workflows/push_format.yml +57 -0
  3. .gitignore +184 -0
  4. .gitmodules +0 -0
  5. .pre-commit-config.yaml +25 -0
  6. LICENSE +661 -0
  7. README.md +37 -13
  8. all_process.py +1384 -0
  9. asr_transcript.py +102 -0
  10. attentions.py +464 -0
  11. attentions_onnx.py +378 -0
  12. bert/bert-base-japanese-v3/.gitattributes +34 -0
  13. bert/bert-base-japanese-v3/README.md +53 -0
  14. bert/bert-base-japanese-v3/config.json +19 -0
  15. bert/bert-base-japanese-v3/tokenizer_config.json +10 -0
  16. bert/bert-base-japanese-v3/vocab.txt +0 -0
  17. bert/bert-large-japanese-v2/.gitattributes +34 -0
  18. bert/bert-large-japanese-v2/README.md +53 -0
  19. bert/bert-large-japanese-v2/config.json +19 -0
  20. bert/bert-large-japanese-v2/tokenizer_config.json +10 -0
  21. bert/bert-large-japanese-v2/vocab.txt +0 -0
  22. bert/bert_models.json +14 -0
  23. bert/chinese-roberta-wwm-ext-large/.gitattributes +9 -0
  24. bert/chinese-roberta-wwm-ext-large/README.md +57 -0
  25. bert/chinese-roberta-wwm-ext-large/added_tokens.json +1 -0
  26. bert/chinese-roberta-wwm-ext-large/config.json +28 -0
  27. bert/chinese-roberta-wwm-ext-large/special_tokens_map.json +1 -0
  28. bert/chinese-roberta-wwm-ext-large/tokenizer.json +0 -0
  29. bert/chinese-roberta-wwm-ext-large/tokenizer_config.json +1 -0
  30. bert/chinese-roberta-wwm-ext-large/vocab.txt +0 -0
  31. bert/deberta-v2-large-japanese-char-wwm/.gitattributes +34 -0
  32. bert/deberta-v2-large-japanese-char-wwm/README.md +89 -0
  33. bert/deberta-v2-large-japanese-char-wwm/config.json +37 -0
  34. bert/deberta-v2-large-japanese-char-wwm/special_tokens_map.json +7 -0
  35. bert/deberta-v2-large-japanese-char-wwm/tokenizer_config.json +19 -0
  36. bert/deberta-v2-large-japanese-char-wwm/vocab.txt +0 -0
  37. bert/deberta-v2-large-japanese/.gitattributes +34 -0
  38. bert/deberta-v2-large-japanese/README.md +111 -0
  39. bert/deberta-v2-large-japanese/config.json +38 -0
  40. bert/deberta-v2-large-japanese/special_tokens_map.json +9 -0
  41. bert/deberta-v2-large-japanese/tokenizer.json +0 -0
  42. bert/deberta-v2-large-japanese/tokenizer_config.json +15 -0
  43. bert/deberta-v3-large/.gitattributes +27 -0
  44. bert/deberta-v3-large/README.md +93 -0
  45. bert/deberta-v3-large/config.json +22 -0
  46. bert/deberta-v3-large/generator_config.json +22 -0
  47. bert/deberta-v3-large/tokenizer_config.json +4 -0
  48. bert_gen.py +74 -0
  49. clean_list.py +48 -0
  50. commons.py +166 -0
.github/workflows/pull_format.yml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: pull format
2
+
3
+ on: [pull_request]
4
+
5
+ permissions:
6
+ contents: write
7
+
8
+ jobs:
9
+ pull_format:
10
+ runs-on: ${{ matrix.os }}
11
+
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.10"]
15
+ os: [ubuntu-latest]
16
+ fail-fast: false
17
+
18
+ continue-on-error: true
19
+
20
+ steps:
21
+ - name: checkout
22
+ continue-on-error: true
23
+ uses: actions/checkout@v3
24
+ with:
25
+ ref: ${{ github.head_ref }}
26
+ fetch-depth: 0
27
+
28
+ - name: Set up Python ${{ matrix.python-version }}
29
+ uses: actions/setup-python@v4
30
+ with:
31
+ python-version: ${{ matrix.python-version }}
32
+
33
+ - name: Install Black
34
+ run: pip install "black[jupyter]"
35
+
36
+ - name: Run Black
37
+ # run: black $(git ls-files '*.py')
38
+ run: black .
39
+
40
+ - name: Commit Back
41
+ uses: stefanzweifel/git-auto-commit-action@v4
42
+ with:
43
+ commit_message: Apply Code Formatter Change
.github/workflows/push_format.yml ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: push format
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - master
7
+ - dev
8
+
9
+ permissions:
10
+ contents: write
11
+ pull-requests: write
12
+
13
+ jobs:
14
+ push_format:
15
+ runs-on: ${{ matrix.os }}
16
+
17
+ strategy:
18
+ matrix:
19
+ python-version: ["3.10"]
20
+ os: [ubuntu-latest]
21
+ fail-fast: false
22
+
23
+ steps:
24
+ - uses: actions/checkout@v3
25
+ with:
26
+ ref: ${{github.ref_name}}
27
+
28
+ - name: Set up Python ${{ matrix.python-version }}
29
+ uses: actions/setup-python@v4
30
+ with:
31
+ python-version: ${{ matrix.python-version }}
32
+
33
+ - name: Install Black
34
+ run: pip install "black[jupyter]"
35
+
36
+ - name: Run Black
37
+ # run: black $(git ls-files '*.py')
38
+ run: black .
39
+
40
+ - name: Commit Back
41
+ continue-on-error: true
42
+ id: commitback
43
+ run: |
44
+ git config --local user.email "github-actions[bot]@users.noreply.github.com"
45
+ git config --local user.name "github-actions[bot]"
46
+ git add --all
47
+ git commit -m "Format code"
48
+
49
+ - name: Create Pull Request
50
+ if: steps.commitback.outcome == 'success'
51
+ continue-on-error: true
52
+ uses: peter-evans/create-pull-request@v5
53
+ with:
54
+ delete-branch: true
55
+ body: Apply Code Formatter Change
56
+ title: Apply Code Formatter Change
57
+ commit-message: Automatic code format
.gitignore ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
161
+
162
+ .DS_Store
163
+ /models
164
+ /logs
165
+
166
+ filelists/*
167
+ !/filelists/esd.list
168
+ data/*
169
+ /*.yml
170
+ !/default_config.yml
171
+ /Web/
172
+ /emotional/*/*.bin
173
+ /bert/*/*.bin
174
+ /bert/*/*.h5
175
+ /bert/*/*.model
176
+ /bert/*/*.safetensors
177
+ /bert/*/*.msgpack
178
+
179
+ dataset
180
+ /Data
181
+ Model
182
+ raw/
183
+ logs/
184
+ Data/*
.gitmodules ADDED
File without changes
.pre-commit-config.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v4.5.0
4
+ hooks:
5
+ - id: check-yaml
6
+ - id: end-of-file-fixer
7
+ - id: trailing-whitespace
8
+
9
+ - repo: https://github.com/astral-sh/ruff-pre-commit
10
+ rev: v0.1.6
11
+ hooks:
12
+ - id: ruff
13
+ args: [ --fix ]
14
+
15
+ - repo: https://github.com/psf/black
16
+ rev: 23.11.0
17
+ hooks:
18
+ - id: black
19
+
20
+ - repo: https://github.com/codespell-project/codespell
21
+ rev: v2.2.6
22
+ hooks:
23
+ - id: codespell
24
+ files: ^.*\.(py|md|rst|yml)$
25
+ args: [-L=fro]
LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
README.md CHANGED
@@ -1,13 +1,37 @@
1
- ---
2
- title: Kn
3
- emoji: 🐨
4
- colorFrom: pink
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 4.8.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <img alt="LOGO" src="https://cdn.jsdelivr.net/gh/fishaudio/fish-diffusion@main/images/logo_512x512.png" width="256" height="256" />
4
+
5
+ # Bert-VITS2
6
+
7
+ VITS2 Backbone with multilingual bert
8
+ ## 请注意,本项目核心思路来源于[anyvoiceai/MassTTS](https://github.com/anyvoiceai/MassTTS) 一个非常好的tts项目
9
+ ## MassTTS的演示demo为[ai版峰哥锐评峰哥本人,并找回了在金三角失落的腰子](https://www.bilibili.com/video/BV1w24y1c7z9)
10
+
11
+ [//]: # (## 本项目与[PlayVoice/vits_chinese]&#40;https://github.com/PlayVoice/vits_chinese&#41; 没有任何关系)
12
+
13
+ [//]: # ()
14
+ [//]: # (本仓库来源于之前朋友分享了ai峰哥的视频,本人被其中的效果惊艳,在自己尝试MassTTS以后发现fs在音质方面与vits有一定差距,并且training的pipeline比vits更复杂,因此按照其思路将bert)
15
+
16
+ ## 成熟的旅行者/开拓者/舰长/博士/sensei/猎魔人/喵喵露/V应当参阅代码自己学习如何训练。
17
+
18
+ ### 严禁将此项目用于一切违反《中华人民共和国宪法》,《中华人民共和国刑法》,《中华人民共和国治安管理处罚法》和《中华人民共和国民法典》之用途。
19
+ ### 严禁用于任何政治相关用途。
20
+ #### Video:https://www.bilibili.com/video/BV1hp4y1K78E
21
+ #### Demo:https://www.bilibili.com/video/BV1TF411k78w
22
+ #### QQ Group:815818430
23
+ ## References
24
+ + [anyvoiceai/MassTTS](https://github.com/anyvoiceai/MassTTS)
25
+ + [jaywalnut310/vits](https://github.com/jaywalnut310/vits)
26
+ + [p0p4k/vits2_pytorch](https://github.com/p0p4k/vits2_pytorch)
27
+ + [svc-develop-team/so-vits-svc](https://github.com/svc-develop-team/so-vits-svc)
28
+ + [PaddlePaddle/PaddleSpeech](https://github.com/PaddlePaddle/PaddleSpeech)
29
+ + [emotional-vits](https://github.com/innnky/emotional-vits)
30
+ + [Bert-VITS2-en](https://github.com/xwan07017/Bert-VITS2-en)
31
+ + [Bert-VITS2-UI](https://github.com/jiangyuxiaoxiao/Bert-VITS2-UI)
32
+ ## 感谢所有贡献者作出的努力
33
+ <a href="https://github.com/fishaudio/Bert-VITS2/graphs/contributors" target="_blank">
34
+ <img src="https://contrib.rocks/image?repo=fishaudio/Bert-VITS2"/>
35
+ </a>
36
+
37
+ [//]: # (# 本项目所有代码引用均已写明,bert部分代码思路来源于[AI峰哥]&#40;https://www.bilibili.com/video/BV1w24y1c7z9&#41;,与[vits_chinese]&#40;https://github.com/PlayVoice/vits_chinese&#41;无任何关系。欢迎各位查阅代码。同时,我们也对该开发者的[碰瓷,乃至开盒开发者的行为]&#40;https://www.bilibili.com/read/cv27101514/&#41;表示强烈谴责。)
all_process.py ADDED
@@ -0,0 +1,1384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import platform
4
+ import shutil
5
+ import signal
6
+ import subprocess
7
+ import webbrowser
8
+
9
+ import GPUtil
10
+ import gradio as gr
11
+ import psutil
12
+ import torch
13
+ import yaml
14
+
15
+ from config import yml_config
16
+ from tools.log import logger
17
+
18
+ bert_model_paths = [
19
+ "./bert/chinese-roberta-wwm-ext-large/pytorch_model.bin",
20
+ "./bert/deberta-v2-large-japanese-char-wwm/pytorch_model.bin",
21
+ "./bert/deberta-v3-large/pytorch_model.bin",
22
+ "./bert/deberta-v3-large/spm.model",
23
+ ]
24
+
25
+ emo_model_paths = [
26
+ "./emotional/wav2vec2-large-robust-12-ft-emotion-msp-dim/pytorch_model.bin"
27
+ ]
28
+
29
+ train_base_model_paths = ["D_0.pth", "G_0.pth", "DUR_0.pth"]
30
+ default_yaml_path = "default_config.yml"
31
+ default_config_path = "configs/config.json"
32
+
33
+
34
+ def load_yaml_data_in_raw(yml_path=yml_config):
35
+ with open(yml_path, "r", encoding="utf-8") as file:
36
+ # data = yaml.safe_load(file)
37
+ data = file.read()
38
+ return str(data)
39
+
40
+
41
+ def load_json_data_in_raw(json_path):
42
+ with open(json_path, "r", encoding="utf-8") as file:
43
+ json_data = json.load(file)
44
+ formatted_json_data = json.dumps(json_data, ensure_ascii=False, indent=2)
45
+ return formatted_json_data
46
+
47
+
48
+ def load_json_data_in_fact(json_path):
49
+ with open(json_path, "r", encoding="utf-8") as file:
50
+ json_data = json.load(file)
51
+ return json_data
52
+
53
+
54
+ def load_yaml_data_in_fact(yml_path=yml_config):
55
+ with open(yml_path, "r", encoding="utf-8") as file:
56
+ yml = yaml.safe_load(file)
57
+ # data = file.read()
58
+ return yml
59
+
60
+
61
+ def fill_openi_token(token: str):
62
+ yml = load_yaml_data_in_fact()
63
+ yml["mirror"] = "openi"
64
+ yml["openi_token"] = token
65
+ write_yaml_data_in_fact(yml)
66
+ msg = "openi 令牌已填写完成"
67
+ logger.info(msg)
68
+ return gr.Textbox(value=msg), gr.Code(value=load_yaml_data_in_raw())
69
+
70
+
71
+ def load_train_param(cfg_path):
72
+ yml = load_yaml_data_in_fact()
73
+ data_path = yml["dataset_path"]
74
+ train_json_path = os.path.join(data_path, cfg_path).replace("\\", "/")
75
+ json_data = load_json_data_in_fact(train_json_path)
76
+ bs = json_data["train"]["batch_size"]
77
+ nc = json_data["train"].get("keep_ckpts", 5)
78
+ li = json_data["train"]["log_interval"]
79
+ ei = json_data["train"]["eval_interval"]
80
+ ep = json_data["train"]["epochs"]
81
+ lr = json_data["train"]["learning_rate"]
82
+ ver = json_data["version"]
83
+ msg = f"加载训练配置文件: {train_json_path}"
84
+ logger.info(msg)
85
+ return (
86
+ gr.Textbox(value=msg),
87
+ gr.Code(label=train_json_path, value=load_yaml_data_in_raw(train_json_path)),
88
+ gr.Slider(value=bs),
89
+ gr.Slider(value=nc),
90
+ gr.Slider(value=li),
91
+ gr.Slider(value=ei),
92
+ gr.Slider(value=ep),
93
+ gr.Slider(value=lr),
94
+ gr.Dropdown(value=ver),
95
+ )
96
+
97
+
98
+ def write_yaml_data_in_fact(yml, yml_path=yml_config):
99
+ with open(yml_path, "w", encoding="utf-8") as file:
100
+ yaml.safe_dump(yml, file, allow_unicode=True)
101
+ # data = file.read()
102
+ return yml
103
+
104
+
105
+ def write_json_data_in_fact(json_path, json_data):
106
+ with open(json_path, "w", encoding="utf-8") as file:
107
+ json.dump(json_data, file, ensure_ascii=False, indent=2)
108
+
109
+
110
+ def check_if_exists_model(paths: list[str]):
111
+ check_results = {
112
+ path: os.path.exists(path) and os.path.isfile(path) for path in paths
113
+ }
114
+ val = [path for path, exists in check_results.items() if exists]
115
+ return val
116
+
117
+
118
+ def check_bert_models():
119
+ return gr.CheckboxGroup(value=check_if_exists_model(bert_model_paths))
120
+
121
+
122
+ def check_emo_models():
123
+ return gr.CheckboxGroup(value=check_if_exists_model(emo_model_paths))
124
+
125
+
126
+ def check_base_models():
127
+ yml = load_yaml_data_in_fact()
128
+ data_path = yml["dataset_path"]
129
+ models_dir = yml["train_ms"]["model"]
130
+ model_paths = [
131
+ os.path.join(data_path, models_dir, p).replace("\\", "/")
132
+ for p in train_base_model_paths
133
+ ]
134
+ return gr.CheckboxGroup(
135
+ label="检测底模状态",
136
+ info="最好去下载底模进行训练",
137
+ choices=model_paths,
138
+ value=check_if_exists_model(model_paths),
139
+ interactive=False,
140
+ )
141
+
142
+
143
+ def modify_data_path(data_path):
144
+ yml = load_yaml_data_in_fact()
145
+ yml["dataset_path"] = data_path
146
+ write_yaml_data_in_fact(yml)
147
+ txt_box = gr.Textbox(value=data_path)
148
+ return (
149
+ gr.Dropdown(value=data_path),
150
+ txt_box,
151
+ txt_box,
152
+ txt_box,
153
+ gr.Code(value=load_yaml_data_in_raw()),
154
+ check_base_models(),
155
+ )
156
+
157
+
158
+ def modify_preprocess_param(trans_path, cfg_path, val_per_spk, max_val_total):
159
+ yml = load_yaml_data_in_fact()
160
+ data_path = yml["dataset_path"]
161
+ yml["preprocess_text"]["transcription_path"] = trans_path
162
+ yml["preprocess_text"]["config_path"] = cfg_path
163
+ yml["preprocess_text"]["val_per_spk"] = val_per_spk
164
+ yml["preprocess_text"]["max_val_total"] = max_val_total
165
+ write_yaml_data_in_fact(yml)
166
+ whole_path = os.path.join(data_path, cfg_path).replace("\\", "/")
167
+ logger.info("预处理配置: ", whole_path)
168
+ if not os.path.exists(whole_path):
169
+ os.makedirs(os.path.dirname(whole_path), exist_ok=True)
170
+ shutil.copy(default_config_path, os.path.dirname(whole_path))
171
+ return gr.Dropdown(value=trans_path), gr.Code(value=load_yaml_data_in_raw())
172
+
173
+
174
+ def modify_resample_path(in_dir, out_dir, sr):
175
+ yml = load_yaml_data_in_fact()
176
+ yml["resample"]["in_dir"] = in_dir
177
+ yml["resample"]["out_dir"] = out_dir
178
+ yml["resample"]["sampling_rate"] = int(sr)
179
+ write_yaml_data_in_fact(yml)
180
+ msg = f"重采样参数已更改: [{in_dir}, {out_dir}, {sr}]\n"
181
+ logger.info(msg)
182
+ return (
183
+ gr.Textbox(value=in_dir),
184
+ gr.Textbox(value=out_dir),
185
+ gr.Textbox(value=msg),
186
+ gr.Dropdown(value=sr),
187
+ gr.Code(value=load_yaml_data_in_raw()),
188
+ )
189
+
190
+
191
+ def modify_bert_config(cfg_path, nps, dev, multi):
192
+ yml = load_yaml_data_in_fact()
193
+ data_path = yml["dataset_path"]
194
+ yml["bert_gen"]["config_path"] = cfg_path
195
+ yml["bert_gen"]["num_processes"] = int(nps)
196
+ yml["bert_gen"]["device"] = dev
197
+ yml["bert_gen"]["use_multi_device"] = multi
198
+ write_yaml_data_in_fact(yml)
199
+ whole_path = os.path.join(data_path, cfg_path).replace("\\", "/")
200
+ logger.info("bert配置路径: ", whole_path)
201
+ if not os.path.exists(whole_path):
202
+ os.makedirs(os.path.dirname(whole_path), exist_ok=True)
203
+ shutil.copy(default_config_path, os.path.dirname(whole_path))
204
+ return (
205
+ gr.Textbox(value=cfg_path),
206
+ gr.Slider(value=int(nps)),
207
+ gr.Dropdown(value=dev),
208
+ gr.Radio(value=multi),
209
+ gr.Code(value=load_yaml_data_in_raw()),
210
+ )
211
+
212
+
213
+ def modify_train_path(model, cfg_path):
214
+ yml = load_yaml_data_in_fact()
215
+ yml["train_ms"]["config_path"] = cfg_path
216
+ yml["train_ms"]["model"] = model
217
+ write_yaml_data_in_fact(yml)
218
+ logger.info(f"训练配置文件路径: {cfg_path}\n")
219
+ logger.info(f"训练模型文件夹路径: {model}")
220
+ return (
221
+ gr.Textbox(value=model),
222
+ gr.Textbox(value=cfg_path),
223
+ gr.Code(value=load_yaml_data_in_raw()),
224
+ check_base_models(),
225
+ )
226
+
227
+
228
+ def modify_train_param(bs, nc, li, ei, ep, lr, ver):
229
+ yml = load_yaml_data_in_fact()
230
+ data_path = yml["dataset_path"]
231
+ cfg_path = yml["train_ms"]["config_path"]
232
+ ok = False
233
+ whole_path = os.path.join(data_path, cfg_path).replace("\\", "/")
234
+ logger.info("config_path: ", whole_path)
235
+ if not os.path.exists(whole_path):
236
+ os.makedirs(os.path.dirname(whole_path), exist_ok=True)
237
+ shutil.copy(default_config_path, os.path.dirname(whole_path))
238
+ if os.path.exists(whole_path) and os.path.isfile(whole_path):
239
+ ok = True
240
+ with open(whole_path, "r", encoding="utf-8") as file:
241
+ json_data = json.load(file)
242
+ json_data["train"]["batch_size"] = bs
243
+ json_data["train"]["keep_ckpts"] = nc
244
+ json_data["train"]["log_interval"] = li
245
+ json_data["train"]["eval_interval"] = ei
246
+ json_data["train"]["epochs"] = ep
247
+ json_data["train"]["learning_rate"] = lr
248
+ json_data["version"] = ver
249
+ with open(whole_path, "w", encoding="utf-8") as file:
250
+ json.dump(json_data, file, ensure_ascii=False, indent=2)
251
+ msg = f"成功更改训练参数! [{bs},{nc},{li},{ei},{ep},{lr}]"
252
+ logger.info(msg)
253
+ else:
254
+ msg = f"打开训练配置文件时出现错误: {whole_path}\n" f"该文件不存在或损坏,现在打开默认配置文件"
255
+ logger.error(msg)
256
+ return gr.Textbox(value=msg), gr.Code(
257
+ label=whole_path if ok else default_config_path,
258
+ value=load_json_data_in_raw(whole_path)
259
+ if ok
260
+ else load_json_data_in_raw(default_config_path),
261
+ )
262
+
263
+
264
+ def modify_infer_param(model_path, config_path, port, share, debug, ver):
265
+ yml = load_yaml_data_in_fact()
266
+ data_path = yml["dataset_path"]
267
+ yml["webui"]["model"] = os.path.relpath(model_path, start=data_path)
268
+ yml["webui"]["config_path"] = os.path.relpath(config_path, start=data_path)
269
+ port = int(port)
270
+ port = port if 0 <= port <= 65535 else 10086
271
+ yml["webui"]["port"] = port
272
+ yml["webui"]["share"] = share
273
+ yml["webui"]["debug"] = debug
274
+ write_yaml_data_in_fact(yml)
275
+ json_data = load_json_data_in_fact(config_path)
276
+ json_data["version"] = ver
277
+ write_json_data_in_fact(config_path, json_data)
278
+ msg = f"修改推理配置文件成功: [{model_path}, {config_path}, {port}, {ver}]"
279
+ logger.info(msg)
280
+ return (
281
+ gr.Textbox(value=msg),
282
+ gr.Code(value=load_yaml_data_in_raw()),
283
+ gr.Code(
284
+ label=config_path,
285
+ value=load_json_data_in_raw(config_path)
286
+ if os.path.exists(config_path)
287
+ else load_json_data_in_raw(default_config_path),
288
+ ),
289
+ )
290
+
291
+
292
+ def get_status():
293
+ """获取电脑运行状态"""
294
+ cpu_percent = psutil.cpu_percent(interval=1)
295
+ memory_info = psutil.virtual_memory()
296
+ memory_total = memory_info.total
297
+ memory_available = memory_info.available
298
+ memory_used = memory_info.used
299
+ memory_percent = memory_info.percent
300
+ gpuInfo = []
301
+ devices = ["cpu"]
302
+ for i in range(torch.cuda.device_count()):
303
+ devices.append(f"cuda:{i}")
304
+ if torch.cuda.device_count() > 0:
305
+ gpus = GPUtil.getGPUs()
306
+ for gpu in gpus:
307
+ gpuInfo.append(
308
+ {
309
+ "GPU编号": gpu.id,
310
+ "GPU负载": f"{gpu.load} %",
311
+ "专用GPU内存": {
312
+ "总内存": f"{gpu.memoryTotal} MB",
313
+ "已使用": f"{gpu.memoryUsed} MB",
314
+ "空闲": f"{gpu.memoryFree} MB",
315
+ },
316
+ }
317
+ )
318
+ status_data = {
319
+ "devices": devices,
320
+ "CPU占用率": f"{cpu_percent} %",
321
+ "总内存": f"{memory_total // (1024 * 1024)} MB",
322
+ "可用内存": f"{memory_available // (1024 * 1024)} MB",
323
+ "已使用内存": f"{memory_used // (1024 * 1024)} MB",
324
+ "百分数": f"{memory_percent} %",
325
+ "gpu信息": gpuInfo,
326
+ }
327
+ formatted_json_data = json.dumps(status_data, ensure_ascii=False, indent=2)
328
+ logger.info(formatted_json_data)
329
+ return str(formatted_json_data)
330
+
331
+
332
+ def get_gpu_status():
333
+ return gr.Code(value=get_status())
334
+
335
+
336
+ def list_infer_models():
337
+ yml = load_yaml_data_in_fact()
338
+ data_path = yml["dataset_path"]
339
+ inf_models, json_files = [], []
340
+ for root, dirs, files in os.walk(data_path):
341
+ for file in files:
342
+ filepath = os.path.join(root, file).replace("\\", "/")
343
+ if file.startswith("G_") and file.lower().endswith(".pth"):
344
+ inf_models.append(filepath)
345
+ elif file.lower().endswith(".json"):
346
+ json_files.append(filepath)
347
+ logger.info("找到推理模型文件: " + str(inf_models))
348
+ logger.info("找到推理配置文件: " + str(json_files))
349
+ return gr.Dropdown(choices=inf_models), gr.Dropdown(choices=json_files)
350
+
351
+
352
+ def do_resample(nps):
353
+ yml = load_yaml_data_in_fact()
354
+ data_path = yml["dataset_path"]
355
+ in_dir = yml["resample"]["in_dir"]
356
+ comp_in_dir = os.path.join(os.path.abspath(data_path), in_dir).replace("\\", "/")
357
+ logger.info(f"\n重采样路径: {comp_in_dir}")
358
+ cmd = f"python resample.py --processes {nps}"
359
+ logger.info(cmd)
360
+ subprocess.run(cmd, shell=True)
361
+ return gr.Textbox(value="重采样完成!")
362
+
363
+
364
+ def do_transcript(lang, workers):
365
+ yml = load_yaml_data_in_fact()
366
+ data_path = yml["dataset_path"]
367
+ in_dir = yml["resample"]["in_dir"]
368
+ comp_in_dir = os.path.join(os.path.abspath(data_path), in_dir).replace("\\", "/")
369
+ logger.info(f"\n转写文件夹路径: {comp_in_dir}")
370
+ cmd = f'python asr_transcript.py -f "{comp_in_dir}" -l {lang} -w {workers}'
371
+ logger.info(cmd)
372
+ subprocess.run(cmd, shell=True)
373
+ return gr.Textbox(value=f"\n转写文件夹路径: {comp_in_dir}\n转写到.lab完成!")
374
+
375
+
376
+ def do_extract(raw_path, lang, unclean, char_name):
377
+ yml = load_yaml_data_in_fact()
378
+ data_path = yml["dataset_path"]
379
+ lab_path = os.path.join(os.path.abspath(data_path), raw_path).replace("\\", "/")
380
+ unclean_path = os.path.join(
381
+ data_path, os.path.splitext(unclean)[0] + ".txt"
382
+ ).replace("\\", "/")
383
+ logger.info(f"\n提取转写文本路径: {lab_path}")
384
+ lab_ok = False
385
+ for root, _, files in os.walk(lab_path):
386
+ for f_name in files:
387
+ if str(f_name).lower().endswith(".lab"):
388
+ lab_ok = True
389
+ break
390
+ if lab_ok:
391
+ break
392
+
393
+ if os.path.exists(lab_path) and os.path.isdir(lab_path):
394
+ if lab_ok:
395
+ cmd = f'python extract_list.py -f "{lab_path}" -l {lang} -n "{char_name}" -o "{unclean_path}"'
396
+ logger.info(cmd)
397
+ subprocess.run(cmd, shell=True)
398
+ msg = f"提取完成!生成如下文件: {unclean_path}"
399
+ logger.info(msg)
400
+ else:
401
+ msg = "未找到提取转写文本路径下的.lab文件!"
402
+ logger.warning(msg)
403
+ else:
404
+ msg = "路径未选择正确!"
405
+ logger.error(msg)
406
+ return gr.Textbox(value=msg)
407
+
408
+
409
+ def do_clean_list(ban_chars, unclean, clean):
410
+ yml = load_yaml_data_in_fact()
411
+ data_path = yml["dataset_path"]
412
+ unclean_path = os.path.join(data_path, unclean)
413
+ clean_path = os.path.join(data_path, clean)
414
+ if os.path.exists(unclean_path) and os.path.isfile(unclean_path):
415
+ cmd = f'python clean_list.py -c "{ban_chars}" -i "{unclean_path}" -o "{clean_path}"'
416
+ logger.info(cmd)
417
+ subprocess.run(cmd, shell=True)
418
+ msg = "清洗标注文本完成!"
419
+ logger.info(msg)
420
+ else:
421
+ msg = "未找到可清洗标注文本,请到2.2节重新生成!"
422
+ logger.warning(msg)
423
+ return gr.Textbox(value=msg)
424
+
425
+
426
+ def do_preprocess_text():
427
+ yml = load_yaml_data_in_fact()
428
+ data_path = yml["dataset_path"]
429
+ trans_path = yml["preprocess_text"]["transcription_path"]
430
+ comp_trans_path = os.path.join(os.path.abspath(data_path), trans_path).replace(
431
+ "\\", "/"
432
+ )
433
+ logger.info(f"\n清洗后标注文本文件路径: {comp_trans_path}")
434
+ if os.path.exists(comp_trans_path) and os.path.isfile(comp_trans_path):
435
+ cmd = "python preprocess_text.py"
436
+ logger.info(cmd)
437
+ subprocess.run(cmd, shell=True)
438
+ msg = "文本预处理完成!"
439
+ else:
440
+ msg = "\n清洗后标注文本文件不存在或失效!"
441
+ logger.info(msg)
442
+ return gr.Textbox(value=msg)
443
+
444
+
445
+ def do_bert_gen():
446
+ yml = load_yaml_data_in_fact()
447
+ data_path = yml["dataset_path"]
448
+ train_list_path = yml["preprocess_text"]["train_path"]
449
+ val_list_path = yml["preprocess_text"]["val_path"]
450
+ comp_t_path = os.path.join(os.path.abspath(data_path), train_list_path).replace(
451
+ "\\", "/"
452
+ )
453
+ comp_v_path = os.path.join(os.path.abspath(data_path), val_list_path).replace(
454
+ "\\", "/"
455
+ )
456
+ if os.path.exists(comp_t_path) and os.path.isfile(comp_t_path):
457
+ subprocess.run("python bert_gen.py", shell=True)
458
+ msg = "bert文件生成完成!"
459
+ logger.info(msg)
460
+ else:
461
+ msg = f"未找到训练集和验证集文本!\ntrain: {comp_t_path}\nval:{comp_v_path}"
462
+ logger.error(msg)
463
+ return gr.Textbox(value=msg)
464
+
465
+
466
+ def modify_emo_gen(emo_cfg, emo_nps, emo_device):
467
+ yml = load_yaml_data_in_fact()
468
+ data_path = yml["dataset_path"]
469
+ yml["emo_gen"]["config_path"] = emo_cfg
470
+ yml["emo_gen"]["num_processes"] = emo_nps
471
+ yml["emo_gen"]["device"] = emo_device
472
+ write_yaml_data_in_fact(yml)
473
+ comp_emo_cfg = os.path.join(os.path.abspath(data_path), emo_cfg).replace("\\", "/")
474
+ if not os.path.exists(comp_emo_cfg):
475
+ os.makedirs(os.path.dirname(comp_emo_cfg), exist_ok=True)
476
+ shutil.copy(default_config_path, os.path.dirname(comp_emo_cfg))
477
+ msg = f"修改emo配置参数: [配置路径:{comp_emo_cfg}, 处理数:{emo_nps}, 设备:{emo_device}]"
478
+ logger.info(msg)
479
+ return gr.Textbox(value=msg), gr.Code(value=load_yaml_data_in_raw())
480
+
481
+
482
+ def do_emo_gen():
483
+ yml = load_yaml_data_in_fact()
484
+ data_path = yml["dataset_path"]
485
+ emo_config_path = yml["emo_gen"]["config_path"]
486
+ comp_emo_path = os.path.join(os.path.abspath(data_path), emo_config_path).replace(
487
+ "\\", "/"
488
+ )
489
+ if os.path.exists(comp_emo_path) and os.path.isfile(comp_emo_path):
490
+ subprocess.run("python emo_gen.py", shell=True)
491
+ msg = "emo.npy文件生成完成!"
492
+ logger.info(msg)
493
+ else:
494
+ msg = f"选定路径下未找到配置文件!\n需要的config路径 : {comp_emo_path}"
495
+ logger.error(msg)
496
+
497
+ return gr.Textbox(value=msg)
498
+
499
+
500
+ def do_my_train():
501
+ yml = load_yaml_data_in_fact()
502
+ n_gpus = torch.cuda.device_count()
503
+ # subprocess.run(f'python train_ms.py', shell=True)
504
+ if os.path.exists(r"..\vits\python.exe") and os.path.isfile(r"..\vits\python.exe"):
505
+ cmd = (
506
+ r"..\vits\python ..\vits\Scripts\torchrun.exe "
507
+ f"--nproc_per_node={n_gpus} train_ms.py"
508
+ )
509
+ else:
510
+ cmd = f"torchrun --nproc_per_node={n_gpus} train_ms.py"
511
+
512
+ subprocess.Popen(cmd, shell=True)
513
+ train_port = yml["train_ms"]["env"]["MASTER_PORT"]
514
+ train_addr = yml["train_ms"]["env"]["MASTER_ADDR"]
515
+ url = f"env://{train_addr}:{train_port}"
516
+ msg = f"训练开始!\nMASTER_URL: {url}\n使用gpu数:{n_gpus}\n推荐按下终止训练按钮来结束!"
517
+ logger.info(msg)
518
+ return gr.Textbox(value=msg)
519
+
520
+
521
+ def do_tensorboard():
522
+ yml = load_yaml_data_in_fact()
523
+ data_path = yml["dataset_path"]
524
+ train_model_dir = yml["train_ms"]["model"]
525
+ whole_dir = os.path.join(data_path, train_model_dir).replace("\\", "/")
526
+ if os.path.exists(r"..\vits\python.exe") and os.path.isfile(r"..\vits\python.exe"):
527
+ first_cmd = r"..\vits\python ..\vits\Scripts\tensorboard.exe "
528
+ else:
529
+ first_cmd = "tensorboard "
530
+ tb_cmd = (
531
+ first_cmd + f"--logdir={whole_dir} "
532
+ f"--port={11451} "
533
+ f'--window_title="训练情况一览" '
534
+ f"--reload_interval={120}"
535
+ )
536
+ subprocess.Popen(tb_cmd, shell=True)
537
+ url = f"http://localhost:{11451}"
538
+ webbrowser.open(url=url)
539
+ msg = tb_cmd + "\n" + url
540
+ logger.info(msg)
541
+ return gr.Textbox(value=msg)
542
+
543
+
544
+ def do_webui_infer():
545
+ yml = load_yaml_data_in_fact()
546
+ data_path = yml["dataset_path"]
547
+ model_path = yml["webui"]["model"]
548
+ config_path = yml["webui"]["config_path"]
549
+ comp_m_path = os.path.join(os.path.abspath(data_path), model_path)
550
+ comp_c_path = os.path.join(os.path.abspath(data_path), config_path)
551
+ if os.path.exists(comp_c_path) and os.path.exists(comp_m_path):
552
+ webui_port = yml["webui"]["port"]
553
+ subprocess.Popen("python webui.py", shell=True)
554
+ url = f"http://localhost:{webui_port} | http://127.0.0.1:{webui_port}"
555
+ msg = f"推理端已开启, 到控制台中复制网址打开页面\n{url}\n选择的模型:{model_path}"
556
+ logger.info(msg)
557
+ else:
558
+ msg = f"未找到有效的模型或配置文件!\n模型路径:{comp_m_path}\n配置路径:{comp_c_path}"
559
+ logger.error(msg)
560
+ return gr.Textbox(value=msg)
561
+
562
+
563
+ def compress_model(cfg_path, in_path, out_path):
564
+ subprocess.Popen(
565
+ "python compress_model.py" f" -c {cfg_path}" f" -i {in_path}", shell=True
566
+ )
567
+ msg = "到控制台中查看压缩结果"
568
+ logger.info(msg)
569
+ return gr.Textbox(value=msg)
570
+
571
+
572
+ def kill_specific_process_linux(cmd):
573
+ try:
574
+ output = subprocess.check_output(["pgrep", "-f", cmd], text=True)
575
+ pids = output.strip().split("\n")
576
+
577
+ for pid in pids:
578
+ if pid:
579
+ logger.critical(f"终止进程: {pid}")
580
+ os.kill(int(pid), signal.SIGTERM)
581
+ # os.kill(int(pid), signal.SIGKILL)
582
+ except subprocess.CalledProcessError:
583
+ logger.error("没有找到匹配的进程。")
584
+ except Exception as e:
585
+ logger.error(f"发生错误: {e}")
586
+
587
+
588
+ def kill_specific_process_windows(cmd):
589
+ try:
590
+ # 使用tasklist和findstr来找到匹配特定命令行模式的进程
591
+ output = subprocess.check_output(
592
+ f'tasklist /FO CSV /V | findstr /C:"{cmd}"', shell=True, text=True
593
+ )
594
+ lines = output.strip().split("\n")
595
+
596
+ for line in lines:
597
+ if line:
598
+ pid = line.split(",")[1].strip('"')
599
+ logger.critical(f"终止进程: {pid}")
600
+ subprocess.run(["taskkill", "/PID", pid, "/F"], shell=True) # 强制终止
601
+ except subprocess.CalledProcessError:
602
+ logger.error(f"没有找到匹配的{cmd}进程。")
603
+ except Exception as e:
604
+ logger.error(f"发生错误: {e}")
605
+
606
+
607
+ def stop_train_ms():
608
+ yml = load_yaml_data_in_fact()
609
+ train_port = yml["train_ms"]["env"]["MASTER_PORT"]
610
+ train_addr = yml["train_ms"]["env"]["MASTER_ADDR"]
611
+ if platform.system() == "Windows":
612
+ kill_specific_process_windows("torchrun")
613
+ else:
614
+ kill_specific_process_linux("torchrun")
615
+ url = f"env://{train_addr}:{train_port}"
616
+ msg = f"训练结束!\nMASTER_URL: {url}"
617
+ logger.critical(msg)
618
+ return gr.Textbox(value=msg)
619
+
620
+
621
+ def stop_tensorboard():
622
+ if platform.system() == "Windows":
623
+ kill_specific_process_windows("tensorboard")
624
+ else:
625
+ kill_specific_process_linux("tensorboard")
626
+ msg = "关闭tensorboard!\n"
627
+ logger.critical(msg)
628
+ return gr.Textbox(value=msg)
629
+
630
+
631
+ def stop_webui_infer():
632
+ yml = load_yaml_data_in_fact()
633
+ webui_port = yml["webui"]["port"]
634
+ if platform.system() == "Linux":
635
+ kill_specific_process_linux("python webui.py")
636
+ else:
637
+ kill_specific_process_windows("python webui.py")
638
+ msg = f"尝试终止推理进程,请到控制台查看情况\nport={webui_port}"
639
+ logger.critical(msg)
640
+ return gr.Textbox(value=msg)
641
+
642
+
643
+ if __name__ == "__main__":
644
+ init_yml = load_yaml_data_in_fact()
645
+ with gr.Blocks(
646
+ title="Bert-VITS-2-v2.0-管理器",
647
+ theme=gr.themes.Soft(),
648
+ css=os.path.abspath("./css/custom.css"),
649
+ ) as app:
650
+ with gr.Row():
651
+ with gr.Tabs():
652
+ with gr.TabItem("首页"):
653
+ gr.Markdown(
654
+ """
655
+ ## Bert-VITS2-v2.0 可视化界面
656
+ #### Copyright/Powered by 怕吃辣滴辣子酱
657
+ #### 许可: [AGPL 3.0 Licence](https://github.com/AnyaCoder/Bert-VITS2/blob/master/LICENSE)
658
+ #### 请订阅我的频道:
659
+ 1. Bilibili: [spicysama](https://space.bilibili.com/47278440)
660
+ 2. github: [AnyaCoder](https://github.com/AnyaCoder)
661
+
662
+ ### 严禁将此项目用于一切违反《中华人民共和国宪法》,《中华人民共和国刑法》,《中华人民共和国治安管理处罚法》和《中华人民共和国民法典》之用途。
663
+ ### 严禁用于任何政治相关用途。
664
+ ## References
665
+ + [anyvoiceai/MassTTS](https://github.com/anyvoiceai/MassTTS)
666
+ + [jaywalnut310/vits](https://github.com/jaywalnut310/vits)
667
+ + [p0p4k/vits2_pytorch](https://github.com/p0p4k/vits2_pytorch)
668
+ + [svc-develop-team/so-vits-svc](https://github.com/svc-develop-team/so-vits-svc)
669
+ + [PaddlePaddle/PaddleSpeech](https://github.com/PaddlePaddle/PaddleSpeech)
670
+ ## 感谢所有贡献者作出的努力
671
+ <a href="https://github.com/AnyaCoder/Bert-VITS2/graphs/contributors">
672
+ <img src="https://contrib.rocks/image?repo=AnyaCoder/Bert-VITS2" />
673
+ </a>
674
+
675
+ Made with [contrib.rocks](https://contrib.rocks).
676
+
677
+ """
678
+ )
679
+ with gr.TabItem("填入openi token"):
680
+ with gr.Row():
681
+ gr.Markdown(
682
+ """
683
+ ### 为了后续步骤中能够方便地自动下载模型,强烈推荐完成这一步骤!
684
+ ### 去openi官网注册并登录后:
685
+ ### [点击此处跳转到openi官网](https://openi.pcl.ac.cn/)
686
+ ### , 点击右上角`个人头像`-> `设置` -> `应用`, 生成令牌(token)
687
+ ### 复制token, 粘贴到下面的框框, 点击确认
688
+ """
689
+ )
690
+ with gr.Row():
691
+ openi_token_box = gr.Textbox(
692
+ label="填入openi token", value=init_yml["openi_token"]
693
+ )
694
+ with gr.Row():
695
+ openi_token_btn = gr.Button(value="确认填写", variant="primary")
696
+ with gr.Row():
697
+ openi_token_status = gr.Textbox(label="状态信息")
698
+
699
+ with gr.TabItem("模型检测"):
700
+ CheckboxGroup_bert_models = gr.CheckboxGroup(
701
+ label="检测bert模型状态",
702
+ info="对应文件夹下必须有对应的模型文件(填入openi token后,则后续步骤中会自动下载)",
703
+ choices=bert_model_paths,
704
+ value=check_if_exists_model(bert_model_paths),
705
+ interactive=False,
706
+ )
707
+ check_pth_btn1 = gr.Button(value="检查bert模型状态")
708
+ CheckboxGroup_emo_models = gr.CheckboxGroup(
709
+ label="检测emo模型状态",
710
+ info="对应文件夹下必须有对应的模型文件",
711
+ choices=emo_model_paths,
712
+ value=check_if_exists_model(emo_model_paths),
713
+ interactive=False,
714
+ )
715
+ check_pth_btn2 = gr.Button(value="检查emo模型状态")
716
+ with gr.TabItem("数据处理"):
717
+ with gr.Row():
718
+ dropdown_data_path = gr.Dropdown(
719
+ label="选择数据集存放路径 (右侧的dataset_path)",
720
+ info="详细说明可见右侧带注释的yaml文件",
721
+ interactive=True,
722
+ allow_custom_value=True,
723
+ choices=[init_yml["dataset_path"]],
724
+ value=init_yml["dataset_path"],
725
+ )
726
+ with gr.Row():
727
+ data_path_btn = gr.Button(value="确认更改存放路径", variant="primary")
728
+ with gr.Tabs():
729
+ with gr.TabItem("1. 音频重采样"):
730
+ with gr.Row():
731
+ resample_in_box = gr.Textbox(
732
+ label="输入音频文件夹in_dir",
733
+ value=init_yml["resample"]["in_dir"],
734
+ lines=1,
735
+ interactive=True,
736
+ )
737
+ resample_out_box = gr.Textbox(
738
+ label="输出音频文件夹out_dir",
739
+ lines=1,
740
+ value=init_yml["resample"]["out_dir"],
741
+ interactive=True,
742
+ )
743
+ with gr.Row():
744
+ dropdown_resample_sr = gr.Dropdown(
745
+ label="输出采样率(Hz)",
746
+ choices=["16000", "22050", "44100", "48000"],
747
+ value="44100",
748
+ )
749
+ slider_resample_nps = gr.Slider(
750
+ label="采样用的CPU核心数",
751
+ minimum=1,
752
+ maximum=64,
753
+ step=1,
754
+ value=2,
755
+ )
756
+ with gr.Row():
757
+ resample_config_btn = gr.Button(
758
+ value="确认重采样配置",
759
+ variant="secondary",
760
+ )
761
+ resample_btn = gr.Button(
762
+ value="1. 音频重采样",
763
+ variant="primary",
764
+ )
765
+ with gr.Row():
766
+ resample_status = gr.Textbox(
767
+ label="重采样结果",
768
+ placeholder="执行重采样后可查看",
769
+ lines=3,
770
+ interactive=False,
771
+ )
772
+ with gr.TabItem("2. 转写文本生成"):
773
+ with gr.Row():
774
+ dropdown_lang = gr.Dropdown(
775
+ label="选择语言",
776
+ info="ZH中文,JP日语,EN英语",
777
+ choices=["ZH", "JP", "EN"],
778
+ value="ZH",
779
+ )
780
+ slider_transcribe = gr.Slider(
781
+ label="转写进程数",
782
+ info="目的路径与前一节一致\n 重采样的输入路径",
783
+ minimum=1,
784
+ maximum=10,
785
+ step=1,
786
+ value=1,
787
+ interactive=True,
788
+ )
789
+ clean_txt_box = gr.Textbox(
790
+ label="非法字符集",
791
+ info="在此文本框内出现的字符都会被整行删除",
792
+ lines=1,
793
+ value="{}<>",
794
+ interactive=True,
795
+ )
796
+ with gr.Row():
797
+ unclean_box = gr.Textbox(
798
+ label="未清洗的文本",
799
+ info="仅将.lab提取到这个文件里, 请保持txt格式",
800
+ lines=1,
801
+ value=os.path.splitext(
802
+ init_yml["preprocess_text"][
803
+ "transcription_path"
804
+ ]
805
+ )[0]
806
+ + ".txt",
807
+ interactive=True,
808
+ )
809
+ clean_box = gr.Textbox(
810
+ label="已清洗的文本",
811
+ info="将未清洗的文本做去除非法字符集处理后的文本",
812
+ lines=1,
813
+ value=init_yml["preprocess_text"][
814
+ "transcription_path"
815
+ ],
816
+ interactive=True,
817
+ )
818
+ char_name_box = gr.Textbox(
819
+ label="输入角色名",
820
+ info="区分说话人用",
821
+ lines=1,
822
+ placeholder="填入一个名称",
823
+ interactive=True,
824
+ )
825
+ with gr.Row():
826
+ transcribe_btn = gr.Button(
827
+ value="2.1 转写文本", interactive=True
828
+ )
829
+ extract_list_btn = gr.Button(
830
+ value="2.2 合成filelist",
831
+ )
832
+ clean_trans_btn = gr.Button(value="2.3 清洗标注")
833
+ with gr.Row():
834
+ preprocess_status_box = gr.Textbox(label="标注状态")
835
+ with gr.TabItem("3. 文本预处理"):
836
+ with gr.Row():
837
+ slider_val_per_spk = gr.Slider(
838
+ label="每个speaker的验证集条数",
839
+ info="TensorBoard里的eval音频展示条目",
840
+ minimum=1,
841
+ maximum=20,
842
+ step=1,
843
+ value=init_yml["preprocess_text"]["val_per_spk"],
844
+ )
845
+ slider_max_val_total = gr.Slider(
846
+ label="验证集最大条数",
847
+ info="多于此项的会被截断并放到训练集中",
848
+ minimum=8,
849
+ maximum=160,
850
+ step=8,
851
+ value=init_yml["preprocess_text"]["max_val_total"],
852
+ )
853
+ with gr.Row():
854
+ dropdown_filelist_path = gr.Dropdown(
855
+ interactive=True,
856
+ label="输入filelist路径",
857
+ allow_custom_value=True,
858
+ choices=[
859
+ init_yml["preprocess_text"][
860
+ "transcription_path"
861
+ ]
862
+ ],
863
+ value=init_yml["preprocess_text"][
864
+ "transcription_path"
865
+ ],
866
+ )
867
+ preprocess_config_box = gr.Textbox(
868
+ label="预处理配置文件路径",
869
+ value=init_yml["preprocess_text"]["config_path"],
870
+ )
871
+ with gr.Row():
872
+ preprocess_config_btn = gr.Button(value="更新预处理配置文件")
873
+ preprocess_text_btn = gr.Button(
874
+ value="标注文本预处理", variant="primary"
875
+ )
876
+ with gr.Row():
877
+ label_status = gr.Textbox(label="转写状态")
878
+ with gr.TabItem("4. bert_gen"):
879
+ with gr.Row():
880
+ bert_dataset_box = gr.Textbox(
881
+ label="数据集存放路径",
882
+ text_align="right",
883
+ value=str(init_yml["dataset_path"]).rstrip("/"),
884
+ lines=1,
885
+ interactive=False,
886
+ scale=10,
887
+ )
888
+ gr.Markdown(
889
+ """
890
+ <br></br>
891
+ ## +
892
+ """
893
+ )
894
+ bert_config_box = gr.Textbox(
895
+ label="bert_gen配置文件路径",
896
+ text_align="left",
897
+ value=init_yml["bert_gen"]["config_path"],
898
+ lines=1,
899
+ interactive=True,
900
+ scale=10,
901
+ )
902
+ with gr.Row():
903
+ slider_bert_nps = gr.Slider(
904
+ label="bert_gen并行处理数",
905
+ minimum=1,
906
+ maximum=12,
907
+ step=1,
908
+ value=init_yml["bert_gen"]["num_processes"],
909
+ )
910
+ dropdown_bert_dev = gr.Dropdown(
911
+ label="bert_gen处理设备",
912
+ choices=["cuda", "cpu"],
913
+ value=init_yml["bert_gen"]["device"],
914
+ )
915
+ radio_bert_multi = gr.Radio(
916
+ label="使用多卡推理", choices=[True, False], value=False
917
+ )
918
+ with gr.Row():
919
+ bert_config_btn = gr.Button(value="确认更改bert配置项")
920
+ bert_gen_btn = gr.Button(
921
+ value="Go! Bert Gen!", variant="primary"
922
+ )
923
+ with gr.Row():
924
+ bert_status = gr.Textbox(label="状态信息")
925
+ with gr.TabItem("5. emo_gen"):
926
+ with gr.Row():
927
+ emo_config_box = gr.Textbox(
928
+ label="emo_gen配置文件路径",
929
+ info="找一找你的config.json路径,相对于数据集路径",
930
+ value=init_yml["emo_gen"]["config_path"],
931
+ lines=1,
932
+ interactive=True,
933
+ scale=10,
934
+ )
935
+ with gr.Row():
936
+ slider_emo_nps = gr.Slider(
937
+ label="emo_gen并行处理数",
938
+ info="最好预留2个以上的核数空闲,防卡死",
939
+ minimum=1,
940
+ maximum=32,
941
+ step=1,
942
+ value=init_yml["emo_gen"]["num_processes"],
943
+ )
944
+ dropdown_emo_device = gr.Dropdown(
945
+ label="emo_gen使用设备",
946
+ info="可选cpu或cuda",
947
+ choices=["cpu", "cuda"],
948
+ value="cuda",
949
+ )
950
+ with gr.Row():
951
+ emo_config_btn = gr.Button(value="更新emo配置")
952
+ emo_gen_btn = gr.Button(
953
+ value="Emo Gen!", variant="primary"
954
+ )
955
+ with gr.Row():
956
+ emo_status = gr.Textbox(label="状态信息")
957
+
958
+ with gr.TabItem("训练界面"):
959
+ with gr.Tabs():
960
+ with gr.TabItem("训练配置文件路径"):
961
+ with gr.Row():
962
+ train_dataset_box_1 = gr.Textbox(
963
+ label="数据集存放路径",
964
+ text_align="right",
965
+ value=str(init_yml["dataset_path"]).rstrip("/"),
966
+ lines=1,
967
+ interactive=False,
968
+ scale=20,
969
+ )
970
+ gr.Markdown(
971
+ """
972
+ <br></br>
973
+ ## +
974
+ """
975
+ )
976
+ train_config_box = gr.Textbox(
977
+ label="train_ms配置文件路径",
978
+ text_align="left",
979
+ value=init_yml["train_ms"]["config_path"],
980
+ lines=1,
981
+ interactive=True,
982
+ scale=20,
983
+ )
984
+ with gr.Row():
985
+ train_dataset_box_2 = gr.Textbox(
986
+ label="数据集存放路径",
987
+ text_align="right",
988
+ value=str(init_yml["dataset_path"]).rstrip("/"),
989
+ lines=1,
990
+ interactive=False,
991
+ scale=20,
992
+ )
993
+ gr.Markdown(
994
+ """
995
+ <br></br>
996
+ ## +
997
+ """
998
+ )
999
+ train_model_box = gr.Textbox(
1000
+ label="train_ms模型文件夹路径",
1001
+ value=init_yml["train_ms"]["model"],
1002
+ lines=1,
1003
+ interactive=True,
1004
+ scale=20,
1005
+ )
1006
+ with gr.Row():
1007
+ train_ms_path_btn = gr.Button(value="更改训练路径配置")
1008
+ CheckboxGroup_train_models = check_base_models()
1009
+ check_pth_btn3 = gr.Button(value="检查训练底模状态")
1010
+ with gr.TabItem("训练参数设置"):
1011
+ with gr.Row():
1012
+ slider_batch_size = gr.Slider(
1013
+ minimum=1,
1014
+ maximum=40,
1015
+ value=4,
1016
+ step=1,
1017
+ label="batch_size 批处理大小",
1018
+ )
1019
+ slider_keep_ckpts = gr.Slider(
1020
+ minimum=1,
1021
+ maximum=20,
1022
+ value=5,
1023
+ step=1,
1024
+ label="keep_ckpts 最多保存n个最新模型",
1025
+ info="若超过,则删除最早的"
1026
+ )
1027
+ with gr.Row():
1028
+ slider_log_interval = gr.Slider(
1029
+ minimum=50,
1030
+ maximum=3000,
1031
+ value=200,
1032
+ step=50,
1033
+ label="log_interval 打印日志步数间隔",
1034
+ )
1035
+ slider_eval_interval = gr.Slider(
1036
+ minimum=100,
1037
+ maximum=5000,
1038
+ value=1000,
1039
+ step=50,
1040
+ label="eval_interval 保存模型步数间隔",
1041
+ )
1042
+ with gr.Row():
1043
+ slider_epochs = gr.Slider(
1044
+ minimum=50,
1045
+ maximum=2000,
1046
+ value=100,
1047
+ step=50,
1048
+ label="epochs 训练轮数",
1049
+ )
1050
+ slider_lr = gr.Slider(
1051
+ minimum=0.0001,
1052
+ maximum=0.0010,
1053
+ value=0.0003,
1054
+ step=0.0001,
1055
+ label="learning_rate 初始学习率",
1056
+ )
1057
+ with gr.Row():
1058
+ dropdown_version = gr.Dropdown(
1059
+ label="模型版本选择",
1060
+ info="推荐使用最新版底模和版本训练",
1061
+ choices=["2.1", "2.0.2", "2.0.1", "2.0", "1.1.1", "1.1.0", "1.0.1"],
1062
+ value="2.1",
1063
+ )
1064
+ with gr.Row():
1065
+ train_ms_load_btn = gr.Button(
1066
+ value="加载训练参数配置", variant="primary"
1067
+ )
1068
+ train_ms_param_btn = gr.Button(
1069
+ value="更改训练参数配置", variant="primary"
1070
+ )
1071
+ with gr.Row():
1072
+ train_btn = gr.Button(
1073
+ value="3.1 点击开始训练", variant="primary"
1074
+ )
1075
+ train_btn_2 = gr.Button(
1076
+ value="3.2 继续训练", variant="primary"
1077
+ )
1078
+ stop_train_btn = gr.Button(
1079
+ value="终止训练", variant="secondary"
1080
+ )
1081
+ with gr.Row():
1082
+ train_output_box = gr.Textbox(
1083
+ label="状态信息", lines=1, autoscroll=True
1084
+ )
1085
+ with gr.TabItem("TensorBoard"):
1086
+ with gr.Row():
1087
+ gr.Markdown(
1088
+ """
1089
+ ### Tensorboard的logdir 默认为训练的models路径
1090
+ ### 请在前一节 `训练配置文件路径` 查看
1091
+ """
1092
+ )
1093
+ with gr.Row():
1094
+ open_tb_btn = gr.Button("开启Tensorboard")
1095
+ stop_tb_btn = gr.Button("关闭Tensorboard")
1096
+ with gr.Row():
1097
+ tb_output_box = gr.Textbox(
1098
+ label="状态信息", lines=1, autoscroll=True
1099
+ )
1100
+ with gr.TabItem("推理界面"):
1101
+ with gr.Tabs():
1102
+ with gr.TabItem("模型选择"):
1103
+ with gr.Row():
1104
+ dropdown_infer_model = gr.Dropdown(
1105
+ label="选择推理模型",
1106
+ info="默认选择预处理阶段配置的文件夹内容; 也可以自己输入路径。",
1107
+ interactive=True,
1108
+ allow_custom_value=True,
1109
+ )
1110
+ dropdown_infer_config = gr.Dropdown(
1111
+ label="选择配置文件",
1112
+ info="默认选择预处理阶段配置的文件夹内容; 也可以自己输入路径。",
1113
+ interactive=True,
1114
+ allow_custom_value=True,
1115
+ )
1116
+ with gr.Row():
1117
+ dropdown_model_fresh_btn = gr.Button(value="刷新推理模型列表")
1118
+ with gr.Row():
1119
+ webui_port_box = gr.Textbox(
1120
+ label="WebUI推理的端口号",
1121
+ placeholder="范围:[0, 65535]",
1122
+ max_lines=1,
1123
+ lines=1,
1124
+ value=init_yml["webui"]["port"],
1125
+ interactive=True,
1126
+ )
1127
+ infer_ver_box = gr.Dropdown(
1128
+ label="更改推理版本",
1129
+ info="已经实现兼容推理,请选择合适的版本",
1130
+ choices=["2.1", "2.0.2", "2.0.1", "2.0", "1.1.1", "1.1.0", "1.0.1"],
1131
+ value="2.1",
1132
+ )
1133
+ with gr.Row():
1134
+ radio_webui_share = gr.Radio(
1135
+ label="公开",
1136
+ info="是否公开部署,对外网开放",
1137
+ choices=[True, False],
1138
+ value=init_yml["webui"]["share"],
1139
+ )
1140
+ radio_webui_debug = gr.Radio(
1141
+ label="调试模式",
1142
+ info="是否开启debug模式",
1143
+ choices=[True, False],
1144
+ value=init_yml["webui"]["debug"],
1145
+ )
1146
+ with gr.Row():
1147
+ infer_config_btn = gr.Button(value="更新推理配置文件")
1148
+ stop_infer_btn = gr.Button(value="结束WebUI推理")
1149
+ with gr.Row():
1150
+ infer_webui_btn = gr.Button(
1151
+ value="开启WebUI推理", variant="primary"
1152
+ )
1153
+ with gr.Row():
1154
+ infer_webui_box = gr.Textbox(
1155
+ label="提示信息", interactive=False
1156
+ )
1157
+
1158
+ with gr.TabItem("模型压缩"):
1159
+ with gr.Row():
1160
+ compress_config = gr.Textbox(
1161
+ label="压缩配置文件", info="模型对应的config.json"
1162
+ )
1163
+ with gr.Row():
1164
+ compress_input_path = gr.Textbox(
1165
+ label="待压缩模型路径", info="所谓的模型是:G_{步数}.pth"
1166
+ )
1167
+ with gr.Row():
1168
+ compress_output_path = gr.Textbox(
1169
+ label="输出模型路径",
1170
+ info="输出为:G_{步数}_release.pth",
1171
+ value="在待压缩模型路径的同一文件夹下",
1172
+ interactive=False,
1173
+ )
1174
+ with gr.Row():
1175
+ compress_btn = gr.Button(
1176
+ value="压缩模型", variant="primary"
1177
+ )
1178
+ with gr.Row():
1179
+ compress_status = gr.Textbox(label="状态信息")
1180
+ with gr.Tabs():
1181
+ with gr.TabItem("yaml配置文件状态"):
1182
+ code_config_yml = gr.Code(
1183
+ interactive=False,
1184
+ label=yml_config,
1185
+ value=load_yaml_data_in_raw(),
1186
+ language="yaml",
1187
+ elem_id="yml_code",
1188
+ )
1189
+ with gr.TabItem("带注释的yaml配置文件"):
1190
+ code_default_yml = gr.Code(
1191
+ interactive=False,
1192
+ label=default_yaml_path,
1193
+ value=load_yaml_data_in_raw(default_yaml_path),
1194
+ language="yaml",
1195
+ elem_id="yml_code",
1196
+ )
1197
+ with gr.TabItem("训练的json配置文件"):
1198
+ code_train_config_json = gr.Code(
1199
+ interactive=False,
1200
+ label=default_config_path,
1201
+ value=load_json_data_in_raw(default_config_path),
1202
+ language="json",
1203
+ elem_id="json_code",
1204
+ )
1205
+ with gr.TabItem("推理的json配置文件"):
1206
+ code_infer_config_json = gr.Code(
1207
+ interactive=False,
1208
+ label=default_config_path,
1209
+ value=load_json_data_in_raw(default_config_path),
1210
+ language="json",
1211
+ elem_id="json_code",
1212
+ )
1213
+ with gr.TabItem("其他状态"):
1214
+ code_gpu_json = gr.Code(
1215
+ label="本机资源使用情况",
1216
+ interactive=False,
1217
+ value=get_status(),
1218
+ language="json",
1219
+ elem_id="gpu_code",
1220
+ )
1221
+ gpu_json_btn = gr.Button(value="刷新本机状态")
1222
+
1223
+ openi_token_btn.click(
1224
+ fn=fill_openi_token,
1225
+ inputs=[openi_token_box],
1226
+ outputs=[openi_token_status, code_config_yml],
1227
+ )
1228
+ check_pth_btn1.click(
1229
+ fn=check_bert_models, inputs=[], outputs=[CheckboxGroup_bert_models]
1230
+ )
1231
+ check_pth_btn2.click(
1232
+ fn=check_emo_models, inputs=[], outputs=[CheckboxGroup_emo_models]
1233
+ )
1234
+ check_pth_btn3.click(
1235
+ fn=check_base_models, inputs=[], outputs=[CheckboxGroup_train_models]
1236
+ )
1237
+ data_path_btn.click(
1238
+ fn=modify_data_path,
1239
+ inputs=[dropdown_data_path],
1240
+ outputs=[
1241
+ dropdown_data_path,
1242
+ bert_dataset_box,
1243
+ train_dataset_box_1,
1244
+ train_dataset_box_2,
1245
+ code_config_yml,
1246
+ CheckboxGroup_train_models,
1247
+ ],
1248
+ )
1249
+ preprocess_config_btn.click(
1250
+ fn=modify_preprocess_param,
1251
+ inputs=[
1252
+ dropdown_filelist_path,
1253
+ preprocess_config_box,
1254
+ slider_val_per_spk,
1255
+ slider_max_val_total,
1256
+ ],
1257
+ outputs=[dropdown_filelist_path, code_config_yml],
1258
+ )
1259
+ preprocess_text_btn.click(
1260
+ fn=do_preprocess_text, inputs=[], outputs=[label_status]
1261
+ )
1262
+ resample_config_btn.click(
1263
+ fn=modify_resample_path,
1264
+ inputs=[resample_in_box, resample_out_box, dropdown_resample_sr],
1265
+ outputs=[
1266
+ resample_in_box,
1267
+ resample_out_box,
1268
+ resample_status,
1269
+ dropdown_resample_sr,
1270
+ code_config_yml,
1271
+ ],
1272
+ )
1273
+ resample_btn.click(
1274
+ fn=do_resample, inputs=[slider_resample_nps], outputs=[resample_status]
1275
+ )
1276
+ transcribe_btn.click(
1277
+ fn=do_transcript,
1278
+ inputs=[dropdown_lang, slider_transcribe],
1279
+ outputs=[preprocess_status_box],
1280
+ )
1281
+ extract_list_btn.click(
1282
+ fn=do_extract,
1283
+ inputs=[resample_in_box, dropdown_lang, unclean_box, char_name_box],
1284
+ outputs=[preprocess_status_box],
1285
+ )
1286
+ clean_trans_btn.click(
1287
+ fn=do_clean_list,
1288
+ inputs=[clean_txt_box, unclean_box, clean_box],
1289
+ outputs=[preprocess_status_box],
1290
+ )
1291
+ bert_config_btn.click(
1292
+ fn=modify_bert_config,
1293
+ inputs=[
1294
+ bert_config_box,
1295
+ slider_bert_nps,
1296
+ dropdown_bert_dev,
1297
+ radio_bert_multi,
1298
+ ],
1299
+ outputs=[
1300
+ bert_config_box,
1301
+ slider_bert_nps,
1302
+ dropdown_bert_dev,
1303
+ radio_bert_multi,
1304
+ code_config_yml,
1305
+ ],
1306
+ )
1307
+ bert_gen_btn.click(fn=do_bert_gen, inputs=[], outputs=[bert_status])
1308
+ emo_config_btn.click(
1309
+ fn=modify_emo_gen,
1310
+ inputs=[emo_config_box, slider_emo_nps, dropdown_emo_device],
1311
+ outputs=[emo_status, code_config_yml],
1312
+ )
1313
+ emo_gen_btn.click(fn=do_emo_gen, inputs=[], outputs=[emo_status])
1314
+ train_ms_load_btn.click(
1315
+ fn=load_train_param,
1316
+ inputs=[train_config_box],
1317
+ outputs=[
1318
+ train_output_box,
1319
+ code_train_config_json,
1320
+ slider_batch_size,
1321
+ slider_keep_ckpts,
1322
+ slider_log_interval,
1323
+ slider_eval_interval,
1324
+ slider_epochs,
1325
+ slider_lr,
1326
+ dropdown_version,
1327
+ ],
1328
+ )
1329
+ train_ms_path_btn.click(
1330
+ fn=modify_train_path,
1331
+ inputs=[train_model_box, train_config_box],
1332
+ outputs=[
1333
+ train_model_box,
1334
+ train_config_box,
1335
+ code_config_yml,
1336
+ CheckboxGroup_train_models,
1337
+ ],
1338
+ )
1339
+ train_ms_param_btn.click(
1340
+ fn=modify_train_param,
1341
+ inputs=[
1342
+ slider_batch_size,
1343
+ slider_keep_ckpts,
1344
+ slider_log_interval,
1345
+ slider_eval_interval,
1346
+ slider_epochs,
1347
+ slider_lr,
1348
+ dropdown_version,
1349
+ ],
1350
+ outputs=[train_output_box, code_train_config_json],
1351
+ )
1352
+ train_btn.click(fn=do_my_train, inputs=[], outputs=[train_output_box])
1353
+ train_btn_2.click(fn=do_my_train, inputs=[], outputs=[train_output_box])
1354
+ stop_train_btn.click(fn=stop_train_ms, inputs=[], outputs=[train_output_box])
1355
+ open_tb_btn.click(fn=do_tensorboard, inputs=[], outputs=[tb_output_box])
1356
+ stop_tb_btn.click(fn=stop_tensorboard, inputs=[], outputs=[tb_output_box])
1357
+ dropdown_model_fresh_btn.click(
1358
+ fn=list_infer_models,
1359
+ inputs=[],
1360
+ outputs=[dropdown_infer_model, dropdown_infer_config],
1361
+ )
1362
+ infer_config_btn.click(
1363
+ fn=modify_infer_param,
1364
+ inputs=[
1365
+ dropdown_infer_model,
1366
+ dropdown_infer_config,
1367
+ webui_port_box,
1368
+ radio_webui_share,
1369
+ radio_webui_debug,
1370
+ infer_ver_box,
1371
+ ],
1372
+ outputs=[infer_webui_box, code_config_yml, code_infer_config_json],
1373
+ )
1374
+ infer_webui_btn.click(fn=do_webui_infer, inputs=[], outputs=[infer_webui_box])
1375
+ compress_btn.click(
1376
+ fn=compress_model,
1377
+ inputs=[compress_config, compress_input_path, compress_output_path],
1378
+ outputs=[compress_status],
1379
+ )
1380
+ stop_infer_btn.click(fn=stop_webui_infer, inputs=[], outputs=[infer_webui_box])
1381
+ gpu_json_btn.click(fn=get_gpu_status, inputs=[], outputs=[code_gpu_json])
1382
+ os.environ["no_proxy"] = "localhost,127.0.0.1,0.0.0.0"
1383
+ webbrowser.open("http://127.0.0.1:6006")
1384
+ app.launch(share=False, server_port=6006)
asr_transcript.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import concurrent.futures
3
+ import os
4
+
5
+ from loguru import logger
6
+ from modelscope.pipelines import pipeline
7
+ from modelscope.utils.constant import Tasks
8
+ from tqdm import tqdm
9
+
10
+ os.environ["MODELSCOPE_CACHE"] = "./"
11
+
12
+
13
+ def transcribe_worker(file_path: str, inference_pipeline, language):
14
+ """
15
+ Worker function for transcribing a segment of an audio file.
16
+ """
17
+ rec_result = inference_pipeline(audio_in=file_path)
18
+ text = str(rec_result.get("text", "")).strip()
19
+ text_without_spaces = text.replace(" ", "")
20
+ logger.info(file_path)
21
+ if language != "EN":
22
+ logger.info("text: " + text_without_spaces)
23
+ return text_without_spaces
24
+ else:
25
+ logger.info("text: " + text)
26
+ return text
27
+
28
+
29
+ def transcribe_folder_parallel(folder_path, language, max_workers=4):
30
+ """
31
+ Transcribe all .wav files in the given folder using ThreadPoolExecutor.
32
+ """
33
+ logger.critical(f"parallel transcribe: {folder_path}|{language}|{max_workers}")
34
+ if language == "JP":
35
+ workers = [
36
+ pipeline(
37
+ task=Tasks.auto_speech_recognition,
38
+ model="damo/speech_UniASR_asr_2pass-ja-16k-common-vocab93-tensorflow1-offline",
39
+ )
40
+ for _ in range(max_workers)
41
+ ]
42
+
43
+ elif language == "ZH":
44
+ workers = [
45
+ pipeline(
46
+ task=Tasks.auto_speech_recognition,
47
+ model="damo/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch",
48
+ model_revision="v1.2.4",
49
+ )
50
+ for _ in range(max_workers)
51
+ ]
52
+ else:
53
+ workers = [
54
+ pipeline(
55
+ task=Tasks.auto_speech_recognition,
56
+ model="damo/speech_UniASR_asr_2pass-en-16k-common-vocab1080-tensorflow1-offline",
57
+ )
58
+ for _ in range(max_workers)
59
+ ]
60
+
61
+ file_paths = []
62
+ langs = []
63
+ for root, _, files in os.walk(folder_path):
64
+ for file in files:
65
+ if file.lower().endswith(".wav"):
66
+ file_path = os.path.join(root, file)
67
+ lab_file_path = os.path.splitext(file_path)[0] + ".lab"
68
+ file_paths.append(file_path)
69
+ langs.append(language)
70
+
71
+ all_workers = (
72
+ workers * (len(file_paths) // max_workers)
73
+ + workers[: len(file_paths) % max_workers]
74
+ )
75
+
76
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
77
+ for i in tqdm(range(0, len(file_paths), max_workers), desc="转写进度: "):
78
+ l, r = i, min(i + max_workers, len(file_paths))
79
+ transcriptions = list(
80
+ executor.map(
81
+ transcribe_worker, file_paths[l:r], all_workers[l:r], langs[l:r]
82
+ )
83
+ )
84
+ for file_path, transcription in zip(file_paths[l:r], transcriptions):
85
+ if transcription:
86
+ lab_file_path = os.path.splitext(file_path)[0] + ".lab"
87
+ with open(lab_file_path, "w", encoding="utf-8") as lab_file:
88
+ lab_file.write(transcription)
89
+ logger.critical("已经将wav文件转写为同名的.lab文件")
90
+
91
+
92
+ if __name__ == "__main__":
93
+ parser = argparse.ArgumentParser()
94
+ parser.add_argument(
95
+ "-f", "--filepath", default="./raw/lzy_zh", help="path of your model"
96
+ )
97
+ parser.add_argument("-l", "--language", default="ZH", help="language")
98
+ parser.add_argument("-w", "--workers", default="1", help="trans workers")
99
+ args = parser.parse_args()
100
+
101
+ transcribe_folder_parallel(args.filepath, args.language, int(args.workers))
102
+ print("转写结束!")
attentions.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ import commons
7
+ import logging
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class LayerNorm(nn.Module):
13
+ def __init__(self, channels, eps=1e-5):
14
+ super().__init__()
15
+ self.channels = channels
16
+ self.eps = eps
17
+
18
+ self.gamma = nn.Parameter(torch.ones(channels))
19
+ self.beta = nn.Parameter(torch.zeros(channels))
20
+
21
+ def forward(self, x):
22
+ x = x.transpose(1, -1)
23
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
24
+ return x.transpose(1, -1)
25
+
26
+
27
+ @torch.jit.script
28
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
29
+ n_channels_int = n_channels[0]
30
+ in_act = input_a + input_b
31
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
32
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
33
+ acts = t_act * s_act
34
+ return acts
35
+
36
+
37
+ class Encoder(nn.Module):
38
+ def __init__(
39
+ self,
40
+ hidden_channels,
41
+ filter_channels,
42
+ n_heads,
43
+ n_layers,
44
+ kernel_size=1,
45
+ p_dropout=0.0,
46
+ window_size=4,
47
+ isflow=True,
48
+ **kwargs
49
+ ):
50
+ super().__init__()
51
+ self.hidden_channels = hidden_channels
52
+ self.filter_channels = filter_channels
53
+ self.n_heads = n_heads
54
+ self.n_layers = n_layers
55
+ self.kernel_size = kernel_size
56
+ self.p_dropout = p_dropout
57
+ self.window_size = window_size
58
+ # if isflow:
59
+ # cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
60
+ # self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
61
+ # self.cond_layer = weight_norm(cond_layer, name='weight')
62
+ # self.gin_channels = 256
63
+ self.cond_layer_idx = self.n_layers
64
+ if "gin_channels" in kwargs:
65
+ self.gin_channels = kwargs["gin_channels"]
66
+ if self.gin_channels != 0:
67
+ self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
68
+ # vits2 says 3rd block, so idx is 2 by default
69
+ self.cond_layer_idx = (
70
+ kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
71
+ )
72
+ logging.debug(self.gin_channels, self.cond_layer_idx)
73
+ assert (
74
+ self.cond_layer_idx < self.n_layers
75
+ ), "cond_layer_idx should be less than n_layers"
76
+ self.drop = nn.Dropout(p_dropout)
77
+ self.attn_layers = nn.ModuleList()
78
+ self.norm_layers_1 = nn.ModuleList()
79
+ self.ffn_layers = nn.ModuleList()
80
+ self.norm_layers_2 = nn.ModuleList()
81
+ for i in range(self.n_layers):
82
+ self.attn_layers.append(
83
+ MultiHeadAttention(
84
+ hidden_channels,
85
+ hidden_channels,
86
+ n_heads,
87
+ p_dropout=p_dropout,
88
+ window_size=window_size,
89
+ )
90
+ )
91
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
92
+ self.ffn_layers.append(
93
+ FFN(
94
+ hidden_channels,
95
+ hidden_channels,
96
+ filter_channels,
97
+ kernel_size,
98
+ p_dropout=p_dropout,
99
+ )
100
+ )
101
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
102
+
103
+ def forward(self, x, x_mask, g=None):
104
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
105
+ x = x * x_mask
106
+ for i in range(self.n_layers):
107
+ if i == self.cond_layer_idx and g is not None:
108
+ g = self.spk_emb_linear(g.transpose(1, 2))
109
+ g = g.transpose(1, 2)
110
+ x = x + g
111
+ x = x * x_mask
112
+ y = self.attn_layers[i](x, x, attn_mask)
113
+ y = self.drop(y)
114
+ x = self.norm_layers_1[i](x + y)
115
+
116
+ y = self.ffn_layers[i](x, x_mask)
117
+ y = self.drop(y)
118
+ x = self.norm_layers_2[i](x + y)
119
+ x = x * x_mask
120
+ return x
121
+
122
+
123
+ class Decoder(nn.Module):
124
+ def __init__(
125
+ self,
126
+ hidden_channels,
127
+ filter_channels,
128
+ n_heads,
129
+ n_layers,
130
+ kernel_size=1,
131
+ p_dropout=0.0,
132
+ proximal_bias=False,
133
+ proximal_init=True,
134
+ **kwargs
135
+ ):
136
+ super().__init__()
137
+ self.hidden_channels = hidden_channels
138
+ self.filter_channels = filter_channels
139
+ self.n_heads = n_heads
140
+ self.n_layers = n_layers
141
+ self.kernel_size = kernel_size
142
+ self.p_dropout = p_dropout
143
+ self.proximal_bias = proximal_bias
144
+ self.proximal_init = proximal_init
145
+
146
+ self.drop = nn.Dropout(p_dropout)
147
+ self.self_attn_layers = nn.ModuleList()
148
+ self.norm_layers_0 = nn.ModuleList()
149
+ self.encdec_attn_layers = nn.ModuleList()
150
+ self.norm_layers_1 = nn.ModuleList()
151
+ self.ffn_layers = nn.ModuleList()
152
+ self.norm_layers_2 = nn.ModuleList()
153
+ for i in range(self.n_layers):
154
+ self.self_attn_layers.append(
155
+ MultiHeadAttention(
156
+ hidden_channels,
157
+ hidden_channels,
158
+ n_heads,
159
+ p_dropout=p_dropout,
160
+ proximal_bias=proximal_bias,
161
+ proximal_init=proximal_init,
162
+ )
163
+ )
164
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
165
+ self.encdec_attn_layers.append(
166
+ MultiHeadAttention(
167
+ hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
168
+ )
169
+ )
170
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
171
+ self.ffn_layers.append(
172
+ FFN(
173
+ hidden_channels,
174
+ hidden_channels,
175
+ filter_channels,
176
+ kernel_size,
177
+ p_dropout=p_dropout,
178
+ causal=True,
179
+ )
180
+ )
181
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
182
+
183
+ def forward(self, x, x_mask, h, h_mask):
184
+ """
185
+ x: decoder input
186
+ h: encoder output
187
+ """
188
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
189
+ device=x.device, dtype=x.dtype
190
+ )
191
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
192
+ x = x * x_mask
193
+ for i in range(self.n_layers):
194
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
195
+ y = self.drop(y)
196
+ x = self.norm_layers_0[i](x + y)
197
+
198
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
199
+ y = self.drop(y)
200
+ x = self.norm_layers_1[i](x + y)
201
+
202
+ y = self.ffn_layers[i](x, x_mask)
203
+ y = self.drop(y)
204
+ x = self.norm_layers_2[i](x + y)
205
+ x = x * x_mask
206
+ return x
207
+
208
+
209
+ class MultiHeadAttention(nn.Module):
210
+ def __init__(
211
+ self,
212
+ channels,
213
+ out_channels,
214
+ n_heads,
215
+ p_dropout=0.0,
216
+ window_size=None,
217
+ heads_share=True,
218
+ block_length=None,
219
+ proximal_bias=False,
220
+ proximal_init=False,
221
+ ):
222
+ super().__init__()
223
+ assert channels % n_heads == 0
224
+
225
+ self.channels = channels
226
+ self.out_channels = out_channels
227
+ self.n_heads = n_heads
228
+ self.p_dropout = p_dropout
229
+ self.window_size = window_size
230
+ self.heads_share = heads_share
231
+ self.block_length = block_length
232
+ self.proximal_bias = proximal_bias
233
+ self.proximal_init = proximal_init
234
+ self.attn = None
235
+
236
+ self.k_channels = channels // n_heads
237
+ self.conv_q = nn.Conv1d(channels, channels, 1)
238
+ self.conv_k = nn.Conv1d(channels, channels, 1)
239
+ self.conv_v = nn.Conv1d(channels, channels, 1)
240
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
241
+ self.drop = nn.Dropout(p_dropout)
242
+
243
+ if window_size is not None:
244
+ n_heads_rel = 1 if heads_share else n_heads
245
+ rel_stddev = self.k_channels**-0.5
246
+ self.emb_rel_k = nn.Parameter(
247
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
248
+ * rel_stddev
249
+ )
250
+ self.emb_rel_v = nn.Parameter(
251
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
252
+ * rel_stddev
253
+ )
254
+
255
+ nn.init.xavier_uniform_(self.conv_q.weight)
256
+ nn.init.xavier_uniform_(self.conv_k.weight)
257
+ nn.init.xavier_uniform_(self.conv_v.weight)
258
+ if proximal_init:
259
+ with torch.no_grad():
260
+ self.conv_k.weight.copy_(self.conv_q.weight)
261
+ self.conv_k.bias.copy_(self.conv_q.bias)
262
+
263
+ def forward(self, x, c, attn_mask=None):
264
+ q = self.conv_q(x)
265
+ k = self.conv_k(c)
266
+ v = self.conv_v(c)
267
+
268
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
269
+
270
+ x = self.conv_o(x)
271
+ return x
272
+
273
+ def attention(self, query, key, value, mask=None):
274
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
275
+ b, d, t_s, t_t = (*key.size(), query.size(2))
276
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
277
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
278
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
279
+
280
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
281
+ if self.window_size is not None:
282
+ assert (
283
+ t_s == t_t
284
+ ), "Relative attention is only available for self-attention."
285
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
286
+ rel_logits = self._matmul_with_relative_keys(
287
+ query / math.sqrt(self.k_channels), key_relative_embeddings
288
+ )
289
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
290
+ scores = scores + scores_local
291
+ if self.proximal_bias:
292
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
293
+ scores = scores + self._attention_bias_proximal(t_s).to(
294
+ device=scores.device, dtype=scores.dtype
295
+ )
296
+ if mask is not None:
297
+ scores = scores.masked_fill(mask == 0, -1e4)
298
+ if self.block_length is not None:
299
+ assert (
300
+ t_s == t_t
301
+ ), "Local attention is only available for self-attention."
302
+ block_mask = (
303
+ torch.ones_like(scores)
304
+ .triu(-self.block_length)
305
+ .tril(self.block_length)
306
+ )
307
+ scores = scores.masked_fill(block_mask == 0, -1e4)
308
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
309
+ p_attn = self.drop(p_attn)
310
+ output = torch.matmul(p_attn, value)
311
+ if self.window_size is not None:
312
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
313
+ value_relative_embeddings = self._get_relative_embeddings(
314
+ self.emb_rel_v, t_s
315
+ )
316
+ output = output + self._matmul_with_relative_values(
317
+ relative_weights, value_relative_embeddings
318
+ )
319
+ output = (
320
+ output.transpose(2, 3).contiguous().view(b, d, t_t)
321
+ ) # [b, n_h, t_t, d_k] -> [b, d, t_t]
322
+ return output, p_attn
323
+
324
+ def _matmul_with_relative_values(self, x, y):
325
+ """
326
+ x: [b, h, l, m]
327
+ y: [h or 1, m, d]
328
+ ret: [b, h, l, d]
329
+ """
330
+ ret = torch.matmul(x, y.unsqueeze(0))
331
+ return ret
332
+
333
+ def _matmul_with_relative_keys(self, x, y):
334
+ """
335
+ x: [b, h, l, d]
336
+ y: [h or 1, m, d]
337
+ ret: [b, h, l, m]
338
+ """
339
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
340
+ return ret
341
+
342
+ def _get_relative_embeddings(self, relative_embeddings, length):
343
+ 2 * self.window_size + 1
344
+ # Pad first before slice to avoid using cond ops.
345
+ pad_length = max(length - (self.window_size + 1), 0)
346
+ slice_start_position = max((self.window_size + 1) - length, 0)
347
+ slice_end_position = slice_start_position + 2 * length - 1
348
+ if pad_length > 0:
349
+ padded_relative_embeddings = F.pad(
350
+ relative_embeddings,
351
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
352
+ )
353
+ else:
354
+ padded_relative_embeddings = relative_embeddings
355
+ used_relative_embeddings = padded_relative_embeddings[
356
+ :, slice_start_position:slice_end_position
357
+ ]
358
+ return used_relative_embeddings
359
+
360
+ def _relative_position_to_absolute_position(self, x):
361
+ """
362
+ x: [b, h, l, 2*l-1]
363
+ ret: [b, h, l, l]
364
+ """
365
+ batch, heads, length, _ = x.size()
366
+ # Concat columns of pad to shift from relative to absolute indexing.
367
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
368
+
369
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
370
+ x_flat = x.view([batch, heads, length * 2 * length])
371
+ x_flat = F.pad(
372
+ x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
373
+ )
374
+
375
+ # Reshape and slice out the padded elements.
376
+ x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
377
+ :, :, :length, length - 1 :
378
+ ]
379
+ return x_final
380
+
381
+ def _absolute_position_to_relative_position(self, x):
382
+ """
383
+ x: [b, h, l, l]
384
+ ret: [b, h, l, 2*l-1]
385
+ """
386
+ batch, heads, length, _ = x.size()
387
+ # pad along column
388
+ x = F.pad(
389
+ x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
390
+ )
391
+ x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
392
+ # add 0's in the beginning that will skew the elements after reshape
393
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
394
+ x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
395
+ return x_final
396
+
397
+ def _attention_bias_proximal(self, length):
398
+ """Bias for self-attention to encourage attention to close positions.
399
+ Args:
400
+ length: an integer scalar.
401
+ Returns:
402
+ a Tensor with shape [1, 1, length, length]
403
+ """
404
+ r = torch.arange(length, dtype=torch.float32)
405
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
406
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
407
+
408
+
409
+ class FFN(nn.Module):
410
+ def __init__(
411
+ self,
412
+ in_channels,
413
+ out_channels,
414
+ filter_channels,
415
+ kernel_size,
416
+ p_dropout=0.0,
417
+ activation=None,
418
+ causal=False,
419
+ ):
420
+ super().__init__()
421
+ self.in_channels = in_channels
422
+ self.out_channels = out_channels
423
+ self.filter_channels = filter_channels
424
+ self.kernel_size = kernel_size
425
+ self.p_dropout = p_dropout
426
+ self.activation = activation
427
+ self.causal = causal
428
+
429
+ if causal:
430
+ self.padding = self._causal_padding
431
+ else:
432
+ self.padding = self._same_padding
433
+
434
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
435
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
436
+ self.drop = nn.Dropout(p_dropout)
437
+
438
+ def forward(self, x, x_mask):
439
+ x = self.conv_1(self.padding(x * x_mask))
440
+ if self.activation == "gelu":
441
+ x = x * torch.sigmoid(1.702 * x)
442
+ else:
443
+ x = torch.relu(x)
444
+ x = self.drop(x)
445
+ x = self.conv_2(self.padding(x * x_mask))
446
+ return x * x_mask
447
+
448
+ def _causal_padding(self, x):
449
+ if self.kernel_size == 1:
450
+ return x
451
+ pad_l = self.kernel_size - 1
452
+ pad_r = 0
453
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
454
+ x = F.pad(x, commons.convert_pad_shape(padding))
455
+ return x
456
+
457
+ def _same_padding(self, x):
458
+ if self.kernel_size == 1:
459
+ return x
460
+ pad_l = (self.kernel_size - 1) // 2
461
+ pad_r = self.kernel_size // 2
462
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
463
+ x = F.pad(x, commons.convert_pad_shape(padding))
464
+ return x
attentions_onnx.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ import commons
7
+ import logging
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class LayerNorm(nn.Module):
13
+ def __init__(self, channels, eps=1e-5):
14
+ super().__init__()
15
+ self.channels = channels
16
+ self.eps = eps
17
+
18
+ self.gamma = nn.Parameter(torch.ones(channels))
19
+ self.beta = nn.Parameter(torch.zeros(channels))
20
+
21
+ def forward(self, x):
22
+ x = x.transpose(1, -1)
23
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
24
+ return x.transpose(1, -1)
25
+
26
+
27
+ @torch.jit.script
28
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
29
+ n_channels_int = n_channels[0]
30
+ in_act = input_a + input_b
31
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
32
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
33
+ acts = t_act * s_act
34
+ return acts
35
+
36
+
37
+ class Encoder(nn.Module):
38
+ def __init__(
39
+ self,
40
+ hidden_channels,
41
+ filter_channels,
42
+ n_heads,
43
+ n_layers,
44
+ kernel_size=1,
45
+ p_dropout=0.0,
46
+ window_size=4,
47
+ isflow=True,
48
+ **kwargs
49
+ ):
50
+ super().__init__()
51
+ self.hidden_channels = hidden_channels
52
+ self.filter_channels = filter_channels
53
+ self.n_heads = n_heads
54
+ self.n_layers = n_layers
55
+ self.kernel_size = kernel_size
56
+ self.p_dropout = p_dropout
57
+ self.window_size = window_size
58
+ # if isflow:
59
+ # cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
60
+ # self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
61
+ # self.cond_layer = weight_norm(cond_layer, name='weight')
62
+ # self.gin_channels = 256
63
+ self.cond_layer_idx = self.n_layers
64
+ if "gin_channels" in kwargs:
65
+ self.gin_channels = kwargs["gin_channels"]
66
+ if self.gin_channels != 0:
67
+ self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
68
+ # vits2 says 3rd block, so idx is 2 by default
69
+ self.cond_layer_idx = (
70
+ kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
71
+ )
72
+ logging.debug(self.gin_channels, self.cond_layer_idx)
73
+ assert (
74
+ self.cond_layer_idx < self.n_layers
75
+ ), "cond_layer_idx should be less than n_layers"
76
+ self.drop = nn.Dropout(p_dropout)
77
+ self.attn_layers = nn.ModuleList()
78
+ self.norm_layers_1 = nn.ModuleList()
79
+ self.ffn_layers = nn.ModuleList()
80
+ self.norm_layers_2 = nn.ModuleList()
81
+ for i in range(self.n_layers):
82
+ self.attn_layers.append(
83
+ MultiHeadAttention(
84
+ hidden_channels,
85
+ hidden_channels,
86
+ n_heads,
87
+ p_dropout=p_dropout,
88
+ window_size=window_size,
89
+ )
90
+ )
91
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
92
+ self.ffn_layers.append(
93
+ FFN(
94
+ hidden_channels,
95
+ hidden_channels,
96
+ filter_channels,
97
+ kernel_size,
98
+ p_dropout=p_dropout,
99
+ )
100
+ )
101
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
102
+
103
+ def forward(self, x, x_mask, g=None):
104
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
105
+ x = x * x_mask
106
+ for i in range(self.n_layers):
107
+ if i == self.cond_layer_idx and g is not None:
108
+ g = self.spk_emb_linear(g.transpose(1, 2))
109
+ g = g.transpose(1, 2)
110
+ x = x + g
111
+ x = x * x_mask
112
+ y = self.attn_layers[i](x, x, attn_mask)
113
+ y = self.drop(y)
114
+ x = self.norm_layers_1[i](x + y)
115
+
116
+ y = self.ffn_layers[i](x, x_mask)
117
+ y = self.drop(y)
118
+ x = self.norm_layers_2[i](x + y)
119
+ x = x * x_mask
120
+ return x
121
+
122
+
123
+ class MultiHeadAttention(nn.Module):
124
+ def __init__(
125
+ self,
126
+ channels,
127
+ out_channels,
128
+ n_heads,
129
+ p_dropout=0.0,
130
+ window_size=None,
131
+ heads_share=True,
132
+ block_length=None,
133
+ proximal_bias=False,
134
+ proximal_init=False,
135
+ ):
136
+ super().__init__()
137
+ assert channels % n_heads == 0
138
+
139
+ self.channels = channels
140
+ self.out_channels = out_channels
141
+ self.n_heads = n_heads
142
+ self.p_dropout = p_dropout
143
+ self.window_size = window_size
144
+ self.heads_share = heads_share
145
+ self.block_length = block_length
146
+ self.proximal_bias = proximal_bias
147
+ self.proximal_init = proximal_init
148
+ self.attn = None
149
+
150
+ self.k_channels = channels // n_heads
151
+ self.conv_q = nn.Conv1d(channels, channels, 1)
152
+ self.conv_k = nn.Conv1d(channels, channels, 1)
153
+ self.conv_v = nn.Conv1d(channels, channels, 1)
154
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
155
+ self.drop = nn.Dropout(p_dropout)
156
+
157
+ if window_size is not None:
158
+ n_heads_rel = 1 if heads_share else n_heads
159
+ rel_stddev = self.k_channels**-0.5
160
+ self.emb_rel_k = nn.Parameter(
161
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
162
+ * rel_stddev
163
+ )
164
+ self.emb_rel_v = nn.Parameter(
165
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
166
+ * rel_stddev
167
+ )
168
+
169
+ nn.init.xavier_uniform_(self.conv_q.weight)
170
+ nn.init.xavier_uniform_(self.conv_k.weight)
171
+ nn.init.xavier_uniform_(self.conv_v.weight)
172
+ if proximal_init:
173
+ with torch.no_grad():
174
+ self.conv_k.weight.copy_(self.conv_q.weight)
175
+ self.conv_k.bias.copy_(self.conv_q.bias)
176
+
177
+ def forward(self, x, c, attn_mask=None):
178
+ q = self.conv_q(x)
179
+ k = self.conv_k(c)
180
+ v = self.conv_v(c)
181
+
182
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
183
+
184
+ x = self.conv_o(x)
185
+ return x
186
+
187
+ def attention(self, query, key, value, mask=None):
188
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
189
+ b, d, t_s, t_t = (*key.size(), query.size(2))
190
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
191
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
192
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
193
+
194
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
195
+ if self.window_size is not None:
196
+ assert (
197
+ t_s == t_t
198
+ ), "Relative attention is only available for self-attention."
199
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
200
+ rel_logits = self._matmul_with_relative_keys(
201
+ query / math.sqrt(self.k_channels), key_relative_embeddings
202
+ )
203
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
204
+ scores = scores + scores_local
205
+ if self.proximal_bias:
206
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
207
+ scores = scores + self._attention_bias_proximal(t_s).to(
208
+ device=scores.device, dtype=scores.dtype
209
+ )
210
+ if mask is not None:
211
+ scores = scores.masked_fill(mask == 0, -1e4)
212
+ if self.block_length is not None:
213
+ assert (
214
+ t_s == t_t
215
+ ), "Local attention is only available for self-attention."
216
+ block_mask = (
217
+ torch.ones_like(scores)
218
+ .triu(-self.block_length)
219
+ .tril(self.block_length)
220
+ )
221
+ scores = scores.masked_fill(block_mask == 0, -1e4)
222
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
223
+ p_attn = self.drop(p_attn)
224
+ output = torch.matmul(p_attn, value)
225
+ if self.window_size is not None:
226
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
227
+ value_relative_embeddings = self._get_relative_embeddings(
228
+ self.emb_rel_v, t_s
229
+ )
230
+ output = output + self._matmul_with_relative_values(
231
+ relative_weights, value_relative_embeddings
232
+ )
233
+ output = (
234
+ output.transpose(2, 3).contiguous().view(b, d, t_t)
235
+ ) # [b, n_h, t_t, d_k] -> [b, d, t_t]
236
+ return output, p_attn
237
+
238
+ def _matmul_with_relative_values(self, x, y):
239
+ """
240
+ x: [b, h, l, m]
241
+ y: [h or 1, m, d]
242
+ ret: [b, h, l, d]
243
+ """
244
+ ret = torch.matmul(x, y.unsqueeze(0))
245
+ return ret
246
+
247
+ def _matmul_with_relative_keys(self, x, y):
248
+ """
249
+ x: [b, h, l, d]
250
+ y: [h or 1, m, d]
251
+ ret: [b, h, l, m]
252
+ """
253
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
254
+ return ret
255
+
256
+ def _get_relative_embeddings(self, relative_embeddings, length):
257
+ max_relative_position = 2 * self.window_size + 1
258
+ # Pad first before slice to avoid using cond ops.
259
+ pad_length = max(length - (self.window_size + 1), 0)
260
+ slice_start_position = max((self.window_size + 1) - length, 0)
261
+ slice_end_position = slice_start_position + 2 * length - 1
262
+ if pad_length > 0:
263
+ padded_relative_embeddings = F.pad(
264
+ relative_embeddings,
265
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
266
+ )
267
+ else:
268
+ padded_relative_embeddings = relative_embeddings
269
+ used_relative_embeddings = padded_relative_embeddings[
270
+ :, slice_start_position:slice_end_position
271
+ ]
272
+ return used_relative_embeddings
273
+
274
+ def _relative_position_to_absolute_position(self, x):
275
+ """
276
+ x: [b, h, l, 2*l-1]
277
+ ret: [b, h, l, l]
278
+ """
279
+ batch, heads, length, _ = x.size()
280
+ # Concat columns of pad to shift from relative to absolute indexing.
281
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
282
+
283
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
284
+ x_flat = x.view([batch, heads, length * 2 * length])
285
+ x_flat = F.pad(
286
+ x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
287
+ )
288
+
289
+ # Reshape and slice out the padded elements.
290
+ x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
291
+ :, :, :length, length - 1 :
292
+ ]
293
+ return x_final
294
+
295
+ def _absolute_position_to_relative_position(self, x):
296
+ """
297
+ x: [b, h, l, l]
298
+ ret: [b, h, l, 2*l-1]
299
+ """
300
+ batch, heads, length, _ = x.size()
301
+ # padd along column
302
+ x = F.pad(
303
+ x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
304
+ )
305
+ x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
306
+ # add 0's in the beginning that will skew the elements after reshape
307
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
308
+ x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
309
+ return x_final
310
+
311
+ def _attention_bias_proximal(self, length):
312
+ """Bias for self-attention to encourage attention to close positions.
313
+ Args:
314
+ length: an integer scalar.
315
+ Returns:
316
+ a Tensor with shape [1, 1, length, length]
317
+ """
318
+ r = torch.arange(length, dtype=torch.float32)
319
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
320
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
321
+
322
+
323
+ class FFN(nn.Module):
324
+ def __init__(
325
+ self,
326
+ in_channels,
327
+ out_channels,
328
+ filter_channels,
329
+ kernel_size,
330
+ p_dropout=0.0,
331
+ activation=None,
332
+ causal=False,
333
+ ):
334
+ super().__init__()
335
+ self.in_channels = in_channels
336
+ self.out_channels = out_channels
337
+ self.filter_channels = filter_channels
338
+ self.kernel_size = kernel_size
339
+ self.p_dropout = p_dropout
340
+ self.activation = activation
341
+ self.causal = causal
342
+
343
+ if causal:
344
+ self.padding = self._causal_padding
345
+ else:
346
+ self.padding = self._same_padding
347
+
348
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
349
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
350
+ self.drop = nn.Dropout(p_dropout)
351
+
352
+ def forward(self, x, x_mask):
353
+ x = self.conv_1(self.padding(x * x_mask))
354
+ if self.activation == "gelu":
355
+ x = x * torch.sigmoid(1.702 * x)
356
+ else:
357
+ x = torch.relu(x)
358
+ x = self.drop(x)
359
+ x = self.conv_2(self.padding(x * x_mask))
360
+ return x * x_mask
361
+
362
+ def _causal_padding(self, x):
363
+ if self.kernel_size == 1:
364
+ return x
365
+ pad_l = self.kernel_size - 1
366
+ pad_r = 0
367
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
368
+ x = F.pad(x, commons.convert_pad_shape(padding))
369
+ return x
370
+
371
+ def _same_padding(self, x):
372
+ if self.kernel_size == 1:
373
+ return x
374
+ pad_l = (self.kernel_size - 1) // 2
375
+ pad_r = self.kernel_size // 2
376
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
377
+ x = F.pad(x, commons.convert_pad_shape(padding))
378
+ return x
bert/bert-base-japanese-v3/.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
bert/bert-base-japanese-v3/README.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ datasets:
4
+ - cc100
5
+ - wikipedia
6
+ language:
7
+ - ja
8
+ widget:
9
+ - text: 東北大学で[MASK]の研究をしています。
10
+ ---
11
+
12
+ # BERT base Japanese (unidic-lite with whole word masking, CC-100 and jawiki-20230102)
13
+
14
+ This is a [BERT](https://github.com/google-research/bert) model pretrained on texts in the Japanese language.
15
+
16
+ This version of the model processes input texts with word-level tokenization based on the Unidic 2.1.2 dictionary (available in [unidic-lite](https://pypi.org/project/unidic-lite/) package), followed by the WordPiece subword tokenization.
17
+ Additionally, the model is trained with the whole word masking enabled for the masked language modeling (MLM) objective.
18
+
19
+ The codes for the pretraining are available at [cl-tohoku/bert-japanese](https://github.com/cl-tohoku/bert-japanese/).
20
+
21
+ ## Model architecture
22
+
23
+ The model architecture is the same as the original BERT base model; 12 layers, 768 dimensions of hidden states, and 12 attention heads.
24
+
25
+ ## Training Data
26
+
27
+ The model is trained on the Japanese portion of [CC-100 dataset](https://data.statmt.org/cc-100/) and the Japanese version of Wikipedia.
28
+ For Wikipedia, we generated a text corpus from the [Wikipedia Cirrussearch dump file](https://dumps.wikimedia.org/other/cirrussearch/) as of January 2, 2023.
29
+ The corpus files generated from CC-100 and Wikipedia are 74.3GB and 4.9GB in size and consist of approximately 392M and 34M sentences, respectively.
30
+
31
+ For the purpose of splitting texts into sentences, we used [fugashi](https://github.com/polm/fugashi) with [mecab-ipadic-NEologd](https://github.com/neologd/mecab-ipadic-neologd) dictionary (v0.0.7).
32
+
33
+ ## Tokenization
34
+
35
+ The texts are first tokenized by MeCab with the Unidic 2.1.2 dictionary and then split into subwords by the WordPiece algorithm.
36
+ The vocabulary size is 32768.
37
+
38
+ We used [fugashi](https://github.com/polm/fugashi) and [unidic-lite](https://github.com/polm/unidic-lite) packages for the tokenization.
39
+
40
+ ## Training
41
+
42
+ We trained the model first on the CC-100 corpus for 1M steps and then on the Wikipedia corpus for another 1M steps.
43
+ For training of the MLM (masked language modeling) objective, we introduced whole word masking in which all of the subword tokens corresponding to a single word (tokenized by MeCab) are masked at once.
44
+
45
+ For training of each model, we used a v3-8 instance of Cloud TPUs provided by [TPU Research Cloud](https://sites.research.google/trc/about/).
46
+
47
+ ## Licenses
48
+
49
+ The pretrained models are distributed under the Apache License 2.0.
50
+
51
+ ## Acknowledgments
52
+
53
+ This model is trained with Cloud TPUs provided by [TPU Research Cloud](https://sites.research.google/trc/about/) program.
bert/bert-base-japanese-v3/config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForPreTraining"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "hidden_act": "gelu",
7
+ "hidden_dropout_prob": 0.1,
8
+ "hidden_size": 768,
9
+ "initializer_range": 0.02,
10
+ "intermediate_size": 3072,
11
+ "layer_norm_eps": 1e-12,
12
+ "max_position_embeddings": 512,
13
+ "model_type": "bert",
14
+ "num_attention_heads": 12,
15
+ "num_hidden_layers": 12,
16
+ "pad_token_id": 0,
17
+ "type_vocab_size": 2,
18
+ "vocab_size": 32768
19
+ }
bert/bert-base-japanese-v3/tokenizer_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tokenizer_class": "BertJapaneseTokenizer",
3
+ "model_max_length": 512,
4
+ "do_lower_case": false,
5
+ "word_tokenizer_type": "mecab",
6
+ "subword_tokenizer_type": "wordpiece",
7
+ "mecab_kwargs": {
8
+ "mecab_dic": "unidic_lite"
9
+ }
10
+ }
bert/bert-base-japanese-v3/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
bert/bert-large-japanese-v2/.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
bert/bert-large-japanese-v2/README.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ datasets:
4
+ - cc100
5
+ - wikipedia
6
+ language:
7
+ - ja
8
+ widget:
9
+ - text: 東北大学で[MASK]の研究をしています。
10
+ ---
11
+
12
+ # BERT large Japanese (unidic-lite with whole word masking, CC-100 and jawiki-20230102)
13
+
14
+ This is a [BERT](https://github.com/google-research/bert) model pretrained on texts in the Japanese language.
15
+
16
+ This version of the model processes input texts with word-level tokenization based on the Unidic 2.1.2 dictionary (available in [unidic-lite](https://pypi.org/project/unidic-lite/) package), followed by the WordPiece subword tokenization.
17
+ Additionally, the model is trained with the whole word masking enabled for the masked language modeling (MLM) objective.
18
+
19
+ The codes for the pretraining are available at [cl-tohoku/bert-japanese](https://github.com/cl-tohoku/bert-japanese/).
20
+
21
+ ## Model architecture
22
+
23
+ The model architecture is the same as the original BERT large model; 24 layers, 1024 dimensions of hidden states, and 16 attention heads.
24
+
25
+ ## Training Data
26
+
27
+ The model is trained on the Japanese portion of [CC-100 dataset](https://data.statmt.org/cc-100/) and the Japanese version of Wikipedia.
28
+ For Wikipedia, we generated a text corpus from the [Wikipedia Cirrussearch dump file](https://dumps.wikimedia.org/other/cirrussearch/) as of January 2, 2023.
29
+ The corpus files generated from CC-100 and Wikipedia are 74.3GB and 4.9GB in size and consist of approximately 392M and 34M sentences, respectively.
30
+
31
+ For the purpose of splitting texts into sentences, we used [fugashi](https://github.com/polm/fugashi) with [mecab-ipadic-NEologd](https://github.com/neologd/mecab-ipadic-neologd) dictionary (v0.0.7).
32
+
33
+ ## Tokenization
34
+
35
+ The texts are first tokenized by MeCab with the Unidic 2.1.2 dictionary and then split into subwords by the WordPiece algorithm.
36
+ The vocabulary size is 32768.
37
+
38
+ We used [fugashi](https://github.com/polm/fugashi) and [unidic-lite](https://github.com/polm/unidic-lite) packages for the tokenization.
39
+
40
+ ## Training
41
+
42
+ We trained the model first on the CC-100 corpus for 1M steps and then on the Wikipedia corpus for another 1M steps.
43
+ For training of the MLM (masked language modeling) objective, we introduced whole word masking in which all of the subword tokens corresponding to a single word (tokenized by MeCab) are masked at once.
44
+
45
+ For training of each model, we used a v3-8 instance of Cloud TPUs provided by [TPU Research Cloud](https://sites.research.google/trc/about/).
46
+
47
+ ## Licenses
48
+
49
+ The pretrained models are distributed under the Apache License 2.0.
50
+
51
+ ## Acknowledgments
52
+
53
+ This model is trained with Cloud TPUs provided by [TPU Research Cloud](https://sites.research.google/trc/about/) program.
bert/bert-large-japanese-v2/config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForPreTraining"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "hidden_act": "gelu",
7
+ "hidden_dropout_prob": 0.1,
8
+ "hidden_size": 1024,
9
+ "initializer_range": 0.02,
10
+ "intermediate_size": 4096,
11
+ "layer_norm_eps": 1e-12,
12
+ "max_position_embeddings": 512,
13
+ "model_type": "bert",
14
+ "num_attention_heads": 16,
15
+ "num_hidden_layers": 24,
16
+ "pad_token_id": 0,
17
+ "type_vocab_size": 2,
18
+ "vocab_size": 32768
19
+ }
bert/bert-large-japanese-v2/tokenizer_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tokenizer_class": "BertJapaneseTokenizer",
3
+ "model_max_length": 512,
4
+ "do_lower_case": false,
5
+ "word_tokenizer_type": "mecab",
6
+ "subword_tokenizer_type": "wordpiece",
7
+ "mecab_kwargs": {
8
+ "mecab_dic": "unidic_lite"
9
+ }
10
+ }
bert/bert-large-japanese-v2/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
bert/bert_models.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "deberta-v2-large-japanese-char-wwm": {
3
+ "repo_id": "ku-nlp/deberta-v2-large-japanese-char-wwm",
4
+ "files": ["pytorch_model.bin"]
5
+ },
6
+ "chinese-roberta-wwm-ext-large": {
7
+ "repo_id": "hfl/chinese-roberta-wwm-ext-large",
8
+ "files": ["pytorch_model.bin"]
9
+ },
10
+ "deberta-v3-large": {
11
+ "repo_id": "microsoft/deberta-v3-large",
12
+ "files": ["spm.model", "pytorch_model.bin"]
13
+ }
14
+ }
bert/chinese-roberta-wwm-ext-large/.gitattributes ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
2
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.h5 filter=lfs diff=lfs merge=lfs -text
5
+ *.tflite filter=lfs diff=lfs merge=lfs -text
6
+ *.tar.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.ot filter=lfs diff=lfs merge=lfs -text
8
+ *.onnx filter=lfs diff=lfs merge=lfs -text
9
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
bert/chinese-roberta-wwm-ext-large/README.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ tags:
5
+ - bert
6
+ license: "apache-2.0"
7
+ ---
8
+
9
+ # Please use 'Bert' related functions to load this model!
10
+
11
+ ## Chinese BERT with Whole Word Masking
12
+ For further accelerating Chinese natural language processing, we provide **Chinese pre-trained BERT with Whole Word Masking**.
13
+
14
+ **[Pre-Training with Whole Word Masking for Chinese BERT](https://arxiv.org/abs/1906.08101)**
15
+ Yiming Cui, Wanxiang Che, Ting Liu, Bing Qin, Ziqing Yang, Shijin Wang, Guoping Hu
16
+
17
+ This repository is developed based on:https://github.com/google-research/bert
18
+
19
+ You may also interested in,
20
+ - Chinese BERT series: https://github.com/ymcui/Chinese-BERT-wwm
21
+ - Chinese MacBERT: https://github.com/ymcui/MacBERT
22
+ - Chinese ELECTRA: https://github.com/ymcui/Chinese-ELECTRA
23
+ - Chinese XLNet: https://github.com/ymcui/Chinese-XLNet
24
+ - Knowledge Distillation Toolkit - TextBrewer: https://github.com/airaria/TextBrewer
25
+
26
+ More resources by HFL: https://github.com/ymcui/HFL-Anthology
27
+
28
+ ## Citation
29
+ If you find the technical report or resource is useful, please cite the following technical report in your paper.
30
+ - Primary: https://arxiv.org/abs/2004.13922
31
+ ```
32
+ @inproceedings{cui-etal-2020-revisiting,
33
+ title = "Revisiting Pre-Trained Models for {C}hinese Natural Language Processing",
34
+ author = "Cui, Yiming and
35
+ Che, Wanxiang and
36
+ Liu, Ting and
37
+ Qin, Bing and
38
+ Wang, Shijin and
39
+ Hu, Guoping",
40
+ booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: Findings",
41
+ month = nov,
42
+ year = "2020",
43
+ address = "Online",
44
+ publisher = "Association for Computational Linguistics",
45
+ url = "https://www.aclweb.org/anthology/2020.findings-emnlp.58",
46
+ pages = "657--668",
47
+ }
48
+ ```
49
+ - Secondary: https://arxiv.org/abs/1906.08101
50
+ ```
51
+ @article{chinese-bert-wwm,
52
+ title={Pre-Training with Whole Word Masking for Chinese BERT},
53
+ author={Cui, Yiming and Che, Wanxiang and Liu, Ting and Qin, Bing and Yang, Ziqing and Wang, Shijin and Hu, Guoping},
54
+ journal={arXiv preprint arXiv:1906.08101},
55
+ year={2019}
56
+ }
57
+ ```
bert/chinese-roberta-wwm-ext-large/added_tokens.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
bert/chinese-roberta-wwm-ext-large/config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForMaskedLM"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "bos_token_id": 0,
7
+ "directionality": "bidi",
8
+ "eos_token_id": 2,
9
+ "hidden_act": "gelu",
10
+ "hidden_dropout_prob": 0.1,
11
+ "hidden_size": 1024,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 4096,
14
+ "layer_norm_eps": 1e-12,
15
+ "max_position_embeddings": 512,
16
+ "model_type": "bert",
17
+ "num_attention_heads": 16,
18
+ "num_hidden_layers": 24,
19
+ "output_past": true,
20
+ "pad_token_id": 0,
21
+ "pooler_fc_size": 768,
22
+ "pooler_num_attention_heads": 12,
23
+ "pooler_num_fc_layers": 3,
24
+ "pooler_size_per_head": 128,
25
+ "pooler_type": "first_token_transform",
26
+ "type_vocab_size": 2,
27
+ "vocab_size": 21128
28
+ }
bert/chinese-roberta-wwm-ext-large/special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"}
bert/chinese-roberta-wwm-ext-large/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
bert/chinese-roberta-wwm-ext-large/tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"init_inputs": []}
bert/chinese-roberta-wwm-ext-large/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
bert/deberta-v2-large-japanese-char-wwm/.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
bert/deberta-v2-large-japanese-char-wwm/README.md ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: ja
3
+ license: cc-by-sa-4.0
4
+ library_name: transformers
5
+ tags:
6
+ - deberta
7
+ - deberta-v2
8
+ - fill-mask
9
+ - character
10
+ - wwm
11
+ datasets:
12
+ - wikipedia
13
+ - cc100
14
+ - oscar
15
+ metrics:
16
+ - accuracy
17
+ mask_token: "[MASK]"
18
+ widget:
19
+ - text: "京都大学で自然言語処理を[MASK][MASK]する。"
20
+ ---
21
+
22
+ # Model Card for Japanese character-level DeBERTa V2 large
23
+
24
+ ## Model description
25
+
26
+ This is a Japanese DeBERTa V2 large model pre-trained on Japanese Wikipedia, the Japanese portion of CC-100, and the Japanese portion of OSCAR.
27
+ This model is trained with character-level tokenization and whole word masking.
28
+
29
+ ## How to use
30
+
31
+ You can use this model for masked language modeling as follows:
32
+
33
+ ```python
34
+ from transformers import AutoTokenizer, AutoModelForMaskedLM
35
+ tokenizer = AutoTokenizer.from_pretrained('ku-nlp/deberta-v2-large-japanese-char-wwm')
36
+ model = AutoModelForMaskedLM.from_pretrained('ku-nlp/deberta-v2-large-japanese-char-wwm')
37
+
38
+ sentence = '京都大学で自然言語処理を[MASK][MASK]する。'
39
+ encoding = tokenizer(sentence, return_tensors='pt')
40
+ ...
41
+ ```
42
+
43
+ You can also fine-tune this model on downstream tasks.
44
+
45
+ ## Tokenization
46
+
47
+ There is no need to tokenize texts in advance, and you can give raw texts to the tokenizer.
48
+ The texts are tokenized into character-level tokens by [sentencepiece](https://github.com/google/sentencepiece).
49
+
50
+ ## Training data
51
+
52
+ We used the following corpora for pre-training:
53
+
54
+ - Japanese Wikipedia (as of 20221020, 3.2GB, 27M sentences, 1.3M documents)
55
+ - Japanese portion of CC-100 (85GB, 619M sentences, 66M documents)
56
+ - Japanese portion of OSCAR (54GB, 326M sentences, 25M documents)
57
+
58
+ Note that we filtered out documents annotated with "header", "footer", or "noisy" tags in OSCAR.
59
+ Also note that Japanese Wikipedia was duplicated 10 times to make the total size of the corpus comparable to that of CC-100 and OSCAR. As a result, the total size of the training data is 171GB.
60
+
61
+ ## Training procedure
62
+
63
+ We first segmented texts in the corpora into words using [Juman++ 2.0.0-rc3](https://github.com/ku-nlp/jumanpp/releases/tag/v2.0.0-rc3) for whole word masking.
64
+ Then, we built a sentencepiece model with 22,012 tokens including all characters that appear in the training corpus.
65
+
66
+ We tokenized raw corpora into character-level subwords using the sentencepiece model and trained the Japanese DeBERTa model using [transformers](https://github.com/huggingface/transformers) library.
67
+ The training took 26 days using 16 NVIDIA A100-SXM4-40GB GPUs.
68
+
69
+ The following hyperparameters were used during pre-training:
70
+
71
+ - learning_rate: 1e-4
72
+ - per_device_train_batch_size: 26
73
+ - distributed_type: multi-GPU
74
+ - num_devices: 16
75
+ - gradient_accumulation_steps: 8
76
+ - total_train_batch_size: 3,328
77
+ - max_seq_length: 512
78
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-06
79
+ - lr_scheduler_type: linear schedule with warmup (lr = 0 at 300k steps)
80
+ - training_steps: 260,000
81
+ - warmup_steps: 10,000
82
+
83
+ The accuracy of the trained model on the masked language modeling task was 0.795.
84
+ The evaluation set consists of 5,000 randomly sampled documents from each of the training corpora.
85
+
86
+ ## Acknowledgments
87
+
88
+ This work was supported by Joint Usage/Research Center for Interdisciplinary Large-scale Information Infrastructures (JHPCN) through General Collaboration Project no. jh221004, "Developing a Platform for Constructing and Sharing of Large-Scale Japanese Language Models".
89
+ For training models, we used the mdx: a platform for the data-driven future.
bert/deberta-v2-large-japanese-char-wwm/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DebertaV2ForMaskedLM"
4
+ ],
5
+ "attention_head_size": 64,
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "conv_act": "gelu",
8
+ "conv_kernel_size": 3,
9
+ "hidden_act": "gelu",
10
+ "hidden_dropout_prob": 0.1,
11
+ "hidden_size": 1024,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 4096,
14
+ "layer_norm_eps": 1e-07,
15
+ "max_position_embeddings": 512,
16
+ "max_relative_positions": -1,
17
+ "model_type": "deberta-v2",
18
+ "norm_rel_ebd": "layer_norm",
19
+ "num_attention_heads": 16,
20
+ "num_hidden_layers": 24,
21
+ "pad_token_id": 0,
22
+ "pooler_dropout": 0,
23
+ "pooler_hidden_act": "gelu",
24
+ "pooler_hidden_size": 1024,
25
+ "pos_att_type": [
26
+ "p2c",
27
+ "c2p"
28
+ ],
29
+ "position_biased_input": false,
30
+ "position_buckets": 256,
31
+ "relative_attention": true,
32
+ "share_att_key": true,
33
+ "torch_dtype": "float16",
34
+ "transformers_version": "4.25.1",
35
+ "type_vocab_size": 0,
36
+ "vocab_size": 22012
37
+ }
bert/deberta-v2-large-japanese-char-wwm/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
bert/deberta-v2-large-japanese-char-wwm/tokenizer_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "do_lower_case": false,
4
+ "do_subword_tokenize": true,
5
+ "do_word_tokenize": true,
6
+ "jumanpp_kwargs": null,
7
+ "mask_token": "[MASK]",
8
+ "mecab_kwargs": null,
9
+ "model_max_length": 1000000000000000019884624838656,
10
+ "never_split": null,
11
+ "pad_token": "[PAD]",
12
+ "sep_token": "[SEP]",
13
+ "special_tokens_map_file": null,
14
+ "subword_tokenizer_type": "character",
15
+ "sudachi_kwargs": null,
16
+ "tokenizer_class": "BertJapaneseTokenizer",
17
+ "unk_token": "[UNK]",
18
+ "word_tokenizer_type": "basic"
19
+ }
bert/deberta-v2-large-japanese-char-wwm/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
bert/deberta-v2-large-japanese/.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
bert/deberta-v2-large-japanese/README.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: ja
3
+ license: cc-by-sa-4.0
4
+ library_name: transformers
5
+ tags:
6
+ - deberta
7
+ - deberta-v2
8
+ - fill-mask
9
+ datasets:
10
+ - wikipedia
11
+ - cc100
12
+ - oscar
13
+ metrics:
14
+ - accuracy
15
+ mask_token: "[MASK]"
16
+ widget:
17
+ - text: "京都 大学 で 自然 言語 処理 を [MASK] する 。"
18
+ ---
19
+
20
+ # Model Card for Japanese DeBERTa V2 large
21
+
22
+ ## Model description
23
+
24
+ This is a Japanese DeBERTa V2 large model pre-trained on Japanese Wikipedia, the Japanese portion of CC-100, and the
25
+ Japanese portion of OSCAR.
26
+
27
+ ## How to use
28
+
29
+ You can use this model for masked language modeling as follows:
30
+
31
+ ```python
32
+ from transformers import AutoTokenizer, AutoModelForMaskedLM
33
+
34
+ tokenizer = AutoTokenizer.from_pretrained('ku-nlp/deberta-v2-large-japanese')
35
+ model = AutoModelForMaskedLM.from_pretrained('ku-nlp/deberta-v2-large-japanese')
36
+
37
+ sentence = '京都 大学 で 自然 言語 処理 を [MASK] する 。' # input should be segmented into words by Juman++ in advance
38
+ encoding = tokenizer(sentence, return_tensors='pt')
39
+ ...
40
+ ```
41
+
42
+ You can also fine-tune this model on downstream tasks.
43
+
44
+ ## Tokenization
45
+
46
+ The input text should be segmented into words by [Juman++](https://github.com/ku-nlp/jumanpp) in
47
+ advance. [Juman++ 2.0.0-rc3](https://github.com/ku-nlp/jumanpp/releases/tag/v2.0.0-rc3) was used for pre-training. Each
48
+ word is tokenized into subwords by [sentencepiece](https://github.com/google/sentencepiece).
49
+
50
+ ## Training data
51
+
52
+ We used the following corpora for pre-training:
53
+
54
+ - Japanese Wikipedia (as of 20221020, 3.2GB, 27M sentences, 1.3M documents)
55
+ - Japanese portion of CC-100 (85GB, 619M sentences, 66M documents)
56
+ - Japanese portion of OSCAR (54GB, 326M sentences, 25M documents)
57
+
58
+ Note that we filtered out documents annotated with "header", "footer", or "noisy" tags in OSCAR.
59
+ Also note that Japanese Wikipedia was duplicated 10 times to make the total size of the corpus comparable to that of
60
+ CC-100 and OSCAR. As a result, the total size of the training data is 171GB.
61
+
62
+ ## Training procedure
63
+
64
+ We first segmented texts in the corpora into words using [Juman++](https://github.com/ku-nlp/jumanpp).
65
+ Then, we built a sentencepiece model with 32000 tokens including words ([JumanDIC](https://github.com/ku-nlp/JumanDIC))
66
+ and subwords induced by the unigram language model of [sentencepiece](https://github.com/google/sentencepiece).
67
+
68
+ We tokenized the segmented corpora into subwords using the sentencepiece model and trained the Japanese DeBERTa model
69
+ using [transformers](https://github.com/huggingface/transformers) library.
70
+ The training took 36 days using 8 NVIDIA A100-SXM4-40GB GPUs.
71
+
72
+ The following hyperparameters were used during pre-training:
73
+
74
+ - learning_rate: 1e-4
75
+ - per_device_train_batch_size: 18
76
+ - distributed_type: multi-GPU
77
+ - num_devices: 8
78
+ - gradient_accumulation_steps: 16
79
+ - total_train_batch_size: 2,304
80
+ - max_seq_length: 512
81
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-06
82
+ - lr_scheduler_type: linear schedule with warmup
83
+ - training_steps: 300,000
84
+ - warmup_steps: 10,000
85
+
86
+ The accuracy of the trained model on the masked language modeling task was 0.799.
87
+ The evaluation set consists of 5,000 randomly sampled documents from each of the training corpora.
88
+
89
+ ## Fine-tuning on NLU tasks
90
+
91
+ We fine-tuned the following models and evaluated them on the dev set of JGLUE.
92
+ We tuned learning rate and training epochs for each model and task
93
+ following [the JGLUE paper](https://www.jstage.jst.go.jp/article/jnlp/30/1/30_63/_pdf/-char/ja).
94
+
95
+ | Model | MARC-ja/acc | JSTS/pearson | JSTS/spearman | JNLI/acc | JSQuAD/EM | JSQuAD/F1 | JComQA/acc |
96
+ |-------------------------------|-------------|--------------|---------------|----------|-----------|-----------|------------|
97
+ | Waseda RoBERTa base | 0.965 | 0.913 | 0.876 | 0.905 | 0.853 | 0.916 | 0.853 |
98
+ | Waseda RoBERTa large (seq512) | 0.969 | 0.925 | 0.890 | 0.928 | 0.910 | 0.955 | 0.900 |
99
+ | LUKE Japanese base* | 0.965 | 0.916 | 0.877 | 0.912 | - | - | 0.842 |
100
+ | LUKE Japanese large* | 0.965 | 0.932 | 0.902 | 0.927 | - | - | 0.893 |
101
+ | DeBERTaV2 base | 0.970 | 0.922 | 0.886 | 0.922 | 0.899 | 0.951 | 0.873 |
102
+ | DeBERTaV2 large | 0.968 | 0.925 | 0.892 | 0.924 | 0.912 | 0.959 | 0.890 |
103
+
104
+ *The scores of LUKE are from [the official repository](https://github.com/studio-ousia/luke).
105
+
106
+ ## Acknowledgments
107
+
108
+ This work was supported by Joint Usage/Research Center for Interdisciplinary Large-scale Information Infrastructures (
109
+ JHPCN) through General Collaboration Project no. jh221004, "Developing a Platform for Constructing and Sharing of
110
+ Large-Scale Japanese Language Models".
111
+ For training models, we used the mdx: a platform for the data-driven future.
bert/deberta-v2-large-japanese/config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "configs/deberta_v2_large.json",
3
+ "architectures": [
4
+ "DebertaV2ForMaskedLM"
5
+ ],
6
+ "attention_head_size": 64,
7
+ "attention_probs_dropout_prob": 0.1,
8
+ "conv_act": "gelu",
9
+ "conv_kernel_size": 3,
10
+ "hidden_act": "gelu",
11
+ "hidden_dropout_prob": 0.1,
12
+ "hidden_size": 1024,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 4096,
15
+ "layer_norm_eps": 1e-07,
16
+ "max_position_embeddings": 512,
17
+ "max_relative_positions": -1,
18
+ "model_type": "deberta-v2",
19
+ "norm_rel_ebd": "layer_norm",
20
+ "num_attention_heads": 16,
21
+ "num_hidden_layers": 24,
22
+ "pad_token_id": 0,
23
+ "pooler_dropout": 0,
24
+ "pooler_hidden_act": "gelu",
25
+ "pooler_hidden_size": 1024,
26
+ "pos_att_type": [
27
+ "p2c",
28
+ "c2p"
29
+ ],
30
+ "position_biased_input": false,
31
+ "position_buckets": 256,
32
+ "relative_attention": true,
33
+ "share_att_key": true,
34
+ "torch_dtype": "float32",
35
+ "transformers_version": "4.23.1",
36
+ "type_vocab_size": 0,
37
+ "vocab_size": 32000
38
+ }
bert/deberta-v2-large-japanese/special_tokens_map.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "[CLS]",
3
+ "cls_token": "[CLS]",
4
+ "eos_token": "[SEP]",
5
+ "mask_token": "[MASK]",
6
+ "pad_token": "[PAD]",
7
+ "sep_token": "[SEP]",
8
+ "unk_token": "[UNK]"
9
+ }
bert/deberta-v2-large-japanese/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
bert/deberta-v2-large-japanese/tokenizer_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "[CLS]",
3
+ "cls_token": "[CLS]",
4
+ "do_lower_case": false,
5
+ "eos_token": "[SEP]",
6
+ "keep_accents": true,
7
+ "mask_token": "[MASK]",
8
+ "pad_token": "[PAD]",
9
+ "sep_token": "[SEP]",
10
+ "sp_model_kwargs": {},
11
+ "special_tokens_map_file": null,
12
+ "split_by_punct": false,
13
+ "tokenizer_class": "DebertaV2Tokenizer",
14
+ "unk_token": "[UNK]"
15
+ }
bert/deberta-v3-large/.gitattributes ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 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
+ *.model filter=lfs diff=lfs merge=lfs -text
12
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
13
+ *.onnx filter=lfs diff=lfs merge=lfs -text
14
+ *.ot filter=lfs diff=lfs merge=lfs -text
15
+ *.parquet filter=lfs diff=lfs merge=lfs -text
16
+ *.pb filter=lfs diff=lfs merge=lfs -text
17
+ *.pt filter=lfs diff=lfs merge=lfs -text
18
+ *.pth filter=lfs diff=lfs merge=lfs -text
19
+ *.rar filter=lfs diff=lfs merge=lfs -text
20
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
21
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
22
+ *.tflite filter=lfs diff=lfs merge=lfs -text
23
+ *.tgz filter=lfs diff=lfs merge=lfs -text
24
+ *.xz filter=lfs diff=lfs merge=lfs -text
25
+ *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
bert/deberta-v3-large/README.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: en
3
+ tags:
4
+ - deberta
5
+ - deberta-v3
6
+ - fill-mask
7
+ thumbnail: https://huggingface.co/front/thumbnails/microsoft.png
8
+ license: mit
9
+ ---
10
+
11
+ ## DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing
12
+
13
+ [DeBERTa](https://arxiv.org/abs/2006.03654) improves the BERT and RoBERTa models using disentangled attention and enhanced mask decoder. With those two improvements, DeBERTa out perform RoBERTa on a majority of NLU tasks with 80GB training data.
14
+
15
+ In [DeBERTa V3](https://arxiv.org/abs/2111.09543), we further improved the efficiency of DeBERTa using ELECTRA-Style pre-training with Gradient Disentangled Embedding Sharing. Compared to DeBERTa, our V3 version significantly improves the model performance on downstream tasks. You can find more technique details about the new model from our [paper](https://arxiv.org/abs/2111.09543).
16
+
17
+ Please check the [official repository](https://github.com/microsoft/DeBERTa) for more implementation details and updates.
18
+
19
+ The DeBERTa V3 large model comes with 24 layers and a hidden size of 1024. It has 304M backbone parameters with a vocabulary containing 128K tokens which introduces 131M parameters in the Embedding layer. This model was trained using the 160GB data as DeBERTa V2.
20
+
21
+
22
+ #### Fine-tuning on NLU tasks
23
+
24
+ We present the dev results on SQuAD 2.0 and MNLI tasks.
25
+
26
+ | Model |Vocabulary(K)|Backbone #Params(M)| SQuAD 2.0(F1/EM) | MNLI-m/mm(ACC)|
27
+ |-------------------|----------|-------------------|-----------|----------|
28
+ | RoBERTa-large |50 |304 | 89.4/86.5 | 90.2 |
29
+ | XLNet-large |32 |- | 90.6/87.9 | 90.8 |
30
+ | DeBERTa-large |50 |- | 90.7/88.0 | 91.3 |
31
+ | **DeBERTa-v3-large**|128|304 | **91.5/89.0**| **91.8/91.9**|
32
+
33
+
34
+ #### Fine-tuning with HF transformers
35
+
36
+ ```bash
37
+ #!/bin/bash
38
+
39
+ cd transformers/examples/pytorch/text-classification/
40
+
41
+ pip install datasets
42
+ export TASK_NAME=mnli
43
+
44
+ output_dir="ds_results"
45
+
46
+ num_gpus=8
47
+
48
+ batch_size=8
49
+
50
+ python -m torch.distributed.launch --nproc_per_node=${num_gpus} \
51
+ run_glue.py \
52
+ --model_name_or_path microsoft/deberta-v3-large \
53
+ --task_name $TASK_NAME \
54
+ --do_train \
55
+ --do_eval \
56
+ --evaluation_strategy steps \
57
+ --max_seq_length 256 \
58
+ --warmup_steps 50 \
59
+ --per_device_train_batch_size ${batch_size} \
60
+ --learning_rate 6e-6 \
61
+ --num_train_epochs 2 \
62
+ --output_dir $output_dir \
63
+ --overwrite_output_dir \
64
+ --logging_steps 1000 \
65
+ --logging_dir $output_dir
66
+
67
+ ```
68
+
69
+ ### Citation
70
+
71
+ If you find DeBERTa useful for your work, please cite the following papers:
72
+
73
+ ``` latex
74
+ @misc{he2021debertav3,
75
+ title={DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing},
76
+ author={Pengcheng He and Jianfeng Gao and Weizhu Chen},
77
+ year={2021},
78
+ eprint={2111.09543},
79
+ archivePrefix={arXiv},
80
+ primaryClass={cs.CL}
81
+ }
82
+ ```
83
+
84
+ ``` latex
85
+ @inproceedings{
86
+ he2021deberta,
87
+ title={DEBERTA: DECODING-ENHANCED BERT WITH DISENTANGLED ATTENTION},
88
+ author={Pengcheng He and Xiaodong Liu and Jianfeng Gao and Weizhu Chen},
89
+ booktitle={International Conference on Learning Representations},
90
+ year={2021},
91
+ url={https://openreview.net/forum?id=XPZIaotutsD}
92
+ }
93
+ ```
bert/deberta-v3-large/config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "deberta-v2",
3
+ "attention_probs_dropout_prob": 0.1,
4
+ "hidden_act": "gelu",
5
+ "hidden_dropout_prob": 0.1,
6
+ "hidden_size": 1024,
7
+ "initializer_range": 0.02,
8
+ "intermediate_size": 4096,
9
+ "max_position_embeddings": 512,
10
+ "relative_attention": true,
11
+ "position_buckets": 256,
12
+ "norm_rel_ebd": "layer_norm",
13
+ "share_att_key": true,
14
+ "pos_att_type": "p2c|c2p",
15
+ "layer_norm_eps": 1e-7,
16
+ "max_relative_positions": -1,
17
+ "position_biased_input": false,
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 24,
20
+ "type_vocab_size": 0,
21
+ "vocab_size": 128100
22
+ }
bert/deberta-v3-large/generator_config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "deberta-v2",
3
+ "attention_probs_dropout_prob": 0.1,
4
+ "hidden_act": "gelu",
5
+ "hidden_dropout_prob": 0.1,
6
+ "hidden_size": 1024,
7
+ "initializer_range": 0.02,
8
+ "intermediate_size": 4096,
9
+ "max_position_embeddings": 512,
10
+ "relative_attention": true,
11
+ "position_buckets": 256,
12
+ "norm_rel_ebd": "layer_norm",
13
+ "share_att_key": true,
14
+ "pos_att_type": "p2c|c2p",
15
+ "layer_norm_eps": 1e-7,
16
+ "max_relative_positions": -1,
17
+ "position_biased_input": false,
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 12,
20
+ "type_vocab_size": 0,
21
+ "vocab_size": 128100
22
+ }
bert/deberta-v3-large/tokenizer_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "do_lower_case": false,
3
+ "vocab_type": "spm"
4
+ }
bert_gen.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from multiprocessing import Pool, cpu_count
3
+
4
+ import torch
5
+ import torch.multiprocessing as mp
6
+ from tqdm import tqdm
7
+
8
+ import commons
9
+ import utils
10
+ from config import config
11
+ from text import cleaned_text_to_sequence, get_bert
12
+
13
+
14
+ def process_line(line):
15
+ device = config.bert_gen_config.device
16
+ if config.bert_gen_config.use_multi_device:
17
+ rank = mp.current_process()._identity
18
+ rank = rank[0] if len(rank) > 0 else 0
19
+ if torch.cuda.is_available():
20
+ gpu_id = rank % torch.cuda.device_count()
21
+ device = torch.device(f"cuda:{gpu_id}")
22
+ else:
23
+ device = torch.device("cpu")
24
+ wav_path, _, language_str, text, phones, tone, word2ph = line.strip().split("|")
25
+ phone = phones.split(" ")
26
+ tone = [int(i) for i in tone.split(" ")]
27
+ word2ph = [int(i) for i in word2ph.split(" ")]
28
+ word2ph = [i for i in word2ph]
29
+ phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
30
+
31
+ phone = commons.intersperse(phone, 0)
32
+ tone = commons.intersperse(tone, 0)
33
+ language = commons.intersperse(language, 0)
34
+ for i in range(len(word2ph)):
35
+ word2ph[i] = word2ph[i] * 2
36
+ word2ph[0] += 1
37
+
38
+ bert_path = wav_path.replace(".WAV", ".wav").replace(".wav", ".bert.pt")
39
+
40
+ try:
41
+ bert = torch.load(bert_path)
42
+ assert bert.shape[-1] == len(phone)
43
+ except Exception:
44
+ bert = get_bert(text, word2ph, language_str, device)
45
+ assert bert.shape[-1] == len(phone)
46
+ torch.save(bert, bert_path)
47
+
48
+
49
+ preprocess_text_config = config.preprocess_text_config
50
+
51
+ if __name__ == "__main__":
52
+ parser = argparse.ArgumentParser()
53
+ parser.add_argument(
54
+ "-c", "--config", type=str, default=config.bert_gen_config.config_path
55
+ )
56
+ parser.add_argument(
57
+ "--num_processes", type=int, default=config.bert_gen_config.num_processes
58
+ )
59
+ args, _ = parser.parse_known_args()
60
+ config_path = args.config
61
+ hps = utils.get_hparams_from_file(config_path)
62
+ lines = []
63
+ with open(hps.data.training_files, encoding="utf-8") as f:
64
+ lines.extend(f.readlines())
65
+
66
+ with open(hps.data.validation_files, encoding="utf-8") as f:
67
+ lines.extend(f.readlines())
68
+ if len(lines) != 0:
69
+ num_processes = min(args.num_processes, cpu_count())
70
+ with Pool(processes=num_processes) as pool:
71
+ for _ in tqdm(pool.imap_unordered(process_line, lines), total=len(lines)):
72
+ pass
73
+
74
+ print(f"bert生成完毕!, 共有{len(lines)}个bert.pt生成!")
clean_list.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import shutil
3
+ from tempfile import NamedTemporaryFile
4
+
5
+ from loguru import logger
6
+
7
+
8
+ def remove_chars_from_file(chars_to_remove, input_file, output_file):
9
+ rm_cnt = 0
10
+ with open(input_file, "r", encoding="utf-8") as f_in, NamedTemporaryFile(
11
+ "w", delete=False, encoding="utf-8"
12
+ ) as f_tmp:
13
+ for line in f_in:
14
+ if any(char in line for char in chars_to_remove):
15
+ logger.info(f"删除了这一行:\n {line.strip()}")
16
+ rm_cnt += 1
17
+ else:
18
+ f_tmp.write(line)
19
+
20
+ shutil.move(f_tmp.name, output_file)
21
+ logger.critical(f"总计移除了: {rm_cnt} 行")
22
+
23
+
24
+ if __name__ == "__main__":
25
+ parser = argparse.ArgumentParser(
26
+ description="Remove lines from a file containing specified characters."
27
+ )
28
+
29
+ parser.add_argument(
30
+ "-c",
31
+ "--chars",
32
+ type=str,
33
+ required=True,
34
+ help="String of characters. If a line contains any of these characters, it will be removed.",
35
+ )
36
+ parser.add_argument(
37
+ "-i", "--input", type=str, required=True, help="Path to the input file."
38
+ )
39
+ parser.add_argument(
40
+ "-o", "--output", type=str, required=True, help="Path to the output file."
41
+ )
42
+
43
+ args = parser.parse_args()
44
+
45
+ # Setting up basic logging configuration for loguru
46
+ logger.add("removed_lines.log", rotation="1 MB")
47
+
48
+ remove_chars_from_file(args.chars, args.input, args.output)
commons.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch.nn import functional as F
4
+
5
+
6
+ def init_weights(m, mean=0.0, std=0.01):
7
+ classname = m.__class__.__name__
8
+ if classname.find("Conv") != -1:
9
+ m.weight.data.normal_(mean, std)
10
+
11
+
12
+ def get_padding(kernel_size, dilation=1):
13
+ return int((kernel_size * dilation - dilation) / 2)
14
+
15
+
16
+ def convert_pad_shape(pad_shape):
17
+ layer = pad_shape[::-1]
18
+ pad_shape = [item for sublist in layer for item in sublist]
19
+ return pad_shape
20
+
21
+
22
+ def intersperse(lst, item):
23
+ result = [item] * (len(lst) * 2 + 1)
24
+ result[1::2] = lst
25
+ return result
26
+
27
+
28
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
29
+ """KL(P||Q)"""
30
+ kl = (logs_q - logs_p) - 0.5
31
+ kl += (
32
+ 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
33
+ )
34
+ return kl
35
+
36
+
37
+ def rand_gumbel(shape):
38
+ """Sample from the Gumbel distribution, protect from overflows."""
39
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
40
+ return -torch.log(-torch.log(uniform_samples))
41
+
42
+
43
+ def rand_gumbel_like(x):
44
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
45
+ return g
46
+
47
+
48
+ def slice_segments(x, ids_str, segment_size=4):
49
+ ret = torch.zeros_like(x[:, :, :segment_size])
50
+ for i in range(x.size(0)):
51
+ idx_str = ids_str[i]
52
+ idx_end = idx_str + segment_size
53
+ if idx_str < 0:
54
+ i1 = x.size(2) + idx_str
55
+ r1 = x[i, :, i1:]
56
+ r2 = x[i, :, :idx_end]
57
+ ret[i] = torch.cat([r1, r2], dim=1)
58
+ else:
59
+ ret[i] = x[i, :, idx_str:idx_end]
60
+ return ret
61
+
62
+
63
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
64
+ b, d, t = x.size()
65
+ if x_lengths is None:
66
+ x_lengths = t
67
+ ids_str_max = x_lengths - segment_size + 1
68
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
69
+ ret = slice_segments(x, ids_str, segment_size)
70
+ return ret, ids_str
71
+
72
+
73
+ def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
74
+ position = torch.arange(length, dtype=torch.float)
75
+ num_timescales = channels // 2
76
+ log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (
77
+ num_timescales - 1
78
+ )
79
+ inv_timescales = min_timescale * torch.exp(
80
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
81
+ )
82
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
83
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
84
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
85
+ signal = signal.view(1, channels, length)
86
+ return signal
87
+
88
+
89
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
90
+ b, channels, length = x.size()
91
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
92
+ return x + signal.to(dtype=x.dtype, device=x.device)
93
+
94
+
95
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
96
+ b, channels, length = x.size()
97
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
98
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
99
+
100
+
101
+ def subsequent_mask(length):
102
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
103
+ return mask
104
+
105
+
106
+ @torch.jit.script
107
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
108
+ n_channels_int = n_channels[0]
109
+ in_act = input_a + input_b
110
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
111
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
112
+ acts = t_act * s_act
113
+ return acts
114
+
115
+
116
+ def convert_pad_shape(pad_shape):
117
+ layer = pad_shape[::-1]
118
+ pad_shape = [item for sublist in layer for item in sublist]
119
+ return pad_shape
120
+
121
+
122
+ def shift_1d(x):
123
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
124
+ return x
125
+
126
+
127
+ def sequence_mask(length, max_length=None):
128
+ if max_length is None:
129
+ max_length = length.max()
130
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
131
+ return x.unsqueeze(0) < length.unsqueeze(1)
132
+
133
+
134
+ def generate_path(duration, mask):
135
+ """
136
+ duration: [b, 1, t_x]
137
+ mask: [b, 1, t_y, t_x]
138
+ """
139
+
140
+ b, _, t_y, t_x = mask.shape
141
+ cum_duration = torch.cumsum(duration, -1)
142
+
143
+ cum_duration_flat = cum_duration.view(b * t_x)
144
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
145
+ path = path.view(b, t_x, t_y)
146
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
147
+ path = path.unsqueeze(1).transpose(2, 3) * mask
148
+ return path
149
+
150
+
151
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
152
+ if isinstance(parameters, torch.Tensor):
153
+ parameters = [parameters]
154
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
155
+ norm_type = float(norm_type)
156
+ if clip_value is not None:
157
+ clip_value = float(clip_value)
158
+
159
+ total_norm = 0
160
+ for p in parameters:
161
+ param_norm = p.grad.data.norm(norm_type)
162
+ total_norm += param_norm.item() ** norm_type
163
+ if clip_value is not None:
164
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
165
+ total_norm = total_norm ** (1.0 / norm_type)
166
+ return total_norm