Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/convert_chinese_clip_original_pytorch_to_hf.py +134 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/feature_extraction_chinese_clip.py +33 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__init__.py +109 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/image_processing_efficientformer.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/modeling_tf_efficientformer.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/univnet/__init__.py +65 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/univnet/__pycache__/feature_extraction_univnet.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/univnet/convert_univnet.py +162 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/univnet/feature_extraction_univnet.py +456 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/univnet/modeling_univnet.py +636 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/yoso/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/yoso/__pycache__/configuration_yoso.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/yoso/__pycache__/modeling_yoso.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/yoso/convert_yoso_pytorch_to_pytorch.py +108 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/yoso/modeling_yoso.py +1304 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/designspaceLib/__init__.py +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__main__.py +78 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/__main__.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/ast.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/error.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/lexer.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/location.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/lookupDebugInfo.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/parser.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/variableScalar.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/error.py +22 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/lookupDebugInfo.py +12 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/parser.py +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/variableScalar.py +113 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__init__.py +248 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__main__.py +6 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/__main__.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/base.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/cmap.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/layout.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/options.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/tables.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/unicode.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/util.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/base.py +81 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/cmap.py +141 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/layout.py +526 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/options.py +85 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/tables.py +341 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/unicode.py +78 -0
.gitattributes
CHANGED
|
@@ -1576,3 +1576,4 @@ evalkit_tf446/lib/python3.10/site-packages/nvidia/cufft/lib/libcufft.so.10 filte
|
|
| 1576 |
evalkit_tf449/lib/python3.10/site-packages/nvidia/cublas/lib/libcublasLt.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1577 |
infer_4_47_1/lib/python3.10/site-packages/gradio/_frontend_code/lite/dist/assets/gradio_client-1.5.3-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
|
| 1578 |
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/perceiver/__pycache__/modeling_perceiver.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 1576 |
evalkit_tf449/lib/python3.10/site-packages/nvidia/cublas/lib/libcublasLt.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1577 |
infer_4_47_1/lib/python3.10/site-packages/gradio/_frontend_code/lite/dist/assets/gradio_client-1.5.3-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
|
| 1578 |
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/perceiver/__pycache__/modeling_perceiver.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1579 |
+
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/momentsPen.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/convert_chinese_clip_original_pytorch_to_hf.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
from transformers import ChineseCLIPConfig, ChineseCLIPModel
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def copy_attn_layer(hf_attn_layer, pt_weights, prefix):
|
| 24 |
+
q_proj, k_proj, v_proj = pt_weights[f"{prefix}.in_proj_weight"].chunk(3, dim=0)
|
| 25 |
+
q_proj_bias, k_proj_bias, v_proj_bias = pt_weights[f"{prefix}.in_proj_bias"].chunk(3, dim=0)
|
| 26 |
+
|
| 27 |
+
out_proj_weights = pt_weights[f"{prefix}.out_proj.weight"]
|
| 28 |
+
out_proj_bias = pt_weights[f"{prefix}.out_proj.bias"]
|
| 29 |
+
|
| 30 |
+
hf_attn_layer.q_proj.weight.data = q_proj
|
| 31 |
+
hf_attn_layer.q_proj.bias.data = q_proj_bias
|
| 32 |
+
|
| 33 |
+
hf_attn_layer.k_proj.weight.data = k_proj
|
| 34 |
+
hf_attn_layer.k_proj.bias.data = k_proj_bias
|
| 35 |
+
|
| 36 |
+
hf_attn_layer.v_proj.weight.data = v_proj
|
| 37 |
+
hf_attn_layer.v_proj.bias.data = v_proj_bias
|
| 38 |
+
|
| 39 |
+
hf_attn_layer.out_proj.weight.data = out_proj_weights
|
| 40 |
+
hf_attn_layer.out_proj.bias.data = out_proj_bias
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def copy_mlp(hf_mlp, pt_weights, prefix):
|
| 44 |
+
copy_linear(hf_mlp.fc1, pt_weights, f"{prefix}.c_fc")
|
| 45 |
+
copy_linear(hf_mlp.fc2, pt_weights, f"{prefix}.c_proj")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def copy_linear(hf_linear, pt_weights, prefix):
|
| 49 |
+
hf_linear.weight.data = pt_weights[f"{prefix}.weight"].data
|
| 50 |
+
hf_linear.bias.data = pt_weights[f"{prefix}.bias"].data
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def copy_layer(hf_layer, pt_weights, prefix):
|
| 54 |
+
# copy layer norms
|
| 55 |
+
copy_linear(hf_layer.layer_norm1, pt_weights, f"{prefix}.ln_1")
|
| 56 |
+
copy_linear(hf_layer.layer_norm2, pt_weights, f"{prefix}.ln_2")
|
| 57 |
+
|
| 58 |
+
# copy MLP
|
| 59 |
+
copy_mlp(hf_layer.mlp, pt_weights, f"{prefix}.mlp")
|
| 60 |
+
|
| 61 |
+
# copy attn
|
| 62 |
+
copy_attn_layer(hf_layer.self_attn, pt_weights, f"{prefix}.attn")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def copy_layers(hf_layers, pt_weights, prefix):
|
| 66 |
+
for layer_id, hf_layer in enumerate(hf_layers):
|
| 67 |
+
copy_layer(hf_layer, pt_weights, f"{prefix}.{layer_id}")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def copy_text_model_and_projection(hf_model, pt_weights):
|
| 71 |
+
# copy projection
|
| 72 |
+
hf_model.text_projection.weight.data = pt_weights["text_projection"].data.T
|
| 73 |
+
|
| 74 |
+
# copy text encoder
|
| 75 |
+
for name, param in hf_model.text_model.named_parameters():
|
| 76 |
+
param.data = pt_weights[f"bert.{name}"].data
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def copy_vision_model_and_projection(hf_model, pt_weights):
|
| 80 |
+
# copy projection
|
| 81 |
+
hf_model.visual_projection.weight.data = pt_weights["visual.proj"].data.T
|
| 82 |
+
|
| 83 |
+
# copy layer norms
|
| 84 |
+
copy_linear(hf_model.vision_model.pre_layrnorm, pt_weights, "visual.ln_pre")
|
| 85 |
+
copy_linear(hf_model.vision_model.post_layernorm, pt_weights, "visual.ln_post")
|
| 86 |
+
|
| 87 |
+
# copy embeddings
|
| 88 |
+
hf_model.vision_model.embeddings.patch_embedding.weight.data = pt_weights["visual.conv1.weight"].data
|
| 89 |
+
hf_model.vision_model.embeddings.class_embedding.data = pt_weights["visual.class_embedding"].data
|
| 90 |
+
hf_model.vision_model.embeddings.position_embedding.weight.data = pt_weights["visual.positional_embedding"].data
|
| 91 |
+
|
| 92 |
+
# copy encoder
|
| 93 |
+
copy_layers(hf_model.vision_model.encoder.layers, pt_weights, "visual.transformer.resblocks")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@torch.no_grad()
|
| 97 |
+
def convert_chinese_clip_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path=None):
|
| 98 |
+
"""
|
| 99 |
+
Copy/paste/tweak model's weights to transformers design.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
|
| 103 |
+
config = ChineseCLIPConfig.from_pretrained(config_path)
|
| 104 |
+
|
| 105 |
+
hf_model = ChineseCLIPModel(config).eval()
|
| 106 |
+
|
| 107 |
+
pt_weights = torch.load(checkpoint_path, map_location="cpu")["state_dict"]
|
| 108 |
+
pt_weights = {(name[7:] if name.startswith("module.") else name): value for name, value in pt_weights.items()}
|
| 109 |
+
|
| 110 |
+
copy_text_model_and_projection(hf_model, pt_weights)
|
| 111 |
+
copy_vision_model_and_projection(hf_model, pt_weights)
|
| 112 |
+
hf_model.logit_scale.data = pt_weights["logit_scale"].data
|
| 113 |
+
|
| 114 |
+
hf_model.save_pretrained(pytorch_dump_folder_path)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
if __name__ == "__main__":
|
| 118 |
+
parser = argparse.ArgumentParser()
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--pytorch_dump_folder_path",
|
| 121 |
+
default=None,
|
| 122 |
+
type=str,
|
| 123 |
+
help="Path to the output folder storing converted hf PyTorch model.",
|
| 124 |
+
)
|
| 125 |
+
parser.add_argument(
|
| 126 |
+
"--checkpoint_path", default=None, type=str, help="Path to original github format ChineseCLIP checkpoint."
|
| 127 |
+
)
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--config_path", default=None, required=True, type=str, help="Path to hf config.json of model to convert."
|
| 130 |
+
)
|
| 131 |
+
args = parser.parse_args()
|
| 132 |
+
|
| 133 |
+
convert_chinese_clip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
|
| 134 |
+
print("The conversion is finished!")
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/feature_extraction_chinese_clip.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Feature extractor class for Chinese-CLIP."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
from .image_processing_chinese_clip import ChineseCLIPImageProcessor
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ChineseCLIPFeatureExtractor(ChineseCLIPImageProcessor):
|
| 27 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 28 |
+
warnings.warn(
|
| 29 |
+
"The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
|
| 30 |
+
" Please use ChineseCLIPImageProcessor instead.",
|
| 31 |
+
FutureWarning,
|
| 32 |
+
)
|
| 33 |
+
super().__init__(*args, **kwargs)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__init__.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import (
|
| 17 |
+
OptionalDependencyNotAvailable,
|
| 18 |
+
_LazyModule,
|
| 19 |
+
is_tf_available,
|
| 20 |
+
is_torch_available,
|
| 21 |
+
is_vision_available,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
_import_structure = {
|
| 26 |
+
"configuration_efficientformer": [
|
| 27 |
+
"EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
| 28 |
+
"EfficientFormerConfig",
|
| 29 |
+
]
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
if not is_vision_available():
|
| 34 |
+
raise OptionalDependencyNotAvailable()
|
| 35 |
+
except OptionalDependencyNotAvailable:
|
| 36 |
+
pass
|
| 37 |
+
else:
|
| 38 |
+
_import_structure["image_processing_efficientformer"] = ["EfficientFormerImageProcessor"]
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
if not is_torch_available():
|
| 42 |
+
raise OptionalDependencyNotAvailable()
|
| 43 |
+
except OptionalDependencyNotAvailable:
|
| 44 |
+
pass
|
| 45 |
+
else:
|
| 46 |
+
_import_structure["modeling_efficientformer"] = [
|
| 47 |
+
"EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 48 |
+
"EfficientFormerForImageClassification",
|
| 49 |
+
"EfficientFormerForImageClassificationWithTeacher",
|
| 50 |
+
"EfficientFormerModel",
|
| 51 |
+
"EfficientFormerPreTrainedModel",
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
try:
|
| 55 |
+
if not is_tf_available():
|
| 56 |
+
raise OptionalDependencyNotAvailable()
|
| 57 |
+
except OptionalDependencyNotAvailable:
|
| 58 |
+
pass
|
| 59 |
+
else:
|
| 60 |
+
_import_structure["modeling_tf_efficientformer"] = [
|
| 61 |
+
"TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 62 |
+
"TFEfficientFormerForImageClassification",
|
| 63 |
+
"TFEfficientFormerForImageClassificationWithTeacher",
|
| 64 |
+
"TFEfficientFormerModel",
|
| 65 |
+
"TFEfficientFormerPreTrainedModel",
|
| 66 |
+
]
|
| 67 |
+
|
| 68 |
+
if TYPE_CHECKING:
|
| 69 |
+
from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
if not is_vision_available():
|
| 73 |
+
raise OptionalDependencyNotAvailable()
|
| 74 |
+
except OptionalDependencyNotAvailable:
|
| 75 |
+
pass
|
| 76 |
+
else:
|
| 77 |
+
from .image_processing_efficientformer import EfficientFormerImageProcessor
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
if not is_torch_available():
|
| 81 |
+
raise OptionalDependencyNotAvailable()
|
| 82 |
+
except OptionalDependencyNotAvailable:
|
| 83 |
+
pass
|
| 84 |
+
else:
|
| 85 |
+
from .modeling_efficientformer import (
|
| 86 |
+
EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 87 |
+
EfficientFormerForImageClassification,
|
| 88 |
+
EfficientFormerForImageClassificationWithTeacher,
|
| 89 |
+
EfficientFormerModel,
|
| 90 |
+
EfficientFormerPreTrainedModel,
|
| 91 |
+
)
|
| 92 |
+
try:
|
| 93 |
+
if not is_tf_available():
|
| 94 |
+
raise OptionalDependencyNotAvailable()
|
| 95 |
+
except OptionalDependencyNotAvailable:
|
| 96 |
+
pass
|
| 97 |
+
else:
|
| 98 |
+
from .modeling_tf_efficientformer import (
|
| 99 |
+
TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 100 |
+
TFEfficientFormerForImageClassification,
|
| 101 |
+
TFEfficientFormerForImageClassificationWithTeacher,
|
| 102 |
+
TFEfficientFormerModel,
|
| 103 |
+
TFEfficientFormerPreTrainedModel,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
else:
|
| 107 |
+
import sys
|
| 108 |
+
|
| 109 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.73 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (6.14 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/image_processing_efficientformer.cpython-310.pyc
ADDED
|
Binary file (12.8 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/modeling_tf_efficientformer.cpython-310.pyc
ADDED
|
Binary file (37.2 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/univnet/__init__.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import (
|
| 18 |
+
OptionalDependencyNotAvailable,
|
| 19 |
+
_LazyModule,
|
| 20 |
+
is_torch_available,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
_import_structure = {
|
| 25 |
+
"configuration_univnet": [
|
| 26 |
+
"UNIVNET_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
| 27 |
+
"UnivNetConfig",
|
| 28 |
+
],
|
| 29 |
+
"feature_extraction_univnet": ["UnivNetFeatureExtractor"],
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
if not is_torch_available():
|
| 34 |
+
raise OptionalDependencyNotAvailable()
|
| 35 |
+
except OptionalDependencyNotAvailable:
|
| 36 |
+
pass
|
| 37 |
+
else:
|
| 38 |
+
_import_structure["modeling_univnet"] = [
|
| 39 |
+
"UNIVNET_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 40 |
+
"UnivNetModel",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if TYPE_CHECKING:
|
| 45 |
+
from .configuration_univnet import (
|
| 46 |
+
UNIVNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
| 47 |
+
UnivNetConfig,
|
| 48 |
+
)
|
| 49 |
+
from .feature_extraction_univnet import UnivNetFeatureExtractor
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
if not is_torch_available():
|
| 53 |
+
raise OptionalDependencyNotAvailable()
|
| 54 |
+
except OptionalDependencyNotAvailable:
|
| 55 |
+
pass
|
| 56 |
+
else:
|
| 57 |
+
from .modeling_univnet import (
|
| 58 |
+
UNIVNET_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 59 |
+
UnivNetModel,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
else:
|
| 63 |
+
import sys
|
| 64 |
+
|
| 65 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/univnet/__pycache__/feature_extraction_univnet.cpython-310.pyc
ADDED
|
Binary file (19.5 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/univnet/convert_univnet.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
from transformers import UnivNetConfig, UnivNetModel, logging
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logging.set_verbosity_info()
|
| 23 |
+
logger = logging.get_logger("transformers.models.univnet")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_kernel_predictor_key_mapping(config: UnivNetConfig, old_prefix: str = "", new_prefix: str = ""):
|
| 27 |
+
mapping = {}
|
| 28 |
+
# Initial conv layer
|
| 29 |
+
mapping[f"{old_prefix}.input_conv.0.weight_g"] = f"{new_prefix}.input_conv.weight_g"
|
| 30 |
+
mapping[f"{old_prefix}.input_conv.0.weight_v"] = f"{new_prefix}.input_conv.weight_v"
|
| 31 |
+
mapping[f"{old_prefix}.input_conv.0.bias"] = f"{new_prefix}.input_conv.bias"
|
| 32 |
+
|
| 33 |
+
# Kernel predictor resnet blocks
|
| 34 |
+
for i in range(config.kernel_predictor_num_blocks):
|
| 35 |
+
mapping[f"{old_prefix}.residual_convs.{i}.1.weight_g"] = f"{new_prefix}.resblocks.{i}.conv1.weight_g"
|
| 36 |
+
mapping[f"{old_prefix}.residual_convs.{i}.1.weight_v"] = f"{new_prefix}.resblocks.{i}.conv1.weight_v"
|
| 37 |
+
mapping[f"{old_prefix}.residual_convs.{i}.1.bias"] = f"{new_prefix}.resblocks.{i}.conv1.bias"
|
| 38 |
+
|
| 39 |
+
mapping[f"{old_prefix}.residual_convs.{i}.3.weight_g"] = f"{new_prefix}.resblocks.{i}.conv2.weight_g"
|
| 40 |
+
mapping[f"{old_prefix}.residual_convs.{i}.3.weight_v"] = f"{new_prefix}.resblocks.{i}.conv2.weight_v"
|
| 41 |
+
mapping[f"{old_prefix}.residual_convs.{i}.3.bias"] = f"{new_prefix}.resblocks.{i}.conv2.bias"
|
| 42 |
+
|
| 43 |
+
# Kernel output conv
|
| 44 |
+
mapping[f"{old_prefix}.kernel_conv.weight_g"] = f"{new_prefix}.kernel_conv.weight_g"
|
| 45 |
+
mapping[f"{old_prefix}.kernel_conv.weight_v"] = f"{new_prefix}.kernel_conv.weight_v"
|
| 46 |
+
mapping[f"{old_prefix}.kernel_conv.bias"] = f"{new_prefix}.kernel_conv.bias"
|
| 47 |
+
|
| 48 |
+
# Bias output conv
|
| 49 |
+
mapping[f"{old_prefix}.bias_conv.weight_g"] = f"{new_prefix}.bias_conv.weight_g"
|
| 50 |
+
mapping[f"{old_prefix}.bias_conv.weight_v"] = f"{new_prefix}.bias_conv.weight_v"
|
| 51 |
+
mapping[f"{old_prefix}.bias_conv.bias"] = f"{new_prefix}.bias_conv.bias"
|
| 52 |
+
|
| 53 |
+
return mapping
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_key_mapping(config: UnivNetConfig):
|
| 57 |
+
mapping = {}
|
| 58 |
+
|
| 59 |
+
# NOTE: inital conv layer keys are the same
|
| 60 |
+
|
| 61 |
+
# LVC Residual blocks
|
| 62 |
+
for i in range(len(config.resblock_stride_sizes)):
|
| 63 |
+
# LVCBlock initial convt layer
|
| 64 |
+
mapping[f"res_stack.{i}.convt_pre.1.weight_g"] = f"resblocks.{i}.convt_pre.weight_g"
|
| 65 |
+
mapping[f"res_stack.{i}.convt_pre.1.weight_v"] = f"resblocks.{i}.convt_pre.weight_v"
|
| 66 |
+
mapping[f"res_stack.{i}.convt_pre.1.bias"] = f"resblocks.{i}.convt_pre.bias"
|
| 67 |
+
|
| 68 |
+
# Kernel predictor
|
| 69 |
+
kernel_predictor_mapping = get_kernel_predictor_key_mapping(
|
| 70 |
+
config, old_prefix=f"res_stack.{i}.kernel_predictor", new_prefix=f"resblocks.{i}.kernel_predictor"
|
| 71 |
+
)
|
| 72 |
+
mapping.update(kernel_predictor_mapping)
|
| 73 |
+
|
| 74 |
+
# LVC Residual blocks
|
| 75 |
+
for j in range(len(config.resblock_dilation_sizes[i])):
|
| 76 |
+
mapping[f"res_stack.{i}.conv_blocks.{j}.1.weight_g"] = f"resblocks.{i}.resblocks.{j}.conv.weight_g"
|
| 77 |
+
mapping[f"res_stack.{i}.conv_blocks.{j}.1.weight_v"] = f"resblocks.{i}.resblocks.{j}.conv.weight_v"
|
| 78 |
+
mapping[f"res_stack.{i}.conv_blocks.{j}.1.bias"] = f"resblocks.{i}.resblocks.{j}.conv.bias"
|
| 79 |
+
|
| 80 |
+
# Output conv layer
|
| 81 |
+
mapping["conv_post.1.weight_g"] = "conv_post.weight_g"
|
| 82 |
+
mapping["conv_post.1.weight_v"] = "conv_post.weight_v"
|
| 83 |
+
mapping["conv_post.1.bias"] = "conv_post.bias"
|
| 84 |
+
|
| 85 |
+
return mapping
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def rename_state_dict(state_dict, keys_to_modify, keys_to_remove):
|
| 89 |
+
model_state_dict = {}
|
| 90 |
+
for key, value in state_dict.items():
|
| 91 |
+
if key in keys_to_remove:
|
| 92 |
+
continue
|
| 93 |
+
|
| 94 |
+
if key in keys_to_modify:
|
| 95 |
+
new_key = keys_to_modify[key]
|
| 96 |
+
model_state_dict[new_key] = value
|
| 97 |
+
else:
|
| 98 |
+
model_state_dict[key] = value
|
| 99 |
+
return model_state_dict
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def convert_univnet_checkpoint(
|
| 103 |
+
checkpoint_path,
|
| 104 |
+
pytorch_dump_folder_path,
|
| 105 |
+
config_path=None,
|
| 106 |
+
repo_id=None,
|
| 107 |
+
safe_serialization=False,
|
| 108 |
+
):
|
| 109 |
+
model_state_dict_base = torch.load(checkpoint_path, map_location="cpu")
|
| 110 |
+
# Get the generator's state dict
|
| 111 |
+
state_dict = model_state_dict_base["model_g"]
|
| 112 |
+
|
| 113 |
+
if config_path is not None:
|
| 114 |
+
config = UnivNetConfig.from_pretrained(config_path)
|
| 115 |
+
else:
|
| 116 |
+
config = UnivNetConfig()
|
| 117 |
+
|
| 118 |
+
keys_to_modify = get_key_mapping(config)
|
| 119 |
+
keys_to_remove = set()
|
| 120 |
+
hf_state_dict = rename_state_dict(state_dict, keys_to_modify, keys_to_remove)
|
| 121 |
+
|
| 122 |
+
model = UnivNetModel(config)
|
| 123 |
+
# Apply weight norm since the original checkpoint has weight norm applied
|
| 124 |
+
model.apply_weight_norm()
|
| 125 |
+
model.load_state_dict(hf_state_dict)
|
| 126 |
+
# Remove weight norm in preparation for inference
|
| 127 |
+
model.remove_weight_norm()
|
| 128 |
+
|
| 129 |
+
model.save_pretrained(pytorch_dump_folder_path, safe_serialization=safe_serialization)
|
| 130 |
+
|
| 131 |
+
if repo_id:
|
| 132 |
+
print("Pushing to the hub...")
|
| 133 |
+
model.push_to_hub(repo_id)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def main():
|
| 137 |
+
parser = argparse.ArgumentParser()
|
| 138 |
+
parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint")
|
| 139 |
+
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
|
| 140 |
+
parser.add_argument(
|
| 141 |
+
"--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model."
|
| 142 |
+
)
|
| 143 |
+
parser.add_argument(
|
| 144 |
+
"--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub."
|
| 145 |
+
)
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--safe_serialization", action="store_true", help="Whether to save the model using `safetensors`."
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
args = parser.parse_args()
|
| 151 |
+
|
| 152 |
+
convert_univnet_checkpoint(
|
| 153 |
+
args.checkpoint_path,
|
| 154 |
+
args.pytorch_dump_folder_path,
|
| 155 |
+
args.config_path,
|
| 156 |
+
args.push_to_hub,
|
| 157 |
+
args.safe_serialization,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
if __name__ == "__main__":
|
| 162 |
+
main()
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/univnet/feature_extraction_univnet.py
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Feature extractor class for UnivNetModel."""
|
| 15 |
+
|
| 16 |
+
from typing import Any, Dict, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
|
| 21 |
+
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
|
| 22 |
+
from ...feature_extraction_utils import BatchFeature
|
| 23 |
+
from ...utils import PaddingStrategy, TensorType, logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class UnivNetFeatureExtractor(SequenceFeatureExtractor):
|
| 30 |
+
r"""
|
| 31 |
+
Constructs a UnivNet feature extractor.
|
| 32 |
+
|
| 33 |
+
This class extracts log-mel-filter bank features from raw speech using the short time Fourier Transform (STFT). The
|
| 34 |
+
STFT implementation follows that of TacoTron 2 and Hifi-GAN.
|
| 35 |
+
|
| 36 |
+
This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
|
| 37 |
+
most of the main methods. Users should refer to this superclass for more information regarding those methods.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
feature_size (`int`, *optional*, defaults to 1):
|
| 41 |
+
The feature dimension of the extracted features.
|
| 42 |
+
sampling_rate (`int`, *optional*, defaults to 24000):
|
| 43 |
+
The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
|
| 44 |
+
padding_value (`float`, *optional*, defaults to 0.0):
|
| 45 |
+
The value to pad with when applying the padding strategy defined by the `padding` argument to
|
| 46 |
+
[`UnivNetFeatureExtractor.__call__`]. Should correspond to audio silence. The `pad_end` argument to
|
| 47 |
+
`__call__` will also use this padding value.
|
| 48 |
+
do_normalize (`bool`, *optional*, defaults to `False`):
|
| 49 |
+
Whether to perform Tacotron 2 normalization on the input. Normalizing can help to significantly improve the
|
| 50 |
+
performance for some models.
|
| 51 |
+
num_mel_bins (`int`, *optional*, defaults to 100):
|
| 52 |
+
The number of mel-frequency bins in the extracted spectrogram features. This should match
|
| 53 |
+
`UnivNetModel.config.num_mel_bins`.
|
| 54 |
+
hop_length (`int`, *optional*, defaults to 256):
|
| 55 |
+
The direct number of samples between sliding windows. Otherwise referred to as "shift" in many papers. Note
|
| 56 |
+
that this is different from other audio feature extractors such as [`SpeechT5FeatureExtractor`] which take
|
| 57 |
+
the `hop_length` in ms.
|
| 58 |
+
win_length (`int`, *optional*, defaults to 1024):
|
| 59 |
+
The direct number of samples for each sliding window. Note that this is different from other audio feature
|
| 60 |
+
extractors such as [`SpeechT5FeatureExtractor`] which take the `win_length` in ms.
|
| 61 |
+
win_function (`str`, *optional*, defaults to `"hann_window"`):
|
| 62 |
+
Name for the window function used for windowing, must be accessible via `torch.{win_function}`
|
| 63 |
+
filter_length (`int`, *optional*, defaults to 1024):
|
| 64 |
+
The number of FFT components to use. If `None`, this is determined using
|
| 65 |
+
`transformers.audio_utils.optimal_fft_length`.
|
| 66 |
+
max_length_s (`int`, *optional*, defaults to 10):
|
| 67 |
+
The maximum input lenght of the model in seconds. This is used to pad the audio.
|
| 68 |
+
fmin (`float`, *optional*, defaults to 0.0):
|
| 69 |
+
Minimum mel frequency in Hz.
|
| 70 |
+
fmax (`float`, *optional*):
|
| 71 |
+
Maximum mel frequency in Hz. If not set, defaults to `sampling_rate / 2`.
|
| 72 |
+
mel_floor (`float`, *optional*, defaults to 1e-09):
|
| 73 |
+
Minimum value of mel frequency banks. Note that the way [`UnivNetFeatureExtractor`] uses `mel_floor` is
|
| 74 |
+
different than in [`transformers.audio_utils.spectrogram`].
|
| 75 |
+
center (`bool`, *optional*, defaults to `False`):
|
| 76 |
+
Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `False`, frame
|
| 77 |
+
`t` will start at time `t * hop_length`.
|
| 78 |
+
compression_factor (`float`, *optional*, defaults to 1.0):
|
| 79 |
+
The multiplicative compression factor for dynamic range compression during spectral normalization.
|
| 80 |
+
compression_clip_val (`float`, *optional*, defaults to 1e-05):
|
| 81 |
+
The clip value applied to the waveform before applying dynamic range compression during spectral
|
| 82 |
+
normalization.
|
| 83 |
+
normalize_min (`float`, *optional*, defaults to -11.512925148010254):
|
| 84 |
+
The min value used for Tacotron 2-style linear normalization. The default is the original value from the
|
| 85 |
+
Tacotron 2 implementation.
|
| 86 |
+
normalize_max (`float`, *optional*, defaults to 2.3143386840820312):
|
| 87 |
+
The max value used for Tacotron 2-style linear normalization. The default is the original value from the
|
| 88 |
+
Tacotron 2 implementation.
|
| 89 |
+
model_in_channels (`int`, *optional*, defaults to 64):
|
| 90 |
+
The number of input channels to the [`UnivNetModel`] model. This should match
|
| 91 |
+
`UnivNetModel.config.model_in_channels`.
|
| 92 |
+
pad_end_length (`int`, *optional*, defaults to 10):
|
| 93 |
+
If padding the end of each waveform, the number of spectrogram frames worth of samples to append. The
|
| 94 |
+
number of appended samples will be `pad_end_length * hop_length`.
|
| 95 |
+
return_attention_mask (`bool`, *optional*, defaults to `True`):
|
| 96 |
+
Whether or not [`~UnivNetFeatureExtractor.__call__`] should return `attention_mask`.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
model_input_names = ["input_features", "noise_sequence", "padding_mask"]
|
| 100 |
+
|
| 101 |
+
def __init__(
|
| 102 |
+
self,
|
| 103 |
+
feature_size: int = 1,
|
| 104 |
+
sampling_rate: int = 24000,
|
| 105 |
+
padding_value: float = 0.0,
|
| 106 |
+
do_normalize: bool = False,
|
| 107 |
+
num_mel_bins: int = 100,
|
| 108 |
+
hop_length: int = 256,
|
| 109 |
+
win_length: int = 1024,
|
| 110 |
+
win_function: str = "hann_window",
|
| 111 |
+
filter_length: Optional[int] = 1024,
|
| 112 |
+
max_length_s: int = 10,
|
| 113 |
+
fmin: float = 0.0,
|
| 114 |
+
fmax: Optional[float] = None,
|
| 115 |
+
mel_floor: float = 1e-9,
|
| 116 |
+
center: bool = False,
|
| 117 |
+
compression_factor: float = 1.0,
|
| 118 |
+
compression_clip_val: float = 1e-5,
|
| 119 |
+
normalize_min: float = -11.512925148010254,
|
| 120 |
+
normalize_max: float = 2.3143386840820312,
|
| 121 |
+
model_in_channels: int = 64,
|
| 122 |
+
pad_end_length: int = 10,
|
| 123 |
+
return_attention_mask=True,
|
| 124 |
+
**kwargs,
|
| 125 |
+
):
|
| 126 |
+
super().__init__(
|
| 127 |
+
feature_size=feature_size,
|
| 128 |
+
sampling_rate=sampling_rate,
|
| 129 |
+
padding_value=padding_value,
|
| 130 |
+
return_attention_mask=return_attention_mask,
|
| 131 |
+
**kwargs,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
self.do_normalize = do_normalize
|
| 135 |
+
|
| 136 |
+
self.num_mel_bins = num_mel_bins
|
| 137 |
+
self.hop_length = hop_length
|
| 138 |
+
self.win_length = win_length
|
| 139 |
+
self.win_function = win_function
|
| 140 |
+
self.filter_length = filter_length
|
| 141 |
+
self.fmin = fmin
|
| 142 |
+
if fmax is None:
|
| 143 |
+
# Follows the librosa.filters.mel implementation
|
| 144 |
+
fmax = float(sampling_rate) / 2
|
| 145 |
+
self.fmax = fmax
|
| 146 |
+
self.mel_floor = mel_floor
|
| 147 |
+
|
| 148 |
+
self.max_length_s = max_length_s
|
| 149 |
+
self.num_max_samples = max_length_s * sampling_rate
|
| 150 |
+
|
| 151 |
+
if self.filter_length is None:
|
| 152 |
+
self.n_fft = optimal_fft_length(self.win_length)
|
| 153 |
+
else:
|
| 154 |
+
self.n_fft = self.filter_length
|
| 155 |
+
self.n_freqs = (self.n_fft // 2) + 1
|
| 156 |
+
|
| 157 |
+
self.window = window_function(window_length=self.win_length, name=self.win_function, periodic=True)
|
| 158 |
+
|
| 159 |
+
self.mel_filters = mel_filter_bank(
|
| 160 |
+
num_frequency_bins=self.n_freqs,
|
| 161 |
+
num_mel_filters=self.num_mel_bins,
|
| 162 |
+
min_frequency=self.fmin,
|
| 163 |
+
max_frequency=self.fmax,
|
| 164 |
+
sampling_rate=self.sampling_rate,
|
| 165 |
+
norm="slaney",
|
| 166 |
+
mel_scale="slaney",
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
self.center = center
|
| 170 |
+
self.compression_factor = compression_factor
|
| 171 |
+
self.compression_clip_val = compression_clip_val
|
| 172 |
+
self.normalize_min = normalize_min
|
| 173 |
+
self.normalize_max = normalize_max
|
| 174 |
+
self.model_in_channels = model_in_channels
|
| 175 |
+
self.pad_end_length = pad_end_length
|
| 176 |
+
|
| 177 |
+
def normalize(self, spectrogram):
|
| 178 |
+
return 2 * ((spectrogram - self.normalize_min) / (self.normalize_max - self.normalize_min)) - 1
|
| 179 |
+
|
| 180 |
+
def denormalize(self, spectrogram):
|
| 181 |
+
return self.normalize_min + (self.normalize_max - self.normalize_min) * ((spectrogram + 1) / 2)
|
| 182 |
+
|
| 183 |
+
def mel_spectrogram(self, waveform: np.ndarray) -> np.ndarray:
|
| 184 |
+
"""
|
| 185 |
+
Calculates log MEL spectrograms from a batch of waveforms. Note that the input waveform(s) will be padded by
|
| 186 |
+
`int(self.n_fft - self.hop_length) / 2` on both sides using the `reflect` padding mode.
|
| 187 |
+
|
| 188 |
+
Args:
|
| 189 |
+
waveform (`np.ndarray` of shape `(length,)`):
|
| 190 |
+
The input waveform. This must be a single real-valued, mono waveform.
|
| 191 |
+
|
| 192 |
+
Returns:
|
| 193 |
+
`numpy.ndarray`: Array containing a log-mel spectrogram of shape `(num_frames, num_mel_bins)`.
|
| 194 |
+
"""
|
| 195 |
+
# Do custom padding based on the official MelGAN and Hifi-GAN implementations
|
| 196 |
+
# See https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/utils/stft.py#L84-L86
|
| 197 |
+
waveform = np.pad(
|
| 198 |
+
waveform,
|
| 199 |
+
(int((self.n_fft - self.hop_length) / 2), int((self.n_fft - self.hop_length) / 2)),
|
| 200 |
+
mode="reflect",
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# Get the complex spectrogram.
|
| 204 |
+
# Note: waveform must be unbatched currently due to the implementation of spectrogram(...).
|
| 205 |
+
complex_spectrogram = spectrogram(
|
| 206 |
+
waveform,
|
| 207 |
+
window=self.window,
|
| 208 |
+
frame_length=self.n_fft,
|
| 209 |
+
hop_length=self.hop_length,
|
| 210 |
+
fft_length=self.n_fft,
|
| 211 |
+
power=None,
|
| 212 |
+
center=self.center,
|
| 213 |
+
mel_filters=None,
|
| 214 |
+
mel_floor=None,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# Apply the MEL filter bank and MEL floor manually since UnivNet uses a slightly different implementation
|
| 218 |
+
amplitude_spectrogram = np.sqrt(
|
| 219 |
+
np.real(complex_spectrogram) ** 2 + np.imag(complex_spectrogram) ** 2 + self.mel_floor
|
| 220 |
+
)
|
| 221 |
+
mel_spectrogram = np.matmul(self.mel_filters.T, amplitude_spectrogram)
|
| 222 |
+
|
| 223 |
+
# Perform spectral normalization to get the log mel spectrogram.
|
| 224 |
+
log_mel_spectrogram = np.log(
|
| 225 |
+
np.clip(mel_spectrogram, a_min=self.compression_clip_val, a_max=None) * self.compression_factor
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
# Return spectrogram with num_mel_bins last
|
| 229 |
+
return log_mel_spectrogram.T
|
| 230 |
+
|
| 231 |
+
def generate_noise(
|
| 232 |
+
self,
|
| 233 |
+
noise_length: int,
|
| 234 |
+
generator: Optional[np.random.Generator] = None,
|
| 235 |
+
) -> np.ndarray:
|
| 236 |
+
"""
|
| 237 |
+
Generates a random noise sequence of standard Gaussian noise for use in the `noise_sequence` argument of
|
| 238 |
+
[`UnivNetModel.forward`].
|
| 239 |
+
|
| 240 |
+
Args:
|
| 241 |
+
spectrogram_length (`int`):
|
| 242 |
+
The length (dim 0) of the generated noise.
|
| 243 |
+
model_in_channels (`int`, *optional*, defaults to `None`):
|
| 244 |
+
The number of features (dim 1) of the generated noise. This should correspond to the
|
| 245 |
+
`model_in_channels` of the [`UnivNetGan`] model. If not set, this will default to
|
| 246 |
+
`self.config.model_in_channels`.
|
| 247 |
+
generator (`numpy.random.Generator`, *optional*, defaults to `None`)
|
| 248 |
+
An optional `numpy.random.Generator` random number generator to control noise generation. If not set, a
|
| 249 |
+
new generator with fresh entropy will be created.
|
| 250 |
+
|
| 251 |
+
Returns:
|
| 252 |
+
`numpy.ndarray`: Array containing random standard Gaussian noise of shape `(noise_length,
|
| 253 |
+
model_in_channels)`.
|
| 254 |
+
"""
|
| 255 |
+
if generator is None:
|
| 256 |
+
generator = np.random.default_rng()
|
| 257 |
+
|
| 258 |
+
noise_shape = (noise_length, self.model_in_channels)
|
| 259 |
+
noise = generator.standard_normal(noise_shape, dtype=np.float32)
|
| 260 |
+
|
| 261 |
+
return noise
|
| 262 |
+
|
| 263 |
+
def batch_decode(self, waveforms, waveform_lengths=None) -> List[np.ndarray]:
|
| 264 |
+
r"""
|
| 265 |
+
Removes padding from generated audio after running [`UnivNetModel.forward`]. This returns a ragged list of 1D
|
| 266 |
+
audio waveform arrays and not a single tensor/array because in general the waveforms will have different
|
| 267 |
+
lengths after removing padding.
|
| 268 |
+
|
| 269 |
+
Args:
|
| 270 |
+
waveforms (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 271 |
+
The batched output waveforms from the [`UnivNetModel`].
|
| 272 |
+
waveform_lengths (`torch.FloatTensor` of shape `(batch_size,)`, *optional*):
|
| 273 |
+
The batched lengths of each waveform before padding.
|
| 274 |
+
|
| 275 |
+
Returns:
|
| 276 |
+
`List[np.ndarray]`: A ragged list of 1D waveform arrays with padding removed.
|
| 277 |
+
"""
|
| 278 |
+
# Collapse the batched waveform tensor to a list of 1D audio waveforms
|
| 279 |
+
waveforms = [waveform.detach().clone().cpu().numpy() for waveform in waveforms]
|
| 280 |
+
|
| 281 |
+
if waveform_lengths is not None:
|
| 282 |
+
waveforms = [waveform[: waveform_lengths[i]] for i, waveform in enumerate(waveforms)]
|
| 283 |
+
|
| 284 |
+
return waveforms
|
| 285 |
+
|
| 286 |
+
def __call__(
|
| 287 |
+
self,
|
| 288 |
+
raw_speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],
|
| 289 |
+
sampling_rate: Optional[int] = None,
|
| 290 |
+
padding: Union[bool, str, PaddingStrategy] = True,
|
| 291 |
+
max_length: Optional[int] = None,
|
| 292 |
+
truncation: bool = True,
|
| 293 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 294 |
+
return_noise: bool = True,
|
| 295 |
+
generator: Optional[np.random.Generator] = None,
|
| 296 |
+
pad_end: bool = False,
|
| 297 |
+
pad_length: Optional[int] = None,
|
| 298 |
+
do_normalize: Optional[str] = None,
|
| 299 |
+
return_attention_mask: Optional[bool] = None,
|
| 300 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 301 |
+
) -> BatchFeature:
|
| 302 |
+
"""
|
| 303 |
+
Main method to featurize and prepare for the model one or several sequence(s).
|
| 304 |
+
|
| 305 |
+
Args:
|
| 306 |
+
raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):
|
| 307 |
+
The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
|
| 308 |
+
values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
|
| 309 |
+
stereo, i.e. single float per timestep.
|
| 310 |
+
sampling_rate (`int`, *optional*):
|
| 311 |
+
The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
|
| 312 |
+
`sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
|
| 313 |
+
pipeline.
|
| 314 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
|
| 315 |
+
Select a strategy to pad the input `raw_speech` waveforms (according to the model's padding side and
|
| 316 |
+
padding index) among:
|
| 317 |
+
|
| 318 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 319 |
+
sequence if provided).
|
| 320 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 321 |
+
acceptable input length for the model if that argument is not provided.
|
| 322 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 323 |
+
lengths).
|
| 324 |
+
|
| 325 |
+
If `pad_end = True`, that padding will occur before the `padding` strategy is applied.
|
| 326 |
+
max_length (`int`, *optional*):
|
| 327 |
+
Maximum length of the returned list and optionally padding length (see above).
|
| 328 |
+
truncation (`bool`, *optional*, defaults to `True`):
|
| 329 |
+
Activates truncation to cut input sequences longer than `max_length` to `max_length`.
|
| 330 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 331 |
+
If set will pad the sequence to a multiple of the provided value.
|
| 332 |
+
|
| 333 |
+
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
|
| 334 |
+
`>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
|
| 335 |
+
return_noise (`bool`, *optional*, defaults to `True`):
|
| 336 |
+
Whether to generate and return a noise waveform for use in [`UnivNetModel.forward`].
|
| 337 |
+
generator (`numpy.random.Generator`, *optional*, defaults to `None`):
|
| 338 |
+
An optional `numpy.random.Generator` random number generator to use when generating noise.
|
| 339 |
+
pad_end (`bool`, *optional*, defaults to `False`):
|
| 340 |
+
Whether to pad the end of each waveform with silence. This can help reduce artifacts at the end of the
|
| 341 |
+
generated audio sample; see https://github.com/seungwonpark/melgan/issues/8 for more details. This
|
| 342 |
+
padding will be done before the padding strategy specified in `padding` is performed.
|
| 343 |
+
pad_length (`int`, *optional*, defaults to `None`):
|
| 344 |
+
If padding the end of each waveform, the length of the padding in spectrogram frames. If not set, this
|
| 345 |
+
will default to `self.config.pad_end_length`.
|
| 346 |
+
do_normalize (`bool`, *optional*):
|
| 347 |
+
Whether to perform Tacotron 2 normalization on the input. Normalizing can help to significantly improve
|
| 348 |
+
the performance for some models. If not set, this will default to `self.config.do_normalize`.
|
| 349 |
+
return_attention_mask (`bool`, *optional*):
|
| 350 |
+
Whether to return the attention mask. If left to the default, will return the attention mask according
|
| 351 |
+
to the specific feature_extractor's default.
|
| 352 |
+
|
| 353 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 354 |
+
|
| 355 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 356 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 357 |
+
|
| 358 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 359 |
+
- `'pt'`: Return PyTorch `torch.np.array` objects.
|
| 360 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 361 |
+
"""
|
| 362 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 363 |
+
|
| 364 |
+
if sampling_rate is not None:
|
| 365 |
+
if sampling_rate != self.sampling_rate:
|
| 366 |
+
raise ValueError(
|
| 367 |
+
f"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
|
| 368 |
+
f" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
|
| 369 |
+
f" was sampled with {self.sampling_rate} and not {sampling_rate}."
|
| 370 |
+
)
|
| 371 |
+
else:
|
| 372 |
+
logger.warning(
|
| 373 |
+
"It is strongly recommended to pass the `sampling_rate` argument to this function. "
|
| 374 |
+
"Failing to do so can result in silent errors that might be hard to debug."
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
|
| 378 |
+
if is_batched_numpy and len(raw_speech.shape) > 2:
|
| 379 |
+
raise ValueError(f"Only mono-channel audio is supported for input to {self}")
|
| 380 |
+
is_batched = is_batched_numpy or (
|
| 381 |
+
isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
if is_batched:
|
| 385 |
+
raw_speech = [np.asarray(speech, dtype=np.float32) for speech in raw_speech]
|
| 386 |
+
elif not is_batched and not isinstance(raw_speech, np.ndarray):
|
| 387 |
+
raw_speech = np.asarray(raw_speech, dtype=np.float32)
|
| 388 |
+
elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
|
| 389 |
+
raw_speech = raw_speech.astype(np.float32)
|
| 390 |
+
|
| 391 |
+
# always return batch
|
| 392 |
+
if not is_batched:
|
| 393 |
+
raw_speech = [np.asarray(raw_speech, dtype=np.float32)]
|
| 394 |
+
|
| 395 |
+
# Pad end to reduce artifacts
|
| 396 |
+
if pad_end:
|
| 397 |
+
pad_length = pad_length if pad_length is not None else self.pad_end_length
|
| 398 |
+
raw_speech = [
|
| 399 |
+
np.pad(waveform, (0, pad_length * self.hop_length), constant_values=self.padding_value)
|
| 400 |
+
for waveform in raw_speech
|
| 401 |
+
]
|
| 402 |
+
|
| 403 |
+
batched_speech = BatchFeature({"input_features": raw_speech})
|
| 404 |
+
|
| 405 |
+
padded_inputs = self.pad(
|
| 406 |
+
batched_speech,
|
| 407 |
+
padding=padding,
|
| 408 |
+
max_length=max_length if max_length is not None else self.num_max_samples,
|
| 409 |
+
truncation=truncation,
|
| 410 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 411 |
+
return_attention_mask=return_attention_mask,
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
# make sure list is in array format
|
| 415 |
+
# input_features = padded_inputs.get("input_features").transpose(2, 0, 1)
|
| 416 |
+
input_features = padded_inputs.get("input_features")
|
| 417 |
+
|
| 418 |
+
mel_spectrograms = [self.mel_spectrogram(waveform) for waveform in input_features]
|
| 419 |
+
|
| 420 |
+
if isinstance(input_features[0], List):
|
| 421 |
+
batched_speech["input_features"] = [np.asarray(mel, dtype=np.float32) for mel in mel_spectrograms]
|
| 422 |
+
else:
|
| 423 |
+
batched_speech["input_features"] = [mel.astype(np.float32) for mel in mel_spectrograms]
|
| 424 |
+
|
| 425 |
+
# convert attention_mask to correct format
|
| 426 |
+
attention_mask = padded_inputs.get("attention_mask")
|
| 427 |
+
if attention_mask is not None:
|
| 428 |
+
batched_speech["padding_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask]
|
| 429 |
+
|
| 430 |
+
if return_noise:
|
| 431 |
+
noise = [
|
| 432 |
+
self.generate_noise(spectrogram.shape[0], generator)
|
| 433 |
+
for spectrogram in batched_speech["input_features"]
|
| 434 |
+
]
|
| 435 |
+
batched_speech["noise_sequence"] = noise
|
| 436 |
+
|
| 437 |
+
if do_normalize:
|
| 438 |
+
batched_speech["input_features"] = [
|
| 439 |
+
self.normalize(spectrogram) for spectrogram in batched_speech["input_features"]
|
| 440 |
+
]
|
| 441 |
+
|
| 442 |
+
if return_tensors is not None:
|
| 443 |
+
batched_speech = batched_speech.convert_to_tensors(return_tensors)
|
| 444 |
+
|
| 445 |
+
return batched_speech
|
| 446 |
+
|
| 447 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 448 |
+
output = super().to_dict()
|
| 449 |
+
|
| 450 |
+
# Don't serialize these as they are derived from the other properties.
|
| 451 |
+
names = ["window", "mel_filters", "n_fft", "n_freqs", "num_max_samples"]
|
| 452 |
+
for name in names:
|
| 453 |
+
if name in output:
|
| 454 |
+
del output[name]
|
| 455 |
+
|
| 456 |
+
return output
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/univnet/modeling_univnet.py
ADDED
|
@@ -0,0 +1,636 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
""" PyTorch UnivNetModel model."""
|
| 15 |
+
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from typing import Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.utils.checkpoint
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
from ...modeling_utils import ModelOutput, PreTrainedModel
|
| 24 |
+
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
|
| 25 |
+
from .configuration_univnet import UnivNetConfig
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
# General docstring
|
| 31 |
+
_CONFIG_FOR_DOC = "UnivNetConfig"
|
| 32 |
+
|
| 33 |
+
_CHECKPOINT_FOR_DOC = "dg845/univnet-dev"
|
| 34 |
+
|
| 35 |
+
UNIVNET_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 36 |
+
"dg845/univnet-dev",
|
| 37 |
+
# See all UnivNet models at https://huggingface.co/models?filter=univnet
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
class UnivNetModelOutput(ModelOutput):
|
| 43 |
+
"""
|
| 44 |
+
Output class for the [`UnivNetModel`], which includes the generated audio waveforms and the original unpadded
|
| 45 |
+
lengths of those waveforms (so that the padding can be removed by [`UnivNetModel.batch_decode`]).
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
waveforms (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 49 |
+
Batched 1D (mono-channel) output audio waveforms.
|
| 50 |
+
waveform_lengths (`torch.FloatTensor` of shape `(batch_size,)`):
|
| 51 |
+
The batched length in samples of each unpadded waveform in `waveforms`.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
waveforms: torch.FloatTensor = None
|
| 55 |
+
waveform_lengths: torch.FloatTensor = None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class UnivNetKernelPredictorResidualBlock(nn.Module):
|
| 59 |
+
"""
|
| 60 |
+
Implementation of the residual block for the kernel predictor network inside each location variable convolution
|
| 61 |
+
block (LVCBlock).
|
| 62 |
+
|
| 63 |
+
Parameters:
|
| 64 |
+
config: (`UnivNetConfig`):
|
| 65 |
+
Config for the `UnivNetModel` model.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
def __init__(
|
| 69 |
+
self,
|
| 70 |
+
config: UnivNetConfig,
|
| 71 |
+
):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.channels = config.model_in_channels
|
| 74 |
+
self.kernel_size = config.kernel_predictor_conv_size
|
| 75 |
+
self.dropout_prob = config.kernel_predictor_dropout
|
| 76 |
+
self.leaky_relu_slope = config.leaky_relu_slope
|
| 77 |
+
|
| 78 |
+
padding = (self.kernel_size - 1) // 2
|
| 79 |
+
|
| 80 |
+
self.dropout = nn.Dropout(self.dropout_prob)
|
| 81 |
+
self.conv1 = nn.Conv1d(self.channels, self.channels, self.kernel_size, padding=padding, bias=True)
|
| 82 |
+
self.conv2 = nn.Conv1d(self.channels, self.channels, self.kernel_size, padding=padding, bias=True)
|
| 83 |
+
|
| 84 |
+
def forward(self, hidden_states: torch.FloatTensor):
|
| 85 |
+
# hidden_states should have shape (batch_size, channels, seq_length)
|
| 86 |
+
residual = hidden_states
|
| 87 |
+
hidden_states = self.dropout(hidden_states)
|
| 88 |
+
hidden_states = self.conv1(hidden_states)
|
| 89 |
+
hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
|
| 90 |
+
hidden_states = self.conv2(hidden_states)
|
| 91 |
+
hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
|
| 92 |
+
return hidden_states + residual
|
| 93 |
+
|
| 94 |
+
def apply_weight_norm(self):
|
| 95 |
+
nn.utils.weight_norm(self.conv1)
|
| 96 |
+
nn.utils.weight_norm(self.conv2)
|
| 97 |
+
|
| 98 |
+
def remove_weight_norm(self):
|
| 99 |
+
nn.utils.remove_weight_norm(self.conv1)
|
| 100 |
+
nn.utils.remove_weight_norm(self.conv2)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class UnivNetKernelPredictor(nn.Module):
|
| 104 |
+
"""
|
| 105 |
+
Implementation of the kernel predictor network which supplies the kernel and bias for the location variable
|
| 106 |
+
convolutional layers (LVCs) in each UnivNet LVCBlock.
|
| 107 |
+
|
| 108 |
+
Based on the KernelPredictor implementation in
|
| 109 |
+
[maum-ai/univnet](https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L7).
|
| 110 |
+
|
| 111 |
+
Parameters:
|
| 112 |
+
config: (`UnivNetConfig`):
|
| 113 |
+
Config for the `UnivNetModel` model.
|
| 114 |
+
conv_kernel_size (`int`, *optional*, defaults to 3):
|
| 115 |
+
The kernel size for the location variable convolutional layer kernels (convolutional weight tensor).
|
| 116 |
+
conv_layers (`int`, *optional*, defaults to 4):
|
| 117 |
+
The number of location variable convolutional layers to output kernels and biases for.
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
def __init__(
|
| 121 |
+
self,
|
| 122 |
+
config: UnivNetConfig,
|
| 123 |
+
conv_kernel_size: int = 3,
|
| 124 |
+
conv_layers: int = 4,
|
| 125 |
+
):
|
| 126 |
+
super().__init__()
|
| 127 |
+
|
| 128 |
+
self.conv_in_channels = config.model_hidden_channels
|
| 129 |
+
self.conv_out_channels = 2 * config.model_hidden_channels
|
| 130 |
+
self.conv_kernel_size = conv_kernel_size
|
| 131 |
+
self.conv_layers = conv_layers
|
| 132 |
+
|
| 133 |
+
self.kernel_channels = (
|
| 134 |
+
self.conv_in_channels * self.conv_out_channels * self.conv_kernel_size * self.conv_layers
|
| 135 |
+
)
|
| 136 |
+
self.bias_channels = self.conv_out_channels * self.conv_layers
|
| 137 |
+
|
| 138 |
+
self.resnet_in_channels = config.num_mel_bins
|
| 139 |
+
self.resnet_hidden_channels = config.kernel_predictor_hidden_channels
|
| 140 |
+
self.resnet_kernel_size = config.kernel_predictor_conv_size
|
| 141 |
+
self.num_blocks = config.kernel_predictor_num_blocks
|
| 142 |
+
|
| 143 |
+
self.leaky_relu_slope = config.leaky_relu_slope
|
| 144 |
+
|
| 145 |
+
padding = (self.resnet_kernel_size - 1) // 2
|
| 146 |
+
|
| 147 |
+
self.input_conv = nn.Conv1d(self.resnet_in_channels, self.resnet_hidden_channels, 5, padding=2, bias=True)
|
| 148 |
+
|
| 149 |
+
self.resblocks = nn.ModuleList([UnivNetKernelPredictorResidualBlock(config) for _ in range(self.num_blocks)])
|
| 150 |
+
|
| 151 |
+
self.kernel_conv = nn.Conv1d(
|
| 152 |
+
self.resnet_hidden_channels, self.kernel_channels, self.resnet_kernel_size, padding=padding, bias=True
|
| 153 |
+
)
|
| 154 |
+
self.bias_conv = nn.Conv1d(
|
| 155 |
+
self.resnet_hidden_channels, self.bias_channels, self.resnet_kernel_size, padding=padding, bias=True
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def forward(self, spectrogram: torch.FloatTensor):
|
| 159 |
+
"""
|
| 160 |
+
Maps a conditioning log-mel spectrogram to a tensor of convolutional kernels and biases, for use in location
|
| 161 |
+
variable convolutional layers. Note that the input spectrogram should have shape (batch_size, input_channels,
|
| 162 |
+
seq_length).
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
spectrogram (`torch.FloatTensor` of shape `(batch_size, input_channels, seq_length)`):
|
| 166 |
+
Tensor containing the log-mel spectrograms.
|
| 167 |
+
|
| 168 |
+
Returns:
|
| 169 |
+
Tuple[`torch.FloatTensor, `torch.FloatTensor`]: tuple of tensors where the first element is the tensor of
|
| 170 |
+
location variable convolution kernels of shape `(batch_size, self.conv_layers, self.conv_in_channels,
|
| 171 |
+
self.conv_out_channels, self.conv_kernel_size, seq_length)` and the second element is the tensor of
|
| 172 |
+
location variable convolution biases of shape `(batch_size, self.conv_layers. self.conv_out_channels,
|
| 173 |
+
seq_length)`.
|
| 174 |
+
"""
|
| 175 |
+
batch_size, _, seq_length = spectrogram.shape
|
| 176 |
+
|
| 177 |
+
hidden_states = self.input_conv(spectrogram)
|
| 178 |
+
hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
|
| 179 |
+
|
| 180 |
+
for resblock in self.resblocks:
|
| 181 |
+
hidden_states = resblock(hidden_states)
|
| 182 |
+
|
| 183 |
+
kernel_hidden_states = self.kernel_conv(hidden_states)
|
| 184 |
+
bias_hidden_states = self.bias_conv(hidden_states)
|
| 185 |
+
|
| 186 |
+
# Reshape kernels and biases to appropriate shape
|
| 187 |
+
kernels = kernel_hidden_states.view(
|
| 188 |
+
batch_size,
|
| 189 |
+
self.conv_layers,
|
| 190 |
+
self.conv_in_channels,
|
| 191 |
+
self.conv_out_channels,
|
| 192 |
+
self.conv_kernel_size,
|
| 193 |
+
seq_length,
|
| 194 |
+
).contiguous()
|
| 195 |
+
biases = bias_hidden_states.view(
|
| 196 |
+
batch_size,
|
| 197 |
+
self.conv_layers,
|
| 198 |
+
self.conv_out_channels,
|
| 199 |
+
seq_length,
|
| 200 |
+
).contiguous()
|
| 201 |
+
|
| 202 |
+
return kernels, biases
|
| 203 |
+
|
| 204 |
+
def apply_weight_norm(self):
|
| 205 |
+
nn.utils.weight_norm(self.input_conv)
|
| 206 |
+
for layer in self.resblocks:
|
| 207 |
+
layer.apply_weight_norm()
|
| 208 |
+
nn.utils.weight_norm(self.kernel_conv)
|
| 209 |
+
nn.utils.weight_norm(self.bias_conv)
|
| 210 |
+
|
| 211 |
+
def remove_weight_norm(self):
|
| 212 |
+
nn.utils.remove_weight_norm(self.input_conv)
|
| 213 |
+
for layer in self.resblocks:
|
| 214 |
+
layer.remove_weight_norm()
|
| 215 |
+
nn.utils.remove_weight_norm(self.kernel_conv)
|
| 216 |
+
nn.utils.remove_weight_norm(self.bias_conv)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class UnivNetLvcResidualBlock(nn.Module):
|
| 220 |
+
"""
|
| 221 |
+
Implementation of the location variable convolution (LVC) residual block for the UnivNet residual network.
|
| 222 |
+
|
| 223 |
+
Parameters:
|
| 224 |
+
config: (`UnivNetConfig`):
|
| 225 |
+
Config for the `UnivNetModel` model.
|
| 226 |
+
kernel_size (`int`):
|
| 227 |
+
The kernel size for the dilated 1D convolutional layer.
|
| 228 |
+
dilation (`int`):
|
| 229 |
+
The dilation for the dilated 1D convolutional layer.
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
def __init__(
|
| 233 |
+
self,
|
| 234 |
+
config: UnivNetConfig,
|
| 235 |
+
kernel_size: int,
|
| 236 |
+
dilation: int,
|
| 237 |
+
):
|
| 238 |
+
super().__init__()
|
| 239 |
+
self.hidden_channels = config.model_hidden_channels
|
| 240 |
+
self.kernel_size = kernel_size
|
| 241 |
+
self.dilation = dilation
|
| 242 |
+
self.leaky_relu_slope = config.leaky_relu_slope
|
| 243 |
+
|
| 244 |
+
padding = self.dilation * (self.kernel_size - 1) // 2
|
| 245 |
+
|
| 246 |
+
self.conv = nn.Conv1d(
|
| 247 |
+
self.hidden_channels,
|
| 248 |
+
self.hidden_channels,
|
| 249 |
+
self.kernel_size,
|
| 250 |
+
padding=padding,
|
| 251 |
+
dilation=self.dilation,
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
def forward(self, hidden_states, kernel, bias, hop_size=256):
|
| 255 |
+
residual = hidden_states
|
| 256 |
+
hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
|
| 257 |
+
hidden_states = self.conv(hidden_states)
|
| 258 |
+
hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
|
| 259 |
+
hidden_states = self.location_variable_convolution(hidden_states, kernel, bias, hop_size=hop_size)
|
| 260 |
+
# Gated activation unit
|
| 261 |
+
hidden_states = torch.sigmoid(hidden_states[:, : self.hidden_channels, :]) * torch.tanh(
|
| 262 |
+
hidden_states[:, self.hidden_channels :, :]
|
| 263 |
+
)
|
| 264 |
+
# Skip connection
|
| 265 |
+
hidden_states = residual + hidden_states
|
| 266 |
+
|
| 267 |
+
return hidden_states
|
| 268 |
+
|
| 269 |
+
# Based on https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L171
|
| 270 |
+
def location_variable_convolution(
|
| 271 |
+
self,
|
| 272 |
+
hidden_states: torch.FloatTensor,
|
| 273 |
+
kernel: torch.FloatTensor,
|
| 274 |
+
bias: torch.FloatTensor,
|
| 275 |
+
dilation: int = 1,
|
| 276 |
+
hop_size: int = 256,
|
| 277 |
+
):
|
| 278 |
+
"""
|
| 279 |
+
Performs location-variable convolution operation on the input sequence (hidden_states) using the local
|
| 280 |
+
convolution kernel. This was introduced in [LVCNet: Efficient Condition-Dependent Modeling Network for Waveform
|
| 281 |
+
Generation](https://arxiv.org/abs/2102.10815) by Zhen Zheng, Jianzong Wang, Ning Cheng, and Jing Xiao.
|
| 282 |
+
|
| 283 |
+
Time: 414 μs ± 309 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each), test on NVIDIA V100.
|
| 284 |
+
|
| 285 |
+
Args:
|
| 286 |
+
hidden_states (`torch.FloatTensor` of shape `(batch_size, in_channels, in_length)`):
|
| 287 |
+
The input sequence of shape (batch, in_channels, in_length).
|
| 288 |
+
kernel (`torch.FloatTensor` of shape `(batch_size, in_channels, out_channels, kernel_size, kernel_length)`):
|
| 289 |
+
The local convolution kernel of shape (batch, in_channels, out_channels, kernel_size, kernel_length).
|
| 290 |
+
bias (`torch.FloatTensor` of shape `(batch_size, out_channels, kernel_length)`):
|
| 291 |
+
The bias for the local convolution of shape (batch, out_channels, kernel_length).
|
| 292 |
+
dilation (`int`, *optional*, defaults to 1):
|
| 293 |
+
The dilation of convolution.
|
| 294 |
+
hop_size (`int`, *optional*, defaults to 256):
|
| 295 |
+
The hop_size of the conditioning sequence.
|
| 296 |
+
Returns:
|
| 297 |
+
`torch.FloatTensor`: the output sequence after performing local convolution with shape (batch_size,
|
| 298 |
+
out_channels, in_length).
|
| 299 |
+
"""
|
| 300 |
+
batch, _, in_length = hidden_states.shape
|
| 301 |
+
batch, _, out_channels, kernel_size, kernel_length = kernel.shape
|
| 302 |
+
if in_length != (kernel_length * hop_size):
|
| 303 |
+
raise ValueError(
|
| 304 |
+
f"Dim 2 of `hidden_states` should be {kernel_length * hop_size}) but got {in_length}. Please check"
|
| 305 |
+
" `hidden_states` or `kernel` and `hop_size` to make sure they are correct."
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
padding = dilation * int((kernel_size - 1) / 2)
|
| 309 |
+
|
| 310 |
+
# (batch, in_channels, in_length + 2*padding)
|
| 311 |
+
hidden_states = nn.functional.pad(hidden_states, (padding, padding), "constant", 0)
|
| 312 |
+
# (batch, in_channels, kernel_length, hop_size + 2*padding)
|
| 313 |
+
hidden_states = hidden_states.unfold(2, hop_size + 2 * padding, hop_size)
|
| 314 |
+
|
| 315 |
+
if hop_size < dilation:
|
| 316 |
+
hidden_states = nn.functional.pad(hidden_states, (0, dilation), "constant", 0)
|
| 317 |
+
# (batch, in_channels, kernel_length, (hop_size + 2*padding)/dilation, dilation)
|
| 318 |
+
hidden_states = hidden_states.unfold(3, dilation, dilation)
|
| 319 |
+
hidden_states = hidden_states[:, :, :, :, :hop_size]
|
| 320 |
+
# (batch, in_channels, kernel_length, dilation, (hop_size + 2*padding)/dilation)
|
| 321 |
+
hidden_states = hidden_states.transpose(3, 4)
|
| 322 |
+
# (batch, in_channels, kernel_length, dilation, _, kernel_size)
|
| 323 |
+
hidden_states = hidden_states.unfold(4, kernel_size, 1)
|
| 324 |
+
|
| 325 |
+
# Apply local convolution kernel to hidden_states.
|
| 326 |
+
output_hidden_states = torch.einsum("bildsk,biokl->bolsd", hidden_states, kernel)
|
| 327 |
+
|
| 328 |
+
output_hidden_states = output_hidden_states.to(memory_format=torch.channels_last_3d)
|
| 329 |
+
bias = bias.unsqueeze(-1).unsqueeze(-1).to(memory_format=torch.channels_last_3d)
|
| 330 |
+
output_hidden_states = output_hidden_states + bias
|
| 331 |
+
output_hidden_states = output_hidden_states.contiguous().view(batch, out_channels, -1)
|
| 332 |
+
|
| 333 |
+
return output_hidden_states
|
| 334 |
+
|
| 335 |
+
def apply_weight_norm(self):
|
| 336 |
+
nn.utils.weight_norm(self.conv)
|
| 337 |
+
|
| 338 |
+
def remove_weight_norm(self):
|
| 339 |
+
nn.utils.remove_weight_norm(self.conv)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class UnivNetLvcBlock(nn.Module):
|
| 343 |
+
"""
|
| 344 |
+
Implementation of the location variable convolution (LVC) residual block of the UnivNet residual block. Includes a
|
| 345 |
+
`UnivNetKernelPredictor` inside to predict the kernels and biases of the LVC layers.
|
| 346 |
+
|
| 347 |
+
Based on LVCBlock in
|
| 348 |
+
[maum-ai/univnet](https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L98)
|
| 349 |
+
|
| 350 |
+
Parameters:
|
| 351 |
+
config (`UnivNetConfig`):
|
| 352 |
+
Config for the `UnivNetModel` model.
|
| 353 |
+
layer_id (`int`):
|
| 354 |
+
An integer corresponding to the index of the current LVC resnet block layer. This should be between 0 and
|
| 355 |
+
`len(config.resblock_stride_sizes) - 1)` inclusive.
|
| 356 |
+
lvc_hop_size (`int`, *optional*, defaults to 256):
|
| 357 |
+
The hop size for the location variable convolutional layers.
|
| 358 |
+
"""
|
| 359 |
+
|
| 360 |
+
def __init__(
|
| 361 |
+
self,
|
| 362 |
+
config: UnivNetConfig,
|
| 363 |
+
layer_id: int,
|
| 364 |
+
lvc_hop_size: int = 256,
|
| 365 |
+
):
|
| 366 |
+
super().__init__()
|
| 367 |
+
self.hidden_channels = config.model_hidden_channels
|
| 368 |
+
self.kernel_size = config.resblock_kernel_sizes[layer_id]
|
| 369 |
+
self.stride = config.resblock_stride_sizes[layer_id]
|
| 370 |
+
self.dilations = config.resblock_dilation_sizes[layer_id]
|
| 371 |
+
self.cond_hop_length = lvc_hop_size
|
| 372 |
+
self.leaky_relu_slope = config.leaky_relu_slope
|
| 373 |
+
self.num_blocks = len(self.dilations)
|
| 374 |
+
|
| 375 |
+
self.convt_pre = nn.ConvTranspose1d(
|
| 376 |
+
self.hidden_channels,
|
| 377 |
+
self.hidden_channels,
|
| 378 |
+
2 * self.stride,
|
| 379 |
+
stride=self.stride,
|
| 380 |
+
padding=self.stride // 2 + self.stride % 2,
|
| 381 |
+
output_padding=self.stride % 2,
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
self.kernel_predictor = UnivNetKernelPredictor(config, self.kernel_size, self.num_blocks)
|
| 385 |
+
|
| 386 |
+
self.resblocks = nn.ModuleList(
|
| 387 |
+
[UnivNetLvcResidualBlock(config, self.kernel_size, self.dilations[i]) for i in range(self.num_blocks)]
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
def forward(self, hidden_states: torch.FloatTensor, spectrogram: torch.FloatTensor):
|
| 391 |
+
# hidden_states: (batch_size, hidden_channels, seq_length)
|
| 392 |
+
# spectrogram: (batch_size, cond_channels, cond_length)
|
| 393 |
+
hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
|
| 394 |
+
hidden_states = self.convt_pre(hidden_states)
|
| 395 |
+
|
| 396 |
+
kernels, biases = self.kernel_predictor(spectrogram)
|
| 397 |
+
|
| 398 |
+
for i, resblock in enumerate(self.resblocks):
|
| 399 |
+
kernel = kernels[:, i, :, :, :, :]
|
| 400 |
+
bias = biases[:, i, :, :]
|
| 401 |
+
hidden_states = resblock(hidden_states, kernel, bias, hop_size=self.cond_hop_length)
|
| 402 |
+
|
| 403 |
+
return hidden_states
|
| 404 |
+
|
| 405 |
+
def apply_weight_norm(self):
|
| 406 |
+
nn.utils.weight_norm(self.convt_pre)
|
| 407 |
+
self.kernel_predictor.apply_weight_norm()
|
| 408 |
+
for layer in self.resblocks:
|
| 409 |
+
layer.apply_weight_norm()
|
| 410 |
+
|
| 411 |
+
def remove_weight_norm(self):
|
| 412 |
+
nn.utils.remove_weight_norm(self.convt_pre)
|
| 413 |
+
self.kernel_predictor.remove_weight_norm()
|
| 414 |
+
for layer in self.resblocks:
|
| 415 |
+
layer.remove_weight_norm()
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
UNIVNET_START_DOCSTRING = r"""
|
| 419 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 420 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 421 |
+
etc.)
|
| 422 |
+
|
| 423 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 424 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 425 |
+
and behavior.
|
| 426 |
+
|
| 427 |
+
Parameters:
|
| 428 |
+
config ([`UnivNetConfig`]):
|
| 429 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 430 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 431 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 432 |
+
"""
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
UNIVNET_INPUTS_DOCSTRING = r"""
|
| 436 |
+
Converts a noise waveform and a conditioning spectrogram to a speech waveform. Passing a batch of log-mel
|
| 437 |
+
spectrograms returns a batch of speech waveforms. Passing a single, un-batched log-mel spectrogram returns a
|
| 438 |
+
single, un-batched speech waveform.
|
| 439 |
+
|
| 440 |
+
Args:
|
| 441 |
+
input_features (`torch.FloatTensor`):
|
| 442 |
+
Tensor containing the log-mel spectrograms. Can be batched and of shape `(batch_size, sequence_length,
|
| 443 |
+
config.num_mel_channels)`, or un-batched and of shape `(sequence_length, config.num_mel_channels)`.
|
| 444 |
+
noise_sequence (`torch.FloatTensor`, *optional*):
|
| 445 |
+
Tensor containing a noise sequence of standard Gaussian noise. Can be batched and of shape `(batch_size,
|
| 446 |
+
sequence_length, config.model_in_channels)`, or un-batched and of shape (sequence_length,
|
| 447 |
+
config.model_in_channels)`. If not supplied, will be randomly generated.
|
| 448 |
+
padding_mask (`torch.BoolTensor`, *optional*):
|
| 449 |
+
Mask indicating which parts of each sequence are padded. Mask values are selected in `[0, 1]`:
|
| 450 |
+
|
| 451 |
+
- 1 for tokens that are **not masked**
|
| 452 |
+
- 0 for tokens that are **masked**
|
| 453 |
+
|
| 454 |
+
The mask can be batched and of shape `(batch_size, sequence_length)` or un-batched and of shape
|
| 455 |
+
`(sequence_length,)`.
|
| 456 |
+
generator (`torch.Generator`, *optional*):
|
| 457 |
+
A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
|
| 458 |
+
deterministic.
|
| 459 |
+
return_dict:
|
| 460 |
+
Whether to return a [`~utils.ModelOutput`] subclass instead of a plain tuple.
|
| 461 |
+
"""
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
@add_start_docstrings(
|
| 465 |
+
"""UnivNet GAN vocoder.""",
|
| 466 |
+
UNIVNET_START_DOCSTRING,
|
| 467 |
+
)
|
| 468 |
+
class UnivNetModel(PreTrainedModel):
|
| 469 |
+
config_class = UnivNetConfig
|
| 470 |
+
main_input_name = "input_features"
|
| 471 |
+
|
| 472 |
+
def __init__(self, config: UnivNetConfig):
|
| 473 |
+
super().__init__(config)
|
| 474 |
+
|
| 475 |
+
self.num_kernels = len(config.resblock_kernel_sizes)
|
| 476 |
+
self.leaky_relu_slope = config.leaky_relu_slope
|
| 477 |
+
|
| 478 |
+
self.conv_pre = nn.Conv1d(
|
| 479 |
+
config.model_in_channels,
|
| 480 |
+
config.model_hidden_channels,
|
| 481 |
+
kernel_size=7,
|
| 482 |
+
stride=1,
|
| 483 |
+
padding=3,
|
| 484 |
+
padding_mode="reflect",
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
# Initialize location-variable convolution ResNet Blocks.
|
| 488 |
+
num_layers = len(config.resblock_stride_sizes)
|
| 489 |
+
hop_length = 1
|
| 490 |
+
hop_lengths = []
|
| 491 |
+
for stride in config.resblock_stride_sizes:
|
| 492 |
+
hop_length = hop_length * stride
|
| 493 |
+
hop_lengths.append(hop_length)
|
| 494 |
+
|
| 495 |
+
self.resblocks = nn.ModuleList(
|
| 496 |
+
[
|
| 497 |
+
UnivNetLvcBlock(
|
| 498 |
+
config,
|
| 499 |
+
layer_id=i,
|
| 500 |
+
lvc_hop_size=hop_lengths[i],
|
| 501 |
+
)
|
| 502 |
+
for i in range(num_layers)
|
| 503 |
+
]
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
self.conv_post = nn.Conv1d(config.model_hidden_channels, 1, 7, padding=3, padding_mode="reflect")
|
| 507 |
+
|
| 508 |
+
# Initialize weights and apply final processing
|
| 509 |
+
self.post_init()
|
| 510 |
+
|
| 511 |
+
@add_start_docstrings_to_model_forward(UNIVNET_INPUTS_DOCSTRING)
|
| 512 |
+
@replace_return_docstrings(output_type=UnivNetModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 513 |
+
def forward(
|
| 514 |
+
self,
|
| 515 |
+
input_features: torch.FloatTensor,
|
| 516 |
+
noise_sequence: Optional[torch.FloatTensor] = None,
|
| 517 |
+
padding_mask: Optional[torch.FloatTensor] = None,
|
| 518 |
+
generator: Optional[torch.Generator] = None,
|
| 519 |
+
return_dict: Optional[bool] = None,
|
| 520 |
+
) -> Union[Tuple[torch.FloatTensor], UnivNetModelOutput]:
|
| 521 |
+
r"""
|
| 522 |
+
Returns:
|
| 523 |
+
|
| 524 |
+
Example:
|
| 525 |
+
|
| 526 |
+
```python
|
| 527 |
+
>>> from transformers import UnivNetFeatureExtractor, UnivNetModel
|
| 528 |
+
>>> from datasets import load_dataset, Audio
|
| 529 |
+
|
| 530 |
+
>>> model = UnivNetModel.from_pretrained("dg845/univnet-dev")
|
| 531 |
+
>>> feature_extractor = UnivNetFeatureExtractor.from_pretrained("dg845/univnet-dev")
|
| 532 |
+
|
| 533 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 534 |
+
>>> # Resample the audio to the feature extractor's sampling rate.
|
| 535 |
+
>>> ds = ds.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
|
| 536 |
+
>>> inputs = feature_extractor(
|
| 537 |
+
... ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], return_tensors="pt"
|
| 538 |
+
... )
|
| 539 |
+
>>> audio = model(**inputs).waveforms
|
| 540 |
+
>>> list(audio.shape)
|
| 541 |
+
[1, 140288]
|
| 542 |
+
```
|
| 543 |
+
"""
|
| 544 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 545 |
+
|
| 546 |
+
# Resolve batch sizes for noise_sequence and spectrogram
|
| 547 |
+
spectrogram_batched = input_features.dim() == 3
|
| 548 |
+
if not spectrogram_batched:
|
| 549 |
+
input_features = input_features.unsqueeze(0)
|
| 550 |
+
spectrogram_batch_size, spectrogram_length, _ = input_features.shape
|
| 551 |
+
|
| 552 |
+
if noise_sequence is not None:
|
| 553 |
+
noise_sequence_batched = noise_sequence.dim() == 3
|
| 554 |
+
if not noise_sequence_batched:
|
| 555 |
+
noise_sequence = noise_sequence.unsqueeze(0)
|
| 556 |
+
else:
|
| 557 |
+
# Randomly generate noise_sequence
|
| 558 |
+
noise_sequence_shape = (spectrogram_batch_size, spectrogram_length, self.config.model_in_channels)
|
| 559 |
+
noise_sequence = torch.randn(
|
| 560 |
+
noise_sequence_shape, generator=generator, dtype=input_features.dtype, device=input_features.device
|
| 561 |
+
)
|
| 562 |
+
noise_sequence_batch_size = noise_sequence.shape[0]
|
| 563 |
+
|
| 564 |
+
if spectrogram_batch_size > 1 and noise_sequence_batch_size == 1:
|
| 565 |
+
# Repeat noise_sequence spectrogram_batch_size times
|
| 566 |
+
noise_sequence = noise_sequence.repeat(spectrogram_batch_size, 1, 1)
|
| 567 |
+
elif noise_sequence_batch_size > 1 and spectrogram_batch_size == 1:
|
| 568 |
+
# Repeat spectrogram noise_sequence_batch_size times
|
| 569 |
+
input_features = input_features.repeat(noise_sequence_batch_size, 1, 1)
|
| 570 |
+
|
| 571 |
+
if noise_sequence_batch_size != spectrogram_batch_size:
|
| 572 |
+
raise ValueError(
|
| 573 |
+
f"The batch size of `noise_sequence` is {noise_sequence_batch_size} and the batch size of"
|
| 574 |
+
f" `input_features` is {spectrogram_batch_size}, but the two are expected to be equal."
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
if padding_mask is not None:
|
| 578 |
+
if padding_mask.dim() == 1:
|
| 579 |
+
padding_mask = padding_mask.unsqueeze(0)
|
| 580 |
+
padding_mask_batch_size = padding_mask.shape[0]
|
| 581 |
+
if padding_mask_batch_size != spectrogram_batch_size:
|
| 582 |
+
raise ValueError(
|
| 583 |
+
f"The batch size of `padding_mask` is {padding_mask_batch_size} and the batch size of"
|
| 584 |
+
f" `input_features` is {spectrogram_batch_size}, but the two are expected to be equal."
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
# Change shapes to have channels before sequence lengths
|
| 588 |
+
hidden_states = noise_sequence.transpose(2, 1)
|
| 589 |
+
input_features = input_features.transpose(2, 1)
|
| 590 |
+
|
| 591 |
+
hidden_states = self.conv_pre(hidden_states)
|
| 592 |
+
|
| 593 |
+
for resblock in self.resblocks:
|
| 594 |
+
hidden_states = resblock(hidden_states, input_features)
|
| 595 |
+
|
| 596 |
+
hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
|
| 597 |
+
hidden_states = self.conv_post(hidden_states)
|
| 598 |
+
hidden_states = torch.tanh(hidden_states)
|
| 599 |
+
|
| 600 |
+
# Remove sequence length dimension since this collapses to 1
|
| 601 |
+
# NOTE: keep waveforms batched even if there's only one
|
| 602 |
+
waveform = hidden_states.squeeze(1)
|
| 603 |
+
|
| 604 |
+
# Get sequence lengths for UnivNetFeatureExtractor.batch_decode.
|
| 605 |
+
waveform_lengths = None
|
| 606 |
+
if padding_mask is not None:
|
| 607 |
+
# Padding is always contiguous and added on the right
|
| 608 |
+
waveform_lengths = torch.sum(padding_mask, dim=1)
|
| 609 |
+
|
| 610 |
+
if not return_dict:
|
| 611 |
+
outputs = (waveform, waveform_lengths)
|
| 612 |
+
return outputs
|
| 613 |
+
|
| 614 |
+
return UnivNetModelOutput(
|
| 615 |
+
waveforms=waveform,
|
| 616 |
+
waveform_lengths=waveform_lengths,
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
def _init_weights(self, module):
|
| 620 |
+
"""Initialize the weights."""
|
| 621 |
+
if isinstance(module, (nn.Linear, nn.Conv1d, nn.ConvTranspose1d)):
|
| 622 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 623 |
+
if module.bias is not None:
|
| 624 |
+
module.bias.data.zero_()
|
| 625 |
+
|
| 626 |
+
def apply_weight_norm(self):
|
| 627 |
+
nn.utils.weight_norm(self.conv_pre)
|
| 628 |
+
for layer in self.resblocks:
|
| 629 |
+
layer.apply_weight_norm()
|
| 630 |
+
nn.utils.weight_norm(self.conv_post)
|
| 631 |
+
|
| 632 |
+
def remove_weight_norm(self):
|
| 633 |
+
nn.utils.remove_weight_norm(self.conv_pre)
|
| 634 |
+
for layer in self.resblocks:
|
| 635 |
+
layer.remove_weight_norm()
|
| 636 |
+
nn.utils.remove_weight_norm(self.conv_post)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/yoso/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.05 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/yoso/__pycache__/configuration_yoso.cpython-310.pyc
ADDED
|
Binary file (5.93 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/yoso/__pycache__/modeling_yoso.cpython-310.pyc
ADDED
|
Binary file (35.8 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/yoso/convert_yoso_pytorch_to_pytorch.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert YOSO checkpoints from the original repository. URL: https://github.com/mlpen/YOSO"""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from transformers import YosoConfig, YosoForMaskedLM
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def rename_key(orig_key):
|
| 25 |
+
if "model" in orig_key:
|
| 26 |
+
orig_key = orig_key.replace("model.", "")
|
| 27 |
+
if "norm1" in orig_key:
|
| 28 |
+
orig_key = orig_key.replace("norm1", "attention.output.LayerNorm")
|
| 29 |
+
if "norm2" in orig_key:
|
| 30 |
+
orig_key = orig_key.replace("norm2", "output.LayerNorm")
|
| 31 |
+
if "norm" in orig_key:
|
| 32 |
+
orig_key = orig_key.replace("norm", "LayerNorm")
|
| 33 |
+
if "transformer" in orig_key:
|
| 34 |
+
layer_num = orig_key.split(".")[0].split("_")[-1]
|
| 35 |
+
orig_key = orig_key.replace(f"transformer_{layer_num}", f"encoder.layer.{layer_num}")
|
| 36 |
+
if "mha.attn" in orig_key:
|
| 37 |
+
orig_key = orig_key.replace("mha.attn", "attention.self")
|
| 38 |
+
if "mha" in orig_key:
|
| 39 |
+
orig_key = orig_key.replace("mha", "attention")
|
| 40 |
+
if "W_q" in orig_key:
|
| 41 |
+
orig_key = orig_key.replace("W_q", "self.query")
|
| 42 |
+
if "W_k" in orig_key:
|
| 43 |
+
orig_key = orig_key.replace("W_k", "self.key")
|
| 44 |
+
if "W_v" in orig_key:
|
| 45 |
+
orig_key = orig_key.replace("W_v", "self.value")
|
| 46 |
+
if "ff1" in orig_key:
|
| 47 |
+
orig_key = orig_key.replace("ff1", "intermediate.dense")
|
| 48 |
+
if "ff2" in orig_key:
|
| 49 |
+
orig_key = orig_key.replace("ff2", "output.dense")
|
| 50 |
+
if "ff" in orig_key:
|
| 51 |
+
orig_key = orig_key.replace("ff", "output.dense")
|
| 52 |
+
if "mlm_class" in orig_key:
|
| 53 |
+
orig_key = orig_key.replace("mlm.mlm_class", "cls.predictions.decoder")
|
| 54 |
+
if "mlm" in orig_key:
|
| 55 |
+
orig_key = orig_key.replace("mlm", "cls.predictions.transform")
|
| 56 |
+
if "cls" not in orig_key:
|
| 57 |
+
orig_key = "yoso." + orig_key
|
| 58 |
+
|
| 59 |
+
return orig_key
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def convert_checkpoint_helper(max_position_embeddings, orig_state_dict):
|
| 63 |
+
for key in orig_state_dict.copy().keys():
|
| 64 |
+
val = orig_state_dict.pop(key)
|
| 65 |
+
|
| 66 |
+
if ("pooler" in key) or ("sen_class" in key):
|
| 67 |
+
continue
|
| 68 |
+
else:
|
| 69 |
+
orig_state_dict[rename_key(key)] = val
|
| 70 |
+
|
| 71 |
+
orig_state_dict["cls.predictions.bias"] = orig_state_dict["cls.predictions.decoder.bias"]
|
| 72 |
+
orig_state_dict["yoso.embeddings.position_ids"] = torch.arange(max_position_embeddings).expand((1, -1)) + 2
|
| 73 |
+
|
| 74 |
+
return orig_state_dict
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def convert_yoso_checkpoint(checkpoint_path, yoso_config_file, pytorch_dump_path):
|
| 78 |
+
orig_state_dict = torch.load(checkpoint_path, map_location="cpu")["model_state_dict"]
|
| 79 |
+
config = YosoConfig.from_json_file(yoso_config_file)
|
| 80 |
+
model = YosoForMaskedLM(config)
|
| 81 |
+
|
| 82 |
+
new_state_dict = convert_checkpoint_helper(config.max_position_embeddings, orig_state_dict)
|
| 83 |
+
|
| 84 |
+
print(model.load_state_dict(new_state_dict))
|
| 85 |
+
model.eval()
|
| 86 |
+
model.save_pretrained(pytorch_dump_path)
|
| 87 |
+
|
| 88 |
+
print(f"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}")
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
if __name__ == "__main__":
|
| 92 |
+
parser = argparse.ArgumentParser()
|
| 93 |
+
# Required parameters
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--pytorch_model_path", default=None, type=str, required=True, help="Path to YOSO pytorch checkpoint."
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument(
|
| 98 |
+
"--config_file",
|
| 99 |
+
default=None,
|
| 100 |
+
type=str,
|
| 101 |
+
required=True,
|
| 102 |
+
help="The json file for YOSO model config.",
|
| 103 |
+
)
|
| 104 |
+
parser.add_argument(
|
| 105 |
+
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
|
| 106 |
+
)
|
| 107 |
+
args = parser.parse_args()
|
| 108 |
+
convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/yoso/modeling_yoso.py
ADDED
|
@@ -0,0 +1,1304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 University of Wisconsin-Madison and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" PyTorch YOSO model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.utils.checkpoint
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 26 |
+
|
| 27 |
+
from ...activations import ACT2FN
|
| 28 |
+
from ...modeling_outputs import (
|
| 29 |
+
BaseModelOutputWithCrossAttentions,
|
| 30 |
+
MaskedLMOutput,
|
| 31 |
+
MultipleChoiceModelOutput,
|
| 32 |
+
QuestionAnsweringModelOutput,
|
| 33 |
+
SequenceClassifierOutput,
|
| 34 |
+
TokenClassifierOutput,
|
| 35 |
+
)
|
| 36 |
+
from ...modeling_utils import PreTrainedModel
|
| 37 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 38 |
+
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 39 |
+
from .configuration_yoso import YosoConfig
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
_CHECKPOINT_FOR_DOC = "uw-madison/yoso-4096"
|
| 45 |
+
_CONFIG_FOR_DOC = "YosoConfig"
|
| 46 |
+
|
| 47 |
+
YOSO_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 48 |
+
"uw-madison/yoso-4096",
|
| 49 |
+
# See all YOSO models at https://huggingface.co/models?filter=yoso
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def load_cuda_kernels():
|
| 54 |
+
global lsh_cumulation
|
| 55 |
+
try:
|
| 56 |
+
from torch.utils.cpp_extension import load
|
| 57 |
+
|
| 58 |
+
def append_root(files):
|
| 59 |
+
src_folder = Path(__file__).resolve().parent.parent.parent / "kernels" / "yoso"
|
| 60 |
+
return [src_folder / file for file in files]
|
| 61 |
+
|
| 62 |
+
src_files = append_root(
|
| 63 |
+
["fast_lsh_cumulation_torch.cpp", "fast_lsh_cumulation.cu", "fast_lsh_cumulation_cuda.cu"]
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
load("fast_lsh_cumulation", src_files, verbose=True)
|
| 67 |
+
|
| 68 |
+
import fast_lsh_cumulation as lsh_cumulation
|
| 69 |
+
|
| 70 |
+
return True
|
| 71 |
+
except Exception:
|
| 72 |
+
lsh_cumulation = None
|
| 73 |
+
return False
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def to_contiguous(input_tensors):
|
| 77 |
+
if isinstance(input_tensors, list):
|
| 78 |
+
out = []
|
| 79 |
+
for tensor in input_tensors:
|
| 80 |
+
if not tensor.is_contiguous():
|
| 81 |
+
tensor = tensor.contiguous()
|
| 82 |
+
out.append(tensor)
|
| 83 |
+
return out
|
| 84 |
+
else:
|
| 85 |
+
if not input_tensors.is_contiguous():
|
| 86 |
+
input_tensors = input_tensors.contiguous()
|
| 87 |
+
return input_tensors
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def normalize(input_tensors):
|
| 91 |
+
if isinstance(input_tensors, list):
|
| 92 |
+
out = []
|
| 93 |
+
for tensor in input_tensors:
|
| 94 |
+
out.append(nn.functional.normalize(tensor, p=2, dim=-1))
|
| 95 |
+
return out
|
| 96 |
+
else:
|
| 97 |
+
return nn.functional.normalize(input_tensors, p=2, dim=-1)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def hashing(query, key, num_hash, hash_len):
|
| 101 |
+
if len(query.size()) != 3:
|
| 102 |
+
raise ValueError("Query has incorrect size.")
|
| 103 |
+
if len(key.size()) != 3:
|
| 104 |
+
raise ValueError("Key has incorrect size.")
|
| 105 |
+
|
| 106 |
+
rmat = torch.randn(query.size(0), query.size(2), num_hash * hash_len, device=query.device)
|
| 107 |
+
raise_pow = 2 ** torch.arange(hash_len, device=query.device)
|
| 108 |
+
|
| 109 |
+
query_projection = torch.matmul(query, rmat).reshape(query.size(0), query.size(1), num_hash, hash_len)
|
| 110 |
+
key_projection = torch.matmul(key, rmat).reshape(key.size(0), key.size(1), num_hash, hash_len)
|
| 111 |
+
query_binary = (query_projection > 0).int()
|
| 112 |
+
key_binary = (key_projection > 0).int()
|
| 113 |
+
query_hash = torch.sum(query_binary * raise_pow, dim=-1)
|
| 114 |
+
query_hash = torch.sum(key_binary * raise_pow, dim=-1)
|
| 115 |
+
|
| 116 |
+
return query_hash.int(), query_hash.int()
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class YosoCumulation(torch.autograd.Function):
|
| 120 |
+
@staticmethod
|
| 121 |
+
def forward(ctx, query_mask, key_mask, query, key, value, config):
|
| 122 |
+
hash_code_len = config["hash_code_len"]
|
| 123 |
+
|
| 124 |
+
expectation = (1 - torch.acos(torch.matmul(query, key.transpose(-1, -2))) / math.pi) ** hash_code_len
|
| 125 |
+
expectation = expectation * query_mask[:, :, None] * key_mask[:, None, :]
|
| 126 |
+
cumulation_value = torch.matmul(expectation, value)
|
| 127 |
+
|
| 128 |
+
ctx.save_for_backward(query_mask, key_mask, expectation, query, key, value)
|
| 129 |
+
ctx.config = config
|
| 130 |
+
|
| 131 |
+
return cumulation_value
|
| 132 |
+
|
| 133 |
+
@staticmethod
|
| 134 |
+
def backward(ctx, grad):
|
| 135 |
+
grad = to_contiguous(grad)
|
| 136 |
+
|
| 137 |
+
query_mask, key_mask, expectation, query, key, value = ctx.saved_tensors
|
| 138 |
+
config = ctx.config
|
| 139 |
+
|
| 140 |
+
hash_code_len = config["hash_code_len"]
|
| 141 |
+
|
| 142 |
+
weighted_exp = torch.matmul(grad, value.transpose(-1, -2)) * expectation
|
| 143 |
+
grad_query = torch.matmul(weighted_exp, (hash_code_len / 2) * key)
|
| 144 |
+
grad_key = torch.matmul(weighted_exp.transpose(-1, -2), (hash_code_len / 2) * query)
|
| 145 |
+
grad_value = torch.matmul(expectation.transpose(-1, -2), grad)
|
| 146 |
+
|
| 147 |
+
return None, None, grad_query, grad_key, grad_value, None
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class YosoLSHCumulation(torch.autograd.Function):
|
| 151 |
+
@staticmethod
|
| 152 |
+
def forward(ctx, query_mask, key_mask, query, key, value, config):
|
| 153 |
+
if query_mask.size(0) != key_mask.size(0):
|
| 154 |
+
raise ValueError("Query mask and Key mask differ in sizes in dimension 0")
|
| 155 |
+
if query_mask.size(0) != query.size(0):
|
| 156 |
+
raise ValueError("Query mask and Query differ in sizes in dimension 0")
|
| 157 |
+
if query_mask.size(0) != key.size(0):
|
| 158 |
+
raise ValueError("Query mask and Key differ in sizes in dimension 0")
|
| 159 |
+
if query_mask.size(0) != value.size(0):
|
| 160 |
+
raise ValueError("Query mask and Value mask differ in sizes in dimension 0")
|
| 161 |
+
if key.size(1) != value.size(1):
|
| 162 |
+
raise ValueError("Key and Value differ in sizes in dimension 1")
|
| 163 |
+
if query.size(2) != key.size(2):
|
| 164 |
+
raise ValueError("Query and Key differ in sizes in dimension 2")
|
| 165 |
+
|
| 166 |
+
query_mask, key_mask, query, key, value = to_contiguous([query_mask, key_mask, query, key, value])
|
| 167 |
+
|
| 168 |
+
use_cuda = query_mask.is_cuda
|
| 169 |
+
num_hash = config["num_hash"]
|
| 170 |
+
hash_code_len = config["hash_code_len"]
|
| 171 |
+
hashtable_capacity = int(2**hash_code_len)
|
| 172 |
+
|
| 173 |
+
if config["use_fast_hash"]:
|
| 174 |
+
query_hash_code, key_hash_code = lsh_cumulation.fast_hash(
|
| 175 |
+
query_mask, query, key_mask, key, num_hash, hash_code_len, use_cuda, 1
|
| 176 |
+
)
|
| 177 |
+
else:
|
| 178 |
+
query_hash_code, key_hash_code = hashing(query, key, num_hash, hash_code_len)
|
| 179 |
+
|
| 180 |
+
cumulation_value = lsh_cumulation.lsh_cumulation(
|
| 181 |
+
query_mask, query_hash_code, key_mask, key_hash_code, value, hashtable_capacity, use_cuda, 1
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
ctx.save_for_backward(query_mask, key_mask, query_hash_code, key_hash_code, query, key, value)
|
| 185 |
+
ctx.config = config
|
| 186 |
+
|
| 187 |
+
return cumulation_value
|
| 188 |
+
|
| 189 |
+
@staticmethod
|
| 190 |
+
def backward(ctx, grad):
|
| 191 |
+
grad = to_contiguous(grad)
|
| 192 |
+
|
| 193 |
+
query_mask, key_mask, query_hash_code, key_hash_code, query, key, value = ctx.saved_tensors
|
| 194 |
+
config = ctx.config
|
| 195 |
+
|
| 196 |
+
use_cuda = grad.is_cuda
|
| 197 |
+
hash_code_len = config["hash_code_len"]
|
| 198 |
+
hashtable_capacity = int(2**hash_code_len)
|
| 199 |
+
|
| 200 |
+
if config["lsh_backward"]:
|
| 201 |
+
grad_value = lsh_cumulation.lsh_cumulation(
|
| 202 |
+
key_mask, key_hash_code, query_mask, query_hash_code, grad, hashtable_capacity, use_cuda, 1
|
| 203 |
+
)
|
| 204 |
+
grad_query = lsh_cumulation.lsh_weighted_cumulation(
|
| 205 |
+
query_mask,
|
| 206 |
+
query_hash_code,
|
| 207 |
+
grad,
|
| 208 |
+
key_mask,
|
| 209 |
+
key_hash_code,
|
| 210 |
+
value,
|
| 211 |
+
(hash_code_len / 2) * key,
|
| 212 |
+
hashtable_capacity,
|
| 213 |
+
use_cuda,
|
| 214 |
+
4,
|
| 215 |
+
)
|
| 216 |
+
grad_key = lsh_cumulation.lsh_weighted_cumulation(
|
| 217 |
+
key_mask,
|
| 218 |
+
key_hash_code,
|
| 219 |
+
value,
|
| 220 |
+
query_mask,
|
| 221 |
+
query_hash_code,
|
| 222 |
+
grad,
|
| 223 |
+
(hash_code_len / 2) * query,
|
| 224 |
+
hashtable_capacity,
|
| 225 |
+
use_cuda,
|
| 226 |
+
4,
|
| 227 |
+
)
|
| 228 |
+
else:
|
| 229 |
+
expectation = (1 - torch.acos(torch.matmul(query, key.transpose(-1, -2))) / math.pi) ** hash_code_len
|
| 230 |
+
expectation = expectation * query_mask[:, :, None] * key_mask[:, None, :]
|
| 231 |
+
weighted_exp = torch.matmul(grad, value.transpose(-1, -2)) * expectation
|
| 232 |
+
grad_query = torch.matmul(weighted_exp, (hash_code_len / 2) * key)
|
| 233 |
+
grad_key = torch.matmul(weighted_exp.transpose(-1, -2), (hash_code_len / 2) * query)
|
| 234 |
+
grad_value = torch.matmul(expectation.transpose(-1, -2), grad)
|
| 235 |
+
|
| 236 |
+
return None, None, grad_query, grad_key, grad_value, None
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
# Copied from transformers.models.nystromformer.modeling_nystromformer.NystromformerEmbeddings
|
| 240 |
+
class YosoEmbeddings(nn.Module):
|
| 241 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 242 |
+
|
| 243 |
+
def __init__(self, config):
|
| 244 |
+
super().__init__()
|
| 245 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 246 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings + 2, config.hidden_size)
|
| 247 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 248 |
+
|
| 249 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 250 |
+
# any TensorFlow checkpoint file
|
| 251 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 252 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 253 |
+
|
| 254 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 255 |
+
self.register_buffer(
|
| 256 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) + 2, persistent=False
|
| 257 |
+
)
|
| 258 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 259 |
+
self.register_buffer(
|
| 260 |
+
"token_type_ids",
|
| 261 |
+
torch.zeros(self.position_ids.size(), dtype=torch.long, device=self.position_ids.device),
|
| 262 |
+
persistent=False,
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
|
| 266 |
+
if input_ids is not None:
|
| 267 |
+
input_shape = input_ids.size()
|
| 268 |
+
else:
|
| 269 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 270 |
+
|
| 271 |
+
seq_length = input_shape[1]
|
| 272 |
+
|
| 273 |
+
if position_ids is None:
|
| 274 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 275 |
+
|
| 276 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 277 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 278 |
+
# issue #5664
|
| 279 |
+
if token_type_ids is None:
|
| 280 |
+
if hasattr(self, "token_type_ids"):
|
| 281 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 282 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 283 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 284 |
+
else:
|
| 285 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 286 |
+
|
| 287 |
+
if inputs_embeds is None:
|
| 288 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 289 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 290 |
+
|
| 291 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 292 |
+
if self.position_embedding_type == "absolute":
|
| 293 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 294 |
+
embeddings += position_embeddings
|
| 295 |
+
embeddings = self.LayerNorm(embeddings)
|
| 296 |
+
embeddings = self.dropout(embeddings)
|
| 297 |
+
return embeddings
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
class YosoSelfAttention(nn.Module):
|
| 301 |
+
def __init__(self, config, position_embedding_type=None):
|
| 302 |
+
super().__init__()
|
| 303 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 304 |
+
raise ValueError(
|
| 305 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 306 |
+
f"heads ({config.num_attention_heads})"
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
self.num_attention_heads = config.num_attention_heads
|
| 310 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 311 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 312 |
+
|
| 313 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 314 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 315 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 316 |
+
|
| 317 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 318 |
+
self.position_embedding_type = (
|
| 319 |
+
position_embedding_type if position_embedding_type is not None else config.position_embedding_type
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
self.use_expectation = config.use_expectation
|
| 323 |
+
self.hash_code_len = config.hash_code_len
|
| 324 |
+
self.use_conv = config.conv_window is not None
|
| 325 |
+
self.use_fast_hash = config.use_fast_hash
|
| 326 |
+
self.num_hash = config.num_hash
|
| 327 |
+
self.lsh_backward = config.lsh_backward
|
| 328 |
+
|
| 329 |
+
self.lsh_config = {
|
| 330 |
+
"hash_code_len": self.hash_code_len,
|
| 331 |
+
"use_fast_hash": self.use_fast_hash,
|
| 332 |
+
"num_hash": self.num_hash,
|
| 333 |
+
"lsh_backward": self.lsh_backward,
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
if config.conv_window is not None:
|
| 337 |
+
self.conv = nn.Conv2d(
|
| 338 |
+
in_channels=config.num_attention_heads,
|
| 339 |
+
out_channels=config.num_attention_heads,
|
| 340 |
+
kernel_size=(config.conv_window, 1),
|
| 341 |
+
padding=(config.conv_window // 2, 0),
|
| 342 |
+
bias=False,
|
| 343 |
+
groups=config.num_attention_heads,
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
def transpose_for_scores(self, layer):
|
| 347 |
+
new_layer_shape = layer.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 348 |
+
layer = layer.view(*new_layer_shape)
|
| 349 |
+
return layer.permute(0, 2, 1, 3)
|
| 350 |
+
|
| 351 |
+
def forward(self, hidden_states, attention_mask=None, output_attentions=False):
|
| 352 |
+
mixed_query_layer = self.query(hidden_states)
|
| 353 |
+
|
| 354 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 355 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 356 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 357 |
+
|
| 358 |
+
if self.use_conv:
|
| 359 |
+
conv_value_layer = self.conv(value_layer * attention_mask[:, None, :, None])
|
| 360 |
+
|
| 361 |
+
batch_size, num_heads, seq_len, head_dim = query_layer.size()
|
| 362 |
+
|
| 363 |
+
query_layer = query_layer.reshape(batch_size * num_heads, seq_len, head_dim)
|
| 364 |
+
key_layer = key_layer.reshape(batch_size * num_heads, seq_len, head_dim)
|
| 365 |
+
value_layer = value_layer.reshape(batch_size * num_heads, seq_len, head_dim)
|
| 366 |
+
|
| 367 |
+
# revert changes made by get_extended_attention_mask
|
| 368 |
+
attention_mask = 1.0 + attention_mask / 10000.0
|
| 369 |
+
attention_mask = (
|
| 370 |
+
attention_mask.squeeze().repeat(1, num_heads, 1).reshape(batch_size * num_heads, seq_len).int()
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
# The CUDA kernels are most efficient with inputs whose size is a multiple of a GPU's warp size (32). Inputs
|
| 374 |
+
# smaller than this are padded with zeros.
|
| 375 |
+
gpu_warp_size = 32
|
| 376 |
+
|
| 377 |
+
if (not self.use_expectation) and head_dim < gpu_warp_size:
|
| 378 |
+
pad_size = batch_size * num_heads, seq_len, gpu_warp_size - head_dim
|
| 379 |
+
|
| 380 |
+
query_layer = torch.cat(
|
| 381 |
+
[
|
| 382 |
+
query_layer,
|
| 383 |
+
torch.zeros(pad_size, device=query_layer.device),
|
| 384 |
+
],
|
| 385 |
+
dim=-1,
|
| 386 |
+
)
|
| 387 |
+
key_layer = torch.cat(
|
| 388 |
+
[
|
| 389 |
+
key_layer,
|
| 390 |
+
torch.zeros(pad_size, device=key_layer.device),
|
| 391 |
+
],
|
| 392 |
+
dim=-1,
|
| 393 |
+
)
|
| 394 |
+
value_layer = torch.cat(
|
| 395 |
+
[
|
| 396 |
+
value_layer,
|
| 397 |
+
torch.zeros(pad_size, device=value_layer.device),
|
| 398 |
+
],
|
| 399 |
+
dim=-1,
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
if self.use_expectation or self.training:
|
| 403 |
+
query_layer, key_layer = normalize([query_layer, key_layer])
|
| 404 |
+
|
| 405 |
+
if self.use_expectation:
|
| 406 |
+
context_layer = YosoCumulation.apply(
|
| 407 |
+
attention_mask, attention_mask, query_layer, key_layer, value_layer, self.lsh_config
|
| 408 |
+
)
|
| 409 |
+
else:
|
| 410 |
+
context_layer = YosoLSHCumulation.apply(
|
| 411 |
+
attention_mask, attention_mask, query_layer, key_layer, value_layer, self.lsh_config
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
if (not self.use_expectation) and head_dim < gpu_warp_size:
|
| 415 |
+
context_layer = context_layer[:, :, :head_dim]
|
| 416 |
+
|
| 417 |
+
context_layer = normalize(context_layer)
|
| 418 |
+
|
| 419 |
+
context_layer = context_layer.reshape(batch_size, num_heads, seq_len, head_dim)
|
| 420 |
+
|
| 421 |
+
if self.use_conv:
|
| 422 |
+
context_layer += conv_value_layer
|
| 423 |
+
|
| 424 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 425 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 426 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
| 427 |
+
|
| 428 |
+
outputs = (context_layer, context_layer) if output_attentions else (context_layer,)
|
| 429 |
+
|
| 430 |
+
return outputs
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput
|
| 434 |
+
class YosoSelfOutput(nn.Module):
|
| 435 |
+
def __init__(self, config):
|
| 436 |
+
super().__init__()
|
| 437 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 438 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 439 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 440 |
+
|
| 441 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 442 |
+
hidden_states = self.dense(hidden_states)
|
| 443 |
+
hidden_states = self.dropout(hidden_states)
|
| 444 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 445 |
+
return hidden_states
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
class YosoAttention(nn.Module):
|
| 449 |
+
def __init__(self, config, position_embedding_type=None):
|
| 450 |
+
super().__init__()
|
| 451 |
+
self.self = YosoSelfAttention(config, position_embedding_type=position_embedding_type)
|
| 452 |
+
self.output = YosoSelfOutput(config)
|
| 453 |
+
self.pruned_heads = set()
|
| 454 |
+
|
| 455 |
+
def prune_heads(self, heads):
|
| 456 |
+
if len(heads) == 0:
|
| 457 |
+
return
|
| 458 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 459 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
# Prune linear layers
|
| 463 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 464 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 465 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 466 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 467 |
+
|
| 468 |
+
# Update hyper params and store pruned heads
|
| 469 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 470 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 471 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 472 |
+
|
| 473 |
+
def forward(self, hidden_states, attention_mask=None, output_attentions=False):
|
| 474 |
+
self_outputs = self.self(hidden_states, attention_mask, output_attentions)
|
| 475 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 476 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 477 |
+
return outputs
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate
|
| 481 |
+
class YosoIntermediate(nn.Module):
|
| 482 |
+
def __init__(self, config):
|
| 483 |
+
super().__init__()
|
| 484 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 485 |
+
if isinstance(config.hidden_act, str):
|
| 486 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 487 |
+
else:
|
| 488 |
+
self.intermediate_act_fn = config.hidden_act
|
| 489 |
+
|
| 490 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 491 |
+
hidden_states = self.dense(hidden_states)
|
| 492 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 493 |
+
return hidden_states
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput
|
| 497 |
+
class YosoOutput(nn.Module):
|
| 498 |
+
def __init__(self, config):
|
| 499 |
+
super().__init__()
|
| 500 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 501 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 502 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 503 |
+
|
| 504 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 505 |
+
hidden_states = self.dense(hidden_states)
|
| 506 |
+
hidden_states = self.dropout(hidden_states)
|
| 507 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 508 |
+
return hidden_states
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
class YosoLayer(nn.Module):
|
| 512 |
+
def __init__(self, config):
|
| 513 |
+
super().__init__()
|
| 514 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 515 |
+
self.seq_len_dim = 1
|
| 516 |
+
self.attention = YosoAttention(config)
|
| 517 |
+
self.add_cross_attention = config.add_cross_attention
|
| 518 |
+
self.intermediate = YosoIntermediate(config)
|
| 519 |
+
self.output = YosoOutput(config)
|
| 520 |
+
|
| 521 |
+
def forward(self, hidden_states, attention_mask=None, output_attentions=False):
|
| 522 |
+
self_attention_outputs = self.attention(hidden_states, attention_mask, output_attentions=output_attentions)
|
| 523 |
+
attention_output = self_attention_outputs[0]
|
| 524 |
+
|
| 525 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 526 |
+
|
| 527 |
+
layer_output = apply_chunking_to_forward(
|
| 528 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 529 |
+
)
|
| 530 |
+
outputs = (layer_output,) + outputs
|
| 531 |
+
|
| 532 |
+
return outputs
|
| 533 |
+
|
| 534 |
+
def feed_forward_chunk(self, attention_output):
|
| 535 |
+
intermediate_output = self.intermediate(attention_output)
|
| 536 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 537 |
+
return layer_output
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
class YosoEncoder(nn.Module):
|
| 541 |
+
def __init__(self, config):
|
| 542 |
+
super().__init__()
|
| 543 |
+
self.config = config
|
| 544 |
+
self.layer = nn.ModuleList([YosoLayer(config) for _ in range(config.num_hidden_layers)])
|
| 545 |
+
self.gradient_checkpointing = False
|
| 546 |
+
|
| 547 |
+
def forward(
|
| 548 |
+
self,
|
| 549 |
+
hidden_states,
|
| 550 |
+
attention_mask=None,
|
| 551 |
+
head_mask=None,
|
| 552 |
+
output_attentions=False,
|
| 553 |
+
output_hidden_states=False,
|
| 554 |
+
return_dict=True,
|
| 555 |
+
):
|
| 556 |
+
all_hidden_states = () if output_hidden_states else None
|
| 557 |
+
all_self_attentions = () if output_attentions else None
|
| 558 |
+
|
| 559 |
+
for i, layer_module in enumerate(self.layer):
|
| 560 |
+
if output_hidden_states:
|
| 561 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 562 |
+
|
| 563 |
+
if self.gradient_checkpointing and self.training:
|
| 564 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 565 |
+
layer_module.__call__,
|
| 566 |
+
hidden_states,
|
| 567 |
+
attention_mask,
|
| 568 |
+
output_attentions,
|
| 569 |
+
)
|
| 570 |
+
else:
|
| 571 |
+
layer_outputs = layer_module(hidden_states, attention_mask, output_attentions)
|
| 572 |
+
|
| 573 |
+
hidden_states = layer_outputs[0]
|
| 574 |
+
if output_attentions:
|
| 575 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 576 |
+
|
| 577 |
+
if output_hidden_states:
|
| 578 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 579 |
+
|
| 580 |
+
if not return_dict:
|
| 581 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 582 |
+
return BaseModelOutputWithCrossAttentions(
|
| 583 |
+
last_hidden_state=hidden_states,
|
| 584 |
+
hidden_states=all_hidden_states,
|
| 585 |
+
attentions=all_self_attentions,
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform
|
| 590 |
+
class YosoPredictionHeadTransform(nn.Module):
|
| 591 |
+
def __init__(self, config):
|
| 592 |
+
super().__init__()
|
| 593 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 594 |
+
if isinstance(config.hidden_act, str):
|
| 595 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 596 |
+
else:
|
| 597 |
+
self.transform_act_fn = config.hidden_act
|
| 598 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 599 |
+
|
| 600 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 601 |
+
hidden_states = self.dense(hidden_states)
|
| 602 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 603 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 604 |
+
return hidden_states
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Yoso
|
| 608 |
+
class YosoLMPredictionHead(nn.Module):
|
| 609 |
+
def __init__(self, config):
|
| 610 |
+
super().__init__()
|
| 611 |
+
self.transform = YosoPredictionHeadTransform(config)
|
| 612 |
+
|
| 613 |
+
# The output weights are the same as the input embeddings, but there is
|
| 614 |
+
# an output-only bias for each token.
|
| 615 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 616 |
+
|
| 617 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 618 |
+
|
| 619 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
| 620 |
+
self.decoder.bias = self.bias
|
| 621 |
+
|
| 622 |
+
def forward(self, hidden_states):
|
| 623 |
+
hidden_states = self.transform(hidden_states)
|
| 624 |
+
hidden_states = self.decoder(hidden_states)
|
| 625 |
+
return hidden_states
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Yoso
|
| 629 |
+
class YosoOnlyMLMHead(nn.Module):
|
| 630 |
+
def __init__(self, config):
|
| 631 |
+
super().__init__()
|
| 632 |
+
self.predictions = YosoLMPredictionHead(config)
|
| 633 |
+
|
| 634 |
+
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
|
| 635 |
+
prediction_scores = self.predictions(sequence_output)
|
| 636 |
+
return prediction_scores
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
class YosoPreTrainedModel(PreTrainedModel):
|
| 640 |
+
"""
|
| 641 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 642 |
+
models.
|
| 643 |
+
"""
|
| 644 |
+
|
| 645 |
+
config_class = YosoConfig
|
| 646 |
+
base_model_prefix = "yoso"
|
| 647 |
+
supports_gradient_checkpointing = True
|
| 648 |
+
|
| 649 |
+
def _init_weights(self, module):
|
| 650 |
+
"""Initialize the weights"""
|
| 651 |
+
if isinstance(module, nn.Linear):
|
| 652 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 653 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 654 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 655 |
+
if module.bias is not None:
|
| 656 |
+
module.bias.data.zero_()
|
| 657 |
+
elif isinstance(module, nn.Embedding):
|
| 658 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 659 |
+
if module.padding_idx is not None:
|
| 660 |
+
module.weight.data[module.padding_idx].zero_()
|
| 661 |
+
elif isinstance(module, nn.LayerNorm):
|
| 662 |
+
module.bias.data.zero_()
|
| 663 |
+
module.weight.data.fill_(1.0)
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
YOSO_START_DOCSTRING = r"""
|
| 667 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
|
| 668 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 669 |
+
behavior.
|
| 670 |
+
|
| 671 |
+
Parameters:
|
| 672 |
+
config ([`YosoConfig`]): Model configuration class with all the parameters of the model.
|
| 673 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 674 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 675 |
+
"""
|
| 676 |
+
|
| 677 |
+
YOSO_INPUTS_DOCSTRING = r"""
|
| 678 |
+
Args:
|
| 679 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 680 |
+
Indices of input sequence tokens in the vocabulary.
|
| 681 |
+
|
| 682 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 683 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 684 |
+
|
| 685 |
+
[What are input IDs?](../glossary#input-ids)
|
| 686 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
| 687 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 688 |
+
|
| 689 |
+
- 1 for tokens that are **not masked**,
|
| 690 |
+
- 0 for tokens that are **masked**.
|
| 691 |
+
|
| 692 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 693 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 694 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 695 |
+
1]`:
|
| 696 |
+
|
| 697 |
+
- 0 corresponds to a *sentence A* token,
|
| 698 |
+
- 1 corresponds to a *sentence B* token.
|
| 699 |
+
|
| 700 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 701 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 702 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 703 |
+
config.max_position_embeddings - 1]`.
|
| 704 |
+
|
| 705 |
+
[What are position IDs?](../glossary#position-ids)
|
| 706 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 707 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 708 |
+
|
| 709 |
+
- 1 indicates the head is **not masked**,
|
| 710 |
+
- 0 indicates the head is **masked**.
|
| 711 |
+
|
| 712 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 713 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 714 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
| 715 |
+
model's internal embedding lookup matrix.
|
| 716 |
+
output_attentions (`bool`, *optional*):
|
| 717 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 718 |
+
tensors for more detail.
|
| 719 |
+
output_hidden_states (`bool`, *optional*):
|
| 720 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 721 |
+
more detail.
|
| 722 |
+
return_dict (`bool`, *optional*):
|
| 723 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 724 |
+
"""
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
@add_start_docstrings(
|
| 728 |
+
"The bare YOSO Model transformer outputting raw hidden-states without any specific head on top.",
|
| 729 |
+
YOSO_START_DOCSTRING,
|
| 730 |
+
)
|
| 731 |
+
class YosoModel(YosoPreTrainedModel):
|
| 732 |
+
def __init__(self, config):
|
| 733 |
+
super().__init__(config)
|
| 734 |
+
self.config = config
|
| 735 |
+
|
| 736 |
+
self.embeddings = YosoEmbeddings(config)
|
| 737 |
+
self.encoder = YosoEncoder(config)
|
| 738 |
+
|
| 739 |
+
# Initialize weights and apply final processing
|
| 740 |
+
self.post_init()
|
| 741 |
+
|
| 742 |
+
def get_input_embeddings(self):
|
| 743 |
+
return self.embeddings.word_embeddings
|
| 744 |
+
|
| 745 |
+
def set_input_embeddings(self, value):
|
| 746 |
+
self.embeddings.word_embeddings = value
|
| 747 |
+
|
| 748 |
+
def _prune_heads(self, heads_to_prune):
|
| 749 |
+
"""
|
| 750 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 751 |
+
class PreTrainedModel
|
| 752 |
+
"""
|
| 753 |
+
for layer, heads in heads_to_prune.items():
|
| 754 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 755 |
+
|
| 756 |
+
@add_start_docstrings_to_model_forward(YOSO_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 757 |
+
@add_code_sample_docstrings(
|
| 758 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 759 |
+
output_type=BaseModelOutputWithCrossAttentions,
|
| 760 |
+
config_class=_CONFIG_FOR_DOC,
|
| 761 |
+
)
|
| 762 |
+
def forward(
|
| 763 |
+
self,
|
| 764 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 765 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 766 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 767 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 768 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 769 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 770 |
+
output_attentions: Optional[bool] = None,
|
| 771 |
+
output_hidden_states: Optional[bool] = None,
|
| 772 |
+
return_dict: Optional[bool] = None,
|
| 773 |
+
) -> Union[Tuple, BaseModelOutputWithCrossAttentions]:
|
| 774 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 775 |
+
output_hidden_states = (
|
| 776 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 777 |
+
)
|
| 778 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 779 |
+
|
| 780 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 781 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 782 |
+
elif input_ids is not None:
|
| 783 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 784 |
+
input_shape = input_ids.size()
|
| 785 |
+
elif inputs_embeds is not None:
|
| 786 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 787 |
+
else:
|
| 788 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 789 |
+
|
| 790 |
+
batch_size, seq_length = input_shape
|
| 791 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 792 |
+
|
| 793 |
+
if attention_mask is None:
|
| 794 |
+
attention_mask = torch.ones(((batch_size, seq_length)), device=device)
|
| 795 |
+
|
| 796 |
+
if token_type_ids is None:
|
| 797 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 798 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 799 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 800 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 801 |
+
else:
|
| 802 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 803 |
+
|
| 804 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 805 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 806 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 807 |
+
|
| 808 |
+
# Prepare head mask if needed
|
| 809 |
+
# 1.0 in head_mask indicate we keep the head
|
| 810 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 811 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 812 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 813 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 814 |
+
|
| 815 |
+
embedding_output = self.embeddings(
|
| 816 |
+
input_ids=input_ids,
|
| 817 |
+
position_ids=position_ids,
|
| 818 |
+
token_type_ids=token_type_ids,
|
| 819 |
+
inputs_embeds=inputs_embeds,
|
| 820 |
+
)
|
| 821 |
+
encoder_outputs = self.encoder(
|
| 822 |
+
embedding_output,
|
| 823 |
+
attention_mask=extended_attention_mask,
|
| 824 |
+
head_mask=head_mask,
|
| 825 |
+
output_attentions=output_attentions,
|
| 826 |
+
output_hidden_states=output_hidden_states,
|
| 827 |
+
return_dict=return_dict,
|
| 828 |
+
)
|
| 829 |
+
sequence_output = encoder_outputs[0]
|
| 830 |
+
|
| 831 |
+
if not return_dict:
|
| 832 |
+
return (sequence_output,) + encoder_outputs[1:]
|
| 833 |
+
|
| 834 |
+
return BaseModelOutputWithCrossAttentions(
|
| 835 |
+
last_hidden_state=sequence_output,
|
| 836 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 837 |
+
attentions=encoder_outputs.attentions,
|
| 838 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
@add_start_docstrings("""YOSO Model with a `language modeling` head on top.""", YOSO_START_DOCSTRING)
|
| 843 |
+
class YosoForMaskedLM(YosoPreTrainedModel):
|
| 844 |
+
_tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
|
| 845 |
+
|
| 846 |
+
def __init__(self, config):
|
| 847 |
+
super().__init__(config)
|
| 848 |
+
|
| 849 |
+
self.yoso = YosoModel(config)
|
| 850 |
+
self.cls = YosoOnlyMLMHead(config)
|
| 851 |
+
|
| 852 |
+
# Initialize weights and apply final processing
|
| 853 |
+
self.post_init()
|
| 854 |
+
|
| 855 |
+
def get_output_embeddings(self):
|
| 856 |
+
return self.cls.predictions.decoder
|
| 857 |
+
|
| 858 |
+
def set_output_embeddings(self, new_embeddings):
|
| 859 |
+
self.cls.predictions.decoder = new_embeddings
|
| 860 |
+
|
| 861 |
+
@add_start_docstrings_to_model_forward(YOSO_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 862 |
+
@add_code_sample_docstrings(
|
| 863 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 864 |
+
output_type=MaskedLMOutput,
|
| 865 |
+
config_class=_CONFIG_FOR_DOC,
|
| 866 |
+
)
|
| 867 |
+
def forward(
|
| 868 |
+
self,
|
| 869 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 870 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 871 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 872 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 873 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 874 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 875 |
+
labels: Optional[torch.Tensor] = None,
|
| 876 |
+
output_attentions: Optional[bool] = None,
|
| 877 |
+
output_hidden_states: Optional[bool] = None,
|
| 878 |
+
return_dict: Optional[bool] = None,
|
| 879 |
+
) -> Union[Tuple, MaskedLMOutput]:
|
| 880 |
+
r"""
|
| 881 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 882 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 883 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 884 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 885 |
+
"""
|
| 886 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 887 |
+
|
| 888 |
+
outputs = self.yoso(
|
| 889 |
+
input_ids,
|
| 890 |
+
attention_mask=attention_mask,
|
| 891 |
+
token_type_ids=token_type_ids,
|
| 892 |
+
position_ids=position_ids,
|
| 893 |
+
head_mask=head_mask,
|
| 894 |
+
inputs_embeds=inputs_embeds,
|
| 895 |
+
output_attentions=output_attentions,
|
| 896 |
+
output_hidden_states=output_hidden_states,
|
| 897 |
+
return_dict=return_dict,
|
| 898 |
+
)
|
| 899 |
+
|
| 900 |
+
sequence_output = outputs[0]
|
| 901 |
+
prediction_scores = self.cls(sequence_output)
|
| 902 |
+
|
| 903 |
+
masked_lm_loss = None
|
| 904 |
+
if labels is not None:
|
| 905 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
| 906 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 907 |
+
|
| 908 |
+
if not return_dict:
|
| 909 |
+
output = (prediction_scores,) + outputs[1:]
|
| 910 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 911 |
+
|
| 912 |
+
return MaskedLMOutput(
|
| 913 |
+
loss=masked_lm_loss,
|
| 914 |
+
logits=prediction_scores,
|
| 915 |
+
hidden_states=outputs.hidden_states,
|
| 916 |
+
attentions=outputs.attentions,
|
| 917 |
+
)
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
class YosoClassificationHead(nn.Module):
|
| 921 |
+
"""Head for sentence-level classification tasks."""
|
| 922 |
+
|
| 923 |
+
def __init__(self, config):
|
| 924 |
+
super().__init__()
|
| 925 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 926 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 927 |
+
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
|
| 928 |
+
|
| 929 |
+
self.config = config
|
| 930 |
+
|
| 931 |
+
def forward(self, features, **kwargs):
|
| 932 |
+
x = features[:, 0, :] # take <s> token (equiv. to [CLS])
|
| 933 |
+
x = self.dropout(x)
|
| 934 |
+
x = self.dense(x)
|
| 935 |
+
x = ACT2FN[self.config.hidden_act](x)
|
| 936 |
+
x = self.dropout(x)
|
| 937 |
+
x = self.out_proj(x)
|
| 938 |
+
return x
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
@add_start_docstrings(
|
| 942 |
+
"""YOSO Model transformer with a sequence classification/regression head on top (a linear layer on top of
|
| 943 |
+
the pooled output) e.g. for GLUE tasks.""",
|
| 944 |
+
YOSO_START_DOCSTRING,
|
| 945 |
+
)
|
| 946 |
+
class YosoForSequenceClassification(YosoPreTrainedModel):
|
| 947 |
+
def __init__(self, config):
|
| 948 |
+
super().__init__(config)
|
| 949 |
+
self.num_labels = config.num_labels
|
| 950 |
+
self.yoso = YosoModel(config)
|
| 951 |
+
self.classifier = YosoClassificationHead(config)
|
| 952 |
+
|
| 953 |
+
# Initialize weights and apply final processing
|
| 954 |
+
self.post_init()
|
| 955 |
+
|
| 956 |
+
@add_start_docstrings_to_model_forward(YOSO_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 957 |
+
@add_code_sample_docstrings(
|
| 958 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 959 |
+
output_type=SequenceClassifierOutput,
|
| 960 |
+
config_class=_CONFIG_FOR_DOC,
|
| 961 |
+
)
|
| 962 |
+
def forward(
|
| 963 |
+
self,
|
| 964 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 965 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 966 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 967 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 968 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 969 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 970 |
+
labels: Optional[torch.Tensor] = None,
|
| 971 |
+
output_attentions: Optional[bool] = None,
|
| 972 |
+
output_hidden_states: Optional[bool] = None,
|
| 973 |
+
return_dict: Optional[bool] = None,
|
| 974 |
+
) -> Union[Tuple, SequenceClassifierOutput]:
|
| 975 |
+
r"""
|
| 976 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 977 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 978 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 979 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 980 |
+
"""
|
| 981 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 982 |
+
|
| 983 |
+
outputs = self.yoso(
|
| 984 |
+
input_ids,
|
| 985 |
+
attention_mask=attention_mask,
|
| 986 |
+
token_type_ids=token_type_ids,
|
| 987 |
+
position_ids=position_ids,
|
| 988 |
+
head_mask=head_mask,
|
| 989 |
+
inputs_embeds=inputs_embeds,
|
| 990 |
+
output_attentions=output_attentions,
|
| 991 |
+
output_hidden_states=output_hidden_states,
|
| 992 |
+
return_dict=return_dict,
|
| 993 |
+
)
|
| 994 |
+
|
| 995 |
+
sequence_output = outputs[0]
|
| 996 |
+
logits = self.classifier(sequence_output)
|
| 997 |
+
|
| 998 |
+
loss = None
|
| 999 |
+
if labels is not None:
|
| 1000 |
+
if self.config.problem_type is None:
|
| 1001 |
+
if self.num_labels == 1:
|
| 1002 |
+
self.config.problem_type = "regression"
|
| 1003 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1004 |
+
self.config.problem_type = "single_label_classification"
|
| 1005 |
+
else:
|
| 1006 |
+
self.config.problem_type = "multi_label_classification"
|
| 1007 |
+
|
| 1008 |
+
if self.config.problem_type == "regression":
|
| 1009 |
+
loss_fct = MSELoss()
|
| 1010 |
+
if self.num_labels == 1:
|
| 1011 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1012 |
+
else:
|
| 1013 |
+
loss = loss_fct(logits, labels)
|
| 1014 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1015 |
+
loss_fct = CrossEntropyLoss()
|
| 1016 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1017 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1018 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1019 |
+
loss = loss_fct(logits, labels)
|
| 1020 |
+
if not return_dict:
|
| 1021 |
+
output = (logits,) + outputs[1:]
|
| 1022 |
+
return ((loss,) + output) if loss is not None else output
|
| 1023 |
+
|
| 1024 |
+
return SequenceClassifierOutput(
|
| 1025 |
+
loss=loss,
|
| 1026 |
+
logits=logits,
|
| 1027 |
+
hidden_states=outputs.hidden_states,
|
| 1028 |
+
attentions=outputs.attentions,
|
| 1029 |
+
)
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
@add_start_docstrings(
|
| 1033 |
+
"""YOSO Model with a multiple choice classification head on top (a linear layer on top of
|
| 1034 |
+
the pooled output and a softmax) e.g. for RocStories/SWAG tasks.""",
|
| 1035 |
+
YOSO_START_DOCSTRING,
|
| 1036 |
+
)
|
| 1037 |
+
class YosoForMultipleChoice(YosoPreTrainedModel):
|
| 1038 |
+
def __init__(self, config):
|
| 1039 |
+
super().__init__(config)
|
| 1040 |
+
|
| 1041 |
+
self.yoso = YosoModel(config)
|
| 1042 |
+
self.pre_classifier = nn.Linear(config.hidden_size, config.hidden_size)
|
| 1043 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 1044 |
+
|
| 1045 |
+
# Initialize weights and apply final processing
|
| 1046 |
+
self.post_init()
|
| 1047 |
+
|
| 1048 |
+
@add_start_docstrings_to_model_forward(YOSO_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
|
| 1049 |
+
@add_code_sample_docstrings(
|
| 1050 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1051 |
+
output_type=MultipleChoiceModelOutput,
|
| 1052 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1053 |
+
)
|
| 1054 |
+
def forward(
|
| 1055 |
+
self,
|
| 1056 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1057 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1058 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1059 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1060 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1061 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1062 |
+
labels: Optional[torch.Tensor] = None,
|
| 1063 |
+
output_attentions: Optional[bool] = None,
|
| 1064 |
+
output_hidden_states: Optional[bool] = None,
|
| 1065 |
+
return_dict: Optional[bool] = None,
|
| 1066 |
+
) -> Union[Tuple, MultipleChoiceModelOutput]:
|
| 1067 |
+
r"""
|
| 1068 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1069 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 1070 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
| 1071 |
+
`input_ids` above)
|
| 1072 |
+
"""
|
| 1073 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1074 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 1075 |
+
|
| 1076 |
+
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 1077 |
+
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 1078 |
+
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
| 1079 |
+
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
| 1080 |
+
inputs_embeds = (
|
| 1081 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 1082 |
+
if inputs_embeds is not None
|
| 1083 |
+
else None
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
outputs = self.yoso(
|
| 1087 |
+
input_ids,
|
| 1088 |
+
attention_mask=attention_mask,
|
| 1089 |
+
token_type_ids=token_type_ids,
|
| 1090 |
+
position_ids=position_ids,
|
| 1091 |
+
head_mask=head_mask,
|
| 1092 |
+
inputs_embeds=inputs_embeds,
|
| 1093 |
+
output_attentions=output_attentions,
|
| 1094 |
+
output_hidden_states=output_hidden_states,
|
| 1095 |
+
return_dict=return_dict,
|
| 1096 |
+
)
|
| 1097 |
+
|
| 1098 |
+
hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
|
| 1099 |
+
pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
|
| 1100 |
+
pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
|
| 1101 |
+
pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
|
| 1102 |
+
logits = self.classifier(pooled_output)
|
| 1103 |
+
|
| 1104 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 1105 |
+
|
| 1106 |
+
loss = None
|
| 1107 |
+
if labels is not None:
|
| 1108 |
+
loss_fct = CrossEntropyLoss()
|
| 1109 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1110 |
+
|
| 1111 |
+
if not return_dict:
|
| 1112 |
+
output = (reshaped_logits,) + outputs[1:]
|
| 1113 |
+
return ((loss,) + output) if loss is not None else output
|
| 1114 |
+
|
| 1115 |
+
return MultipleChoiceModelOutput(
|
| 1116 |
+
loss=loss,
|
| 1117 |
+
logits=reshaped_logits,
|
| 1118 |
+
hidden_states=outputs.hidden_states,
|
| 1119 |
+
attentions=outputs.attentions,
|
| 1120 |
+
)
|
| 1121 |
+
|
| 1122 |
+
|
| 1123 |
+
@add_start_docstrings(
|
| 1124 |
+
"""YOSO Model with a token classification head on top (a linear layer on top of
|
| 1125 |
+
the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.""",
|
| 1126 |
+
YOSO_START_DOCSTRING,
|
| 1127 |
+
)
|
| 1128 |
+
class YosoForTokenClassification(YosoPreTrainedModel):
|
| 1129 |
+
def __init__(self, config):
|
| 1130 |
+
super().__init__(config)
|
| 1131 |
+
self.num_labels = config.num_labels
|
| 1132 |
+
|
| 1133 |
+
self.yoso = YosoModel(config)
|
| 1134 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1135 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1136 |
+
|
| 1137 |
+
# Initialize weights and apply final processing
|
| 1138 |
+
self.post_init()
|
| 1139 |
+
|
| 1140 |
+
@add_start_docstrings_to_model_forward(YOSO_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1141 |
+
@add_code_sample_docstrings(
|
| 1142 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1143 |
+
output_type=TokenClassifierOutput,
|
| 1144 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1145 |
+
)
|
| 1146 |
+
def forward(
|
| 1147 |
+
self,
|
| 1148 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1149 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1150 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1151 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1152 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1153 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1154 |
+
labels: Optional[torch.Tensor] = None,
|
| 1155 |
+
output_attentions: Optional[bool] = None,
|
| 1156 |
+
output_hidden_states: Optional[bool] = None,
|
| 1157 |
+
return_dict: Optional[bool] = None,
|
| 1158 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
| 1159 |
+
r"""
|
| 1160 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1161 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1162 |
+
"""
|
| 1163 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1164 |
+
|
| 1165 |
+
outputs = self.yoso(
|
| 1166 |
+
input_ids,
|
| 1167 |
+
attention_mask=attention_mask,
|
| 1168 |
+
token_type_ids=token_type_ids,
|
| 1169 |
+
position_ids=position_ids,
|
| 1170 |
+
head_mask=head_mask,
|
| 1171 |
+
inputs_embeds=inputs_embeds,
|
| 1172 |
+
output_attentions=output_attentions,
|
| 1173 |
+
output_hidden_states=output_hidden_states,
|
| 1174 |
+
return_dict=return_dict,
|
| 1175 |
+
)
|
| 1176 |
+
|
| 1177 |
+
sequence_output = outputs[0]
|
| 1178 |
+
|
| 1179 |
+
sequence_output = self.dropout(sequence_output)
|
| 1180 |
+
logits = self.classifier(sequence_output)
|
| 1181 |
+
|
| 1182 |
+
loss = None
|
| 1183 |
+
if labels is not None:
|
| 1184 |
+
loss_fct = CrossEntropyLoss()
|
| 1185 |
+
# Only keep active parts of the loss
|
| 1186 |
+
if attention_mask is not None:
|
| 1187 |
+
active_loss = attention_mask.view(-1) == 1
|
| 1188 |
+
active_logits = logits.view(-1, self.num_labels)
|
| 1189 |
+
active_labels = torch.where(
|
| 1190 |
+
active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
|
| 1191 |
+
)
|
| 1192 |
+
loss = loss_fct(active_logits, active_labels)
|
| 1193 |
+
else:
|
| 1194 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1195 |
+
|
| 1196 |
+
if not return_dict:
|
| 1197 |
+
output = (logits,) + outputs[1:]
|
| 1198 |
+
return ((loss,) + output) if loss is not None else output
|
| 1199 |
+
|
| 1200 |
+
return TokenClassifierOutput(
|
| 1201 |
+
loss=loss,
|
| 1202 |
+
logits=logits,
|
| 1203 |
+
hidden_states=outputs.hidden_states,
|
| 1204 |
+
attentions=outputs.attentions,
|
| 1205 |
+
)
|
| 1206 |
+
|
| 1207 |
+
|
| 1208 |
+
@add_start_docstrings(
|
| 1209 |
+
"""YOSO Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1210 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).""",
|
| 1211 |
+
YOSO_START_DOCSTRING,
|
| 1212 |
+
)
|
| 1213 |
+
class YosoForQuestionAnswering(YosoPreTrainedModel):
|
| 1214 |
+
def __init__(self, config):
|
| 1215 |
+
super().__init__(config)
|
| 1216 |
+
|
| 1217 |
+
config.num_labels = 2
|
| 1218 |
+
self.num_labels = config.num_labels
|
| 1219 |
+
|
| 1220 |
+
self.yoso = YosoModel(config)
|
| 1221 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1222 |
+
|
| 1223 |
+
# Initialize weights and apply final processing
|
| 1224 |
+
self.post_init()
|
| 1225 |
+
|
| 1226 |
+
@add_start_docstrings_to_model_forward(YOSO_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1227 |
+
@add_code_sample_docstrings(
|
| 1228 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1229 |
+
output_type=QuestionAnsweringModelOutput,
|
| 1230 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1231 |
+
)
|
| 1232 |
+
def forward(
|
| 1233 |
+
self,
|
| 1234 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1235 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1236 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1237 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1238 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1239 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1240 |
+
start_positions: Optional[torch.Tensor] = None,
|
| 1241 |
+
end_positions: Optional[torch.Tensor] = None,
|
| 1242 |
+
output_attentions: Optional[bool] = None,
|
| 1243 |
+
output_hidden_states: Optional[bool] = None,
|
| 1244 |
+
return_dict: Optional[bool] = None,
|
| 1245 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
| 1246 |
+
r"""
|
| 1247 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1248 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1249 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1250 |
+
are not taken into account for computing the loss.
|
| 1251 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1252 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1253 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1254 |
+
are not taken into account for computing the loss.
|
| 1255 |
+
"""
|
| 1256 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1257 |
+
|
| 1258 |
+
outputs = self.yoso(
|
| 1259 |
+
input_ids,
|
| 1260 |
+
attention_mask=attention_mask,
|
| 1261 |
+
token_type_ids=token_type_ids,
|
| 1262 |
+
position_ids=position_ids,
|
| 1263 |
+
head_mask=head_mask,
|
| 1264 |
+
inputs_embeds=inputs_embeds,
|
| 1265 |
+
output_attentions=output_attentions,
|
| 1266 |
+
output_hidden_states=output_hidden_states,
|
| 1267 |
+
return_dict=return_dict,
|
| 1268 |
+
)
|
| 1269 |
+
|
| 1270 |
+
sequence_output = outputs[0]
|
| 1271 |
+
|
| 1272 |
+
logits = self.qa_outputs(sequence_output)
|
| 1273 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1274 |
+
start_logits = start_logits.squeeze(-1)
|
| 1275 |
+
end_logits = end_logits.squeeze(-1)
|
| 1276 |
+
|
| 1277 |
+
total_loss = None
|
| 1278 |
+
if start_positions is not None and end_positions is not None:
|
| 1279 |
+
# If we are on multi-GPU, split add a dimension
|
| 1280 |
+
if len(start_positions.size()) > 1:
|
| 1281 |
+
start_positions = start_positions.squeeze(-1)
|
| 1282 |
+
if len(end_positions.size()) > 1:
|
| 1283 |
+
end_positions = end_positions.squeeze(-1)
|
| 1284 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1285 |
+
ignored_index = start_logits.size(1)
|
| 1286 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1287 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1288 |
+
|
| 1289 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1290 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1291 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1292 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1293 |
+
|
| 1294 |
+
if not return_dict:
|
| 1295 |
+
output = (start_logits, end_logits) + outputs[1:]
|
| 1296 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1297 |
+
|
| 1298 |
+
return QuestionAnsweringModelOutput(
|
| 1299 |
+
loss=total_loss,
|
| 1300 |
+
start_logits=start_logits,
|
| 1301 |
+
end_logits=end_logits,
|
| 1302 |
+
hidden_states=outputs.hidden_states,
|
| 1303 |
+
attentions=outputs.attentions,
|
| 1304 |
+
)
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/designspaceLib/__init__.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__main__.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.ttLib import TTFont
|
| 2 |
+
from fontTools.feaLib.builder import addOpenTypeFeatures, Builder
|
| 3 |
+
from fontTools.feaLib.error import FeatureLibError
|
| 4 |
+
from fontTools import configLogger
|
| 5 |
+
from fontTools.misc.cliTools import makeOutputFileName
|
| 6 |
+
import sys
|
| 7 |
+
import argparse
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
log = logging.getLogger("fontTools.feaLib")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main(args=None):
|
| 15 |
+
"""Add features from a feature file (.fea) into an OTF font"""
|
| 16 |
+
parser = argparse.ArgumentParser(
|
| 17 |
+
description="Use fontTools to compile OpenType feature files (*.fea)."
|
| 18 |
+
)
|
| 19 |
+
parser.add_argument(
|
| 20 |
+
"input_fea", metavar="FEATURES", help="Path to the feature file"
|
| 21 |
+
)
|
| 22 |
+
parser.add_argument(
|
| 23 |
+
"input_font", metavar="INPUT_FONT", help="Path to the input font"
|
| 24 |
+
)
|
| 25 |
+
parser.add_argument(
|
| 26 |
+
"-o",
|
| 27 |
+
"--output",
|
| 28 |
+
dest="output_font",
|
| 29 |
+
metavar="OUTPUT_FONT",
|
| 30 |
+
help="Path to the output font.",
|
| 31 |
+
)
|
| 32 |
+
parser.add_argument(
|
| 33 |
+
"-t",
|
| 34 |
+
"--tables",
|
| 35 |
+
metavar="TABLE_TAG",
|
| 36 |
+
choices=Builder.supportedTables,
|
| 37 |
+
nargs="+",
|
| 38 |
+
help="Specify the table(s) to be built.",
|
| 39 |
+
)
|
| 40 |
+
parser.add_argument(
|
| 41 |
+
"-d",
|
| 42 |
+
"--debug",
|
| 43 |
+
action="store_true",
|
| 44 |
+
help="Add source-level debugging information to font.",
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"-v",
|
| 48 |
+
"--verbose",
|
| 49 |
+
help="Increase the logger verbosity. Multiple -v " "options are allowed.",
|
| 50 |
+
action="count",
|
| 51 |
+
default=0,
|
| 52 |
+
)
|
| 53 |
+
parser.add_argument(
|
| 54 |
+
"--traceback", help="show traceback for exceptions.", action="store_true"
|
| 55 |
+
)
|
| 56 |
+
options = parser.parse_args(args)
|
| 57 |
+
|
| 58 |
+
levels = ["WARNING", "INFO", "DEBUG"]
|
| 59 |
+
configLogger(level=levels[min(len(levels) - 1, options.verbose)])
|
| 60 |
+
|
| 61 |
+
output_font = options.output_font or makeOutputFileName(options.input_font)
|
| 62 |
+
log.info("Compiling features to '%s'" % (output_font))
|
| 63 |
+
|
| 64 |
+
font = TTFont(options.input_font)
|
| 65 |
+
try:
|
| 66 |
+
addOpenTypeFeatures(
|
| 67 |
+
font, options.input_fea, tables=options.tables, debug=options.debug
|
| 68 |
+
)
|
| 69 |
+
except FeatureLibError as e:
|
| 70 |
+
if options.traceback:
|
| 71 |
+
raise
|
| 72 |
+
log.error(e)
|
| 73 |
+
sys.exit(1)
|
| 74 |
+
font.save(output_font)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if __name__ == "__main__":
|
| 78 |
+
sys.exit(main())
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (256 Bytes). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/__main__.cpython-310.pyc
ADDED
|
Binary file (2.17 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/ast.cpython-310.pyc
ADDED
|
Binary file (75.9 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/error.cpython-310.pyc
ADDED
|
Binary file (1.11 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/lexer.cpython-310.pyc
ADDED
|
Binary file (8.33 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/location.cpython-310.pyc
ADDED
|
Binary file (671 Bytes). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/lookupDebugInfo.cpython-310.pyc
ADDED
|
Binary file (670 Bytes). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/parser.cpython-310.pyc
ADDED
|
Binary file (54.7 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__pycache__/variableScalar.cpython-310.pyc
ADDED
|
Binary file (5.36 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/error.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class FeatureLibError(Exception):
|
| 2 |
+
def __init__(self, message, location):
|
| 3 |
+
Exception.__init__(self, message)
|
| 4 |
+
self.location = location
|
| 5 |
+
|
| 6 |
+
def __str__(self):
|
| 7 |
+
message = Exception.__str__(self)
|
| 8 |
+
if self.location:
|
| 9 |
+
return f"{self.location}: {message}"
|
| 10 |
+
else:
|
| 11 |
+
return message
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class IncludedFeaNotFound(FeatureLibError):
|
| 15 |
+
def __str__(self):
|
| 16 |
+
assert self.location is not None
|
| 17 |
+
|
| 18 |
+
message = (
|
| 19 |
+
"The following feature file should be included but cannot be found: "
|
| 20 |
+
f"{Exception.__str__(self)}"
|
| 21 |
+
)
|
| 22 |
+
return f"{self.location}: {message}"
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/lookupDebugInfo.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import NamedTuple
|
| 2 |
+
|
| 3 |
+
LOOKUP_DEBUG_INFO_KEY = "com.github.fonttools.feaLib"
|
| 4 |
+
LOOKUP_DEBUG_ENV_VAR = "FONTTOOLS_LOOKUP_DEBUGGING"
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class LookupDebugInfo(NamedTuple):
|
| 8 |
+
"""Information about where a lookup came from, to be embedded in a font"""
|
| 9 |
+
|
| 10 |
+
location: str
|
| 11 |
+
name: str
|
| 12 |
+
feature: list
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/parser.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/variableScalar.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.varLib.models import VariationModel, normalizeValue, piecewiseLinearMap
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def Location(loc):
|
| 5 |
+
return tuple(sorted(loc.items()))
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class VariableScalar:
|
| 9 |
+
"""A scalar with different values at different points in the designspace."""
|
| 10 |
+
|
| 11 |
+
def __init__(self, location_value={}):
|
| 12 |
+
self.values = {}
|
| 13 |
+
self.axes = {}
|
| 14 |
+
for location, value in location_value.items():
|
| 15 |
+
self.add_value(location, value)
|
| 16 |
+
|
| 17 |
+
def __repr__(self):
|
| 18 |
+
items = []
|
| 19 |
+
for location, value in self.values.items():
|
| 20 |
+
loc = ",".join(["%s=%i" % (ax, loc) for ax, loc in location])
|
| 21 |
+
items.append("%s:%i" % (loc, value))
|
| 22 |
+
return "(" + (" ".join(items)) + ")"
|
| 23 |
+
|
| 24 |
+
@property
|
| 25 |
+
def does_vary(self):
|
| 26 |
+
values = list(self.values.values())
|
| 27 |
+
return any(v != values[0] for v in values[1:])
|
| 28 |
+
|
| 29 |
+
@property
|
| 30 |
+
def axes_dict(self):
|
| 31 |
+
if not self.axes:
|
| 32 |
+
raise ValueError(
|
| 33 |
+
".axes must be defined on variable scalar before interpolating"
|
| 34 |
+
)
|
| 35 |
+
return {ax.axisTag: ax for ax in self.axes}
|
| 36 |
+
|
| 37 |
+
def _normalized_location(self, location):
|
| 38 |
+
location = self.fix_location(location)
|
| 39 |
+
normalized_location = {}
|
| 40 |
+
for axtag in location.keys():
|
| 41 |
+
if axtag not in self.axes_dict:
|
| 42 |
+
raise ValueError("Unknown axis %s in %s" % (axtag, location))
|
| 43 |
+
axis = self.axes_dict[axtag]
|
| 44 |
+
normalized_location[axtag] = normalizeValue(
|
| 45 |
+
location[axtag], (axis.minValue, axis.defaultValue, axis.maxValue)
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
return Location(normalized_location)
|
| 49 |
+
|
| 50 |
+
def fix_location(self, location):
|
| 51 |
+
location = dict(location)
|
| 52 |
+
for tag, axis in self.axes_dict.items():
|
| 53 |
+
if tag not in location:
|
| 54 |
+
location[tag] = axis.defaultValue
|
| 55 |
+
return location
|
| 56 |
+
|
| 57 |
+
def add_value(self, location, value):
|
| 58 |
+
if self.axes:
|
| 59 |
+
location = self.fix_location(location)
|
| 60 |
+
|
| 61 |
+
self.values[Location(location)] = value
|
| 62 |
+
|
| 63 |
+
def fix_all_locations(self):
|
| 64 |
+
self.values = {
|
| 65 |
+
Location(self.fix_location(l)): v for l, v in self.values.items()
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
@property
|
| 69 |
+
def default(self):
|
| 70 |
+
self.fix_all_locations()
|
| 71 |
+
key = Location({ax.axisTag: ax.defaultValue for ax in self.axes})
|
| 72 |
+
if key not in self.values:
|
| 73 |
+
raise ValueError("Default value could not be found")
|
| 74 |
+
# I *guess* we could interpolate one, but I don't know how.
|
| 75 |
+
return self.values[key]
|
| 76 |
+
|
| 77 |
+
def value_at_location(self, location, model_cache=None, avar=None):
|
| 78 |
+
loc = Location(location)
|
| 79 |
+
if loc in self.values.keys():
|
| 80 |
+
return self.values[loc]
|
| 81 |
+
values = list(self.values.values())
|
| 82 |
+
loc = dict(self._normalized_location(loc))
|
| 83 |
+
return self.model(model_cache, avar).interpolateFromMasters(loc, values)
|
| 84 |
+
|
| 85 |
+
def model(self, model_cache=None, avar=None):
|
| 86 |
+
if model_cache is not None:
|
| 87 |
+
key = tuple(self.values.keys())
|
| 88 |
+
if key in model_cache:
|
| 89 |
+
return model_cache[key]
|
| 90 |
+
locations = [dict(self._normalized_location(k)) for k in self.values.keys()]
|
| 91 |
+
if avar is not None:
|
| 92 |
+
mapping = avar.segments
|
| 93 |
+
locations = [
|
| 94 |
+
{
|
| 95 |
+
k: piecewiseLinearMap(v, mapping[k]) if k in mapping else v
|
| 96 |
+
for k, v in location.items()
|
| 97 |
+
}
|
| 98 |
+
for location in locations
|
| 99 |
+
]
|
| 100 |
+
m = VariationModel(locations)
|
| 101 |
+
if model_cache is not None:
|
| 102 |
+
model_cache[key] = m
|
| 103 |
+
return m
|
| 104 |
+
|
| 105 |
+
def get_deltas_and_supports(self, model_cache=None, avar=None):
|
| 106 |
+
values = list(self.values.values())
|
| 107 |
+
return self.model(model_cache, avar).getDeltasAndSupports(values)
|
| 108 |
+
|
| 109 |
+
def add_to_variation_store(self, store_builder, model_cache=None, avar=None):
|
| 110 |
+
deltas, supports = self.get_deltas_and_supports(model_cache, avar)
|
| 111 |
+
store_builder.setSupports(supports)
|
| 112 |
+
index = store_builder.storeDeltas(deltas)
|
| 113 |
+
return int(self.default), index
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__init__.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Behdad Esfahbod, Roozbeh Pournader
|
| 4 |
+
|
| 5 |
+
from fontTools import ttLib
|
| 6 |
+
import fontTools.merge.base
|
| 7 |
+
from fontTools.merge.cmap import (
|
| 8 |
+
computeMegaGlyphOrder,
|
| 9 |
+
computeMegaCmap,
|
| 10 |
+
renameCFFCharStrings,
|
| 11 |
+
)
|
| 12 |
+
from fontTools.merge.layout import layoutPreMerge, layoutPostMerge
|
| 13 |
+
from fontTools.merge.options import Options
|
| 14 |
+
import fontTools.merge.tables
|
| 15 |
+
from fontTools.misc.loggingTools import Timer
|
| 16 |
+
from functools import reduce
|
| 17 |
+
import sys
|
| 18 |
+
import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
log = logging.getLogger("fontTools.merge")
|
| 22 |
+
timer = Timer(logger=logging.getLogger(__name__ + ".timer"), level=logging.INFO)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Merger(object):
|
| 26 |
+
"""Font merger.
|
| 27 |
+
|
| 28 |
+
This class merges multiple files into a single OpenType font, taking into
|
| 29 |
+
account complexities such as OpenType layout (``GSUB``/``GPOS``) tables and
|
| 30 |
+
cross-font metrics (for example ``hhea.ascent`` is set to the maximum value
|
| 31 |
+
across all the fonts).
|
| 32 |
+
|
| 33 |
+
If multiple glyphs map to the same Unicode value, and the glyphs are considered
|
| 34 |
+
sufficiently different (that is, they differ in any of paths, widths, or
|
| 35 |
+
height), then subsequent glyphs are renamed and a lookup in the ``locl``
|
| 36 |
+
feature will be created to disambiguate them. For example, if the arguments
|
| 37 |
+
are an Arabic font and a Latin font and both contain a set of parentheses,
|
| 38 |
+
the Latin glyphs will be renamed to ``parenleft.1`` and ``parenright.1``,
|
| 39 |
+
and a lookup will be inserted into the to ``locl`` feature (creating it if
|
| 40 |
+
necessary) under the ``latn`` script to substitute ``parenleft`` with
|
| 41 |
+
``parenleft.1`` etc.
|
| 42 |
+
|
| 43 |
+
Restrictions:
|
| 44 |
+
|
| 45 |
+
- All fonts must have the same units per em.
|
| 46 |
+
- If duplicate glyph disambiguation takes place as described above then the
|
| 47 |
+
fonts must have a ``GSUB`` table.
|
| 48 |
+
|
| 49 |
+
Attributes:
|
| 50 |
+
options: Currently unused.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(self, options=None):
|
| 54 |
+
if not options:
|
| 55 |
+
options = Options()
|
| 56 |
+
|
| 57 |
+
self.options = options
|
| 58 |
+
|
| 59 |
+
def _openFonts(self, fontfiles):
|
| 60 |
+
fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles]
|
| 61 |
+
for font, fontfile in zip(fonts, fontfiles):
|
| 62 |
+
font._merger__fontfile = fontfile
|
| 63 |
+
font._merger__name = font["name"].getDebugName(4)
|
| 64 |
+
return fonts
|
| 65 |
+
|
| 66 |
+
def merge(self, fontfiles):
|
| 67 |
+
"""Merges fonts together.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
fontfiles: A list of file names to be merged
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
A :class:`fontTools.ttLib.TTFont` object. Call the ``save`` method on
|
| 74 |
+
this to write it out to an OTF file.
|
| 75 |
+
"""
|
| 76 |
+
#
|
| 77 |
+
# Settle on a mega glyph order.
|
| 78 |
+
#
|
| 79 |
+
fonts = self._openFonts(fontfiles)
|
| 80 |
+
glyphOrders = [list(font.getGlyphOrder()) for font in fonts]
|
| 81 |
+
computeMegaGlyphOrder(self, glyphOrders)
|
| 82 |
+
|
| 83 |
+
# Take first input file sfntVersion
|
| 84 |
+
sfntVersion = fonts[0].sfntVersion
|
| 85 |
+
|
| 86 |
+
# Reload fonts and set new glyph names on them.
|
| 87 |
+
fonts = self._openFonts(fontfiles)
|
| 88 |
+
for font, glyphOrder in zip(fonts, glyphOrders):
|
| 89 |
+
font.setGlyphOrder(glyphOrder)
|
| 90 |
+
if "CFF " in font:
|
| 91 |
+
renameCFFCharStrings(self, glyphOrder, font["CFF "])
|
| 92 |
+
|
| 93 |
+
cmaps = [font["cmap"] for font in fonts]
|
| 94 |
+
self.duplicateGlyphsPerFont = [{} for _ in fonts]
|
| 95 |
+
computeMegaCmap(self, cmaps)
|
| 96 |
+
|
| 97 |
+
mega = ttLib.TTFont(sfntVersion=sfntVersion)
|
| 98 |
+
mega.setGlyphOrder(self.glyphOrder)
|
| 99 |
+
|
| 100 |
+
for font in fonts:
|
| 101 |
+
self._preMerge(font)
|
| 102 |
+
|
| 103 |
+
self.fonts = fonts
|
| 104 |
+
|
| 105 |
+
allTags = reduce(set.union, (list(font.keys()) for font in fonts), set())
|
| 106 |
+
allTags.remove("GlyphOrder")
|
| 107 |
+
|
| 108 |
+
for tag in sorted(allTags):
|
| 109 |
+
if tag in self.options.drop_tables:
|
| 110 |
+
continue
|
| 111 |
+
|
| 112 |
+
with timer("merge '%s'" % tag):
|
| 113 |
+
tables = [font.get(tag, NotImplemented) for font in fonts]
|
| 114 |
+
|
| 115 |
+
log.info("Merging '%s'.", tag)
|
| 116 |
+
clazz = ttLib.getTableClass(tag)
|
| 117 |
+
table = clazz(tag).merge(self, tables)
|
| 118 |
+
# XXX Clean this up and use: table = mergeObjects(tables)
|
| 119 |
+
|
| 120 |
+
if table is not NotImplemented and table is not False:
|
| 121 |
+
mega[tag] = table
|
| 122 |
+
log.info("Merged '%s'.", tag)
|
| 123 |
+
else:
|
| 124 |
+
log.info("Dropped '%s'.", tag)
|
| 125 |
+
|
| 126 |
+
del self.duplicateGlyphsPerFont
|
| 127 |
+
del self.fonts
|
| 128 |
+
|
| 129 |
+
self._postMerge(mega)
|
| 130 |
+
|
| 131 |
+
return mega
|
| 132 |
+
|
| 133 |
+
def mergeObjects(self, returnTable, logic, tables):
|
| 134 |
+
# Right now we don't use self at all. Will use in the future
|
| 135 |
+
# for options and logging.
|
| 136 |
+
|
| 137 |
+
allKeys = set.union(
|
| 138 |
+
set(),
|
| 139 |
+
*(vars(table).keys() for table in tables if table is not NotImplemented),
|
| 140 |
+
)
|
| 141 |
+
for key in allKeys:
|
| 142 |
+
log.info(" %s", key)
|
| 143 |
+
try:
|
| 144 |
+
mergeLogic = logic[key]
|
| 145 |
+
except KeyError:
|
| 146 |
+
try:
|
| 147 |
+
mergeLogic = logic["*"]
|
| 148 |
+
except KeyError:
|
| 149 |
+
raise Exception(
|
| 150 |
+
"Don't know how to merge key %s of class %s"
|
| 151 |
+
% (key, returnTable.__class__.__name__)
|
| 152 |
+
)
|
| 153 |
+
if mergeLogic is NotImplemented:
|
| 154 |
+
continue
|
| 155 |
+
value = mergeLogic(getattr(table, key, NotImplemented) for table in tables)
|
| 156 |
+
if value is not NotImplemented:
|
| 157 |
+
setattr(returnTable, key, value)
|
| 158 |
+
|
| 159 |
+
return returnTable
|
| 160 |
+
|
| 161 |
+
def _preMerge(self, font):
|
| 162 |
+
layoutPreMerge(font)
|
| 163 |
+
|
| 164 |
+
def _postMerge(self, font):
|
| 165 |
+
layoutPostMerge(font)
|
| 166 |
+
|
| 167 |
+
if "OS/2" in font:
|
| 168 |
+
# https://github.com/fonttools/fonttools/issues/2538
|
| 169 |
+
# TODO: Add an option to disable this?
|
| 170 |
+
font["OS/2"].recalcAvgCharWidth(font)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
__all__ = ["Options", "Merger", "main"]
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
@timer("make one with everything (TOTAL TIME)")
|
| 177 |
+
def main(args=None):
|
| 178 |
+
"""Merge multiple fonts into one"""
|
| 179 |
+
from fontTools import configLogger
|
| 180 |
+
|
| 181 |
+
if args is None:
|
| 182 |
+
args = sys.argv[1:]
|
| 183 |
+
|
| 184 |
+
options = Options()
|
| 185 |
+
args = options.parse_opts(args)
|
| 186 |
+
fontfiles = []
|
| 187 |
+
if options.input_file:
|
| 188 |
+
with open(options.input_file) as inputfile:
|
| 189 |
+
fontfiles = [
|
| 190 |
+
line.strip()
|
| 191 |
+
for line in inputfile.readlines()
|
| 192 |
+
if not line.lstrip().startswith("#")
|
| 193 |
+
]
|
| 194 |
+
for g in args:
|
| 195 |
+
fontfiles.append(g)
|
| 196 |
+
|
| 197 |
+
if len(fontfiles) < 1:
|
| 198 |
+
print(
|
| 199 |
+
"usage: pyftmerge [font1 ... fontN] [--input-file=filelist.txt] [--output-file=merged.ttf] [--import-file=tables.ttx]",
|
| 200 |
+
file=sys.stderr,
|
| 201 |
+
)
|
| 202 |
+
print(
|
| 203 |
+
" [--drop-tables=tags] [--verbose] [--timing]",
|
| 204 |
+
file=sys.stderr,
|
| 205 |
+
)
|
| 206 |
+
print("", file=sys.stderr)
|
| 207 |
+
print(" font1 ... fontN Files to merge.", file=sys.stderr)
|
| 208 |
+
print(
|
| 209 |
+
" --input-file=<filename> Read files to merge from a text file, each path new line. # Comment lines allowed.",
|
| 210 |
+
file=sys.stderr,
|
| 211 |
+
)
|
| 212 |
+
print(
|
| 213 |
+
" --output-file=<filename> Specify output file name (default: merged.ttf).",
|
| 214 |
+
file=sys.stderr,
|
| 215 |
+
)
|
| 216 |
+
print(
|
| 217 |
+
" --import-file=<filename> TTX file to import after merging. This can be used to set metadata.",
|
| 218 |
+
file=sys.stderr,
|
| 219 |
+
)
|
| 220 |
+
print(
|
| 221 |
+
" --drop-tables=<table tags> Comma separated list of table tags to skip, case sensitive.",
|
| 222 |
+
file=sys.stderr,
|
| 223 |
+
)
|
| 224 |
+
print(
|
| 225 |
+
" --verbose Output progress information.",
|
| 226 |
+
file=sys.stderr,
|
| 227 |
+
)
|
| 228 |
+
print(" --timing Output progress timing.", file=sys.stderr)
|
| 229 |
+
return 1
|
| 230 |
+
|
| 231 |
+
configLogger(level=logging.INFO if options.verbose else logging.WARNING)
|
| 232 |
+
if options.timing:
|
| 233 |
+
timer.logger.setLevel(logging.DEBUG)
|
| 234 |
+
else:
|
| 235 |
+
timer.logger.disabled = True
|
| 236 |
+
|
| 237 |
+
merger = Merger(options=options)
|
| 238 |
+
font = merger.merge(fontfiles)
|
| 239 |
+
|
| 240 |
+
if options.import_file:
|
| 241 |
+
font.importXML(options.import_file)
|
| 242 |
+
|
| 243 |
+
with timer("compile and save font"):
|
| 244 |
+
font.save(options.output_file)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
if __name__ == "__main__":
|
| 248 |
+
sys.exit(main())
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__main__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from fontTools.merge import main
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
sys.exit(main())
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (7.87 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/__main__.cpython-310.pyc
ADDED
|
Binary file (288 Bytes). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/base.cpython-310.pyc
ADDED
|
Binary file (2.52 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/cmap.cpython-310.pyc
ADDED
|
Binary file (3.34 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/layout.cpython-310.pyc
ADDED
|
Binary file (11.7 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/options.cpython-310.pyc
ADDED
|
Binary file (2.16 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/tables.cpython-310.pyc
ADDED
|
Binary file (7.54 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/unicode.cpython-310.pyc
ADDED
|
Binary file (1.12 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/__pycache__/util.cpython-310.pyc
ADDED
|
Binary file (5.88 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/base.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Behdad Esfahbod, Roozbeh Pournader
|
| 4 |
+
|
| 5 |
+
from fontTools.ttLib.tables.DefaultTable import DefaultTable
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
log = logging.getLogger("fontTools.merge")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def add_method(*clazzes, **kwargs):
|
| 13 |
+
"""Returns a decorator function that adds a new method to one or
|
| 14 |
+
more classes."""
|
| 15 |
+
allowDefault = kwargs.get("allowDefaultTable", False)
|
| 16 |
+
|
| 17 |
+
def wrapper(method):
|
| 18 |
+
done = []
|
| 19 |
+
for clazz in clazzes:
|
| 20 |
+
if clazz in done:
|
| 21 |
+
continue # Support multiple names of a clazz
|
| 22 |
+
done.append(clazz)
|
| 23 |
+
assert allowDefault or clazz != DefaultTable, "Oops, table class not found."
|
| 24 |
+
assert (
|
| 25 |
+
method.__name__ not in clazz.__dict__
|
| 26 |
+
), "Oops, class '%s' has method '%s'." % (clazz.__name__, method.__name__)
|
| 27 |
+
setattr(clazz, method.__name__, method)
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
return wrapper
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def mergeObjects(lst):
|
| 34 |
+
lst = [item for item in lst if item is not NotImplemented]
|
| 35 |
+
if not lst:
|
| 36 |
+
return NotImplemented
|
| 37 |
+
lst = [item for item in lst if item is not None]
|
| 38 |
+
if not lst:
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
clazz = lst[0].__class__
|
| 42 |
+
assert all(type(item) == clazz for item in lst), lst
|
| 43 |
+
|
| 44 |
+
logic = clazz.mergeMap
|
| 45 |
+
returnTable = clazz()
|
| 46 |
+
returnDict = {}
|
| 47 |
+
|
| 48 |
+
allKeys = set.union(set(), *(vars(table).keys() for table in lst))
|
| 49 |
+
for key in allKeys:
|
| 50 |
+
try:
|
| 51 |
+
mergeLogic = logic[key]
|
| 52 |
+
except KeyError:
|
| 53 |
+
try:
|
| 54 |
+
mergeLogic = logic["*"]
|
| 55 |
+
except KeyError:
|
| 56 |
+
raise Exception(
|
| 57 |
+
"Don't know how to merge key %s of class %s" % (key, clazz.__name__)
|
| 58 |
+
)
|
| 59 |
+
if mergeLogic is NotImplemented:
|
| 60 |
+
continue
|
| 61 |
+
value = mergeLogic(getattr(table, key, NotImplemented) for table in lst)
|
| 62 |
+
if value is not NotImplemented:
|
| 63 |
+
returnDict[key] = value
|
| 64 |
+
|
| 65 |
+
returnTable.__dict__ = returnDict
|
| 66 |
+
|
| 67 |
+
return returnTable
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@add_method(DefaultTable, allowDefaultTable=True)
|
| 71 |
+
def merge(self, m, tables):
|
| 72 |
+
if not hasattr(self, "mergeMap"):
|
| 73 |
+
log.info("Don't know how to merge '%s'.", self.tableTag)
|
| 74 |
+
return NotImplemented
|
| 75 |
+
|
| 76 |
+
logic = self.mergeMap
|
| 77 |
+
|
| 78 |
+
if isinstance(logic, dict):
|
| 79 |
+
return m.mergeObjects(self, self.mergeMap, tables)
|
| 80 |
+
else:
|
| 81 |
+
return logic(tables)
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/cmap.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Behdad Esfahbod, Roozbeh Pournader
|
| 4 |
+
|
| 5 |
+
from fontTools.merge.unicode import is_Default_Ignorable
|
| 6 |
+
from fontTools.pens.recordingPen import DecomposingRecordingPen
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
log = logging.getLogger("fontTools.merge")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def computeMegaGlyphOrder(merger, glyphOrders):
|
| 14 |
+
"""Modifies passed-in glyphOrders to reflect new glyph names.
|
| 15 |
+
Stores merger.glyphOrder."""
|
| 16 |
+
megaOrder = {}
|
| 17 |
+
for glyphOrder in glyphOrders:
|
| 18 |
+
for i, glyphName in enumerate(glyphOrder):
|
| 19 |
+
if glyphName in megaOrder:
|
| 20 |
+
n = megaOrder[glyphName]
|
| 21 |
+
while (glyphName + "." + repr(n)) in megaOrder:
|
| 22 |
+
n += 1
|
| 23 |
+
megaOrder[glyphName] = n
|
| 24 |
+
glyphName += "." + repr(n)
|
| 25 |
+
glyphOrder[i] = glyphName
|
| 26 |
+
megaOrder[glyphName] = 1
|
| 27 |
+
merger.glyphOrder = megaOrder = list(megaOrder.keys())
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _glyphsAreSame(
|
| 31 |
+
glyphSet1,
|
| 32 |
+
glyphSet2,
|
| 33 |
+
glyph1,
|
| 34 |
+
glyph2,
|
| 35 |
+
advanceTolerance=0.05,
|
| 36 |
+
advanceToleranceEmpty=0.20,
|
| 37 |
+
):
|
| 38 |
+
pen1 = DecomposingRecordingPen(glyphSet1)
|
| 39 |
+
pen2 = DecomposingRecordingPen(glyphSet2)
|
| 40 |
+
g1 = glyphSet1[glyph1]
|
| 41 |
+
g2 = glyphSet2[glyph2]
|
| 42 |
+
g1.draw(pen1)
|
| 43 |
+
g2.draw(pen2)
|
| 44 |
+
if pen1.value != pen2.value:
|
| 45 |
+
return False
|
| 46 |
+
# Allow more width tolerance for glyphs with no ink
|
| 47 |
+
tolerance = advanceTolerance if pen1.value else advanceToleranceEmpty
|
| 48 |
+
# TODO Warn if advances not the same but within tolerance.
|
| 49 |
+
if abs(g1.width - g2.width) > g1.width * tolerance:
|
| 50 |
+
return False
|
| 51 |
+
if hasattr(g1, "height") and g1.height is not None:
|
| 52 |
+
if abs(g1.height - g2.height) > g1.height * tolerance:
|
| 53 |
+
return False
|
| 54 |
+
return True
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# Valid (format, platformID, platEncID) triplets for cmap subtables containing
|
| 58 |
+
# Unicode BMP-only and Unicode Full Repertoire semantics.
|
| 59 |
+
# Cf. OpenType spec for "Platform specific encodings":
|
| 60 |
+
# https://docs.microsoft.com/en-us/typography/opentype/spec/name
|
| 61 |
+
class _CmapUnicodePlatEncodings:
|
| 62 |
+
BMP = {(4, 3, 1), (4, 0, 3), (4, 0, 4), (4, 0, 6)}
|
| 63 |
+
FullRepertoire = {(12, 3, 10), (12, 0, 4), (12, 0, 6)}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def computeMegaCmap(merger, cmapTables):
|
| 67 |
+
"""Sets merger.cmap and merger.glyphOrder."""
|
| 68 |
+
|
| 69 |
+
# TODO Handle format=14.
|
| 70 |
+
# Only merge format 4 and 12 Unicode subtables, ignores all other subtables
|
| 71 |
+
# If there is a format 12 table for a font, ignore the format 4 table of it
|
| 72 |
+
chosenCmapTables = []
|
| 73 |
+
for fontIdx, table in enumerate(cmapTables):
|
| 74 |
+
format4 = None
|
| 75 |
+
format12 = None
|
| 76 |
+
for subtable in table.tables:
|
| 77 |
+
properties = (subtable.format, subtable.platformID, subtable.platEncID)
|
| 78 |
+
if properties in _CmapUnicodePlatEncodings.BMP:
|
| 79 |
+
format4 = subtable
|
| 80 |
+
elif properties in _CmapUnicodePlatEncodings.FullRepertoire:
|
| 81 |
+
format12 = subtable
|
| 82 |
+
else:
|
| 83 |
+
log.warning(
|
| 84 |
+
"Dropped cmap subtable from font '%s':\t"
|
| 85 |
+
"format %2s, platformID %2s, platEncID %2s",
|
| 86 |
+
fontIdx,
|
| 87 |
+
subtable.format,
|
| 88 |
+
subtable.platformID,
|
| 89 |
+
subtable.platEncID,
|
| 90 |
+
)
|
| 91 |
+
if format12 is not None:
|
| 92 |
+
chosenCmapTables.append((format12, fontIdx))
|
| 93 |
+
elif format4 is not None:
|
| 94 |
+
chosenCmapTables.append((format4, fontIdx))
|
| 95 |
+
|
| 96 |
+
# Build the unicode mapping
|
| 97 |
+
merger.cmap = cmap = {}
|
| 98 |
+
fontIndexForGlyph = {}
|
| 99 |
+
glyphSets = [None for f in merger.fonts] if hasattr(merger, "fonts") else None
|
| 100 |
+
|
| 101 |
+
for table, fontIdx in chosenCmapTables:
|
| 102 |
+
# handle duplicates
|
| 103 |
+
for uni, gid in table.cmap.items():
|
| 104 |
+
oldgid = cmap.get(uni, None)
|
| 105 |
+
if oldgid is None:
|
| 106 |
+
cmap[uni] = gid
|
| 107 |
+
fontIndexForGlyph[gid] = fontIdx
|
| 108 |
+
elif is_Default_Ignorable(uni) or uni in (0x25CC,): # U+25CC DOTTED CIRCLE
|
| 109 |
+
continue
|
| 110 |
+
elif oldgid != gid:
|
| 111 |
+
# Char previously mapped to oldgid, now to gid.
|
| 112 |
+
# Record, to fix up in GSUB 'locl' later.
|
| 113 |
+
if merger.duplicateGlyphsPerFont[fontIdx].get(oldgid) is None:
|
| 114 |
+
if glyphSets is not None:
|
| 115 |
+
oldFontIdx = fontIndexForGlyph[oldgid]
|
| 116 |
+
for idx in (fontIdx, oldFontIdx):
|
| 117 |
+
if glyphSets[idx] is None:
|
| 118 |
+
glyphSets[idx] = merger.fonts[idx].getGlyphSet()
|
| 119 |
+
# if _glyphsAreSame(glyphSets[oldFontIdx], glyphSets[fontIdx], oldgid, gid):
|
| 120 |
+
# continue
|
| 121 |
+
merger.duplicateGlyphsPerFont[fontIdx][oldgid] = gid
|
| 122 |
+
elif merger.duplicateGlyphsPerFont[fontIdx][oldgid] != gid:
|
| 123 |
+
# Char previously mapped to oldgid but oldgid is already remapped to a different
|
| 124 |
+
# gid, because of another Unicode character.
|
| 125 |
+
# TODO: Try harder to do something about these.
|
| 126 |
+
log.warning(
|
| 127 |
+
"Dropped mapping from codepoint %#06X to glyphId '%s'", uni, gid
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def renameCFFCharStrings(merger, glyphOrder, cffTable):
|
| 132 |
+
"""Rename topDictIndex charStrings based on glyphOrder."""
|
| 133 |
+
td = cffTable.cff.topDictIndex[0]
|
| 134 |
+
|
| 135 |
+
charStrings = {}
|
| 136 |
+
for i, v in enumerate(td.CharStrings.charStrings.values()):
|
| 137 |
+
glyphName = glyphOrder[i]
|
| 138 |
+
charStrings[glyphName] = v
|
| 139 |
+
td.CharStrings.charStrings = charStrings
|
| 140 |
+
|
| 141 |
+
td.charset = list(glyphOrder)
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/layout.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Behdad Esfahbod, Roozbeh Pournader
|
| 4 |
+
|
| 5 |
+
from fontTools import ttLib
|
| 6 |
+
from fontTools.ttLib.tables.DefaultTable import DefaultTable
|
| 7 |
+
from fontTools.ttLib.tables import otTables
|
| 8 |
+
from fontTools.merge.base import add_method, mergeObjects
|
| 9 |
+
from fontTools.merge.util import *
|
| 10 |
+
import logging
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
log = logging.getLogger("fontTools.merge")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def mergeLookupLists(lst):
|
| 17 |
+
# TODO Do smarter merge.
|
| 18 |
+
return sumLists(lst)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def mergeFeatures(lst):
|
| 22 |
+
assert lst
|
| 23 |
+
self = otTables.Feature()
|
| 24 |
+
self.FeatureParams = None
|
| 25 |
+
self.LookupListIndex = mergeLookupLists(
|
| 26 |
+
[l.LookupListIndex for l in lst if l.LookupListIndex]
|
| 27 |
+
)
|
| 28 |
+
self.LookupCount = len(self.LookupListIndex)
|
| 29 |
+
return self
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def mergeFeatureLists(lst):
|
| 33 |
+
d = {}
|
| 34 |
+
for l in lst:
|
| 35 |
+
for f in l:
|
| 36 |
+
tag = f.FeatureTag
|
| 37 |
+
if tag not in d:
|
| 38 |
+
d[tag] = []
|
| 39 |
+
d[tag].append(f.Feature)
|
| 40 |
+
ret = []
|
| 41 |
+
for tag in sorted(d.keys()):
|
| 42 |
+
rec = otTables.FeatureRecord()
|
| 43 |
+
rec.FeatureTag = tag
|
| 44 |
+
rec.Feature = mergeFeatures(d[tag])
|
| 45 |
+
ret.append(rec)
|
| 46 |
+
return ret
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def mergeLangSyses(lst):
|
| 50 |
+
assert lst
|
| 51 |
+
|
| 52 |
+
# TODO Support merging ReqFeatureIndex
|
| 53 |
+
assert all(l.ReqFeatureIndex == 0xFFFF for l in lst)
|
| 54 |
+
|
| 55 |
+
self = otTables.LangSys()
|
| 56 |
+
self.LookupOrder = None
|
| 57 |
+
self.ReqFeatureIndex = 0xFFFF
|
| 58 |
+
self.FeatureIndex = mergeFeatureLists(
|
| 59 |
+
[l.FeatureIndex for l in lst if l.FeatureIndex]
|
| 60 |
+
)
|
| 61 |
+
self.FeatureCount = len(self.FeatureIndex)
|
| 62 |
+
return self
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def mergeScripts(lst):
|
| 66 |
+
assert lst
|
| 67 |
+
|
| 68 |
+
if len(lst) == 1:
|
| 69 |
+
return lst[0]
|
| 70 |
+
langSyses = {}
|
| 71 |
+
for sr in lst:
|
| 72 |
+
for lsr in sr.LangSysRecord:
|
| 73 |
+
if lsr.LangSysTag not in langSyses:
|
| 74 |
+
langSyses[lsr.LangSysTag] = []
|
| 75 |
+
langSyses[lsr.LangSysTag].append(lsr.LangSys)
|
| 76 |
+
lsrecords = []
|
| 77 |
+
for tag, langSys_list in sorted(langSyses.items()):
|
| 78 |
+
lsr = otTables.LangSysRecord()
|
| 79 |
+
lsr.LangSys = mergeLangSyses(langSys_list)
|
| 80 |
+
lsr.LangSysTag = tag
|
| 81 |
+
lsrecords.append(lsr)
|
| 82 |
+
|
| 83 |
+
self = otTables.Script()
|
| 84 |
+
self.LangSysRecord = lsrecords
|
| 85 |
+
self.LangSysCount = len(lsrecords)
|
| 86 |
+
dfltLangSyses = [s.DefaultLangSys for s in lst if s.DefaultLangSys]
|
| 87 |
+
if dfltLangSyses:
|
| 88 |
+
self.DefaultLangSys = mergeLangSyses(dfltLangSyses)
|
| 89 |
+
else:
|
| 90 |
+
self.DefaultLangSys = None
|
| 91 |
+
return self
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def mergeScriptRecords(lst):
|
| 95 |
+
d = {}
|
| 96 |
+
for l in lst:
|
| 97 |
+
for s in l:
|
| 98 |
+
tag = s.ScriptTag
|
| 99 |
+
if tag not in d:
|
| 100 |
+
d[tag] = []
|
| 101 |
+
d[tag].append(s.Script)
|
| 102 |
+
ret = []
|
| 103 |
+
for tag in sorted(d.keys()):
|
| 104 |
+
rec = otTables.ScriptRecord()
|
| 105 |
+
rec.ScriptTag = tag
|
| 106 |
+
rec.Script = mergeScripts(d[tag])
|
| 107 |
+
ret.append(rec)
|
| 108 |
+
return ret
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
otTables.ScriptList.mergeMap = {
|
| 112 |
+
"ScriptCount": lambda lst: None, # TODO
|
| 113 |
+
"ScriptRecord": mergeScriptRecords,
|
| 114 |
+
}
|
| 115 |
+
otTables.BaseScriptList.mergeMap = {
|
| 116 |
+
"BaseScriptCount": lambda lst: None, # TODO
|
| 117 |
+
# TODO: Merge duplicate entries
|
| 118 |
+
"BaseScriptRecord": lambda lst: sorted(
|
| 119 |
+
sumLists(lst), key=lambda s: s.BaseScriptTag
|
| 120 |
+
),
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
otTables.FeatureList.mergeMap = {
|
| 124 |
+
"FeatureCount": sum,
|
| 125 |
+
"FeatureRecord": lambda lst: sorted(sumLists(lst), key=lambda s: s.FeatureTag),
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
otTables.LookupList.mergeMap = {
|
| 129 |
+
"LookupCount": sum,
|
| 130 |
+
"Lookup": sumLists,
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
otTables.Coverage.mergeMap = {
|
| 134 |
+
"Format": min,
|
| 135 |
+
"glyphs": sumLists,
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
otTables.ClassDef.mergeMap = {
|
| 139 |
+
"Format": min,
|
| 140 |
+
"classDefs": sumDicts,
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
otTables.LigCaretList.mergeMap = {
|
| 144 |
+
"Coverage": mergeObjects,
|
| 145 |
+
"LigGlyphCount": sum,
|
| 146 |
+
"LigGlyph": sumLists,
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
otTables.AttachList.mergeMap = {
|
| 150 |
+
"Coverage": mergeObjects,
|
| 151 |
+
"GlyphCount": sum,
|
| 152 |
+
"AttachPoint": sumLists,
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
# XXX Renumber MarkFilterSets of lookups
|
| 156 |
+
otTables.MarkGlyphSetsDef.mergeMap = {
|
| 157 |
+
"MarkSetTableFormat": equal,
|
| 158 |
+
"MarkSetCount": sum,
|
| 159 |
+
"Coverage": sumLists,
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
otTables.Axis.mergeMap = {
|
| 163 |
+
"*": mergeObjects,
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
# XXX Fix BASE table merging
|
| 167 |
+
otTables.BaseTagList.mergeMap = {
|
| 168 |
+
"BaseTagCount": sum,
|
| 169 |
+
"BaselineTag": sumLists,
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
otTables.GDEF.mergeMap = otTables.GSUB.mergeMap = otTables.GPOS.mergeMap = (
|
| 173 |
+
otTables.BASE.mergeMap
|
| 174 |
+
) = otTables.JSTF.mergeMap = otTables.MATH.mergeMap = {
|
| 175 |
+
"*": mergeObjects,
|
| 176 |
+
"Version": max,
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
ttLib.getTableClass("GDEF").mergeMap = ttLib.getTableClass("GSUB").mergeMap = (
|
| 180 |
+
ttLib.getTableClass("GPOS").mergeMap
|
| 181 |
+
) = ttLib.getTableClass("BASE").mergeMap = ttLib.getTableClass(
|
| 182 |
+
"JSTF"
|
| 183 |
+
).mergeMap = ttLib.getTableClass(
|
| 184 |
+
"MATH"
|
| 185 |
+
).mergeMap = {
|
| 186 |
+
"tableTag": onlyExisting(equal), # XXX clean me up
|
| 187 |
+
"table": mergeObjects,
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
@add_method(ttLib.getTableClass("GSUB"))
|
| 192 |
+
def merge(self, m, tables):
|
| 193 |
+
assert len(tables) == len(m.duplicateGlyphsPerFont)
|
| 194 |
+
for i, (table, dups) in enumerate(zip(tables, m.duplicateGlyphsPerFont)):
|
| 195 |
+
if not dups:
|
| 196 |
+
continue
|
| 197 |
+
if table is None or table is NotImplemented:
|
| 198 |
+
log.warning(
|
| 199 |
+
"Have non-identical duplicates to resolve for '%s' but no GSUB. Are duplicates intended?: %s",
|
| 200 |
+
m.fonts[i]._merger__name,
|
| 201 |
+
dups,
|
| 202 |
+
)
|
| 203 |
+
continue
|
| 204 |
+
|
| 205 |
+
synthFeature = None
|
| 206 |
+
synthLookup = None
|
| 207 |
+
for script in table.table.ScriptList.ScriptRecord:
|
| 208 |
+
if script.ScriptTag == "DFLT":
|
| 209 |
+
continue # XXX
|
| 210 |
+
for langsys in [script.Script.DefaultLangSys] + [
|
| 211 |
+
l.LangSys for l in script.Script.LangSysRecord
|
| 212 |
+
]:
|
| 213 |
+
if langsys is None:
|
| 214 |
+
continue # XXX Create!
|
| 215 |
+
feature = [v for v in langsys.FeatureIndex if v.FeatureTag == "locl"]
|
| 216 |
+
assert len(feature) <= 1
|
| 217 |
+
if feature:
|
| 218 |
+
feature = feature[0]
|
| 219 |
+
else:
|
| 220 |
+
if not synthFeature:
|
| 221 |
+
synthFeature = otTables.FeatureRecord()
|
| 222 |
+
synthFeature.FeatureTag = "locl"
|
| 223 |
+
f = synthFeature.Feature = otTables.Feature()
|
| 224 |
+
f.FeatureParams = None
|
| 225 |
+
f.LookupCount = 0
|
| 226 |
+
f.LookupListIndex = []
|
| 227 |
+
table.table.FeatureList.FeatureRecord.append(synthFeature)
|
| 228 |
+
table.table.FeatureList.FeatureCount += 1
|
| 229 |
+
feature = synthFeature
|
| 230 |
+
langsys.FeatureIndex.append(feature)
|
| 231 |
+
langsys.FeatureIndex.sort(key=lambda v: v.FeatureTag)
|
| 232 |
+
|
| 233 |
+
if not synthLookup:
|
| 234 |
+
subtable = otTables.SingleSubst()
|
| 235 |
+
subtable.mapping = dups
|
| 236 |
+
synthLookup = otTables.Lookup()
|
| 237 |
+
synthLookup.LookupFlag = 0
|
| 238 |
+
synthLookup.LookupType = 1
|
| 239 |
+
synthLookup.SubTableCount = 1
|
| 240 |
+
synthLookup.SubTable = [subtable]
|
| 241 |
+
if table.table.LookupList is None:
|
| 242 |
+
# mtiLib uses None as default value for LookupList,
|
| 243 |
+
# while feaLib points to an empty array with count 0
|
| 244 |
+
# TODO: make them do the same
|
| 245 |
+
table.table.LookupList = otTables.LookupList()
|
| 246 |
+
table.table.LookupList.Lookup = []
|
| 247 |
+
table.table.LookupList.LookupCount = 0
|
| 248 |
+
table.table.LookupList.Lookup.append(synthLookup)
|
| 249 |
+
table.table.LookupList.LookupCount += 1
|
| 250 |
+
|
| 251 |
+
if feature.Feature.LookupListIndex[:1] != [synthLookup]:
|
| 252 |
+
feature.Feature.LookupListIndex[:0] = [synthLookup]
|
| 253 |
+
feature.Feature.LookupCount += 1
|
| 254 |
+
|
| 255 |
+
DefaultTable.merge(self, m, tables)
|
| 256 |
+
return self
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@add_method(
|
| 260 |
+
otTables.SingleSubst,
|
| 261 |
+
otTables.MultipleSubst,
|
| 262 |
+
otTables.AlternateSubst,
|
| 263 |
+
otTables.LigatureSubst,
|
| 264 |
+
otTables.ReverseChainSingleSubst,
|
| 265 |
+
otTables.SinglePos,
|
| 266 |
+
otTables.PairPos,
|
| 267 |
+
otTables.CursivePos,
|
| 268 |
+
otTables.MarkBasePos,
|
| 269 |
+
otTables.MarkLigPos,
|
| 270 |
+
otTables.MarkMarkPos,
|
| 271 |
+
)
|
| 272 |
+
def mapLookups(self, lookupMap):
|
| 273 |
+
pass
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# Copied and trimmed down from subset.py
|
| 277 |
+
@add_method(
|
| 278 |
+
otTables.ContextSubst,
|
| 279 |
+
otTables.ChainContextSubst,
|
| 280 |
+
otTables.ContextPos,
|
| 281 |
+
otTables.ChainContextPos,
|
| 282 |
+
)
|
| 283 |
+
def __merge_classify_context(self):
|
| 284 |
+
class ContextHelper(object):
|
| 285 |
+
def __init__(self, klass, Format):
|
| 286 |
+
if klass.__name__.endswith("Subst"):
|
| 287 |
+
Typ = "Sub"
|
| 288 |
+
Type = "Subst"
|
| 289 |
+
else:
|
| 290 |
+
Typ = "Pos"
|
| 291 |
+
Type = "Pos"
|
| 292 |
+
if klass.__name__.startswith("Chain"):
|
| 293 |
+
Chain = "Chain"
|
| 294 |
+
else:
|
| 295 |
+
Chain = ""
|
| 296 |
+
ChainTyp = Chain + Typ
|
| 297 |
+
|
| 298 |
+
self.Typ = Typ
|
| 299 |
+
self.Type = Type
|
| 300 |
+
self.Chain = Chain
|
| 301 |
+
self.ChainTyp = ChainTyp
|
| 302 |
+
|
| 303 |
+
self.LookupRecord = Type + "LookupRecord"
|
| 304 |
+
|
| 305 |
+
if Format == 1:
|
| 306 |
+
self.Rule = ChainTyp + "Rule"
|
| 307 |
+
self.RuleSet = ChainTyp + "RuleSet"
|
| 308 |
+
elif Format == 2:
|
| 309 |
+
self.Rule = ChainTyp + "ClassRule"
|
| 310 |
+
self.RuleSet = ChainTyp + "ClassSet"
|
| 311 |
+
|
| 312 |
+
if self.Format not in [1, 2, 3]:
|
| 313 |
+
return None # Don't shoot the messenger; let it go
|
| 314 |
+
if not hasattr(self.__class__, "_merge__ContextHelpers"):
|
| 315 |
+
self.__class__._merge__ContextHelpers = {}
|
| 316 |
+
if self.Format not in self.__class__._merge__ContextHelpers:
|
| 317 |
+
helper = ContextHelper(self.__class__, self.Format)
|
| 318 |
+
self.__class__._merge__ContextHelpers[self.Format] = helper
|
| 319 |
+
return self.__class__._merge__ContextHelpers[self.Format]
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
@add_method(
|
| 323 |
+
otTables.ContextSubst,
|
| 324 |
+
otTables.ChainContextSubst,
|
| 325 |
+
otTables.ContextPos,
|
| 326 |
+
otTables.ChainContextPos,
|
| 327 |
+
)
|
| 328 |
+
def mapLookups(self, lookupMap):
|
| 329 |
+
c = self.__merge_classify_context()
|
| 330 |
+
|
| 331 |
+
if self.Format in [1, 2]:
|
| 332 |
+
for rs in getattr(self, c.RuleSet):
|
| 333 |
+
if not rs:
|
| 334 |
+
continue
|
| 335 |
+
for r in getattr(rs, c.Rule):
|
| 336 |
+
if not r:
|
| 337 |
+
continue
|
| 338 |
+
for ll in getattr(r, c.LookupRecord):
|
| 339 |
+
if not ll:
|
| 340 |
+
continue
|
| 341 |
+
ll.LookupListIndex = lookupMap[ll.LookupListIndex]
|
| 342 |
+
elif self.Format == 3:
|
| 343 |
+
for ll in getattr(self, c.LookupRecord):
|
| 344 |
+
if not ll:
|
| 345 |
+
continue
|
| 346 |
+
ll.LookupListIndex = lookupMap[ll.LookupListIndex]
|
| 347 |
+
else:
|
| 348 |
+
assert 0, "unknown format: %s" % self.Format
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
@add_method(otTables.ExtensionSubst, otTables.ExtensionPos)
|
| 352 |
+
def mapLookups(self, lookupMap):
|
| 353 |
+
if self.Format == 1:
|
| 354 |
+
self.ExtSubTable.mapLookups(lookupMap)
|
| 355 |
+
else:
|
| 356 |
+
assert 0, "unknown format: %s" % self.Format
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
@add_method(otTables.Lookup)
|
| 360 |
+
def mapLookups(self, lookupMap):
|
| 361 |
+
for st in self.SubTable:
|
| 362 |
+
if not st:
|
| 363 |
+
continue
|
| 364 |
+
st.mapLookups(lookupMap)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
@add_method(otTables.LookupList)
|
| 368 |
+
def mapLookups(self, lookupMap):
|
| 369 |
+
for l in self.Lookup:
|
| 370 |
+
if not l:
|
| 371 |
+
continue
|
| 372 |
+
l.mapLookups(lookupMap)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
@add_method(otTables.Lookup)
|
| 376 |
+
def mapMarkFilteringSets(self, markFilteringSetMap):
|
| 377 |
+
if self.LookupFlag & 0x0010:
|
| 378 |
+
self.MarkFilteringSet = markFilteringSetMap[self.MarkFilteringSet]
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
@add_method(otTables.LookupList)
|
| 382 |
+
def mapMarkFilteringSets(self, markFilteringSetMap):
|
| 383 |
+
for l in self.Lookup:
|
| 384 |
+
if not l:
|
| 385 |
+
continue
|
| 386 |
+
l.mapMarkFilteringSets(markFilteringSetMap)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
@add_method(otTables.Feature)
|
| 390 |
+
def mapLookups(self, lookupMap):
|
| 391 |
+
self.LookupListIndex = [lookupMap[i] for i in self.LookupListIndex]
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
@add_method(otTables.FeatureList)
|
| 395 |
+
def mapLookups(self, lookupMap):
|
| 396 |
+
for f in self.FeatureRecord:
|
| 397 |
+
if not f or not f.Feature:
|
| 398 |
+
continue
|
| 399 |
+
f.Feature.mapLookups(lookupMap)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
@add_method(otTables.DefaultLangSys, otTables.LangSys)
|
| 403 |
+
def mapFeatures(self, featureMap):
|
| 404 |
+
self.FeatureIndex = [featureMap[i] for i in self.FeatureIndex]
|
| 405 |
+
if self.ReqFeatureIndex != 65535:
|
| 406 |
+
self.ReqFeatureIndex = featureMap[self.ReqFeatureIndex]
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@add_method(otTables.Script)
|
| 410 |
+
def mapFeatures(self, featureMap):
|
| 411 |
+
if self.DefaultLangSys:
|
| 412 |
+
self.DefaultLangSys.mapFeatures(featureMap)
|
| 413 |
+
for l in self.LangSysRecord:
|
| 414 |
+
if not l or not l.LangSys:
|
| 415 |
+
continue
|
| 416 |
+
l.LangSys.mapFeatures(featureMap)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
@add_method(otTables.ScriptList)
|
| 420 |
+
def mapFeatures(self, featureMap):
|
| 421 |
+
for s in self.ScriptRecord:
|
| 422 |
+
if not s or not s.Script:
|
| 423 |
+
continue
|
| 424 |
+
s.Script.mapFeatures(featureMap)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def layoutPreMerge(font):
|
| 428 |
+
# Map indices to references
|
| 429 |
+
|
| 430 |
+
GDEF = font.get("GDEF")
|
| 431 |
+
GSUB = font.get("GSUB")
|
| 432 |
+
GPOS = font.get("GPOS")
|
| 433 |
+
|
| 434 |
+
for t in [GSUB, GPOS]:
|
| 435 |
+
if not t:
|
| 436 |
+
continue
|
| 437 |
+
|
| 438 |
+
if t.table.LookupList:
|
| 439 |
+
lookupMap = {i: v for i, v in enumerate(t.table.LookupList.Lookup)}
|
| 440 |
+
t.table.LookupList.mapLookups(lookupMap)
|
| 441 |
+
t.table.FeatureList.mapLookups(lookupMap)
|
| 442 |
+
|
| 443 |
+
if (
|
| 444 |
+
GDEF
|
| 445 |
+
and GDEF.table.Version >= 0x00010002
|
| 446 |
+
and GDEF.table.MarkGlyphSetsDef
|
| 447 |
+
):
|
| 448 |
+
markFilteringSetMap = {
|
| 449 |
+
i: v for i, v in enumerate(GDEF.table.MarkGlyphSetsDef.Coverage)
|
| 450 |
+
}
|
| 451 |
+
t.table.LookupList.mapMarkFilteringSets(markFilteringSetMap)
|
| 452 |
+
|
| 453 |
+
if t.table.FeatureList and t.table.ScriptList:
|
| 454 |
+
featureMap = {i: v for i, v in enumerate(t.table.FeatureList.FeatureRecord)}
|
| 455 |
+
t.table.ScriptList.mapFeatures(featureMap)
|
| 456 |
+
|
| 457 |
+
# TODO FeatureParams nameIDs
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def layoutPostMerge(font):
|
| 461 |
+
# Map references back to indices
|
| 462 |
+
|
| 463 |
+
GDEF = font.get("GDEF")
|
| 464 |
+
GSUB = font.get("GSUB")
|
| 465 |
+
GPOS = font.get("GPOS")
|
| 466 |
+
|
| 467 |
+
for t in [GSUB, GPOS]:
|
| 468 |
+
if not t:
|
| 469 |
+
continue
|
| 470 |
+
|
| 471 |
+
if t.table.FeatureList and t.table.ScriptList:
|
| 472 |
+
# Collect unregistered (new) features.
|
| 473 |
+
featureMap = GregariousIdentityDict(t.table.FeatureList.FeatureRecord)
|
| 474 |
+
t.table.ScriptList.mapFeatures(featureMap)
|
| 475 |
+
|
| 476 |
+
# Record used features.
|
| 477 |
+
featureMap = AttendanceRecordingIdentityDict(
|
| 478 |
+
t.table.FeatureList.FeatureRecord
|
| 479 |
+
)
|
| 480 |
+
t.table.ScriptList.mapFeatures(featureMap)
|
| 481 |
+
usedIndices = featureMap.s
|
| 482 |
+
|
| 483 |
+
# Remove unused features
|
| 484 |
+
t.table.FeatureList.FeatureRecord = [
|
| 485 |
+
f
|
| 486 |
+
for i, f in enumerate(t.table.FeatureList.FeatureRecord)
|
| 487 |
+
if i in usedIndices
|
| 488 |
+
]
|
| 489 |
+
|
| 490 |
+
# Map back to indices.
|
| 491 |
+
featureMap = NonhashableDict(t.table.FeatureList.FeatureRecord)
|
| 492 |
+
t.table.ScriptList.mapFeatures(featureMap)
|
| 493 |
+
|
| 494 |
+
t.table.FeatureList.FeatureCount = len(t.table.FeatureList.FeatureRecord)
|
| 495 |
+
|
| 496 |
+
if t.table.LookupList:
|
| 497 |
+
# Collect unregistered (new) lookups.
|
| 498 |
+
lookupMap = GregariousIdentityDict(t.table.LookupList.Lookup)
|
| 499 |
+
t.table.FeatureList.mapLookups(lookupMap)
|
| 500 |
+
t.table.LookupList.mapLookups(lookupMap)
|
| 501 |
+
|
| 502 |
+
# Record used lookups.
|
| 503 |
+
lookupMap = AttendanceRecordingIdentityDict(t.table.LookupList.Lookup)
|
| 504 |
+
t.table.FeatureList.mapLookups(lookupMap)
|
| 505 |
+
t.table.LookupList.mapLookups(lookupMap)
|
| 506 |
+
usedIndices = lookupMap.s
|
| 507 |
+
|
| 508 |
+
# Remove unused lookups
|
| 509 |
+
t.table.LookupList.Lookup = [
|
| 510 |
+
l for i, l in enumerate(t.table.LookupList.Lookup) if i in usedIndices
|
| 511 |
+
]
|
| 512 |
+
|
| 513 |
+
# Map back to indices.
|
| 514 |
+
lookupMap = NonhashableDict(t.table.LookupList.Lookup)
|
| 515 |
+
t.table.FeatureList.mapLookups(lookupMap)
|
| 516 |
+
t.table.LookupList.mapLookups(lookupMap)
|
| 517 |
+
|
| 518 |
+
t.table.LookupList.LookupCount = len(t.table.LookupList.Lookup)
|
| 519 |
+
|
| 520 |
+
if GDEF and GDEF.table.Version >= 0x00010002:
|
| 521 |
+
markFilteringSetMap = NonhashableDict(
|
| 522 |
+
GDEF.table.MarkGlyphSetsDef.Coverage
|
| 523 |
+
)
|
| 524 |
+
t.table.LookupList.mapMarkFilteringSets(markFilteringSetMap)
|
| 525 |
+
|
| 526 |
+
# TODO FeatureParams nameIDs
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/options.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Behdad Esfahbod, Roozbeh Pournader
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Options(object):
|
| 7 |
+
class UnknownOptionError(Exception):
|
| 8 |
+
pass
|
| 9 |
+
|
| 10 |
+
def __init__(self, **kwargs):
|
| 11 |
+
self.verbose = False
|
| 12 |
+
self.timing = False
|
| 13 |
+
self.drop_tables = []
|
| 14 |
+
self.input_file = None
|
| 15 |
+
self.output_file = "merged.ttf"
|
| 16 |
+
self.import_file = None
|
| 17 |
+
|
| 18 |
+
self.set(**kwargs)
|
| 19 |
+
|
| 20 |
+
def set(self, **kwargs):
|
| 21 |
+
for k, v in kwargs.items():
|
| 22 |
+
if not hasattr(self, k):
|
| 23 |
+
raise self.UnknownOptionError("Unknown option '%s'" % k)
|
| 24 |
+
setattr(self, k, v)
|
| 25 |
+
|
| 26 |
+
def parse_opts(self, argv, ignore_unknown=[]):
|
| 27 |
+
ret = []
|
| 28 |
+
opts = {}
|
| 29 |
+
for a in argv:
|
| 30 |
+
orig_a = a
|
| 31 |
+
if not a.startswith("--"):
|
| 32 |
+
ret.append(a)
|
| 33 |
+
continue
|
| 34 |
+
a = a[2:]
|
| 35 |
+
i = a.find("=")
|
| 36 |
+
op = "="
|
| 37 |
+
if i == -1:
|
| 38 |
+
if a.startswith("no-"):
|
| 39 |
+
k = a[3:]
|
| 40 |
+
v = False
|
| 41 |
+
else:
|
| 42 |
+
k = a
|
| 43 |
+
v = True
|
| 44 |
+
else:
|
| 45 |
+
k = a[:i]
|
| 46 |
+
if k[-1] in "-+":
|
| 47 |
+
op = k[-1] + "=" # Ops is '-=' or '+=' now.
|
| 48 |
+
k = k[:-1]
|
| 49 |
+
v = a[i + 1 :]
|
| 50 |
+
ok = k
|
| 51 |
+
k = k.replace("-", "_")
|
| 52 |
+
if not hasattr(self, k):
|
| 53 |
+
if ignore_unknown is True or ok in ignore_unknown:
|
| 54 |
+
ret.append(orig_a)
|
| 55 |
+
continue
|
| 56 |
+
else:
|
| 57 |
+
raise self.UnknownOptionError("Unknown option '%s'" % a)
|
| 58 |
+
|
| 59 |
+
ov = getattr(self, k)
|
| 60 |
+
if isinstance(ov, bool):
|
| 61 |
+
v = bool(v)
|
| 62 |
+
elif isinstance(ov, int):
|
| 63 |
+
v = int(v)
|
| 64 |
+
elif isinstance(ov, list):
|
| 65 |
+
vv = v.split(",")
|
| 66 |
+
if vv == [""]:
|
| 67 |
+
vv = []
|
| 68 |
+
vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv]
|
| 69 |
+
if op == "=":
|
| 70 |
+
v = vv
|
| 71 |
+
elif op == "+=":
|
| 72 |
+
v = ov
|
| 73 |
+
v.extend(vv)
|
| 74 |
+
elif op == "-=":
|
| 75 |
+
v = ov
|
| 76 |
+
for x in vv:
|
| 77 |
+
if x in v:
|
| 78 |
+
v.remove(x)
|
| 79 |
+
else:
|
| 80 |
+
assert 0
|
| 81 |
+
|
| 82 |
+
opts[k] = v
|
| 83 |
+
self.set(**opts)
|
| 84 |
+
|
| 85 |
+
return ret
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/tables.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Behdad Esfahbod, Roozbeh Pournader
|
| 4 |
+
|
| 5 |
+
from fontTools import ttLib, cffLib
|
| 6 |
+
from fontTools.misc.psCharStrings import T2WidthExtractor
|
| 7 |
+
from fontTools.ttLib.tables.DefaultTable import DefaultTable
|
| 8 |
+
from fontTools.merge.base import add_method, mergeObjects
|
| 9 |
+
from fontTools.merge.cmap import computeMegaCmap
|
| 10 |
+
from fontTools.merge.util import *
|
| 11 |
+
import logging
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
log = logging.getLogger("fontTools.merge")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
ttLib.getTableClass("maxp").mergeMap = {
|
| 18 |
+
"*": max,
|
| 19 |
+
"tableTag": equal,
|
| 20 |
+
"tableVersion": equal,
|
| 21 |
+
"numGlyphs": sum,
|
| 22 |
+
"maxStorage": first,
|
| 23 |
+
"maxFunctionDefs": first,
|
| 24 |
+
"maxInstructionDefs": first,
|
| 25 |
+
# TODO When we correctly merge hinting data, update these values:
|
| 26 |
+
# maxFunctionDefs, maxInstructionDefs, maxSizeOfInstructions
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
headFlagsMergeBitMap = {
|
| 30 |
+
"size": 16,
|
| 31 |
+
"*": bitwise_or,
|
| 32 |
+
1: bitwise_and, # Baseline at y = 0
|
| 33 |
+
2: bitwise_and, # lsb at x = 0
|
| 34 |
+
3: bitwise_and, # Force ppem to integer values. FIXME?
|
| 35 |
+
5: bitwise_and, # Font is vertical
|
| 36 |
+
6: lambda bit: 0, # Always set to zero
|
| 37 |
+
11: bitwise_and, # Font data is 'lossless'
|
| 38 |
+
13: bitwise_and, # Optimized for ClearType
|
| 39 |
+
14: bitwise_and, # Last resort font. FIXME? equal or first may be better
|
| 40 |
+
15: lambda bit: 0, # Always set to zero
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
ttLib.getTableClass("head").mergeMap = {
|
| 44 |
+
"tableTag": equal,
|
| 45 |
+
"tableVersion": max,
|
| 46 |
+
"fontRevision": max,
|
| 47 |
+
"checkSumAdjustment": lambda lst: 0, # We need *something* here
|
| 48 |
+
"magicNumber": equal,
|
| 49 |
+
"flags": mergeBits(headFlagsMergeBitMap),
|
| 50 |
+
"unitsPerEm": equal,
|
| 51 |
+
"created": current_time,
|
| 52 |
+
"modified": current_time,
|
| 53 |
+
"xMin": min,
|
| 54 |
+
"yMin": min,
|
| 55 |
+
"xMax": max,
|
| 56 |
+
"yMax": max,
|
| 57 |
+
"macStyle": first,
|
| 58 |
+
"lowestRecPPEM": max,
|
| 59 |
+
"fontDirectionHint": lambda lst: 2,
|
| 60 |
+
"indexToLocFormat": first,
|
| 61 |
+
"glyphDataFormat": equal,
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
ttLib.getTableClass("hhea").mergeMap = {
|
| 65 |
+
"*": equal,
|
| 66 |
+
"tableTag": equal,
|
| 67 |
+
"tableVersion": max,
|
| 68 |
+
"ascent": max,
|
| 69 |
+
"descent": min,
|
| 70 |
+
"lineGap": max,
|
| 71 |
+
"advanceWidthMax": max,
|
| 72 |
+
"minLeftSideBearing": min,
|
| 73 |
+
"minRightSideBearing": min,
|
| 74 |
+
"xMaxExtent": max,
|
| 75 |
+
"caretSlopeRise": first,
|
| 76 |
+
"caretSlopeRun": first,
|
| 77 |
+
"caretOffset": first,
|
| 78 |
+
"numberOfHMetrics": recalculate,
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
ttLib.getTableClass("vhea").mergeMap = {
|
| 82 |
+
"*": equal,
|
| 83 |
+
"tableTag": equal,
|
| 84 |
+
"tableVersion": max,
|
| 85 |
+
"ascent": max,
|
| 86 |
+
"descent": min,
|
| 87 |
+
"lineGap": max,
|
| 88 |
+
"advanceHeightMax": max,
|
| 89 |
+
"minTopSideBearing": min,
|
| 90 |
+
"minBottomSideBearing": min,
|
| 91 |
+
"yMaxExtent": max,
|
| 92 |
+
"caretSlopeRise": first,
|
| 93 |
+
"caretSlopeRun": first,
|
| 94 |
+
"caretOffset": first,
|
| 95 |
+
"numberOfVMetrics": recalculate,
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
os2FsTypeMergeBitMap = {
|
| 99 |
+
"size": 16,
|
| 100 |
+
"*": lambda bit: 0,
|
| 101 |
+
1: bitwise_or, # no embedding permitted
|
| 102 |
+
2: bitwise_and, # allow previewing and printing documents
|
| 103 |
+
3: bitwise_and, # allow editing documents
|
| 104 |
+
8: bitwise_or, # no subsetting permitted
|
| 105 |
+
9: bitwise_or, # no embedding of outlines permitted
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def mergeOs2FsType(lst):
|
| 110 |
+
lst = list(lst)
|
| 111 |
+
if all(item == 0 for item in lst):
|
| 112 |
+
return 0
|
| 113 |
+
|
| 114 |
+
# Compute least restrictive logic for each fsType value
|
| 115 |
+
for i in range(len(lst)):
|
| 116 |
+
# unset bit 1 (no embedding permitted) if either bit 2 or 3 is set
|
| 117 |
+
if lst[i] & 0x000C:
|
| 118 |
+
lst[i] &= ~0x0002
|
| 119 |
+
# set bit 2 (allow previewing) if bit 3 is set (allow editing)
|
| 120 |
+
elif lst[i] & 0x0008:
|
| 121 |
+
lst[i] |= 0x0004
|
| 122 |
+
# set bits 2 and 3 if everything is allowed
|
| 123 |
+
elif lst[i] == 0:
|
| 124 |
+
lst[i] = 0x000C
|
| 125 |
+
|
| 126 |
+
fsType = mergeBits(os2FsTypeMergeBitMap)(lst)
|
| 127 |
+
# unset bits 2 and 3 if bit 1 is set (some font is "no embedding")
|
| 128 |
+
if fsType & 0x0002:
|
| 129 |
+
fsType &= ~0x000C
|
| 130 |
+
return fsType
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
ttLib.getTableClass("OS/2").mergeMap = {
|
| 134 |
+
"*": first,
|
| 135 |
+
"tableTag": equal,
|
| 136 |
+
"version": max,
|
| 137 |
+
"xAvgCharWidth": first, # Will be recalculated at the end on the merged font
|
| 138 |
+
"fsType": mergeOs2FsType, # Will be overwritten
|
| 139 |
+
"panose": first, # FIXME: should really be the first Latin font
|
| 140 |
+
"ulUnicodeRange1": bitwise_or,
|
| 141 |
+
"ulUnicodeRange2": bitwise_or,
|
| 142 |
+
"ulUnicodeRange3": bitwise_or,
|
| 143 |
+
"ulUnicodeRange4": bitwise_or,
|
| 144 |
+
"fsFirstCharIndex": min,
|
| 145 |
+
"fsLastCharIndex": max,
|
| 146 |
+
"sTypoAscender": max,
|
| 147 |
+
"sTypoDescender": min,
|
| 148 |
+
"sTypoLineGap": max,
|
| 149 |
+
"usWinAscent": max,
|
| 150 |
+
"usWinDescent": max,
|
| 151 |
+
# Version 1
|
| 152 |
+
"ulCodePageRange1": onlyExisting(bitwise_or),
|
| 153 |
+
"ulCodePageRange2": onlyExisting(bitwise_or),
|
| 154 |
+
# Version 2, 3, 4
|
| 155 |
+
"sxHeight": onlyExisting(max),
|
| 156 |
+
"sCapHeight": onlyExisting(max),
|
| 157 |
+
"usDefaultChar": onlyExisting(first),
|
| 158 |
+
"usBreakChar": onlyExisting(first),
|
| 159 |
+
"usMaxContext": onlyExisting(max),
|
| 160 |
+
# version 5
|
| 161 |
+
"usLowerOpticalPointSize": onlyExisting(min),
|
| 162 |
+
"usUpperOpticalPointSize": onlyExisting(max),
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@add_method(ttLib.getTableClass("OS/2"))
|
| 167 |
+
def merge(self, m, tables):
|
| 168 |
+
DefaultTable.merge(self, m, tables)
|
| 169 |
+
if self.version < 2:
|
| 170 |
+
# bits 8 and 9 are reserved and should be set to zero
|
| 171 |
+
self.fsType &= ~0x0300
|
| 172 |
+
if self.version >= 3:
|
| 173 |
+
# Only one of bits 1, 2, and 3 may be set. We already take
|
| 174 |
+
# care of bit 1 implications in mergeOs2FsType. So unset
|
| 175 |
+
# bit 2 if bit 3 is already set.
|
| 176 |
+
if self.fsType & 0x0008:
|
| 177 |
+
self.fsType &= ~0x0004
|
| 178 |
+
return self
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
ttLib.getTableClass("post").mergeMap = {
|
| 182 |
+
"*": first,
|
| 183 |
+
"tableTag": equal,
|
| 184 |
+
"formatType": max,
|
| 185 |
+
"isFixedPitch": min,
|
| 186 |
+
"minMemType42": max,
|
| 187 |
+
"maxMemType42": lambda lst: 0,
|
| 188 |
+
"minMemType1": max,
|
| 189 |
+
"maxMemType1": lambda lst: 0,
|
| 190 |
+
"mapping": onlyExisting(sumDicts),
|
| 191 |
+
"extraNames": lambda lst: [],
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
ttLib.getTableClass("vmtx").mergeMap = ttLib.getTableClass("hmtx").mergeMap = {
|
| 195 |
+
"tableTag": equal,
|
| 196 |
+
"metrics": sumDicts,
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
ttLib.getTableClass("name").mergeMap = {
|
| 200 |
+
"tableTag": equal,
|
| 201 |
+
"names": first, # FIXME? Does mixing name records make sense?
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
ttLib.getTableClass("loca").mergeMap = {
|
| 205 |
+
"*": recalculate,
|
| 206 |
+
"tableTag": equal,
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
ttLib.getTableClass("glyf").mergeMap = {
|
| 210 |
+
"tableTag": equal,
|
| 211 |
+
"glyphs": sumDicts,
|
| 212 |
+
"glyphOrder": sumLists,
|
| 213 |
+
"_reverseGlyphOrder": recalculate,
|
| 214 |
+
"axisTags": equal,
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@add_method(ttLib.getTableClass("glyf"))
|
| 219 |
+
def merge(self, m, tables):
|
| 220 |
+
for i, table in enumerate(tables):
|
| 221 |
+
for g in table.glyphs.values():
|
| 222 |
+
if i:
|
| 223 |
+
# Drop hints for all but first font, since
|
| 224 |
+
# we don't map functions / CVT values.
|
| 225 |
+
g.removeHinting()
|
| 226 |
+
# Expand composite glyphs to load their
|
| 227 |
+
# composite glyph names.
|
| 228 |
+
if g.isComposite():
|
| 229 |
+
g.expand(table)
|
| 230 |
+
return DefaultTable.merge(self, m, tables)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
ttLib.getTableClass("prep").mergeMap = lambda self, lst: first(lst)
|
| 234 |
+
ttLib.getTableClass("fpgm").mergeMap = lambda self, lst: first(lst)
|
| 235 |
+
ttLib.getTableClass("cvt ").mergeMap = lambda self, lst: first(lst)
|
| 236 |
+
ttLib.getTableClass("gasp").mergeMap = lambda self, lst: first(
|
| 237 |
+
lst
|
| 238 |
+
) # FIXME? Appears irreconcilable
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
@add_method(ttLib.getTableClass("CFF "))
|
| 242 |
+
def merge(self, m, tables):
|
| 243 |
+
if any(hasattr(table.cff[0], "FDSelect") for table in tables):
|
| 244 |
+
raise NotImplementedError("Merging CID-keyed CFF tables is not supported yet")
|
| 245 |
+
|
| 246 |
+
for table in tables:
|
| 247 |
+
table.cff.desubroutinize()
|
| 248 |
+
|
| 249 |
+
newcff = tables[0]
|
| 250 |
+
newfont = newcff.cff[0]
|
| 251 |
+
private = newfont.Private
|
| 252 |
+
newDefaultWidthX, newNominalWidthX = private.defaultWidthX, private.nominalWidthX
|
| 253 |
+
storedNamesStrings = []
|
| 254 |
+
glyphOrderStrings = []
|
| 255 |
+
glyphOrder = set(newfont.getGlyphOrder())
|
| 256 |
+
|
| 257 |
+
for name in newfont.strings.strings:
|
| 258 |
+
if name not in glyphOrder:
|
| 259 |
+
storedNamesStrings.append(name)
|
| 260 |
+
else:
|
| 261 |
+
glyphOrderStrings.append(name)
|
| 262 |
+
|
| 263 |
+
chrset = list(newfont.charset)
|
| 264 |
+
newcs = newfont.CharStrings
|
| 265 |
+
log.debug("FONT 0 CharStrings: %d.", len(newcs))
|
| 266 |
+
|
| 267 |
+
for i, table in enumerate(tables[1:], start=1):
|
| 268 |
+
font = table.cff[0]
|
| 269 |
+
defaultWidthX, nominalWidthX = (
|
| 270 |
+
font.Private.defaultWidthX,
|
| 271 |
+
font.Private.nominalWidthX,
|
| 272 |
+
)
|
| 273 |
+
widthsDiffer = (
|
| 274 |
+
defaultWidthX != newDefaultWidthX or nominalWidthX != newNominalWidthX
|
| 275 |
+
)
|
| 276 |
+
font.Private = private
|
| 277 |
+
fontGlyphOrder = set(font.getGlyphOrder())
|
| 278 |
+
for name in font.strings.strings:
|
| 279 |
+
if name in fontGlyphOrder:
|
| 280 |
+
glyphOrderStrings.append(name)
|
| 281 |
+
cs = font.CharStrings
|
| 282 |
+
gs = table.cff.GlobalSubrs
|
| 283 |
+
log.debug("Font %d CharStrings: %d.", i, len(cs))
|
| 284 |
+
chrset.extend(font.charset)
|
| 285 |
+
if newcs.charStringsAreIndexed:
|
| 286 |
+
for i, name in enumerate(cs.charStrings, start=len(newcs)):
|
| 287 |
+
newcs.charStrings[name] = i
|
| 288 |
+
newcs.charStringsIndex.items.append(None)
|
| 289 |
+
for name in cs.charStrings:
|
| 290 |
+
if widthsDiffer:
|
| 291 |
+
c = cs[name]
|
| 292 |
+
defaultWidthXToken = object()
|
| 293 |
+
extractor = T2WidthExtractor([], [], nominalWidthX, defaultWidthXToken)
|
| 294 |
+
extractor.execute(c)
|
| 295 |
+
width = extractor.width
|
| 296 |
+
if width is not defaultWidthXToken:
|
| 297 |
+
# The following will be wrong if the width is added
|
| 298 |
+
# by a subroutine. Ouch!
|
| 299 |
+
c.program.pop(0)
|
| 300 |
+
else:
|
| 301 |
+
width = defaultWidthX
|
| 302 |
+
if width != newDefaultWidthX:
|
| 303 |
+
c.program.insert(0, width - newNominalWidthX)
|
| 304 |
+
newcs[name] = cs[name]
|
| 305 |
+
|
| 306 |
+
newfont.charset = chrset
|
| 307 |
+
newfont.numGlyphs = len(chrset)
|
| 308 |
+
newfont.strings.strings = glyphOrderStrings + storedNamesStrings
|
| 309 |
+
|
| 310 |
+
return newcff
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@add_method(ttLib.getTableClass("cmap"))
|
| 314 |
+
def merge(self, m, tables):
|
| 315 |
+
# TODO Handle format=14.
|
| 316 |
+
if not hasattr(m, "cmap"):
|
| 317 |
+
computeMegaCmap(m, tables)
|
| 318 |
+
cmap = m.cmap
|
| 319 |
+
|
| 320 |
+
cmapBmpOnly = {uni: gid for uni, gid in cmap.items() if uni <= 0xFFFF}
|
| 321 |
+
self.tables = []
|
| 322 |
+
module = ttLib.getTableModule("cmap")
|
| 323 |
+
if len(cmapBmpOnly) != len(cmap):
|
| 324 |
+
# format-12 required.
|
| 325 |
+
cmapTable = module.cmap_classes[12](12)
|
| 326 |
+
cmapTable.platformID = 3
|
| 327 |
+
cmapTable.platEncID = 10
|
| 328 |
+
cmapTable.language = 0
|
| 329 |
+
cmapTable.cmap = cmap
|
| 330 |
+
self.tables.append(cmapTable)
|
| 331 |
+
# always create format-4
|
| 332 |
+
cmapTable = module.cmap_classes[4](4)
|
| 333 |
+
cmapTable.platformID = 3
|
| 334 |
+
cmapTable.platEncID = 1
|
| 335 |
+
cmapTable.language = 0
|
| 336 |
+
cmapTable.cmap = cmapBmpOnly
|
| 337 |
+
# ordered by platform then encoding
|
| 338 |
+
self.tables.insert(0, cmapTable)
|
| 339 |
+
self.tableVersion = 0
|
| 340 |
+
self.numSubTables = len(self.tables)
|
| 341 |
+
return self
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/merge/unicode.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 Behdad Esfahbod. All Rights Reserved.
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def is_Default_Ignorable(u):
|
| 5 |
+
# http://www.unicode.org/reports/tr44/#Default_Ignorable_Code_Point
|
| 6 |
+
#
|
| 7 |
+
# TODO Move me to unicodedata module and autogenerate.
|
| 8 |
+
#
|
| 9 |
+
# Unicode 14.0:
|
| 10 |
+
# $ grep '; Default_Ignorable_Code_Point ' DerivedCoreProperties.txt | sed 's/;.*#/#/'
|
| 11 |
+
# 00AD # Cf SOFT HYPHEN
|
| 12 |
+
# 034F # Mn COMBINING GRAPHEME JOINER
|
| 13 |
+
# 061C # Cf ARABIC LETTER MARK
|
| 14 |
+
# 115F..1160 # Lo [2] HANGUL CHOSEONG FILLER..HANGUL JUNGSEONG FILLER
|
| 15 |
+
# 17B4..17B5 # Mn [2] KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA
|
| 16 |
+
# 180B..180D # Mn [3] MONGOLIAN FREE VARIATION SELECTOR ONE..MONGOLIAN FREE VARIATION SELECTOR THREE
|
| 17 |
+
# 180E # Cf MONGOLIAN VOWEL SEPARATOR
|
| 18 |
+
# 180F # Mn MONGOLIAN FREE VARIATION SELECTOR FOUR
|
| 19 |
+
# 200B..200F # Cf [5] ZERO WIDTH SPACE..RIGHT-TO-LEFT MARK
|
| 20 |
+
# 202A..202E # Cf [5] LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE
|
| 21 |
+
# 2060..2064 # Cf [5] WORD JOINER..INVISIBLE PLUS
|
| 22 |
+
# 2065 # Cn <reserved-2065>
|
| 23 |
+
# 2066..206F # Cf [10] LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES
|
| 24 |
+
# 3164 # Lo HANGUL FILLER
|
| 25 |
+
# FE00..FE0F # Mn [16] VARIATION SELECTOR-1..VARIATION SELECTOR-16
|
| 26 |
+
# FEFF # Cf ZERO WIDTH NO-BREAK SPACE
|
| 27 |
+
# FFA0 # Lo HALFWIDTH HANGUL FILLER
|
| 28 |
+
# FFF0..FFF8 # Cn [9] <reserved-FFF0>..<reserved-FFF8>
|
| 29 |
+
# 1BCA0..1BCA3 # Cf [4] SHORTHAND FORMAT LETTER OVERLAP..SHORTHAND FORMAT UP STEP
|
| 30 |
+
# 1D173..1D17A # Cf [8] MUSICAL SYMBOL BEGIN BEAM..MUSICAL SYMBOL END PHRASE
|
| 31 |
+
# E0000 # Cn <reserved-E0000>
|
| 32 |
+
# E0001 # Cf LANGUAGE TAG
|
| 33 |
+
# E0002..E001F # Cn [30] <reserved-E0002>..<reserved-E001F>
|
| 34 |
+
# E0020..E007F # Cf [96] TAG SPACE..CANCEL TAG
|
| 35 |
+
# E0080..E00FF # Cn [128] <reserved-E0080>..<reserved-E00FF>
|
| 36 |
+
# E0100..E01EF # Mn [240] VARIATION SELECTOR-17..VARIATION SELECTOR-256
|
| 37 |
+
# E01F0..E0FFF # Cn [3600] <reserved-E01F0>..<reserved-E0FFF>
|
| 38 |
+
return (
|
| 39 |
+
u == 0x00AD
|
| 40 |
+
or u == 0x034F # Cf SOFT HYPHEN
|
| 41 |
+
or u == 0x061C # Mn COMBINING GRAPHEME JOINER
|
| 42 |
+
or 0x115F <= u <= 0x1160 # Cf ARABIC LETTER MARK
|
| 43 |
+
or 0x17B4 # Lo [2] HANGUL CHOSEONG FILLER..HANGUL JUNGSEONG FILLER
|
| 44 |
+
<= u
|
| 45 |
+
<= 0x17B5
|
| 46 |
+
or 0x180B # Mn [2] KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA
|
| 47 |
+
<= u
|
| 48 |
+
<= 0x180D
|
| 49 |
+
or u # Mn [3] MONGOLIAN FREE VARIATION SELECTOR ONE..MONGOLIAN FREE VARIATION SELECTOR THREE
|
| 50 |
+
== 0x180E
|
| 51 |
+
or u == 0x180F # Cf MONGOLIAN VOWEL SEPARATOR
|
| 52 |
+
or 0x200B <= u <= 0x200F # Mn MONGOLIAN FREE VARIATION SELECTOR FOUR
|
| 53 |
+
or 0x202A <= u <= 0x202E # Cf [5] ZERO WIDTH SPACE..RIGHT-TO-LEFT MARK
|
| 54 |
+
or 0x2060 # Cf [5] LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE
|
| 55 |
+
<= u
|
| 56 |
+
<= 0x2064
|
| 57 |
+
or u == 0x2065 # Cf [5] WORD JOINER..INVISIBLE PLUS
|
| 58 |
+
or 0x2066 <= u <= 0x206F # Cn <reserved-2065>
|
| 59 |
+
or u == 0x3164 # Cf [10] LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES
|
| 60 |
+
or 0xFE00 <= u <= 0xFE0F # Lo HANGUL FILLER
|
| 61 |
+
or u == 0xFEFF # Mn [16] VARIATION SELECTOR-1..VARIATION SELECTOR-16
|
| 62 |
+
or u == 0xFFA0 # Cf ZERO WIDTH NO-BREAK SPACE
|
| 63 |
+
or 0xFFF0 <= u <= 0xFFF8 # Lo HALFWIDTH HANGUL FILLER
|
| 64 |
+
or 0x1BCA0 <= u <= 0x1BCA3 # Cn [9] <reserved-FFF0>..<reserved-FFF8>
|
| 65 |
+
or 0x1D173 # Cf [4] SHORTHAND FORMAT LETTER OVERLAP..SHORTHAND FORMAT UP STEP
|
| 66 |
+
<= u
|
| 67 |
+
<= 0x1D17A
|
| 68 |
+
or u == 0xE0000 # Cf [8] MUSICAL SYMBOL BEGIN BEAM..MUSICAL SYMBOL END PHRASE
|
| 69 |
+
or u == 0xE0001 # Cn <reserved-E0000>
|
| 70 |
+
or 0xE0002 <= u <= 0xE001F # Cf LANGUAGE TAG
|
| 71 |
+
or 0xE0020 <= u <= 0xE007F # Cn [30] <reserved-E0002>..<reserved-E001F>
|
| 72 |
+
or 0xE0080 <= u <= 0xE00FF # Cf [96] TAG SPACE..CANCEL TAG
|
| 73 |
+
or 0xE0100 <= u <= 0xE01EF # Cn [128] <reserved-E0080>..<reserved-E00FF>
|
| 74 |
+
or 0xE01F0 # Mn [240] VARIATION SELECTOR-17..VARIATION SELECTOR-256
|
| 75 |
+
<= u
|
| 76 |
+
<= 0xE0FFF
|
| 77 |
+
or False # Cn [3600] <reserved-E01F0>..<reserved-E0FFF>
|
| 78 |
+
)
|