LeoFeng commited on
Commit
e129232
·
1 Parent(s): de59356
Files changed (6) hide show
  1. LICENSE +201 -0
  2. README.md +182 -0
  3. cli.py +78 -0
  4. expert.py +145 -0
  5. model.pt +3 -0
  6. requirements.txt +2 -0
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SUPERB Submission Template
2
+
3
+ Welcome to the [SUPERB Challenge](https://superbbenchmark.org/challenge-slt2022/challenge_overview)! SUPERB is a collection of benchmarking resources to evaluate the capability of a universal shared representation for speech processing. It comes with a benchmark on the publicly available datasets and a challenge on a secret/not released hidden dataset. In SUPERB Challenge, a challenging hidden dataset is newly recorded to evaluate the ultimate generaliziblity across various tasks and data.
4
+
5
+ You can participate the challenge by simply submitting your self-supervised (SSL) pretrained models (model definition & pretrained weights), and we benchmark it with the hidden datasets. This repository constains useful tools to let you easliy [submit](https://superbbenchmark.org/submit) your models ***privately*** for evaluation to [the challenge hidden-set leaderboard](https://superbbenchmark.org/leaderboard?track=constrained&subset=Hidden+Dev+Set).
6
+
7
+ 1. Generate a submission template
8
+ 2. Validate the format/interface correctness of your model
9
+ 3. Upload to Huggingface's Hub (privately)
10
+ 4. Submit the upload information to [SUPERB website](https://superbbenchmark.org/submit)
11
+
12
+ #### Note 1.
13
+
14
+ We accept pre-trained models in PyTorch by default. If you wish to submit upstreams in non-PyTorch frameworks, please mail to [[email protected]](mailto:[email protected])!
15
+
16
+ #### Note 2.
17
+
18
+ If you are not feasible to submit the pre-trained model, please mail to [[email protected]](mailto:[email protected]) for us to see how to help!
19
+
20
+ ## Quickstart
21
+
22
+ ### 1. Add model interfaces
23
+
24
+ #### forward
25
+
26
+ Extract features from waveforms.
27
+
28
+ - **Input:** A list of waveforms in 16000 Hz
29
+
30
+ ```python
31
+ SAMPLE_RATE = 16000
32
+ BATCH_SIZE = 8
33
+ EXAMPLE_SEC = 10
34
+ wavs = [torch.randn(SAMPLE_RATE * EXAMPLE_SEC).cuda() for _ in range(BATCH_SIZE)]
35
+ ```
36
+
37
+ - **Output:** A dictionary with a key "hidden_states" (for compatiblility with old ver.). The value is **a list** of padded sequences in the same shape of **(batch_size, max_sequence_length_of_batch, hidden_size)** for weighted-sum to work. It is welcome to perform some task-specified / independent pre- / post-processing on the upstream's raw hidden-sets, including upsampling and downsampling. However, all the values must come from **a single upstream model**:
38
+
39
+ ```python
40
+ tasks = ["hidden_states", "PR", "SID", "ER", "ASR", "ASV", "SD", "QbE", "ST", "SS", "SE", "secret"]
41
+ for task in tasks:
42
+ # you can do task-specified pre- / post-processing depend on the arg "upstream_feature_selection"
43
+ results = upstream(wavs, upstream_feature_selection=task)
44
+ hidden_states = results["hidden_states"]
45
+ assert isinstance(results, dict)
46
+ assert isinstance(hidden_states, list)
47
+
48
+ for state in hidden_states:
49
+ assert isinstance(state, torch.Tensor)
50
+ assert state.dim() == 3, "(batch_size, max_sequence_length_of_batch, hidden_size)"
51
+ assert state.shape == hidden_states[0].shape
52
+ ```
53
+
54
+ #### get_downsample_rates
55
+
56
+ Provide the downsample rate **from 16000 Hz waveforms** for each task's representation in the dict. For the standard 10ms stride representation, the downsample rate is 160.
57
+
58
+ ```python
59
+ SAMPLE_RATE = 16000
60
+ MSEC_PER_SEC = 1000
61
+ downsample_rate = SAMPLE_RATE * 10 / MSEC_PER_SEC # 160
62
+ ```
63
+
64
+ The downsample rate will be used to:
65
+
66
+ 1. Calculate the valid representation length of each utterance in the output padded representation.
67
+ 2. Prepare the training materials according to the representation's downsample rate for frame-level tasks, e.g. SD, SE, and SS.
68
+
69
+ - **Input:** the task key (str)
70
+ - **Output:** the downsample rate (int) of the representation for that task
71
+
72
+ ```python
73
+ for task in tasks:
74
+ assert isinstance(task, str)
75
+ downsample_rate = upstream.get_downsample_rate(task)
76
+ assert isinstance(downsample_rate, int)
77
+ print("The upstream's representation for {task}"
78
+ f" has the downsample rate of {downsample_rate}.")
79
+ ```
80
+
81
+ ### 2. Create an account and organization on the Hugging Face Hub
82
+
83
+ First create an account on the Hugging Face Hub and you can sign up [here](https://huggingface.co/join) if you haven't already! Next, create a new organization and invite the SUPERB Hidden Set Committee to join. You will upload your model to a repository under this organization so that members inside it can access the model which is not publicly available.
84
+
85
+ * [superb-hidden-set](https://huggingface.co/superb-hidden-set)
86
+
87
+ ### 3. Create a template repository on your machine
88
+
89
+ The next step is to create a template repository on your local machine that contains various files and a CLI to help you validate and submit your pretrained models. The Hugging Face Hub uses [Git Large File Storage (LFS)](https://git-lfs.github.com) to manage large files, so first install it if you don't have it already. For example, on macOS you can run:
90
+
91
+ ```bash
92
+ brew install git-lfs
93
+ git lfs install
94
+ ```
95
+
96
+ Next, run the following commands to create the repository. We recommend creating a Python virtual environment for the project, e.g. with Anaconda:
97
+
98
+ ```bash
99
+ # Create and activate a virtual environment
100
+ conda create -n superb-submit python=3.8 && conda activate superb-submit
101
+ # Install the following libraries
102
+ pip install cookiecutter huggingface-hub==0.0.16
103
+ # Create the template repository
104
+ cookiecutter git+https://huggingface.co/superb/superb-submission
105
+ ```
106
+
107
+ This will ask you to specify your Hugging Face Hub username, password, organisation, and the name of the repository:
108
+
109
+ ```
110
+ hf_hub_username [<huggingface>]:
111
+ hf_hub_password [<password>]:
112
+ hf_hub_organisation [superb-submissions]:
113
+ repo_name [<my-superb-submissions>]:
114
+ ```
115
+
116
+ This will trigger the following steps:
117
+
118
+ 1. Create a private dataset repository on the Hugging Face Hub under `{hf_hub_organisation}/{repo_name}`
119
+ 2. Clone the repository to your local machine
120
+ 3. Add various template files, commit them locally to the repository, and push them to the Hub
121
+
122
+ The resulting repository should have the following structure:
123
+
124
+ ```
125
+ my-superb-submission
126
+ ├── LICENSE
127
+ ├── README.md <- The README with submission instructions
128
+ ├── cli.py <- The CLI for validating predictions etc
129
+ └── requirements.txt <- The requirements packages for the submissions
130
+ ├── expert.py <- Your model definition
131
+ └── model.pt <- Your model weights
132
+ ```
133
+
134
+ ### 4. Install the dependencies
135
+
136
+ The final step is to install the project's dependencies:
137
+
138
+ ```bash
139
+ # Navigate to the template repository
140
+ cd my-superb-submission
141
+ # Install dependencies
142
+ python -m pip install -r requirements.txt
143
+ ```
144
+
145
+ That's it! You're now all set to start pretraining your speech models - see the instructions below on how to submit them to the Hub.
146
+
147
+
148
+ ## Submitting to the leaderboard
149
+
150
+ To make a submission to the [leaderboard](https://superbbenchmark.org/leaderboard?subset=Hidden+Dev+Set), there are 4 main steps:
151
+
152
+ 1. Modify `expert.py` and change `model.pt` so we can initialize an upstream model following the [challenge policy](https://superbbenchmark.org/challenge-slt2022/upstream) by:
153
+
154
+ ```python
155
+ upstream = UpstreamExpert(ckpt="./model.pt")
156
+ ```
157
+
158
+ ***Package Dependency:*** Note that we only install `torch` package so far by following the above steps. If your model needs more packages, you can modify the `requirement.txt` to meet your need and install them inside the current conda environment. We will install the packages you list in the `requirement.txt` before initializing the upstream model.
159
+
160
+ 2. Validate the upstream model's interface meets the requirements in the [challenge policy](https://superbbenchmark.org/challenge-slt2022/upstream). If everything is correct, you should see the following message: "All submission files validated! Now you can make a submission."
161
+
162
+ ```
163
+ python cli.py validate
164
+ ```
165
+
166
+ 3. Push the model to the Hub! If there are no errors, you should see the following message: "Upload successful!"
167
+
168
+ ```
169
+ python cli.py upload "commit message: my best model"
170
+ ```
171
+
172
+ 4. [Make a submission at SUPERB website](https://superbbenchmark.org/submit) by uniquely indentifying this uploaded model with the following information, which can be shown by:
173
+
174
+ ```
175
+ python cli.py info
176
+ ```
177
+
178
+ - Organization Name
179
+ - Repository Name
180
+ - Commit Hash (full 40 characters)
181
+
182
+ After you finish the above 4 steps. You will see a new entry in your [SUPERB profile page](https://superbbenchmark.org/profile) (need login) which does not have any benchmark numbers yet. Please wait for us to finetuned it on the hidden dataset and get the benchmark results. The results will be revealed within one week. Please stay tuned!
cli.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import typer
2
+ import torch
3
+ import subprocess
4
+ from pathlib import Path
5
+
6
+ from expert import UpstreamExpert
7
+
8
+ SUBMISSION_FILES = ["expert.py", "model.pt"]
9
+ SAMPLE_RATE = 16000
10
+ SECONDS = [2, 1.8, 3.7]
11
+
12
+ app = typer.Typer()
13
+
14
+ @app.command()
15
+ def validate():
16
+ # Check that all the expected files exist
17
+ for file in SUBMISSION_FILES:
18
+ if not Path(file).is_file():
19
+ raise ValueError(f"File {file} not found! Please include {file} in your submission")
20
+
21
+ try:
22
+ upstream = UpstreamExpert(ckpt="model.pt")
23
+ samples = [round(SAMPLE_RATE * sec) for sec in SECONDS]
24
+ wavs = [torch.rand(sample) for sample in samples]
25
+ results = upstream(wavs)
26
+
27
+ assert isinstance(results, dict)
28
+ tasks = ["PR", "SID", "ER", "ASR", "ASV", "SD", "QbE", "ST", "SS", "SE", "secret"]
29
+ for task in tasks:
30
+ hidden_states = results.get(task, results["hidden_states"])
31
+ assert isinstance(hidden_states, list)
32
+
33
+ for state in hidden_states:
34
+ assert isinstance(state, torch.Tensor)
35
+ assert state.dim() == 3, "(batch_size, max_sequence_length_of_batch, hidden_size)"
36
+ assert state.shape == hidden_states[0].shape
37
+
38
+ downsample_rate = upstream.get_downsample_rates(task)
39
+ assert isinstance(downsample_rate, int)
40
+ assert abs(round(max(samples) / downsample_rate) - hidden_states[0].size(1)) < 5, "wrong downsample rate"
41
+
42
+ except:
43
+ print("Please check the Upstream Specification on https://superbbenchmark.org/challenge-slt2022/upstream")
44
+ raise
45
+
46
+ typer.echo("All submission files validated!")
47
+ typer.echo("Now you can upload these files to huggingface's Hub.")
48
+
49
+
50
+ @app.command()
51
+ def upload(commit_message: str):
52
+ subprocess.call("git pull origin main".split())
53
+ subprocess.call(["git", "add", "."])
54
+ subprocess.call(["git", "commit", "-m", f"Upload Upstream: {commit_message} "])
55
+ subprocess.call(["git", "push"])
56
+ typer.echo("Upload successful!")
57
+ typer.echo("Please go to https://superbbenchmark.org/submit to make a submission with the following information:")
58
+ typer.echo("1. Organization Name")
59
+ typer.echo("2. Repository Name")
60
+ typer.echo("3. Commit Hash (full 40 characters)")
61
+ typer.echo("These information can be shown by: python cli.py info")
62
+
63
+ @app.command()
64
+ def info():
65
+ result = subprocess.run(["git", "config", "--get", "remote.origin.url"], capture_output=True)
66
+ url = result.stdout.decode("utf-8").strip()
67
+ organization = url.split("/")[-2]
68
+ repo = url.split("/")[-1]
69
+
70
+ result = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True)
71
+ commit_hash = result.stdout.decode("utf-8").strip()
72
+
73
+ typer.echo(f"Organization Name: {organization}")
74
+ typer.echo(f"Repository Name: {repo}")
75
+ typer.echo(f"Commit Hash: {commit_hash}")
76
+
77
+ if __name__ == "__main__":
78
+ app()
expert.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import List, Union, Dict
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from torch import Tensor
7
+ from torch.nn.utils.rnn import pad_sequence
8
+
9
+ import fairseq
10
+
11
+ # class Model(nn.Module):
12
+ # def __init__(self):
13
+ # super().__init__()
14
+ # # The model needs to be a nn.Module for finetuning, not required for representation extraction
15
+ # self.model1 = nn.Linear(1, HIDDEN_DIM)
16
+ # self.model2 = nn.Linear(HIDDEN_DIM, HIDDEN_DIM)
17
+
18
+ # def forward(self, wavs, upstream_feature_selection="hidden_states"):
19
+ # # You can do task-specified pre- / post-processing based on upstream_feature_selection
20
+ # hidden = self.model1(wavs)
21
+ # # hidden: (batch_size, max_len, hidden_dim)
22
+
23
+ # feature = self.model2(hidden)
24
+ # # feature: (batch_size, max_len, hidden_dim)
25
+
26
+ # return [hidden, feature]
27
+
28
+ class UpstreamExpert(nn.Module):
29
+ def __init__(
30
+ self,
31
+ ckpt: str = "https://dl.fbaipublicfiles.com/hubert/hubert_base_ls960.pt",
32
+ upstream_feature_selection: str = "hidden_states",
33
+ **kwargs):
34
+ """
35
+ Args:
36
+ ckpt:
37
+ The checkpoint path for loading your pretrained weights.
38
+ Should be fixed as model.pt for SUPERB Challenge.
39
+ upstream_feature_selection:
40
+ The value could be
41
+ 'hidden_states', 'PR', 'SID', 'ER', 'ASR', 'QbE', 'ASV', 'SD', 'ST', 'SE', 'SS', 'secret', or others(new tasks).
42
+ You can use it to control which task-specified pre- / post-processing to do.
43
+ """
44
+ super().__init__()
45
+ self.name = "[Example UpstreamExpert]"
46
+ self.upstream_feature_selection = upstream_feature_selection
47
+
48
+ # # You can use ckpt to load your pretrained weights
49
+ # ckpt = torch.load(ckpt, map_location="cpu")
50
+ # self.model = Model()
51
+ # self.model.load_state_dict(ckpt)
52
+
53
+ assert version.parse(fairseq.__version__) > version.parse(
54
+ "0.10.2"
55
+ ), "Please install the fairseq master branch."
56
+
57
+ model, cfg, task = fairseq.checkpoint_utils.load_model_ensemble_and_task(
58
+ [ckpt]
59
+ )
60
+ self.model = model[0]
61
+ self.task = task
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+ def get_downsample_rates(self, key: str) -> int:
70
+ """
71
+ Since we do not do any downsampling in this example upstream
72
+ All keys' corresponding representations have downsample rate of 1
73
+ Eg. 10ms stride representation has the downsample rate 160 (input wavs are all in 16kHz)
74
+ """
75
+ return 320
76
+
77
+ def forward(self, wavs: List[Tensor]) -> Dict[str, List[Tensor]]:
78
+ """
79
+ When the returning Dict contains the List with more than one Tensor,
80
+ those Tensors should be in the same shape to train a weighted-sum on them.
81
+ """
82
+ wavs_silence = []
83
+
84
+
85
+ #Total 7 settings
86
+
87
+ #original
88
+ wavs_silence = wavs
89
+
90
+
91
+ #front, 5
92
+ for wav in wavs:
93
+ temp_wav = torch.zeros(len(wav)//5).to(wav.device)
94
+ wavs_silence.append(torch.cat((temp_wav, wav)))
95
+
96
+ #front, 10
97
+ for wav in wavs:
98
+ temp_wav = torch.zeros(len(wav)//10).to(wav.device)
99
+ wavs_silence.append(torch.cat((temp_wav, wav)))
100
+
101
+ #front, 20
102
+ for wav in wavs:
103
+ temp_wav = torch.zeros(len(wav)//20).to(wav.device)
104
+ wavs_silence.append(torch.cat((temp_wav, wav)))
105
+
106
+ #end, 5
107
+ for wav in wavs:
108
+ temp_wav = torch.zeros(len(wav)//5).to(wav.device)
109
+ wavs_silence.append(torch.cat((wav, temp_wav)))
110
+
111
+ #end, 10
112
+ for wav in wavs:
113
+ temp_wav = torch.zeros(len(wav)//10).to(wav.device)
114
+ wavs_silence.append(torch.cat((wav, temp_wav)))
115
+
116
+ #end, 20
117
+ for wav in wavs:
118
+ temp_wav = torch.zeros(len(wav)//20).to(wav.device)
119
+ wavs_silence.append(torch.cat((wav, temp_wav)))
120
+
121
+
122
+ wavs = wavs_silence
123
+
124
+ device = wavs[0].device
125
+ wav_lengths = torch.LongTensor([len(wav) for wav in wavs]).to(device)
126
+ wav_padding_mask = ~torch.lt(
127
+ torch.arange(max(wav_lengths)).unsqueeze(0).to(device),
128
+ wav_lengths.unsqueeze(1),
129
+ )
130
+ padded_wav = pad_sequence(wavs, batch_first=True)
131
+
132
+ features, feat_padding_mask = self.model.extract_features(
133
+ padded_wav,
134
+ padding_mask=wav_padding_mask,
135
+ mask=None,
136
+ )
137
+
138
+
139
+ # Deprecated! Do not do any task-specified postprocess below
140
+ # You can use the init arg "upstream_feature_selection" to control which task-specified pre- / post-processing to do.
141
+ # The "hidden_states" key will be used as default in many cases
142
+ # Others keys in this example are presented for SUPERB Challenge
143
+ return {
144
+ "hidden_states": features,
145
+ }
model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:151456b83765c14f38da56dad79771cc576be7ccbe088536af558cb6761238f0
3
+ size 1823
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ typer
2
+ torch