-
Notifications
You must be signed in to change notification settings - Fork 2.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add change_vocabulary and save_tokenizers() support to Multitask ASR models #8357
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,6 +13,8 @@ | |
# limitations under the License. | ||
|
||
import os | ||
import shutil | ||
import tarfile | ||
from abc import ABC, abstractmethod | ||
from typing import List | ||
|
||
|
@@ -25,7 +27,7 @@ | |
from nemo.collections.asr.parts.utils import asr_module_utils | ||
from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis | ||
from nemo.collections.common import tokenizers | ||
from nemo.utils import logging | ||
from nemo.utils import app_state, logging | ||
|
||
|
||
class ASRBPEMixin(ABC): | ||
|
@@ -372,6 +374,97 @@ def _cleanup_aggregate_config_and_artifacts_if_needed(self): | |
if akey.startswith('tokenizer.' + self.AGGREGATE_TOKENIZERS_DICT_PREFIX + '.'): | ||
self.artifacts.pop(akey) | ||
|
||
def save_tokenizers(self, directory: str): | ||
""" | ||
Save the model tokenizer(s) to the specified directory. | ||
|
||
Args: | ||
directory: The directory to save the tokenizer(s) to. | ||
""" | ||
if not hasattr(self, 'cfg'): | ||
raise RuntimeError( | ||
"The model has not been initialized with a tokenizer yet. Please call the model's " | ||
"__init__ and _setup_tokenizer methods first." | ||
) | ||
|
||
if self.tokenizer_type == 'agg': | ||
for lang in self.tokenizer.langs: | ||
subconfig = self.cfg.tokenizer.langs.get(lang) | ||
new_dir = os.path.join(directory, lang) | ||
self._extract_tokenizer_from_config(subconfig, new_dir) | ||
else: | ||
self._extract_tokenizer_from_config(self.cfg.tokenizer, directory) | ||
|
||
def _extract_tokenizer_from_config(self, tokenizer_cfg: DictConfig, dir: str): | ||
""" | ||
Extracts the tokenizer from the config and write the objects to dir. | ||
The file may be from a local path (new model init) or from a .nemo file (restored model). | ||
If its from a newly initialized model, the file is copied to dir. | ||
If its from a restored model, the file is extracted from the .nemo file and copied to dir. | ||
|
||
Args: | ||
tokenizer_cfg: The tokenizer config to extract the tokenizer from. | ||
dir: The directory to write the tokenizer objects to. | ||
""" | ||
if not os.path.exists(dir): | ||
os.makedirs(dir, exist_ok=True) | ||
|
||
nemo_file_objects = [] | ||
|
||
for k, v in tokenizer_cfg.items(): | ||
# Check if the value is a filepath (new model init) or has `nemo:` in it (restored model) | ||
if isinstance(v, str) and os.path.exists(v): | ||
# local file from first instantiation | ||
loc = shutil.copy2(v, dir) | ||
logging.info(f"Saved {k} at {loc}") | ||
|
||
if isinstance(v, str) and v.startswith('nemo:'): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nemo files modify config of registered items like this to denote registered artifacts. |
||
nemo_object_name = v[5:] | ||
nemo_file_objects.append(nemo_object_name) | ||
|
||
if len(nemo_file_objects) > 0: | ||
logging.debug(f"Copying the following nemo file objects to {dir}: {nemo_file_objects}") | ||
|
||
if not hasattr(self, 'model_guid'): | ||
raise ValueError( | ||
"The model does not have a model_guid attribute. " | ||
"Please ensure that the model has been restored from a .nemo file." | ||
) | ||
|
||
appstate = app_state.AppState() | ||
restore_path = appstate.get_model_metadata_from_guid(self.model_guid).restoration_path | ||
if restore_path is None: | ||
raise ValueError( | ||
"The model has not been restored from a .nemo file. Cannot extract the tokenizer " | ||
"as the nemo file cannot be located." | ||
) | ||
|
||
# Read the nemo file without fully extracting all contents | ||
# we start with an assumption of uncompressed tar, | ||
# which should be true for versions 1.7.0 and above | ||
tar_header = "r:" | ||
try: | ||
tar_test = tarfile.open(restore_path, tar_header) | ||
tar_test.close() | ||
except tarfile.ReadError: | ||
# can be older checkpoint => try compressed tar | ||
tar_header = "r:gz" | ||
tar = tarfile.open(restore_path, tar_header) | ||
|
||
for nemo_object_name in nemo_file_objects: | ||
members = [x for x in tar.getmembers() if nemo_object_name in x.name] | ||
for member in members: | ||
tar.extract(member, dir) | ||
|
||
new_name = member.name.split("_")[1:] | ||
if len(new_name) > 1: | ||
new_name = "_".join(new_name) | ||
else: | ||
new_name = new_name[0] | ||
os.rename(os.path.join(dir, member.name), os.path.join(dir, new_name)) | ||
|
||
logging.info(f"Saved {nemo_object_name} at {os.path.join(dir, new_name)}") | ||
|
||
|
||
class ASRModuleMixin(ASRAdapterModelMixin): | ||
""" | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why number 8 here and not another int?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is from the original code. @krishnacpuvvada