Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/README.md +68 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/__init__.py +49 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/accelerate.py +196 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/activations.py +240 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/activations_tf.py +147 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/added_tokens.json +28 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/all_results.json +13 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/aqlm.py +100 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/audio_utils.py +1193 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/auto.py +266 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/auto_factory.py +842 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/awq.py +498 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/backbone_utils.py +377 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/base.py +349 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/beam_constraints.py +524 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/beam_search.py +1013 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/bitnet.py +288 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/bitsandbytes.py +561 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/cache_utils.py +0 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/candidate_generator.py +1160 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/chat_template_utils.py +435 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/config.json +46 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/config.py +741 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_auto.py +1172 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_bert.py +154 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_encoder_decoder.py +111 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_qwen3.py +212 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_timm_backbone.py +86 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_utils.py +1632 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/constants.py +6 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/convert.py +460 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/convert_slow_tokenizer.py +1736 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/data_collator.py +0 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/debug_utils.py +346 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/deepspeed.py +498 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/dependency_versions_check.py +63 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/dependency_versions_table.py +107 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/deprecation.py +176 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/doc.py +1218 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/dynamic_module_utils.py +702 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/eetq.py +121 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/eval_results.json +8 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/executorch.py +408 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/fbgemm_fp8.py +284 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/feature_extraction_auto.py +408 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/feature_extraction_sequence_utils.py +371 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/feature_extraction_utils.py +701 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/features.py +749 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/file_utils.py +131 -0
- qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/finegrained_fp8.py +426 -0
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
license: other
|
| 4 |
+
base_model: /data/jrlin/HyperScale/.cache/model_specs/qwen3_hyp/qwen3/base/std/p047m
|
| 5 |
+
tags:
|
| 6 |
+
- llama-factory
|
| 7 |
+
- full
|
| 8 |
+
- generated_from_trainer
|
| 9 |
+
datasets:
|
| 10 |
+
- arrow
|
| 11 |
+
model-index:
|
| 12 |
+
- name: attempt3_20260310_043623
|
| 13 |
+
results: []
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
<!-- This model card has been generated automatically according to the information the Trainer had access to. You
|
| 17 |
+
should probably proofread and complete it, then remove this comment. -->
|
| 18 |
+
|
| 19 |
+
# attempt3_20260310_043623
|
| 20 |
+
|
| 21 |
+
This model is a fine-tuned version of [/data/jrlin/HyperScale/.cache/model_specs/qwen3_hyp/qwen3/base/std/p047m](https://huggingface.co//data/jrlin/HyperScale/.cache/model_specs/qwen3_hyp/qwen3/base/std/p047m) on the owt_local_train dataset.
|
| 22 |
+
It achieves the following results on the evaluation set:
|
| 23 |
+
- Loss: 8.2395
|
| 24 |
+
|
| 25 |
+
## Model description
|
| 26 |
+
|
| 27 |
+
More information needed
|
| 28 |
+
|
| 29 |
+
## Intended uses & limitations
|
| 30 |
+
|
| 31 |
+
More information needed
|
| 32 |
+
|
| 33 |
+
## Training and evaluation data
|
| 34 |
+
|
| 35 |
+
More information needed
|
| 36 |
+
|
| 37 |
+
## Training procedure
|
| 38 |
+
|
| 39 |
+
### Training hyperparameters
|
| 40 |
+
|
| 41 |
+
The following hyperparameters were used during training:
|
| 42 |
+
- learning_rate: 0.0001
|
| 43 |
+
- train_batch_size: 4
|
| 44 |
+
- eval_batch_size: 8
|
| 45 |
+
- seed: 42
|
| 46 |
+
- distributed_type: multi-GPU
|
| 47 |
+
- num_devices: 2
|
| 48 |
+
- gradient_accumulation_steps: 16
|
| 49 |
+
- total_train_batch_size: 128
|
| 50 |
+
- total_eval_batch_size: 16
|
| 51 |
+
- optimizer: Use adamw_torch with betas=(0.9,0.999) and epsilon=1e-08 and optimizer_args=No additional optimizer arguments
|
| 52 |
+
- lr_scheduler_type: cosine
|
| 53 |
+
- lr_scheduler_warmup_ratio: 0.02
|
| 54 |
+
- training_steps: 251
|
| 55 |
+
|
| 56 |
+
### Training results
|
| 57 |
+
|
| 58 |
+
| Training Loss | Epoch | Step | Validation Loss |
|
| 59 |
+
|:-------------:|:------:|:----:|:---------------:|
|
| 60 |
+
| 10.2462 | 0.0039 | 128 | 8.6207 |
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
### Framework versions
|
| 64 |
+
|
| 65 |
+
- Transformers 4.51.3
|
| 66 |
+
- Pytorch 2.5.1+cu124
|
| 67 |
+
- Datasets 3.6.0
|
| 68 |
+
- Tokenizers 0.21.4
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 _LazyModule
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_import_structure = {
|
| 21 |
+
"config": [
|
| 22 |
+
"EXTERNAL_DATA_FORMAT_SIZE_LIMIT",
|
| 23 |
+
"OnnxConfig",
|
| 24 |
+
"OnnxConfigWithPast",
|
| 25 |
+
"OnnxSeq2SeqConfigWithPast",
|
| 26 |
+
"PatchingSpec",
|
| 27 |
+
],
|
| 28 |
+
"convert": ["export", "validate_model_outputs"],
|
| 29 |
+
"features": ["FeaturesManager"],
|
| 30 |
+
"utils": ["ParameterFormat", "compute_serialized_parameters_size"],
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if TYPE_CHECKING:
|
| 35 |
+
from .config import (
|
| 36 |
+
EXTERNAL_DATA_FORMAT_SIZE_LIMIT,
|
| 37 |
+
OnnxConfig,
|
| 38 |
+
OnnxConfigWithPast,
|
| 39 |
+
OnnxSeq2SeqConfigWithPast,
|
| 40 |
+
PatchingSpec,
|
| 41 |
+
)
|
| 42 |
+
from .convert import export, validate_model_outputs
|
| 43 |
+
from .features import FeaturesManager
|
| 44 |
+
from .utils import ParameterFormat, compute_serialized_parameters_size
|
| 45 |
+
|
| 46 |
+
else:
|
| 47 |
+
import sys
|
| 48 |
+
|
| 49 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/accelerate.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 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 |
+
Since, https://github.com/huggingface/transformers/pull/36963, loading is always performed with models on meta
|
| 16 |
+
device. But since the `init_empty_weights` and `find_tied_parameters` functions are from accelerate, and accelerate is
|
| 17 |
+
somewhat still a soft dependency, we copy the functions here to be used natively in Transformers.
|
| 18 |
+
|
| 19 |
+
The `init_empty_weights` and `init_on_device` functions were copied from `accelerate.big_modeling.py`, and the
|
| 20 |
+
`find_tied_parameters` was copied from `accelerate.utils.modeling.py`
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from contextlib import contextmanager
|
| 24 |
+
|
| 25 |
+
from ..utils import is_torch_available, logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_torch_available():
|
| 29 |
+
import torch
|
| 30 |
+
import torch.nn as nn
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@contextmanager
|
| 37 |
+
def init_empty_weights(include_buffers: bool = False):
|
| 38 |
+
"""
|
| 39 |
+
A context manager under which models are initialized with all parameters on the meta device, therefore creating an
|
| 40 |
+
empty model. Useful when just initializing the model would blow the available RAM.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
include_buffers (`bool`, *optional*):
|
| 44 |
+
Whether or not to also put all buffers on the meta device while initializing.
|
| 45 |
+
|
| 46 |
+
Example:
|
| 47 |
+
|
| 48 |
+
```python
|
| 49 |
+
import torch.nn as nn
|
| 50 |
+
from accelerate import init_empty_weights
|
| 51 |
+
|
| 52 |
+
# Initialize a model with 100 billions parameters in no time and without using any RAM.
|
| 53 |
+
with init_empty_weights():
|
| 54 |
+
tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
<Tip warning={true}>
|
| 58 |
+
|
| 59 |
+
Any model created under this context manager has no weights. As such you can't do something like
|
| 60 |
+
`model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
|
| 61 |
+
Make sure to overwrite the default device_map param for [`load_checkpoint_and_dispatch`], otherwise dispatch is not
|
| 62 |
+
called.
|
| 63 |
+
|
| 64 |
+
</Tip>
|
| 65 |
+
"""
|
| 66 |
+
with init_on_device(torch.device("meta"), include_buffers=include_buffers) as f:
|
| 67 |
+
yield f
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@contextmanager
|
| 71 |
+
def init_on_device(device: "torch.device", include_buffers: bool = False):
|
| 72 |
+
"""
|
| 73 |
+
A context manager under which models are initialized with all parameters on the specified device.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
device (`torch.device`):
|
| 77 |
+
Device to initialize all parameters on.
|
| 78 |
+
include_buffers (`bool`, *optional*):
|
| 79 |
+
Whether or not to also put all buffers on the meta device while initializing.
|
| 80 |
+
|
| 81 |
+
Example:
|
| 82 |
+
|
| 83 |
+
```python
|
| 84 |
+
import torch.nn as nn
|
| 85 |
+
from accelerate import init_on_device
|
| 86 |
+
|
| 87 |
+
with init_on_device(device=torch.device("cuda")):
|
| 88 |
+
tst = nn.Linear(100, 100) # on `cuda` device
|
| 89 |
+
```
|
| 90 |
+
"""
|
| 91 |
+
if include_buffers:
|
| 92 |
+
with device:
|
| 93 |
+
yield
|
| 94 |
+
return
|
| 95 |
+
|
| 96 |
+
old_register_parameter = nn.Module.register_parameter
|
| 97 |
+
if include_buffers:
|
| 98 |
+
old_register_buffer = nn.Module.register_buffer
|
| 99 |
+
|
| 100 |
+
def register_empty_parameter(module, name, param):
|
| 101 |
+
old_register_parameter(module, name, param)
|
| 102 |
+
if param is not None:
|
| 103 |
+
param_cls = type(module._parameters[name])
|
| 104 |
+
kwargs = module._parameters[name].__dict__
|
| 105 |
+
kwargs["requires_grad"] = param.requires_grad
|
| 106 |
+
module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
|
| 107 |
+
|
| 108 |
+
def register_empty_buffer(module, name, buffer, persistent=True):
|
| 109 |
+
old_register_buffer(module, name, buffer, persistent=persistent)
|
| 110 |
+
if buffer is not None:
|
| 111 |
+
module._buffers[name] = module._buffers[name].to(device)
|
| 112 |
+
|
| 113 |
+
# Patch tensor creation
|
| 114 |
+
if include_buffers:
|
| 115 |
+
tensor_constructors_to_patch = {
|
| 116 |
+
torch_function_name: getattr(torch, torch_function_name)
|
| 117 |
+
for torch_function_name in ["empty", "zeros", "ones", "full"]
|
| 118 |
+
}
|
| 119 |
+
else:
|
| 120 |
+
tensor_constructors_to_patch = {}
|
| 121 |
+
|
| 122 |
+
def patch_tensor_constructor(fn):
|
| 123 |
+
def wrapper(*args, **kwargs):
|
| 124 |
+
kwargs["device"] = device
|
| 125 |
+
return fn(*args, **kwargs)
|
| 126 |
+
|
| 127 |
+
return wrapper
|
| 128 |
+
|
| 129 |
+
try:
|
| 130 |
+
nn.Module.register_parameter = register_empty_parameter
|
| 131 |
+
if include_buffers:
|
| 132 |
+
nn.Module.register_buffer = register_empty_buffer
|
| 133 |
+
for torch_function_name in tensor_constructors_to_patch.keys():
|
| 134 |
+
setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
|
| 135 |
+
yield
|
| 136 |
+
finally:
|
| 137 |
+
nn.Module.register_parameter = old_register_parameter
|
| 138 |
+
if include_buffers:
|
| 139 |
+
nn.Module.register_buffer = old_register_buffer
|
| 140 |
+
for torch_function_name, old_torch_function in tensor_constructors_to_patch.items():
|
| 141 |
+
setattr(torch, torch_function_name, old_torch_function)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def find_tied_parameters(model: "nn.Module", **kwargs):
|
| 145 |
+
"""
|
| 146 |
+
Find the tied parameters in a given model.
|
| 147 |
+
|
| 148 |
+
<Tip warning={true}>
|
| 149 |
+
|
| 150 |
+
The signature accepts keyword arguments, but they are for the recursive part of this function and you should ignore
|
| 151 |
+
them.
|
| 152 |
+
|
| 153 |
+
</Tip>
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
model (`torch.nn.Module`): The model to inspect.
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
List[List[str]]: A list of lists of parameter names being all tied together.
|
| 160 |
+
|
| 161 |
+
Example:
|
| 162 |
+
|
| 163 |
+
```py
|
| 164 |
+
>>> from collections import OrderedDict
|
| 165 |
+
>>> import torch.nn as nn
|
| 166 |
+
|
| 167 |
+
>>> model = nn.Sequential(OrderedDict([("linear1", nn.Linear(4, 4)), ("linear2", nn.Linear(4, 4))]))
|
| 168 |
+
>>> model.linear2.weight = model.linear1.weight
|
| 169 |
+
>>> find_tied_parameters(model)
|
| 170 |
+
[['linear1.weight', 'linear2.weight']]
|
| 171 |
+
```
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
# get ALL model parameters and thier names
|
| 175 |
+
all_named_parameters = dict(model.named_parameters(remove_duplicate=False))
|
| 176 |
+
|
| 177 |
+
# get ONLY unique named parameters,
|
| 178 |
+
# if parameter is tied and have multiple names, it will be included only once
|
| 179 |
+
no_duplicate_named_parameters = dict(model.named_parameters(remove_duplicate=True))
|
| 180 |
+
|
| 181 |
+
# the difference of the two sets will give us the tied parameters
|
| 182 |
+
tied_param_names = set(all_named_parameters.keys()) - set(no_duplicate_named_parameters.keys())
|
| 183 |
+
|
| 184 |
+
# 'tied_param_names' contains the names of parameters that are tied in the model, but we do not know
|
| 185 |
+
# which names refer to the same parameter. To identify this, we need to group them together.
|
| 186 |
+
tied_param_groups = {}
|
| 187 |
+
for tied_param_name in tied_param_names:
|
| 188 |
+
tied_param = all_named_parameters[tied_param_name]
|
| 189 |
+
for param_name, param in no_duplicate_named_parameters.items():
|
| 190 |
+
# compare if parameters are the same, if so, group thier names together
|
| 191 |
+
if param is tied_param:
|
| 192 |
+
if param_name not in tied_param_groups:
|
| 193 |
+
tied_param_groups[param_name] = []
|
| 194 |
+
tied_param_groups[param_name].append(tied_param_name)
|
| 195 |
+
|
| 196 |
+
return [sorted([weight] + list(set(tied))) for weight, tied in tied_param_groups.items()]
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/activations.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 math
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from packaging import version
|
| 20 |
+
from torch import Tensor, nn
|
| 21 |
+
|
| 22 |
+
from .utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class PytorchGELUTanh(nn.Module):
|
| 29 |
+
"""
|
| 30 |
+
A fast C implementation of the tanh approximation of the GeLU activation function. See
|
| 31 |
+
https://arxiv.org/abs/1606.08415.
|
| 32 |
+
|
| 33 |
+
This implementation is equivalent to NewGELU and FastGELU but much faster. However, it is not an exact numerical
|
| 34 |
+
match due to rounding errors.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self):
|
| 38 |
+
super().__init__()
|
| 39 |
+
if version.parse(torch.__version__) < version.parse("1.12.0"):
|
| 40 |
+
raise ImportError(
|
| 41 |
+
f"You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use "
|
| 42 |
+
"PytorchGELUTanh. Please upgrade torch."
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 46 |
+
return nn.functional.gelu(input, approximate="tanh")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class NewGELUActivation(nn.Module):
|
| 50 |
+
"""
|
| 51 |
+
Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see
|
| 52 |
+
the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 56 |
+
return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(input, 3.0))))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class GELUActivation(nn.Module):
|
| 60 |
+
"""
|
| 61 |
+
Original Implementation of the GELU activation function in Google BERT repo when initially created. For
|
| 62 |
+
information: OpenAI GPT's GELU is slightly different (and gives slightly different results): 0.5 * x * (1 +
|
| 63 |
+
torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) This is now written in C in nn.functional
|
| 64 |
+
Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(self, use_gelu_python: bool = False):
|
| 68 |
+
super().__init__()
|
| 69 |
+
if use_gelu_python:
|
| 70 |
+
self.act = self._gelu_python
|
| 71 |
+
else:
|
| 72 |
+
self.act = nn.functional.gelu
|
| 73 |
+
|
| 74 |
+
def _gelu_python(self, input: Tensor) -> Tensor:
|
| 75 |
+
return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0)))
|
| 76 |
+
|
| 77 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 78 |
+
return self.act(input)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class FastGELUActivation(nn.Module):
|
| 82 |
+
"""
|
| 83 |
+
Applies GELU approximation that is slower than QuickGELU but more accurate. See: https://github.com/hendrycks/GELUs
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 87 |
+
return 0.5 * input * (1.0 + torch.tanh(input * 0.7978845608 * (1.0 + 0.044715 * input * input)))
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class QuickGELUActivation(nn.Module):
|
| 91 |
+
"""
|
| 92 |
+
Applies GELU approximation that is fast but somewhat inaccurate. See: https://github.com/hendrycks/GELUs
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 96 |
+
return input * torch.sigmoid(1.702 * input)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class ClippedGELUActivation(nn.Module):
|
| 100 |
+
"""
|
| 101 |
+
Clip the range of possible GeLU outputs between [min, max]. This is especially useful for quantization purpose, as
|
| 102 |
+
it allows mapping negatives values in the GeLU spectrum. For more information on this trick, please refer to
|
| 103 |
+
https://arxiv.org/abs/2004.09602.
|
| 104 |
+
|
| 105 |
+
Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when
|
| 106 |
+
initially created.
|
| 107 |
+
|
| 108 |
+
For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 +
|
| 109 |
+
torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))). See https://arxiv.org/abs/1606.08415
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, min: float, max: float):
|
| 113 |
+
if min > max:
|
| 114 |
+
raise ValueError(f"min should be < max (got min: {min}, max: {max})")
|
| 115 |
+
|
| 116 |
+
super().__init__()
|
| 117 |
+
self.min = min
|
| 118 |
+
self.max = max
|
| 119 |
+
|
| 120 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 121 |
+
return torch.clip(gelu(x), self.min, self.max)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class AccurateGELUActivation(nn.Module):
|
| 125 |
+
"""
|
| 126 |
+
Applies GELU approximation that is faster than default and more accurate than QuickGELU. See:
|
| 127 |
+
https://github.com/hendrycks/GELUs
|
| 128 |
+
|
| 129 |
+
Implemented along with MEGA (Moving Average Equipped Gated Attention)
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
def __init__(self):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.precomputed_constant = math.sqrt(2 / math.pi)
|
| 135 |
+
|
| 136 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 137 |
+
return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044715 * torch.pow(input, 3))))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class MishActivation(nn.Module):
|
| 141 |
+
"""
|
| 142 |
+
See Mish: A Self-Regularized Non-Monotonic Activation Function (Misra., https://arxiv.org/abs/1908.08681). Also
|
| 143 |
+
visit the official repository for the paper: https://github.com/digantamisra98/Mish
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
def __init__(self):
|
| 147 |
+
super().__init__()
|
| 148 |
+
if version.parse(torch.__version__) < version.parse("1.9.0"):
|
| 149 |
+
self.act = self._mish_python
|
| 150 |
+
else:
|
| 151 |
+
self.act = nn.functional.mish
|
| 152 |
+
|
| 153 |
+
def _mish_python(self, input: Tensor) -> Tensor:
|
| 154 |
+
return input * torch.tanh(nn.functional.softplus(input))
|
| 155 |
+
|
| 156 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 157 |
+
return self.act(input)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class LinearActivation(nn.Module):
|
| 161 |
+
"""
|
| 162 |
+
Applies the linear activation function, i.e. forwarding input directly to output.
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 166 |
+
return input
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class LaplaceActivation(nn.Module):
|
| 170 |
+
"""
|
| 171 |
+
Applies elementwise activation based on Laplace function, introduced in MEGA as an attention activation. See
|
| 172 |
+
https://arxiv.org/abs/2209.10655
|
| 173 |
+
|
| 174 |
+
Inspired by squared relu, but with bounded range and gradient for better stability
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
def forward(self, input, mu=0.707107, sigma=0.282095):
|
| 178 |
+
input = (input - mu).div(sigma * math.sqrt(2.0))
|
| 179 |
+
return 0.5 * (1.0 + torch.erf(input))
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class ReLUSquaredActivation(nn.Module):
|
| 183 |
+
"""
|
| 184 |
+
Applies the relu^2 activation introduced in https://arxiv.org/abs/2109.08668v2
|
| 185 |
+
"""
|
| 186 |
+
|
| 187 |
+
def forward(self, input):
|
| 188 |
+
relu_applied = nn.functional.relu(input)
|
| 189 |
+
squared = torch.square(relu_applied)
|
| 190 |
+
return squared
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class ClassInstantier(OrderedDict):
|
| 194 |
+
def __getitem__(self, key):
|
| 195 |
+
content = super().__getitem__(key)
|
| 196 |
+
cls, kwargs = content if isinstance(content, tuple) else (content, {})
|
| 197 |
+
return cls(**kwargs)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
ACT2CLS = {
|
| 201 |
+
"gelu": GELUActivation,
|
| 202 |
+
"gelu_10": (ClippedGELUActivation, {"min": -10, "max": 10}),
|
| 203 |
+
"gelu_fast": FastGELUActivation,
|
| 204 |
+
"gelu_new": NewGELUActivation,
|
| 205 |
+
"gelu_python": (GELUActivation, {"use_gelu_python": True}),
|
| 206 |
+
"gelu_pytorch_tanh": PytorchGELUTanh,
|
| 207 |
+
"gelu_accurate": AccurateGELUActivation,
|
| 208 |
+
"laplace": LaplaceActivation,
|
| 209 |
+
"leaky_relu": nn.LeakyReLU,
|
| 210 |
+
"linear": LinearActivation,
|
| 211 |
+
"mish": MishActivation,
|
| 212 |
+
"quick_gelu": QuickGELUActivation,
|
| 213 |
+
"relu": nn.ReLU,
|
| 214 |
+
"relu2": ReLUSquaredActivation,
|
| 215 |
+
"relu6": nn.ReLU6,
|
| 216 |
+
"sigmoid": nn.Sigmoid,
|
| 217 |
+
"silu": nn.SiLU,
|
| 218 |
+
"swish": nn.SiLU,
|
| 219 |
+
"tanh": nn.Tanh,
|
| 220 |
+
"prelu": nn.PReLU,
|
| 221 |
+
}
|
| 222 |
+
ACT2FN = ClassInstantier(ACT2CLS)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def get_activation(activation_string):
|
| 226 |
+
if activation_string in ACT2FN:
|
| 227 |
+
return ACT2FN[activation_string]
|
| 228 |
+
else:
|
| 229 |
+
raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACT2FN.keys())}")
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
# For backwards compatibility with: from activations import gelu_python
|
| 233 |
+
gelu_python = get_activation("gelu_python")
|
| 234 |
+
gelu_new = get_activation("gelu_new")
|
| 235 |
+
gelu = get_activation("gelu")
|
| 236 |
+
gelu_fast = get_activation("gelu_fast")
|
| 237 |
+
quick_gelu = get_activation("quick_gelu")
|
| 238 |
+
silu = get_activation("silu")
|
| 239 |
+
mish = get_activation("mish")
|
| 240 |
+
linear_act = get_activation("linear")
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/activations_tf.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 math
|
| 16 |
+
|
| 17 |
+
import tensorflow as tf
|
| 18 |
+
from packaging.version import parse
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
import tf_keras as keras
|
| 23 |
+
except (ModuleNotFoundError, ImportError):
|
| 24 |
+
import keras
|
| 25 |
+
|
| 26 |
+
if parse(keras.__version__).major > 2:
|
| 27 |
+
raise ValueError(
|
| 28 |
+
"Your currently installed version of Keras is Keras 3, but this is not yet supported in "
|
| 29 |
+
"Transformers. Please install the backwards-compatible tf-keras package with "
|
| 30 |
+
"`pip install tf-keras`."
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _gelu(x):
|
| 35 |
+
"""
|
| 36 |
+
Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when
|
| 37 |
+
initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
|
| 38 |
+
0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see
|
| 39 |
+
https://arxiv.org/abs/1606.08415
|
| 40 |
+
"""
|
| 41 |
+
x = tf.convert_to_tensor(x)
|
| 42 |
+
cdf = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0), x.dtype)))
|
| 43 |
+
|
| 44 |
+
return x * cdf
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _gelu_new(x):
|
| 48 |
+
"""
|
| 49 |
+
Gaussian Error Linear Unit. This is a smoother version of the GELU. Original paper: https://arxiv.org/abs/1606.0841
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
x: float Tensor to perform activation
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
`x` with the GELU activation applied.
|
| 56 |
+
"""
|
| 57 |
+
x = tf.convert_to_tensor(x)
|
| 58 |
+
pi = tf.cast(math.pi, x.dtype)
|
| 59 |
+
coeff = tf.cast(0.044715, x.dtype)
|
| 60 |
+
cdf = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi) * (x + coeff * tf.pow(x, 3))))
|
| 61 |
+
|
| 62 |
+
return x * cdf
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def mish(x):
|
| 66 |
+
x = tf.convert_to_tensor(x)
|
| 67 |
+
|
| 68 |
+
return x * tf.tanh(tf.math.softplus(x))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def gelu_fast(x):
|
| 72 |
+
x = tf.convert_to_tensor(x)
|
| 73 |
+
coeff1 = tf.cast(0.044715, x.dtype)
|
| 74 |
+
coeff2 = tf.cast(0.7978845608, x.dtype)
|
| 75 |
+
|
| 76 |
+
return 0.5 * x * (1.0 + tf.tanh(x * coeff2 * (1.0 + coeff1 * x * x)))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def quick_gelu(x):
|
| 80 |
+
x = tf.convert_to_tensor(x)
|
| 81 |
+
coeff = tf.cast(1.702, x.dtype)
|
| 82 |
+
return x * tf.math.sigmoid(coeff * x)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def gelu_10(x):
|
| 86 |
+
"""
|
| 87 |
+
Clip the range of possible GeLU outputs between [-10, 10]. This is especially useful for quantization purpose, as
|
| 88 |
+
it allows mapping 2 negatives values in the GeLU spectrum. For more information on this trick, please refer to
|
| 89 |
+
https://arxiv.org/abs/2004.09602
|
| 90 |
+
|
| 91 |
+
Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when
|
| 92 |
+
initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
|
| 93 |
+
0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see
|
| 94 |
+
https://arxiv.org/abs/1606.08415 :param x: :return:
|
| 95 |
+
"""
|
| 96 |
+
return tf.clip_by_value(_gelu(x), -10, 10)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def glu(x, axis=-1):
|
| 100 |
+
"""
|
| 101 |
+
Gated Linear Unit. Implementation as defined in the original paper (see https://arxiv.org/abs/1612.08083), where
|
| 102 |
+
the input `x` is split in two halves across a dimension (`axis`), A and B, returning A * sigmoid(B).
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
`x`: float Tensor to perform activation
|
| 106 |
+
`axis`: dimension across which `x` be split in half
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
`x` with the GLU activation applied (with its size halved across the dimension `axis`).
|
| 110 |
+
"""
|
| 111 |
+
a, b = tf.split(x, 2, axis=axis)
|
| 112 |
+
return a * tf.math.sigmoid(b)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if parse(tf.version.VERSION) >= parse("2.4"):
|
| 116 |
+
|
| 117 |
+
def approximate_gelu_wrap(x):
|
| 118 |
+
return keras.activations.gelu(x, approximate=True)
|
| 119 |
+
|
| 120 |
+
gelu = keras.activations.gelu
|
| 121 |
+
gelu_new = approximate_gelu_wrap
|
| 122 |
+
else:
|
| 123 |
+
gelu = _gelu
|
| 124 |
+
gelu_new = _gelu_new
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
ACT2FN = {
|
| 128 |
+
"gelu": gelu,
|
| 129 |
+
"gelu_10": gelu_10,
|
| 130 |
+
"gelu_fast": gelu_fast,
|
| 131 |
+
"gelu_new": gelu_new,
|
| 132 |
+
"glu": glu,
|
| 133 |
+
"mish": mish,
|
| 134 |
+
"quick_gelu": quick_gelu,
|
| 135 |
+
"relu": keras.activations.relu,
|
| 136 |
+
"sigmoid": keras.activations.sigmoid,
|
| 137 |
+
"silu": keras.activations.swish,
|
| 138 |
+
"swish": keras.activations.swish,
|
| 139 |
+
"tanh": keras.activations.tanh,
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def get_tf_activation(activation_string):
|
| 144 |
+
if activation_string in ACT2FN:
|
| 145 |
+
return ACT2FN[activation_string]
|
| 146 |
+
else:
|
| 147 |
+
raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACT2FN.keys())}")
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/added_tokens.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"</think>": 151668,
|
| 3 |
+
"</tool_call>": 151658,
|
| 4 |
+
"</tool_response>": 151666,
|
| 5 |
+
"<think>": 151667,
|
| 6 |
+
"<tool_call>": 151657,
|
| 7 |
+
"<tool_response>": 151665,
|
| 8 |
+
"<|box_end|>": 151649,
|
| 9 |
+
"<|box_start|>": 151648,
|
| 10 |
+
"<|endoftext|>": 151643,
|
| 11 |
+
"<|file_sep|>": 151664,
|
| 12 |
+
"<|fim_middle|>": 151660,
|
| 13 |
+
"<|fim_pad|>": 151662,
|
| 14 |
+
"<|fim_prefix|>": 151659,
|
| 15 |
+
"<|fim_suffix|>": 151661,
|
| 16 |
+
"<|im_end|>": 151645,
|
| 17 |
+
"<|im_start|>": 151644,
|
| 18 |
+
"<|image_pad|>": 151655,
|
| 19 |
+
"<|object_ref_end|>": 151647,
|
| 20 |
+
"<|object_ref_start|>": 151646,
|
| 21 |
+
"<|quad_end|>": 151651,
|
| 22 |
+
"<|quad_start|>": 151650,
|
| 23 |
+
"<|repo_name|>": 151663,
|
| 24 |
+
"<|video_pad|>": 151656,
|
| 25 |
+
"<|vision_end|>": 151653,
|
| 26 |
+
"<|vision_pad|>": 151654,
|
| 27 |
+
"<|vision_start|>": 151652
|
| 28 |
+
}
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/all_results.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"epoch": 0.007551029617484695,
|
| 3 |
+
"eval_loss": 8.239520072937012,
|
| 4 |
+
"eval_perplexity": 3787.722041573,
|
| 5 |
+
"eval_runtime": 9.0399,
|
| 6 |
+
"eval_samples_per_second": 468.808,
|
| 7 |
+
"eval_steps_per_second": 29.314,
|
| 8 |
+
"total_flos": 3107272607662080.0,
|
| 9 |
+
"train_loss": 9.145651889512264,
|
| 10 |
+
"train_runtime": 257.6976,
|
| 11 |
+
"train_samples_per_second": 124.673,
|
| 12 |
+
"train_steps_per_second": 0.974
|
| 13 |
+
}
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/aqlm.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
"AQLM (Additive Quantization of Language Model) integration file"
|
| 15 |
+
|
| 16 |
+
from ..utils import ACCELERATE_MIN_VERSION, is_accelerate_available, is_aqlm_available, is_torch_available
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if is_torch_available():
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def replace_with_aqlm_linear(
|
| 24 |
+
model,
|
| 25 |
+
quantization_config=None,
|
| 26 |
+
linear_weights_not_to_quantize=None,
|
| 27 |
+
current_key_name=None,
|
| 28 |
+
has_been_replaced=False,
|
| 29 |
+
):
|
| 30 |
+
"""
|
| 31 |
+
Public method that recursively replaces the Linear layers of the given model with AQLM quantized layers.
|
| 32 |
+
`accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the
|
| 33 |
+
conversion has been successfull or not.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
model (`torch.nn.Module`):
|
| 37 |
+
The model to convert, can be any `torch.nn.Module` instance.
|
| 38 |
+
quantization_config (`AqlmConfig`):
|
| 39 |
+
The quantization config object that contains the quantization parameters.
|
| 40 |
+
linear_weights_not_to_quantize (`list[str]`, *optional*):
|
| 41 |
+
A list of nn.Linear weights to not convert. If a parameter path is in the list (e.g. `lm_head.weight`), the corresponding module will not be
|
| 42 |
+
converted.
|
| 43 |
+
current_key_name (`list`, *optional*):
|
| 44 |
+
A list that contains the current key name. This is used for recursion and should not be passed by the user.
|
| 45 |
+
has_been_replaced (`bool`, *optional*):
|
| 46 |
+
A boolean that indicates if the conversion has been successful or not. This is used for recursion and
|
| 47 |
+
should not be passed by the user.
|
| 48 |
+
"""
|
| 49 |
+
if not is_aqlm_available():
|
| 50 |
+
raise ValueError("AQLM is not available. Please install it with `pip install aqlm[cpu,gpu]`")
|
| 51 |
+
|
| 52 |
+
if not is_accelerate_available():
|
| 53 |
+
raise ValueError(
|
| 54 |
+
f"AQLM requires Accelerate to be installed: `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
if linear_weights_not_to_quantize is None:
|
| 58 |
+
linear_weights_not_to_quantize = []
|
| 59 |
+
|
| 60 |
+
from accelerate import init_empty_weights
|
| 61 |
+
from aqlm import QuantizedLinear
|
| 62 |
+
|
| 63 |
+
for name, module in model.named_children():
|
| 64 |
+
if current_key_name is None:
|
| 65 |
+
current_key_name = []
|
| 66 |
+
current_key_name.append(name)
|
| 67 |
+
|
| 68 |
+
if isinstance(module, nn.Linear):
|
| 69 |
+
# Check if the current key is not in the `linear_weights_not_to_quantize`
|
| 70 |
+
if ".".join(current_key_name) + ".weight" not in linear_weights_not_to_quantize:
|
| 71 |
+
with init_empty_weights():
|
| 72 |
+
in_features = module.in_features
|
| 73 |
+
out_features = module.out_features
|
| 74 |
+
|
| 75 |
+
model._modules[name] = QuantizedLinear(
|
| 76 |
+
in_features,
|
| 77 |
+
out_features,
|
| 78 |
+
bias=module.bias is not None,
|
| 79 |
+
in_group_size=quantization_config.in_group_size,
|
| 80 |
+
out_group_size=quantization_config.out_group_size,
|
| 81 |
+
num_codebooks=quantization_config.num_codebooks,
|
| 82 |
+
nbits_per_codebook=quantization_config.nbits_per_codebook,
|
| 83 |
+
)
|
| 84 |
+
has_been_replaced = True
|
| 85 |
+
|
| 86 |
+
# Store the module class in case we need to transpose the weight later
|
| 87 |
+
model._modules[name].source_cls = type(module)
|
| 88 |
+
# Force requires grad to False to avoid unexpected errors
|
| 89 |
+
model._modules[name].requires_grad_(False)
|
| 90 |
+
if len(list(module.children())) > 0:
|
| 91 |
+
_, has_been_replaced = replace_with_aqlm_linear(
|
| 92 |
+
module,
|
| 93 |
+
quantization_config=quantization_config,
|
| 94 |
+
linear_weights_not_to_quantize=linear_weights_not_to_quantize,
|
| 95 |
+
current_key_name=current_key_name,
|
| 96 |
+
has_been_replaced=has_been_replaced,
|
| 97 |
+
)
|
| 98 |
+
# Remove the last key for recursion
|
| 99 |
+
current_key_name.pop(-1)
|
| 100 |
+
return model, has_been_replaced
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/audio_utils.py
ADDED
|
@@ -0,0 +1,1193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Inc. team and the librosa & torchaudio authors.
|
| 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 |
+
Audio processing functions to extract features from audio waveforms. This code is pure numpy to support all frameworks
|
| 16 |
+
and remove unnecessary dependencies.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
import warnings
|
| 21 |
+
from io import BytesIO
|
| 22 |
+
from typing import List, Optional, Tuple, Union
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import requests
|
| 26 |
+
|
| 27 |
+
from .utils import is_librosa_available, requires_backends
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_librosa_available():
|
| 31 |
+
import librosa
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def load_audio(audio: Union[str, np.ndarray], sampling_rate=16000, timeout=None) -> np.ndarray:
|
| 35 |
+
"""
|
| 36 |
+
Loads `audio` to an np.ndarray object.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
audio (`str` or `np.ndarray`):
|
| 40 |
+
The audio to be laoded to the numpy array format.
|
| 41 |
+
sampling_rate (`int`, *optional*, defaults to 16000):
|
| 42 |
+
The samlping rate to be used when loading the audio. It should be same as the
|
| 43 |
+
sampling rate the model you will be using further was trained with.
|
| 44 |
+
timeout (`float`, *optional*):
|
| 45 |
+
The timeout value in seconds for the URL request.
|
| 46 |
+
|
| 47 |
+
Returns:
|
| 48 |
+
`np.ndarray`: A numpy artay representing the audio.
|
| 49 |
+
"""
|
| 50 |
+
requires_backends(load_audio, ["librosa"])
|
| 51 |
+
|
| 52 |
+
if isinstance(audio, str):
|
| 53 |
+
# Load audio from URL (e.g https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/translate_to_chinese.wav)
|
| 54 |
+
if audio.startswith("http://") or audio.startswith("https://"):
|
| 55 |
+
audio = librosa.load(BytesIO(requests.get(audio, timeout=timeout).content), sr=sampling_rate)[0]
|
| 56 |
+
elif os.path.isfile(audio):
|
| 57 |
+
audio = librosa.load(audio, sr=sampling_rate)[0]
|
| 58 |
+
elif isinstance(audio, np.ndarray):
|
| 59 |
+
audio = audio
|
| 60 |
+
else:
|
| 61 |
+
raise TypeError(
|
| 62 |
+
"Incorrect format used for `audio`. Should be an url linking to an audio, a local path, or numpy array."
|
| 63 |
+
)
|
| 64 |
+
return audio
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
AudioInput = Union[
|
| 68 |
+
np.ndarray, "torch.Tensor", List[np.ndarray], Tuple[np.ndarray], List["torch.Tensor"], Tuple["torch.Tensor"] # noqa: F821
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def hertz_to_mel(freq: Union[float, np.ndarray], mel_scale: str = "htk") -> Union[float, np.ndarray]:
|
| 73 |
+
"""
|
| 74 |
+
Convert frequency from hertz to mels.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
freq (`float` or `np.ndarray`):
|
| 78 |
+
The frequency, or multiple frequencies, in hertz (Hz).
|
| 79 |
+
mel_scale (`str`, *optional*, defaults to `"htk"`):
|
| 80 |
+
The mel frequency scale to use, `"htk"`, `"kaldi"` or `"slaney"`.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
`float` or `np.ndarray`: The frequencies on the mel scale.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
if mel_scale not in ["slaney", "htk", "kaldi"]:
|
| 87 |
+
raise ValueError('mel_scale should be one of "htk", "slaney" or "kaldi".')
|
| 88 |
+
|
| 89 |
+
if mel_scale == "htk":
|
| 90 |
+
return 2595.0 * np.log10(1.0 + (freq / 700.0))
|
| 91 |
+
elif mel_scale == "kaldi":
|
| 92 |
+
return 1127.0 * np.log(1.0 + (freq / 700.0))
|
| 93 |
+
|
| 94 |
+
min_log_hertz = 1000.0
|
| 95 |
+
min_log_mel = 15.0
|
| 96 |
+
logstep = 27.0 / np.log(6.4)
|
| 97 |
+
mels = 3.0 * freq / 200.0
|
| 98 |
+
|
| 99 |
+
if isinstance(freq, np.ndarray):
|
| 100 |
+
log_region = freq >= min_log_hertz
|
| 101 |
+
mels[log_region] = min_log_mel + np.log(freq[log_region] / min_log_hertz) * logstep
|
| 102 |
+
elif freq >= min_log_hertz:
|
| 103 |
+
mels = min_log_mel + np.log(freq / min_log_hertz) * logstep
|
| 104 |
+
|
| 105 |
+
return mels
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def mel_to_hertz(mels: Union[float, np.ndarray], mel_scale: str = "htk") -> Union[float, np.ndarray]:
|
| 109 |
+
"""
|
| 110 |
+
Convert frequency from mels to hertz.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
mels (`float` or `np.ndarray`):
|
| 114 |
+
The frequency, or multiple frequencies, in mels.
|
| 115 |
+
mel_scale (`str`, *optional*, `"htk"`):
|
| 116 |
+
The mel frequency scale to use, `"htk"`, `"kaldi"` or `"slaney"`.
|
| 117 |
+
|
| 118 |
+
Returns:
|
| 119 |
+
`float` or `np.ndarray`: The frequencies in hertz.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
if mel_scale not in ["slaney", "htk", "kaldi"]:
|
| 123 |
+
raise ValueError('mel_scale should be one of "htk", "slaney" or "kaldi".')
|
| 124 |
+
|
| 125 |
+
if mel_scale == "htk":
|
| 126 |
+
return 700.0 * (np.power(10, mels / 2595.0) - 1.0)
|
| 127 |
+
elif mel_scale == "kaldi":
|
| 128 |
+
return 700.0 * (np.exp(mels / 1127.0) - 1.0)
|
| 129 |
+
|
| 130 |
+
min_log_hertz = 1000.0
|
| 131 |
+
min_log_mel = 15.0
|
| 132 |
+
logstep = np.log(6.4) / 27.0
|
| 133 |
+
freq = 200.0 * mels / 3.0
|
| 134 |
+
|
| 135 |
+
if isinstance(mels, np.ndarray):
|
| 136 |
+
log_region = mels >= min_log_mel
|
| 137 |
+
freq[log_region] = min_log_hertz * np.exp(logstep * (mels[log_region] - min_log_mel))
|
| 138 |
+
elif mels >= min_log_mel:
|
| 139 |
+
freq = min_log_hertz * np.exp(logstep * (mels - min_log_mel))
|
| 140 |
+
|
| 141 |
+
return freq
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def hertz_to_octave(
|
| 145 |
+
freq: Union[float, np.ndarray], tuning: Optional[float] = 0.0, bins_per_octave: Optional[int] = 12
|
| 146 |
+
):
|
| 147 |
+
"""
|
| 148 |
+
Convert frequency from hertz to fractional octave numbers.
|
| 149 |
+
Adapted from *librosa*.
|
| 150 |
+
|
| 151 |
+
Args:
|
| 152 |
+
freq (`float` or `np.ndarray`):
|
| 153 |
+
The frequency, or multiple frequencies, in hertz (Hz).
|
| 154 |
+
tuning (`float`, defaults to `0.`):
|
| 155 |
+
Tuning deviation from the Stuttgart pitch (A440) in (fractional) bins per octave.
|
| 156 |
+
bins_per_octave (`int`, defaults to `12`):
|
| 157 |
+
Number of bins per octave.
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
`float` or `np.ndarray`: The frequencies on the octave scale.
|
| 161 |
+
"""
|
| 162 |
+
stuttgart_pitch = 440.0 * 2.0 ** (tuning / bins_per_octave)
|
| 163 |
+
octave = np.log2(freq / (float(stuttgart_pitch) / 16))
|
| 164 |
+
return octave
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _create_triangular_filter_bank(fft_freqs: np.ndarray, filter_freqs: np.ndarray) -> np.ndarray:
|
| 168 |
+
"""
|
| 169 |
+
Creates a triangular filter bank.
|
| 170 |
+
|
| 171 |
+
Adapted from *torchaudio* and *librosa*.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
fft_freqs (`np.ndarray` of shape `(num_frequency_bins,)`):
|
| 175 |
+
Discrete frequencies of the FFT bins in Hz.
|
| 176 |
+
filter_freqs (`np.ndarray` of shape `(num_mel_filters,)`):
|
| 177 |
+
Center frequencies of the triangular filters to create, in Hz.
|
| 178 |
+
|
| 179 |
+
Returns:
|
| 180 |
+
`np.ndarray` of shape `(num_frequency_bins, num_mel_filters)`
|
| 181 |
+
"""
|
| 182 |
+
filter_diff = np.diff(filter_freqs)
|
| 183 |
+
slopes = np.expand_dims(filter_freqs, 0) - np.expand_dims(fft_freqs, 1)
|
| 184 |
+
down_slopes = -slopes[:, :-2] / filter_diff[:-1]
|
| 185 |
+
up_slopes = slopes[:, 2:] / filter_diff[1:]
|
| 186 |
+
return np.maximum(np.zeros(1), np.minimum(down_slopes, up_slopes))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def chroma_filter_bank(
|
| 190 |
+
num_frequency_bins: int,
|
| 191 |
+
num_chroma: int,
|
| 192 |
+
sampling_rate: int,
|
| 193 |
+
tuning: float = 0.0,
|
| 194 |
+
power: Optional[float] = 2.0,
|
| 195 |
+
weighting_parameters: Optional[tuple[float, float]] = (5.0, 2.0),
|
| 196 |
+
start_at_c_chroma: Optional[bool] = True,
|
| 197 |
+
):
|
| 198 |
+
"""
|
| 199 |
+
Creates a chroma filter bank, i.e a linear transformation to project spectrogram bins onto chroma bins.
|
| 200 |
+
|
| 201 |
+
Adapted from *librosa*.
|
| 202 |
+
|
| 203 |
+
Args:
|
| 204 |
+
num_frequency_bins (`int`):
|
| 205 |
+
Number of frequencies used to compute the spectrogram (should be the same as in `stft`).
|
| 206 |
+
num_chroma (`int`):
|
| 207 |
+
Number of chroma bins (i.e pitch classes).
|
| 208 |
+
sampling_rate (`float`):
|
| 209 |
+
Sample rate of the audio waveform.
|
| 210 |
+
tuning (`float`):
|
| 211 |
+
Tuning deviation from A440 in fractions of a chroma bin.
|
| 212 |
+
power (`float`, *optional*, defaults to 2.0):
|
| 213 |
+
If 12.0, normalizes each column with their L2 norm. If 1.0, normalizes each column with their L1 norm.
|
| 214 |
+
weighting_parameters (`Tuple[float, float]`, *optional*, defaults to `(5., 2.)`):
|
| 215 |
+
If specified, apply a Gaussian weighting parameterized by the first element of the tuple being the center and
|
| 216 |
+
the second element being the Gaussian half-width.
|
| 217 |
+
start_at_c_chroma (`float`, *optional*, defaults to `True`):
|
| 218 |
+
If True, the filter bank will start at the 'C' pitch class. Otherwise, it will start at 'A'.
|
| 219 |
+
Returns:
|
| 220 |
+
`np.ndarray` of shape `(num_frequency_bins, num_chroma)`
|
| 221 |
+
"""
|
| 222 |
+
# Get the FFT bins, not counting the DC component
|
| 223 |
+
frequencies = np.linspace(0, sampling_rate, num_frequency_bins, endpoint=False)[1:]
|
| 224 |
+
|
| 225 |
+
freq_bins = num_chroma * hertz_to_octave(frequencies, tuning=tuning, bins_per_octave=num_chroma)
|
| 226 |
+
|
| 227 |
+
# make up a value for the 0 Hz bin = 1.5 octaves below bin 1
|
| 228 |
+
# (so chroma is 50% rotated from bin 1, and bin width is broad)
|
| 229 |
+
freq_bins = np.concatenate(([freq_bins[0] - 1.5 * num_chroma], freq_bins))
|
| 230 |
+
|
| 231 |
+
bins_width = np.concatenate((np.maximum(freq_bins[1:] - freq_bins[:-1], 1.0), [1]))
|
| 232 |
+
|
| 233 |
+
chroma_filters = np.subtract.outer(freq_bins, np.arange(0, num_chroma, dtype="d")).T
|
| 234 |
+
|
| 235 |
+
num_chroma2 = np.round(float(num_chroma) / 2)
|
| 236 |
+
|
| 237 |
+
# Project into range -num_chroma/2 .. num_chroma/2
|
| 238 |
+
# add on fixed offset of 10*num_chroma to ensure all values passed to
|
| 239 |
+
# rem are positive
|
| 240 |
+
chroma_filters = np.remainder(chroma_filters + num_chroma2 + 10 * num_chroma, num_chroma) - num_chroma2
|
| 241 |
+
|
| 242 |
+
# Gaussian bumps - 2*D to make them narrower
|
| 243 |
+
chroma_filters = np.exp(-0.5 * (2 * chroma_filters / np.tile(bins_width, (num_chroma, 1))) ** 2)
|
| 244 |
+
|
| 245 |
+
# normalize each column
|
| 246 |
+
if power is not None:
|
| 247 |
+
chroma_filters = chroma_filters / np.sum(chroma_filters**power, axis=0, keepdims=True) ** (1.0 / power)
|
| 248 |
+
|
| 249 |
+
# Maybe apply scaling for fft bins
|
| 250 |
+
if weighting_parameters is not None:
|
| 251 |
+
center, half_width = weighting_parameters
|
| 252 |
+
chroma_filters *= np.tile(
|
| 253 |
+
np.exp(-0.5 * (((freq_bins / num_chroma - center) / half_width) ** 2)),
|
| 254 |
+
(num_chroma, 1),
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
if start_at_c_chroma:
|
| 258 |
+
chroma_filters = np.roll(chroma_filters, -3 * (num_chroma // 12), axis=0)
|
| 259 |
+
|
| 260 |
+
# remove aliasing columns, copy to ensure row-contiguity
|
| 261 |
+
return np.ascontiguousarray(chroma_filters[:, : int(1 + num_frequency_bins / 2)])
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def mel_filter_bank(
|
| 265 |
+
num_frequency_bins: int,
|
| 266 |
+
num_mel_filters: int,
|
| 267 |
+
min_frequency: float,
|
| 268 |
+
max_frequency: float,
|
| 269 |
+
sampling_rate: int,
|
| 270 |
+
norm: Optional[str] = None,
|
| 271 |
+
mel_scale: str = "htk",
|
| 272 |
+
triangularize_in_mel_space: bool = False,
|
| 273 |
+
) -> np.ndarray:
|
| 274 |
+
"""
|
| 275 |
+
Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and
|
| 276 |
+
various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters
|
| 277 |
+
are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these
|
| 278 |
+
features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency.
|
| 279 |
+
|
| 280 |
+
Different banks of mel filters were introduced in the literature. The following variations are supported:
|
| 281 |
+
|
| 282 |
+
- MFCC FB-20: introduced in 1980 by Davis and Mermelstein, it assumes a sampling frequency of 10 kHz and a speech
|
| 283 |
+
bandwidth of `[0, 4600]` Hz.
|
| 284 |
+
- MFCC FB-24 HTK: from the Cambridge HMM Toolkit (HTK) (1995) uses a filter bank of 24 filters for a speech
|
| 285 |
+
bandwidth of `[0, 8000]` Hz. This assumes sampling rate ≥ 16 kHz.
|
| 286 |
+
- MFCC FB-40: from the Auditory Toolbox for MATLAB written by Slaney in 1998, assumes a sampling rate of 16 kHz and
|
| 287 |
+
speech bandwidth of `[133, 6854]` Hz. This version also includes area normalization.
|
| 288 |
+
- HFCC-E FB-29 (Human Factor Cepstral Coefficients) of Skowronski and Harris (2004), assumes a sampling rate of
|
| 289 |
+
12.5 kHz and speech bandwidth of `[0, 6250]` Hz.
|
| 290 |
+
|
| 291 |
+
This code is adapted from *torchaudio* and *librosa*. Note that the default parameters of torchaudio's
|
| 292 |
+
`melscale_fbanks` implement the `"htk"` filters while librosa uses the `"slaney"` implementation.
|
| 293 |
+
|
| 294 |
+
Args:
|
| 295 |
+
num_frequency_bins (`int`):
|
| 296 |
+
Number of frequency bins (should be the same as `n_fft // 2 + 1` where `n_fft` is the size of the Fourier Transform used to compute the spectrogram).
|
| 297 |
+
num_mel_filters (`int`):
|
| 298 |
+
Number of mel filters to generate.
|
| 299 |
+
min_frequency (`float`):
|
| 300 |
+
Lowest frequency of interest in Hz.
|
| 301 |
+
max_frequency (`float`):
|
| 302 |
+
Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`.
|
| 303 |
+
sampling_rate (`int`):
|
| 304 |
+
Sample rate of the audio waveform.
|
| 305 |
+
norm (`str`, *optional*):
|
| 306 |
+
If `"slaney"`, divide the triangular mel weights by the width of the mel band (area normalization).
|
| 307 |
+
mel_scale (`str`, *optional*, defaults to `"htk"`):
|
| 308 |
+
The mel frequency scale to use, `"htk"`, `"kaldi"` or `"slaney"`.
|
| 309 |
+
triangularize_in_mel_space (`bool`, *optional*, defaults to `False`):
|
| 310 |
+
If this option is enabled, the triangular filter is applied in mel space rather than frequency space. This
|
| 311 |
+
should be set to `true` in order to get the same results as `torchaudio` when computing mel filters.
|
| 312 |
+
|
| 313 |
+
Returns:
|
| 314 |
+
`np.ndarray` of shape (`num_frequency_bins`, `num_mel_filters`): Triangular filter bank matrix. This is a
|
| 315 |
+
projection matrix to go from a spectrogram to a mel spectrogram.
|
| 316 |
+
"""
|
| 317 |
+
if norm is not None and norm != "slaney":
|
| 318 |
+
raise ValueError('norm must be one of None or "slaney"')
|
| 319 |
+
|
| 320 |
+
if num_frequency_bins < 2:
|
| 321 |
+
raise ValueError(f"Require num_frequency_bins: {num_frequency_bins} >= 2")
|
| 322 |
+
|
| 323 |
+
if min_frequency > max_frequency:
|
| 324 |
+
raise ValueError(f"Require min_frequency: {min_frequency} <= max_frequency: {max_frequency}")
|
| 325 |
+
|
| 326 |
+
# center points of the triangular mel filters
|
| 327 |
+
mel_min = hertz_to_mel(min_frequency, mel_scale=mel_scale)
|
| 328 |
+
mel_max = hertz_to_mel(max_frequency, mel_scale=mel_scale)
|
| 329 |
+
mel_freqs = np.linspace(mel_min, mel_max, num_mel_filters + 2)
|
| 330 |
+
filter_freqs = mel_to_hertz(mel_freqs, mel_scale=mel_scale)
|
| 331 |
+
|
| 332 |
+
if triangularize_in_mel_space:
|
| 333 |
+
# frequencies of FFT bins in Hz, but filters triangularized in mel space
|
| 334 |
+
fft_bin_width = sampling_rate / ((num_frequency_bins - 1) * 2)
|
| 335 |
+
fft_freqs = hertz_to_mel(fft_bin_width * np.arange(num_frequency_bins), mel_scale=mel_scale)
|
| 336 |
+
filter_freqs = mel_freqs
|
| 337 |
+
else:
|
| 338 |
+
# frequencies of FFT bins in Hz
|
| 339 |
+
fft_freqs = np.linspace(0, sampling_rate // 2, num_frequency_bins)
|
| 340 |
+
|
| 341 |
+
mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs)
|
| 342 |
+
|
| 343 |
+
if norm is not None and norm == "slaney":
|
| 344 |
+
# Slaney-style mel is scaled to be approx constant energy per channel
|
| 345 |
+
enorm = 2.0 / (filter_freqs[2 : num_mel_filters + 2] - filter_freqs[:num_mel_filters])
|
| 346 |
+
mel_filters *= np.expand_dims(enorm, 0)
|
| 347 |
+
|
| 348 |
+
if (mel_filters.max(axis=0) == 0.0).any():
|
| 349 |
+
warnings.warn(
|
| 350 |
+
"At least one mel filter has all zero values. "
|
| 351 |
+
f"The value for `num_mel_filters` ({num_mel_filters}) may be set too high. "
|
| 352 |
+
f"Or, the value for `num_frequency_bins` ({num_frequency_bins}) may be set too low."
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
return mel_filters
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def optimal_fft_length(window_length: int) -> int:
|
| 359 |
+
"""
|
| 360 |
+
Finds the best FFT input size for a given `window_length`. This function takes a given window length and, if not
|
| 361 |
+
already a power of two, rounds it up to the next power or two.
|
| 362 |
+
|
| 363 |
+
The FFT algorithm works fastest when the length of the input is a power of two, which may be larger than the size
|
| 364 |
+
of the window or analysis frame. For example, if the window is 400 samples, using an FFT input size of 512 samples
|
| 365 |
+
is more optimal than an FFT size of 400 samples. Using a larger FFT size does not affect the detected frequencies,
|
| 366 |
+
it simply gives a higher frequency resolution (i.e. the frequency bins are smaller).
|
| 367 |
+
"""
|
| 368 |
+
return 2 ** int(np.ceil(np.log2(window_length)))
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def window_function(
|
| 372 |
+
window_length: int,
|
| 373 |
+
name: str = "hann",
|
| 374 |
+
periodic: bool = True,
|
| 375 |
+
frame_length: Optional[int] = None,
|
| 376 |
+
center: bool = True,
|
| 377 |
+
) -> np.ndarray:
|
| 378 |
+
"""
|
| 379 |
+
Returns an array containing the specified window. This window is intended to be used with `stft`.
|
| 380 |
+
|
| 381 |
+
The following window types are supported:
|
| 382 |
+
|
| 383 |
+
- `"boxcar"`: a rectangular window
|
| 384 |
+
- `"hamming"`: the Hamming window
|
| 385 |
+
- `"hann"`: the Hann window
|
| 386 |
+
- `"povey"`: the Povey window
|
| 387 |
+
|
| 388 |
+
Args:
|
| 389 |
+
window_length (`int`):
|
| 390 |
+
The length of the window in samples.
|
| 391 |
+
name (`str`, *optional*, defaults to `"hann"`):
|
| 392 |
+
The name of the window function.
|
| 393 |
+
periodic (`bool`, *optional*, defaults to `True`):
|
| 394 |
+
Whether the window is periodic or symmetric.
|
| 395 |
+
frame_length (`int`, *optional*):
|
| 396 |
+
The length of the analysis frames in samples. Provide a value for `frame_length` if the window is smaller
|
| 397 |
+
than the frame length, so that it will be zero-padded.
|
| 398 |
+
center (`bool`, *optional*, defaults to `True`):
|
| 399 |
+
Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.
|
| 400 |
+
|
| 401 |
+
Returns:
|
| 402 |
+
`np.ndarray` of shape `(window_length,)` or `(frame_length,)` containing the window.
|
| 403 |
+
"""
|
| 404 |
+
length = window_length + 1 if periodic else window_length
|
| 405 |
+
|
| 406 |
+
if name == "boxcar":
|
| 407 |
+
window = np.ones(length)
|
| 408 |
+
elif name in ["hamming", "hamming_window"]:
|
| 409 |
+
window = np.hamming(length)
|
| 410 |
+
elif name in ["hann", "hann_window"]:
|
| 411 |
+
window = np.hanning(length)
|
| 412 |
+
elif name in ["povey"]:
|
| 413 |
+
window = np.power(np.hanning(length), 0.85)
|
| 414 |
+
else:
|
| 415 |
+
raise ValueError(f"Unknown window function '{name}'")
|
| 416 |
+
|
| 417 |
+
if periodic:
|
| 418 |
+
window = window[:-1]
|
| 419 |
+
|
| 420 |
+
if frame_length is None:
|
| 421 |
+
return window
|
| 422 |
+
|
| 423 |
+
if window_length > frame_length:
|
| 424 |
+
raise ValueError(
|
| 425 |
+
f"Length of the window ({window_length}) may not be larger than frame_length ({frame_length})"
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
padded_window = np.zeros(frame_length)
|
| 429 |
+
offset = (frame_length - window_length) // 2 if center else 0
|
| 430 |
+
padded_window[offset : offset + window_length] = window
|
| 431 |
+
return padded_window
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
# TODO This method does not support batching yet as we are mainly focused on inference.
|
| 435 |
+
def spectrogram(
|
| 436 |
+
waveform: np.ndarray,
|
| 437 |
+
window: np.ndarray,
|
| 438 |
+
frame_length: int,
|
| 439 |
+
hop_length: int,
|
| 440 |
+
fft_length: Optional[int] = None,
|
| 441 |
+
power: Optional[float] = 1.0,
|
| 442 |
+
center: bool = True,
|
| 443 |
+
pad_mode: str = "reflect",
|
| 444 |
+
onesided: bool = True,
|
| 445 |
+
dither: float = 0.0,
|
| 446 |
+
preemphasis: Optional[float] = None,
|
| 447 |
+
mel_filters: Optional[np.ndarray] = None,
|
| 448 |
+
mel_floor: float = 1e-10,
|
| 449 |
+
log_mel: Optional[str] = None,
|
| 450 |
+
reference: float = 1.0,
|
| 451 |
+
min_value: float = 1e-10,
|
| 452 |
+
db_range: Optional[float] = None,
|
| 453 |
+
remove_dc_offset: Optional[bool] = None,
|
| 454 |
+
dtype: np.dtype = np.float32,
|
| 455 |
+
) -> np.ndarray:
|
| 456 |
+
"""
|
| 457 |
+
Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.
|
| 458 |
+
|
| 459 |
+
This function can create the following kinds of spectrograms:
|
| 460 |
+
|
| 461 |
+
- amplitude spectrogram (`power = 1.0`)
|
| 462 |
+
- power spectrogram (`power = 2.0`)
|
| 463 |
+
- complex-valued spectrogram (`power = None`)
|
| 464 |
+
- log spectrogram (use `log_mel` argument)
|
| 465 |
+
- mel spectrogram (provide `mel_filters`)
|
| 466 |
+
- log-mel spectrogram (provide `mel_filters` and `log_mel`)
|
| 467 |
+
|
| 468 |
+
How this works:
|
| 469 |
+
|
| 470 |
+
1. The input waveform is split into frames of size `frame_length` that are partially overlapping by `frame_length
|
| 471 |
+
- hop_length` samples.
|
| 472 |
+
2. Each frame is multiplied by the window and placed into a buffer of size `fft_length`.
|
| 473 |
+
3. The DFT is taken of each windowed frame.
|
| 474 |
+
4. The results are stacked into a spectrogram.
|
| 475 |
+
|
| 476 |
+
We make a distinction between the following "blocks" of sample data, each of which may have a different lengths:
|
| 477 |
+
|
| 478 |
+
- The analysis frame. This is the size of the time slices that the input waveform is split into.
|
| 479 |
+
- The window. Each analysis frame is multiplied by the window to avoid spectral leakage.
|
| 480 |
+
- The FFT input buffer. The length of this determines how many frequency bins are in the spectrogram.
|
| 481 |
+
|
| 482 |
+
In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame. A
|
| 483 |
+
padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame,
|
| 484 |
+
typically the next power of two.
|
| 485 |
+
|
| 486 |
+
Note: This function is not optimized for speed yet. It should be mostly compatible with `librosa.stft` and
|
| 487 |
+
`torchaudio.functional.transforms.Spectrogram`, although it is more flexible due to the different ways spectrograms
|
| 488 |
+
can be constructed.
|
| 489 |
+
|
| 490 |
+
Args:
|
| 491 |
+
waveform (`np.ndarray` of shape `(length,)`):
|
| 492 |
+
The input waveform. This must be a single real-valued, mono waveform.
|
| 493 |
+
window (`np.ndarray` of shape `(frame_length,)`):
|
| 494 |
+
The windowing function to apply, including zero-padding if necessary. The actual window length may be
|
| 495 |
+
shorter than `frame_length`, but we're assuming the array has already been zero-padded.
|
| 496 |
+
frame_length (`int`):
|
| 497 |
+
The length of the analysis frames in samples. With librosa this is always equal to `fft_length` but we also
|
| 498 |
+
allow smaller sizes.
|
| 499 |
+
hop_length (`int`):
|
| 500 |
+
The stride between successive analysis frames in samples.
|
| 501 |
+
fft_length (`int`, *optional*):
|
| 502 |
+
The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have.
|
| 503 |
+
For optimal speed, this should be a power of two. If `None`, uses `frame_length`.
|
| 504 |
+
power (`float`, *optional*, defaults to 1.0):
|
| 505 |
+
If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `None`, returns
|
| 506 |
+
complex numbers.
|
| 507 |
+
center (`bool`, *optional*, defaults to `True`):
|
| 508 |
+
Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `False`, frame
|
| 509 |
+
`t` will start at time `t * hop_length`.
|
| 510 |
+
pad_mode (`str`, *optional*, defaults to `"reflect"`):
|
| 511 |
+
Padding mode used when `center` is `True`. Possible values are: `"constant"` (pad with zeros), `"edge"`
|
| 512 |
+
(pad with edge values), `"reflect"` (pads with mirrored values).
|
| 513 |
+
onesided (`bool`, *optional*, defaults to `True`):
|
| 514 |
+
If True, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1`
|
| 515 |
+
frequency bins. If False, also computes the negative frequencies and returns `fft_length` frequency bins.
|
| 516 |
+
dither (`float`, *optional*, defaults to 0.0):
|
| 517 |
+
Adds dithering. In other words, adds a small Gaussian noise to each frame.
|
| 518 |
+
E.g. use 4.0 to add dithering with a normal distribution centered
|
| 519 |
+
around 0.0 with standard deviation 4.0, 0.0 means no dithering.
|
| 520 |
+
Dithering has similar effect as `mel_floor`. It reduces the high log_mel_fbank
|
| 521 |
+
values for signals with hard-zero sections, when VAD cutoff is present in the signal.
|
| 522 |
+
preemphasis (`float`, *optional*)
|
| 523 |
+
Coefficient for a low-pass filter that applies pre-emphasis before the DFT.
|
| 524 |
+
mel_filters (`np.ndarray` of shape `(num_freq_bins, num_mel_filters)`, *optional*):
|
| 525 |
+
The mel filter bank. If supplied, applies a this filter bank to create a mel spectrogram.
|
| 526 |
+
mel_floor (`float`, *optional*, defaults to 1e-10):
|
| 527 |
+
Minimum value of mel frequency banks.
|
| 528 |
+
log_mel (`str`, *optional*):
|
| 529 |
+
How to convert the spectrogram to log scale. Possible options are: `None` (don't convert), `"log"` (take
|
| 530 |
+
the natural logarithm) `"log10"` (take the base-10 logarithm), `"dB"` (convert to decibels). Can only be
|
| 531 |
+
used when `power` is not `None`.
|
| 532 |
+
reference (`float`, *optional*, defaults to 1.0):
|
| 533 |
+
Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
|
| 534 |
+
the loudest part to 0 dB. Must be greater than zero.
|
| 535 |
+
min_value (`float`, *optional*, defaults to `1e-10`):
|
| 536 |
+
The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
|
| 537 |
+
`log(0)`. For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an
|
| 538 |
+
amplitude spectrogram, the value `1e-5` corresponds to -100 dB. Must be greater than zero.
|
| 539 |
+
db_range (`float`, *optional*):
|
| 540 |
+
Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
|
| 541 |
+
peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
|
| 542 |
+
remove_dc_offset (`bool`, *optional*):
|
| 543 |
+
Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in
|
| 544 |
+
order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters.
|
| 545 |
+
dtype (`np.dtype`, *optional*, defaults to `np.float32`):
|
| 546 |
+
Data type of the spectrogram tensor. If `power` is None, this argument is ignored and the dtype will be
|
| 547 |
+
`np.complex64`.
|
| 548 |
+
|
| 549 |
+
Returns:
|
| 550 |
+
`nd.array` containing a spectrogram of shape `(num_frequency_bins, length)` for a regular spectrogram or shape
|
| 551 |
+
`(num_mel_filters, length)` for a mel spectrogram.
|
| 552 |
+
"""
|
| 553 |
+
window_length = len(window)
|
| 554 |
+
|
| 555 |
+
if fft_length is None:
|
| 556 |
+
fft_length = frame_length
|
| 557 |
+
|
| 558 |
+
if frame_length > fft_length:
|
| 559 |
+
raise ValueError(f"frame_length ({frame_length}) may not be larger than fft_length ({fft_length})")
|
| 560 |
+
|
| 561 |
+
if window_length != frame_length:
|
| 562 |
+
raise ValueError(f"Length of the window ({window_length}) must equal frame_length ({frame_length})")
|
| 563 |
+
|
| 564 |
+
if hop_length <= 0:
|
| 565 |
+
raise ValueError("hop_length must be greater than zero")
|
| 566 |
+
|
| 567 |
+
if waveform.ndim != 1:
|
| 568 |
+
raise ValueError(f"Input waveform must have only one dimension, shape is {waveform.shape}")
|
| 569 |
+
|
| 570 |
+
if np.iscomplexobj(waveform):
|
| 571 |
+
raise ValueError("Complex-valued input waveforms are not currently supported")
|
| 572 |
+
|
| 573 |
+
if power is None and mel_filters is not None:
|
| 574 |
+
raise ValueError(
|
| 575 |
+
"You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram."
|
| 576 |
+
"Specify `power` to fix this issue."
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
# center pad the waveform
|
| 580 |
+
if center:
|
| 581 |
+
padding = [(int(frame_length // 2), int(frame_length // 2))]
|
| 582 |
+
waveform = np.pad(waveform, padding, mode=pad_mode)
|
| 583 |
+
|
| 584 |
+
# promote to float64, since np.fft uses float64 internally
|
| 585 |
+
waveform = waveform.astype(np.float64)
|
| 586 |
+
window = window.astype(np.float64)
|
| 587 |
+
|
| 588 |
+
# split waveform into frames of frame_length size
|
| 589 |
+
num_frames = int(1 + np.floor((waveform.size - frame_length) / hop_length))
|
| 590 |
+
|
| 591 |
+
num_frequency_bins = (fft_length // 2) + 1 if onesided else fft_length
|
| 592 |
+
spectrogram = np.empty((num_frames, num_frequency_bins), dtype=np.complex64)
|
| 593 |
+
|
| 594 |
+
# rfft is faster than fft
|
| 595 |
+
fft_func = np.fft.rfft if onesided else np.fft.fft
|
| 596 |
+
buffer = np.zeros(fft_length)
|
| 597 |
+
|
| 598 |
+
timestep = 0
|
| 599 |
+
for frame_idx in range(num_frames):
|
| 600 |
+
buffer[:frame_length] = waveform[timestep : timestep + frame_length]
|
| 601 |
+
|
| 602 |
+
if dither != 0.0:
|
| 603 |
+
buffer[:frame_length] += dither * np.random.randn(frame_length)
|
| 604 |
+
|
| 605 |
+
if remove_dc_offset:
|
| 606 |
+
buffer[:frame_length] = buffer[:frame_length] - buffer[:frame_length].mean()
|
| 607 |
+
|
| 608 |
+
if preemphasis is not None:
|
| 609 |
+
buffer[1:frame_length] -= preemphasis * buffer[: frame_length - 1]
|
| 610 |
+
buffer[0] *= 1 - preemphasis
|
| 611 |
+
|
| 612 |
+
buffer[:frame_length] *= window
|
| 613 |
+
|
| 614 |
+
spectrogram[frame_idx] = fft_func(buffer)
|
| 615 |
+
timestep += hop_length
|
| 616 |
+
|
| 617 |
+
# note: ** is much faster than np.power
|
| 618 |
+
if power is not None:
|
| 619 |
+
spectrogram = np.abs(spectrogram, dtype=np.float64) ** power
|
| 620 |
+
|
| 621 |
+
spectrogram = spectrogram.T
|
| 622 |
+
|
| 623 |
+
if mel_filters is not None:
|
| 624 |
+
spectrogram = np.maximum(mel_floor, np.dot(mel_filters.T, spectrogram))
|
| 625 |
+
|
| 626 |
+
if power is not None and log_mel is not None:
|
| 627 |
+
if log_mel == "log":
|
| 628 |
+
spectrogram = np.log(spectrogram)
|
| 629 |
+
elif log_mel == "log10":
|
| 630 |
+
spectrogram = np.log10(spectrogram)
|
| 631 |
+
elif log_mel == "dB":
|
| 632 |
+
if power == 1.0:
|
| 633 |
+
spectrogram = amplitude_to_db(spectrogram, reference, min_value, db_range)
|
| 634 |
+
elif power == 2.0:
|
| 635 |
+
spectrogram = power_to_db(spectrogram, reference, min_value, db_range)
|
| 636 |
+
else:
|
| 637 |
+
raise ValueError(f"Cannot use log_mel option '{log_mel}' with power {power}")
|
| 638 |
+
else:
|
| 639 |
+
raise ValueError(f"Unknown log_mel option: {log_mel}")
|
| 640 |
+
|
| 641 |
+
spectrogram = np.asarray(spectrogram, dtype)
|
| 642 |
+
|
| 643 |
+
return spectrogram
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def spectrogram_batch(
|
| 647 |
+
waveform_list: list[np.ndarray],
|
| 648 |
+
window: np.ndarray,
|
| 649 |
+
frame_length: int,
|
| 650 |
+
hop_length: int,
|
| 651 |
+
fft_length: Optional[int] = None,
|
| 652 |
+
power: Optional[float] = 1.0,
|
| 653 |
+
center: bool = True,
|
| 654 |
+
pad_mode: str = "reflect",
|
| 655 |
+
onesided: bool = True,
|
| 656 |
+
dither: float = 0.0,
|
| 657 |
+
preemphasis: Optional[float] = None,
|
| 658 |
+
mel_filters: Optional[np.ndarray] = None,
|
| 659 |
+
mel_floor: float = 1e-10,
|
| 660 |
+
log_mel: Optional[str] = None,
|
| 661 |
+
reference: float = 1.0,
|
| 662 |
+
min_value: float = 1e-10,
|
| 663 |
+
db_range: Optional[float] = None,
|
| 664 |
+
remove_dc_offset: Optional[bool] = None,
|
| 665 |
+
dtype: np.dtype = np.float32,
|
| 666 |
+
) -> list[np.ndarray]:
|
| 667 |
+
"""
|
| 668 |
+
Calculates spectrograms for a list of waveforms using the Short-Time Fourier Transform, optimized for batch processing.
|
| 669 |
+
This function extends the capabilities of the `spectrogram` function to handle multiple waveforms efficiently by leveraging broadcasting.
|
| 670 |
+
|
| 671 |
+
It supports generating various types of spectrograms:
|
| 672 |
+
|
| 673 |
+
- amplitude spectrogram (`power = 1.0`)
|
| 674 |
+
- power spectrogram (`power = 2.0`)
|
| 675 |
+
- complex-valued spectrogram (`power = None`)
|
| 676 |
+
- log spectrogram (use `log_mel` argument)
|
| 677 |
+
- mel spectrogram (provide `mel_filters`)
|
| 678 |
+
- log-mel spectrogram (provide `mel_filters` and `log_mel`)
|
| 679 |
+
|
| 680 |
+
How this works:
|
| 681 |
+
|
| 682 |
+
1. The input waveform is split into frames of size `frame_length` that are partially overlapping by `frame_length
|
| 683 |
+
- hop_length` samples.
|
| 684 |
+
2. Each frame is multiplied by the window and placed into a buffer of size `fft_length`.
|
| 685 |
+
3. The DFT is taken of each windowed frame.
|
| 686 |
+
4. The results are stacked into a spectrogram.
|
| 687 |
+
|
| 688 |
+
We make a distinction between the following "blocks" of sample data, each of which may have a different lengths:
|
| 689 |
+
|
| 690 |
+
- The analysis frame. This is the size of the time slices that the input waveform is split into.
|
| 691 |
+
- The window. Each analysis frame is multiplied by the window to avoid spectral leakage.
|
| 692 |
+
- The FFT input buffer. The length of this determines how many frequency bins are in the spectrogram.
|
| 693 |
+
|
| 694 |
+
In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame. A
|
| 695 |
+
padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame,
|
| 696 |
+
typically the next power of two.
|
| 697 |
+
|
| 698 |
+
Note: This function is designed for efficient batch processing of multiple waveforms but retains compatibility with individual waveform processing methods like `librosa.stft`.
|
| 699 |
+
|
| 700 |
+
Args:
|
| 701 |
+
waveform_list (`List[np.ndarray]` with arrays of shape `(length,)`):
|
| 702 |
+
The list of input waveforms, each a single-channel (mono) signal.
|
| 703 |
+
window (`np.ndarray` of shape `(frame_length,)`):
|
| 704 |
+
The windowing function to apply, including zero-padding if necessary.
|
| 705 |
+
frame_length (`int`):
|
| 706 |
+
The length of each frame for analysis.
|
| 707 |
+
hop_length (`int`):
|
| 708 |
+
The step size between successive frames.
|
| 709 |
+
fft_length (`int`, *optional*):
|
| 710 |
+
The size of the FFT buffer, defining frequency bin resolution.
|
| 711 |
+
power (`float`, *optional*, defaults to 1.0):
|
| 712 |
+
Determines the type of spectrogram: 1.0 for amplitude, 2.0 for power, None for complex.
|
| 713 |
+
center (`bool`, *optional*, defaults to `True`):
|
| 714 |
+
Whether to center-pad the waveform frames.
|
| 715 |
+
pad_mode (`str`, *optional*, defaults to `"reflect"`):
|
| 716 |
+
The padding strategy when `center` is `True`.
|
| 717 |
+
onesided (`bool`, *optional*, defaults to `True`):
|
| 718 |
+
If True, returns a one-sided spectrogram for real input signals.
|
| 719 |
+
dither (`float`, *optional*, defaults to 0.0):
|
| 720 |
+
Adds dithering. In other words, adds a small Gaussian noise to each frame.
|
| 721 |
+
E.g. use 4.0 to add dithering with a normal distribution centered
|
| 722 |
+
around 0.0 with standard deviation 4.0, 0.0 means no dithering.
|
| 723 |
+
preemphasis (`float`, *optional*):
|
| 724 |
+
Applies a pre-emphasis filter to each frame.
|
| 725 |
+
mel_filters (`np.ndarray`, *optional*):
|
| 726 |
+
Mel filter bank for converting to mel spectrogram.
|
| 727 |
+
mel_floor (`float`, *optional*, defaults to 1e-10):
|
| 728 |
+
Floor value for mel spectrogram to avoid log(0).
|
| 729 |
+
log_mel (`str`, *optional*):
|
| 730 |
+
Specifies log scaling strategy; options are None, "log", "log10", "dB".
|
| 731 |
+
reference (`float`, *optional*, defaults to 1.0):
|
| 732 |
+
Reference value for dB conversion in log_mel.
|
| 733 |
+
min_value (`float`, *optional*, defaults to 1e-10):
|
| 734 |
+
Minimum floor value for log scale conversions.
|
| 735 |
+
db_range (`float`, *optional*):
|
| 736 |
+
Dynamic range for dB scale spectrograms.
|
| 737 |
+
remove_dc_offset (`bool`, *optional*):
|
| 738 |
+
Whether to remove the DC offset from each frame.
|
| 739 |
+
dtype (`np.dtype`, *optional*, defaults to `np.float32`):
|
| 740 |
+
Data type of the output spectrogram.
|
| 741 |
+
|
| 742 |
+
Returns:
|
| 743 |
+
List[`np.ndarray`]: A list of spectrogram arrays, one for each input waveform.
|
| 744 |
+
"""
|
| 745 |
+
window_length = len(window)
|
| 746 |
+
|
| 747 |
+
if fft_length is None:
|
| 748 |
+
fft_length = frame_length
|
| 749 |
+
|
| 750 |
+
if frame_length > fft_length:
|
| 751 |
+
raise ValueError(f"frame_length ({frame_length}) may not be larger than fft_length ({fft_length})")
|
| 752 |
+
|
| 753 |
+
if window_length != frame_length:
|
| 754 |
+
raise ValueError(f"Length of the window ({window_length}) must equal frame_length ({frame_length})")
|
| 755 |
+
|
| 756 |
+
if hop_length <= 0:
|
| 757 |
+
raise ValueError("hop_length must be greater than zero")
|
| 758 |
+
|
| 759 |
+
# Check the dimensions of the waveform , and if waveform is complex
|
| 760 |
+
for waveform in waveform_list:
|
| 761 |
+
if waveform.ndim != 1:
|
| 762 |
+
raise ValueError(f"Input waveform must have only one dimension, shape is {waveform.shape}")
|
| 763 |
+
if np.iscomplexobj(waveform):
|
| 764 |
+
raise ValueError("Complex-valued input waveforms are not currently supported")
|
| 765 |
+
# Center pad the waveform
|
| 766 |
+
if center:
|
| 767 |
+
padding = [(int(frame_length // 2), int(frame_length // 2))]
|
| 768 |
+
waveform_list = [
|
| 769 |
+
np.pad(
|
| 770 |
+
waveform,
|
| 771 |
+
padding,
|
| 772 |
+
mode=pad_mode,
|
| 773 |
+
)
|
| 774 |
+
for waveform in waveform_list
|
| 775 |
+
]
|
| 776 |
+
original_waveform_lengths = [
|
| 777 |
+
len(waveform) for waveform in waveform_list
|
| 778 |
+
] # these lengths will be used to remove padding later
|
| 779 |
+
|
| 780 |
+
# Batch pad the waveform
|
| 781 |
+
max_length = max(original_waveform_lengths)
|
| 782 |
+
padded_waveform_batch = np.array(
|
| 783 |
+
[
|
| 784 |
+
np.pad(waveform, (0, max_length - len(waveform)), mode="constant", constant_values=0)
|
| 785 |
+
for waveform in waveform_list
|
| 786 |
+
],
|
| 787 |
+
dtype=dtype,
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
# Promote to float64, since np.fft uses float64 internally
|
| 791 |
+
padded_waveform_batch = padded_waveform_batch.astype(np.float64)
|
| 792 |
+
window = window.astype(np.float64)
|
| 793 |
+
|
| 794 |
+
# Split waveform into frames of frame_length size
|
| 795 |
+
num_frames = int(1 + np.floor((padded_waveform_batch.shape[1] - frame_length) / hop_length))
|
| 796 |
+
# these lengths will be used to remove padding later
|
| 797 |
+
true_num_frames = [int(1 + np.floor((length - frame_length) / hop_length)) for length in original_waveform_lengths]
|
| 798 |
+
num_batches = padded_waveform_batch.shape[0]
|
| 799 |
+
|
| 800 |
+
num_frequency_bins = (fft_length // 2) + 1 if onesided else fft_length
|
| 801 |
+
spectrogram = np.empty((num_batches, num_frames, num_frequency_bins), dtype=np.complex64)
|
| 802 |
+
|
| 803 |
+
# rfft is faster than fft
|
| 804 |
+
fft_func = np.fft.rfft if onesided else np.fft.fft
|
| 805 |
+
buffer = np.zeros((num_batches, fft_length))
|
| 806 |
+
|
| 807 |
+
for frame_idx in range(num_frames):
|
| 808 |
+
timestep = frame_idx * hop_length
|
| 809 |
+
buffer[:, :frame_length] = padded_waveform_batch[:, timestep : timestep + frame_length]
|
| 810 |
+
|
| 811 |
+
if dither != 0.0:
|
| 812 |
+
buffer[:, :frame_length] += dither * np.random.randn(*buffer[:, :frame_length].shape)
|
| 813 |
+
|
| 814 |
+
if remove_dc_offset:
|
| 815 |
+
buffer[:, :frame_length] -= buffer[:, :frame_length].mean(axis=1, keepdims=True)
|
| 816 |
+
|
| 817 |
+
if preemphasis is not None:
|
| 818 |
+
buffer[:, 1:frame_length] -= preemphasis * buffer[:, : frame_length - 1]
|
| 819 |
+
buffer[:, 0] *= 1 - preemphasis
|
| 820 |
+
|
| 821 |
+
buffer[:, :frame_length] *= window
|
| 822 |
+
|
| 823 |
+
spectrogram[:, frame_idx] = fft_func(buffer)
|
| 824 |
+
|
| 825 |
+
# Note: ** is much faster than np.power
|
| 826 |
+
if power is not None:
|
| 827 |
+
spectrogram = np.abs(spectrogram, dtype=np.float64) ** power
|
| 828 |
+
|
| 829 |
+
# Apply mel filters if provided
|
| 830 |
+
if mel_filters is not None:
|
| 831 |
+
result = np.tensordot(spectrogram, mel_filters.T, axes=([2], [1]))
|
| 832 |
+
spectrogram = np.maximum(mel_floor, result)
|
| 833 |
+
|
| 834 |
+
# Convert to log scale if specified
|
| 835 |
+
if power is not None and log_mel is not None:
|
| 836 |
+
if log_mel == "log":
|
| 837 |
+
spectrogram = np.log(spectrogram)
|
| 838 |
+
elif log_mel == "log10":
|
| 839 |
+
spectrogram = np.log10(spectrogram)
|
| 840 |
+
elif log_mel == "dB":
|
| 841 |
+
if power == 1.0:
|
| 842 |
+
spectrogram = amplitude_to_db_batch(spectrogram, reference, min_value, db_range)
|
| 843 |
+
elif power == 2.0:
|
| 844 |
+
spectrogram = power_to_db_batch(spectrogram, reference, min_value, db_range)
|
| 845 |
+
else:
|
| 846 |
+
raise ValueError(f"Cannot use log_mel option '{log_mel}' with power {power}")
|
| 847 |
+
else:
|
| 848 |
+
raise ValueError(f"Unknown log_mel option: {log_mel}")
|
| 849 |
+
|
| 850 |
+
spectrogram = np.asarray(spectrogram, dtype)
|
| 851 |
+
|
| 852 |
+
spectrogram_list = [spectrogram[i, : true_num_frames[i], :].T for i in range(len(true_num_frames))]
|
| 853 |
+
|
| 854 |
+
return spectrogram_list
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
def power_to_db(
|
| 858 |
+
spectrogram: np.ndarray,
|
| 859 |
+
reference: float = 1.0,
|
| 860 |
+
min_value: float = 1e-10,
|
| 861 |
+
db_range: Optional[float] = None,
|
| 862 |
+
) -> np.ndarray:
|
| 863 |
+
"""
|
| 864 |
+
Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`, using basic
|
| 865 |
+
logarithm properties for numerical stability.
|
| 866 |
+
|
| 867 |
+
The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
|
| 868 |
+
linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
|
| 869 |
+
This means that large variations in energy may not sound all that different if the sound is loud to begin with.
|
| 870 |
+
This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
|
| 871 |
+
|
| 872 |
+
Based on the implementation of `librosa.power_to_db`.
|
| 873 |
+
|
| 874 |
+
Args:
|
| 875 |
+
spectrogram (`np.ndarray`):
|
| 876 |
+
The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared!
|
| 877 |
+
reference (`float`, *optional*, defaults to 1.0):
|
| 878 |
+
Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
|
| 879 |
+
the loudest part to 0 dB. Must be greater than zero.
|
| 880 |
+
min_value (`float`, *optional*, defaults to `1e-10`):
|
| 881 |
+
The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
|
| 882 |
+
`log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero.
|
| 883 |
+
db_range (`float`, *optional*):
|
| 884 |
+
Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
|
| 885 |
+
peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
|
| 886 |
+
|
| 887 |
+
Returns:
|
| 888 |
+
`np.ndarray`: the spectrogram in decibels
|
| 889 |
+
"""
|
| 890 |
+
if reference <= 0.0:
|
| 891 |
+
raise ValueError("reference must be greater than zero")
|
| 892 |
+
if min_value <= 0.0:
|
| 893 |
+
raise ValueError("min_value must be greater than zero")
|
| 894 |
+
|
| 895 |
+
reference = max(min_value, reference)
|
| 896 |
+
|
| 897 |
+
spectrogram = np.clip(spectrogram, a_min=min_value, a_max=None)
|
| 898 |
+
spectrogram = 10.0 * (np.log10(spectrogram) - np.log10(reference))
|
| 899 |
+
|
| 900 |
+
if db_range is not None:
|
| 901 |
+
if db_range <= 0.0:
|
| 902 |
+
raise ValueError("db_range must be greater than zero")
|
| 903 |
+
spectrogram = np.clip(spectrogram, a_min=spectrogram.max() - db_range, a_max=None)
|
| 904 |
+
|
| 905 |
+
return spectrogram
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
def power_to_db_batch(
|
| 909 |
+
spectrogram: np.ndarray,
|
| 910 |
+
reference: float = 1.0,
|
| 911 |
+
min_value: float = 1e-10,
|
| 912 |
+
db_range: Optional[float] = None,
|
| 913 |
+
) -> np.ndarray:
|
| 914 |
+
"""
|
| 915 |
+
Converts a batch of power spectrograms to the decibel scale. This computes `10 * log10(spectrogram / reference)`,
|
| 916 |
+
using basic logarithm properties for numerical stability.
|
| 917 |
+
|
| 918 |
+
This function supports batch processing, where each item in the batch is an individual power (mel) spectrogram.
|
| 919 |
+
|
| 920 |
+
Args:
|
| 921 |
+
spectrogram (`np.ndarray`):
|
| 922 |
+
The input batch of power (mel) spectrograms. Expected shape is (batch_size, *spectrogram_shape).
|
| 923 |
+
Note that a power spectrogram has the amplitudes squared!
|
| 924 |
+
reference (`float`, *optional*, defaults to 1.0):
|
| 925 |
+
Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
|
| 926 |
+
the loudest part to 0 dB. Must be greater than zero.
|
| 927 |
+
min_value (`float`, *optional*, defaults to `1e-10`):
|
| 928 |
+
The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
|
| 929 |
+
`log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero.
|
| 930 |
+
db_range (`float`, *optional*):
|
| 931 |
+
Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
|
| 932 |
+
peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
|
| 933 |
+
|
| 934 |
+
Returns:
|
| 935 |
+
`np.ndarray`: the batch of spectrograms in decibels
|
| 936 |
+
"""
|
| 937 |
+
if reference <= 0.0:
|
| 938 |
+
raise ValueError("reference must be greater than zero")
|
| 939 |
+
if min_value <= 0.0:
|
| 940 |
+
raise ValueError("min_value must be greater than zero")
|
| 941 |
+
|
| 942 |
+
reference = max(min_value, reference)
|
| 943 |
+
|
| 944 |
+
spectrogram = np.clip(spectrogram, a_min=min_value, a_max=None)
|
| 945 |
+
spectrogram = 10.0 * (np.log10(spectrogram) - np.log10(reference))
|
| 946 |
+
|
| 947 |
+
if db_range is not None:
|
| 948 |
+
if db_range <= 0.0:
|
| 949 |
+
raise ValueError("db_range must be greater than zero")
|
| 950 |
+
# Apply db_range clipping per batch item
|
| 951 |
+
max_values = spectrogram.max(axis=(1, 2), keepdims=True)
|
| 952 |
+
spectrogram = np.clip(spectrogram, a_min=max_values - db_range, a_max=None)
|
| 953 |
+
|
| 954 |
+
return spectrogram
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
def amplitude_to_db(
|
| 958 |
+
spectrogram: np.ndarray,
|
| 959 |
+
reference: float = 1.0,
|
| 960 |
+
min_value: float = 1e-5,
|
| 961 |
+
db_range: Optional[float] = None,
|
| 962 |
+
) -> np.ndarray:
|
| 963 |
+
"""
|
| 964 |
+
Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`, using
|
| 965 |
+
basic logarithm properties for numerical stability.
|
| 966 |
+
|
| 967 |
+
The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
|
| 968 |
+
linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
|
| 969 |
+
This means that large variations in energy may not sound all that different if the sound is loud to begin with.
|
| 970 |
+
This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
|
| 971 |
+
|
| 972 |
+
Args:
|
| 973 |
+
spectrogram (`np.ndarray`):
|
| 974 |
+
The input amplitude (mel) spectrogram.
|
| 975 |
+
reference (`float`, *optional*, defaults to 1.0):
|
| 976 |
+
Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
|
| 977 |
+
the loudest part to 0 dB. Must be greater than zero.
|
| 978 |
+
min_value (`float`, *optional*, defaults to `1e-5`):
|
| 979 |
+
The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
|
| 980 |
+
`log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero.
|
| 981 |
+
db_range (`float`, *optional*):
|
| 982 |
+
Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
|
| 983 |
+
peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
|
| 984 |
+
|
| 985 |
+
Returns:
|
| 986 |
+
`np.ndarray`: the spectrogram in decibels
|
| 987 |
+
"""
|
| 988 |
+
if reference <= 0.0:
|
| 989 |
+
raise ValueError("reference must be greater than zero")
|
| 990 |
+
if min_value <= 0.0:
|
| 991 |
+
raise ValueError("min_value must be greater than zero")
|
| 992 |
+
|
| 993 |
+
reference = max(min_value, reference)
|
| 994 |
+
|
| 995 |
+
spectrogram = np.clip(spectrogram, a_min=min_value, a_max=None)
|
| 996 |
+
spectrogram = 20.0 * (np.log10(spectrogram) - np.log10(reference))
|
| 997 |
+
|
| 998 |
+
if db_range is not None:
|
| 999 |
+
if db_range <= 0.0:
|
| 1000 |
+
raise ValueError("db_range must be greater than zero")
|
| 1001 |
+
spectrogram = np.clip(spectrogram, a_min=spectrogram.max() - db_range, a_max=None)
|
| 1002 |
+
|
| 1003 |
+
return spectrogram
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
def amplitude_to_db_batch(
|
| 1007 |
+
spectrogram: np.ndarray, reference: float = 1.0, min_value: float = 1e-5, db_range: Optional[float] = None
|
| 1008 |
+
) -> np.ndarray:
|
| 1009 |
+
"""
|
| 1010 |
+
Converts a batch of amplitude spectrograms to the decibel scale. This computes `20 * log10(spectrogram / reference)`,
|
| 1011 |
+
using basic logarithm properties for numerical stability.
|
| 1012 |
+
|
| 1013 |
+
The function supports batch processing, where each item in the batch is an individual amplitude (mel) spectrogram.
|
| 1014 |
+
|
| 1015 |
+
Args:
|
| 1016 |
+
spectrogram (`np.ndarray`):
|
| 1017 |
+
The input batch of amplitude (mel) spectrograms. Expected shape is (batch_size, *spectrogram_shape).
|
| 1018 |
+
reference (`float`, *optional*, defaults to 1.0):
|
| 1019 |
+
Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
|
| 1020 |
+
the loudest part to 0 dB. Must be greater than zero.
|
| 1021 |
+
min_value (`float`, *optional*, defaults to `1e-5`):
|
| 1022 |
+
The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
|
| 1023 |
+
`log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero.
|
| 1024 |
+
db_range (`float`, *optional*):
|
| 1025 |
+
Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
|
| 1026 |
+
peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
|
| 1027 |
+
|
| 1028 |
+
Returns:
|
| 1029 |
+
`np.ndarray`: the batch of spectrograms in decibels
|
| 1030 |
+
"""
|
| 1031 |
+
if reference <= 0.0:
|
| 1032 |
+
raise ValueError("reference must be greater than zero")
|
| 1033 |
+
if min_value <= 0.0:
|
| 1034 |
+
raise ValueError("min_value must be greater than zero")
|
| 1035 |
+
|
| 1036 |
+
reference = max(min_value, reference)
|
| 1037 |
+
|
| 1038 |
+
spectrogram = np.clip(spectrogram, a_min=min_value, a_max=None)
|
| 1039 |
+
spectrogram = 20.0 * (np.log10(spectrogram) - np.log10(reference))
|
| 1040 |
+
|
| 1041 |
+
if db_range is not None:
|
| 1042 |
+
if db_range <= 0.0:
|
| 1043 |
+
raise ValueError("db_range must be greater than zero")
|
| 1044 |
+
# Apply db_range clipping per batch item
|
| 1045 |
+
max_values = spectrogram.max(axis=(1, 2), keepdims=True)
|
| 1046 |
+
spectrogram = np.clip(spectrogram, a_min=max_values - db_range, a_max=None)
|
| 1047 |
+
|
| 1048 |
+
return spectrogram
|
| 1049 |
+
|
| 1050 |
+
|
| 1051 |
+
### deprecated functions below this line ###
|
| 1052 |
+
|
| 1053 |
+
|
| 1054 |
+
def get_mel_filter_banks(
|
| 1055 |
+
nb_frequency_bins: int,
|
| 1056 |
+
nb_mel_filters: int,
|
| 1057 |
+
frequency_min: float,
|
| 1058 |
+
frequency_max: float,
|
| 1059 |
+
sample_rate: int,
|
| 1060 |
+
norm: Optional[str] = None,
|
| 1061 |
+
mel_scale: str = "htk",
|
| 1062 |
+
) -> np.array:
|
| 1063 |
+
warnings.warn(
|
| 1064 |
+
"The function `get_mel_filter_banks` is deprecated and will be removed in version 4.31.0 of Transformers",
|
| 1065 |
+
FutureWarning,
|
| 1066 |
+
)
|
| 1067 |
+
return mel_filter_bank(
|
| 1068 |
+
num_frequency_bins=nb_frequency_bins,
|
| 1069 |
+
num_mel_filters=nb_mel_filters,
|
| 1070 |
+
min_frequency=frequency_min,
|
| 1071 |
+
max_frequency=frequency_max,
|
| 1072 |
+
sampling_rate=sample_rate,
|
| 1073 |
+
norm=norm,
|
| 1074 |
+
mel_scale=mel_scale,
|
| 1075 |
+
)
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
def fram_wave(waveform: np.array, hop_length: int = 160, fft_window_size: int = 400, center: bool = True):
|
| 1079 |
+
"""
|
| 1080 |
+
In order to compute the short time fourier transform, the waveform needs to be split in overlapping windowed
|
| 1081 |
+
segments called `frames`.
|
| 1082 |
+
|
| 1083 |
+
The window length (window_length) defines how much of the signal is contained in each frame, while the hop length
|
| 1084 |
+
defines the step between the beginning of each new frame.
|
| 1085 |
+
|
| 1086 |
+
|
| 1087 |
+
Args:
|
| 1088 |
+
waveform (`np.array` of shape `(sample_length,)`):
|
| 1089 |
+
The raw waveform which will be split into smaller chunks.
|
| 1090 |
+
hop_length (`int`, *optional*, defaults to 160):
|
| 1091 |
+
Step between each window of the waveform.
|
| 1092 |
+
fft_window_size (`int`, *optional*, defaults to 400):
|
| 1093 |
+
Defines the size of the window.
|
| 1094 |
+
center (`bool`, defaults to `True`):
|
| 1095 |
+
Whether or not to center each frame around the middle of the frame. Centering is done by reflecting the
|
| 1096 |
+
waveform on the left and on the right.
|
| 1097 |
+
|
| 1098 |
+
Return:
|
| 1099 |
+
framed_waveform (`np.array` of shape `(waveform.shape // hop_length , fft_window_size)`):
|
| 1100 |
+
The framed waveforms that can be fed to `np.fft`.
|
| 1101 |
+
"""
|
| 1102 |
+
warnings.warn(
|
| 1103 |
+
"The function `fram_wave` is deprecated and will be removed in version 4.31.0 of Transformers",
|
| 1104 |
+
FutureWarning,
|
| 1105 |
+
)
|
| 1106 |
+
frames = []
|
| 1107 |
+
for i in range(0, waveform.shape[0] + 1, hop_length):
|
| 1108 |
+
if center:
|
| 1109 |
+
half_window = (fft_window_size - 1) // 2 + 1
|
| 1110 |
+
start = i - half_window if i > half_window else 0
|
| 1111 |
+
end = i + half_window if i < waveform.shape[0] - half_window else waveform.shape[0]
|
| 1112 |
+
frame = waveform[start:end]
|
| 1113 |
+
if start == 0:
|
| 1114 |
+
padd_width = (-i + half_window, 0)
|
| 1115 |
+
frame = np.pad(frame, pad_width=padd_width, mode="reflect")
|
| 1116 |
+
|
| 1117 |
+
elif end == waveform.shape[0]:
|
| 1118 |
+
padd_width = (0, (i - waveform.shape[0] + half_window))
|
| 1119 |
+
frame = np.pad(frame, pad_width=padd_width, mode="reflect")
|
| 1120 |
+
|
| 1121 |
+
else:
|
| 1122 |
+
frame = waveform[i : i + fft_window_size]
|
| 1123 |
+
frame_width = frame.shape[0]
|
| 1124 |
+
if frame_width < waveform.shape[0]:
|
| 1125 |
+
frame = np.lib.pad(
|
| 1126 |
+
frame, pad_width=(0, fft_window_size - frame_width), mode="constant", constant_values=0
|
| 1127 |
+
)
|
| 1128 |
+
frames.append(frame)
|
| 1129 |
+
|
| 1130 |
+
frames = np.stack(frames, 0)
|
| 1131 |
+
return frames
|
| 1132 |
+
|
| 1133 |
+
|
| 1134 |
+
def stft(frames: np.array, windowing_function: np.array, fft_window_size: Optional[int] = None):
|
| 1135 |
+
"""
|
| 1136 |
+
Calculates the complex Short-Time Fourier Transform (STFT) of the given framed signal. Should give the same results
|
| 1137 |
+
as `torch.stft`.
|
| 1138 |
+
|
| 1139 |
+
Args:
|
| 1140 |
+
frames (`np.array` of dimension `(num_frames, fft_window_size)`):
|
| 1141 |
+
A framed audio signal obtained using `audio_utils.fram_wav`.
|
| 1142 |
+
windowing_function (`np.array` of dimension `(nb_frequency_bins, nb_mel_filters)`:
|
| 1143 |
+
A array representing the function that will be used to reduces the amplitude of the discontinuities at the
|
| 1144 |
+
boundaries of each frame when computing the STFT. Each frame will be multiplied by the windowing_function.
|
| 1145 |
+
For more information on the discontinuities, called *Spectral leakage*, refer to [this
|
| 1146 |
+
tutorial]https://download.ni.com/evaluation/pxi/Understanding%20FFTs%20and%20Windowing.pdf
|
| 1147 |
+
fft_window_size (`int`, *optional*):
|
| 1148 |
+
Size of the window om which the Fourier transform is applied. This controls the frequency resolution of the
|
| 1149 |
+
spectrogram. 400 means that the fourrier transform is computed on windows of 400 samples. The number of
|
| 1150 |
+
frequency bins (`nb_frequency_bins`) used to divide the window into equal strips is equal to
|
| 1151 |
+
`(1+fft_window_size)//2`. An increase of the fft_window_size slows the calculus time proportionnally.
|
| 1152 |
+
|
| 1153 |
+
Example:
|
| 1154 |
+
|
| 1155 |
+
```python
|
| 1156 |
+
>>> from transformers.audio_utils import stft, fram_wave
|
| 1157 |
+
>>> import numpy as np
|
| 1158 |
+
|
| 1159 |
+
>>> audio = np.random.rand(50)
|
| 1160 |
+
>>> fft_window_size = 10
|
| 1161 |
+
>>> hop_length = 2
|
| 1162 |
+
>>> framed_audio = fram_wave(audio, hop_length, fft_window_size)
|
| 1163 |
+
>>> spectrogram = stft(framed_audio, np.hanning(fft_window_size + 1))
|
| 1164 |
+
```
|
| 1165 |
+
|
| 1166 |
+
Returns:
|
| 1167 |
+
spectrogram (`np.ndarray`):
|
| 1168 |
+
A spectrogram of shape `(num_frames, nb_frequency_bins)` obtained using the STFT algorithm
|
| 1169 |
+
"""
|
| 1170 |
+
warnings.warn(
|
| 1171 |
+
"The function `stft` is deprecated and will be removed in version 4.31.0 of Transformers",
|
| 1172 |
+
FutureWarning,
|
| 1173 |
+
)
|
| 1174 |
+
frame_size = frames.shape[1]
|
| 1175 |
+
|
| 1176 |
+
if fft_window_size is None:
|
| 1177 |
+
fft_window_size = frame_size
|
| 1178 |
+
|
| 1179 |
+
if fft_window_size < frame_size:
|
| 1180 |
+
raise ValueError("FFT size must greater or equal the frame size")
|
| 1181 |
+
# number of FFT bins to store
|
| 1182 |
+
nb_frequency_bins = (fft_window_size >> 1) + 1
|
| 1183 |
+
|
| 1184 |
+
spectrogram = np.empty((len(frames), nb_frequency_bins), dtype=np.complex64)
|
| 1185 |
+
fft_signal = np.zeros(fft_window_size)
|
| 1186 |
+
|
| 1187 |
+
for f, frame in enumerate(frames):
|
| 1188 |
+
if windowing_function is not None:
|
| 1189 |
+
np.multiply(frame, windowing_function, out=fft_signal[:frame_size])
|
| 1190 |
+
else:
|
| 1191 |
+
fft_signal[:frame_size] = frame
|
| 1192 |
+
spectrogram[f] = np.fft.fft(fft_signal, axis=0)[:nb_frequency_bins]
|
| 1193 |
+
return spectrogram.T
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/auto.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
# Modifications Copyright (C) 2025, Advanced Micro Devices, Inc. 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 |
+
import warnings
|
| 16 |
+
from typing import Dict, Optional, Union
|
| 17 |
+
|
| 18 |
+
from ..models.auto.configuration_auto import AutoConfig
|
| 19 |
+
from ..utils import logging
|
| 20 |
+
from ..utils.quantization_config import (
|
| 21 |
+
AqlmConfig,
|
| 22 |
+
AwqConfig,
|
| 23 |
+
BitNetConfig,
|
| 24 |
+
BitsAndBytesConfig,
|
| 25 |
+
CompressedTensorsConfig,
|
| 26 |
+
EetqConfig,
|
| 27 |
+
FbgemmFp8Config,
|
| 28 |
+
FineGrainedFP8Config,
|
| 29 |
+
GPTQConfig,
|
| 30 |
+
HiggsConfig,
|
| 31 |
+
HqqConfig,
|
| 32 |
+
QuantizationConfigMixin,
|
| 33 |
+
QuantizationMethod,
|
| 34 |
+
QuantoConfig,
|
| 35 |
+
QuarkConfig,
|
| 36 |
+
SpQRConfig,
|
| 37 |
+
TorchAoConfig,
|
| 38 |
+
VptqConfig,
|
| 39 |
+
)
|
| 40 |
+
from .base import HfQuantizer
|
| 41 |
+
from .quantizer_aqlm import AqlmHfQuantizer
|
| 42 |
+
from .quantizer_awq import AwqQuantizer
|
| 43 |
+
from .quantizer_bitnet import BitNetHfQuantizer
|
| 44 |
+
from .quantizer_bnb_4bit import Bnb4BitHfQuantizer
|
| 45 |
+
from .quantizer_bnb_8bit import Bnb8BitHfQuantizer
|
| 46 |
+
from .quantizer_compressed_tensors import CompressedTensorsHfQuantizer
|
| 47 |
+
from .quantizer_eetq import EetqHfQuantizer
|
| 48 |
+
from .quantizer_fbgemm_fp8 import FbgemmFp8HfQuantizer
|
| 49 |
+
from .quantizer_finegrained_fp8 import FineGrainedFP8HfQuantizer
|
| 50 |
+
from .quantizer_gptq import GptqHfQuantizer
|
| 51 |
+
from .quantizer_higgs import HiggsHfQuantizer
|
| 52 |
+
from .quantizer_hqq import HqqHfQuantizer
|
| 53 |
+
from .quantizer_quanto import QuantoHfQuantizer
|
| 54 |
+
from .quantizer_quark import QuarkHfQuantizer
|
| 55 |
+
from .quantizer_spqr import SpQRHfQuantizer
|
| 56 |
+
from .quantizer_torchao import TorchAoHfQuantizer
|
| 57 |
+
from .quantizer_vptq import VptqHfQuantizer
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
AUTO_QUANTIZER_MAPPING = {
|
| 61 |
+
"awq": AwqQuantizer,
|
| 62 |
+
"bitsandbytes_4bit": Bnb4BitHfQuantizer,
|
| 63 |
+
"bitsandbytes_8bit": Bnb8BitHfQuantizer,
|
| 64 |
+
"gptq": GptqHfQuantizer,
|
| 65 |
+
"aqlm": AqlmHfQuantizer,
|
| 66 |
+
"quanto": QuantoHfQuantizer,
|
| 67 |
+
"quark": QuarkHfQuantizer,
|
| 68 |
+
"eetq": EetqHfQuantizer,
|
| 69 |
+
"higgs": HiggsHfQuantizer,
|
| 70 |
+
"hqq": HqqHfQuantizer,
|
| 71 |
+
"compressed-tensors": CompressedTensorsHfQuantizer,
|
| 72 |
+
"fbgemm_fp8": FbgemmFp8HfQuantizer,
|
| 73 |
+
"torchao": TorchAoHfQuantizer,
|
| 74 |
+
"bitnet": BitNetHfQuantizer,
|
| 75 |
+
"vptq": VptqHfQuantizer,
|
| 76 |
+
"spqr": SpQRHfQuantizer,
|
| 77 |
+
"fp8": FineGrainedFP8HfQuantizer,
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
AUTO_QUANTIZATION_CONFIG_MAPPING = {
|
| 81 |
+
"awq": AwqConfig,
|
| 82 |
+
"bitsandbytes_4bit": BitsAndBytesConfig,
|
| 83 |
+
"bitsandbytes_8bit": BitsAndBytesConfig,
|
| 84 |
+
"eetq": EetqConfig,
|
| 85 |
+
"gptq": GPTQConfig,
|
| 86 |
+
"aqlm": AqlmConfig,
|
| 87 |
+
"quanto": QuantoConfig,
|
| 88 |
+
"quark": QuarkConfig,
|
| 89 |
+
"hqq": HqqConfig,
|
| 90 |
+
"compressed-tensors": CompressedTensorsConfig,
|
| 91 |
+
"fbgemm_fp8": FbgemmFp8Config,
|
| 92 |
+
"higgs": HiggsConfig,
|
| 93 |
+
"torchao": TorchAoConfig,
|
| 94 |
+
"bitnet": BitNetConfig,
|
| 95 |
+
"vptq": VptqConfig,
|
| 96 |
+
"spqr": SpQRConfig,
|
| 97 |
+
"fp8": FineGrainedFP8Config,
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
logger = logging.get_logger(__name__)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class AutoQuantizationConfig:
|
| 104 |
+
"""
|
| 105 |
+
The Auto-HF quantization config class that takes care of automatically dispatching to the correct
|
| 106 |
+
quantization config given a quantization config stored in a dictionary.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
@classmethod
|
| 110 |
+
def from_dict(cls, quantization_config_dict: Dict):
|
| 111 |
+
quant_method = quantization_config_dict.get("quant_method", None)
|
| 112 |
+
# We need a special care for bnb models to make sure everything is BC ..
|
| 113 |
+
if quantization_config_dict.get("load_in_8bit", False) or quantization_config_dict.get("load_in_4bit", False):
|
| 114 |
+
suffix = "_4bit" if quantization_config_dict.get("load_in_4bit", False) else "_8bit"
|
| 115 |
+
quant_method = QuantizationMethod.BITS_AND_BYTES + suffix
|
| 116 |
+
elif quant_method is None:
|
| 117 |
+
raise ValueError(
|
| 118 |
+
"The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized"
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
if quant_method not in AUTO_QUANTIZATION_CONFIG_MAPPING.keys():
|
| 122 |
+
raise ValueError(
|
| 123 |
+
f"Unknown quantization type, got {quant_method} - supported types are:"
|
| 124 |
+
f" {list(AUTO_QUANTIZER_MAPPING.keys())}"
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
target_cls = AUTO_QUANTIZATION_CONFIG_MAPPING[quant_method]
|
| 128 |
+
return target_cls.from_dict(quantization_config_dict)
|
| 129 |
+
|
| 130 |
+
@classmethod
|
| 131 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 132 |
+
model_config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 133 |
+
if getattr(model_config, "quantization_config", None) is None:
|
| 134 |
+
raise ValueError(
|
| 135 |
+
f"Did not found a `quantization_config` in {pretrained_model_name_or_path}. Make sure that the model is correctly quantized."
|
| 136 |
+
)
|
| 137 |
+
quantization_config_dict = model_config.quantization_config
|
| 138 |
+
quantization_config = cls.from_dict(quantization_config_dict)
|
| 139 |
+
# Update with potential kwargs that are passed through from_pretrained.
|
| 140 |
+
quantization_config.update(**kwargs)
|
| 141 |
+
return quantization_config
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class AutoHfQuantizer:
|
| 145 |
+
"""
|
| 146 |
+
The Auto-HF quantizer class that takes care of automatically instantiating to the correct
|
| 147 |
+
`HfQuantizer` given the `QuantizationConfig`.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
@classmethod
|
| 151 |
+
def from_config(cls, quantization_config: Union[QuantizationConfigMixin, Dict], **kwargs):
|
| 152 |
+
# Convert it to a QuantizationConfig if the q_config is a dict
|
| 153 |
+
if isinstance(quantization_config, dict):
|
| 154 |
+
quantization_config = AutoQuantizationConfig.from_dict(quantization_config)
|
| 155 |
+
|
| 156 |
+
quant_method = quantization_config.quant_method
|
| 157 |
+
|
| 158 |
+
# Again, we need a special care for bnb as we have a single quantization config
|
| 159 |
+
# class for both 4-bit and 8-bit quantization
|
| 160 |
+
if quant_method == QuantizationMethod.BITS_AND_BYTES:
|
| 161 |
+
if quantization_config.load_in_8bit:
|
| 162 |
+
quant_method += "_8bit"
|
| 163 |
+
else:
|
| 164 |
+
quant_method += "_4bit"
|
| 165 |
+
|
| 166 |
+
if quant_method not in AUTO_QUANTIZER_MAPPING.keys():
|
| 167 |
+
raise ValueError(
|
| 168 |
+
f"Unknown quantization type, got {quant_method} - supported types are:"
|
| 169 |
+
f" {list(AUTO_QUANTIZER_MAPPING.keys())}"
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
target_cls = AUTO_QUANTIZER_MAPPING[quant_method]
|
| 173 |
+
return target_cls(quantization_config, **kwargs)
|
| 174 |
+
|
| 175 |
+
@classmethod
|
| 176 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 177 |
+
quantization_config = AutoQuantizationConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 178 |
+
return cls.from_config(quantization_config)
|
| 179 |
+
|
| 180 |
+
@classmethod
|
| 181 |
+
def merge_quantization_configs(
|
| 182 |
+
cls,
|
| 183 |
+
quantization_config: Union[dict, QuantizationConfigMixin],
|
| 184 |
+
quantization_config_from_args: Optional[QuantizationConfigMixin],
|
| 185 |
+
):
|
| 186 |
+
"""
|
| 187 |
+
handles situations where both quantization_config from args and quantization_config from model config are present.
|
| 188 |
+
"""
|
| 189 |
+
if quantization_config_from_args is not None:
|
| 190 |
+
warning_msg = (
|
| 191 |
+
"You passed `quantization_config` or equivalent parameters to `from_pretrained` but the model you're loading"
|
| 192 |
+
" already has a `quantization_config` attribute. The `quantization_config` from the model will be used."
|
| 193 |
+
)
|
| 194 |
+
else:
|
| 195 |
+
warning_msg = ""
|
| 196 |
+
|
| 197 |
+
if isinstance(quantization_config, dict):
|
| 198 |
+
quantization_config = AutoQuantizationConfig.from_dict(quantization_config)
|
| 199 |
+
|
| 200 |
+
if (
|
| 201 |
+
isinstance(quantization_config, (GPTQConfig, AwqConfig, FbgemmFp8Config, CompressedTensorsConfig))
|
| 202 |
+
and quantization_config_from_args is not None
|
| 203 |
+
):
|
| 204 |
+
# special case for GPTQ / AWQ / FbgemmFp8 config collision
|
| 205 |
+
loading_attr_dict = quantization_config_from_args.get_loading_attributes()
|
| 206 |
+
for attr, val in loading_attr_dict.items():
|
| 207 |
+
setattr(quantization_config, attr, val)
|
| 208 |
+
|
| 209 |
+
warning_msg += f"However, loading attributes (e.g. {list(loading_attr_dict.keys())}) will be overwritten with the one you passed to `from_pretrained`. The rest will be ignored."
|
| 210 |
+
|
| 211 |
+
if warning_msg != "":
|
| 212 |
+
warnings.warn(warning_msg)
|
| 213 |
+
|
| 214 |
+
return quantization_config
|
| 215 |
+
|
| 216 |
+
@staticmethod
|
| 217 |
+
def supports_quant_method(quantization_config_dict):
|
| 218 |
+
quant_method = quantization_config_dict.get("quant_method", None)
|
| 219 |
+
if quantization_config_dict.get("load_in_8bit", False) or quantization_config_dict.get("load_in_4bit", False):
|
| 220 |
+
suffix = "_4bit" if quantization_config_dict.get("load_in_4bit", False) else "_8bit"
|
| 221 |
+
quant_method = QuantizationMethod.BITS_AND_BYTES + suffix
|
| 222 |
+
elif quant_method is None:
|
| 223 |
+
raise ValueError(
|
| 224 |
+
"The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized"
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
if quant_method not in AUTO_QUANTIZATION_CONFIG_MAPPING.keys():
|
| 228 |
+
logger.warning(
|
| 229 |
+
f"Unknown quantization type, got {quant_method} - supported types are:"
|
| 230 |
+
f" {list(AUTO_QUANTIZER_MAPPING.keys())}. Hence, we will skip the quantization. "
|
| 231 |
+
"To remove the warning, you can delete the quantization_config attribute in config.json"
|
| 232 |
+
)
|
| 233 |
+
return False
|
| 234 |
+
return True
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def register_quantization_config(method: str):
|
| 238 |
+
"""Register a custom quantization configuration."""
|
| 239 |
+
|
| 240 |
+
def register_config_fn(cls):
|
| 241 |
+
if method in AUTO_QUANTIZATION_CONFIG_MAPPING:
|
| 242 |
+
raise ValueError(f"Config '{method}' already registered")
|
| 243 |
+
|
| 244 |
+
if not issubclass(cls, QuantizationConfigMixin):
|
| 245 |
+
raise ValueError("Config must extend QuantizationConfigMixin")
|
| 246 |
+
|
| 247 |
+
AUTO_QUANTIZATION_CONFIG_MAPPING[method] = cls
|
| 248 |
+
return cls
|
| 249 |
+
|
| 250 |
+
return register_config_fn
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def register_quantizer(name: str):
|
| 254 |
+
"""Register a custom quantizer."""
|
| 255 |
+
|
| 256 |
+
def register_quantizer_fn(cls):
|
| 257 |
+
if name in AUTO_QUANTIZER_MAPPING:
|
| 258 |
+
raise ValueError(f"Quantizer '{name}' already registered")
|
| 259 |
+
|
| 260 |
+
if not issubclass(cls, HfQuantizer):
|
| 261 |
+
raise ValueError("Quantizer must extend HfQuantizer")
|
| 262 |
+
|
| 263 |
+
AUTO_QUANTIZER_MAPPING[name] = cls
|
| 264 |
+
return cls
|
| 265 |
+
|
| 266 |
+
return register_quantizer_fn
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/auto_factory.py
ADDED
|
@@ -0,0 +1,842 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 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 |
+
"""Factory function to build auto-model classes."""
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
import importlib
|
| 19 |
+
import json
|
| 20 |
+
import warnings
|
| 21 |
+
from collections import OrderedDict
|
| 22 |
+
|
| 23 |
+
from ...configuration_utils import PretrainedConfig
|
| 24 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
|
| 25 |
+
from ...utils import (
|
| 26 |
+
CONFIG_NAME,
|
| 27 |
+
cached_file,
|
| 28 |
+
copy_func,
|
| 29 |
+
extract_commit_hash,
|
| 30 |
+
find_adapter_config_file,
|
| 31 |
+
is_peft_available,
|
| 32 |
+
is_torch_available,
|
| 33 |
+
logging,
|
| 34 |
+
requires_backends,
|
| 35 |
+
)
|
| 36 |
+
from .configuration_auto import AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if is_torch_available():
|
| 40 |
+
from ...generation import GenerationMixin
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
logger = logging.get_logger(__name__)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
CLASS_DOCSTRING = """
|
| 47 |
+
This is a generic model class that will be instantiated as one of the model classes of the library when created
|
| 48 |
+
with the [`~BaseAutoModelClass.from_pretrained`] class method or the [`~BaseAutoModelClass.from_config`] class
|
| 49 |
+
method.
|
| 50 |
+
|
| 51 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
FROM_CONFIG_DOCSTRING = """
|
| 55 |
+
Instantiates one of the model classes of the library from a configuration.
|
| 56 |
+
|
| 57 |
+
Note:
|
| 58 |
+
Loading a model from its configuration file does **not** load the model weights. It only affects the
|
| 59 |
+
model's configuration. Use [`~BaseAutoModelClass.from_pretrained`] to load the model weights.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
config ([`PretrainedConfig`]):
|
| 63 |
+
The model class to instantiate is selected based on the configuration class:
|
| 64 |
+
|
| 65 |
+
List options
|
| 66 |
+
attn_implementation (`str`, *optional*):
|
| 67 |
+
The attention implementation to use in the model (if relevant). Can be any of `"eager"` (manual implementation of the attention), `"sdpa"` (using [`F.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention.html)), or `"flash_attention_2"` (using [Dao-AILab/flash-attention](https://github.com/Dao-AILab/flash-attention)). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual `"eager"` implementation.
|
| 68 |
+
|
| 69 |
+
Examples:
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
>>> from transformers import AutoConfig, BaseAutoModelClass
|
| 73 |
+
|
| 74 |
+
>>> # Download configuration from huggingface.co and cache.
|
| 75 |
+
>>> config = AutoConfig.from_pretrained("checkpoint_placeholder")
|
| 76 |
+
>>> model = BaseAutoModelClass.from_config(config)
|
| 77 |
+
```
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
FROM_PRETRAINED_TORCH_DOCSTRING = """
|
| 81 |
+
Instantiate one of the model classes of the library from a pretrained model.
|
| 82 |
+
|
| 83 |
+
The model class to instantiate is selected based on the `model_type` property of the config object (either
|
| 84 |
+
passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
|
| 85 |
+
falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 86 |
+
|
| 87 |
+
List options
|
| 88 |
+
|
| 89 |
+
The model is set in evaluation mode by default using `model.eval()` (so for instance, dropout modules are
|
| 90 |
+
deactivated). To train the model, you should first set it back in training mode with `model.train()`
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 94 |
+
Can be either:
|
| 95 |
+
|
| 96 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
| 97 |
+
- A path to a *directory* containing model weights saved using
|
| 98 |
+
[`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
|
| 99 |
+
- A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
|
| 100 |
+
this case, `from_tf` should be set to `True` and a configuration object should be provided as
|
| 101 |
+
`config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
|
| 102 |
+
PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
|
| 103 |
+
model_args (additional positional arguments, *optional*):
|
| 104 |
+
Will be passed along to the underlying model `__init__()` method.
|
| 105 |
+
config ([`PretrainedConfig`], *optional*):
|
| 106 |
+
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
|
| 107 |
+
be automatically loaded when:
|
| 108 |
+
|
| 109 |
+
- The model is a model provided by the library (loaded with the *model id* string of a pretrained
|
| 110 |
+
model).
|
| 111 |
+
- The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
|
| 112 |
+
save directory.
|
| 113 |
+
- The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
|
| 114 |
+
configuration JSON file named *config.json* is found in the directory.
|
| 115 |
+
state_dict (*Dict[str, torch.Tensor]*, *optional*):
|
| 116 |
+
A state dictionary to use instead of a state dictionary loaded from saved weights file.
|
| 117 |
+
|
| 118 |
+
This option can be used if you want to create a model from a pretrained configuration but load your own
|
| 119 |
+
weights. In this case though, you should check if using [`~PreTrainedModel.save_pretrained`] and
|
| 120 |
+
[`~PreTrainedModel.from_pretrained`] is not a simpler option.
|
| 121 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 122 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 123 |
+
standard cache should not be used.
|
| 124 |
+
from_tf (`bool`, *optional*, defaults to `False`):
|
| 125 |
+
Load the model weights from a TensorFlow checkpoint save file (see docstring of
|
| 126 |
+
`pretrained_model_name_or_path` argument).
|
| 127 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 128 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 129 |
+
cached versions if they exist.
|
| 130 |
+
resume_download:
|
| 131 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 132 |
+
Will be removed in v5 of Transformers.
|
| 133 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 134 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 135 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 136 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 137 |
+
Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 138 |
+
local_files_only(`bool`, *optional*, defaults to `False`):
|
| 139 |
+
Whether or not to only look at local files (e.g., not try downloading the model).
|
| 140 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 141 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 142 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 143 |
+
identifier allowed by git.
|
| 144 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 145 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 146 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 147 |
+
execute code present on the Hub on your local machine.
|
| 148 |
+
code_revision (`str`, *optional*, defaults to `"main"`):
|
| 149 |
+
The specific revision to use for the code on the Hub, if the code leaves in a different repository than
|
| 150 |
+
the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based
|
| 151 |
+
system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier
|
| 152 |
+
allowed by git.
|
| 153 |
+
kwargs (additional keyword arguments, *optional*):
|
| 154 |
+
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
|
| 155 |
+
`output_attentions=True`). Behaves differently depending on whether a `config` is provided or
|
| 156 |
+
automatically loaded:
|
| 157 |
+
|
| 158 |
+
- If a configuration is provided with `config`, `**kwargs` will be directly passed to the
|
| 159 |
+
underlying model's `__init__` method (we assume all relevant updates to the configuration have
|
| 160 |
+
already been done)
|
| 161 |
+
- If a configuration is not provided, `kwargs` will be first passed to the configuration class
|
| 162 |
+
initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
|
| 163 |
+
corresponds to a configuration attribute will be used to override said attribute with the
|
| 164 |
+
supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
|
| 165 |
+
will be passed to the underlying model's `__init__` function.
|
| 166 |
+
|
| 167 |
+
Examples:
|
| 168 |
+
|
| 169 |
+
```python
|
| 170 |
+
>>> from transformers import AutoConfig, BaseAutoModelClass
|
| 171 |
+
|
| 172 |
+
>>> # Download model and configuration from huggingface.co and cache.
|
| 173 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder")
|
| 174 |
+
|
| 175 |
+
>>> # Update configuration during loading
|
| 176 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder", output_attentions=True)
|
| 177 |
+
>>> model.config.output_attentions
|
| 178 |
+
True
|
| 179 |
+
|
| 180 |
+
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
|
| 181 |
+
>>> config = AutoConfig.from_pretrained("./tf_model/shortcut_placeholder_tf_model_config.json")
|
| 182 |
+
>>> model = BaseAutoModelClass.from_pretrained(
|
| 183 |
+
... "./tf_model/shortcut_placeholder_tf_checkpoint.ckpt.index", from_tf=True, config=config
|
| 184 |
+
... )
|
| 185 |
+
```
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
FROM_PRETRAINED_TF_DOCSTRING = """
|
| 189 |
+
Instantiate one of the model classes of the library from a pretrained model.
|
| 190 |
+
|
| 191 |
+
The model class to instantiate is selected based on the `model_type` property of the config object (either
|
| 192 |
+
passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
|
| 193 |
+
falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 194 |
+
|
| 195 |
+
List options
|
| 196 |
+
|
| 197 |
+
Args:
|
| 198 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 199 |
+
Can be either:
|
| 200 |
+
|
| 201 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
| 202 |
+
- A path to a *directory* containing model weights saved using
|
| 203 |
+
[`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
|
| 204 |
+
- A path or url to a *PyTorch state_dict save file* (e.g, `./pt_model/pytorch_model.bin`). In this
|
| 205 |
+
case, `from_pt` should be set to `True` and a configuration object should be provided as `config`
|
| 206 |
+
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model
|
| 207 |
+
using the provided conversion scripts and loading the TensorFlow model afterwards.
|
| 208 |
+
model_args (additional positional arguments, *optional*):
|
| 209 |
+
Will be passed along to the underlying model `__init__()` method.
|
| 210 |
+
config ([`PretrainedConfig`], *optional*):
|
| 211 |
+
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
|
| 212 |
+
be automatically loaded when:
|
| 213 |
+
|
| 214 |
+
- The model is a model provided by the library (loaded with the *model id* string of a pretrained
|
| 215 |
+
model).
|
| 216 |
+
- The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
|
| 217 |
+
save directory.
|
| 218 |
+
- The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
|
| 219 |
+
configuration JSON file named *config.json* is found in the directory.
|
| 220 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 221 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 222 |
+
standard cache should not be used.
|
| 223 |
+
from_pt (`bool`, *optional*, defaults to `False`):
|
| 224 |
+
Load the model weights from a PyTorch checkpoint save file (see docstring of
|
| 225 |
+
`pretrained_model_name_or_path` argument).
|
| 226 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 227 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 228 |
+
cached versions if they exist.
|
| 229 |
+
resume_download:
|
| 230 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 231 |
+
Will be removed in v5 of Transformers.
|
| 232 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 233 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 234 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 235 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 236 |
+
Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 237 |
+
local_files_only(`bool`, *optional*, defaults to `False`):
|
| 238 |
+
Whether or not to only look at local files (e.g., not try downloading the model).
|
| 239 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 240 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 241 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 242 |
+
identifier allowed by git.
|
| 243 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 244 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 245 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 246 |
+
execute code present on the Hub on your local machine.
|
| 247 |
+
code_revision (`str`, *optional*, defaults to `"main"`):
|
| 248 |
+
The specific revision to use for the code on the Hub, if the code leaves in a different repository than
|
| 249 |
+
the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based
|
| 250 |
+
system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier
|
| 251 |
+
allowed by git.
|
| 252 |
+
kwargs (additional keyword arguments, *optional*):
|
| 253 |
+
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
|
| 254 |
+
`output_attentions=True`). Behaves differently depending on whether a `config` is provided or
|
| 255 |
+
automatically loaded:
|
| 256 |
+
|
| 257 |
+
- If a configuration is provided with `config`, `**kwargs` will be directly passed to the
|
| 258 |
+
underlying model's `__init__` method (we assume all relevant updates to the configuration have
|
| 259 |
+
already been done)
|
| 260 |
+
- If a configuration is not provided, `kwargs` will be first passed to the configuration class
|
| 261 |
+
initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
|
| 262 |
+
corresponds to a configuration attribute will be used to override said attribute with the
|
| 263 |
+
supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
|
| 264 |
+
will be passed to the underlying model's `__init__` function.
|
| 265 |
+
|
| 266 |
+
Examples:
|
| 267 |
+
|
| 268 |
+
```python
|
| 269 |
+
>>> from transformers import AutoConfig, BaseAutoModelClass
|
| 270 |
+
|
| 271 |
+
>>> # Download model and configuration from huggingface.co and cache.
|
| 272 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder")
|
| 273 |
+
|
| 274 |
+
>>> # Update configuration during loading
|
| 275 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder", output_attentions=True)
|
| 276 |
+
>>> model.config.output_attentions
|
| 277 |
+
True
|
| 278 |
+
|
| 279 |
+
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
|
| 280 |
+
>>> config = AutoConfig.from_pretrained("./pt_model/shortcut_placeholder_pt_model_config.json")
|
| 281 |
+
>>> model = BaseAutoModelClass.from_pretrained(
|
| 282 |
+
... "./pt_model/shortcut_placeholder_pytorch_model.bin", from_pt=True, config=config
|
| 283 |
+
... )
|
| 284 |
+
```
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
FROM_PRETRAINED_FLAX_DOCSTRING = """
|
| 288 |
+
Instantiate one of the model classes of the library from a pretrained model.
|
| 289 |
+
|
| 290 |
+
The model class to instantiate is selected based on the `model_type` property of the config object (either
|
| 291 |
+
passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
|
| 292 |
+
falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 293 |
+
|
| 294 |
+
List options
|
| 295 |
+
|
| 296 |
+
Args:
|
| 297 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 298 |
+
Can be either:
|
| 299 |
+
|
| 300 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
| 301 |
+
- A path to a *directory* containing model weights saved using
|
| 302 |
+
[`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
|
| 303 |
+
- A path or url to a *PyTorch state_dict save file* (e.g, `./pt_model/pytorch_model.bin`). In this
|
| 304 |
+
case, `from_pt` should be set to `True` and a configuration object should be provided as `config`
|
| 305 |
+
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model
|
| 306 |
+
using the provided conversion scripts and loading the TensorFlow model afterwards.
|
| 307 |
+
model_args (additional positional arguments, *optional*):
|
| 308 |
+
Will be passed along to the underlying model `__init__()` method.
|
| 309 |
+
config ([`PretrainedConfig`], *optional*):
|
| 310 |
+
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
|
| 311 |
+
be automatically loaded when:
|
| 312 |
+
|
| 313 |
+
- The model is a model provided by the library (loaded with the *model id* string of a pretrained
|
| 314 |
+
model).
|
| 315 |
+
- The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
|
| 316 |
+
save directory.
|
| 317 |
+
- The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
|
| 318 |
+
configuration JSON file named *config.json* is found in the directory.
|
| 319 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 320 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 321 |
+
standard cache should not be used.
|
| 322 |
+
from_pt (`bool`, *optional*, defaults to `False`):
|
| 323 |
+
Load the model weights from a PyTorch checkpoint save file (see docstring of
|
| 324 |
+
`pretrained_model_name_or_path` argument).
|
| 325 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 326 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 327 |
+
cached versions if they exist.
|
| 328 |
+
resume_download:
|
| 329 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 330 |
+
Will be removed in v5 of Transformers.
|
| 331 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 332 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 333 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 334 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 335 |
+
Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 336 |
+
local_files_only(`bool`, *optional*, defaults to `False`):
|
| 337 |
+
Whether or not to only look at local files (e.g., not try downloading the model).
|
| 338 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 339 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 340 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 341 |
+
identifier allowed by git.
|
| 342 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 343 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 344 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 345 |
+
execute code present on the Hub on your local machine.
|
| 346 |
+
code_revision (`str`, *optional*, defaults to `"main"`):
|
| 347 |
+
The specific revision to use for the code on the Hub, if the code leaves in a different repository than
|
| 348 |
+
the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based
|
| 349 |
+
system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier
|
| 350 |
+
allowed by git.
|
| 351 |
+
kwargs (additional keyword arguments, *optional*):
|
| 352 |
+
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
|
| 353 |
+
`output_attentions=True`). Behaves differently depending on whether a `config` is provided or
|
| 354 |
+
automatically loaded:
|
| 355 |
+
|
| 356 |
+
- If a configuration is provided with `config`, `**kwargs` will be directly passed to the
|
| 357 |
+
underlying model's `__init__` method (we assume all relevant updates to the configuration have
|
| 358 |
+
already been done)
|
| 359 |
+
- If a configuration is not provided, `kwargs` will be first passed to the configuration class
|
| 360 |
+
initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
|
| 361 |
+
corresponds to a configuration attribute will be used to override said attribute with the
|
| 362 |
+
supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
|
| 363 |
+
will be passed to the underlying model's `__init__` function.
|
| 364 |
+
|
| 365 |
+
Examples:
|
| 366 |
+
|
| 367 |
+
```python
|
| 368 |
+
>>> from transformers import AutoConfig, BaseAutoModelClass
|
| 369 |
+
|
| 370 |
+
>>> # Download model and configuration from huggingface.co and cache.
|
| 371 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder")
|
| 372 |
+
|
| 373 |
+
>>> # Update configuration during loading
|
| 374 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder", output_attentions=True)
|
| 375 |
+
>>> model.config.output_attentions
|
| 376 |
+
True
|
| 377 |
+
|
| 378 |
+
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
|
| 379 |
+
>>> config = AutoConfig.from_pretrained("./pt_model/shortcut_placeholder_pt_model_config.json")
|
| 380 |
+
>>> model = BaseAutoModelClass.from_pretrained(
|
| 381 |
+
... "./pt_model/shortcut_placeholder_pytorch_model.bin", from_pt=True, config=config
|
| 382 |
+
... )
|
| 383 |
+
```
|
| 384 |
+
"""
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def _get_model_class(config, model_mapping):
|
| 388 |
+
supported_models = model_mapping[type(config)]
|
| 389 |
+
if not isinstance(supported_models, (list, tuple)):
|
| 390 |
+
return supported_models
|
| 391 |
+
|
| 392 |
+
name_to_model = {model.__name__: model for model in supported_models}
|
| 393 |
+
architectures = getattr(config, "architectures", [])
|
| 394 |
+
for arch in architectures:
|
| 395 |
+
if arch in name_to_model:
|
| 396 |
+
return name_to_model[arch]
|
| 397 |
+
elif f"TF{arch}" in name_to_model:
|
| 398 |
+
return name_to_model[f"TF{arch}"]
|
| 399 |
+
elif f"Flax{arch}" in name_to_model:
|
| 400 |
+
return name_to_model[f"Flax{arch}"]
|
| 401 |
+
|
| 402 |
+
# If not architecture is set in the config or match the supported models, the first element of the tuple is the
|
| 403 |
+
# defaults.
|
| 404 |
+
return supported_models[0]
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class _BaseAutoModelClass:
|
| 408 |
+
# Base class for auto models.
|
| 409 |
+
_model_mapping = None
|
| 410 |
+
|
| 411 |
+
def __init__(self, *args, **kwargs):
|
| 412 |
+
raise EnvironmentError(
|
| 413 |
+
f"{self.__class__.__name__} is designed to be instantiated "
|
| 414 |
+
f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
|
| 415 |
+
f"`{self.__class__.__name__}.from_config(config)` methods."
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
@classmethod
|
| 419 |
+
def from_config(cls, config, **kwargs):
|
| 420 |
+
trust_remote_code = kwargs.pop("trust_remote_code", None)
|
| 421 |
+
has_remote_code = hasattr(config, "auto_map") and cls.__name__ in config.auto_map
|
| 422 |
+
has_local_code = type(config) in cls._model_mapping.keys()
|
| 423 |
+
trust_remote_code = resolve_trust_remote_code(
|
| 424 |
+
trust_remote_code, config._name_or_path, has_local_code, has_remote_code
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
if has_remote_code and trust_remote_code:
|
| 428 |
+
class_ref = config.auto_map[cls.__name__]
|
| 429 |
+
if "--" in class_ref:
|
| 430 |
+
repo_id, class_ref = class_ref.split("--")
|
| 431 |
+
else:
|
| 432 |
+
repo_id = config.name_or_path
|
| 433 |
+
model_class = get_class_from_dynamic_module(class_ref, repo_id, **kwargs)
|
| 434 |
+
cls.register(config.__class__, model_class, exist_ok=True)
|
| 435 |
+
_ = kwargs.pop("code_revision", None)
|
| 436 |
+
model_class = add_generation_mixin_to_remote_model(model_class)
|
| 437 |
+
return model_class._from_config(config, **kwargs)
|
| 438 |
+
elif type(config) in cls._model_mapping.keys():
|
| 439 |
+
model_class = _get_model_class(config, cls._model_mapping)
|
| 440 |
+
return model_class._from_config(config, **kwargs)
|
| 441 |
+
|
| 442 |
+
raise ValueError(
|
| 443 |
+
f"Unrecognized configuration class {config.__class__} for this kind of AutoModel: {cls.__name__}.\n"
|
| 444 |
+
f"Model type should be one of {', '.join(c.__name__ for c in cls._model_mapping.keys())}."
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
@classmethod
|
| 448 |
+
def _prepare_config_for_auto_class(cls, config: PretrainedConfig) -> PretrainedConfig:
|
| 449 |
+
"""Additional autoclass-specific config post-loading manipulation. May be overridden in subclasses."""
|
| 450 |
+
return config
|
| 451 |
+
|
| 452 |
+
@classmethod
|
| 453 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 454 |
+
config = kwargs.pop("config", None)
|
| 455 |
+
trust_remote_code = kwargs.pop("trust_remote_code", None)
|
| 456 |
+
kwargs["_from_auto"] = True
|
| 457 |
+
hub_kwargs_names = [
|
| 458 |
+
"cache_dir",
|
| 459 |
+
"force_download",
|
| 460 |
+
"local_files_only",
|
| 461 |
+
"proxies",
|
| 462 |
+
"resume_download",
|
| 463 |
+
"revision",
|
| 464 |
+
"subfolder",
|
| 465 |
+
"use_auth_token",
|
| 466 |
+
"token",
|
| 467 |
+
]
|
| 468 |
+
hub_kwargs = {name: kwargs.pop(name) for name in hub_kwargs_names if name in kwargs}
|
| 469 |
+
code_revision = kwargs.pop("code_revision", None)
|
| 470 |
+
commit_hash = kwargs.pop("_commit_hash", None)
|
| 471 |
+
adapter_kwargs = kwargs.pop("adapter_kwargs", None)
|
| 472 |
+
|
| 473 |
+
token = hub_kwargs.pop("token", None)
|
| 474 |
+
use_auth_token = hub_kwargs.pop("use_auth_token", None)
|
| 475 |
+
if use_auth_token is not None:
|
| 476 |
+
warnings.warn(
|
| 477 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 478 |
+
FutureWarning,
|
| 479 |
+
)
|
| 480 |
+
if token is not None:
|
| 481 |
+
raise ValueError(
|
| 482 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 483 |
+
)
|
| 484 |
+
token = use_auth_token
|
| 485 |
+
|
| 486 |
+
if token is not None:
|
| 487 |
+
hub_kwargs["token"] = token
|
| 488 |
+
|
| 489 |
+
if commit_hash is None:
|
| 490 |
+
if not isinstance(config, PretrainedConfig):
|
| 491 |
+
# We make a call to the config file first (which may be absent) to get the commit hash as soon as possible
|
| 492 |
+
resolved_config_file = cached_file(
|
| 493 |
+
pretrained_model_name_or_path,
|
| 494 |
+
CONFIG_NAME,
|
| 495 |
+
_raise_exceptions_for_gated_repo=False,
|
| 496 |
+
_raise_exceptions_for_missing_entries=False,
|
| 497 |
+
_raise_exceptions_for_connection_errors=False,
|
| 498 |
+
**hub_kwargs,
|
| 499 |
+
)
|
| 500 |
+
commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
|
| 501 |
+
else:
|
| 502 |
+
commit_hash = getattr(config, "_commit_hash", None)
|
| 503 |
+
|
| 504 |
+
if is_peft_available():
|
| 505 |
+
if adapter_kwargs is None:
|
| 506 |
+
adapter_kwargs = {}
|
| 507 |
+
if token is not None:
|
| 508 |
+
adapter_kwargs["token"] = token
|
| 509 |
+
|
| 510 |
+
maybe_adapter_path = find_adapter_config_file(
|
| 511 |
+
pretrained_model_name_or_path, _commit_hash=commit_hash, **adapter_kwargs
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
if maybe_adapter_path is not None:
|
| 515 |
+
with open(maybe_adapter_path, "r", encoding="utf-8") as f:
|
| 516 |
+
adapter_config = json.load(f)
|
| 517 |
+
|
| 518 |
+
adapter_kwargs["_adapter_model_path"] = pretrained_model_name_or_path
|
| 519 |
+
pretrained_model_name_or_path = adapter_config["base_model_name_or_path"]
|
| 520 |
+
|
| 521 |
+
if not isinstance(config, PretrainedConfig):
|
| 522 |
+
kwargs_orig = copy.deepcopy(kwargs)
|
| 523 |
+
# ensure not to pollute the config object with torch_dtype="auto" - since it's
|
| 524 |
+
# meaningless in the context of the config object - torch.dtype values are acceptable
|
| 525 |
+
if kwargs.get("torch_dtype", None) == "auto":
|
| 526 |
+
_ = kwargs.pop("torch_dtype")
|
| 527 |
+
# to not overwrite the quantization_config if config has a quantization_config
|
| 528 |
+
if kwargs.get("quantization_config", None) is not None:
|
| 529 |
+
_ = kwargs.pop("quantization_config")
|
| 530 |
+
|
| 531 |
+
config, kwargs = AutoConfig.from_pretrained(
|
| 532 |
+
pretrained_model_name_or_path,
|
| 533 |
+
return_unused_kwargs=True,
|
| 534 |
+
trust_remote_code=trust_remote_code,
|
| 535 |
+
code_revision=code_revision,
|
| 536 |
+
_commit_hash=commit_hash,
|
| 537 |
+
**hub_kwargs,
|
| 538 |
+
**kwargs,
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
# if torch_dtype=auto was passed here, ensure to pass it on
|
| 542 |
+
if kwargs_orig.get("torch_dtype", None) == "auto":
|
| 543 |
+
kwargs["torch_dtype"] = "auto"
|
| 544 |
+
if kwargs_orig.get("quantization_config", None) is not None:
|
| 545 |
+
kwargs["quantization_config"] = kwargs_orig["quantization_config"]
|
| 546 |
+
|
| 547 |
+
has_remote_code = hasattr(config, "auto_map") and cls.__name__ in config.auto_map
|
| 548 |
+
has_local_code = type(config) in cls._model_mapping.keys()
|
| 549 |
+
trust_remote_code = resolve_trust_remote_code(
|
| 550 |
+
trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
# Set the adapter kwargs
|
| 554 |
+
kwargs["adapter_kwargs"] = adapter_kwargs
|
| 555 |
+
|
| 556 |
+
if has_remote_code and trust_remote_code:
|
| 557 |
+
class_ref = config.auto_map[cls.__name__]
|
| 558 |
+
model_class = get_class_from_dynamic_module(
|
| 559 |
+
class_ref, pretrained_model_name_or_path, code_revision=code_revision, **hub_kwargs, **kwargs
|
| 560 |
+
)
|
| 561 |
+
_ = hub_kwargs.pop("code_revision", None)
|
| 562 |
+
cls.register(config.__class__, model_class, exist_ok=True)
|
| 563 |
+
model_class = add_generation_mixin_to_remote_model(model_class)
|
| 564 |
+
return model_class.from_pretrained(
|
| 565 |
+
pretrained_model_name_or_path, *model_args, config=config, **hub_kwargs, **kwargs
|
| 566 |
+
)
|
| 567 |
+
elif type(config) in cls._model_mapping.keys():
|
| 568 |
+
model_class = _get_model_class(config, cls._model_mapping)
|
| 569 |
+
if model_class.config_class == config.sub_configs.get("text_config", None):
|
| 570 |
+
config = config.get_text_config()
|
| 571 |
+
return model_class.from_pretrained(
|
| 572 |
+
pretrained_model_name_or_path, *model_args, config=config, **hub_kwargs, **kwargs
|
| 573 |
+
)
|
| 574 |
+
raise ValueError(
|
| 575 |
+
f"Unrecognized configuration class {config.__class__} for this kind of AutoModel: {cls.__name__}.\n"
|
| 576 |
+
f"Model type should be one of {', '.join(c.__name__ for c in cls._model_mapping.keys())}."
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
@classmethod
|
| 580 |
+
def register(cls, config_class, model_class, exist_ok=False):
|
| 581 |
+
"""
|
| 582 |
+
Register a new model for this class.
|
| 583 |
+
|
| 584 |
+
Args:
|
| 585 |
+
config_class ([`PretrainedConfig`]):
|
| 586 |
+
The configuration corresponding to the model to register.
|
| 587 |
+
model_class ([`PreTrainedModel`]):
|
| 588 |
+
The model to register.
|
| 589 |
+
"""
|
| 590 |
+
if hasattr(model_class, "config_class") and model_class.config_class.__name__ != config_class.__name__:
|
| 591 |
+
raise ValueError(
|
| 592 |
+
"The model class you are passing has a `config_class` attribute that is not consistent with the "
|
| 593 |
+
f"config class you passed (model has {model_class.config_class} and you passed {config_class}. Fix "
|
| 594 |
+
"one of those so they match!"
|
| 595 |
+
)
|
| 596 |
+
cls._model_mapping.register(config_class, model_class, exist_ok=exist_ok)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
class _BaseAutoBackboneClass(_BaseAutoModelClass):
|
| 600 |
+
# Base class for auto backbone models.
|
| 601 |
+
_model_mapping = None
|
| 602 |
+
|
| 603 |
+
@classmethod
|
| 604 |
+
def _load_timm_backbone_from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 605 |
+
requires_backends(cls, ["vision", "timm"])
|
| 606 |
+
from ...models.timm_backbone import TimmBackboneConfig
|
| 607 |
+
|
| 608 |
+
config = kwargs.pop("config", TimmBackboneConfig())
|
| 609 |
+
|
| 610 |
+
if kwargs.get("out_features", None) is not None:
|
| 611 |
+
raise ValueError("Cannot specify `out_features` for timm backbones")
|
| 612 |
+
|
| 613 |
+
if kwargs.get("output_loading_info", False):
|
| 614 |
+
raise ValueError("Cannot specify `output_loading_info=True` when loading from timm")
|
| 615 |
+
|
| 616 |
+
num_channels = kwargs.pop("num_channels", config.num_channels)
|
| 617 |
+
features_only = kwargs.pop("features_only", config.features_only)
|
| 618 |
+
use_pretrained_backbone = kwargs.pop("use_pretrained_backbone", config.use_pretrained_backbone)
|
| 619 |
+
out_indices = kwargs.pop("out_indices", config.out_indices)
|
| 620 |
+
config = TimmBackboneConfig(
|
| 621 |
+
backbone=pretrained_model_name_or_path,
|
| 622 |
+
num_channels=num_channels,
|
| 623 |
+
features_only=features_only,
|
| 624 |
+
use_pretrained_backbone=use_pretrained_backbone,
|
| 625 |
+
out_indices=out_indices,
|
| 626 |
+
)
|
| 627 |
+
return super().from_config(config, **kwargs)
|
| 628 |
+
|
| 629 |
+
@classmethod
|
| 630 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 631 |
+
use_timm_backbone = kwargs.pop("use_timm_backbone", False)
|
| 632 |
+
if use_timm_backbone:
|
| 633 |
+
return cls._load_timm_backbone_from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 634 |
+
|
| 635 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def insert_head_doc(docstring, head_doc=""):
|
| 639 |
+
if len(head_doc) > 0:
|
| 640 |
+
return docstring.replace(
|
| 641 |
+
"one of the model classes of the library ",
|
| 642 |
+
f"one of the model classes of the library (with a {head_doc} head) ",
|
| 643 |
+
)
|
| 644 |
+
return docstring.replace(
|
| 645 |
+
"one of the model classes of the library ", "one of the base model classes of the library "
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def auto_class_update(cls, checkpoint_for_example="google-bert/bert-base-cased", head_doc=""):
|
| 650 |
+
# Create a new class with the right name from the base class
|
| 651 |
+
model_mapping = cls._model_mapping
|
| 652 |
+
name = cls.__name__
|
| 653 |
+
class_docstring = insert_head_doc(CLASS_DOCSTRING, head_doc=head_doc)
|
| 654 |
+
cls.__doc__ = class_docstring.replace("BaseAutoModelClass", name)
|
| 655 |
+
|
| 656 |
+
# Now we need to copy and re-register `from_config` and `from_pretrained` as class methods otherwise we can't
|
| 657 |
+
# have a specific docstrings for them.
|
| 658 |
+
from_config = copy_func(_BaseAutoModelClass.from_config)
|
| 659 |
+
from_config_docstring = insert_head_doc(FROM_CONFIG_DOCSTRING, head_doc=head_doc)
|
| 660 |
+
from_config_docstring = from_config_docstring.replace("BaseAutoModelClass", name)
|
| 661 |
+
from_config_docstring = from_config_docstring.replace("checkpoint_placeholder", checkpoint_for_example)
|
| 662 |
+
from_config.__doc__ = from_config_docstring
|
| 663 |
+
from_config = replace_list_option_in_docstrings(model_mapping._model_mapping, use_model_types=False)(from_config)
|
| 664 |
+
cls.from_config = classmethod(from_config)
|
| 665 |
+
|
| 666 |
+
if name.startswith("TF"):
|
| 667 |
+
from_pretrained_docstring = FROM_PRETRAINED_TF_DOCSTRING
|
| 668 |
+
elif name.startswith("Flax"):
|
| 669 |
+
from_pretrained_docstring = FROM_PRETRAINED_FLAX_DOCSTRING
|
| 670 |
+
else:
|
| 671 |
+
from_pretrained_docstring = FROM_PRETRAINED_TORCH_DOCSTRING
|
| 672 |
+
from_pretrained = copy_func(_BaseAutoModelClass.from_pretrained)
|
| 673 |
+
from_pretrained_docstring = insert_head_doc(from_pretrained_docstring, head_doc=head_doc)
|
| 674 |
+
from_pretrained_docstring = from_pretrained_docstring.replace("BaseAutoModelClass", name)
|
| 675 |
+
from_pretrained_docstring = from_pretrained_docstring.replace("checkpoint_placeholder", checkpoint_for_example)
|
| 676 |
+
shortcut = checkpoint_for_example.split("/")[-1].split("-")[0]
|
| 677 |
+
from_pretrained_docstring = from_pretrained_docstring.replace("shortcut_placeholder", shortcut)
|
| 678 |
+
from_pretrained.__doc__ = from_pretrained_docstring
|
| 679 |
+
from_pretrained = replace_list_option_in_docstrings(model_mapping._model_mapping)(from_pretrained)
|
| 680 |
+
cls.from_pretrained = classmethod(from_pretrained)
|
| 681 |
+
return cls
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def get_values(model_mapping):
|
| 685 |
+
result = []
|
| 686 |
+
for model in model_mapping.values():
|
| 687 |
+
if isinstance(model, (list, tuple)):
|
| 688 |
+
result += list(model)
|
| 689 |
+
else:
|
| 690 |
+
result.append(model)
|
| 691 |
+
|
| 692 |
+
return result
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def getattribute_from_module(module, attr):
|
| 696 |
+
if attr is None:
|
| 697 |
+
return None
|
| 698 |
+
if isinstance(attr, tuple):
|
| 699 |
+
return tuple(getattribute_from_module(module, a) for a in attr)
|
| 700 |
+
if hasattr(module, attr):
|
| 701 |
+
return getattr(module, attr)
|
| 702 |
+
# Some of the mappings have entries model_type -> object of another model type. In that case we try to grab the
|
| 703 |
+
# object at the top level.
|
| 704 |
+
transformers_module = importlib.import_module("transformers")
|
| 705 |
+
|
| 706 |
+
if module != transformers_module:
|
| 707 |
+
try:
|
| 708 |
+
return getattribute_from_module(transformers_module, attr)
|
| 709 |
+
except ValueError:
|
| 710 |
+
raise ValueError(f"Could not find {attr} neither in {module} nor in {transformers_module}!")
|
| 711 |
+
else:
|
| 712 |
+
raise ValueError(f"Could not find {attr} in {transformers_module}!")
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
def add_generation_mixin_to_remote_model(model_class):
|
| 716 |
+
"""
|
| 717 |
+
Adds `GenerationMixin` to the inheritance of `model_class`, if `model_class` is a PyTorch model.
|
| 718 |
+
|
| 719 |
+
This function is used for backwards compatibility purposes: in v4.45, we've started a deprecation cycle to make
|
| 720 |
+
`PreTrainedModel` stop inheriting from `GenerationMixin`. Without this function, older models dynamically loaded
|
| 721 |
+
from the Hub may not have the `generate` method after we remove the inheritance.
|
| 722 |
+
"""
|
| 723 |
+
# 1. If it is not a PT model (i.e. doesn't inherit Module), do nothing
|
| 724 |
+
if "torch.nn.modules.module.Module" not in str(model_class.__mro__):
|
| 725 |
+
return model_class
|
| 726 |
+
|
| 727 |
+
# 2. If it already **directly** inherits from GenerationMixin, do nothing
|
| 728 |
+
if "GenerationMixin" in str(model_class.__bases__):
|
| 729 |
+
return model_class
|
| 730 |
+
|
| 731 |
+
# 3. Prior to v4.45, we could detect whether a model was `generate`-compatible if it had its own `generate` and/or
|
| 732 |
+
# `prepare_inputs_for_generation` method.
|
| 733 |
+
has_custom_generate = "GenerationMixin" not in str(getattr(model_class, "generate"))
|
| 734 |
+
has_custom_prepare_inputs = "GenerationMixin" not in str(getattr(model_class, "prepare_inputs_for_generation"))
|
| 735 |
+
if has_custom_generate or has_custom_prepare_inputs:
|
| 736 |
+
model_class_with_generation_mixin = type(
|
| 737 |
+
model_class.__name__, (model_class, GenerationMixin), {**model_class.__dict__}
|
| 738 |
+
)
|
| 739 |
+
return model_class_with_generation_mixin
|
| 740 |
+
return model_class
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
class _LazyAutoMapping(OrderedDict):
|
| 744 |
+
"""
|
| 745 |
+
" A mapping config to object (model or tokenizer for instance) that will load keys and values when it is accessed.
|
| 746 |
+
|
| 747 |
+
Args:
|
| 748 |
+
- config_mapping: The map model type to config class
|
| 749 |
+
- model_mapping: The map model type to model (or tokenizer) class
|
| 750 |
+
"""
|
| 751 |
+
|
| 752 |
+
def __init__(self, config_mapping, model_mapping):
|
| 753 |
+
self._config_mapping = config_mapping
|
| 754 |
+
self._reverse_config_mapping = {v: k for k, v in config_mapping.items()}
|
| 755 |
+
self._model_mapping = model_mapping
|
| 756 |
+
self._model_mapping._model_mapping = self
|
| 757 |
+
self._extra_content = {}
|
| 758 |
+
self._modules = {}
|
| 759 |
+
|
| 760 |
+
def __len__(self):
|
| 761 |
+
common_keys = set(self._config_mapping.keys()).intersection(self._model_mapping.keys())
|
| 762 |
+
return len(common_keys) + len(self._extra_content)
|
| 763 |
+
|
| 764 |
+
def __getitem__(self, key):
|
| 765 |
+
if key in self._extra_content:
|
| 766 |
+
return self._extra_content[key]
|
| 767 |
+
model_type = self._reverse_config_mapping[key.__name__]
|
| 768 |
+
if model_type in self._model_mapping:
|
| 769 |
+
model_name = self._model_mapping[model_type]
|
| 770 |
+
return self._load_attr_from_module(model_type, model_name)
|
| 771 |
+
|
| 772 |
+
# Maybe there was several model types associated with this config.
|
| 773 |
+
model_types = [k for k, v in self._config_mapping.items() if v == key.__name__]
|
| 774 |
+
for mtype in model_types:
|
| 775 |
+
if mtype in self._model_mapping:
|
| 776 |
+
model_name = self._model_mapping[mtype]
|
| 777 |
+
return self._load_attr_from_module(mtype, model_name)
|
| 778 |
+
raise KeyError(key)
|
| 779 |
+
|
| 780 |
+
def _load_attr_from_module(self, model_type, attr):
|
| 781 |
+
module_name = model_type_to_module_name(model_type)
|
| 782 |
+
if module_name not in self._modules:
|
| 783 |
+
self._modules[module_name] = importlib.import_module(f".{module_name}", "transformers.models")
|
| 784 |
+
return getattribute_from_module(self._modules[module_name], attr)
|
| 785 |
+
|
| 786 |
+
def keys(self):
|
| 787 |
+
mapping_keys = [
|
| 788 |
+
self._load_attr_from_module(key, name)
|
| 789 |
+
for key, name in self._config_mapping.items()
|
| 790 |
+
if key in self._model_mapping.keys()
|
| 791 |
+
]
|
| 792 |
+
return mapping_keys + list(self._extra_content.keys())
|
| 793 |
+
|
| 794 |
+
def get(self, key, default):
|
| 795 |
+
try:
|
| 796 |
+
return self.__getitem__(key)
|
| 797 |
+
except KeyError:
|
| 798 |
+
return default
|
| 799 |
+
|
| 800 |
+
def __bool__(self):
|
| 801 |
+
return bool(self.keys())
|
| 802 |
+
|
| 803 |
+
def values(self):
|
| 804 |
+
mapping_values = [
|
| 805 |
+
self._load_attr_from_module(key, name)
|
| 806 |
+
for key, name in self._model_mapping.items()
|
| 807 |
+
if key in self._config_mapping.keys()
|
| 808 |
+
]
|
| 809 |
+
return mapping_values + list(self._extra_content.values())
|
| 810 |
+
|
| 811 |
+
def items(self):
|
| 812 |
+
mapping_items = [
|
| 813 |
+
(
|
| 814 |
+
self._load_attr_from_module(key, self._config_mapping[key]),
|
| 815 |
+
self._load_attr_from_module(key, self._model_mapping[key]),
|
| 816 |
+
)
|
| 817 |
+
for key in self._model_mapping.keys()
|
| 818 |
+
if key in self._config_mapping.keys()
|
| 819 |
+
]
|
| 820 |
+
return mapping_items + list(self._extra_content.items())
|
| 821 |
+
|
| 822 |
+
def __iter__(self):
|
| 823 |
+
return iter(self.keys())
|
| 824 |
+
|
| 825 |
+
def __contains__(self, item):
|
| 826 |
+
if item in self._extra_content:
|
| 827 |
+
return True
|
| 828 |
+
if not hasattr(item, "__name__") or item.__name__ not in self._reverse_config_mapping:
|
| 829 |
+
return False
|
| 830 |
+
model_type = self._reverse_config_mapping[item.__name__]
|
| 831 |
+
return model_type in self._model_mapping
|
| 832 |
+
|
| 833 |
+
def register(self, key, value, exist_ok=False):
|
| 834 |
+
"""
|
| 835 |
+
Register a new model in this mapping.
|
| 836 |
+
"""
|
| 837 |
+
if hasattr(key, "__name__") and key.__name__ in self._reverse_config_mapping:
|
| 838 |
+
model_type = self._reverse_config_mapping[key.__name__]
|
| 839 |
+
if model_type in self._model_mapping.keys() and not exist_ok:
|
| 840 |
+
raise ValueError(f"'{key}' is already used by a Transformers model.")
|
| 841 |
+
|
| 842 |
+
self._extra_content[key] = value
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/awq.py
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"AWQ (Activation aware Weight Quantization) integration file"
|
| 15 |
+
|
| 16 |
+
import importlib
|
| 17 |
+
|
| 18 |
+
from packaging import version
|
| 19 |
+
|
| 20 |
+
from ..activations import ACT2FN
|
| 21 |
+
from ..modeling_utils import PreTrainedModel
|
| 22 |
+
from ..utils import is_auto_awq_available, is_ipex_available, is_torch_available, logging
|
| 23 |
+
from ..utils.quantization_config import (
|
| 24 |
+
AwqBackendPackingMethod,
|
| 25 |
+
AwqConfig,
|
| 26 |
+
AWQLinearVersion,
|
| 27 |
+
ExllamaVersion,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if is_torch_available():
|
| 32 |
+
import torch
|
| 33 |
+
import torch.nn as nn
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
AWQ_FUSED_MAPPINGS = {
|
| 38 |
+
"mistral": {
|
| 39 |
+
"attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
|
| 40 |
+
"mlp": ["gate_proj", "up_proj", "down_proj"],
|
| 41 |
+
"layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
|
| 42 |
+
"use_alibi": False,
|
| 43 |
+
},
|
| 44 |
+
"mixtral": {
|
| 45 |
+
"attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
|
| 46 |
+
"mlp": ["w1", "w3", "w2"],
|
| 47 |
+
"layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
|
| 48 |
+
"use_alibi": False,
|
| 49 |
+
"rope_theta": 1000000.0,
|
| 50 |
+
},
|
| 51 |
+
"llama": {
|
| 52 |
+
"attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
|
| 53 |
+
"mlp": ["gate_proj", "up_proj", "down_proj"],
|
| 54 |
+
"layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
|
| 55 |
+
"use_alibi": False,
|
| 56 |
+
},
|
| 57 |
+
"llava": {
|
| 58 |
+
"attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
|
| 59 |
+
"mlp": ["gate_proj", "up_proj", "down_proj"],
|
| 60 |
+
"layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
|
| 61 |
+
"use_alibi": False,
|
| 62 |
+
},
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
AWQ_SCALES_MAPPINGS = {
|
| 66 |
+
"starcoder2": {"act": "act", "layer_before_act": "c_fc"},
|
| 67 |
+
"RefinedWebModel": {"act": "act", "layer_before_act": "dense_h_to_4h"},
|
| 68 |
+
"falcon": {"act": "act", "layer_before_act": "dense_h_to_4h"},
|
| 69 |
+
"mpt": {"act": "act", "layer_before_act": "up_proj"},
|
| 70 |
+
"gptj": {"act": "act", "layer_before_act": "fc_in"},
|
| 71 |
+
"gpt_neox": {"act": "act", "layer_before_act": "dense_h_to_4h"},
|
| 72 |
+
"gpt_bigcode": {"act": "act", "layer_before_act": "c_fc"},
|
| 73 |
+
"bloom": {"act": "gelu_impl", "layer_before_act": "dense_h_to_4h"},
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def replace_quantization_scales(model, model_type):
|
| 78 |
+
from awq.modules.act import ScaledActivation
|
| 79 |
+
|
| 80 |
+
if model_type not in AWQ_SCALES_MAPPINGS:
|
| 81 |
+
return model
|
| 82 |
+
for name, module in model.named_children():
|
| 83 |
+
act_name = AWQ_SCALES_MAPPINGS[model_type]["act"]
|
| 84 |
+
layer_before_act_name = AWQ_SCALES_MAPPINGS[model_type]["layer_before_act"]
|
| 85 |
+
if name == act_name and hasattr(model, layer_before_act_name):
|
| 86 |
+
layer_before_act = getattr(model, AWQ_SCALES_MAPPINGS[model_type]["layer_before_act"])
|
| 87 |
+
size = layer_before_act.out_features
|
| 88 |
+
scale_like = torch.ones(size)
|
| 89 |
+
model._modules[name] = ScaledActivation(module, scale_like)
|
| 90 |
+
_ = replace_quantization_scales(module, model_type)
|
| 91 |
+
return model
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def replace_with_awq_linear(
|
| 95 |
+
model,
|
| 96 |
+
modules_to_not_convert=None,
|
| 97 |
+
quantization_config=None,
|
| 98 |
+
current_key_name=None,
|
| 99 |
+
has_been_replaced=False,
|
| 100 |
+
) -> bool:
|
| 101 |
+
"""
|
| 102 |
+
Public method that recursively replaces the Linear layers of the given model with AWQ quantized layers.
|
| 103 |
+
`accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the
|
| 104 |
+
conversion has been successfull or not.
|
| 105 |
+
|
| 106 |
+
During the module replacement, we also infer the backend to use through the `quantization_config` object.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
model (`torch.nn.Module`):
|
| 110 |
+
The model to convert, can be any `torch.nn.Module` instance.
|
| 111 |
+
quantization_config (`AwqConfig`):
|
| 112 |
+
The quantization config object that contains the quantization parameters.
|
| 113 |
+
modules_to_not_convert (`list`, *optional*):
|
| 114 |
+
A list of modules to not convert. If a module name is in the list (e.g. `lm_head`), it will not be
|
| 115 |
+
converted.
|
| 116 |
+
current_key_name (`list`, *optional*):
|
| 117 |
+
A list that contains the current key name. This is used for recursion and should not be passed by the user.
|
| 118 |
+
has_been_replaced (`bool`, *optional*):
|
| 119 |
+
A boolean that indicates if the conversion has been successful or not. This is used for recursion and
|
| 120 |
+
should not be passed by the user.
|
| 121 |
+
"""
|
| 122 |
+
if modules_to_not_convert is None:
|
| 123 |
+
modules_to_not_convert = []
|
| 124 |
+
|
| 125 |
+
backend = quantization_config.backend
|
| 126 |
+
|
| 127 |
+
if not is_auto_awq_available():
|
| 128 |
+
raise ValueError(
|
| 129 |
+
"AWQ (either `autoawq` or `llmawq`) is not available. Please install it with `pip install autoawq` or check out the installation guide in https://github.com/mit-han-lab/llm-awq"
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
if backend == AwqBackendPackingMethod.AUTOAWQ:
|
| 133 |
+
if quantization_config.version == AWQLinearVersion.GEMM:
|
| 134 |
+
from awq.modules.linear.gemm import WQLinear_GEMM
|
| 135 |
+
|
| 136 |
+
target_cls = WQLinear_GEMM
|
| 137 |
+
elif quantization_config.version == AWQLinearVersion.GEMV:
|
| 138 |
+
from awq.modules.linear.gemv import WQLinear_GEMV
|
| 139 |
+
|
| 140 |
+
target_cls = WQLinear_GEMV
|
| 141 |
+
elif quantization_config.version == AWQLinearVersion.EXLLAMA:
|
| 142 |
+
if quantization_config.exllama_config["version"] == ExllamaVersion.ONE:
|
| 143 |
+
from awq.modules.linear.exllama import WQLinear_Exllama
|
| 144 |
+
|
| 145 |
+
target_cls = WQLinear_Exllama
|
| 146 |
+
elif quantization_config.exllama_config["version"] == ExllamaVersion.TWO:
|
| 147 |
+
from awq.modules.linear.exllamav2 import WQLinear_ExllamaV2
|
| 148 |
+
|
| 149 |
+
target_cls = WQLinear_ExllamaV2
|
| 150 |
+
else:
|
| 151 |
+
raise ValueError(f"Unrecognized Exllama version: {quantization_config.exllama_config['version']}")
|
| 152 |
+
elif quantization_config.version == AWQLinearVersion.IPEX:
|
| 153 |
+
from awq.modules.linear.gemm_ipex import WQLinear_IPEX
|
| 154 |
+
|
| 155 |
+
target_cls = WQLinear_IPEX
|
| 156 |
+
else:
|
| 157 |
+
raise ValueError(f"Unrecognized AWQ version: {quantization_config.version}")
|
| 158 |
+
else:
|
| 159 |
+
from awq.quantize.qmodule import WQLinear
|
| 160 |
+
|
| 161 |
+
target_cls = WQLinear
|
| 162 |
+
|
| 163 |
+
for name, module in model.named_children():
|
| 164 |
+
if current_key_name is None:
|
| 165 |
+
current_key_name = []
|
| 166 |
+
current_key_name.append(name)
|
| 167 |
+
|
| 168 |
+
if isinstance(module, nn.Linear) and name not in modules_to_not_convert:
|
| 169 |
+
# Check if the current key is not in the `modules_to_not_convert`
|
| 170 |
+
if not any(key in ".".join(current_key_name) for key in modules_to_not_convert):
|
| 171 |
+
in_features = module.in_features
|
| 172 |
+
out_features = module.out_features
|
| 173 |
+
|
| 174 |
+
model._modules[name] = target_cls(
|
| 175 |
+
w_bit=quantization_config.bits,
|
| 176 |
+
group_size=quantization_config.group_size,
|
| 177 |
+
in_features=in_features,
|
| 178 |
+
out_features=out_features,
|
| 179 |
+
bias=module.bias is not None,
|
| 180 |
+
dev=module.weight.device,
|
| 181 |
+
)
|
| 182 |
+
has_been_replaced = True
|
| 183 |
+
|
| 184 |
+
# Force requires grad to False to avoid unexpected errors
|
| 185 |
+
model._modules[name].requires_grad_(False)
|
| 186 |
+
if len(list(module.children())) > 0:
|
| 187 |
+
_, has_been_replaced = replace_with_awq_linear(
|
| 188 |
+
module,
|
| 189 |
+
modules_to_not_convert=modules_to_not_convert,
|
| 190 |
+
current_key_name=current_key_name,
|
| 191 |
+
quantization_config=quantization_config,
|
| 192 |
+
has_been_replaced=has_been_replaced,
|
| 193 |
+
)
|
| 194 |
+
# Remove the last key for recursion
|
| 195 |
+
current_key_name.pop(-1)
|
| 196 |
+
return model, has_been_replaced
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def get_modules_to_fuse(model, quantization_config):
|
| 200 |
+
"""
|
| 201 |
+
Returns the fusing mapping given the quantization config and the model
|
| 202 |
+
|
| 203 |
+
Args:
|
| 204 |
+
model (`~PreTrainedModel`):
|
| 205 |
+
The model to fuse - note this model should have been converted into AWQ format beforehand.
|
| 206 |
+
quantization_config (`~transformers.quantization_config.AWQConfig`):
|
| 207 |
+
The quantization configuration to use.
|
| 208 |
+
"""
|
| 209 |
+
if not isinstance(model, PreTrainedModel):
|
| 210 |
+
raise TypeError(f"The model should be an instance of `PreTrainedModel`, got {model.__class__.__name__}")
|
| 211 |
+
|
| 212 |
+
# Always default to `quantization_config.modules_to_fuse`
|
| 213 |
+
if quantization_config.modules_to_fuse is not None:
|
| 214 |
+
current_fused_mapping = quantization_config.modules_to_fuse
|
| 215 |
+
current_fused_mapping["max_seq_len"] = quantization_config.fuse_max_seq_len
|
| 216 |
+
elif model.config.model_type in AWQ_FUSED_MAPPINGS:
|
| 217 |
+
current_fused_mapping = AWQ_FUSED_MAPPINGS[model.config.model_type]
|
| 218 |
+
|
| 219 |
+
# Properly deal with the case where we have a multi-modal model as well (e.g. Llava)
|
| 220 |
+
config = model.config.get_text_config(decoder=True)
|
| 221 |
+
|
| 222 |
+
# Handle hidden_size, num_attention_heads, num_key_value_heads on our own.
|
| 223 |
+
hidden_size = config.hidden_size
|
| 224 |
+
num_attention_heads = config.num_attention_heads
|
| 225 |
+
num_key_value_heads = getattr(config, "num_key_value_heads", num_attention_heads)
|
| 226 |
+
|
| 227 |
+
# Fill `current_fused_mapping` with the expected values
|
| 228 |
+
current_fused_mapping["hidden_size"] = hidden_size
|
| 229 |
+
current_fused_mapping["num_attention_heads"] = num_attention_heads
|
| 230 |
+
current_fused_mapping["num_key_value_heads"] = num_key_value_heads
|
| 231 |
+
current_fused_mapping["max_seq_len"] = quantization_config.fuse_max_seq_len
|
| 232 |
+
else:
|
| 233 |
+
raise ValueError(
|
| 234 |
+
"Fusing mapping not found either on the quantization config or the supported `AWQ_FUSED_MAPPINGS`. Please pass a `fused_mapping` argument"
|
| 235 |
+
" in the `quantization_config` or raise an issue on transformers https://github.com/huggingface/transformers to add its support."
|
| 236 |
+
)
|
| 237 |
+
return current_fused_mapping
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def fuse_awq_modules(model, quantization_config):
|
| 241 |
+
"""
|
| 242 |
+
Optionally fuse some modules in the model to speedup inference.
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
model (`~PreTrainedModel`):
|
| 246 |
+
The model to fuse - note this model should have been converted into AWQ format beforehand.
|
| 247 |
+
quantization_config (`Union[AwqConfig, dict]`):
|
| 248 |
+
The quantization configuration to use.
|
| 249 |
+
"""
|
| 250 |
+
# We need to convert it from dict in order to get an AwqConfig object
|
| 251 |
+
# otherwise the fields `backend` etc. will not be available
|
| 252 |
+
# https://github.com/huggingface/transformers/pull/27411#discussion_r1414044495
|
| 253 |
+
if isinstance(quantization_config, dict):
|
| 254 |
+
quantization_config = AwqConfig.from_dict(quantization_config)
|
| 255 |
+
backend = quantization_config.backend
|
| 256 |
+
|
| 257 |
+
modules_to_fuse = get_modules_to_fuse(model, quantization_config)
|
| 258 |
+
modules_to_not_convert = getattr(quantization_config, "modules_to_not_convert", None)
|
| 259 |
+
|
| 260 |
+
if backend == AwqBackendPackingMethod.AUTOAWQ:
|
| 261 |
+
from awq.modules.fused.attn import QuantAttentionFused
|
| 262 |
+
from awq.modules.fused.mlp import QuantFusedMLP
|
| 263 |
+
from awq.modules.fused.norm import FasterTransformerRMSNorm
|
| 264 |
+
else:
|
| 265 |
+
raise ValueError("Fusing is only supported for the AutoAWQ backend")
|
| 266 |
+
|
| 267 |
+
fused_attention_modules = []
|
| 268 |
+
|
| 269 |
+
for name, module in model.named_modules():
|
| 270 |
+
if modules_to_not_convert is not None:
|
| 271 |
+
if any(module_name_to_not_convert in name for module_name_to_not_convert in modules_to_not_convert):
|
| 272 |
+
continue
|
| 273 |
+
|
| 274 |
+
# Replace layer norms
|
| 275 |
+
_fuse_awq_layernorm(modules_to_fuse["layernorm"], module, FasterTransformerRMSNorm)
|
| 276 |
+
|
| 277 |
+
# Replace MLP layers if awq version is not ipex.
|
| 278 |
+
if quantization_config.version != "ipex":
|
| 279 |
+
_fuse_awq_mlp(model, name, modules_to_fuse["mlp"], module, QuantFusedMLP)
|
| 280 |
+
else:
|
| 281 |
+
logger.info("The IPEX version AWQ does not support fuse mlp for now.")
|
| 282 |
+
|
| 283 |
+
# Replace attention layers
|
| 284 |
+
attention_has_been_fused = _fuse_awq_attention_layers(
|
| 285 |
+
model, module, modules_to_fuse, name, QuantAttentionFused
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
if attention_has_been_fused:
|
| 289 |
+
fused_attention_modules.append(name.split(".")[0])
|
| 290 |
+
|
| 291 |
+
# For AWQ fused + Llama we need to set `config._attn_implementation` = "custom" to avoid unexpected behavior and pass
|
| 292 |
+
# `None` attention mask to the fused attention modules as now the attention mask is dropped by our models and dealt
|
| 293 |
+
# by the `AttentionMaskConverter` module.
|
| 294 |
+
if len(fused_attention_modules) > 0:
|
| 295 |
+
for module_name, module in model.named_modules():
|
| 296 |
+
if any(
|
| 297 |
+
module_name in fused_attention_modules for fused_attention_parent_module in fused_attention_modules
|
| 298 |
+
):
|
| 299 |
+
if hasattr(module, "config") and hasattr(module.config, "_attn_implementation"):
|
| 300 |
+
module.config._attn_implementation = "custom"
|
| 301 |
+
return model
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def _fuse_awq_layernorm(fuse_module_names, module, target_cls):
|
| 305 |
+
"""
|
| 306 |
+
Fuse the LayerNorm layers into a target class using autoawq
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
fuse_module_names (`List[str]`):
|
| 310 |
+
The list of module names to fuse
|
| 311 |
+
module (`nn.Module`):
|
| 312 |
+
The pytorch parent module that has layernorm modules to fuse
|
| 313 |
+
target_cls (`~autoawq.FasterTransformerRMSNorm`):
|
| 314 |
+
The `FasterTransformerRMSNorm` class as it only supports that class
|
| 315 |
+
for now.
|
| 316 |
+
"""
|
| 317 |
+
for module_name in fuse_module_names:
|
| 318 |
+
if hasattr(module, module_name):
|
| 319 |
+
old_module = getattr(module, module_name)
|
| 320 |
+
module._modules[module_name] = target_cls(
|
| 321 |
+
old_module.weight,
|
| 322 |
+
old_module.variance_epsilon,
|
| 323 |
+
).to(old_module.weight.device)
|
| 324 |
+
del old_module
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _fuse_awq_mlp(model, current_module_name, fuse_module_names, module, target_cls):
|
| 328 |
+
"""
|
| 329 |
+
Fuse the MLP layers into a target class using autoawq
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
model (`~PreTrainedModel`):
|
| 333 |
+
The input pretrained model
|
| 334 |
+
current_module_name (`str`):
|
| 335 |
+
The current submodule name
|
| 336 |
+
fuse_module_names (`List[str]`):
|
| 337 |
+
The list of module names to fuse. For the MLP layers it has to be an array
|
| 338 |
+
of length 3 that consists of the 3 MLP layers in the order (gate (dense layer post-attention) / up / down layers)
|
| 339 |
+
module (`nn.Module`):
|
| 340 |
+
The pytorch parent module that has layernorm modules to fuse
|
| 341 |
+
target_cls (`~autoawq.QuantFusedMLP`):
|
| 342 |
+
The `QuantFusedMLP` class as it only supports that class
|
| 343 |
+
for now.
|
| 344 |
+
"""
|
| 345 |
+
if len(fuse_module_names) == 0:
|
| 346 |
+
return
|
| 347 |
+
|
| 348 |
+
if hasattr(module, fuse_module_names[0]):
|
| 349 |
+
gate_proj = getattr(module, fuse_module_names[0])
|
| 350 |
+
up_proj = getattr(module, fuse_module_names[1])
|
| 351 |
+
down_proj = getattr(module, fuse_module_names[2])
|
| 352 |
+
|
| 353 |
+
previous_device = gate_proj.qweight.device
|
| 354 |
+
|
| 355 |
+
# Deal also with the case model has `text_config` attribute
|
| 356 |
+
config = model.config.get_text_config(decoder=True)
|
| 357 |
+
hidden_act = config.hidden_act
|
| 358 |
+
activation_fn = ACT2FN[hidden_act]
|
| 359 |
+
new_module = target_cls(gate_proj, down_proj, up_proj, activation_fn)
|
| 360 |
+
|
| 361 |
+
parent_name, child_name = current_module_name.rsplit(".", 1)
|
| 362 |
+
parent = model.get_submodule(parent_name)
|
| 363 |
+
setattr(parent, child_name, new_module.to(previous_device))
|
| 364 |
+
|
| 365 |
+
del gate_proj, up_proj, down_proj
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _fuse_awq_attention_layers(model, module, modules_to_fuse, current_module_name, target_cls):
|
| 369 |
+
"""
|
| 370 |
+
Fuse the Attention layers into a target class using autoawq
|
| 371 |
+
|
| 372 |
+
Args:
|
| 373 |
+
model (`~PreTrainedModel`):
|
| 374 |
+
The input pretrained model
|
| 375 |
+
module (`nn.Module`):
|
| 376 |
+
The pytorch parent module that has layernorm modules to fuse
|
| 377 |
+
modules_to_fuse (`List[str]`):
|
| 378 |
+
The module fusing mapping. The dictionary has to contain a field `attention` with attention module names
|
| 379 |
+
in the correct order: q, k, v, o layer
|
| 380 |
+
current_module_name (`str`):
|
| 381 |
+
The current submodule name
|
| 382 |
+
target_cls (`~autoawq.QuantAttentionFused`):
|
| 383 |
+
The `QuantAttentionFused` class as it only supports that class
|
| 384 |
+
for now.
|
| 385 |
+
"""
|
| 386 |
+
from awq.modules.linear import WQLinear_GEMM, WQLinear_GEMV
|
| 387 |
+
|
| 388 |
+
module_has_been_fused = False
|
| 389 |
+
|
| 390 |
+
if len(modules_to_fuse["attention"]) == 0:
|
| 391 |
+
return module_has_been_fused
|
| 392 |
+
|
| 393 |
+
if hasattr(module, modules_to_fuse["attention"][0]):
|
| 394 |
+
# First, we pack the QKV layers together
|
| 395 |
+
q_proj = getattr(module, modules_to_fuse["attention"][0])
|
| 396 |
+
|
| 397 |
+
if isinstance(q_proj, WQLinear_GEMV):
|
| 398 |
+
linear_target_cls = WQLinear_GEMV
|
| 399 |
+
cat_dim = 0
|
| 400 |
+
elif isinstance(q_proj, WQLinear_GEMM):
|
| 401 |
+
linear_target_cls = WQLinear_GEMM
|
| 402 |
+
cat_dim = 1
|
| 403 |
+
elif is_ipex_available() and version.parse(importlib.metadata.version("autoawq")) > version.parse("0.2.6"):
|
| 404 |
+
from awq.modules.linear import WQLinear_IPEX
|
| 405 |
+
|
| 406 |
+
if isinstance(q_proj, WQLinear_IPEX):
|
| 407 |
+
linear_target_cls = WQLinear_IPEX
|
| 408 |
+
cat_dim = 1
|
| 409 |
+
else:
|
| 410 |
+
raise ValueError("Unsupported q_proj type: {type(q_proj)}")
|
| 411 |
+
|
| 412 |
+
previous_device = q_proj.qweight.device
|
| 413 |
+
|
| 414 |
+
k_proj = getattr(module, modules_to_fuse["attention"][1])
|
| 415 |
+
v_proj = getattr(module, modules_to_fuse["attention"][2])
|
| 416 |
+
o_proj = getattr(module, modules_to_fuse["attention"][3])
|
| 417 |
+
|
| 418 |
+
bias = torch.cat([q_proj.bias, k_proj.bias, v_proj.bias], dim=0) if q_proj.bias is not None else None
|
| 419 |
+
|
| 420 |
+
qkv_layer = linear_target_cls(
|
| 421 |
+
q_proj.w_bit,
|
| 422 |
+
q_proj.group_size,
|
| 423 |
+
q_proj.in_features,
|
| 424 |
+
q_proj.out_features + k_proj.out_features + v_proj.out_features,
|
| 425 |
+
q_proj.bias is not None,
|
| 426 |
+
next(iter(module.state_dict().values())).device,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
qkv_layer.qweight = torch.cat([q_proj.qweight, k_proj.qweight, v_proj.qweight], dim=cat_dim)
|
| 430 |
+
qkv_layer.qzeros = torch.cat([q_proj.qzeros, k_proj.qzeros, v_proj.qzeros], dim=cat_dim)
|
| 431 |
+
qkv_layer.scales = torch.cat([q_proj.scales, k_proj.scales, v_proj.scales], dim=cat_dim)
|
| 432 |
+
|
| 433 |
+
if isinstance(qkv_layer, WQLinear_GEMV):
|
| 434 |
+
qkv_layer.split_k_iters = q_proj.split_k_iters
|
| 435 |
+
|
| 436 |
+
qkv_layer.bias = bias
|
| 437 |
+
|
| 438 |
+
fused_attention_layer = target_cls(
|
| 439 |
+
modules_to_fuse["hidden_size"],
|
| 440 |
+
modules_to_fuse["num_attention_heads"],
|
| 441 |
+
modules_to_fuse["num_key_value_heads"],
|
| 442 |
+
qkv_layer,
|
| 443 |
+
o_proj,
|
| 444 |
+
previous_device,
|
| 445 |
+
modules_to_fuse["max_seq_len"],
|
| 446 |
+
use_alibi=modules_to_fuse["use_alibi"],
|
| 447 |
+
# The default value in autoawq is set to 10000.0
|
| 448 |
+
rope_theta=modules_to_fuse.get("rope_theta", 10000.0),
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
fused_attention_layer.is_hf_transformers = True
|
| 452 |
+
|
| 453 |
+
parent_name, child_name = current_module_name.rsplit(".", 1)
|
| 454 |
+
parent = model.get_submodule(parent_name)
|
| 455 |
+
setattr(parent, child_name, fused_attention_layer.to(previous_device))
|
| 456 |
+
|
| 457 |
+
del q_proj, k_proj, v_proj, o_proj
|
| 458 |
+
module_has_been_fused = True
|
| 459 |
+
|
| 460 |
+
return module_has_been_fused
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def post_init_awq_exllama_modules(model, exllama_config):
|
| 464 |
+
"""
|
| 465 |
+
Runs post init for Exllama layers which performs:
|
| 466 |
+
- Weights unpacking, reordering and repacking
|
| 467 |
+
- Devices scratch space allocation
|
| 468 |
+
"""
|
| 469 |
+
|
| 470 |
+
if exllama_config["version"] == ExllamaVersion.ONE:
|
| 471 |
+
from awq.modules.linear.exllama import exllama_post_init
|
| 472 |
+
|
| 473 |
+
model = exllama_post_init(model)
|
| 474 |
+
elif exllama_config["version"] == ExllamaVersion.TWO:
|
| 475 |
+
from awq.modules.linear.exllamav2 import exllamav2_post_init
|
| 476 |
+
|
| 477 |
+
model = exllamav2_post_init(
|
| 478 |
+
model,
|
| 479 |
+
max_input_len=exllama_config["max_input_len"],
|
| 480 |
+
max_batch_size=exllama_config["max_batch_size"],
|
| 481 |
+
)
|
| 482 |
+
else:
|
| 483 |
+
raise ValueError(f"Unrecognized Exllama version: {exllama_config['version']}")
|
| 484 |
+
|
| 485 |
+
return model
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def post_init_awq_ipex_modules(model):
|
| 489 |
+
"""
|
| 490 |
+
Runs post init for IPEX layers which performs:
|
| 491 |
+
- Weights packing, reordering and repacking
|
| 492 |
+
"""
|
| 493 |
+
|
| 494 |
+
from awq.modules.linear.gemm_ipex import ipex_post_init
|
| 495 |
+
|
| 496 |
+
model = ipex_post_init(model)
|
| 497 |
+
|
| 498 |
+
return model
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 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 |
+
"""Collection of utils to be used by backbones and their components."""
|
| 16 |
+
|
| 17 |
+
import enum
|
| 18 |
+
import inspect
|
| 19 |
+
from collections.abc import Iterable
|
| 20 |
+
from typing import TYPE_CHECKING, Optional, Union
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from ..configuration_utils import PretrainedConfig
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class BackboneType(enum.Enum):
|
| 28 |
+
TIMM = "timm"
|
| 29 |
+
TRANSFORMERS = "transformers"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def verify_out_features_out_indices(
|
| 33 |
+
out_features: Optional[Iterable[str]], out_indices: Optional[Iterable[int]], stage_names: Optional[Iterable[str]]
|
| 34 |
+
):
|
| 35 |
+
"""
|
| 36 |
+
Verify that out_indices and out_features are valid for the given stage_names.
|
| 37 |
+
"""
|
| 38 |
+
if stage_names is None:
|
| 39 |
+
raise ValueError("Stage_names must be set for transformers backbones")
|
| 40 |
+
|
| 41 |
+
if out_features is not None:
|
| 42 |
+
if not isinstance(out_features, (list,)):
|
| 43 |
+
raise ValueError(f"out_features must be a list got {type(out_features)}")
|
| 44 |
+
if any(feat not in stage_names for feat in out_features):
|
| 45 |
+
raise ValueError(f"out_features must be a subset of stage_names: {stage_names} got {out_features}")
|
| 46 |
+
if len(out_features) != len(set(out_features)):
|
| 47 |
+
raise ValueError(f"out_features must not contain any duplicates, got {out_features}")
|
| 48 |
+
if out_features != (sorted_feats := [feat for feat in stage_names if feat in out_features]):
|
| 49 |
+
raise ValueError(
|
| 50 |
+
f"out_features must be in the same order as stage_names, expected {sorted_feats} got {out_features}"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
if out_indices is not None:
|
| 54 |
+
if not isinstance(out_indices, list):
|
| 55 |
+
raise ValueError(f"out_indices must be a list, got {type(out_indices)}")
|
| 56 |
+
# Convert negative indices to their positive equivalent: [-1,] -> [len(stage_names) - 1,]
|
| 57 |
+
positive_indices = tuple(idx % len(stage_names) if idx < 0 else idx for idx in out_indices)
|
| 58 |
+
if any(idx for idx in positive_indices if idx not in range(len(stage_names))):
|
| 59 |
+
raise ValueError(f"out_indices must be valid indices for stage_names {stage_names}, got {out_indices}")
|
| 60 |
+
if len(positive_indices) != len(set(positive_indices)):
|
| 61 |
+
msg = f"out_indices must not contain any duplicates, got {out_indices}"
|
| 62 |
+
msg += f"(equivalent to {positive_indices}))" if positive_indices != out_indices else ""
|
| 63 |
+
raise ValueError(msg)
|
| 64 |
+
if positive_indices != tuple(sorted(positive_indices)):
|
| 65 |
+
sorted_negative = [idx for _, idx in sorted(zip(positive_indices, out_indices), key=lambda x: x[0])]
|
| 66 |
+
raise ValueError(
|
| 67 |
+
f"out_indices must be in the same order as stage_names, expected {sorted_negative} got {out_indices}"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
if out_features is not None and out_indices is not None:
|
| 71 |
+
if len(out_features) != len(out_indices):
|
| 72 |
+
raise ValueError("out_features and out_indices should have the same length if both are set")
|
| 73 |
+
if out_features != [stage_names[idx] for idx in out_indices]:
|
| 74 |
+
raise ValueError("out_features and out_indices should correspond to the same stages if both are set")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _align_output_features_output_indices(
|
| 78 |
+
out_features: Optional[list[str]],
|
| 79 |
+
out_indices: Optional[Union[list[int], tuple[int]]],
|
| 80 |
+
stage_names: list[str],
|
| 81 |
+
):
|
| 82 |
+
"""
|
| 83 |
+
Finds the corresponding `out_features` and `out_indices` for the given `stage_names`.
|
| 84 |
+
|
| 85 |
+
The logic is as follows:
|
| 86 |
+
- `out_features` not set, `out_indices` set: `out_features` is set to the `out_features` corresponding to the
|
| 87 |
+
`out_indices`.
|
| 88 |
+
- `out_indices` not set, `out_features` set: `out_indices` is set to the `out_indices` corresponding to the
|
| 89 |
+
`out_features`.
|
| 90 |
+
- `out_indices` and `out_features` not set: `out_indices` and `out_features` are set to the last stage.
|
| 91 |
+
- `out_indices` and `out_features` set: input `out_indices` and `out_features` are returned.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
out_features (`List[str]`): The names of the features for the backbone to output.
|
| 95 |
+
out_indices (`List[int]` or `Tuple[int]`): The indices of the features for the backbone to output.
|
| 96 |
+
stage_names (`List[str]`): The names of the stages of the backbone.
|
| 97 |
+
"""
|
| 98 |
+
if out_indices is None and out_features is None:
|
| 99 |
+
out_indices = [len(stage_names) - 1]
|
| 100 |
+
out_features = [stage_names[-1]]
|
| 101 |
+
elif out_indices is None and out_features is not None:
|
| 102 |
+
out_indices = [stage_names.index(layer) for layer in out_features]
|
| 103 |
+
elif out_features is None and out_indices is not None:
|
| 104 |
+
out_features = [stage_names[idx] for idx in out_indices]
|
| 105 |
+
return out_features, out_indices
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def get_aligned_output_features_output_indices(
|
| 109 |
+
out_features: Optional[list[str]],
|
| 110 |
+
out_indices: Optional[Union[list[int], tuple[int]]],
|
| 111 |
+
stage_names: list[str],
|
| 112 |
+
) -> tuple[list[str], list[int]]:
|
| 113 |
+
"""
|
| 114 |
+
Get the `out_features` and `out_indices` so that they are aligned.
|
| 115 |
+
|
| 116 |
+
The logic is as follows:
|
| 117 |
+
- `out_features` not set, `out_indices` set: `out_features` is set to the `out_features` corresponding to the
|
| 118 |
+
`out_indices`.
|
| 119 |
+
- `out_indices` not set, `out_features` set: `out_indices` is set to the `out_indices` corresponding to the
|
| 120 |
+
`out_features`.
|
| 121 |
+
- `out_indices` and `out_features` not set: `out_indices` and `out_features` are set to the last stage.
|
| 122 |
+
- `out_indices` and `out_features` set: they are verified to be aligned.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
out_features (`List[str]`): The names of the features for the backbone to output.
|
| 126 |
+
out_indices (`List[int]` or `Tuple[int]`): The indices of the features for the backbone to output.
|
| 127 |
+
stage_names (`List[str]`): The names of the stages of the backbone.
|
| 128 |
+
"""
|
| 129 |
+
out_indices = list(out_indices) if out_indices is not None else None
|
| 130 |
+
# First verify that the out_features and out_indices are valid
|
| 131 |
+
verify_out_features_out_indices(out_features=out_features, out_indices=out_indices, stage_names=stage_names)
|
| 132 |
+
output_features, output_indices = _align_output_features_output_indices(
|
| 133 |
+
out_features=out_features, out_indices=out_indices, stage_names=stage_names
|
| 134 |
+
)
|
| 135 |
+
# Verify that the aligned out_features and out_indices are valid
|
| 136 |
+
verify_out_features_out_indices(out_features=output_features, out_indices=output_indices, stage_names=stage_names)
|
| 137 |
+
return output_features, output_indices
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class BackboneMixin:
|
| 141 |
+
backbone_type: Optional[BackboneType] = None
|
| 142 |
+
|
| 143 |
+
def _init_timm_backbone(self, config) -> None:
|
| 144 |
+
"""
|
| 145 |
+
Initialize the backbone model from timm The backbone must already be loaded to self._backbone
|
| 146 |
+
"""
|
| 147 |
+
if getattr(self, "_backbone", None) is None:
|
| 148 |
+
raise ValueError("self._backbone must be set before calling _init_timm_backbone")
|
| 149 |
+
|
| 150 |
+
# These will diagree with the defaults for the transformers models e.g. for resnet50
|
| 151 |
+
# the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4']
|
| 152 |
+
# the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4']
|
| 153 |
+
self.stage_names = [stage["module"] for stage in self._backbone.feature_info.info]
|
| 154 |
+
self.num_features = [stage["num_chs"] for stage in self._backbone.feature_info.info]
|
| 155 |
+
|
| 156 |
+
# In some timm versions, out_indices reflects the input type of out_indices on the `create_model` call,
|
| 157 |
+
# in later versions >= 1, it is always a tuple
|
| 158 |
+
out_indices = list(self._backbone.feature_info.out_indices)
|
| 159 |
+
out_features = self._backbone.feature_info.module_name()
|
| 160 |
+
|
| 161 |
+
# We verify the out indices and out features are valid
|
| 162 |
+
verify_out_features_out_indices(
|
| 163 |
+
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
|
| 164 |
+
)
|
| 165 |
+
self._out_features, self._out_indices = out_features, out_indices
|
| 166 |
+
|
| 167 |
+
def _init_transformers_backbone(self, config) -> None:
|
| 168 |
+
stage_names = getattr(config, "stage_names")
|
| 169 |
+
out_features = getattr(config, "out_features", None)
|
| 170 |
+
out_indices = getattr(config, "out_indices", None)
|
| 171 |
+
|
| 172 |
+
self.stage_names = stage_names
|
| 173 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 174 |
+
out_features=out_features, out_indices=out_indices, stage_names=stage_names
|
| 175 |
+
)
|
| 176 |
+
# Number of channels for each stage. This is set in the transformer backbone model init
|
| 177 |
+
self.num_features = None
|
| 178 |
+
|
| 179 |
+
def _init_backbone(self, config) -> None:
|
| 180 |
+
"""
|
| 181 |
+
Method to initialize the backbone. This method is called by the constructor of the base class after the
|
| 182 |
+
pretrained model weights have been loaded.
|
| 183 |
+
"""
|
| 184 |
+
self.config = config
|
| 185 |
+
|
| 186 |
+
self.use_timm_backbone = getattr(config, "use_timm_backbone", False)
|
| 187 |
+
self.backbone_type = BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS
|
| 188 |
+
|
| 189 |
+
if self.backbone_type == BackboneType.TIMM:
|
| 190 |
+
self._init_timm_backbone(config)
|
| 191 |
+
elif self.backbone_type == BackboneType.TRANSFORMERS:
|
| 192 |
+
self._init_transformers_backbone(config)
|
| 193 |
+
else:
|
| 194 |
+
raise ValueError(f"backbone_type {self.backbone_type} not supported.")
|
| 195 |
+
|
| 196 |
+
@property
|
| 197 |
+
def out_features(self):
|
| 198 |
+
return self._out_features
|
| 199 |
+
|
| 200 |
+
@out_features.setter
|
| 201 |
+
def out_features(self, out_features: list[str]):
|
| 202 |
+
"""
|
| 203 |
+
Set the out_features attribute. This will also update the out_indices attribute to match the new out_features.
|
| 204 |
+
"""
|
| 205 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 206 |
+
out_features=out_features, out_indices=None, stage_names=self.stage_names
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
@property
|
| 210 |
+
def out_indices(self):
|
| 211 |
+
return self._out_indices
|
| 212 |
+
|
| 213 |
+
@out_indices.setter
|
| 214 |
+
def out_indices(self, out_indices: Union[tuple[int], list[int]]):
|
| 215 |
+
"""
|
| 216 |
+
Set the out_indices attribute. This will also update the out_features attribute to match the new out_indices.
|
| 217 |
+
"""
|
| 218 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 219 |
+
out_features=None, out_indices=out_indices, stage_names=self.stage_names
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
@property
|
| 223 |
+
def out_feature_channels(self):
|
| 224 |
+
# the current backbones will output the number of channels for each stage
|
| 225 |
+
# even if that stage is not in the out_features list.
|
| 226 |
+
return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names)}
|
| 227 |
+
|
| 228 |
+
@property
|
| 229 |
+
def channels(self):
|
| 230 |
+
return [self.out_feature_channels[name] for name in self.out_features]
|
| 231 |
+
|
| 232 |
+
def forward_with_filtered_kwargs(self, *args, **kwargs):
|
| 233 |
+
signature = dict(inspect.signature(self.forward).parameters)
|
| 234 |
+
filtered_kwargs = {k: v for k, v in kwargs.items() if k in signature}
|
| 235 |
+
return self(*args, **filtered_kwargs)
|
| 236 |
+
|
| 237 |
+
def forward(
|
| 238 |
+
self,
|
| 239 |
+
pixel_values,
|
| 240 |
+
output_hidden_states: Optional[bool] = None,
|
| 241 |
+
output_attentions: Optional[bool] = None,
|
| 242 |
+
return_dict: Optional[bool] = None,
|
| 243 |
+
):
|
| 244 |
+
raise NotImplementedError("This method should be implemented by the derived class.")
|
| 245 |
+
|
| 246 |
+
def to_dict(self):
|
| 247 |
+
"""
|
| 248 |
+
Serializes this instance to a Python dictionary. Override the default `to_dict()` from `PretrainedConfig` to
|
| 249 |
+
include the `out_features` and `out_indices` attributes.
|
| 250 |
+
"""
|
| 251 |
+
output = super().to_dict()
|
| 252 |
+
output["out_features"] = output.pop("_out_features")
|
| 253 |
+
output["out_indices"] = output.pop("_out_indices")
|
| 254 |
+
return output
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class BackboneConfigMixin:
|
| 258 |
+
"""
|
| 259 |
+
A Mixin to support handling the `out_features` and `out_indices` attributes for the backbone configurations.
|
| 260 |
+
"""
|
| 261 |
+
|
| 262 |
+
@property
|
| 263 |
+
def out_features(self):
|
| 264 |
+
return self._out_features
|
| 265 |
+
|
| 266 |
+
@out_features.setter
|
| 267 |
+
def out_features(self, out_features: list[str]):
|
| 268 |
+
"""
|
| 269 |
+
Set the out_features attribute. This will also update the out_indices attribute to match the new out_features.
|
| 270 |
+
"""
|
| 271 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 272 |
+
out_features=out_features, out_indices=None, stage_names=self.stage_names
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
@property
|
| 276 |
+
def out_indices(self):
|
| 277 |
+
return self._out_indices
|
| 278 |
+
|
| 279 |
+
@out_indices.setter
|
| 280 |
+
def out_indices(self, out_indices: Union[tuple[int], list[int]]):
|
| 281 |
+
"""
|
| 282 |
+
Set the out_indices attribute. This will also update the out_features attribute to match the new out_indices.
|
| 283 |
+
"""
|
| 284 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 285 |
+
out_features=None, out_indices=out_indices, stage_names=self.stage_names
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
def to_dict(self):
|
| 289 |
+
"""
|
| 290 |
+
Serializes this instance to a Python dictionary. Override the default `to_dict()` from `PretrainedConfig` to
|
| 291 |
+
include the `out_features` and `out_indices` attributes.
|
| 292 |
+
"""
|
| 293 |
+
output = super().to_dict()
|
| 294 |
+
output["out_features"] = output.pop("_out_features")
|
| 295 |
+
output["out_indices"] = output.pop("_out_indices")
|
| 296 |
+
return output
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def load_backbone(config):
|
| 300 |
+
"""
|
| 301 |
+
Loads the backbone model from a config object.
|
| 302 |
+
|
| 303 |
+
If the config is from the backbone model itself, then we return a backbone model with randomly initialized
|
| 304 |
+
weights.
|
| 305 |
+
|
| 306 |
+
If the config is from the parent model of the backbone model itself, then we load the pretrained backbone weights
|
| 307 |
+
if specified.
|
| 308 |
+
"""
|
| 309 |
+
from transformers import AutoBackbone, AutoConfig
|
| 310 |
+
|
| 311 |
+
backbone_config = getattr(config, "backbone_config", None)
|
| 312 |
+
use_timm_backbone = getattr(config, "use_timm_backbone", None)
|
| 313 |
+
use_pretrained_backbone = getattr(config, "use_pretrained_backbone", None)
|
| 314 |
+
backbone_checkpoint = getattr(config, "backbone", None)
|
| 315 |
+
backbone_kwargs = getattr(config, "backbone_kwargs", None)
|
| 316 |
+
backbone_kwargs = {} if backbone_kwargs is None else backbone_kwargs
|
| 317 |
+
|
| 318 |
+
if backbone_kwargs and backbone_config is not None:
|
| 319 |
+
raise ValueError("You can't specify both `backbone_kwargs` and `backbone_config`.")
|
| 320 |
+
|
| 321 |
+
# If there is a backbone_config and a backbone checkpoint, and use_pretrained_backbone=False then the desired
|
| 322 |
+
# behaviour is ill-defined: do you want to load from the checkpoint's config or the backbone_config?
|
| 323 |
+
if backbone_config is not None and backbone_checkpoint is not None and use_pretrained_backbone is not None:
|
| 324 |
+
raise ValueError("Cannot specify both config.backbone_config and config.backbone")
|
| 325 |
+
|
| 326 |
+
# If any of thhe following are set, then the config passed in is from a model which contains a backbone.
|
| 327 |
+
if (
|
| 328 |
+
backbone_config is None
|
| 329 |
+
and use_timm_backbone is None
|
| 330 |
+
and backbone_checkpoint is None
|
| 331 |
+
and backbone_checkpoint is None
|
| 332 |
+
):
|
| 333 |
+
return AutoBackbone.from_config(config=config, **backbone_kwargs)
|
| 334 |
+
|
| 335 |
+
# config from the parent model that has a backbone
|
| 336 |
+
if use_timm_backbone:
|
| 337 |
+
if backbone_checkpoint is None:
|
| 338 |
+
raise ValueError("config.backbone must be set if use_timm_backbone is True")
|
| 339 |
+
# Because of how timm backbones were originally added to models, we need to pass in use_pretrained_backbone
|
| 340 |
+
# to determine whether to load the pretrained weights.
|
| 341 |
+
backbone = AutoBackbone.from_pretrained(
|
| 342 |
+
backbone_checkpoint,
|
| 343 |
+
use_timm_backbone=use_timm_backbone,
|
| 344 |
+
use_pretrained_backbone=use_pretrained_backbone,
|
| 345 |
+
**backbone_kwargs,
|
| 346 |
+
)
|
| 347 |
+
elif use_pretrained_backbone:
|
| 348 |
+
if backbone_checkpoint is None:
|
| 349 |
+
raise ValueError("config.backbone must be set if use_pretrained_backbone is True")
|
| 350 |
+
backbone = AutoBackbone.from_pretrained(backbone_checkpoint, **backbone_kwargs)
|
| 351 |
+
else:
|
| 352 |
+
if backbone_config is None and backbone_checkpoint is None:
|
| 353 |
+
raise ValueError("Either config.backbone_config or config.backbone must be set")
|
| 354 |
+
if backbone_config is None:
|
| 355 |
+
backbone_config = AutoConfig.from_pretrained(backbone_checkpoint, **backbone_kwargs)
|
| 356 |
+
backbone = AutoBackbone.from_config(config=backbone_config)
|
| 357 |
+
return backbone
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def verify_backbone_config_arguments(
|
| 361 |
+
use_timm_backbone: bool,
|
| 362 |
+
use_pretrained_backbone: bool,
|
| 363 |
+
backbone: Optional[str],
|
| 364 |
+
backbone_config: Optional[Union[dict, "PretrainedConfig"]],
|
| 365 |
+
backbone_kwargs: Optional[dict],
|
| 366 |
+
):
|
| 367 |
+
"""
|
| 368 |
+
Verify that the config arguments to be passed to load_backbone are valid
|
| 369 |
+
"""
|
| 370 |
+
if backbone_config is not None and backbone is not None:
|
| 371 |
+
raise ValueError("You can't specify both `backbone` and `backbone_config`.")
|
| 372 |
+
|
| 373 |
+
if backbone_config is not None and use_timm_backbone:
|
| 374 |
+
raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`.")
|
| 375 |
+
|
| 376 |
+
if backbone_kwargs is not None and backbone_kwargs and backbone_config is not None:
|
| 377 |
+
raise ValueError("You can't specify both `backbone_kwargs` and `backbone_config`.")
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/base.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Inc. 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 abc import ABC, abstractmethod
|
| 15 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
|
| 16 |
+
|
| 17 |
+
from ..utils import is_torch_available
|
| 18 |
+
from ..utils.quantization_config import QuantizationConfigMixin, QuantizationMethod
|
| 19 |
+
from .quantizers_utils import get_module_from_name
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ..modeling_utils import PreTrainedModel
|
| 24 |
+
|
| 25 |
+
if is_torch_available():
|
| 26 |
+
import torch
|
| 27 |
+
from torch.nn import ModuleList
|
| 28 |
+
else:
|
| 29 |
+
ModuleList = str
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class HfQuantizer(ABC):
|
| 33 |
+
"""
|
| 34 |
+
Abstract class of the HuggingFace quantizer. Supports for now quantizing HF transformers models for inference and/or quantization.
|
| 35 |
+
This class is used only for transformers.PreTrainedModel.from_pretrained and cannot be easily used outside the scope of that method
|
| 36 |
+
yet.
|
| 37 |
+
|
| 38 |
+
Attributes
|
| 39 |
+
quantization_config (`transformers.utils.quantization_config.QuantizationConfigMixin`):
|
| 40 |
+
The quantization config that defines the quantization parameters of your model that you want to quantize.
|
| 41 |
+
modules_to_not_convert (`List[str]`, *optional*):
|
| 42 |
+
The list of module names to not convert when quantizing the model.
|
| 43 |
+
required_packages (`List[str]`, *optional*):
|
| 44 |
+
The list of required pip packages to install prior to using the quantizer
|
| 45 |
+
requires_calibration (`bool`):
|
| 46 |
+
Whether the quantization method requires to calibrate the model before using it.
|
| 47 |
+
requires_parameters_quantization (`bool`):
|
| 48 |
+
Whether the quantization method requires to create a new Parameter. For example, for bitsandbytes, it is
|
| 49 |
+
required to create a new xxxParameter in order to properly quantize the model.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
requires_calibration = False
|
| 53 |
+
required_packages = None
|
| 54 |
+
requires_parameters_quantization = False
|
| 55 |
+
|
| 56 |
+
def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
|
| 57 |
+
self.quantization_config = quantization_config
|
| 58 |
+
|
| 59 |
+
# -- Handle extra kwargs below --
|
| 60 |
+
self.modules_to_not_convert = kwargs.pop("modules_to_not_convert", [])
|
| 61 |
+
self.pre_quantized = kwargs.pop("pre_quantized", True)
|
| 62 |
+
|
| 63 |
+
if not self.pre_quantized and self.requires_calibration:
|
| 64 |
+
raise ValueError(
|
| 65 |
+
f"The quantization method {quantization_config.quant_method} does require the model to be pre-quantized."
|
| 66 |
+
f" You explicitly passed `pre_quantized=False` meaning your model weights are not quantized. Make sure to "
|
| 67 |
+
f"pass `pre_quantized=True` while knowing what you are doing."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 71 |
+
"""
|
| 72 |
+
Some quantization methods require to explicitly set the dtype of the model to a
|
| 73 |
+
target dtype. You need to override this method in case you want to make sure that behavior is
|
| 74 |
+
preserved
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
torch_dtype (`torch.dtype`):
|
| 78 |
+
The input dtype that is passed in `from_pretrained`
|
| 79 |
+
"""
|
| 80 |
+
return torch_dtype
|
| 81 |
+
|
| 82 |
+
def update_device_map(self, device_map: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
| 83 |
+
"""
|
| 84 |
+
Override this method if you want to pass a override the existing device map with a new
|
| 85 |
+
one. E.g. for bitsandbytes, since `accelerate` is a hard requirement, if no device_map is
|
| 86 |
+
passed, the device_map is set to `"auto"``
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
device_map (`Union[dict, str]`, *optional*):
|
| 90 |
+
The device_map that is passed through the `from_pretrained` method.
|
| 91 |
+
"""
|
| 92 |
+
return device_map
|
| 93 |
+
|
| 94 |
+
def adjust_target_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
|
| 95 |
+
"""
|
| 96 |
+
Override this method if you want to adjust the `target_dtype` variable used in `from_pretrained`
|
| 97 |
+
to compute the device_map in case the device_map is a `str`. E.g. for bitsandbytes we force-set `target_dtype`
|
| 98 |
+
to `torch.int8` and for 4-bit we pass a custom enum `accelerate.CustomDtype.int4`.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
torch_dtype (`torch.dtype`, *optional*):
|
| 102 |
+
The torch_dtype that is used to compute the device_map.
|
| 103 |
+
"""
|
| 104 |
+
return torch_dtype
|
| 105 |
+
|
| 106 |
+
def update_missing_keys(self, model, missing_keys: List[str], prefix: str) -> List[str]:
|
| 107 |
+
"""
|
| 108 |
+
Override this method if you want to adjust the `missing_keys`.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
missing_keys (`List[str]`, *optional*):
|
| 112 |
+
The list of missing keys in the checkpoint compared to the state dict of the model
|
| 113 |
+
"""
|
| 114 |
+
return missing_keys
|
| 115 |
+
|
| 116 |
+
def update_unexpected_keys(self, model, unexpected_keys: List[str], prefix: str) -> List[str]:
|
| 117 |
+
"""
|
| 118 |
+
Override this method if you want to adjust the `unexpected_keys`.
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
unexpected_keys (`List[str]`, *optional*):
|
| 122 |
+
The list of unexpected keys in the checkpoint compared to the state dict of the model
|
| 123 |
+
"""
|
| 124 |
+
return unexpected_keys
|
| 125 |
+
|
| 126 |
+
def update_missing_keys_after_loading(self, model, missing_keys: List[str], prefix: str) -> List[str]:
|
| 127 |
+
"""
|
| 128 |
+
Override this method if you want to adjust the `missing_keys` after loading the model params,
|
| 129 |
+
but before the model is post-processed.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
missing_keys (`List[str]`, *optional*):
|
| 133 |
+
The list of missing keys in the checkpoint compared to the state dict of the model
|
| 134 |
+
"""
|
| 135 |
+
return missing_keys
|
| 136 |
+
|
| 137 |
+
def update_expected_keys(self, model, expected_keys: List[str], loaded_keys: List[str]) -> List[str]:
|
| 138 |
+
"""
|
| 139 |
+
Override this method if you want to adjust the `update_expected_keys`.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
expected_keys (`List[str]`, *optional*):
|
| 143 |
+
The list of the expected keys in the initialized model.
|
| 144 |
+
loaded_keys (`List[str]`, *optional*):
|
| 145 |
+
The list of the loaded keys in the checkpoint.
|
| 146 |
+
"""
|
| 147 |
+
return expected_keys
|
| 148 |
+
|
| 149 |
+
def get_special_dtypes_update(self, model, torch_dtype: "torch.dtype") -> Dict[str, "torch.dtype"]:
|
| 150 |
+
"""
|
| 151 |
+
returns dtypes for modules that are not quantized - used for the computation of the device_map in case
|
| 152 |
+
one passes a str as a device_map. The method will use the `modules_to_not_convert` that is modified
|
| 153 |
+
in `_process_model_before_weight_loading`.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
model (`~transformers.PreTrainedModel`):
|
| 157 |
+
The model to quantize
|
| 158 |
+
torch_dtype (`torch.dtype`):
|
| 159 |
+
The dtype passed in `from_pretrained` method.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
return {
|
| 163 |
+
name: torch_dtype
|
| 164 |
+
for name, _ in model.named_parameters()
|
| 165 |
+
if any(m in name for m in self.modules_to_not_convert)
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
|
| 169 |
+
"""adjust max_memory argument for infer_auto_device_map() if extra memory is needed for quantization"""
|
| 170 |
+
return max_memory
|
| 171 |
+
|
| 172 |
+
def check_quantized_param(
|
| 173 |
+
self,
|
| 174 |
+
model: "PreTrainedModel",
|
| 175 |
+
param_value: "torch.Tensor",
|
| 176 |
+
param_name: str,
|
| 177 |
+
state_dict: Dict[str, Any],
|
| 178 |
+
**kwargs,
|
| 179 |
+
) -> bool:
|
| 180 |
+
"""
|
| 181 |
+
checks if a loaded state_dict component is part of quantized param + some validation; only defined if
|
| 182 |
+
requires_parameters_quantization == True for quantization methods that require to create a new parameters
|
| 183 |
+
for quantization.
|
| 184 |
+
"""
|
| 185 |
+
return False
|
| 186 |
+
|
| 187 |
+
def create_quantized_param(self, *args, **kwargs) -> "torch.nn.Parameter":
|
| 188 |
+
"""
|
| 189 |
+
takes needed components from state_dict and creates quantized param; only applicable if
|
| 190 |
+
requires_parameters_quantization == True
|
| 191 |
+
"""
|
| 192 |
+
if not self.requires_parameters_quantization:
|
| 193 |
+
raise AttributeError(
|
| 194 |
+
f"`.create_quantized_param()` method is not supported by quantizer class {self.__class__.__name__}."
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
def validate_environment(self, *args, **kwargs):
|
| 198 |
+
"""
|
| 199 |
+
This method is used to potentially check for potential conflicts with arguments that are
|
| 200 |
+
passed in `from_pretrained`. You need to define it for all future quantizers that are integrated with transformers.
|
| 201 |
+
If no explicit check are needed, simply return nothing.
|
| 202 |
+
"""
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
def update_tp_plan(self, config):
|
| 206 |
+
"updates the tp plan for the scales"
|
| 207 |
+
return config
|
| 208 |
+
|
| 209 |
+
def preprocess_model(self, model: "PreTrainedModel", **kwargs):
|
| 210 |
+
"""
|
| 211 |
+
Setting model attributes and/or converting model before weights loading. At this point
|
| 212 |
+
the model should be initialized on the meta device so you can freely manipulate the skeleton
|
| 213 |
+
of the model in order to replace modules in-place. Make sure to override the abstract method `_process_model_before_weight_loading`.
|
| 214 |
+
|
| 215 |
+
Args:
|
| 216 |
+
model (`~transformers.PreTrainedModel`):
|
| 217 |
+
The model to quantize
|
| 218 |
+
kwargs (`dict`, *optional*):
|
| 219 |
+
The keyword arguments that are passed along `_process_model_before_weight_loading`.
|
| 220 |
+
"""
|
| 221 |
+
model.is_quantized = True
|
| 222 |
+
model.quantization_method = self.quantization_config.quant_method
|
| 223 |
+
if self.pre_quantized:
|
| 224 |
+
self._convert_model_for_quantization(model)
|
| 225 |
+
return self._process_model_before_weight_loading(model, **kwargs)
|
| 226 |
+
|
| 227 |
+
def postprocess_model(self, model: "PreTrainedModel", **kwargs):
|
| 228 |
+
"""
|
| 229 |
+
Post-process the model post weights loading.
|
| 230 |
+
Make sure to override the abstract method `_process_model_after_weight_loading`.
|
| 231 |
+
|
| 232 |
+
Args:
|
| 233 |
+
model (`~transformers.PreTrainedModel`):
|
| 234 |
+
The model to quantize
|
| 235 |
+
kwargs (`dict`, *optional*):
|
| 236 |
+
The keyword arguments that are passed along `_process_model_after_weight_loading`.
|
| 237 |
+
"""
|
| 238 |
+
return self._process_model_after_weight_loading(model, **kwargs)
|
| 239 |
+
|
| 240 |
+
def dequantize(self, model):
|
| 241 |
+
"""
|
| 242 |
+
Potentially dequantize the model to retrive the original model, with some loss in accuracy / performance.
|
| 243 |
+
Note not all quantization schemes support this.
|
| 244 |
+
"""
|
| 245 |
+
model = self._dequantize(model)
|
| 246 |
+
|
| 247 |
+
# Delete quantizer and quantization config
|
| 248 |
+
del model.hf_quantizer
|
| 249 |
+
del model.config.quantization_config
|
| 250 |
+
del model.config._pre_quantization_dtype
|
| 251 |
+
model.is_quantized = False
|
| 252 |
+
|
| 253 |
+
return model
|
| 254 |
+
|
| 255 |
+
def _dequantize(self, model):
|
| 256 |
+
raise NotImplementedError(
|
| 257 |
+
f"{self.quantization_config.quant_method} has no implementation of `dequantize`, please raise an issue on GitHub."
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
@staticmethod
|
| 261 |
+
def get_modules_to_not_convert(
|
| 262 |
+
model: "PreTrainedModel",
|
| 263 |
+
skip_modules: Optional[List[str]] = None,
|
| 264 |
+
keep_in_fp32_modules: Optional[List[str]] = None,
|
| 265 |
+
):
|
| 266 |
+
from ..integrations import get_keys_to_not_convert
|
| 267 |
+
|
| 268 |
+
modules_to_not_convert = []
|
| 269 |
+
if skip_modules is None:
|
| 270 |
+
modules_to_not_convert = get_keys_to_not_convert(model)
|
| 271 |
+
else:
|
| 272 |
+
modules_to_not_convert = skip_modules
|
| 273 |
+
|
| 274 |
+
if keep_in_fp32_modules is not None:
|
| 275 |
+
modules_to_not_convert.extend(keep_in_fp32_modules)
|
| 276 |
+
|
| 277 |
+
return modules_to_not_convert
|
| 278 |
+
|
| 279 |
+
@property
|
| 280 |
+
def is_qat_trainable(self) -> bool:
|
| 281 |
+
"""Flag indicating whether the quantized model can carry out quantization aware training"""
|
| 282 |
+
return False
|
| 283 |
+
|
| 284 |
+
@property
|
| 285 |
+
def is_compileable(self) -> bool:
|
| 286 |
+
"""Flag indicating whether the quantized model can be compiled"""
|
| 287 |
+
return False
|
| 288 |
+
|
| 289 |
+
@abstractmethod
|
| 290 |
+
def _process_model_before_weight_loading(self, model, **kwargs): ...
|
| 291 |
+
|
| 292 |
+
@abstractmethod
|
| 293 |
+
def _process_model_after_weight_loading(self, model, **kwargs): ...
|
| 294 |
+
|
| 295 |
+
@abstractmethod
|
| 296 |
+
def is_serializable(self, safe_serialization=None): ...
|
| 297 |
+
|
| 298 |
+
@property
|
| 299 |
+
@abstractmethod
|
| 300 |
+
def is_trainable(self): ...
|
| 301 |
+
|
| 302 |
+
def _convert_model_for_quantization(self, model):
|
| 303 |
+
from accelerate import init_empty_weights
|
| 304 |
+
|
| 305 |
+
for name, module in model.named_modules():
|
| 306 |
+
module_class_name = module.__class__.__name__
|
| 307 |
+
if (
|
| 308 |
+
module_class_name in MODULES_TO_PATCH_FOR_QUANTIZATION.keys()
|
| 309 |
+
and self.quantization_config.quant_method == QuantizationMethod.COMPRESSED_TENSORS
|
| 310 |
+
):
|
| 311 |
+
with init_empty_weights():
|
| 312 |
+
parent_module, name = get_module_from_name(model, name)
|
| 313 |
+
parent_module._modules[name] = MODULES_TO_PATCH_FOR_QUANTIZATION[module_class_name](
|
| 314 |
+
model.config.get_text_config()
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class SequentialLlama4TextExperts(ModuleList):
|
| 319 |
+
"""
|
| 320 |
+
A module that implements a compressed version of a list of expert modules.
|
| 321 |
+
This is specifically designed to work with Llama4TextExperts in MoE layers.
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
def __init__(self, config):
|
| 325 |
+
from transformers.models.llama4.modeling_llama4 import Llama4TextMLP
|
| 326 |
+
|
| 327 |
+
super().__init__([Llama4TextMLP(config) for _ in range(config.num_local_experts)])
|
| 328 |
+
self.num_experts = config.num_local_experts
|
| 329 |
+
|
| 330 |
+
def forward(
|
| 331 |
+
self,
|
| 332 |
+
hidden_states: "torch.Tensor",
|
| 333 |
+
) -> "torch.Tensor":
|
| 334 |
+
hidden_states = hidden_states.reshape(self.num_experts, -1, hidden_states.shape[-1])
|
| 335 |
+
routed_out = torch.zeros_like(hidden_states)
|
| 336 |
+
for expert_idx in range(self.num_experts):
|
| 337 |
+
routed_out[expert_idx] = self[expert_idx](hidden_states[expert_idx])
|
| 338 |
+
return routed_out
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
MODULES_TO_PATCH_FOR_QUANTIZATION = {
|
| 342 |
+
"Llama4TextExperts": {
|
| 343 |
+
"module_name": SequentialLlama4TextExperts,
|
| 344 |
+
"quantization_methods": [
|
| 345 |
+
QuantizationMethod.COMPRESSED_TENSORS,
|
| 346 |
+
QuantizationMethod.BITS_AND_BYTES,
|
| 347 |
+
],
|
| 348 |
+
}
|
| 349 |
+
}
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/beam_constraints.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ABC):
|
| 6 |
+
r"""Abstract base class for all constraints that can be applied during generation.
|
| 7 |
+
It must define how the constraint can be satisfied.
|
| 8 |
+
|
| 9 |
+
All classes that inherit Constraint must follow the requirement that
|
| 10 |
+
|
| 11 |
+
```py
|
| 12 |
+
completed = False
|
| 13 |
+
while not completed:
|
| 14 |
+
_, completed = constraint.update(constraint.advance())
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
will always terminate (halt).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(self):
|
| 21 |
+
# test for the above condition
|
| 22 |
+
self.test()
|
| 23 |
+
|
| 24 |
+
def test(self):
|
| 25 |
+
"""
|
| 26 |
+
Tests whether this constraint has been properly defined.
|
| 27 |
+
"""
|
| 28 |
+
counter = 0
|
| 29 |
+
completed = False
|
| 30 |
+
while not completed:
|
| 31 |
+
if counter == 1:
|
| 32 |
+
self.reset()
|
| 33 |
+
advance = self.advance()
|
| 34 |
+
if not self.does_advance(advance):
|
| 35 |
+
raise Exception(
|
| 36 |
+
"Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
stepped, completed, reset = self.update(advance)
|
| 40 |
+
counter += 1
|
| 41 |
+
|
| 42 |
+
if counter > 10000:
|
| 43 |
+
raise Exception("update() does not fulfill the constraint.")
|
| 44 |
+
|
| 45 |
+
if self.remaining() != 0:
|
| 46 |
+
raise Exception("Custom Constraint is not defined correctly.")
|
| 47 |
+
|
| 48 |
+
@abstractmethod
|
| 49 |
+
def advance(self):
|
| 50 |
+
"""
|
| 51 |
+
When called, returns the token(s) that would take this constraint one step closer to being fulfilled.
|
| 52 |
+
|
| 53 |
+
Return:
|
| 54 |
+
token_ids (Union[int, List[int], None]):
|
| 55 |
+
- A single token ID (int) that advances the constraint, or
|
| 56 |
+
- A list of token IDs that could advance the constraint
|
| 57 |
+
- None if the constraint is completed or cannot be advanced
|
| 58 |
+
"""
|
| 59 |
+
raise NotImplementedError(
|
| 60 |
+
f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
@abstractmethod
|
| 64 |
+
def does_advance(self, token_id: int):
|
| 65 |
+
"""
|
| 66 |
+
Reads in a token and returns whether it creates progress.
|
| 67 |
+
"""
|
| 68 |
+
raise NotImplementedError(
|
| 69 |
+
f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
@abstractmethod
|
| 73 |
+
def update(self, token_id: int):
|
| 74 |
+
"""
|
| 75 |
+
Reads in a token and returns booleans that indicate the progress made by it. This function will update the
|
| 76 |
+
state of this object unlikes `does_advance(self, token_id: int)`.
|
| 77 |
+
|
| 78 |
+
This isn't to test whether a certain token will advance the progress; it's to update its state as if it has
|
| 79 |
+
been generated. This becomes important if token_id != desired token (refer to else statement in
|
| 80 |
+
PhrasalConstraint)
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
token_id(`int`):
|
| 84 |
+
The id of a newly generated token in the beam search.
|
| 85 |
+
Return:
|
| 86 |
+
stepped(`bool`):
|
| 87 |
+
Whether this constraint has become one step closer to being fulfuilled.
|
| 88 |
+
completed(`bool`):
|
| 89 |
+
Whether this constraint has been completely fulfilled by this token being generated.
|
| 90 |
+
reset (`bool`):
|
| 91 |
+
Whether this constraint has reset its progress by this token being generated.
|
| 92 |
+
"""
|
| 93 |
+
raise NotImplementedError(
|
| 94 |
+
f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
@abstractmethod
|
| 98 |
+
def reset(self):
|
| 99 |
+
"""
|
| 100 |
+
Resets the state of this constraint to its initialization. We would call this in cases where the fulfillment of
|
| 101 |
+
a constraint is abrupted by an unwanted token.
|
| 102 |
+
"""
|
| 103 |
+
raise NotImplementedError(
|
| 104 |
+
f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
@abstractmethod
|
| 108 |
+
def remaining(self):
|
| 109 |
+
"""
|
| 110 |
+
Returns the number of remaining steps of `advance()` in order to complete this constraint.
|
| 111 |
+
"""
|
| 112 |
+
raise NotImplementedError(
|
| 113 |
+
f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
@abstractmethod
|
| 117 |
+
def copy(self, stateful=False):
|
| 118 |
+
"""
|
| 119 |
+
Creates a new instance of this constraint.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
stateful(`bool`): Whether to not only copy the constraint for new instance, but also its state.
|
| 123 |
+
|
| 124 |
+
Return:
|
| 125 |
+
constraint(`Constraint`): The same constraint as the one being called from.
|
| 126 |
+
"""
|
| 127 |
+
raise NotImplementedError(
|
| 128 |
+
f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class PhrasalConstraint(Constraint):
|
| 133 |
+
r"""
|
| 134 |
+
[`Constraint`] enforcing that an ordered sequence of tokens is included in the output.
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
token_ids (`List[int]`):
|
| 138 |
+
The id of the token that must be generated by the output.
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
def __init__(self, token_ids: List[int]):
|
| 142 |
+
super(Constraint, self).__init__()
|
| 143 |
+
|
| 144 |
+
if not isinstance(token_ids, list) or len(token_ids) == 0:
|
| 145 |
+
raise ValueError(f"`token_ids` has to be a non-empty list, but is {token_ids}.")
|
| 146 |
+
if any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids):
|
| 147 |
+
raise ValueError(f"Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.")
|
| 148 |
+
|
| 149 |
+
self.token_ids = token_ids
|
| 150 |
+
|
| 151 |
+
self.seqlen = len(self.token_ids)
|
| 152 |
+
self.fulfilled_idx = -1 # the index of the currently fulfilled step
|
| 153 |
+
self.completed = False
|
| 154 |
+
|
| 155 |
+
def advance(self):
|
| 156 |
+
if self.completed:
|
| 157 |
+
return None
|
| 158 |
+
return self.token_ids[self.fulfilled_idx + 1]
|
| 159 |
+
|
| 160 |
+
def does_advance(self, token_id: int):
|
| 161 |
+
if not isinstance(token_id, int):
|
| 162 |
+
raise TypeError(f"`token_id` has to be an `int`, but is {token_id} of type {type(token_id)}")
|
| 163 |
+
|
| 164 |
+
if self.completed:
|
| 165 |
+
return False
|
| 166 |
+
|
| 167 |
+
return token_id == self.token_ids[self.fulfilled_idx + 1]
|
| 168 |
+
|
| 169 |
+
def update(self, token_id: int):
|
| 170 |
+
if not isinstance(token_id, int):
|
| 171 |
+
raise TypeError(f"`token_id` has to be an `int`, but is {token_id} of type {type(token_id)}")
|
| 172 |
+
|
| 173 |
+
stepped = False
|
| 174 |
+
completed = False
|
| 175 |
+
reset = False
|
| 176 |
+
|
| 177 |
+
if self.does_advance(token_id):
|
| 178 |
+
self.fulfilled_idx += 1
|
| 179 |
+
stepped = True
|
| 180 |
+
if self.fulfilled_idx == (self.seqlen - 1):
|
| 181 |
+
completed = True
|
| 182 |
+
self.completed = completed
|
| 183 |
+
else:
|
| 184 |
+
# failed to make progress.
|
| 185 |
+
reset = True
|
| 186 |
+
self.reset()
|
| 187 |
+
return stepped, completed, reset
|
| 188 |
+
|
| 189 |
+
def reset(self):
|
| 190 |
+
self.completed = False
|
| 191 |
+
self.fulfilled_idx = 0
|
| 192 |
+
|
| 193 |
+
def remaining(self):
|
| 194 |
+
return self.seqlen - (self.fulfilled_idx + 1)
|
| 195 |
+
|
| 196 |
+
def copy(self, stateful=False):
|
| 197 |
+
new_constraint = PhrasalConstraint(self.token_ids)
|
| 198 |
+
|
| 199 |
+
if stateful:
|
| 200 |
+
new_constraint.seq_len = self.seqlen
|
| 201 |
+
new_constraint.fulfilled_idx = self.fulfilled_idx
|
| 202 |
+
new_constraint.completed = self.completed
|
| 203 |
+
|
| 204 |
+
return new_constraint
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class DisjunctiveTrie:
|
| 208 |
+
def __init__(self, nested_token_ids: List[List[int]], no_subsets=True):
|
| 209 |
+
r"""
|
| 210 |
+
A helper class that builds a trie with the words represented in `nested_token_ids`.
|
| 211 |
+
"""
|
| 212 |
+
self.max_height = max([len(one) for one in nested_token_ids])
|
| 213 |
+
|
| 214 |
+
root = {}
|
| 215 |
+
for token_ids in nested_token_ids:
|
| 216 |
+
level = root
|
| 217 |
+
for tidx, token_id in enumerate(token_ids):
|
| 218 |
+
if token_id not in level:
|
| 219 |
+
level[token_id] = {}
|
| 220 |
+
|
| 221 |
+
level = level[token_id]
|
| 222 |
+
|
| 223 |
+
if no_subsets and self.has_subsets(root, nested_token_ids):
|
| 224 |
+
raise ValueError(
|
| 225 |
+
"Each list in `nested_token_ids` can't be a complete subset of another list, but is"
|
| 226 |
+
f" {nested_token_ids}."
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
self.trie = root
|
| 230 |
+
|
| 231 |
+
def next_tokens(self, current_seq):
|
| 232 |
+
"""
|
| 233 |
+
The next possible tokens that will progress the trie, given the current sequence of tokens in `current_seq`.
|
| 234 |
+
"""
|
| 235 |
+
start = self.trie
|
| 236 |
+
|
| 237 |
+
for current_token in current_seq:
|
| 238 |
+
start = start[current_token]
|
| 239 |
+
|
| 240 |
+
next_tokens = list(start.keys())
|
| 241 |
+
|
| 242 |
+
return next_tokens
|
| 243 |
+
|
| 244 |
+
def reached_leaf(self, current_seq):
|
| 245 |
+
next_tokens = self.next_tokens(current_seq)
|
| 246 |
+
|
| 247 |
+
return len(next_tokens) == 0
|
| 248 |
+
|
| 249 |
+
def count_leaves(self, root):
|
| 250 |
+
next_nodes = list(root.values())
|
| 251 |
+
if len(next_nodes) == 0:
|
| 252 |
+
return 1
|
| 253 |
+
else:
|
| 254 |
+
return sum([self.count_leaves(nn) for nn in next_nodes])
|
| 255 |
+
|
| 256 |
+
def has_subsets(self, trie, nested_token_ids):
|
| 257 |
+
"""
|
| 258 |
+
Returns whether # of leaves == # of words. Otherwise some word is a subset of another.
|
| 259 |
+
"""
|
| 260 |
+
leaf_count = self.count_leaves(trie)
|
| 261 |
+
return len(nested_token_ids) != leaf_count
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class DisjunctiveConstraint(Constraint):
|
| 265 |
+
r"""
|
| 266 |
+
A special [`Constraint`] that is fulfilled by fulfilling just one of several constraints.
|
| 267 |
+
|
| 268 |
+
Args:
|
| 269 |
+
nested_token_ids (`List[List[int]]`):
|
| 270 |
+
A list of words, where each word is a list of ids. This constraint is fulfilled by generating just one from
|
| 271 |
+
the list of words.
|
| 272 |
+
"""
|
| 273 |
+
|
| 274 |
+
def __init__(self, nested_token_ids: List[List[int]]):
|
| 275 |
+
super(Constraint, self).__init__()
|
| 276 |
+
|
| 277 |
+
if not isinstance(nested_token_ids, list) or len(nested_token_ids) == 0:
|
| 278 |
+
raise ValueError(f"`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.")
|
| 279 |
+
if any(not isinstance(token_ids, list) for token_ids in nested_token_ids):
|
| 280 |
+
raise ValueError(f"`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.")
|
| 281 |
+
if any(
|
| 282 |
+
any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids)
|
| 283 |
+
for token_ids in nested_token_ids
|
| 284 |
+
):
|
| 285 |
+
raise ValueError(
|
| 286 |
+
f"Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}."
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
self.trie = DisjunctiveTrie(nested_token_ids)
|
| 290 |
+
self.token_ids = nested_token_ids
|
| 291 |
+
|
| 292 |
+
self.seqlen = self.trie.max_height
|
| 293 |
+
self.current_seq = []
|
| 294 |
+
self.completed = False
|
| 295 |
+
|
| 296 |
+
def advance(self):
|
| 297 |
+
token_list = self.trie.next_tokens(self.current_seq)
|
| 298 |
+
|
| 299 |
+
if len(token_list) == 0:
|
| 300 |
+
return None
|
| 301 |
+
else:
|
| 302 |
+
return token_list
|
| 303 |
+
|
| 304 |
+
def does_advance(self, token_id: int):
|
| 305 |
+
if not isinstance(token_id, int):
|
| 306 |
+
raise TypeError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(token_id)}")
|
| 307 |
+
|
| 308 |
+
next_tokens = self.trie.next_tokens(self.current_seq)
|
| 309 |
+
|
| 310 |
+
return token_id in next_tokens
|
| 311 |
+
|
| 312 |
+
def update(self, token_id: int):
|
| 313 |
+
if not isinstance(token_id, int):
|
| 314 |
+
raise TypeError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(token_id)}")
|
| 315 |
+
|
| 316 |
+
stepped = False
|
| 317 |
+
completed = False
|
| 318 |
+
reset = False
|
| 319 |
+
|
| 320 |
+
if self.does_advance(token_id):
|
| 321 |
+
self.current_seq.append(token_id)
|
| 322 |
+
stepped = True
|
| 323 |
+
else:
|
| 324 |
+
reset = True
|
| 325 |
+
self.reset()
|
| 326 |
+
|
| 327 |
+
completed = self.trie.reached_leaf(self.current_seq)
|
| 328 |
+
self.completed = completed
|
| 329 |
+
|
| 330 |
+
return stepped, completed, reset
|
| 331 |
+
|
| 332 |
+
def reset(self):
|
| 333 |
+
self.completed = False
|
| 334 |
+
self.current_seq = []
|
| 335 |
+
|
| 336 |
+
def remaining(self):
|
| 337 |
+
if self.completed:
|
| 338 |
+
# since this can be completed without reaching max height
|
| 339 |
+
return 0
|
| 340 |
+
else:
|
| 341 |
+
return self.seqlen - len(self.current_seq)
|
| 342 |
+
|
| 343 |
+
def copy(self, stateful=False):
|
| 344 |
+
new_constraint = DisjunctiveConstraint(self.token_ids)
|
| 345 |
+
|
| 346 |
+
if stateful:
|
| 347 |
+
new_constraint.seq_len = self.seqlen
|
| 348 |
+
new_constraint.current_seq = self.current_seq
|
| 349 |
+
new_constraint.completed = self.completed
|
| 350 |
+
|
| 351 |
+
return new_constraint
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
class ConstraintListState:
|
| 355 |
+
r"""
|
| 356 |
+
A class for beam scorers to track its progress through a list of constraints.
|
| 357 |
+
|
| 358 |
+
Args:
|
| 359 |
+
constraints (`List[Constraint]`):
|
| 360 |
+
A list of [`Constraint`] objects that must be fulfilled by the beam scorer.
|
| 361 |
+
"""
|
| 362 |
+
|
| 363 |
+
def __init__(self, constraints: List[Constraint]):
|
| 364 |
+
self.constraints = constraints
|
| 365 |
+
|
| 366 |
+
# max # of steps required to fulfill a given constraint
|
| 367 |
+
self.max_seqlen = max([c.seqlen for c in constraints])
|
| 368 |
+
self.n_constraints = len(constraints)
|
| 369 |
+
self.completed = False
|
| 370 |
+
|
| 371 |
+
self.init_state()
|
| 372 |
+
|
| 373 |
+
def init_state(self):
|
| 374 |
+
self.complete_constraints = []
|
| 375 |
+
self.inprogress_constraint = None
|
| 376 |
+
self.pending_constraints = [constraint.copy(stateful=False) for constraint in self.constraints]
|
| 377 |
+
|
| 378 |
+
def get_bank(self):
|
| 379 |
+
add = 0
|
| 380 |
+
if self.inprogress_constraint:
|
| 381 |
+
# extra points for having a constraint mid-fulfilled
|
| 382 |
+
add += self.max_seqlen - self.inprogress_constraint.remaining()
|
| 383 |
+
|
| 384 |
+
return (len(self.complete_constraints) * self.max_seqlen) + add
|
| 385 |
+
|
| 386 |
+
def advance(self):
|
| 387 |
+
"""The list of tokens to generate such that we can make progress.
|
| 388 |
+
By "list" we don't mean the list of token that will fully fulfill a constraint.
|
| 389 |
+
|
| 390 |
+
Given constraints `c_i = {t_ij | j == # of tokens}`, If we're not in the middle of progressing through a
|
| 391 |
+
specific constraint `c_i`, we return:
|
| 392 |
+
|
| 393 |
+
`[t_k1 for k in indices of unfulfilled constraints]`
|
| 394 |
+
|
| 395 |
+
If we are in the middle of a constraint, then we return:
|
| 396 |
+
`[t_ij]`, where `i` is the index of the inprogress constraint, `j` is the next step for the constraint.
|
| 397 |
+
|
| 398 |
+
Though we don't care which constraint is fulfilled first, if we are in the progress of fulfilling a constraint,
|
| 399 |
+
that's the only one we'll return.
|
| 400 |
+
"""
|
| 401 |
+
token_list = []
|
| 402 |
+
if self.inprogress_constraint is None:
|
| 403 |
+
for constraint in self.pending_constraints: # "pending" == "unfulfilled yet"
|
| 404 |
+
advance = constraint.advance()
|
| 405 |
+
if isinstance(advance, int):
|
| 406 |
+
token_list.append(advance)
|
| 407 |
+
elif isinstance(advance, list):
|
| 408 |
+
token_list.extend(advance)
|
| 409 |
+
else:
|
| 410 |
+
advance = self.inprogress_constraint.advance()
|
| 411 |
+
if isinstance(advance, int):
|
| 412 |
+
token_list.append(advance)
|
| 413 |
+
elif isinstance(advance, list):
|
| 414 |
+
token_list.extend(advance)
|
| 415 |
+
|
| 416 |
+
if len(token_list) == 0:
|
| 417 |
+
return None
|
| 418 |
+
else:
|
| 419 |
+
return token_list
|
| 420 |
+
|
| 421 |
+
def reset(self, token_ids: Optional[List[int]]):
|
| 422 |
+
"""
|
| 423 |
+
token_ids: the tokens generated thus far to reset the state of the progress through constraints.
|
| 424 |
+
"""
|
| 425 |
+
self.init_state()
|
| 426 |
+
|
| 427 |
+
if token_ids is not None:
|
| 428 |
+
for token in token_ids:
|
| 429 |
+
# completes or steps **one** constraint
|
| 430 |
+
complete, stepped = self.add(token)
|
| 431 |
+
|
| 432 |
+
# the entire list of constraints are fulfilled
|
| 433 |
+
if self.completed:
|
| 434 |
+
break
|
| 435 |
+
|
| 436 |
+
def add(self, token_id: int):
|
| 437 |
+
if not isinstance(token_id, int):
|
| 438 |
+
raise TypeError(f"`token_id` should be an `int`, but is `{token_id}`.")
|
| 439 |
+
|
| 440 |
+
complete, stepped = False, False
|
| 441 |
+
|
| 442 |
+
if self.completed:
|
| 443 |
+
complete = True
|
| 444 |
+
stepped = False
|
| 445 |
+
return complete, stepped
|
| 446 |
+
|
| 447 |
+
if self.inprogress_constraint is not None:
|
| 448 |
+
# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
|
| 449 |
+
# job, simply update the state
|
| 450 |
+
|
| 451 |
+
stepped, complete, reset = self.inprogress_constraint.update(token_id)
|
| 452 |
+
if reset:
|
| 453 |
+
# 1. If the next token breaks the progress, then we must restart.
|
| 454 |
+
# e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".
|
| 455 |
+
|
| 456 |
+
# But that doesn't mean we self.init_state(), since we only reset the state for this particular
|
| 457 |
+
# constraint, not the full list of constraints.
|
| 458 |
+
|
| 459 |
+
self.pending_constraints.append(self.inprogress_constraint.copy(stateful=False))
|
| 460 |
+
self.inprogress_constraint = None
|
| 461 |
+
|
| 462 |
+
if complete:
|
| 463 |
+
# 2. If the next token completes the constraint, move it to completed list, set
|
| 464 |
+
# inprogress to None. If there are no pending constraints either, then this full list of constraints
|
| 465 |
+
# is complete.
|
| 466 |
+
|
| 467 |
+
self.complete_constraints.append(self.inprogress_constraint)
|
| 468 |
+
self.inprogress_constraint = None
|
| 469 |
+
|
| 470 |
+
if len(self.pending_constraints) == 0:
|
| 471 |
+
# we're done!
|
| 472 |
+
self.completed = True
|
| 473 |
+
|
| 474 |
+
else:
|
| 475 |
+
# Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
|
| 476 |
+
# of constraints?
|
| 477 |
+
|
| 478 |
+
for cidx, pending_constraint in enumerate(self.pending_constraints):
|
| 479 |
+
if pending_constraint.does_advance(token_id):
|
| 480 |
+
stepped, complete, reset = pending_constraint.update(token_id)
|
| 481 |
+
|
| 482 |
+
if not stepped:
|
| 483 |
+
raise Exception(
|
| 484 |
+
"`constraint.update(token_id)` is not yielding incremental progress, "
|
| 485 |
+
"even though `constraint.does_advance(token_id)` is true."
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
if complete:
|
| 489 |
+
self.complete_constraints.append(pending_constraint)
|
| 490 |
+
self.inprogress_constraint = None
|
| 491 |
+
|
| 492 |
+
if not complete and stepped:
|
| 493 |
+
self.inprogress_constraint = pending_constraint
|
| 494 |
+
|
| 495 |
+
if complete or stepped:
|
| 496 |
+
# If we made any progress at all, then it's at least not a "pending constraint".
|
| 497 |
+
|
| 498 |
+
self.pending_constraints = (
|
| 499 |
+
self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
if len(self.pending_constraints) == 0 and self.inprogress_constraint is None:
|
| 503 |
+
# If there's no longer any pending after this and no inprogress either, then we must be
|
| 504 |
+
# complete.
|
| 505 |
+
|
| 506 |
+
self.completed = True
|
| 507 |
+
|
| 508 |
+
break # prevent accidentally stepping through multiple constraints with just one token.
|
| 509 |
+
|
| 510 |
+
return complete, stepped
|
| 511 |
+
|
| 512 |
+
def copy(self, stateful=True):
|
| 513 |
+
new_state = ConstraintListState(self.constraints) # we actually never though self.constraints objects
|
| 514 |
+
# throughout this process. So it's at initialization state.
|
| 515 |
+
|
| 516 |
+
if stateful:
|
| 517 |
+
new_state.complete_constraints = [
|
| 518 |
+
constraint.copy(stateful=True) for constraint in self.complete_constraints
|
| 519 |
+
]
|
| 520 |
+
if self.inprogress_constraint is not None:
|
| 521 |
+
new_state.inprogress_constraint = self.inprogress_constraint.copy(stateful=True)
|
| 522 |
+
new_state.pending_constraints = [constraint.copy() for constraint in self.pending_constraints]
|
| 523 |
+
|
| 524 |
+
return new_state
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/beam_search.py
ADDED
|
@@ -0,0 +1,1013 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 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 |
+
|
| 16 |
+
from abc import ABC, abstractmethod
|
| 17 |
+
from collections import UserDict
|
| 18 |
+
from typing import Dict, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
|
| 23 |
+
from ..utils import add_start_docstrings
|
| 24 |
+
from .beam_constraints import Constraint, ConstraintListState
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
PROCESS_INPUTS_DOCSTRING = r"""
|
| 28 |
+
Args:
|
| 29 |
+
input_ids (`torch.LongTensor` of shape `(batch_size * num_beams, sequence_length)`):
|
| 30 |
+
Indices of input sequence tokens in the vocabulary.
|
| 31 |
+
|
| 32 |
+
Indices can be obtained using any class inheriting from [`PreTrainedTokenizer`]. See
|
| 33 |
+
[`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
|
| 34 |
+
|
| 35 |
+
[What are input IDs?](../glossary#input-ids)
|
| 36 |
+
next_scores (`torch.FloatTensor` of shape `(batch_size, 2 * num_beams)`):
|
| 37 |
+
Current scores of the top `2 * num_beams` non-finished beam hypotheses.
|
| 38 |
+
next_tokens (`torch.LongTensor` of shape `(batch_size, 2 * num_beams)`):
|
| 39 |
+
`input_ids` of the tokens corresponding to the top `2 * num_beams` non-finished beam hypotheses.
|
| 40 |
+
next_indices (`torch.LongTensor` of shape `(batch_size, 2 * num_beams)`):
|
| 41 |
+
Beam indices indicating to which beam hypothesis the `next_tokens` correspond.
|
| 42 |
+
pad_token_id (`int`, *optional*):
|
| 43 |
+
The id of the *padding* token.
|
| 44 |
+
eos_token_id (`Union[int, List[int]]`, *optional*):
|
| 45 |
+
The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
|
| 46 |
+
beam_indices (`torch.LongTensor`, *optional*):
|
| 47 |
+
Beam indices indicating to which beam hypothesis each token correspond.
|
| 48 |
+
group_index (`int`, *optional*):
|
| 49 |
+
The index of the group of beams. Used with [`~PreTrainedModel.group_beam_search`].
|
| 50 |
+
|
| 51 |
+
Return:
|
| 52 |
+
`UserDict`: A dictionary composed of the fields as defined above:
|
| 53 |
+
|
| 54 |
+
- **next_beam_scores** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Updated scores of all
|
| 55 |
+
non-finished beams.
|
| 56 |
+
- **next_beam_tokens** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Next tokens to be added
|
| 57 |
+
to the non-finished beam_hypotheses.
|
| 58 |
+
- **next_beam_indices** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Beam indices
|
| 59 |
+
indicating to which beam the next tokens shall be added.
|
| 60 |
+
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
FINALIZE_INPUTS_DOCSTRING = r"""
|
| 64 |
+
Args:
|
| 65 |
+
input_ids (`torch.LongTensor` of shape `(batch_size * num_beams, sequence_length)`):
|
| 66 |
+
Indices of input sequence tokens in the vocabulary.
|
| 67 |
+
|
| 68 |
+
Indices can be obtained using any class inheriting from [`PreTrainedTokenizer`]. See
|
| 69 |
+
[`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
|
| 70 |
+
|
| 71 |
+
[What are input IDs?](../glossary#input-ids)
|
| 72 |
+
final_beam_scores (`torch.FloatTensor` of shape `(batch_size * num_beams)`):
|
| 73 |
+
The final scores of all non-finished beams.
|
| 74 |
+
final_beam_tokens (`torch.FloatTensor` of shape `(batch_size * num_beams)`):
|
| 75 |
+
The last tokens to be added to the non-finished beam_hypotheses.
|
| 76 |
+
final_beam_indices (`torch.FloatTensor` of shape `(batch_size * num_beams)`):
|
| 77 |
+
The beam indices indicating to which beam the `final_beam_tokens` shall be added.
|
| 78 |
+
pad_token_id (`int`, *optional*):
|
| 79 |
+
The id of the *padding* token.
|
| 80 |
+
eos_token_id (`Union[int, List[int]]`, *optional*):
|
| 81 |
+
The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
|
| 82 |
+
|
| 83 |
+
Return:
|
| 84 |
+
`torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`: The generated sequences.
|
| 85 |
+
The second dimension (sequence_length) is either equal to `max_length` or shorter if all batches finished early
|
| 86 |
+
due to the `eos_token_id`.
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class BeamScorer(ABC):
|
| 92 |
+
"""
|
| 93 |
+
Abstract base class for all beam scorers that are used for [`~PreTrainedModel.beam_search`] and
|
| 94 |
+
[`~PreTrainedModel.beam_sample`].
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
@abstractmethod
|
| 98 |
+
@add_start_docstrings(PROCESS_INPUTS_DOCSTRING)
|
| 99 |
+
def process(
|
| 100 |
+
self,
|
| 101 |
+
input_ids: torch.LongTensor,
|
| 102 |
+
next_scores: torch.FloatTensor,
|
| 103 |
+
next_tokens: torch.LongTensor,
|
| 104 |
+
next_indices: torch.LongTensor,
|
| 105 |
+
**kwargs,
|
| 106 |
+
) -> Tuple[torch.Tensor]:
|
| 107 |
+
raise NotImplementedError("This is an abstract method.")
|
| 108 |
+
|
| 109 |
+
@abstractmethod
|
| 110 |
+
@add_start_docstrings(FINALIZE_INPUTS_DOCSTRING)
|
| 111 |
+
def finalize(
|
| 112 |
+
self,
|
| 113 |
+
input_ids: torch.LongTensor,
|
| 114 |
+
next_scores: torch.FloatTensor,
|
| 115 |
+
next_tokens: torch.LongTensor,
|
| 116 |
+
next_indices: torch.LongTensor,
|
| 117 |
+
max_length: int,
|
| 118 |
+
**kwargs,
|
| 119 |
+
) -> torch.LongTensor:
|
| 120 |
+
raise NotImplementedError("This is an abstract method.")
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class BeamSearchScorer(BeamScorer):
|
| 124 |
+
r"""
|
| 125 |
+
[`BeamScorer`] implementing standard beam search decoding.
|
| 126 |
+
|
| 127 |
+
Adapted in part from [Facebook's XLM beam search
|
| 128 |
+
code](https://github.com/facebookresearch/XLM/blob/9e6f6814d17be4fe5b15f2e6c43eb2b2d76daeb4/src/model/transformer.py#L529).
|
| 129 |
+
|
| 130 |
+
Reference for the diverse beam search algorithm and implementation [Ashwin Kalyan's DBS
|
| 131 |
+
implementation](https://github.com/ashwinkalyan/dbs/blob/master/dbs/beam_utils.lua)
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
batch_size (`int`):
|
| 135 |
+
Batch Size of `input_ids` for which standard beam search decoding is run in parallel.
|
| 136 |
+
num_beams (`int`):
|
| 137 |
+
Number of beams for beam search.
|
| 138 |
+
device (`torch.device`):
|
| 139 |
+
Defines the device type (*e.g.*, `"cpu"` or `"cuda"`) on which this instance of `BeamSearchScorer` will be
|
| 140 |
+
allocated.
|
| 141 |
+
length_penalty (`float`, *optional*, defaults to 1.0):
|
| 142 |
+
Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
|
| 143 |
+
the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log
|
| 144 |
+
likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while
|
| 145 |
+
`length_penalty` < 0.0 encourages shorter sequences.
|
| 146 |
+
do_early_stopping (`bool` or `str`, *optional*, defaults to `False`):
|
| 147 |
+
Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
|
| 148 |
+
`True`, where the generation stops as soon as there are `num_beams` complete candidates; `False`, where an
|
| 149 |
+
heuristic is applied and the generation stops when is it very unlikely to find better candidates;
|
| 150 |
+
`"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical
|
| 151 |
+
beam search algorithm).
|
| 152 |
+
num_beam_hyps_to_keep (`int`, *optional*, defaults to 1):
|
| 153 |
+
The number of beam hypotheses that shall be returned upon calling
|
| 154 |
+
[`~transformers.BeamSearchScorer.finalize`].
|
| 155 |
+
num_beam_groups (`int`, *optional*, defaults to 1):
|
| 156 |
+
Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
|
| 157 |
+
See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
|
| 158 |
+
max_length (`int`, *optional*):
|
| 159 |
+
The maximum length of the sequence to be generated.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
def __init__(
|
| 163 |
+
self,
|
| 164 |
+
batch_size: int,
|
| 165 |
+
num_beams: int,
|
| 166 |
+
device: torch.device,
|
| 167 |
+
length_penalty: Optional[float] = 1.0,
|
| 168 |
+
do_early_stopping: Optional[Union[bool, str]] = False,
|
| 169 |
+
num_beam_hyps_to_keep: Optional[int] = 1,
|
| 170 |
+
num_beam_groups: Optional[int] = 1,
|
| 171 |
+
max_length: Optional[int] = None,
|
| 172 |
+
):
|
| 173 |
+
self.num_beams = num_beams
|
| 174 |
+
self.device = device
|
| 175 |
+
self.length_penalty = length_penalty
|
| 176 |
+
self.do_early_stopping = do_early_stopping
|
| 177 |
+
self.num_beam_hyps_to_keep = num_beam_hyps_to_keep
|
| 178 |
+
self.num_beam_groups = num_beam_groups
|
| 179 |
+
self.group_size = self.num_beams // self.num_beam_groups
|
| 180 |
+
|
| 181 |
+
self._is_init = False
|
| 182 |
+
# self._beam_hyps[i*self.num_beam_groups+j] is the beam_hyps of the j-th group in the i-th mini-batch.
|
| 183 |
+
# If group_beam_search is not used, the list consists of `batch_size` beam_hyps.
|
| 184 |
+
self._beam_hyps = [
|
| 185 |
+
BeamHypotheses(
|
| 186 |
+
num_beams=self.group_size,
|
| 187 |
+
length_penalty=self.length_penalty,
|
| 188 |
+
early_stopping=self.do_early_stopping,
|
| 189 |
+
max_length=max_length,
|
| 190 |
+
)
|
| 191 |
+
for _ in range(batch_size * self.num_beam_groups)
|
| 192 |
+
]
|
| 193 |
+
# self._done[i*self.num_beam_groups+j] indicates whether the generation of the beam_hyps of the j-th group
|
| 194 |
+
# in the i-th mini-batch is complete.
|
| 195 |
+
self._done = torch.tensor(
|
| 196 |
+
[False for _ in range(batch_size * self.num_beam_groups)], dtype=torch.bool, device=self.device
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
if not isinstance(num_beams, int) or num_beams <= 1:
|
| 200 |
+
raise ValueError(
|
| 201 |
+
f"`num_beams` has to be an integer strictly greater than 1, but is {num_beams}. For `num_beams` == 1,"
|
| 202 |
+
" one should make use of `greedy_search` instead."
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
if not isinstance(num_beam_groups, int) or (num_beam_groups > num_beams) or (num_beams % num_beam_groups != 0):
|
| 206 |
+
raise ValueError(
|
| 207 |
+
"`num_beam_groups` has to be an integer smaller or equal than `num_beams` and `num_beams` has to be"
|
| 208 |
+
f" divisible by `num_beam_groups`, but is {num_beam_groups} with `num_beams` being {num_beams}."
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
@property
|
| 212 |
+
def is_done(self) -> bool:
|
| 213 |
+
return self._done.all()
|
| 214 |
+
|
| 215 |
+
def process(
|
| 216 |
+
self,
|
| 217 |
+
input_ids: torch.LongTensor,
|
| 218 |
+
next_scores: torch.FloatTensor,
|
| 219 |
+
next_tokens: torch.LongTensor,
|
| 220 |
+
next_indices: torch.LongTensor,
|
| 221 |
+
pad_token_id: Optional[Union[int, torch.Tensor]] = None,
|
| 222 |
+
eos_token_id: Optional[Union[int, List[int], torch.Tensor]] = None,
|
| 223 |
+
beam_indices: Optional[torch.LongTensor] = None,
|
| 224 |
+
group_index: Optional[int] = 0,
|
| 225 |
+
decoder_prompt_len: Optional[int] = 0,
|
| 226 |
+
) -> Dict[str, torch.Tensor]:
|
| 227 |
+
# add up to the length which the next_scores is calculated on (including decoder prompt)
|
| 228 |
+
cur_len = input_ids.shape[-1] + 1
|
| 229 |
+
batch_size = len(self._beam_hyps) // self.num_beam_groups
|
| 230 |
+
|
| 231 |
+
if not (batch_size == (input_ids.shape[0] // self.group_size)):
|
| 232 |
+
if self.num_beam_groups > 1:
|
| 233 |
+
raise ValueError(
|
| 234 |
+
f"A group beam size of {input_ids.shape[0]} is used as the input, but a group beam "
|
| 235 |
+
f"size of {self.group_size} is expected by the beam scorer."
|
| 236 |
+
)
|
| 237 |
+
else:
|
| 238 |
+
raise ValueError(
|
| 239 |
+
f"A beam size of {input_ids.shape[0]} is used as the input, but a beam size of "
|
| 240 |
+
f"{self.group_size} is expected by the beam scorer."
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
device = input_ids.device
|
| 244 |
+
next_beam_scores = torch.zeros((batch_size, self.group_size), dtype=next_scores.dtype, device=device)
|
| 245 |
+
next_beam_tokens = torch.zeros((batch_size, self.group_size), dtype=next_tokens.dtype, device=device)
|
| 246 |
+
next_beam_indices = torch.zeros((batch_size, self.group_size), dtype=next_indices.dtype, device=device)
|
| 247 |
+
|
| 248 |
+
if eos_token_id is not None and not isinstance(eos_token_id, torch.Tensor):
|
| 249 |
+
if isinstance(eos_token_id, int):
|
| 250 |
+
eos_token_id = [eos_token_id]
|
| 251 |
+
eos_token_id = torch.tensor(eos_token_id)
|
| 252 |
+
|
| 253 |
+
for batch_idx in range(batch_size):
|
| 254 |
+
batch_group_idx = batch_idx * self.num_beam_groups + group_index
|
| 255 |
+
if self._done[batch_group_idx]:
|
| 256 |
+
if self.num_beams < len(self._beam_hyps[batch_group_idx]):
|
| 257 |
+
raise ValueError(f"Batch can only be done if at least {self.num_beams} beams have been generated")
|
| 258 |
+
if eos_token_id is None or pad_token_id is None:
|
| 259 |
+
raise ValueError("Generated beams >= num_beams -> eos_token_id and pad_token have to be defined")
|
| 260 |
+
# pad the batch
|
| 261 |
+
next_beam_scores[batch_idx, :] = 0
|
| 262 |
+
next_beam_tokens[batch_idx, :] = pad_token_id
|
| 263 |
+
next_beam_indices[batch_idx, :] = 0
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
# next tokens for this sentence
|
| 267 |
+
beam_idx = 0
|
| 268 |
+
for beam_token_rank, (next_token, next_score, next_index) in enumerate(
|
| 269 |
+
zip(next_tokens[batch_idx], next_scores[batch_idx], next_indices[batch_idx])
|
| 270 |
+
):
|
| 271 |
+
batch_beam_idx = batch_idx * self.group_size + next_index
|
| 272 |
+
# add to generated hypotheses if end of sentence
|
| 273 |
+
if (eos_token_id is not None) and (next_token.item() in eos_token_id):
|
| 274 |
+
# if beam_token does not belong to top num_beams tokens, it should not be added
|
| 275 |
+
is_beam_token_worse_than_top_num_beams = beam_token_rank >= self.group_size
|
| 276 |
+
if is_beam_token_worse_than_top_num_beams:
|
| 277 |
+
continue
|
| 278 |
+
if beam_indices is not None:
|
| 279 |
+
beam_index = beam_indices[batch_beam_idx]
|
| 280 |
+
beam_index = beam_index + (batch_beam_idx,)
|
| 281 |
+
else:
|
| 282 |
+
beam_index = None
|
| 283 |
+
|
| 284 |
+
self._beam_hyps[batch_group_idx].add(
|
| 285 |
+
input_ids[batch_beam_idx].clone(),
|
| 286 |
+
next_score.item(),
|
| 287 |
+
beam_indices=beam_index,
|
| 288 |
+
generated_len=cur_len - decoder_prompt_len,
|
| 289 |
+
)
|
| 290 |
+
else:
|
| 291 |
+
# add next predicted token since it is not eos_token
|
| 292 |
+
next_beam_scores[batch_idx, beam_idx] = next_score
|
| 293 |
+
next_beam_tokens[batch_idx, beam_idx] = next_token
|
| 294 |
+
next_beam_indices[batch_idx, beam_idx] = batch_beam_idx
|
| 295 |
+
beam_idx += 1
|
| 296 |
+
|
| 297 |
+
# once the beam for next step is full, don't add more tokens to it.
|
| 298 |
+
if beam_idx == self.group_size:
|
| 299 |
+
break
|
| 300 |
+
|
| 301 |
+
if beam_idx < self.group_size:
|
| 302 |
+
raise ValueError(
|
| 303 |
+
f"At most {self.group_size} tokens in {next_tokens[batch_idx]} can be equal to `eos_token_id:"
|
| 304 |
+
f" {eos_token_id}`. Make sure {next_tokens[batch_idx]} are corrected."
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
# Check if we are done so that we can save a pad step if all(done)
|
| 308 |
+
self._done[batch_group_idx] = self._done[batch_group_idx] or self._beam_hyps[batch_group_idx].is_done(
|
| 309 |
+
next_scores[batch_idx].max().item(), cur_len, decoder_prompt_len
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
return UserDict(
|
| 313 |
+
{
|
| 314 |
+
"next_beam_scores": next_beam_scores.view(-1),
|
| 315 |
+
"next_beam_tokens": next_beam_tokens.view(-1),
|
| 316 |
+
"next_beam_indices": next_beam_indices.view(-1),
|
| 317 |
+
}
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
def finalize(
|
| 321 |
+
self,
|
| 322 |
+
input_ids: torch.LongTensor,
|
| 323 |
+
final_beam_scores: torch.FloatTensor,
|
| 324 |
+
final_beam_tokens: torch.LongTensor,
|
| 325 |
+
final_beam_indices: torch.LongTensor,
|
| 326 |
+
max_length: int,
|
| 327 |
+
pad_token_id: Optional[Union[int, torch.Tensor]] = None,
|
| 328 |
+
eos_token_id: Optional[Union[int, List[int], torch.Tensor]] = None,
|
| 329 |
+
beam_indices: Optional[torch.LongTensor] = None,
|
| 330 |
+
decoder_prompt_len: Optional[int] = 0,
|
| 331 |
+
) -> Tuple[torch.LongTensor]:
|
| 332 |
+
batch_size = len(self._beam_hyps) // self.num_beam_groups
|
| 333 |
+
|
| 334 |
+
if eos_token_id is not None and not isinstance(eos_token_id, torch.Tensor):
|
| 335 |
+
if isinstance(eos_token_id, int):
|
| 336 |
+
eos_token_id = [eos_token_id]
|
| 337 |
+
eos_token_id = torch.tensor(eos_token_id)
|
| 338 |
+
|
| 339 |
+
# finalize all open beam hypotheses and add to generated hypotheses
|
| 340 |
+
for batch_group_idx, beam_hyp in enumerate(self._beam_hyps):
|
| 341 |
+
if self._done[batch_group_idx]:
|
| 342 |
+
continue
|
| 343 |
+
|
| 344 |
+
# all open beam hypotheses are added to the beam hypothesis
|
| 345 |
+
# beam hypothesis class automatically keeps the best beams
|
| 346 |
+
for index_per_group in range(self.group_size):
|
| 347 |
+
batch_beam_idx = batch_group_idx * self.group_size + index_per_group
|
| 348 |
+
final_score = final_beam_scores[batch_beam_idx].item()
|
| 349 |
+
final_tokens = input_ids[batch_beam_idx]
|
| 350 |
+
beam_index = beam_indices[batch_beam_idx] if beam_indices is not None else None
|
| 351 |
+
generated_len = final_tokens.shape[-1] - decoder_prompt_len
|
| 352 |
+
beam_hyp.add(final_tokens, final_score, beam_indices=beam_index, generated_len=generated_len)
|
| 353 |
+
|
| 354 |
+
# select the best hypotheses
|
| 355 |
+
sent_lengths = input_ids.new(batch_size * self.num_beam_hyps_to_keep)
|
| 356 |
+
best = []
|
| 357 |
+
best_indices = []
|
| 358 |
+
best_scores = torch.zeros(batch_size * self.num_beam_hyps_to_keep, device=self.device, dtype=torch.float32)
|
| 359 |
+
|
| 360 |
+
# retrieve best hypotheses
|
| 361 |
+
for i in range(batch_size):
|
| 362 |
+
beam_hyps_in_batch = self._beam_hyps[i * self.num_beam_groups : (i + 1) * self.num_beam_groups]
|
| 363 |
+
candidate_beams = [beam for beam_hyp in beam_hyps_in_batch for beam in beam_hyp.beams]
|
| 364 |
+
sorted_hyps = sorted(candidate_beams, key=lambda x: x[0])
|
| 365 |
+
for j in range(self.num_beam_hyps_to_keep):
|
| 366 |
+
best_hyp_tuple = sorted_hyps.pop()
|
| 367 |
+
best_score = best_hyp_tuple[0]
|
| 368 |
+
best_hyp = best_hyp_tuple[1]
|
| 369 |
+
best_index = best_hyp_tuple[2]
|
| 370 |
+
sent_lengths[self.num_beam_hyps_to_keep * i + j] = len(best_hyp)
|
| 371 |
+
|
| 372 |
+
# append hyp to lists
|
| 373 |
+
best.append(best_hyp)
|
| 374 |
+
|
| 375 |
+
# append indices to list
|
| 376 |
+
best_indices.append(best_index)
|
| 377 |
+
|
| 378 |
+
best_scores[i * self.num_beam_hyps_to_keep + j] = best_score
|
| 379 |
+
|
| 380 |
+
# prepare for adding eos
|
| 381 |
+
sent_lengths_max = sent_lengths.max().item() + 1
|
| 382 |
+
sent_max_len = min(sent_lengths_max, max_length) if max_length is not None else sent_lengths_max
|
| 383 |
+
decoded: torch.LongTensor = input_ids.new(batch_size * self.num_beam_hyps_to_keep, sent_max_len)
|
| 384 |
+
|
| 385 |
+
if len(best_indices) > 0 and best_indices[0] is not None:
|
| 386 |
+
indices: torch.LongTensor = input_ids.new(batch_size * self.num_beam_hyps_to_keep, sent_max_len)
|
| 387 |
+
else:
|
| 388 |
+
indices = None
|
| 389 |
+
|
| 390 |
+
# shorter batches are padded if needed
|
| 391 |
+
if sent_lengths.min().item() != sent_lengths.max().item():
|
| 392 |
+
if pad_token_id is None:
|
| 393 |
+
raise ValueError("`pad_token_id` has to be defined")
|
| 394 |
+
decoded.fill_(pad_token_id)
|
| 395 |
+
|
| 396 |
+
if indices is not None:
|
| 397 |
+
indices.fill_(-1)
|
| 398 |
+
|
| 399 |
+
# fill with hypotheses and eos_token_id if the latter fits in
|
| 400 |
+
for i, (hypo, best_idx) in enumerate(zip(best, best_indices)):
|
| 401 |
+
decoded[i, : sent_lengths[i]] = hypo
|
| 402 |
+
|
| 403 |
+
if indices is not None:
|
| 404 |
+
indices[i, : len(best_idx)] = torch.tensor(best_idx)
|
| 405 |
+
|
| 406 |
+
if sent_lengths[i] < sent_max_len:
|
| 407 |
+
# inserting only the first eos_token_id
|
| 408 |
+
decoded[i, sent_lengths[i]] = eos_token_id[0]
|
| 409 |
+
|
| 410 |
+
return UserDict(
|
| 411 |
+
{
|
| 412 |
+
"sequences": decoded,
|
| 413 |
+
"sequence_scores": best_scores,
|
| 414 |
+
"beam_indices": indices,
|
| 415 |
+
}
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
class ConstrainedBeamSearchScorer(BeamScorer):
|
| 420 |
+
r"""
|
| 421 |
+
[`BeamScorer`] implementing constrained beam search decoding.
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
Args:
|
| 425 |
+
batch_size (`int`):
|
| 426 |
+
Batch Size of `input_ids` for which standard beam search decoding is run in parallel.
|
| 427 |
+
num_beams (`int`):
|
| 428 |
+
Number of beams for beam search.
|
| 429 |
+
constraints (`List[Constraint]`):
|
| 430 |
+
A list of positive constraints represented as `Constraint` objects that must be fulfilled in the generation
|
| 431 |
+
output. For more information, the documentation of [`Constraint`] should be read.
|
| 432 |
+
device (`torch.device`):
|
| 433 |
+
Defines the device type (*e.g.*, `"cpu"` or `"cuda"`) on which this instance of `BeamSearchScorer` will be
|
| 434 |
+
allocated.
|
| 435 |
+
length_penalty (`float`, *optional*, defaults to 1.0):
|
| 436 |
+
Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
|
| 437 |
+
the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log
|
| 438 |
+
likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while
|
| 439 |
+
`length_penalty` < 0.0 encourages shorter sequences.
|
| 440 |
+
do_early_stopping (`bool` or `str`, *optional*, defaults to `False`):
|
| 441 |
+
Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
|
| 442 |
+
`True`, where the generation stops as soon as there are `num_beams` complete candidates; `False`, where an
|
| 443 |
+
heuristic is applied and the generation stops when is it very unlikely to find better candidates;
|
| 444 |
+
`"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical
|
| 445 |
+
beam search algorithm).
|
| 446 |
+
num_beam_hyps_to_keep (`int`, *optional*, defaults to 1):
|
| 447 |
+
The number of beam hypotheses that shall be returned upon calling
|
| 448 |
+
[`~transformers.BeamSearchScorer.finalize`].
|
| 449 |
+
num_beam_groups (`int`, *optional*, defaults to 1):
|
| 450 |
+
Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
|
| 451 |
+
See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
|
| 452 |
+
max_length (`int`, *optional*):
|
| 453 |
+
The maximum length of the sequence to be generated.
|
| 454 |
+
"""
|
| 455 |
+
|
| 456 |
+
def __init__(
|
| 457 |
+
self,
|
| 458 |
+
batch_size: int,
|
| 459 |
+
num_beams: int,
|
| 460 |
+
constraints: List[Constraint],
|
| 461 |
+
device: torch.device,
|
| 462 |
+
length_penalty: Optional[float] = 1.0,
|
| 463 |
+
do_early_stopping: Optional[Union[bool, str]] = False,
|
| 464 |
+
num_beam_hyps_to_keep: Optional[int] = 1,
|
| 465 |
+
num_beam_groups: Optional[int] = 1,
|
| 466 |
+
max_length: Optional[int] = None,
|
| 467 |
+
):
|
| 468 |
+
self.num_beams = num_beams
|
| 469 |
+
self.device = device
|
| 470 |
+
self.length_penalty = length_penalty
|
| 471 |
+
self.do_early_stopping = do_early_stopping
|
| 472 |
+
self.num_beam_hyps_to_keep = num_beam_hyps_to_keep
|
| 473 |
+
self.num_beam_groups = num_beam_groups
|
| 474 |
+
self.group_size = self.num_beams // self.num_beam_groups
|
| 475 |
+
self.constraints = constraints
|
| 476 |
+
|
| 477 |
+
self._is_init = False
|
| 478 |
+
self._beam_hyps = [
|
| 479 |
+
BeamHypotheses(
|
| 480 |
+
num_beams=self.num_beams,
|
| 481 |
+
length_penalty=self.length_penalty,
|
| 482 |
+
early_stopping=self.do_early_stopping,
|
| 483 |
+
max_length=max_length,
|
| 484 |
+
)
|
| 485 |
+
for _ in range(batch_size)
|
| 486 |
+
]
|
| 487 |
+
self._done = torch.tensor([False for _ in range(batch_size)], dtype=torch.bool, device=self.device)
|
| 488 |
+
|
| 489 |
+
if not isinstance(num_beams, int) or num_beams <= 1:
|
| 490 |
+
raise ValueError(
|
| 491 |
+
f"`num_beams` has to be an integer strictly greater than 1, but is {num_beams}. For `num_beams` == 1,"
|
| 492 |
+
" one should make use of `greedy_search` instead."
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
if not isinstance(num_beam_groups, int) or (num_beam_groups > num_beams) or (num_beams % num_beam_groups != 0):
|
| 496 |
+
raise ValueError(
|
| 497 |
+
"`num_beam_groups` has to be an integer smaller or equal than `num_beams` and `num_beams` has to be"
|
| 498 |
+
f" divisible by `num_beam_groups`, but is {num_beam_groups} with `num_beams` being {num_beams}."
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
@property
|
| 502 |
+
def is_done(self) -> bool:
|
| 503 |
+
return self._done.all()
|
| 504 |
+
|
| 505 |
+
def make_constraint_states(self, n):
|
| 506 |
+
return [ConstraintListState([constraint.copy() for constraint in self.constraints]) for _ in range(n)]
|
| 507 |
+
|
| 508 |
+
def check_completes_constraints(self, sequence):
|
| 509 |
+
new_state = self.make_constraint_states(1)[0]
|
| 510 |
+
new_state.reset(sequence)
|
| 511 |
+
return new_state.completed
|
| 512 |
+
|
| 513 |
+
def process(
|
| 514 |
+
self,
|
| 515 |
+
input_ids: torch.LongTensor,
|
| 516 |
+
next_scores: torch.FloatTensor,
|
| 517 |
+
next_tokens: torch.LongTensor,
|
| 518 |
+
next_indices: torch.LongTensor,
|
| 519 |
+
scores_for_all_vocab: torch.FloatTensor,
|
| 520 |
+
pad_token_id: Optional[Union[int, torch.Tensor]] = None,
|
| 521 |
+
eos_token_id: Optional[Union[int, List[int], torch.Tensor]] = None,
|
| 522 |
+
beam_indices: Optional[torch.LongTensor] = None,
|
| 523 |
+
decoder_prompt_len: Optional[int] = 0,
|
| 524 |
+
) -> Tuple[torch.Tensor]:
|
| 525 |
+
r"""
|
| 526 |
+
Args:
|
| 527 |
+
input_ids (`torch.LongTensor` of shape `(batch_size * num_beams, sequence_length)`):
|
| 528 |
+
Indices of input sequence tokens in the vocabulary.
|
| 529 |
+
|
| 530 |
+
Indices can be obtained using any class inheriting from [`PreTrainedTokenizer`]. See
|
| 531 |
+
[`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
|
| 532 |
+
|
| 533 |
+
[What are input IDs?](../glossary#input-ids)
|
| 534 |
+
next_scores (`torch.FloatTensor` of shape `(batch_size, 2 * num_beams)`):
|
| 535 |
+
Current scores of the top `2 * num_beams` non-finished beam hypotheses.
|
| 536 |
+
next_tokens (`torch.LongTensor` of shape `(batch_size, 2 * num_beams)`):
|
| 537 |
+
`input_ids` of the tokens corresponding to the top `2 * num_beams` non-finished beam hypotheses.
|
| 538 |
+
next_indices (`torch.LongTensor` of shape `(batch_size, 2 * num_beams)`):
|
| 539 |
+
Beam indices indicating to which beam hypothesis the `next_tokens` correspond.
|
| 540 |
+
scores_for_all_vocab (`torch.FloatTensor` of shape `(batch_size * num_beams, sequence_length)`):
|
| 541 |
+
The scores of all tokens in the vocabulary for each of the beam hypotheses.
|
| 542 |
+
pad_token_id (`int`, *optional*):
|
| 543 |
+
The id of the *padding* token.
|
| 544 |
+
eos_token_id (`Union[int, List[int]]`, *optional*):
|
| 545 |
+
The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
|
| 546 |
+
beam_indices (`torch.LongTensor`, *optional*):
|
| 547 |
+
Beam indices indicating to which beam hypothesis each token correspond.
|
| 548 |
+
decoder_prompt_len (`int`, *optional*):
|
| 549 |
+
The length of prompt that is included in the input to decoder.
|
| 550 |
+
Return:
|
| 551 |
+
`UserDict`: A dictionary composed of the fields as defined above:
|
| 552 |
+
|
| 553 |
+
- **next_beam_scores** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Updated scores of
|
| 554 |
+
all
|
| 555 |
+
non-finished beams.
|
| 556 |
+
|
| 557 |
+
- **next_beam_tokens** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Next tokens to be
|
| 558 |
+
added
|
| 559 |
+
to the non-finished beam_hypotheses.
|
| 560 |
+
- **next_beam_indices** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Beam indices
|
| 561 |
+
indicating to which beam the next tokens shall be added.
|
| 562 |
+
"""
|
| 563 |
+
|
| 564 |
+
# add up to the length which the next_scores is calculated on (including decoder prompt)
|
| 565 |
+
cur_len = input_ids.shape[-1] + 1
|
| 566 |
+
batch_size = len(self._beam_hyps)
|
| 567 |
+
if not (batch_size == (input_ids.shape[0] // self.group_size)):
|
| 568 |
+
if self.num_beam_groups > 1:
|
| 569 |
+
raise ValueError(
|
| 570 |
+
f"A group beam size of {input_ids.shape[0]} is used as the input, but a group beam "
|
| 571 |
+
f"size of {self.group_size} is expected by the beam scorer."
|
| 572 |
+
)
|
| 573 |
+
else:
|
| 574 |
+
raise ValueError(
|
| 575 |
+
f"A beam size of {input_ids.shape[0]} is used as the input, but a beam size of "
|
| 576 |
+
f"{self.group_size} is expected by the beam scorer."
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
device = input_ids.device
|
| 580 |
+
|
| 581 |
+
next_beam_scores = torch.zeros((batch_size, self.group_size), dtype=next_scores.dtype, device=device)
|
| 582 |
+
next_beam_tokens = torch.zeros((batch_size, self.group_size), dtype=next_tokens.dtype, device=device)
|
| 583 |
+
next_beam_indices = torch.zeros((batch_size, self.group_size), dtype=next_indices.dtype, device=device)
|
| 584 |
+
|
| 585 |
+
if eos_token_id is not None and not isinstance(eos_token_id, torch.Tensor):
|
| 586 |
+
if isinstance(eos_token_id, int):
|
| 587 |
+
eos_token_id = [eos_token_id]
|
| 588 |
+
eos_token_id = torch.tensor(eos_token_id)
|
| 589 |
+
|
| 590 |
+
for batch_idx, beam_hyp in enumerate(self._beam_hyps):
|
| 591 |
+
if self._done[batch_idx]:
|
| 592 |
+
if self.num_beams < len(beam_hyp):
|
| 593 |
+
raise ValueError(f"Batch can only be done if at least {self.num_beams} beams have been generated")
|
| 594 |
+
if eos_token_id is None or pad_token_id is None:
|
| 595 |
+
raise ValueError("Generated beams >= num_beams -> eos_token_id and pad_token have to be defined")
|
| 596 |
+
# pad the batch
|
| 597 |
+
next_beam_scores[batch_idx, :] = 0
|
| 598 |
+
next_beam_tokens[batch_idx, :] = pad_token_id
|
| 599 |
+
next_beam_indices[batch_idx, :] = 0
|
| 600 |
+
continue
|
| 601 |
+
|
| 602 |
+
# next tokens for this sentence.
|
| 603 |
+
beam_idx = 0
|
| 604 |
+
for beam_token_rank, (next_token, next_score, next_index) in enumerate(
|
| 605 |
+
zip(next_tokens[batch_idx], next_scores[batch_idx], next_indices[batch_idx])
|
| 606 |
+
):
|
| 607 |
+
batch_beam_idx = batch_idx * self.group_size + next_index
|
| 608 |
+
# add to generated hypotheses if end of sentence
|
| 609 |
+
if (eos_token_id is not None) and (next_token.item() in eos_token_id):
|
| 610 |
+
# if beam_token does not belong to top num_beams tokens, it should not be added
|
| 611 |
+
is_beam_token_worse_than_top_num_beams = beam_token_rank >= self.group_size
|
| 612 |
+
if is_beam_token_worse_than_top_num_beams:
|
| 613 |
+
continue
|
| 614 |
+
|
| 615 |
+
completes_constraint = self.check_completes_constraints(input_ids[batch_beam_idx].tolist())
|
| 616 |
+
if completes_constraint:
|
| 617 |
+
if beam_indices is not None:
|
| 618 |
+
beam_index = beam_indices[batch_beam_idx]
|
| 619 |
+
beam_index = beam_index + (batch_beam_idx,)
|
| 620 |
+
else:
|
| 621 |
+
beam_index = None
|
| 622 |
+
|
| 623 |
+
beam_hyp.add(
|
| 624 |
+
input_ids[batch_beam_idx].clone(),
|
| 625 |
+
next_score.item(),
|
| 626 |
+
beam_indices=beam_index,
|
| 627 |
+
generated_len=cur_len - decoder_prompt_len,
|
| 628 |
+
)
|
| 629 |
+
else:
|
| 630 |
+
# add next predicted token since it is not eos_token
|
| 631 |
+
next_beam_scores[batch_idx, beam_idx] = next_score
|
| 632 |
+
next_beam_tokens[batch_idx, beam_idx] = next_token
|
| 633 |
+
next_beam_indices[batch_idx, beam_idx] = batch_beam_idx
|
| 634 |
+
beam_idx += 1
|
| 635 |
+
|
| 636 |
+
# once the beam for next step is full, don't add more tokens to it.
|
| 637 |
+
if beam_idx == self.group_size:
|
| 638 |
+
break
|
| 639 |
+
|
| 640 |
+
new_scores, new_tokens, new_indices = self.step_sentence_constraint(
|
| 641 |
+
batch_idx,
|
| 642 |
+
input_ids,
|
| 643 |
+
scores_for_all_vocab,
|
| 644 |
+
next_beam_scores[batch_idx],
|
| 645 |
+
next_beam_tokens[batch_idx],
|
| 646 |
+
next_beam_indices[batch_idx],
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
next_beam_scores[batch_idx] = new_scores
|
| 650 |
+
next_beam_tokens[batch_idx] = new_tokens
|
| 651 |
+
next_beam_indices[batch_idx] = new_indices
|
| 652 |
+
|
| 653 |
+
if beam_idx < self.group_size:
|
| 654 |
+
raise ValueError(
|
| 655 |
+
f"At most {self.group_size} tokens in {next_tokens[batch_idx]} can be equal to `eos_token_id:"
|
| 656 |
+
f" {eos_token_id}`. Make sure {next_tokens[batch_idx]} are corrected."
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
# Check if we are done so that we can save a pad step if all(done)
|
| 660 |
+
self._done[batch_idx] = self._done[batch_idx] or beam_hyp.is_done(
|
| 661 |
+
next_scores[batch_idx].max().item(), cur_len, decoder_prompt_len
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
return UserDict(
|
| 665 |
+
{
|
| 666 |
+
"next_beam_scores": next_beam_scores.view(-1),
|
| 667 |
+
"next_beam_tokens": next_beam_tokens.view(-1),
|
| 668 |
+
"next_beam_indices": next_beam_indices.view(-1),
|
| 669 |
+
}
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
def step_sentence_constraint(
|
| 673 |
+
self,
|
| 674 |
+
batch_idx: int,
|
| 675 |
+
input_ids: torch.LongTensor,
|
| 676 |
+
vocab_scores: torch.FloatTensor,
|
| 677 |
+
sent_beam_scores: torch.FloatTensor,
|
| 678 |
+
sent_beam_tokens: torch.LongTensor,
|
| 679 |
+
sent_beam_indices: torch.LongTensor,
|
| 680 |
+
push_progress: bool = False,
|
| 681 |
+
):
|
| 682 |
+
# sent_beam_tokens are the next {num_beams} number of tokens that are under consideration for this beam
|
| 683 |
+
# (candidate next tokens)
|
| 684 |
+
|
| 685 |
+
# 1. Adding "advance_tokens"
|
| 686 |
+
# using ConstraintStateList.advance(), we propose new tokens to be added into this "candidate list" that will
|
| 687 |
+
# advance us in fulfilling the constraints.
|
| 688 |
+
|
| 689 |
+
# 2. Selecting best candidates such that we end up with highest probable candidates
|
| 690 |
+
# that fulfill our constraints.
|
| 691 |
+
|
| 692 |
+
orig_len = sent_beam_indices.size(0)
|
| 693 |
+
device = sent_beam_indices.device
|
| 694 |
+
|
| 695 |
+
# initialize states
|
| 696 |
+
topk_contraint_states = self.make_constraint_states(orig_len)
|
| 697 |
+
advance_constraint_states = self.make_constraint_states(orig_len)
|
| 698 |
+
|
| 699 |
+
sidx, eidx = batch_idx * orig_len, (batch_idx + 1) * orig_len
|
| 700 |
+
this_batch_input_ids = input_ids[sidx:eidx]
|
| 701 |
+
this_batch_token_scores = vocab_scores[sidx:eidx]
|
| 702 |
+
full_hypotheses = torch.cat((input_ids[sent_beam_indices], sent_beam_tokens.unsqueeze(-1)), dim=-1)
|
| 703 |
+
|
| 704 |
+
# need to make new hypothesis that advance the constraints
|
| 705 |
+
track_new = {
|
| 706 |
+
"new_seqs": full_hypotheses.tolist(),
|
| 707 |
+
"new_states": [],
|
| 708 |
+
"new_indices": [],
|
| 709 |
+
"new_tokens": [],
|
| 710 |
+
"new_scores": [],
|
| 711 |
+
}
|
| 712 |
+
for seq_idx, pre_seq in enumerate(this_batch_input_ids):
|
| 713 |
+
# pre_seq = ith sequence generated before this step.
|
| 714 |
+
|
| 715 |
+
# input_ids -> (topk) generic beam search best model next tokens
|
| 716 |
+
# -> (advance) constraints forcing the next token
|
| 717 |
+
# either way, we need to sort them into "banks" later, so store a "ConstraintListState" for all types of
|
| 718 |
+
# hypotheses.
|
| 719 |
+
|
| 720 |
+
topk_state = topk_contraint_states[seq_idx]
|
| 721 |
+
topk_state.reset(full_hypotheses[seq_idx].tolist())
|
| 722 |
+
|
| 723 |
+
advance_state = advance_constraint_states[seq_idx]
|
| 724 |
+
advance_state.reset(pre_seq.tolist())
|
| 725 |
+
|
| 726 |
+
if not advance_state.completed:
|
| 727 |
+
advance_tokens = torch.tensor(advance_state.advance(), dtype=torch.long, device=device)
|
| 728 |
+
for advance_token in advance_tokens:
|
| 729 |
+
# since adding each `advance_token` leads to a different hypothesis, create new state instance.
|
| 730 |
+
new_state = advance_state.copy(stateful=True)
|
| 731 |
+
new_state.add(advance_token.tolist())
|
| 732 |
+
|
| 733 |
+
advance_seq = torch.cat((pre_seq, advance_token.unsqueeze(0)), -1).tolist()
|
| 734 |
+
if advance_seq not in track_new["new_seqs"]:
|
| 735 |
+
# prevent duplicates, which are basically bound to happen in this process.
|
| 736 |
+
track_new["new_seqs"].append(advance_seq)
|
| 737 |
+
track_new["new_indices"].append(sidx + seq_idx) # idx -> global idx across all the batches
|
| 738 |
+
track_new["new_tokens"].append(advance_token)
|
| 739 |
+
track_new["new_scores"].append(this_batch_token_scores[seq_idx].take(advance_token))
|
| 740 |
+
track_new["new_states"].append(new_state)
|
| 741 |
+
elif push_progress:
|
| 742 |
+
# Basically, `sent_beam_indices` often chooses very little among `input_ids` the generated sequences that
|
| 743 |
+
# actually fulfill our constraints. For example, let constraints == ["loves pies"] and
|
| 744 |
+
|
| 745 |
+
# pre_seq_1 = "The child loves pies and" pre_seq_2 = "The child plays in the playground and"
|
| 746 |
+
|
| 747 |
+
# Without this step, if `sent_beam_indices` is something like [1,1], then
|
| 748 |
+
# 1. `pre_seq_1` won't be added to the list of (topk) hypothesis since it's not in the indices and
|
| 749 |
+
# 2. it won't be added to the list of (advance) hypothesis since it's completed already. (this is
|
| 750 |
+
# the else part of `if constraints_completed[seq_idx]`)
|
| 751 |
+
# 3. it ends up simply getting removed from consideration.
|
| 752 |
+
|
| 753 |
+
# #3 might be fine and actually desired, since it's likely that it's a low-probability output anyways,
|
| 754 |
+
# especially if it's not in the list of `sent_beam_indices`. But this often leads to lengthened beam
|
| 755 |
+
# search times, since completed sequences keep getting removed after all this effort for constrained
|
| 756 |
+
# generation.
|
| 757 |
+
|
| 758 |
+
# Here, we basically take `pre_seq_1` and to "push" it into the considered list of hypotheses, by simply
|
| 759 |
+
# appending the next likely token in the vocabulary and adding it to the list of hypotheses.
|
| 760 |
+
|
| 761 |
+
new_score, new_token = torch.max(this_batch_token_scores[seq_idx], 0) # some next probable token
|
| 762 |
+
advance_seq = torch.cat((pre_seq, new_token.unsqueeze(0)), -1)
|
| 763 |
+
|
| 764 |
+
advance_state = advance_constraint_states[seq_idx]
|
| 765 |
+
|
| 766 |
+
advance_seq = advance_seq.tolist()
|
| 767 |
+
|
| 768 |
+
advance_state.reset(advance_seq)
|
| 769 |
+
if advance_seq not in track_new["new_seqs"]:
|
| 770 |
+
# but still don't want to have duplicates
|
| 771 |
+
track_new["new_seqs"].append(advance_seq)
|
| 772 |
+
track_new["new_indices"].append(seq_idx)
|
| 773 |
+
track_new["new_tokens"].append(new_token)
|
| 774 |
+
track_new["new_scores"].append(new_score)
|
| 775 |
+
track_new["new_states"].append(advance_state)
|
| 776 |
+
|
| 777 |
+
if len(track_new["new_indices"]) > 0:
|
| 778 |
+
new_indices = torch.tensor(track_new["new_indices"], device=device)
|
| 779 |
+
new_tokens = torch.stack(track_new["new_tokens"]).to(device)
|
| 780 |
+
new_scores = torch.stack(track_new["new_scores"]).to(device)
|
| 781 |
+
|
| 782 |
+
all_states = topk_contraint_states + track_new["new_states"]
|
| 783 |
+
all_tokens = torch.cat((sent_beam_tokens, new_tokens), -1)
|
| 784 |
+
all_scores = torch.cat((sent_beam_scores, new_scores), -1)
|
| 785 |
+
all_banks = torch.tensor([one.get_bank() for one in all_states], device=device)
|
| 786 |
+
|
| 787 |
+
zipped = all_banks * 100 + all_scores
|
| 788 |
+
indices = zipped.sort(descending=True).indices
|
| 789 |
+
sorted_banks = all_banks[indices]
|
| 790 |
+
|
| 791 |
+
# Then we end up with {sorted among bank C}, {sorted among bank C-1}, ..., {sorted among bank 0}
|
| 792 |
+
|
| 793 |
+
counter = -1
|
| 794 |
+
cur_bank = sorted_banks[0]
|
| 795 |
+
increments = []
|
| 796 |
+
for bank in sorted_banks:
|
| 797 |
+
if bank == cur_bank:
|
| 798 |
+
counter += 1
|
| 799 |
+
else:
|
| 800 |
+
counter = 0
|
| 801 |
+
cur_bank = bank
|
| 802 |
+
increments.append(counter)
|
| 803 |
+
rearrangers = torch.tensor(np.argsort(increments, kind="mergesort"))
|
| 804 |
+
|
| 805 |
+
indices = indices[rearrangers][:orig_len]
|
| 806 |
+
|
| 807 |
+
sent_beam_scores = all_scores[indices]
|
| 808 |
+
sent_beam_tokens = all_tokens[indices]
|
| 809 |
+
sent_beam_indices = torch.cat((sent_beam_indices, new_indices))[indices]
|
| 810 |
+
|
| 811 |
+
return sent_beam_scores, sent_beam_tokens, sent_beam_indices
|
| 812 |
+
|
| 813 |
+
def finalize(
|
| 814 |
+
self,
|
| 815 |
+
input_ids: torch.LongTensor,
|
| 816 |
+
final_beam_scores: torch.FloatTensor,
|
| 817 |
+
final_beam_tokens: torch.LongTensor,
|
| 818 |
+
final_beam_indices: torch.LongTensor,
|
| 819 |
+
max_length: int,
|
| 820 |
+
pad_token_id: Optional[Union[int, torch.Tensor]] = None,
|
| 821 |
+
eos_token_id: Optional[Union[int, List[int], torch.Tensor]] = None,
|
| 822 |
+
beam_indices: Optional[torch.LongTensor] = None,
|
| 823 |
+
decoder_prompt_len: Optional[int] = 0,
|
| 824 |
+
) -> Tuple[torch.LongTensor]:
|
| 825 |
+
batch_size = len(self._beam_hyps)
|
| 826 |
+
|
| 827 |
+
if eos_token_id is not None and not isinstance(eos_token_id, torch.Tensor):
|
| 828 |
+
if isinstance(eos_token_id, int):
|
| 829 |
+
eos_token_id = [eos_token_id]
|
| 830 |
+
eos_token_id = torch.tensor(eos_token_id)
|
| 831 |
+
|
| 832 |
+
# finalize all open beam hypotheses and add to generated hypotheses
|
| 833 |
+
for batch_idx, beam_hyp in enumerate(self._beam_hyps):
|
| 834 |
+
if self._done[batch_idx]:
|
| 835 |
+
continue
|
| 836 |
+
|
| 837 |
+
# all open beam hypotheses are added to the beam hypothesis
|
| 838 |
+
# beam hypothesis class automatically keeps the best beams
|
| 839 |
+
|
| 840 |
+
ids_collect = []
|
| 841 |
+
for beam_id in range(self.num_beams):
|
| 842 |
+
batch_beam_idx = batch_idx * self.num_beams + beam_id
|
| 843 |
+
final_score = final_beam_scores[batch_beam_idx].item()
|
| 844 |
+
final_tokens = input_ids[batch_beam_idx]
|
| 845 |
+
|
| 846 |
+
completes_constraint = self.check_completes_constraints(final_tokens.tolist())
|
| 847 |
+
if completes_constraint:
|
| 848 |
+
beam_index = beam_indices[batch_beam_idx] if beam_indices is not None else None
|
| 849 |
+
generated_len = final_tokens.shape[-1] - decoder_prompt_len
|
| 850 |
+
beam_hyp.add(final_tokens, final_score, beam_indices=beam_index, generated_len=generated_len)
|
| 851 |
+
ids_collect.append(beam_id)
|
| 852 |
+
|
| 853 |
+
# due to overly complex constraints or other factors, sometimes we can't gaurantee a successful
|
| 854 |
+
# generation. In these cases we simply return the highest scoring outputs.
|
| 855 |
+
if len(ids_collect) < self.num_beam_hyps_to_keep:
|
| 856 |
+
for beam_id in range(self.num_beams):
|
| 857 |
+
if beam_id not in ids_collect:
|
| 858 |
+
batch_beam_idx = batch_idx * self.num_beams + beam_id
|
| 859 |
+
final_score = final_beam_scores[batch_beam_idx].item()
|
| 860 |
+
final_tokens = input_ids[batch_beam_idx]
|
| 861 |
+
generated_len = final_tokens.shape[-1] - decoder_prompt_len
|
| 862 |
+
beam_hyp.add(final_tokens, final_score, generated_len=generated_len)
|
| 863 |
+
if len(ids_collect) >= self.num_beam_hyps_to_keep:
|
| 864 |
+
break
|
| 865 |
+
|
| 866 |
+
# select the best hypotheses
|
| 867 |
+
sent_lengths = input_ids.new(batch_size * self.num_beam_hyps_to_keep)
|
| 868 |
+
best = []
|
| 869 |
+
best_indices = []
|
| 870 |
+
best_scores = torch.zeros(batch_size * self.num_beam_hyps_to_keep, device=self.device, dtype=torch.float32)
|
| 871 |
+
|
| 872 |
+
# retrieve best hypotheses
|
| 873 |
+
for i, beam_hyp in enumerate(self._beam_hyps):
|
| 874 |
+
sorted_hyps = sorted(beam_hyp.beams, key=lambda x: x[0])
|
| 875 |
+
for j in range(self.num_beam_hyps_to_keep):
|
| 876 |
+
best_hyp_tuple = sorted_hyps.pop()
|
| 877 |
+
best_score = best_hyp_tuple[0]
|
| 878 |
+
best_hyp = best_hyp_tuple[1]
|
| 879 |
+
best_index = best_hyp_tuple[2]
|
| 880 |
+
sent_lengths[self.num_beam_hyps_to_keep * i + j] = len(best_hyp)
|
| 881 |
+
|
| 882 |
+
# append to lists
|
| 883 |
+
best.append(best_hyp)
|
| 884 |
+
|
| 885 |
+
# append indices to list
|
| 886 |
+
best_indices.append(best_index)
|
| 887 |
+
|
| 888 |
+
best_scores[i * self.num_beam_hyps_to_keep + j] = best_score
|
| 889 |
+
|
| 890 |
+
# prepare for adding eos
|
| 891 |
+
sent_lengths_max = sent_lengths.max().item() + 1
|
| 892 |
+
|
| 893 |
+
sent_max_len = min(sent_lengths_max, max_length) if max_length is not None else sent_lengths_max
|
| 894 |
+
decoded: torch.LongTensor = input_ids.new(batch_size * self.num_beam_hyps_to_keep, sent_max_len)
|
| 895 |
+
|
| 896 |
+
if len(best_indices) > 0 and best_indices[0] is not None:
|
| 897 |
+
indices: torch.LongTensor = input_ids.new(batch_size * self.num_beam_hyps_to_keep, sent_max_len)
|
| 898 |
+
else:
|
| 899 |
+
indices = None
|
| 900 |
+
|
| 901 |
+
# shorter batches are padded if needed
|
| 902 |
+
if sent_lengths.min().item() != sent_lengths.max().item():
|
| 903 |
+
if pad_token_id is None:
|
| 904 |
+
raise ValueError("`pad_token_id` has to be defined")
|
| 905 |
+
decoded.fill_(pad_token_id)
|
| 906 |
+
|
| 907 |
+
if indices is not None:
|
| 908 |
+
indices.fill_(-1)
|
| 909 |
+
|
| 910 |
+
# fill with hypotheses and eos_token_id if the latter fits in
|
| 911 |
+
for i, (hypo, best_idx) in enumerate(zip(best, best_indices)):
|
| 912 |
+
decoded[i, : sent_lengths[i]] = hypo
|
| 913 |
+
|
| 914 |
+
if indices is not None:
|
| 915 |
+
indices[i, : len(best_idx)] = torch.tensor(best_idx)
|
| 916 |
+
|
| 917 |
+
if sent_lengths[i] < sent_max_len:
|
| 918 |
+
# inserting only the first eos_token_id
|
| 919 |
+
decoded[i, sent_lengths[i]] = eos_token_id[0]
|
| 920 |
+
|
| 921 |
+
return UserDict(
|
| 922 |
+
{
|
| 923 |
+
"sequences": decoded,
|
| 924 |
+
"sequence_scores": best_scores,
|
| 925 |
+
"beam_indices": indices,
|
| 926 |
+
}
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
class BeamHypotheses:
|
| 931 |
+
def __init__(self, num_beams: int, length_penalty: float, early_stopping: bool, max_length: Optional[int] = None):
|
| 932 |
+
"""
|
| 933 |
+
Initialize n-best list of hypotheses.
|
| 934 |
+
"""
|
| 935 |
+
self.length_penalty = length_penalty
|
| 936 |
+
self.early_stopping = early_stopping
|
| 937 |
+
self.max_length = max_length
|
| 938 |
+
self.num_beams = num_beams
|
| 939 |
+
self.beams = []
|
| 940 |
+
self.worst_score = 1e9
|
| 941 |
+
|
| 942 |
+
if not isinstance(self.early_stopping, bool) and self.max_length is None:
|
| 943 |
+
raise ValueError(
|
| 944 |
+
"When `do_early_stopping` is set to a string, `max_length` must be defined. Ensure it is passed to the"
|
| 945 |
+
" BeamScorer class instance at initialization time."
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
def __len__(self):
|
| 949 |
+
"""
|
| 950 |
+
Number of hypotheses in the list.
|
| 951 |
+
"""
|
| 952 |
+
return len(self.beams)
|
| 953 |
+
|
| 954 |
+
def add(
|
| 955 |
+
self,
|
| 956 |
+
hyp: torch.LongTensor,
|
| 957 |
+
sum_logprobs: float,
|
| 958 |
+
beam_indices: Optional[torch.LongTensor] = None,
|
| 959 |
+
generated_len: Optional[int] = None,
|
| 960 |
+
):
|
| 961 |
+
"""
|
| 962 |
+
Add a new hypothesis to the list.
|
| 963 |
+
"""
|
| 964 |
+
if generated_len is not None:
|
| 965 |
+
score = sum_logprobs / (generated_len**self.length_penalty)
|
| 966 |
+
# This 'else' case exists for retrocompatibility
|
| 967 |
+
else:
|
| 968 |
+
score = sum_logprobs / (hyp.shape[-1] ** self.length_penalty)
|
| 969 |
+
|
| 970 |
+
if len(self) < self.num_beams or score > self.worst_score:
|
| 971 |
+
self.beams.append((score, hyp, beam_indices))
|
| 972 |
+
if len(self) > self.num_beams:
|
| 973 |
+
sorted_next_scores = sorted([(s, idx) for idx, (s, _, _) in enumerate(self.beams)])
|
| 974 |
+
del self.beams[sorted_next_scores[0][1]]
|
| 975 |
+
self.worst_score = sorted_next_scores[1][0]
|
| 976 |
+
else:
|
| 977 |
+
self.worst_score = min(score, self.worst_score)
|
| 978 |
+
|
| 979 |
+
def is_done(self, best_sum_logprobs: float, cur_len: int, decoder_prompt_len: Optional[int] = 0) -> bool:
|
| 980 |
+
"""
|
| 981 |
+
If there are enough hypotheses and that none of the hypotheses being generated can become better than the worst
|
| 982 |
+
one in the heap, then we are done with this sentence.
|
| 983 |
+
"""
|
| 984 |
+
|
| 985 |
+
if len(self) < self.num_beams:
|
| 986 |
+
return False
|
| 987 |
+
|
| 988 |
+
# `True`: stop as soon as at least `num_beams` hypotheses are finished
|
| 989 |
+
if self.early_stopping is True:
|
| 990 |
+
return True
|
| 991 |
+
# `False`: heuristic -- compute best possible score from `cur_len`, even though it is not entirely accurate
|
| 992 |
+
# when `length_penalty` is positive. See the discussion below for more details.
|
| 993 |
+
# https://github.com/huggingface/transformers/pull/20901#issuecomment-1369845565
|
| 994 |
+
elif self.early_stopping is False:
|
| 995 |
+
highest_attainable_score = best_sum_logprobs / (cur_len - decoder_prompt_len) ** self.length_penalty
|
| 996 |
+
ret = self.worst_score >= highest_attainable_score
|
| 997 |
+
return ret
|
| 998 |
+
# `"never"`: compute the best possible score, depending on the signal of `length_penalty`
|
| 999 |
+
else:
|
| 1000 |
+
# `length_penalty` > 0.0 -> max denominator is obtaned from `max_length`, not from `cur_len` -> min
|
| 1001 |
+
# abs(`highest_attainable_score`) is obtained -> `highest_attainable_score` is negative, hence we obtain
|
| 1002 |
+
# its max this way
|
| 1003 |
+
if self.length_penalty > 0.0:
|
| 1004 |
+
if self.max_length <= decoder_prompt_len:
|
| 1005 |
+
raise ValueError("max_length is not larger than decoder prompt length")
|
| 1006 |
+
highest_attainable_score = (
|
| 1007 |
+
best_sum_logprobs / (self.max_length - decoder_prompt_len) ** self.length_penalty
|
| 1008 |
+
)
|
| 1009 |
+
# the opposite logic applies here (max `highest_attainable_score` from `cur_len`)
|
| 1010 |
+
else:
|
| 1011 |
+
highest_attainable_score = best_sum_logprobs / (cur_len - decoder_prompt_len) ** self.length_penalty
|
| 1012 |
+
ret = self.worst_score >= highest_attainable_score
|
| 1013 |
+
return ret
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/bitnet.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ..utils import is_accelerate_available, is_torch_available, logging
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
if is_accelerate_available():
|
| 5 |
+
from accelerate import init_empty_weights
|
| 6 |
+
|
| 7 |
+
if is_torch_available():
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
logger = logging.get_logger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# the weights are ternary so can be represented with 2 bits, and they are packed in uint8 tensors, hence the number of values per item is 4
|
| 16 |
+
VALUES_PER_ITEM = 4
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def pack_weights(quantized_weights: torch.Tensor) -> torch.Tensor:
|
| 20 |
+
"""
|
| 21 |
+
Packs a tensor of quantized weights into a compact format using 2 bits per value.
|
| 22 |
+
|
| 23 |
+
Parameters:
|
| 24 |
+
-----------
|
| 25 |
+
quantized_weights : torch.Tensor
|
| 26 |
+
A tensor containing ternary quantized weights with values in {-1, 0, 1}. These values are adjusted to
|
| 27 |
+
{0, 1, 2} before being packed.
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
--------
|
| 31 |
+
torch.Tensor
|
| 32 |
+
A packed tensor where each element stores 4 quantized values (each using 2 bits) in an 8-bit format.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
original_shape = quantized_weights.shape
|
| 36 |
+
|
| 37 |
+
row_dim = (original_shape[0] + VALUES_PER_ITEM - 1) // VALUES_PER_ITEM
|
| 38 |
+
|
| 39 |
+
if len(original_shape) == 1:
|
| 40 |
+
packed_tensor_shape = (row_dim,)
|
| 41 |
+
else:
|
| 42 |
+
packed_tensor_shape = (row_dim, *original_shape[1:])
|
| 43 |
+
|
| 44 |
+
quantized_weights += 1
|
| 45 |
+
packed = torch.zeros(packed_tensor_shape, device=quantized_weights.device, dtype=torch.uint8)
|
| 46 |
+
unpacked = quantized_weights.to(torch.uint8)
|
| 47 |
+
|
| 48 |
+
it = min(VALUES_PER_ITEM, (original_shape[0] // row_dim) + 1)
|
| 49 |
+
for i in range(it):
|
| 50 |
+
start = i * row_dim
|
| 51 |
+
end = min(start + row_dim, original_shape[0])
|
| 52 |
+
packed[: (end - start)] |= unpacked[start:end] << 2 * i
|
| 53 |
+
|
| 54 |
+
return packed
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@torch.compile
|
| 58 |
+
def unpack_weights(packed: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
|
| 59 |
+
"""
|
| 60 |
+
Unpacks a tensor of quantized weights that were stored in a packed format using 2 bits per value.
|
| 61 |
+
|
| 62 |
+
Parameters:
|
| 63 |
+
-----------
|
| 64 |
+
packed : torch.Tensor
|
| 65 |
+
A tensor containing packed weights where each element represents 4 quantized values (using 2 bits per value).
|
| 66 |
+
dtype : torch.dtype
|
| 67 |
+
The dtype of the returned Tensor
|
| 68 |
+
Returns:
|
| 69 |
+
--------
|
| 70 |
+
torch.Tensor
|
| 71 |
+
A tensor of unpacked weights, where each value is converted from its packed 2-bit representation.
|
| 72 |
+
|
| 73 |
+
Example:
|
| 74 |
+
--------
|
| 75 |
+
packed = torch.tensor([[0b10100001, 0b00011000],
|
| 76 |
+
[0b10010000, 0b00001010]], dtype=torch.uint8)
|
| 77 |
+
|
| 78 |
+
# Unpack the values
|
| 79 |
+
unpacked = unpack_weights(packed)
|
| 80 |
+
|
| 81 |
+
# Resulting unpacked tensor
|
| 82 |
+
print(unpacked)
|
| 83 |
+
# Output: tensor([[ 0, -1],
|
| 84 |
+
[-1, 1],
|
| 85 |
+
[-1, 1],
|
| 86 |
+
[-1, 1],
|
| 87 |
+
[ 1, 0],
|
| 88 |
+
[ 0, -1],
|
| 89 |
+
[ 1, -1],
|
| 90 |
+
[ 1, -1]])
|
| 91 |
+
|
| 92 |
+
Explanation of the example:
|
| 93 |
+
---------------------------
|
| 94 |
+
Let's take the first value for example 0b10100001, we we will only focus on the first column,
|
| 95 |
+
because every element is unpacked across the first dimension
|
| 96 |
+
- First 2 bits: `01` → 0 at [0][0]
|
| 97 |
+
- Second 2 bits: `00` → -1 at [0][2]
|
| 98 |
+
- Third 2 bits: `10` → 1 at [0][4]
|
| 99 |
+
- Fourth 2 bits: `10` → 1 at [0][6]
|
| 100 |
+
the second value of the same row (0b10010000) will give the values for [0][1], [0][3], [0][5], [0][7]
|
| 101 |
+
|
| 102 |
+
We subtract 1 because during the packing process, it's easier to work with values like 0, 1, and 2. To make this possible,
|
| 103 |
+
we add 1 to the original ternary weights (which are typically -1, 0, and 1) when packing them. When unpacking, we reverse
|
| 104 |
+
this by subtracting 1 to restore the original ternary values.
|
| 105 |
+
"""
|
| 106 |
+
packed_shape = packed.shape
|
| 107 |
+
|
| 108 |
+
if len(packed_shape) == 1:
|
| 109 |
+
original_row_dim = packed_shape[0] * VALUES_PER_ITEM
|
| 110 |
+
unpacked_shape = (original_row_dim,)
|
| 111 |
+
else:
|
| 112 |
+
original_row_dim = packed_shape[0] * VALUES_PER_ITEM
|
| 113 |
+
unpacked_shape = (original_row_dim, *packed_shape[1:])
|
| 114 |
+
|
| 115 |
+
unpacked = torch.zeros(unpacked_shape, device=packed.device, dtype=torch.uint8)
|
| 116 |
+
|
| 117 |
+
for i in range(VALUES_PER_ITEM):
|
| 118 |
+
start = i * packed_shape[0]
|
| 119 |
+
end = start + packed_shape[0]
|
| 120 |
+
mask = 3 << (2 * i)
|
| 121 |
+
unpacked[start:end] = (packed & mask) >> (2 * i)
|
| 122 |
+
|
| 123 |
+
return unpacked.to(dtype) - 1
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class BitLinear(nn.Module):
|
| 127 |
+
def __init__(self, in_features: int, out_features: int, bias: bool, device=None, dtype=None):
|
| 128 |
+
super().__init__()
|
| 129 |
+
self.dtype = dtype
|
| 130 |
+
self.in_features = in_features
|
| 131 |
+
self.out_features = out_features
|
| 132 |
+
self.register_buffer(
|
| 133 |
+
"weight",
|
| 134 |
+
torch.zeros(
|
| 135 |
+
(out_features // VALUES_PER_ITEM, in_features),
|
| 136 |
+
dtype=torch.uint8,
|
| 137 |
+
device=device,
|
| 138 |
+
),
|
| 139 |
+
)
|
| 140 |
+
self.register_buffer(
|
| 141 |
+
"weight_scale",
|
| 142 |
+
torch.ones(
|
| 143 |
+
(1),
|
| 144 |
+
dtype=dtype,
|
| 145 |
+
device=device,
|
| 146 |
+
),
|
| 147 |
+
)
|
| 148 |
+
if bias:
|
| 149 |
+
self.register_buffer("bias", torch.zeros((out_features), dtype=dtype, device=device))
|
| 150 |
+
else:
|
| 151 |
+
self.bias = None
|
| 152 |
+
|
| 153 |
+
@torch.compile
|
| 154 |
+
def activation_quant(self, input, num_bits=8):
|
| 155 |
+
"""
|
| 156 |
+
Activation function : Performs symmetric, per-token quantization on the input activations.
|
| 157 |
+
Parameters:
|
| 158 |
+
-----------
|
| 159 |
+
x : torch.Tensor
|
| 160 |
+
Input activations to be quantized.
|
| 161 |
+
num_bits : int, optional (default=8)
|
| 162 |
+
Number of bits to use for quantization, determining the quantization range.
|
| 163 |
+
|
| 164 |
+
Returns:
|
| 165 |
+
--------
|
| 166 |
+
result : torch.Tensor
|
| 167 |
+
Quantized activation tensor, with values mapped to an `int8` range.
|
| 168 |
+
scale : torch.Tensor
|
| 169 |
+
The per-channel scaling factors used to quantize the tensor.
|
| 170 |
+
"""
|
| 171 |
+
Qn = -(2 ** (num_bits - 1))
|
| 172 |
+
Qp = 2 ** (num_bits - 1) - 1
|
| 173 |
+
scale = Qp / input.abs().max(dim=-1, keepdim=True).values.clamp(min=1e-5)
|
| 174 |
+
result = (input * scale).round().clamp(Qn, Qp)
|
| 175 |
+
return result.to(torch.int8), scale
|
| 176 |
+
|
| 177 |
+
@torch.compile
|
| 178 |
+
def post_quant_process(self, input, input_scale, weight_scale):
|
| 179 |
+
out = input / (input_scale * weight_scale)
|
| 180 |
+
return out
|
| 181 |
+
|
| 182 |
+
def forward(self, input):
|
| 183 |
+
w = self.weight
|
| 184 |
+
w_quant = unpack_weights(w, dtype=self.dtype)
|
| 185 |
+
input_quant, input_scale = self.activation_quant(input)
|
| 186 |
+
y = F.linear(input_quant.to(self.dtype), w_quant)
|
| 187 |
+
y = self.post_quant_process(y, self.weight_scale, input_scale)
|
| 188 |
+
if self.bias is not None:
|
| 189 |
+
y += self.bias.view(1, -1).expand_as(y)
|
| 190 |
+
return y
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _replace_with_bitnet_linear(
|
| 194 |
+
model,
|
| 195 |
+
modules_to_not_convert=None,
|
| 196 |
+
current_key_name=None,
|
| 197 |
+
quantization_config=None,
|
| 198 |
+
has_been_replaced=False,
|
| 199 |
+
pre_quantized=False,
|
| 200 |
+
):
|
| 201 |
+
"""
|
| 202 |
+
Private method that wraps the recursion for module replacement.
|
| 203 |
+
|
| 204 |
+
Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
if current_key_name is None:
|
| 208 |
+
current_key_name = []
|
| 209 |
+
|
| 210 |
+
for name, module in model.named_children():
|
| 211 |
+
if current_key_name is None:
|
| 212 |
+
current_key_name = []
|
| 213 |
+
current_key_name.append(name)
|
| 214 |
+
|
| 215 |
+
# Check if the current key is not in the `modules_to_not_convert`
|
| 216 |
+
if not any(key in ".".join(current_key_name) for key in modules_to_not_convert):
|
| 217 |
+
with init_empty_weights():
|
| 218 |
+
if isinstance(module, nn.Linear) and name not in modules_to_not_convert:
|
| 219 |
+
in_features = module.in_features
|
| 220 |
+
out_features = module.out_features
|
| 221 |
+
model._modules[name] = BitLinear(
|
| 222 |
+
in_features=in_features,
|
| 223 |
+
out_features=out_features,
|
| 224 |
+
bias=module.bias is not None,
|
| 225 |
+
device=module.weight.device,
|
| 226 |
+
dtype=module.weight.dtype,
|
| 227 |
+
)
|
| 228 |
+
has_been_replaced = True
|
| 229 |
+
model._modules[name].requires_grad_(False)
|
| 230 |
+
|
| 231 |
+
if len(list(module.children())) > 0:
|
| 232 |
+
_, has_been_replaced = _replace_with_bitnet_linear(
|
| 233 |
+
module,
|
| 234 |
+
modules_to_not_convert=modules_to_not_convert,
|
| 235 |
+
current_key_name=current_key_name,
|
| 236 |
+
quantization_config=quantization_config,
|
| 237 |
+
has_been_replaced=has_been_replaced,
|
| 238 |
+
)
|
| 239 |
+
# Remove the last key for recursion
|
| 240 |
+
current_key_name.pop(-1)
|
| 241 |
+
return model, has_been_replaced
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def replace_with_bitnet_linear(
|
| 245 |
+
model,
|
| 246 |
+
modules_to_not_convert=None,
|
| 247 |
+
current_key_name=None,
|
| 248 |
+
quantization_config=None,
|
| 249 |
+
pre_quantized=False,
|
| 250 |
+
):
|
| 251 |
+
"""
|
| 252 |
+
A helper function to replace all `torch.nn.Linear` modules by `BitLinear158` modules`.
|
| 253 |
+
|
| 254 |
+
The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
|
| 255 |
+
be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
|
| 256 |
+
CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
|
| 257 |
+
|
| 258 |
+
Parameters:
|
| 259 |
+
model (`torch.nn.Module`):
|
| 260 |
+
Input model or `torch.nn.Module` as the function is run recursively.
|
| 261 |
+
modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
|
| 262 |
+
Names of the modules to not convert in `EetqLinear`. In practice we keep the `lm_head` in full precision
|
| 263 |
+
for numerical stability reasons.
|
| 264 |
+
current_key_name (`List[`str`]`, *optional*):
|
| 265 |
+
An array to track the current key of the recursion. This is used to check whether the current key (part of
|
| 266 |
+
it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
|
| 267 |
+
`disk`).
|
| 268 |
+
"""
|
| 269 |
+
modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
|
| 270 |
+
if quantization_config and quantization_config.modules_to_not_convert is not None:
|
| 271 |
+
modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
|
| 272 |
+
modules_to_not_convert = list(set(modules_to_not_convert))
|
| 273 |
+
model, has_been_replaced = _replace_with_bitnet_linear(
|
| 274 |
+
model,
|
| 275 |
+
modules_to_not_convert,
|
| 276 |
+
current_key_name,
|
| 277 |
+
quantization_config,
|
| 278 |
+
pre_quantized=pre_quantized,
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
if not has_been_replaced:
|
| 282 |
+
logger.warning(
|
| 283 |
+
"You are loading your model using bitnet but no linear modules were found in your model."
|
| 284 |
+
" Please double check your model architecture, or submit an issue on github if you think this is"
|
| 285 |
+
" a bug."
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
return model
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/bitsandbytes.py
ADDED
|
@@ -0,0 +1,561 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.metadata
|
| 2 |
+
import inspect
|
| 3 |
+
import warnings
|
| 4 |
+
from copy import deepcopy
|
| 5 |
+
from inspect import signature
|
| 6 |
+
|
| 7 |
+
from packaging import version
|
| 8 |
+
|
| 9 |
+
from ..utils import (
|
| 10 |
+
get_available_devices,
|
| 11 |
+
is_accelerate_available,
|
| 12 |
+
is_bitsandbytes_available,
|
| 13 |
+
is_bitsandbytes_multi_backend_available,
|
| 14 |
+
is_ipex_available,
|
| 15 |
+
is_torch_available,
|
| 16 |
+
logging,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if is_bitsandbytes_available():
|
| 21 |
+
import bitsandbytes as bnb
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn as nn
|
| 24 |
+
|
| 25 |
+
from ..pytorch_utils import Conv1D
|
| 26 |
+
|
| 27 |
+
if is_accelerate_available():
|
| 28 |
+
import accelerate
|
| 29 |
+
from accelerate import init_empty_weights
|
| 30 |
+
from accelerate.hooks import add_hook_to_module, remove_hook_from_module
|
| 31 |
+
from accelerate.utils import find_tied_parameters
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def set_module_quantized_tensor_to_device(module, tensor_name, device, value=None, quantized_stats=None):
|
| 37 |
+
"""
|
| 38 |
+
A helper function to set a given tensor (parameter of buffer) of a module on a specific device (note that doing
|
| 39 |
+
`param.to(device)` creates a new tensor not linked to the parameter, which is why we need this function). The
|
| 40 |
+
function is adapted from `set_module_tensor_to_device` function from accelerate that is adapted to support the
|
| 41 |
+
class `Int8Params` from `bitsandbytes`.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
module (`torch.nn.Module`):
|
| 45 |
+
The module in which the tensor we want to move lives.
|
| 46 |
+
tensor_name (`str`):
|
| 47 |
+
The full name of the parameter/buffer.
|
| 48 |
+
device (`int`, `str` or `torch.device`):
|
| 49 |
+
The device on which to set the tensor.
|
| 50 |
+
value (`torch.Tensor`, *optional*):
|
| 51 |
+
The value of the tensor (useful when going from the meta device to any other device).
|
| 52 |
+
quantized_stats (`dict[str, Any]`, *optional*):
|
| 53 |
+
Dict with items for either 4-bit or 8-bit serialization
|
| 54 |
+
"""
|
| 55 |
+
# Recurse if needed
|
| 56 |
+
if "." in tensor_name:
|
| 57 |
+
splits = tensor_name.split(".")
|
| 58 |
+
for split in splits[:-1]:
|
| 59 |
+
new_module = getattr(module, split)
|
| 60 |
+
if new_module is None:
|
| 61 |
+
raise ValueError(f"{module} has no attribute {split}.")
|
| 62 |
+
module = new_module
|
| 63 |
+
tensor_name = splits[-1]
|
| 64 |
+
|
| 65 |
+
if tensor_name not in module._parameters and tensor_name not in module._buffers:
|
| 66 |
+
raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
|
| 67 |
+
is_buffer = tensor_name in module._buffers
|
| 68 |
+
old_value = getattr(module, tensor_name)
|
| 69 |
+
|
| 70 |
+
if old_value.device == torch.device("meta") and device not in ["meta", torch.device("meta")] and value is None:
|
| 71 |
+
raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {device}.")
|
| 72 |
+
|
| 73 |
+
prequantized_loading = quantized_stats is not None
|
| 74 |
+
if is_buffer or not is_bitsandbytes_available():
|
| 75 |
+
is_8bit = False
|
| 76 |
+
is_4bit = False
|
| 77 |
+
else:
|
| 78 |
+
is_4bit = hasattr(bnb.nn, "Params4bit") and isinstance(module._parameters[tensor_name], bnb.nn.Params4bit)
|
| 79 |
+
is_8bit = isinstance(module._parameters[tensor_name], bnb.nn.Int8Params)
|
| 80 |
+
|
| 81 |
+
if is_8bit or is_4bit:
|
| 82 |
+
param = module._parameters[tensor_name]
|
| 83 |
+
if param.device.type != "cuda":
|
| 84 |
+
if value is None:
|
| 85 |
+
new_value = old_value.to(device)
|
| 86 |
+
elif isinstance(value, torch.Tensor):
|
| 87 |
+
new_value = value.to("cpu")
|
| 88 |
+
else:
|
| 89 |
+
new_value = torch.tensor(value, device="cpu")
|
| 90 |
+
|
| 91 |
+
# Support models using `Conv1D` in place of `nn.Linear` (e.g. openai-community/gpt2) by transposing the weight matrix prior to quantization.
|
| 92 |
+
# Since weights are saved in the correct "orientation", we skip transposing when loading.
|
| 93 |
+
if issubclass(module.source_cls, Conv1D) and not prequantized_loading:
|
| 94 |
+
new_value = new_value.T
|
| 95 |
+
|
| 96 |
+
kwargs = old_value.__dict__
|
| 97 |
+
|
| 98 |
+
if prequantized_loading != (new_value.dtype in (torch.int8, torch.uint8)):
|
| 99 |
+
raise ValueError(
|
| 100 |
+
f"Value dtype `{new_value.dtype}` is not compatible with parameter quantization status."
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
if is_8bit:
|
| 104 |
+
is_8bit_serializable = version.parse(importlib.metadata.version("bitsandbytes")) > version.parse(
|
| 105 |
+
"0.37.2"
|
| 106 |
+
)
|
| 107 |
+
if new_value.dtype in (torch.int8, torch.uint8) and not is_8bit_serializable:
|
| 108 |
+
raise ValueError(
|
| 109 |
+
"Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. "
|
| 110 |
+
"Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
|
| 111 |
+
)
|
| 112 |
+
new_value = bnb.nn.Int8Params(new_value, requires_grad=False, **kwargs).to(device)
|
| 113 |
+
if prequantized_loading:
|
| 114 |
+
setattr(new_value, "SCB", quantized_stats["SCB"].to(device))
|
| 115 |
+
elif is_4bit:
|
| 116 |
+
if prequantized_loading:
|
| 117 |
+
is_4bit_serializable = version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse(
|
| 118 |
+
"0.41.3"
|
| 119 |
+
)
|
| 120 |
+
if new_value.dtype in (torch.int8, torch.uint8) and not is_4bit_serializable:
|
| 121 |
+
raise ValueError(
|
| 122 |
+
"Detected 4-bit weights but the version of bitsandbytes is not compatible with 4-bit serialization. "
|
| 123 |
+
"Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
|
| 124 |
+
)
|
| 125 |
+
new_value = bnb.nn.Params4bit.from_prequantized(
|
| 126 |
+
data=new_value,
|
| 127 |
+
quantized_stats=quantized_stats,
|
| 128 |
+
requires_grad=False,
|
| 129 |
+
device=device,
|
| 130 |
+
**kwargs,
|
| 131 |
+
)
|
| 132 |
+
else:
|
| 133 |
+
new_value = bnb.nn.Params4bit(new_value, requires_grad=False, **kwargs).to(device)
|
| 134 |
+
module._parameters[tensor_name] = new_value
|
| 135 |
+
|
| 136 |
+
else:
|
| 137 |
+
if value is None:
|
| 138 |
+
new_value = old_value.to(device)
|
| 139 |
+
elif isinstance(value, torch.Tensor):
|
| 140 |
+
new_value = value.to(device)
|
| 141 |
+
else:
|
| 142 |
+
new_value = torch.tensor(value, device=device)
|
| 143 |
+
|
| 144 |
+
if is_buffer:
|
| 145 |
+
module._buffers[tensor_name] = new_value
|
| 146 |
+
else:
|
| 147 |
+
new_value = nn.Parameter(new_value, requires_grad=old_value.requires_grad)
|
| 148 |
+
module._parameters[tensor_name] = new_value
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _replace_with_bnb_linear(
|
| 152 |
+
model,
|
| 153 |
+
modules_to_not_convert=None,
|
| 154 |
+
current_key_name=None,
|
| 155 |
+
quantization_config=None,
|
| 156 |
+
has_been_replaced=False,
|
| 157 |
+
):
|
| 158 |
+
"""
|
| 159 |
+
Private method that wraps the recursion for module replacement.
|
| 160 |
+
|
| 161 |
+
Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
|
| 162 |
+
"""
|
| 163 |
+
for name, module in model.named_children():
|
| 164 |
+
if current_key_name is None:
|
| 165 |
+
current_key_name = []
|
| 166 |
+
current_key_name.append(name)
|
| 167 |
+
|
| 168 |
+
if (isinstance(module, nn.Linear) or isinstance(module, Conv1D)) and name not in modules_to_not_convert:
|
| 169 |
+
# Check if the current key is not in the `modules_to_not_convert`
|
| 170 |
+
current_key_name_str = ".".join(current_key_name)
|
| 171 |
+
if not any(
|
| 172 |
+
(key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
|
| 173 |
+
):
|
| 174 |
+
with init_empty_weights():
|
| 175 |
+
if isinstance(module, Conv1D):
|
| 176 |
+
in_features, out_features = module.weight.shape
|
| 177 |
+
else:
|
| 178 |
+
in_features = module.in_features
|
| 179 |
+
out_features = module.out_features
|
| 180 |
+
|
| 181 |
+
if quantization_config.quantization_method() == "llm_int8":
|
| 182 |
+
model._modules[name] = bnb.nn.Linear8bitLt(
|
| 183 |
+
in_features,
|
| 184 |
+
out_features,
|
| 185 |
+
module.bias is not None,
|
| 186 |
+
has_fp16_weights=quantization_config.llm_int8_has_fp16_weight,
|
| 187 |
+
threshold=quantization_config.llm_int8_threshold,
|
| 188 |
+
)
|
| 189 |
+
has_been_replaced = True
|
| 190 |
+
else:
|
| 191 |
+
if (
|
| 192 |
+
quantization_config.llm_int8_skip_modules is not None
|
| 193 |
+
and name in quantization_config.llm_int8_skip_modules
|
| 194 |
+
):
|
| 195 |
+
pass
|
| 196 |
+
else:
|
| 197 |
+
extra_kwargs = (
|
| 198 |
+
{"quant_storage": quantization_config.bnb_4bit_quant_storage}
|
| 199 |
+
if "quant_storage" in list(signature(bnb.nn.Linear4bit).parameters)
|
| 200 |
+
else {}
|
| 201 |
+
)
|
| 202 |
+
model._modules[name] = bnb.nn.Linear4bit(
|
| 203 |
+
in_features,
|
| 204 |
+
out_features,
|
| 205 |
+
module.bias is not None,
|
| 206 |
+
quantization_config.bnb_4bit_compute_dtype,
|
| 207 |
+
compress_statistics=quantization_config.bnb_4bit_use_double_quant,
|
| 208 |
+
quant_type=quantization_config.bnb_4bit_quant_type,
|
| 209 |
+
**extra_kwargs,
|
| 210 |
+
)
|
| 211 |
+
has_been_replaced = True
|
| 212 |
+
# Store the module class in case we need to transpose the weight later
|
| 213 |
+
model._modules[name].source_cls = type(module)
|
| 214 |
+
# Force requires grad to False to avoid unexpected errors
|
| 215 |
+
model._modules[name].requires_grad_(False)
|
| 216 |
+
if len(list(module.children())) > 0:
|
| 217 |
+
_, has_been_replaced = _replace_with_bnb_linear(
|
| 218 |
+
module,
|
| 219 |
+
modules_to_not_convert,
|
| 220 |
+
current_key_name,
|
| 221 |
+
quantization_config,
|
| 222 |
+
has_been_replaced=has_been_replaced,
|
| 223 |
+
)
|
| 224 |
+
# Remove the last key for recursion
|
| 225 |
+
current_key_name.pop(-1)
|
| 226 |
+
return model, has_been_replaced
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def replace_with_bnb_linear(model, modules_to_not_convert=None, current_key_name=None, quantization_config=None):
|
| 230 |
+
"""
|
| 231 |
+
A helper function to replace all `torch.nn.Linear` modules by `bnb.nn.Linear8bit` modules from the `bitsandbytes`
|
| 232 |
+
library. This will enable running your models using mixed int8 precision as described by the paper `LLM.int8():
|
| 233 |
+
8-bit Matrix Multiplication for Transformers at Scale`. Make sure `bitsandbytes` compiled with the correct CUDA
|
| 234 |
+
version of your hardware is installed before running this function. `pip install -i https://test.pypi.org/simple/
|
| 235 |
+
bitsandbytes`
|
| 236 |
+
|
| 237 |
+
The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
|
| 238 |
+
be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
|
| 239 |
+
CPU/GPU memory is required to run this function. Int8 mixed-precision matrix decomposition works by separating a
|
| 240 |
+
matrix multiplication into two streams: (1) and systematic feature outlier stream matrix multiplied in fp16
|
| 241 |
+
(0.01%), (2) a regular stream of int8 matrix multiplication (99.9%). With this method, int8 inference with no
|
| 242 |
+
predictive degradation is possible for very large models (>=176B parameters).
|
| 243 |
+
|
| 244 |
+
Parameters:
|
| 245 |
+
model (`torch.nn.Module`):
|
| 246 |
+
Input model or `torch.nn.Module` as the function is run recursively.
|
| 247 |
+
modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
|
| 248 |
+
Names of the modules to not convert in `Linear8bitLt`. In practice we keep the `lm_head` in full precision
|
| 249 |
+
for numerical stability reasons.
|
| 250 |
+
current_key_name (`List[`str`]`, *optional*):
|
| 251 |
+
An array to track the current key of the recursion. This is used to check whether the current key (part of
|
| 252 |
+
it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
|
| 253 |
+
`disk`).
|
| 254 |
+
quantization_config ('transformers.utils.quantization_config.BitsAndBytesConfig'):
|
| 255 |
+
To configure and manage settings related to quantization, a technique used to compress neural network models
|
| 256 |
+
by reducing the precision of the weights and activations, thus making models more efficient in terms of both
|
| 257 |
+
storage and computation.
|
| 258 |
+
"""
|
| 259 |
+
modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
|
| 260 |
+
model, has_been_replaced = _replace_with_bnb_linear(
|
| 261 |
+
model, modules_to_not_convert, current_key_name, quantization_config
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
if not has_been_replaced:
|
| 265 |
+
logger.warning(
|
| 266 |
+
"You are loading your model in 8bit or 4bit but no linear modules were found in your model."
|
| 267 |
+
" Please double check your model architecture, or submit an issue on github if you think this is"
|
| 268 |
+
" a bug."
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
return model
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
# For backward compatibility
|
| 275 |
+
def replace_8bit_linear(*args, **kwargs):
|
| 276 |
+
warnings.warn(
|
| 277 |
+
"`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead",
|
| 278 |
+
FutureWarning,
|
| 279 |
+
)
|
| 280 |
+
return replace_with_bnb_linear(*args, **kwargs)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
# For backward compatiblity
|
| 284 |
+
def set_module_8bit_tensor_to_device(*args, **kwargs):
|
| 285 |
+
warnings.warn(
|
| 286 |
+
"`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead",
|
| 287 |
+
FutureWarning,
|
| 288 |
+
)
|
| 289 |
+
return set_module_quantized_tensor_to_device(*args, **kwargs)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def get_keys_to_not_convert(model):
|
| 293 |
+
r"""
|
| 294 |
+
An utility function to get the key of the module to keep in full precision if any For example for CausalLM modules
|
| 295 |
+
we may want to keep the lm_head in full precision for numerical stability reasons. For other architectures, we want
|
| 296 |
+
to keep the tied weights of the model. The function will return a list of the keys of the modules to not convert in
|
| 297 |
+
int8.
|
| 298 |
+
|
| 299 |
+
Parameters:
|
| 300 |
+
model (`torch.nn.Module`):
|
| 301 |
+
Input model
|
| 302 |
+
"""
|
| 303 |
+
# Create a copy of the model and tie the weights, then
|
| 304 |
+
# check if it contains tied weights
|
| 305 |
+
tied_model = deepcopy(model) # this has 0 cost since it is done inside `init_empty_weights` context manager`
|
| 306 |
+
tied_model.tie_weights()
|
| 307 |
+
|
| 308 |
+
tied_params = find_tied_parameters(tied_model)
|
| 309 |
+
# For compatibility with Accelerate < 0.18
|
| 310 |
+
if isinstance(tied_params, dict):
|
| 311 |
+
tied_keys = sum(list(tied_params.values()), []) + list(tied_params.keys())
|
| 312 |
+
else:
|
| 313 |
+
tied_keys = sum(tied_params, [])
|
| 314 |
+
has_tied_params = len(tied_keys) > 0
|
| 315 |
+
|
| 316 |
+
# If there is not tied weights, we want to keep the lm_head(output_embedding) in full precision
|
| 317 |
+
if not has_tied_params:
|
| 318 |
+
output_emb = model.get_output_embeddings()
|
| 319 |
+
if output_emb is not None:
|
| 320 |
+
list_last_module = [name for name, module in model.named_modules() if id(module) == id(output_emb)]
|
| 321 |
+
return list_last_module
|
| 322 |
+
|
| 323 |
+
# otherwise, no tied weights, no output embedding defined, simply keep the last module in full precision
|
| 324 |
+
list_modules = list(model.named_parameters())
|
| 325 |
+
list_last_module = [list_modules[-1][0]]
|
| 326 |
+
# add last module together with tied weights
|
| 327 |
+
intersection = set(list_last_module) - set(tied_keys)
|
| 328 |
+
list_untouched = list(set(tied_keys)) + list(intersection)
|
| 329 |
+
|
| 330 |
+
# remove ".weight" from the keys
|
| 331 |
+
names_to_remove = [".weight", ".bias"]
|
| 332 |
+
filtered_module_names = []
|
| 333 |
+
for name in list_untouched:
|
| 334 |
+
for name_to_remove in names_to_remove:
|
| 335 |
+
if name_to_remove in name:
|
| 336 |
+
name = name.replace(name_to_remove, "")
|
| 337 |
+
filtered_module_names.append(name)
|
| 338 |
+
|
| 339 |
+
return filtered_module_names
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# Copied from PEFT: https://github.com/huggingface/peft/blob/47b3712898539569c02ec5b3ed4a6c36811331a1/src/peft/utils/integrations.py#L41
|
| 343 |
+
def dequantize_bnb_weight(weight: "torch.nn.Parameter", dtype: "torch.dtype", state=None):
|
| 344 |
+
"""
|
| 345 |
+
Helper function to dequantize 4bit or 8bit bnb weights.
|
| 346 |
+
|
| 347 |
+
If the weight is not a bnb quantized weight, it will be returned as is.
|
| 348 |
+
"""
|
| 349 |
+
if not isinstance(weight, torch.nn.Parameter):
|
| 350 |
+
raise TypeError(f"Input weight should be of type nn.Parameter, got {type(weight)} instead")
|
| 351 |
+
|
| 352 |
+
cls_name = weight.__class__.__name__
|
| 353 |
+
if cls_name not in ("Params4bit", "Int8Params"):
|
| 354 |
+
return weight
|
| 355 |
+
|
| 356 |
+
if cls_name == "Params4bit":
|
| 357 |
+
output_tensor = bnb.functional.dequantize_4bit(weight.data, weight.quant_state)
|
| 358 |
+
logger.warning_once(
|
| 359 |
+
f"The model is going to be dequantized in {output_tensor.dtype} - if you want to upcast it to another dtype, make sure to pass the desired dtype when quantizing the model through `bnb_4bit_quant_type` argument of `BitsAndBytesConfig`"
|
| 360 |
+
)
|
| 361 |
+
return output_tensor.to(dtype)
|
| 362 |
+
|
| 363 |
+
if state.SCB is None:
|
| 364 |
+
state.SCB = weight.SCB
|
| 365 |
+
|
| 366 |
+
if hasattr(bnb.functional, "int8_vectorwise_dequant"):
|
| 367 |
+
# Use bitsandbytes API if available (requires v0.45.0+)
|
| 368 |
+
dequantized = bnb.functional.int8_vectorwise_dequant(weight.data, state.SCB)
|
| 369 |
+
else:
|
| 370 |
+
# Multiply by (scale/127) to dequantize.
|
| 371 |
+
dequantized = weight.data * state.SCB.view(-1, 1) * 7.874015718698502e-3
|
| 372 |
+
|
| 373 |
+
return dequantized.to(dtype)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def _create_accelerate_new_hook(old_hook):
|
| 377 |
+
r"""
|
| 378 |
+
Creates a new hook based on the old hook. Use it only if you know what you are doing !
|
| 379 |
+
This method is a copy of: https://github.com/huggingface/peft/blob/748f7968f3a31ec06a1c2b0328993319ad9a150a/src/peft/utils/other.py#L245
|
| 380 |
+
with some changes
|
| 381 |
+
"""
|
| 382 |
+
old_hook_cls = getattr(accelerate.hooks, old_hook.__class__.__name__)
|
| 383 |
+
old_hook_attr = old_hook.__dict__
|
| 384 |
+
filtered_old_hook_attr = {}
|
| 385 |
+
old_hook_init_signature = inspect.signature(old_hook_cls.__init__)
|
| 386 |
+
for k in old_hook_attr.keys():
|
| 387 |
+
if k in old_hook_init_signature.parameters:
|
| 388 |
+
filtered_old_hook_attr[k] = old_hook_attr[k]
|
| 389 |
+
new_hook = old_hook_cls(**filtered_old_hook_attr)
|
| 390 |
+
return new_hook
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def _dequantize_and_replace(
|
| 394 |
+
model,
|
| 395 |
+
dtype,
|
| 396 |
+
modules_to_not_convert=None,
|
| 397 |
+
current_key_name=None,
|
| 398 |
+
quantization_config=None,
|
| 399 |
+
has_been_replaced=False,
|
| 400 |
+
):
|
| 401 |
+
"""
|
| 402 |
+
Converts a quantized model into its dequantized original version. The newly converted model will have
|
| 403 |
+
some performance drop compared to the original model before quantization - use it only for specific usecases
|
| 404 |
+
such as QLoRA adapters merging.
|
| 405 |
+
|
| 406 |
+
Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
|
| 407 |
+
"""
|
| 408 |
+
quant_method = quantization_config.quantization_method()
|
| 409 |
+
|
| 410 |
+
target_cls = bnb.nn.Linear8bitLt if quant_method == "llm_int8" else bnb.nn.Linear4bit
|
| 411 |
+
|
| 412 |
+
for name, module in model.named_children():
|
| 413 |
+
if current_key_name is None:
|
| 414 |
+
current_key_name = []
|
| 415 |
+
current_key_name.append(name)
|
| 416 |
+
|
| 417 |
+
if isinstance(module, target_cls) and name not in modules_to_not_convert:
|
| 418 |
+
# Check if the current key is not in the `modules_to_not_convert`
|
| 419 |
+
current_key_name_str = ".".join(current_key_name)
|
| 420 |
+
|
| 421 |
+
if not any(
|
| 422 |
+
(key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
|
| 423 |
+
):
|
| 424 |
+
bias = getattr(module, "bias", None)
|
| 425 |
+
|
| 426 |
+
device = module.weight.device
|
| 427 |
+
with init_empty_weights():
|
| 428 |
+
new_module = torch.nn.Linear(module.in_features, module.out_features, bias=bias is not None)
|
| 429 |
+
|
| 430 |
+
if quant_method == "llm_int8":
|
| 431 |
+
state = module.state
|
| 432 |
+
else:
|
| 433 |
+
state = None
|
| 434 |
+
|
| 435 |
+
new_module.weight = torch.nn.Parameter(dequantize_bnb_weight(module.weight, dtype, state))
|
| 436 |
+
|
| 437 |
+
if bias is not None:
|
| 438 |
+
new_module.bias = bias
|
| 439 |
+
|
| 440 |
+
# Create a new hook and attach it in case we use accelerate
|
| 441 |
+
if hasattr(module, "_hf_hook"):
|
| 442 |
+
old_hook = module._hf_hook
|
| 443 |
+
new_hook = _create_accelerate_new_hook(old_hook)
|
| 444 |
+
|
| 445 |
+
remove_hook_from_module(module)
|
| 446 |
+
add_hook_to_module(new_module, new_hook)
|
| 447 |
+
|
| 448 |
+
new_module.to(device)
|
| 449 |
+
model._modules[name] = new_module
|
| 450 |
+
has_been_replaced = True
|
| 451 |
+
if len(list(module.children())) > 0:
|
| 452 |
+
_, has_been_replaced = _dequantize_and_replace(
|
| 453 |
+
module,
|
| 454 |
+
dtype,
|
| 455 |
+
modules_to_not_convert,
|
| 456 |
+
current_key_name,
|
| 457 |
+
quantization_config,
|
| 458 |
+
has_been_replaced=has_been_replaced,
|
| 459 |
+
)
|
| 460 |
+
# Remove the last key for recursion
|
| 461 |
+
current_key_name.pop(-1)
|
| 462 |
+
return model, has_been_replaced
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def dequantize_and_replace(
|
| 466 |
+
model,
|
| 467 |
+
modules_to_not_convert=None,
|
| 468 |
+
quantization_config=None,
|
| 469 |
+
):
|
| 470 |
+
model, has_been_replaced = _dequantize_and_replace(
|
| 471 |
+
model,
|
| 472 |
+
model.dtype,
|
| 473 |
+
modules_to_not_convert=modules_to_not_convert,
|
| 474 |
+
quantization_config=quantization_config,
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
if not has_been_replaced:
|
| 478 |
+
logger.warning(
|
| 479 |
+
"For some reason the model has not been properly dequantized. You might see unexpected behavior."
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
return model
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _validate_bnb_multi_backend_availability(raise_exception):
|
| 486 |
+
import bitsandbytes as bnb
|
| 487 |
+
|
| 488 |
+
bnb_supported_devices = getattr(bnb, "supported_torch_devices", set())
|
| 489 |
+
available_devices = set(get_available_devices())
|
| 490 |
+
|
| 491 |
+
if available_devices == {"cpu"} and not is_ipex_available():
|
| 492 |
+
from importlib.util import find_spec
|
| 493 |
+
|
| 494 |
+
if find_spec("intel_extension_for_pytorch"):
|
| 495 |
+
logger.warning(
|
| 496 |
+
"You have Intel IPEX installed but if you're intending to use it for CPU, it might not have the right version. Be sure to double check that your PyTorch and IPEX installs are compatible."
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
available_devices = frozenset(
|
| 500 |
+
[device for device in available_devices if device != "cpu"]
|
| 501 |
+
) # Only Intel CPU is supported by BNB at the moment
|
| 502 |
+
|
| 503 |
+
if not available_devices.intersection(bnb_supported_devices):
|
| 504 |
+
if raise_exception:
|
| 505 |
+
bnb_supported_devices_with_info = set( # noqa: C401
|
| 506 |
+
'"cpu" (needs an Intel CPU and intel_extension_for_pytorch installed and compatible with the PyTorch version)'
|
| 507 |
+
if device == "cpu"
|
| 508 |
+
else device
|
| 509 |
+
for device in bnb_supported_devices
|
| 510 |
+
)
|
| 511 |
+
err_msg = (
|
| 512 |
+
f"None of the available devices `available_devices = {available_devices or None}` are supported by the bitsandbytes version you have installed: `bnb_supported_devices = {bnb_supported_devices_with_info}`. "
|
| 513 |
+
"Please check the docs to see if the backend you intend to use is available and how to install it: https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend"
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
logger.error(err_msg)
|
| 517 |
+
raise RuntimeError(err_msg)
|
| 518 |
+
|
| 519 |
+
logger.warning("No supported devices found for bitsandbytes multi-backend.")
|
| 520 |
+
return False
|
| 521 |
+
|
| 522 |
+
logger.debug("Multi-backend validation successful.")
|
| 523 |
+
return True
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def _validate_bnb_cuda_backend_availability(raise_exception):
|
| 527 |
+
if not is_torch_available():
|
| 528 |
+
return False
|
| 529 |
+
|
| 530 |
+
import torch
|
| 531 |
+
|
| 532 |
+
if not torch.cuda.is_available():
|
| 533 |
+
log_msg = (
|
| 534 |
+
"CUDA is required but not available for bitsandbytes. Please consider installing the multi-platform enabled version of bitsandbytes, which is currently a work in progress. "
|
| 535 |
+
"Please check currently supported platforms and installation instructions at https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend"
|
| 536 |
+
)
|
| 537 |
+
if raise_exception:
|
| 538 |
+
logger.error(log_msg)
|
| 539 |
+
raise RuntimeError(log_msg)
|
| 540 |
+
|
| 541 |
+
logger.warning(log_msg)
|
| 542 |
+
return False
|
| 543 |
+
|
| 544 |
+
logger.debug("CUDA backend validation successful.")
|
| 545 |
+
return True
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
def validate_bnb_backend_availability(raise_exception=False):
|
| 549 |
+
"""
|
| 550 |
+
Validates if the available devices are supported by bitsandbytes, optionally raising an exception if not.
|
| 551 |
+
"""
|
| 552 |
+
if not is_bitsandbytes_available():
|
| 553 |
+
if importlib.util.find_spec("bitsandbytes") and version.parse(
|
| 554 |
+
importlib.metadata.version("bitsandbytes")
|
| 555 |
+
) < version.parse("0.43.1"):
|
| 556 |
+
return _validate_bnb_cuda_backend_availability(raise_exception)
|
| 557 |
+
return False
|
| 558 |
+
|
| 559 |
+
if is_bitsandbytes_multi_backend_available():
|
| 560 |
+
return _validate_bnb_multi_backend_availability(raise_exception)
|
| 561 |
+
return _validate_bnb_cuda_backend_availability(raise_exception)
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/cache_utils.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/candidate_generator.py
ADDED
|
@@ -0,0 +1,1160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 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 |
+
|
| 16 |
+
import copy
|
| 17 |
+
import weakref
|
| 18 |
+
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
|
| 23 |
+
from ..utils import is_sklearn_available
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if is_sklearn_available():
|
| 27 |
+
from sklearn.metrics import roc_curve
|
| 28 |
+
|
| 29 |
+
from ..cache_utils import DynamicCache
|
| 30 |
+
from ..pytorch_utils import isin_mps_friendly
|
| 31 |
+
from .logits_process import LogitsProcessorList, MinLengthLogitsProcessor, SuppressTokensLogitsProcessor
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if TYPE_CHECKING:
|
| 35 |
+
from ..modeling_utils import PreTrainedModel
|
| 36 |
+
from ..tokenization_utils_base import PreTrainedTokenizerBase
|
| 37 |
+
from .configuration_utils import GenerationConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class CandidateGenerator:
|
| 41 |
+
"""Abstract base class for all candidate generators that can be applied during assisted generation."""
|
| 42 |
+
|
| 43 |
+
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
|
| 44 |
+
"""
|
| 45 |
+
Fetches the candidates to be tried for the current input.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 49 |
+
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
|
| 50 |
+
|
| 51 |
+
Return:
|
| 52 |
+
`torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate sequences to be
|
| 53 |
+
assessed by the model and, optionally, a `torch.FloatTensor` of shape `(batch_size, candidate_length,
|
| 54 |
+
vocabulary_size)` containing the logits associated to each candidate.
|
| 55 |
+
"""
|
| 56 |
+
raise NotImplementedError(
|
| 57 |
+
f"{self.__class__} is an abstract class. Only classes inheriting this class can call `get_candidates`."
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
def update_candidate_strategy(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, num_matches: int):
|
| 61 |
+
"""
|
| 62 |
+
Updates the candidate generation strategy based on the outcomes.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 66 |
+
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
|
| 67 |
+
scores (`torch.FloatTensor` of shape `(batch_size, candidate_length, config.vocab_size)`):
|
| 68 |
+
Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
|
| 69 |
+
beam search or log softmax for each vocabulary token when using beam search
|
| 70 |
+
num_matches (`int`):
|
| 71 |
+
The number of matches between the candidate sequences and the model predictions.
|
| 72 |
+
"""
|
| 73 |
+
raise NotImplementedError(
|
| 74 |
+
f"{self.__class__} is an abstract class. Only classes inheriting this class can call "
|
| 75 |
+
"`update_candidate_strategy`."
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class AssistedCandidateGenerator(CandidateGenerator):
|
| 80 |
+
"""
|
| 81 |
+
`CandidateGenerator` class to be used for assisted generation and speculative decoding. This class generates
|
| 82 |
+
candidates through the use of a smaller model. Read the following blog post for more information:
|
| 83 |
+
https://huggingface.co/blog/assisted-generation
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 87 |
+
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
|
| 88 |
+
assistant_model (`PreTrainedModel`):
|
| 89 |
+
The model to be used for generating candidates. This model should be smaller than the main model.
|
| 90 |
+
generation_config (`~generation.GenerationConfig`, *optional*):
|
| 91 |
+
The generation configuration to be used as base parametrization for the generation call.
|
| 92 |
+
logits_processor (`LogitsProcessorList`):
|
| 93 |
+
An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
|
| 94 |
+
used to modify the prediction scores of the language modeling head applied at each generation step.
|
| 95 |
+
model_kwargs (`Dict`):
|
| 96 |
+
The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant
|
| 97 |
+
model as well.
|
| 98 |
+
inputs_tensor (`torch.Tensor`, *optional*):
|
| 99 |
+
The model input tensor. In encoder-decoder models, this is the encoder input.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def __init__(
|
| 103 |
+
self,
|
| 104 |
+
input_ids: torch.LongTensor,
|
| 105 |
+
assistant_model: "PreTrainedModel",
|
| 106 |
+
generation_config: "GenerationConfig",
|
| 107 |
+
model_kwargs: Dict,
|
| 108 |
+
inputs_tensor: Optional[torch.Tensor] = None,
|
| 109 |
+
logits_processor: "LogitsProcessorList" = None,
|
| 110 |
+
):
|
| 111 |
+
# Make sure all data at the same device as assistant model
|
| 112 |
+
device = assistant_model.device
|
| 113 |
+
input_ids = input_ids.to(device)
|
| 114 |
+
if inputs_tensor is not None:
|
| 115 |
+
inputs_tensor = inputs_tensor.to(device)
|
| 116 |
+
|
| 117 |
+
# Prepare the assistant and the starting number of candidate tokens
|
| 118 |
+
self.assistant_model = assistant_model
|
| 119 |
+
self.num_assistant_tokens = assistant_model.generation_config.num_assistant_tokens
|
| 120 |
+
self.assistant_confidence_threshold = assistant_model.generation_config.assistant_confidence_threshold
|
| 121 |
+
|
| 122 |
+
# Set eos in assistant same as in target model
|
| 123 |
+
self.assistant_model.generation_config.eos_token_id = generation_config.eos_token_id
|
| 124 |
+
|
| 125 |
+
# Prepare the kwargs for the assistant model
|
| 126 |
+
assistant_kwargs = {}
|
| 127 |
+
for key, value in model_kwargs.items(): # deepcopy crashes if we attempt to copy encoder outputs with grads
|
| 128 |
+
if key not in ("encoder_outputs", "past_key_values"):
|
| 129 |
+
assistant_kwargs[key] = (
|
| 130 |
+
value.detach().to(device) if isinstance(value, torch.Tensor) else copy.deepcopy(value)
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
# Remove potential default "logits_to_keep" key
|
| 134 |
+
if "logits_to_keep" in assistant_kwargs.keys() and not assistant_model._supports_logits_to_keep():
|
| 135 |
+
del assistant_kwargs["logits_to_keep"]
|
| 136 |
+
|
| 137 |
+
# If the assistant is an encoder-decoder model, assume the encoder is different on the assistant.
|
| 138 |
+
if assistant_model.config.is_encoder_decoder:
|
| 139 |
+
inputs_tensor, model_input_name, assistant_kwargs = assistant_model._prepare_model_inputs(
|
| 140 |
+
inputs_tensor, assistant_model.generation_config.bos_token_id, assistant_kwargs
|
| 141 |
+
)
|
| 142 |
+
assistant_kwargs = assistant_model._prepare_encoder_decoder_kwargs_for_generation(
|
| 143 |
+
inputs_tensor, assistant_kwargs, model_input_name, assistant_model.generation_config
|
| 144 |
+
)
|
| 145 |
+
elif "encoder_outputs" in model_kwargs:
|
| 146 |
+
assistant_kwargs["encoder_outputs"] = model_kwargs["encoder_outputs"]
|
| 147 |
+
self.assistant_kwargs = assistant_kwargs
|
| 148 |
+
|
| 149 |
+
# Prepare assistant model's keys of inputs
|
| 150 |
+
if assistant_model.config.is_encoder_decoder:
|
| 151 |
+
# both are encoder-decoder
|
| 152 |
+
self.input_ids_key = "decoder_input_ids"
|
| 153 |
+
elif "encoder_outputs" in assistant_kwargs:
|
| 154 |
+
# special case for encoder-decoder with decoder-only assistant (like DistilWhisper)
|
| 155 |
+
self.input_ids_key = "input_ids"
|
| 156 |
+
self.assistant_kwargs["attention_mask"] = self.assistant_kwargs.get(
|
| 157 |
+
"decoder_attention_mask",
|
| 158 |
+
torch.ones((input_ids.shape[0], 1), device=input_ids.device, dtype=torch.long),
|
| 159 |
+
)
|
| 160 |
+
else:
|
| 161 |
+
# both are decoder-only
|
| 162 |
+
self.input_ids_key = "input_ids"
|
| 163 |
+
|
| 164 |
+
# Prepare generation-related options.
|
| 165 |
+
self.logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
|
| 166 |
+
self.generation_config = copy.deepcopy(generation_config)
|
| 167 |
+
|
| 168 |
+
self.generation_config.return_dict_in_generate = True
|
| 169 |
+
self.generation_config.output_scores = True
|
| 170 |
+
self.generation_config.assistant_confidence_threshold = self.assistant_confidence_threshold
|
| 171 |
+
# this flag allow us set the confidence stopping criteria for assistant model generation.
|
| 172 |
+
self.generation_config.is_assistant = True
|
| 173 |
+
|
| 174 |
+
# avoid unnecessary warnings that min_length is larger than max_new_tokens
|
| 175 |
+
# remove the `MinLengthLogitsProcessor` if exists (NOTE: no need to check for `MinNewTokensLogitsProcessor`)
|
| 176 |
+
self.main_model_min_length = self.generation_config.min_length
|
| 177 |
+
self.generation_config.min_length = 0
|
| 178 |
+
self.generation_config.min_new_tokens = None
|
| 179 |
+
for processor in self.logits_processor:
|
| 180 |
+
if isinstance(processor, MinLengthLogitsProcessor):
|
| 181 |
+
raise ValueError(
|
| 182 |
+
"Passing `MinLengthLogitsProcessor` when using `assisted_generation is disabled. "
|
| 183 |
+
"Please pass in `min_length` into `.generate()` instead"
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# We need to roll back the cache in assisted generation, only DynamicCache is supported
|
| 187 |
+
self.generation_config.cache_implementation = None
|
| 188 |
+
|
| 189 |
+
if (
|
| 190 |
+
is_sklearn_available()
|
| 191 |
+
and self.assistant_model.generation_config.assistant_confidence_threshold
|
| 192 |
+
and type(self) is AssistedCandidateGenerator
|
| 193 |
+
):
|
| 194 |
+
self.probs = []
|
| 195 |
+
self.matches = []
|
| 196 |
+
|
| 197 |
+
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
|
| 198 |
+
"""
|
| 199 |
+
Fetches the candidates to be tried for the current input.
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 203 |
+
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
|
| 204 |
+
|
| 205 |
+
Return:
|
| 206 |
+
`torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate sequences to be
|
| 207 |
+
assessed by the model and a `torch.FloatTensor` of shape `(batch_size, candidate_length,
|
| 208 |
+
vocabulary_size)` containing the logits associated to each candidate.
|
| 209 |
+
"""
|
| 210 |
+
input_ids = input_ids.to(self.assistant_model.device)
|
| 211 |
+
# Calculate new tokens to generate
|
| 212 |
+
min_new_tokens, max_new_tokens = self._calculate_new_tokens(input_ids)
|
| 213 |
+
if max_new_tokens == 0:
|
| 214 |
+
return input_ids, None
|
| 215 |
+
# Update past key values and masks
|
| 216 |
+
self._update_past_and_masks(input_ids)
|
| 217 |
+
# Generate candidates
|
| 218 |
+
generation_args = self._prepare_generation_args(input_ids, min_new_tokens, max_new_tokens)
|
| 219 |
+
candidate_ids, candidate_logits = self._generate_candidates(generation_args)
|
| 220 |
+
return candidate_ids, candidate_logits
|
| 221 |
+
|
| 222 |
+
def update_candidate_strategy(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, num_matches: int):
|
| 223 |
+
"""
|
| 224 |
+
Updates the candidate generation strategy based on the outcomes.
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 228 |
+
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
|
| 229 |
+
scores (`torch.FloatTensor` of shape `(batch_size, candidate_length, config.vocab_size)`):
|
| 230 |
+
Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
|
| 231 |
+
beam search or log softmax for each vocabulary token when using beam search
|
| 232 |
+
num_matches (`int`):
|
| 233 |
+
The number of matches between the candidate sequences and the model predictions.
|
| 234 |
+
"""
|
| 235 |
+
# Adjust the max number of assistant tokens to use in the next iteration. This is a simple heuristic,
|
| 236 |
+
# probably can be improved -- we want to balance the benefits of getting assistant tokens correct with the
|
| 237 |
+
# cost of forecasting incorrect assistant tokens.
|
| 238 |
+
if self.assistant_model.generation_config.num_assistant_tokens_schedule in {
|
| 239 |
+
"heuristic",
|
| 240 |
+
"heuristic_transient",
|
| 241 |
+
}:
|
| 242 |
+
# len(scores[0])-1 is the number of candidates according to the target tokenizer.
|
| 243 |
+
if num_matches == len(scores[0]) - 1:
|
| 244 |
+
self.num_assistant_tokens += 2.0
|
| 245 |
+
else:
|
| 246 |
+
self.num_assistant_tokens = max(1.0, self.num_assistant_tokens - 1.0)
|
| 247 |
+
|
| 248 |
+
# The assistant's confidence threshold is adjusted throughout the speculative iterations to reduce the number of unnecessary draft and target forward passes. The costs are estimated based on the ROC curve, which considers the probability of the draft token and its match with the target. A cost of 25% is assigned to false positives and 75% to false negatives.
|
| 249 |
+
# This adaptation is not compatible with UAG, as it relies on the number of matched tokens based on the draft vocabulary, which is unavailable in UAG.
|
| 250 |
+
if (
|
| 251 |
+
is_sklearn_available()
|
| 252 |
+
and self.assistant_model.generation_config.assistant_confidence_threshold
|
| 253 |
+
and type(self) is AssistedCandidateGenerator
|
| 254 |
+
):
|
| 255 |
+
# update self.matches
|
| 256 |
+
self.matches.extend([1] * num_matches)
|
| 257 |
+
if len(self.probs) > len(self.matches):
|
| 258 |
+
self.matches.append(0)
|
| 259 |
+
|
| 260 |
+
# update self.probs
|
| 261 |
+
excess_length = len(self.probs) - len(self.matches)
|
| 262 |
+
if excess_length > 0:
|
| 263 |
+
del self.probs[-excess_length:]
|
| 264 |
+
|
| 265 |
+
if (
|
| 266 |
+
len(self.probs) > 5 and {0, 1}.issubset(self.matches)
|
| 267 |
+
): # require at least 5 samples to calculate the ROC curve and at least one positive and one negative sample
|
| 268 |
+
fpr, tpr, thresholds = roc_curve(self.matches, self.probs)
|
| 269 |
+
fnr = 1 - tpr
|
| 270 |
+
|
| 271 |
+
# Calculate the cost for each threshold
|
| 272 |
+
costs = fpr + 3 * fnr
|
| 273 |
+
|
| 274 |
+
# Find the threshold that minimizes the cost
|
| 275 |
+
optimal_threshold_index = np.argmin(costs)
|
| 276 |
+
best_threshold = thresholds[optimal_threshold_index]
|
| 277 |
+
|
| 278 |
+
self.assistant_model.generation_config.assistant_confidence_threshold = best_threshold
|
| 279 |
+
|
| 280 |
+
def _calculate_new_tokens(self, input_ids: torch.LongTensor) -> Tuple[int, int]:
|
| 281 |
+
"""Calculate the minimum and maximum number of new tokens to generate."""
|
| 282 |
+
new_cur_len = input_ids.shape[-1]
|
| 283 |
+
max_new_tokens = min(int(self.num_assistant_tokens), self.generation_config.max_length - new_cur_len - 1)
|
| 284 |
+
min_new_tokens = max(min(max_new_tokens, self.main_model_min_length - new_cur_len), 0)
|
| 285 |
+
return min_new_tokens, max_new_tokens
|
| 286 |
+
|
| 287 |
+
def _update_past_and_masks(
|
| 288 |
+
self, input_ids: torch.LongTensor, remove_from_pkv: int = 0, num_added_tokens: int = 1
|
| 289 |
+
) -> bool:
|
| 290 |
+
"""Update past key values and attention masks for subsequent generation rounds."""
|
| 291 |
+
has_past_key_values = self.assistant_kwargs.get("past_key_values", None) is not None
|
| 292 |
+
if has_past_key_values:
|
| 293 |
+
new_cache_size = input_ids.shape[-1] - 1 - remove_from_pkv
|
| 294 |
+
self.assistant_kwargs["past_key_values"] = _crop_past_key_values(
|
| 295 |
+
self.assistant_model, self.assistant_kwargs["past_key_values"], new_cache_size - num_added_tokens
|
| 296 |
+
)
|
| 297 |
+
self.assistant_kwargs = _prepare_attention_mask(
|
| 298 |
+
self.assistant_kwargs, input_ids.shape[-1], self.assistant_model.config.is_encoder_decoder
|
| 299 |
+
)
|
| 300 |
+
self.assistant_kwargs = _prepare_token_type_ids(self.assistant_kwargs, input_ids.shape[-1])
|
| 301 |
+
|
| 302 |
+
return has_past_key_values
|
| 303 |
+
|
| 304 |
+
def _prepare_generation_args(self, input_ids: torch.LongTensor, min_new_tokens: int, max_new_tokens: int) -> Dict:
|
| 305 |
+
"""Prepare arguments for the generation call."""
|
| 306 |
+
return {
|
| 307 |
+
self.input_ids_key: input_ids,
|
| 308 |
+
"min_new_tokens": min_new_tokens,
|
| 309 |
+
"max_new_tokens": max_new_tokens,
|
| 310 |
+
"generation_config": self.generation_config,
|
| 311 |
+
"logits_processor": self.logits_processor,
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
def _generate_candidates(self, generation_args: Dict) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
|
| 315 |
+
"""Generate candidate sequences using the assistant model."""
|
| 316 |
+
assistant_output = self.assistant_model.generate(**generation_args, **self.assistant_kwargs)
|
| 317 |
+
self.assistant_kwargs["past_key_values"] = assistant_output.past_key_values
|
| 318 |
+
if (
|
| 319 |
+
is_sklearn_available()
|
| 320 |
+
and self.assistant_model.generation_config.assistant_confidence_threshold
|
| 321 |
+
and type(self) is AssistedCandidateGenerator
|
| 322 |
+
):
|
| 323 |
+
scores_tensor = torch.cat(assistant_output.scores, dim=0)
|
| 324 |
+
scores_softmax = torch.softmax(scores_tensor, dim=-1)
|
| 325 |
+
ids = assistant_output.sequences[-1, -len(assistant_output.scores) :]
|
| 326 |
+
p = scores_softmax[range(len(ids)), ids]
|
| 327 |
+
self.probs.extend(p.tolist())
|
| 328 |
+
candidate_logits = torch.stack(assistant_output.scores, dim=1)
|
| 329 |
+
candidate_ids = assistant_output.sequences
|
| 330 |
+
return candidate_ids, candidate_logits
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class AssistedCandidateGeneratorDifferentTokenizers(AssistedCandidateGenerator):
|
| 334 |
+
"""
|
| 335 |
+
`CandidateGenerator` class to be used for Universal Assisted Generation (UAD): assisted generation with different tokenizers
|
| 336 |
+
for the assistant and main models. This class generates candidates through the use of a smaller
|
| 337 |
+
model.
|
| 338 |
+
|
| 339 |
+
The main model input tokens are re-encoded into assistant model tokens, then candidate tokens are generated in the assistant encoding, which are
|
| 340 |
+
in turn re-encoded into main model candidate tokens. Validation then proceeds as explained above.
|
| 341 |
+
The re-encoding steps involve decoding token ids into text and then encoding the text using a different tokenizer.
|
| 342 |
+
Since re-encoding the tokens may result in tokenization discrepancies, UAD finds the longest common subsequence between the source and target encodings,
|
| 343 |
+
to ensure the new tokens include the correct prompt suffix.
|
| 344 |
+
|
| 345 |
+
Args:
|
| 346 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 347 |
+
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
|
| 348 |
+
assistant_model (`PreTrainedModel`):
|
| 349 |
+
The model to be used for generating candidates. This model should be smaller than the main model.
|
| 350 |
+
target_tokenizer (`PreTrainedTokenizerBase`):
|
| 351 |
+
The tokenizer used for the target model.
|
| 352 |
+
assistant_tokenizer (`PreTrainedTokenizerBase`):
|
| 353 |
+
The tokenizer used for the assistant model.
|
| 354 |
+
generation_config (`~generation.GenerationConfig`, *optional*):
|
| 355 |
+
The generation configuration to be used as base parametrization for the generation call.
|
| 356 |
+
logits_processor (`LogitsProcessorList`):
|
| 357 |
+
An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
|
| 358 |
+
used to modify the prediction scores of the language modeling head applied at each generation step.
|
| 359 |
+
model_kwargs (`Dict`):
|
| 360 |
+
The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant
|
| 361 |
+
model as well.
|
| 362 |
+
inputs_tensor (`torch.Tensor`, *optional*):
|
| 363 |
+
The model input tensor. In encoder-decoder models, this is the encoder input.
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
def __init__(
|
| 367 |
+
self,
|
| 368 |
+
input_ids: torch.LongTensor,
|
| 369 |
+
assistant_model: "PreTrainedModel",
|
| 370 |
+
target_tokenizer: "PreTrainedTokenizerBase",
|
| 371 |
+
assistant_tokenizer: "PreTrainedTokenizerBase",
|
| 372 |
+
generation_config: "GenerationConfig",
|
| 373 |
+
model_kwargs: Dict,
|
| 374 |
+
inputs_tensor: Optional[torch.Tensor] = None,
|
| 375 |
+
logits_processor: "LogitsProcessorList" = None,
|
| 376 |
+
):
|
| 377 |
+
super().__init__(input_ids, assistant_model, generation_config, model_kwargs, inputs_tensor, logits_processor)
|
| 378 |
+
|
| 379 |
+
self.target_tokenizer = target_tokenizer
|
| 380 |
+
self.assistant_tokenizer = assistant_tokenizer
|
| 381 |
+
self.prev_target_ids_len: Optional[int] = None
|
| 382 |
+
self.prev_assistant_ids = None
|
| 383 |
+
self.target_lookbehind = assistant_model.generation_config.target_lookbehind
|
| 384 |
+
self.assistant_lookbehind = assistant_model.generation_config.assistant_lookbehind
|
| 385 |
+
|
| 386 |
+
@staticmethod
|
| 387 |
+
def _get_longest_diag_dict(input_matrix, nonzero_idx):
|
| 388 |
+
"""
|
| 389 |
+
Calculates the length of the longest diagonal sequence in a given matrix.
|
| 390 |
+
Args:
|
| 391 |
+
input_matrix (torch.Tensor): The input matrix.
|
| 392 |
+
nonzero_idx (torch.Tensor): The indices of the non-zero elements in the matrix.
|
| 393 |
+
Returns:
|
| 394 |
+
dict: A dictionary where the keys are the indices of the non-zero elements and the values are the lengths of the longest diagonal sequences starting from those indices.
|
| 395 |
+
"""
|
| 396 |
+
|
| 397 |
+
visited = set()
|
| 398 |
+
diags = {}
|
| 399 |
+
for idx in nonzero_idx:
|
| 400 |
+
start_idx = torch.clone(idx)
|
| 401 |
+
tuple_start_idx = tuple(start_idx.tolist())
|
| 402 |
+
|
| 403 |
+
if tuple_start_idx in visited:
|
| 404 |
+
continue
|
| 405 |
+
|
| 406 |
+
visited.add(tuple_start_idx)
|
| 407 |
+
cur_diag_len = 1
|
| 408 |
+
start_idx += 1
|
| 409 |
+
while start_idx[0] < input_matrix.shape[0] and start_idx[1] < input_matrix.shape[1]:
|
| 410 |
+
tuple_start_idx = tuple(start_idx.tolist())
|
| 411 |
+
visited.add(tuple_start_idx)
|
| 412 |
+
|
| 413 |
+
if input_matrix[start_idx[0], start_idx[1]] == 1:
|
| 414 |
+
cur_diag_len += 1
|
| 415 |
+
start_idx += 1
|
| 416 |
+
else:
|
| 417 |
+
break
|
| 418 |
+
|
| 419 |
+
diags[idx] = cur_diag_len
|
| 420 |
+
return diags
|
| 421 |
+
|
| 422 |
+
@staticmethod
|
| 423 |
+
def _get_longest_diag_index(input_matrix):
|
| 424 |
+
"""
|
| 425 |
+
Returns the start index and length of the longest diagonal in the given input.
|
| 426 |
+
Args:
|
| 427 |
+
input_matrix (numpy.ndarray): The input matrix.
|
| 428 |
+
Returns:
|
| 429 |
+
tuple: A tuple containing the start index and length of the longest diagonal.
|
| 430 |
+
"""
|
| 431 |
+
|
| 432 |
+
diags = AssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_dict(
|
| 433 |
+
input_matrix, input_matrix.nonzero()
|
| 434 |
+
)
|
| 435 |
+
diags_values = list(diags.values())
|
| 436 |
+
diags_keys = list(diags.keys())
|
| 437 |
+
best_diag = np.argmax(diags_values)
|
| 438 |
+
diag_start_index = diags_keys[best_diag]
|
| 439 |
+
diag_start_length = diags_values[best_diag]
|
| 440 |
+
return diag_start_index, diag_start_length
|
| 441 |
+
|
| 442 |
+
@staticmethod
|
| 443 |
+
def _get_tokens_diag(prompt, prompt_plus_new_tokens):
|
| 444 |
+
"""
|
| 445 |
+
Input:
|
| 446 |
+
prompt: 2D array of shape (batch_size, prompt_length), represents the original prompt tokens
|
| 447 |
+
prompt_plus_new_tokens: 2D array of shape (batch_size, prompt_length), represents the suffix of the original prompt, with additional new tokens.
|
| 448 |
+
Output:
|
| 449 |
+
discrepancy_length: int, represents the number of tokens that need to be replaced from prompt
|
| 450 |
+
new_tokens_only: 2D array of shape (batch_size, new_token_length), represents the new tokens that are not in prompt
|
| 451 |
+
discrepancy_only: 2D array of shape (batch_size, discrepancy_length), represents the new tokens that are in prompt but not in prompt_plus_new_tokens
|
| 452 |
+
"""
|
| 453 |
+
compare_mat = prompt_plus_new_tokens.T == prompt
|
| 454 |
+
if not torch.is_tensor(compare_mat):
|
| 455 |
+
compare_mat = torch.tensor(compare_mat)
|
| 456 |
+
|
| 457 |
+
compare_mat_int = compare_mat.to(int)
|
| 458 |
+
|
| 459 |
+
if not compare_mat_int.any().item():
|
| 460 |
+
# empty intersection between prompt and prompt_plus_new_tokens
|
| 461 |
+
return None, None, None
|
| 462 |
+
|
| 463 |
+
longest_location, longest_diag_length = AssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_index(
|
| 464 |
+
compare_mat_int
|
| 465 |
+
)
|
| 466 |
+
new_token_start_index = longest_location[0] + longest_diag_length
|
| 467 |
+
discrepancy_with_old = longest_location[1] + longest_diag_length
|
| 468 |
+
discrepancy_length = (prompt.shape[1] - discrepancy_with_old).item()
|
| 469 |
+
new_tokens_only = prompt_plus_new_tokens[:, new_token_start_index + discrepancy_length :]
|
| 470 |
+
discrepancy_only = prompt_plus_new_tokens[
|
| 471 |
+
:, new_token_start_index : new_token_start_index + discrepancy_length
|
| 472 |
+
]
|
| 473 |
+
return discrepancy_length, new_tokens_only, discrepancy_only
|
| 474 |
+
|
| 475 |
+
def convert_source_tokens_to_target_tokens(
|
| 476 |
+
self,
|
| 477 |
+
input_ids,
|
| 478 |
+
source_tokenizer,
|
| 479 |
+
destination_tokenizer,
|
| 480 |
+
):
|
| 481 |
+
"""
|
| 482 |
+
Convert token IDs from one tokenizer to another.
|
| 483 |
+
Args:
|
| 484 |
+
input_ids: The input token IDs.
|
| 485 |
+
source_tokenizer: The source tokenizer.
|
| 486 |
+
destination_tokenizer: The destination tokenizer.
|
| 487 |
+
Returns:
|
| 488 |
+
The converted token IDs.
|
| 489 |
+
"""
|
| 490 |
+
text = source_tokenizer.batch_decode(input_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
|
| 491 |
+
dest_ids = destination_tokenizer(text, add_special_tokens=True, return_tensors="pt")["input_ids"]
|
| 492 |
+
return dest_ids.to(input_ids.device)
|
| 493 |
+
|
| 494 |
+
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
|
| 495 |
+
"""
|
| 496 |
+
Fetches the candidates to be tried for the current input.
|
| 497 |
+
|
| 498 |
+
Args:
|
| 499 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 500 |
+
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
|
| 501 |
+
|
| 502 |
+
Return:
|
| 503 |
+
`torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate sequences to be
|
| 504 |
+
assessed by the model and a `torch.FloatTensor` of shape `(batch_size, candidate_length,
|
| 505 |
+
vocabulary_size)` containing the logits associated to each candidate.
|
| 506 |
+
"""
|
| 507 |
+
max_new_tokens = int(self.num_assistant_tokens)
|
| 508 |
+
if max_new_tokens == 0:
|
| 509 |
+
return input_ids, None
|
| 510 |
+
|
| 511 |
+
input_ids = input_ids.to(self.assistant_model.device)
|
| 512 |
+
remove_from_pkv = 0
|
| 513 |
+
|
| 514 |
+
assistant_input_ids, remove_from_pkv = self._prepare_assistant_input_ids(input_ids)
|
| 515 |
+
self.prev_assistant_ids = assistant_input_ids
|
| 516 |
+
|
| 517 |
+
min_new_tokens = max(min(max_new_tokens, self.main_model_min_length - assistant_input_ids.shape[-1]), 0)
|
| 518 |
+
|
| 519 |
+
self._update_past_and_masks(assistant_input_ids, remove_from_pkv)
|
| 520 |
+
generation_args = self._prepare_generation_args(assistant_input_ids, min_new_tokens, max_new_tokens)
|
| 521 |
+
self.assistant_kwargs.pop("attention_mask", None)
|
| 522 |
+
|
| 523 |
+
assistant_output = self.assistant_model.generate(**generation_args, **self.assistant_kwargs)
|
| 524 |
+
new_target_ids = self._process_assistant_outputs(input_ids, assistant_output.sequences, assistant_input_ids)
|
| 525 |
+
|
| 526 |
+
# Update state
|
| 527 |
+
self.prev_target_ids_len = input_ids.shape[1]
|
| 528 |
+
self.assistant_kwargs["past_key_values"] = assistant_output.past_key_values
|
| 529 |
+
self.prev_assistant_ids = assistant_output.sequences
|
| 530 |
+
|
| 531 |
+
if self.prev_target_ids_len >= new_target_ids.shape[1]:
|
| 532 |
+
return input_ids, None
|
| 533 |
+
|
| 534 |
+
return new_target_ids, None
|
| 535 |
+
|
| 536 |
+
def _prepare_assistant_input_ids(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, int]:
|
| 537 |
+
"""Converts target input IDs to assistant input IDs, handling discrepancies."""
|
| 538 |
+
convert_kwargs = {
|
| 539 |
+
"source_tokenizer": self.target_tokenizer,
|
| 540 |
+
"destination_tokenizer": self.assistant_tokenizer,
|
| 541 |
+
}
|
| 542 |
+
remove_from_pkv = 0
|
| 543 |
+
|
| 544 |
+
if self.prev_assistant_ids is not None and self.prev_target_ids_len > self.target_lookbehind:
|
| 545 |
+
# input_ids contains all target prompt input ids and some new target input ids
|
| 546 |
+
start_index_in_target_window = self.prev_target_ids_len - self.target_lookbehind
|
| 547 |
+
|
| 548 |
+
new_assistant_ids = self.convert_source_tokens_to_target_tokens(
|
| 549 |
+
input_ids[:, start_index_in_target_window:], **convert_kwargs
|
| 550 |
+
)
|
| 551 |
+
prompt_use_length = new_assistant_ids.shape[1]
|
| 552 |
+
prompt_use = self.prev_assistant_ids[:, -prompt_use_length:]
|
| 553 |
+
|
| 554 |
+
discrepancy_length, new_tokens_only, discrepancy_only = self._get_tokens_diag(
|
| 555 |
+
prompt_use, new_assistant_ids
|
| 556 |
+
)
|
| 557 |
+
assistant_input_ids = self.prev_assistant_ids
|
| 558 |
+
|
| 559 |
+
if new_tokens_only is not None:
|
| 560 |
+
if discrepancy_length > 0 and discrepancy_only.shape[1] > 0:
|
| 561 |
+
if discrepancy_length == discrepancy_only.shape[1]:
|
| 562 |
+
assistant_input_ids[:, -discrepancy_length:] = discrepancy_only
|
| 563 |
+
|
| 564 |
+
elif discrepancy_length > discrepancy_only.shape[1]:
|
| 565 |
+
discrepancy_length_diff = discrepancy_length - discrepancy_only.shape[1]
|
| 566 |
+
assistant_input_ids = assistant_input_ids[:, :-discrepancy_length_diff]
|
| 567 |
+
assistant_input_ids[:, -discrepancy_only.shape[1] :] = discrepancy_only
|
| 568 |
+
|
| 569 |
+
remove_from_pkv = discrepancy_length
|
| 570 |
+
|
| 571 |
+
if new_tokens_only.shape[1] > 0:
|
| 572 |
+
assistant_input_ids = torch.cat([assistant_input_ids, new_tokens_only], dim=-1)
|
| 573 |
+
else:
|
| 574 |
+
# edge case: in case of no intersection between prompt and new_assistant_ids
|
| 575 |
+
assistant_input_ids = torch.cat([assistant_input_ids, new_assistant_ids], dim=-1)
|
| 576 |
+
else:
|
| 577 |
+
assistant_input_ids = self.convert_source_tokens_to_target_tokens(input_ids, **convert_kwargs)
|
| 578 |
+
self.prev_target_ids_len = input_ids.shape[1]
|
| 579 |
+
|
| 580 |
+
return assistant_input_ids, remove_from_pkv
|
| 581 |
+
|
| 582 |
+
def _process_assistant_outputs(
|
| 583 |
+
self, input_ids: torch.LongTensor, assistant_sequences: torch.LongTensor, assistant_input_ids: torch.LongTensor
|
| 584 |
+
) -> torch.LongTensor:
|
| 585 |
+
"""Processes assistant outputs to obtain target input IDs."""
|
| 586 |
+
num_prev_assistant = self.prev_assistant_ids.shape[1]
|
| 587 |
+
start_assistant_look_index = num_prev_assistant - self.assistant_lookbehind
|
| 588 |
+
|
| 589 |
+
new_target_ids_from_window = self.convert_source_tokens_to_target_tokens(
|
| 590 |
+
assistant_sequences[:, start_assistant_look_index:],
|
| 591 |
+
source_tokenizer=self.assistant_tokenizer,
|
| 592 |
+
destination_tokenizer=self.target_tokenizer,
|
| 593 |
+
)
|
| 594 |
+
target_prompt_use_length = new_target_ids_from_window.shape[1]
|
| 595 |
+
|
| 596 |
+
target_prompt_use = input_ids[:, -target_prompt_use_length:]
|
| 597 |
+
|
| 598 |
+
_, target_new_tokens_only, _ = self._get_tokens_diag(target_prompt_use, new_target_ids_from_window)
|
| 599 |
+
|
| 600 |
+
new_target_ids = input_ids
|
| 601 |
+
|
| 602 |
+
if target_new_tokens_only is not None:
|
| 603 |
+
if target_new_tokens_only.shape[1] > 0:
|
| 604 |
+
new_target_ids = torch.cat([new_target_ids, target_new_tokens_only], dim=-1)
|
| 605 |
+
else:
|
| 606 |
+
# edge case: in case of no intersection between prompt and new_target_ids
|
| 607 |
+
new_target_ids = torch.cat([new_target_ids, new_target_ids_from_window], dim=-1)
|
| 608 |
+
|
| 609 |
+
if hasattr(self.generation_config, "max_length"):
|
| 610 |
+
new_target_ids = new_target_ids[:, : self.generation_config.max_length]
|
| 611 |
+
|
| 612 |
+
return new_target_ids
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
class AssistantToTargetTranslator:
|
| 616 |
+
"""
|
| 617 |
+
Translates token ids and logits between assistant and target model vocabularies. This class is used to handle
|
| 618 |
+
vocabulary mismatches when using different tokenizers for the assistant and target models in speculative decoding,
|
| 619 |
+
as introduced in the paper "Lossless Speculative Decoding Algorithms for Heterogeneous Vocabularies"
|
| 620 |
+
(https://www.arxiv.org/abs/2502.05202).
|
| 621 |
+
It maintains mappings between the two vocabularies and handles token/logit conversion.
|
| 622 |
+
|
| 623 |
+
Args:
|
| 624 |
+
target_tokenizer (`PreTrainedTokenizerBase`):
|
| 625 |
+
The tokenizer used by the target (main) model.
|
| 626 |
+
assistant_tokenizer (`PreTrainedTokenizerBase`):
|
| 627 |
+
The tokenizer used by the assistant model.
|
| 628 |
+
assistant_model_device (`str`, defaults to "cpu"):
|
| 629 |
+
The device where the assistant model is located. Used for placing tensors.
|
| 630 |
+
target_vocab_size (`int`, *optional*):
|
| 631 |
+
The size of the target model's vocabulary. If not provided, will be inferred from the target tokenizer.
|
| 632 |
+
"""
|
| 633 |
+
|
| 634 |
+
FILTER_VALUE: float = -float("Inf") # The value used to filter out unmapped tokens in the logits.
|
| 635 |
+
SUPPRESS_TOKEN_ID: int = -1 # The ID used to mark suppressed tokens in the mapping.
|
| 636 |
+
|
| 637 |
+
def __init__(
|
| 638 |
+
self,
|
| 639 |
+
target_tokenizer: "PreTrainedTokenizerBase",
|
| 640 |
+
assistant_tokenizer: "PreTrainedTokenizerBase",
|
| 641 |
+
target_vocab_size: int, # required since target_vocab_size can be different from the length of target_tokenizer.get_vocab()
|
| 642 |
+
assistant_model_device: str = "cpu",
|
| 643 |
+
):
|
| 644 |
+
self._target_tokenizer: "PreTrainedTokenizerBase" = target_tokenizer
|
| 645 |
+
self._assistant_tokenizer: "PreTrainedTokenizerBase" = assistant_tokenizer
|
| 646 |
+
self._assistant_model_device: str = assistant_model_device
|
| 647 |
+
self.target_vocab_size: int = target_vocab_size
|
| 648 |
+
self._assistant_to_target_input_ids, self.target_to_assistant_input_ids = (
|
| 649 |
+
self._get_assistant_to_target_input_ids()
|
| 650 |
+
)
|
| 651 |
+
self._suppress_input_ids: list[int] = self._get_suppress_input_ids()
|
| 652 |
+
self.logits_processors: Optional[LogitsProcessorList] = None
|
| 653 |
+
if len(self._suppress_input_ids) > 0:
|
| 654 |
+
# len(self._suppress_input_ids) = 0 if the assistant vocab is a subset of the target vocab
|
| 655 |
+
self.logits_processors = LogitsProcessorList(
|
| 656 |
+
[SuppressTokensLogitsProcessor(self._get_suppress_input_ids(), self._assistant_model_device)]
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
def _get_assistant_to_target_input_ids(self):
|
| 660 |
+
target_vocab = self._target_tokenizer.get_vocab()
|
| 661 |
+
assistant_vocab = self._assistant_tokenizer.get_vocab()
|
| 662 |
+
|
| 663 |
+
space_str = " "
|
| 664 |
+
target_space_ids = self._target_tokenizer(space_str, add_special_tokens=False)["input_ids"]
|
| 665 |
+
if len(target_space_ids) > 0:
|
| 666 |
+
target_space_sign = self._target_tokenizer.convert_ids_to_tokens(target_space_ids)[0][0]
|
| 667 |
+
|
| 668 |
+
assistant_space_ids = self._assistant_tokenizer(space_str, add_special_tokens=False)["input_ids"]
|
| 669 |
+
if len(assistant_space_ids) > 0:
|
| 670 |
+
assistant_space_sign = self._assistant_tokenizer.convert_ids_to_tokens(assistant_space_ids)[0][0]
|
| 671 |
+
|
| 672 |
+
if target_space_sign != assistant_space_sign:
|
| 673 |
+
# If the assistant tokenizer has a different space sign than the target tokenizer,
|
| 674 |
+
# we need to replace the assistant space sign with the target space sign in the assistant_vocab.
|
| 675 |
+
assistant_vocab = {
|
| 676 |
+
(
|
| 677 |
+
tok.replace(assistant_space_sign, target_space_sign, 1)
|
| 678 |
+
if tok.startswith(assistant_space_sign)
|
| 679 |
+
else tok
|
| 680 |
+
): idx
|
| 681 |
+
for tok, idx in assistant_vocab.items()
|
| 682 |
+
}
|
| 683 |
+
|
| 684 |
+
max_assistant_index = max(assistant_vocab.values())
|
| 685 |
+
assistant_to_target_input_ids = torch.full((max_assistant_index + 1,), self.SUPPRESS_TOKEN_ID, dtype=int)
|
| 686 |
+
target_to_assistant_input_ids: Dict[int, int] = {}
|
| 687 |
+
for tok, assistant_id in assistant_vocab.items():
|
| 688 |
+
target_id = target_vocab.get(tok)
|
| 689 |
+
if target_id is not None:
|
| 690 |
+
assistant_to_target_input_ids[assistant_id] = target_id
|
| 691 |
+
target_to_assistant_input_ids[target_id] = assistant_id
|
| 692 |
+
return assistant_to_target_input_ids.to(self._assistant_model_device), target_to_assistant_input_ids
|
| 693 |
+
|
| 694 |
+
def _get_suppress_input_ids(self) -> list[int]:
|
| 695 |
+
"""
|
| 696 |
+
Get the input ids that are in the assistant vocab but not in the target vocab.
|
| 697 |
+
"""
|
| 698 |
+
return torch.where(self._assistant_to_target_input_ids == self.SUPPRESS_TOKEN_ID)[0]
|
| 699 |
+
|
| 700 |
+
def get_target_ids(
|
| 701 |
+
self, assistant_input_ids, target_input_ids, assistant_candidate_ids: torch.LongTensor
|
| 702 |
+
) -> torch.LongTensor:
|
| 703 |
+
"""
|
| 704 |
+
Return the target candidate ids that correspond to the assistant candidate ids.
|
| 705 |
+
Note that we have already the target ids for the prompt and we only need to find the target ids for the new tokens.
|
| 706 |
+
Moreover, assistant ids of the original prompt does not necessarily appear in _assistant_to_target_input_ids.
|
| 707 |
+
"""
|
| 708 |
+
|
| 709 |
+
num_new_tokens = len(assistant_candidate_ids[0]) - assistant_input_ids.shape[1]
|
| 710 |
+
if num_new_tokens == 0:
|
| 711 |
+
return target_input_ids
|
| 712 |
+
else:
|
| 713 |
+
transformed_slice = self._assistant_to_target_input_ids[assistant_candidate_ids[0, -num_new_tokens:]]
|
| 714 |
+
return torch.cat((target_input_ids, transformed_slice.unsqueeze(0)), dim=1)
|
| 715 |
+
|
| 716 |
+
def get_target_logits(self, assistant_logits: torch.FloatTensor) -> torch.FloatTensor:
|
| 717 |
+
"""
|
| 718 |
+
Return the target logits that correspond to the assistant logits.
|
| 719 |
+
"""
|
| 720 |
+
|
| 721 |
+
target_shape: tuple[int, ...] = (*assistant_logits.shape[:-1], self.target_vocab_size)
|
| 722 |
+
target_logits: torch.FloatTensor = torch.full(
|
| 723 |
+
target_shape, self.FILTER_VALUE, device=self._assistant_model_device
|
| 724 |
+
)
|
| 725 |
+
# Mask for valid indices
|
| 726 |
+
assistant_indices_mask = self._assistant_to_target_input_ids != self.SUPPRESS_TOKEN_ID
|
| 727 |
+
# Exclude invalid indices
|
| 728 |
+
target_logits_supported_indices = self._assistant_to_target_input_ids[assistant_indices_mask]
|
| 729 |
+
valid_assistant_logits = assistant_logits[..., : self._assistant_to_target_input_ids.shape[0]]
|
| 730 |
+
|
| 731 |
+
target_logits[..., target_logits_supported_indices] = valid_assistant_logits[..., assistant_indices_mask]
|
| 732 |
+
|
| 733 |
+
return target_logits
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
class AssistantVocabTranslatorCache:
|
| 737 |
+
"""
|
| 738 |
+
Cache for `AssistantToTargetTranslator` instances. The instances are computed at
|
| 739 |
+
pre-processing time, and this cache allows us to avoid recomputing them.
|
| 740 |
+
"""
|
| 741 |
+
|
| 742 |
+
_cache = weakref.WeakKeyDictionary()
|
| 743 |
+
|
| 744 |
+
@classmethod
|
| 745 |
+
def get_translator(
|
| 746 |
+
cls,
|
| 747 |
+
target_tokenizer: "PreTrainedTokenizerBase",
|
| 748 |
+
assistant_tokenizer: "PreTrainedTokenizerBase",
|
| 749 |
+
target_vocab_size: int,
|
| 750 |
+
assistant_model_device: str = "cpu",
|
| 751 |
+
) -> AssistantToTargetTranslator:
|
| 752 |
+
assistant_dict = cls._cache.get(target_tokenizer)
|
| 753 |
+
if assistant_dict is None:
|
| 754 |
+
assistant_dict = weakref.WeakKeyDictionary()
|
| 755 |
+
cls._cache[target_tokenizer] = assistant_dict
|
| 756 |
+
|
| 757 |
+
mapping = assistant_dict.get(assistant_tokenizer)
|
| 758 |
+
if mapping is None:
|
| 759 |
+
mapping = AssistantToTargetTranslator(
|
| 760 |
+
target_tokenizer, assistant_tokenizer, target_vocab_size, assistant_model_device
|
| 761 |
+
)
|
| 762 |
+
assistant_dict[assistant_tokenizer] = mapping
|
| 763 |
+
|
| 764 |
+
return mapping
|
| 765 |
+
|
| 766 |
+
@classmethod
|
| 767 |
+
def cleanup(cls):
|
| 768 |
+
"""
|
| 769 |
+
Clean up dead references in the cache.
|
| 770 |
+
This removes entries where either the target_tokenizer or assistant_tokenizer
|
| 771 |
+
has been garbage collected.
|
| 772 |
+
"""
|
| 773 |
+
# Remove entries from the outer cache where the target_tokenizer is no longer alive
|
| 774 |
+
dead_keys = [key for key in cls._cache if key is None]
|
| 775 |
+
for key in dead_keys:
|
| 776 |
+
del cls._cache[key]
|
| 777 |
+
|
| 778 |
+
# For each assistant_dict, remove entries where assistant_tokenizer is no longer alive
|
| 779 |
+
for assistant_dict in cls._cache.values():
|
| 780 |
+
dead_keys = [key for key in assistant_dict if key is None]
|
| 781 |
+
for key in dead_keys:
|
| 782 |
+
del assistant_dict[key]
|
| 783 |
+
|
| 784 |
+
|
| 785 |
+
class UniversalSpeculativeDecodingGenerator(AssistedCandidateGeneratorDifferentTokenizers):
|
| 786 |
+
"""
|
| 787 |
+
`CandidateGenerator` class to be used for Universal Speculative Decoding (USD): speculative decoding with different tokenizers
|
| 788 |
+
for the assistant and main models. This class generates candidates through the use of a smaller model.
|
| 789 |
+
"""
|
| 790 |
+
|
| 791 |
+
def __init__(
|
| 792 |
+
self,
|
| 793 |
+
input_ids: torch.LongTensor,
|
| 794 |
+
assistant_model: "PreTrainedModel",
|
| 795 |
+
target_tokenizer: "PreTrainedTokenizerBase",
|
| 796 |
+
assistant_tokenizer: "PreTrainedTokenizerBase",
|
| 797 |
+
generation_config: "GenerationConfig",
|
| 798 |
+
model_kwargs: Dict,
|
| 799 |
+
atm_translator: AssistantToTargetTranslator,
|
| 800 |
+
inputs_tensor: Optional[torch.Tensor] = None,
|
| 801 |
+
logits_processor: "LogitsProcessorList" = None,
|
| 802 |
+
):
|
| 803 |
+
# Initialize translator before parent class
|
| 804 |
+
self._atm_translator = atm_translator
|
| 805 |
+
super().__init__(
|
| 806 |
+
input_ids,
|
| 807 |
+
assistant_model,
|
| 808 |
+
target_tokenizer,
|
| 809 |
+
assistant_tokenizer,
|
| 810 |
+
generation_config,
|
| 811 |
+
model_kwargs,
|
| 812 |
+
inputs_tensor,
|
| 813 |
+
logits_processor,
|
| 814 |
+
)
|
| 815 |
+
# Track sequence lengths and previous assistant IDs
|
| 816 |
+
self._target_seq_len_with_candidates: int = 0
|
| 817 |
+
self._prev_assistant_ids: Optional[torch.LongTensor] = None
|
| 818 |
+
|
| 819 |
+
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
|
| 820 |
+
"""
|
| 821 |
+
Simplified version of get_candidates that uses the translator cache for token conversion.
|
| 822 |
+
"""
|
| 823 |
+
target_input_ids = input_ids.to(self.assistant_model.device)
|
| 824 |
+
assistant_input_ids, num_added_tokens = self._prepare_assistant_input_ids(target_input_ids)
|
| 825 |
+
min_new_tokens, max_new_tokens = self._calculate_new_tokens(target_input_ids)
|
| 826 |
+
|
| 827 |
+
if max_new_tokens == 0:
|
| 828 |
+
return input_ids, None
|
| 829 |
+
|
| 830 |
+
self._update_past_and_masks(assistant_input_ids, num_added_tokens=num_added_tokens)
|
| 831 |
+
generation_args = self._prepare_generation_args(assistant_input_ids, min_new_tokens, max_new_tokens)
|
| 832 |
+
|
| 833 |
+
# Ensure scores are returned
|
| 834 |
+
generation_args["generation_config"].output_scores = True
|
| 835 |
+
generation_args["generation_config"].return_dict_in_generate = True
|
| 836 |
+
|
| 837 |
+
# Generate and process outputs using translator
|
| 838 |
+
if self._atm_translator.logits_processors is not None:
|
| 839 |
+
generation_args["logits_processor"] = self._atm_translator.logits_processors
|
| 840 |
+
self._prev_assistant_ids, assistant_candidate_logits = self._generate_candidates(generation_args)
|
| 841 |
+
|
| 842 |
+
# Use translator to convert tokens and logits
|
| 843 |
+
target_candidate_ids = self._atm_translator.get_target_ids(
|
| 844 |
+
assistant_input_ids, target_input_ids, self._prev_assistant_ids
|
| 845 |
+
)
|
| 846 |
+
self._target_seq_len_with_candidates = target_candidate_ids.shape[-1]
|
| 847 |
+
target_candidate_logits = self._atm_translator.get_target_logits(assistant_candidate_logits)
|
| 848 |
+
|
| 849 |
+
return target_candidate_ids, target_candidate_logits
|
| 850 |
+
|
| 851 |
+
def _update_past_and_masks(self, assistant_input_ids: torch.LongTensor, num_added_tokens: int = 1) -> bool:
|
| 852 |
+
if self._prev_assistant_ids is None:
|
| 853 |
+
# Prepare attention mask for the first generation.
|
| 854 |
+
# For subsequent generations, the attention mask is updated in super()_update_past_and_masks.
|
| 855 |
+
self.assistant_kwargs = _prepare_attention_mask(
|
| 856 |
+
self.assistant_kwargs, assistant_input_ids.shape[-1], self.assistant_model.config.is_encoder_decoder
|
| 857 |
+
)
|
| 858 |
+
return super()._update_past_and_masks(assistant_input_ids, num_added_tokens=num_added_tokens)
|
| 859 |
+
|
| 860 |
+
def _prepare_assistant_input_ids(self, target_input_ids: torch.LongTensor) -> torch.LongTensor:
|
| 861 |
+
"""
|
| 862 |
+
Simplified token conversion that only processes new tokens.
|
| 863 |
+
"""
|
| 864 |
+
# Calculate new tokens since last call
|
| 865 |
+
target_seq_len = target_input_ids.shape[-1]
|
| 866 |
+
if self._target_seq_len_with_candidates == 0:
|
| 867 |
+
new_token_count = target_seq_len
|
| 868 |
+
else:
|
| 869 |
+
new_token_count = 1
|
| 870 |
+
target_new_ids = target_input_ids[:, -new_token_count:]
|
| 871 |
+
|
| 872 |
+
# Convert the new tokens
|
| 873 |
+
assistant_new_ids = None
|
| 874 |
+
if self._target_seq_len_with_candidates > 0:
|
| 875 |
+
# we have only one new token and we can directly convert it
|
| 876 |
+
assistant_new_ids = self._atm_translator.target_to_assistant_input_ids.get(target_new_ids[0].item())
|
| 877 |
+
if assistant_new_ids is None:
|
| 878 |
+
target_new_text = self.target_tokenizer.batch_decode(
|
| 879 |
+
target_new_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
|
| 880 |
+
)
|
| 881 |
+
assistant_new_ids = self.assistant_tokenizer(
|
| 882 |
+
target_new_text, add_special_tokens=False, return_tensors="pt"
|
| 883 |
+
)["input_ids"].to(self.assistant_model.device)
|
| 884 |
+
else:
|
| 885 |
+
assistant_new_ids = torch.tensor([[assistant_new_ids]], device=self.assistant_model.device)
|
| 886 |
+
|
| 887 |
+
# Update or initialize assistant IDs
|
| 888 |
+
if self._prev_assistant_ids is None:
|
| 889 |
+
assistant_input_ids = assistant_new_ids
|
| 890 |
+
else:
|
| 891 |
+
tokens_to_remove = self._target_seq_len_with_candidates + 1 - target_seq_len
|
| 892 |
+
# If the number of new tokens is greater than zero, truncate the previous assistant IDs
|
| 893 |
+
if tokens_to_remove > 0:
|
| 894 |
+
self._prev_assistant_ids = self._prev_assistant_ids[:, :-tokens_to_remove]
|
| 895 |
+
assistant_input_ids = torch.cat([self._prev_assistant_ids, assistant_new_ids], dim=-1)
|
| 896 |
+
assistant_input_ids = assistant_input_ids.to(dtype=torch.long)
|
| 897 |
+
|
| 898 |
+
return assistant_input_ids, len(assistant_new_ids[0])
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
class PromptLookupCandidateGenerator(CandidateGenerator):
|
| 902 |
+
"""
|
| 903 |
+
`CandidateGenerator` class to be used for prompt lookup generation. This class generates candidates by looking up
|
| 904 |
+
likely continuations in the provided prompt (input_ids) itself.
|
| 905 |
+
Read the following blog post for more information: https://github.com/apoorvumang/prompt-lookup-decoding
|
| 906 |
+
|
| 907 |
+
Args:
|
| 908 |
+
max_matching_ngram_size (`int`):
|
| 909 |
+
The maximum ngram size to be considered for matching in the prompt
|
| 910 |
+
num_output_tokens (`int`):
|
| 911 |
+
The number of tokens to be output as candidate tokens.
|
| 912 |
+
max_length (`int`):
|
| 913 |
+
The number of total maximum tokens that can be generated. For decoder-only models that includes the prompt length.
|
| 914 |
+
Defaults to 20, which is the max length used as default in generation config.
|
| 915 |
+
"""
|
| 916 |
+
|
| 917 |
+
def __init__(
|
| 918 |
+
self,
|
| 919 |
+
eos_token_id: Optional[torch.Tensor] = None,
|
| 920 |
+
num_output_tokens: int = 10,
|
| 921 |
+
max_matching_ngram_size: Optional[int] = None,
|
| 922 |
+
max_length: int = 20,
|
| 923 |
+
):
|
| 924 |
+
self.num_output_tokens = num_output_tokens
|
| 925 |
+
self.max_matching_ngram_size = max_matching_ngram_size if max_matching_ngram_size else 2
|
| 926 |
+
self.max_length = max_length
|
| 927 |
+
self.eos_token_id = eos_token_id
|
| 928 |
+
|
| 929 |
+
if self.max_matching_ngram_size <= 0 or self.num_output_tokens <= 0:
|
| 930 |
+
raise ValueError("Invalid max_matching_ngram_size or num_output_tokens")
|
| 931 |
+
|
| 932 |
+
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
|
| 933 |
+
"""
|
| 934 |
+
Fetches the candidates to be tried for the current input.
|
| 935 |
+
|
| 936 |
+
Args:
|
| 937 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 938 |
+
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
|
| 939 |
+
|
| 940 |
+
Return:
|
| 941 |
+
`torch.LongTensor` of shape `(num_candidates, candidate_length)`: The candidate sequences to be tried.
|
| 942 |
+
"""
|
| 943 |
+
input_length = input_ids.size(1)
|
| 944 |
+
|
| 945 |
+
# Don't generate more than `max_length - 1` candidates since the target model generates one extra token.
|
| 946 |
+
if self.max_length == input_length + 1:
|
| 947 |
+
return input_ids, None
|
| 948 |
+
|
| 949 |
+
chosen_ids = None
|
| 950 |
+
match_found = False
|
| 951 |
+
for ngram_size in range(min(self.max_matching_ngram_size, input_length - 1), 0, -1):
|
| 952 |
+
# Create sliding windows of size ngram_size
|
| 953 |
+
windows = input_ids.unfold(dimension=1, size=ngram_size, step=1)
|
| 954 |
+
|
| 955 |
+
# Convert ngram to a tensor for comparison
|
| 956 |
+
ngram_tensor = input_ids[0, -ngram_size:]
|
| 957 |
+
|
| 958 |
+
# Find where the windows match the ngram
|
| 959 |
+
matches = (windows == ngram_tensor).all(dim=2)
|
| 960 |
+
|
| 961 |
+
# Get the indices of matches
|
| 962 |
+
match_indices = matches.nonzero(as_tuple=True)[1]
|
| 963 |
+
|
| 964 |
+
# Iterate through match indices to find a valid continuation
|
| 965 |
+
for idx in match_indices:
|
| 966 |
+
start_idx = idx + ngram_size
|
| 967 |
+
end_idx = start_idx + self.num_output_tokens
|
| 968 |
+
end_idx = min(end_idx, input_length, self.max_length)
|
| 969 |
+
|
| 970 |
+
if start_idx < end_idx:
|
| 971 |
+
chosen_ids = input_ids[0, start_idx:end_idx]
|
| 972 |
+
match_found = True
|
| 973 |
+
|
| 974 |
+
# remove remaining candidate ids if an "eos" token is found, otherwise the target model may
|
| 975 |
+
# accept eos and the rest as valid, thus not stopping generation after "eos"
|
| 976 |
+
# NOTE: below code is written based on the fact that assisted decoding supports only bs=1
|
| 977 |
+
mask = isin_mps_friendly(chosen_ids, self.eos_token_id)
|
| 978 |
+
match_indices_eos = torch.nonzero(mask)
|
| 979 |
+
if match_indices_eos.numel() > 0:
|
| 980 |
+
first_eos_index = match_indices_eos[0].item()
|
| 981 |
+
chosen_ids = chosen_ids[:first_eos_index]
|
| 982 |
+
break
|
| 983 |
+
if match_found:
|
| 984 |
+
break
|
| 985 |
+
|
| 986 |
+
if chosen_ids is None or len(chosen_ids) == 0:
|
| 987 |
+
# In case we didn't find a match return the input sequence unchanged, reverts back to autoregressive decoding
|
| 988 |
+
return input_ids, None
|
| 989 |
+
|
| 990 |
+
# Now need extend input_ids with chosen_ids
|
| 991 |
+
chosen_ids = chosen_ids.unsqueeze(0)
|
| 992 |
+
candidate_input_ids = torch.cat((input_ids, chosen_ids), dim=1)
|
| 993 |
+
# assisted_generation expects logits as well, but we don't have those here, so returning None
|
| 994 |
+
return candidate_input_ids, None
|
| 995 |
+
|
| 996 |
+
def update_candidate_strategy(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, num_matches: int):
|
| 997 |
+
"""
|
| 998 |
+
Updates the candidate generation strategy based on the outcomes.
|
| 999 |
+
|
| 1000 |
+
Args:
|
| 1001 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1002 |
+
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
|
| 1003 |
+
scores (`torch.FloatTensor` of shape `(batch_size, candidate_length, config.vocab_size)`):
|
| 1004 |
+
Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
|
| 1005 |
+
beam search or log softmax for each vocabulary token when using beam search
|
| 1006 |
+
num_matches (`int`):
|
| 1007 |
+
The number of matches between the candidate sequences and the model predictions.
|
| 1008 |
+
"""
|
| 1009 |
+
# Currently does nothing
|
| 1010 |
+
return
|
| 1011 |
+
|
| 1012 |
+
|
| 1013 |
+
class EarlyExitCandidateGenerator(AssistedCandidateGenerator):
|
| 1014 |
+
"""
|
| 1015 |
+
`CandidateGenerator` class to be used for assisted generation and speculative decoding. This class generates
|
| 1016 |
+
candidates through the use of **the model itself**, exiting early. Can only be used with models that support early
|
| 1017 |
+
exit, e.g., `facebook/layerskip-llama3.2-1B`.
|
| 1018 |
+
|
| 1019 |
+
Args:
|
| 1020 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1021 |
+
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
|
| 1022 |
+
assistant_model (`PreTrainedModel`):
|
| 1023 |
+
The original model. This model must support early exit (i.e. is trained to compute logits in earlier
|
| 1024 |
+
layers).
|
| 1025 |
+
generation_config (`~generation.GenerationConfig`, *optional*):
|
| 1026 |
+
The generation configuration to be used as base parametrization for the generation call.
|
| 1027 |
+
logits_processor (`LogitsProcessorList`):
|
| 1028 |
+
An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
|
| 1029 |
+
used to modify the prediction scores of the language modeling head applied at each generation step.
|
| 1030 |
+
model_kwargs (`Dict`):
|
| 1031 |
+
The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant
|
| 1032 |
+
model as well.
|
| 1033 |
+
inputs_tensor (`torch.Tensor`, *optional*):
|
| 1034 |
+
The model input tensor. In encoder-decoder models, this is the encoder input.
|
| 1035 |
+
"""
|
| 1036 |
+
|
| 1037 |
+
def __init__(
|
| 1038 |
+
self,
|
| 1039 |
+
input_ids: torch.LongTensor,
|
| 1040 |
+
assistant_model: "PreTrainedModel",
|
| 1041 |
+
generation_config: "GenerationConfig",
|
| 1042 |
+
model_kwargs: Dict,
|
| 1043 |
+
inputs_tensor: Optional[torch.Tensor] = None,
|
| 1044 |
+
logits_processor: "LogitsProcessorList" = None,
|
| 1045 |
+
):
|
| 1046 |
+
super().__init__(
|
| 1047 |
+
input_ids=input_ids,
|
| 1048 |
+
assistant_model=assistant_model,
|
| 1049 |
+
generation_config=generation_config,
|
| 1050 |
+
model_kwargs=model_kwargs,
|
| 1051 |
+
inputs_tensor=inputs_tensor,
|
| 1052 |
+
logits_processor=logits_processor,
|
| 1053 |
+
)
|
| 1054 |
+
# We have to move early exit out of the generation config, otherwise the assistant will also call `generate`
|
| 1055 |
+
# with early exit
|
| 1056 |
+
self.assistant_early_exit = self.generation_config.assistant_early_exit
|
| 1057 |
+
self.generation_config.assistant_early_exit = None
|
| 1058 |
+
|
| 1059 |
+
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
|
| 1060 |
+
# Temporarily sets the number of hidden layers to the early exit value
|
| 1061 |
+
base_model = getattr(self.assistant_model, self.assistant_model.base_model_prefix)
|
| 1062 |
+
original_num_hidden_layers = base_model.config.num_hidden_layers
|
| 1063 |
+
base_model.config.num_hidden_layers = self.assistant_early_exit
|
| 1064 |
+
candidate_ids, candidate_logits = super().get_candidates(input_ids)
|
| 1065 |
+
base_model.config.num_hidden_layers = original_num_hidden_layers
|
| 1066 |
+
return candidate_ids, candidate_logits
|
| 1067 |
+
|
| 1068 |
+
|
| 1069 |
+
def _crop_past_key_values(model, past_key_values, max_length):
|
| 1070 |
+
"""Crops the past key values up to a certain maximum length."""
|
| 1071 |
+
new_past = []
|
| 1072 |
+
if model.config.is_encoder_decoder:
|
| 1073 |
+
for idx in range(len(past_key_values)):
|
| 1074 |
+
new_past.append(
|
| 1075 |
+
(
|
| 1076 |
+
past_key_values[idx][0][:, :, :max_length, :],
|
| 1077 |
+
past_key_values[idx][1][:, :, :max_length, :],
|
| 1078 |
+
past_key_values[idx][2],
|
| 1079 |
+
past_key_values[idx][3],
|
| 1080 |
+
)
|
| 1081 |
+
)
|
| 1082 |
+
past_key_values = tuple(new_past)
|
| 1083 |
+
# gptbigcode is special and stores kv in shape (batch_size, seq_len, dim), if it's a multi_query model
|
| 1084 |
+
elif "gptbigcode" in model.__class__.__name__.lower() or (
|
| 1085 |
+
model.config.architectures is not None and "gptbigcode" in model.config.architectures[0].lower()
|
| 1086 |
+
):
|
| 1087 |
+
if model.config.multi_query:
|
| 1088 |
+
for idx in range(len(past_key_values)):
|
| 1089 |
+
past_key_values[idx] = past_key_values[idx][:, :max_length, :]
|
| 1090 |
+
else:
|
| 1091 |
+
for idx in range(len(past_key_values)):
|
| 1092 |
+
past_key_values[idx] = past_key_values[idx][:, :, :max_length, :]
|
| 1093 |
+
elif isinstance(past_key_values, DynamicCache):
|
| 1094 |
+
past_key_values.crop(max_length)
|
| 1095 |
+
elif past_key_values is not None:
|
| 1096 |
+
for idx in range(len(past_key_values)):
|
| 1097 |
+
if past_key_values[idx] != ([], []):
|
| 1098 |
+
new_past.append(
|
| 1099 |
+
(
|
| 1100 |
+
past_key_values[idx][0][:, :, :max_length, :],
|
| 1101 |
+
past_key_values[idx][1][:, :, :max_length, :],
|
| 1102 |
+
)
|
| 1103 |
+
)
|
| 1104 |
+
else:
|
| 1105 |
+
new_past.append((past_key_values[idx][0], past_key_values[idx][1]))
|
| 1106 |
+
past_key_values = tuple(new_past)
|
| 1107 |
+
return past_key_values
|
| 1108 |
+
|
| 1109 |
+
|
| 1110 |
+
def _prepare_attention_mask(model_kwargs: Dict[str, Any], new_length: int, is_encoder_decoder: bool) -> Dict[str, Any]:
|
| 1111 |
+
"""Expands or crops the model's mask for decoding purposes, to the defined length"""
|
| 1112 |
+
|
| 1113 |
+
mask_key = "decoder_attention_mask" if is_encoder_decoder else "attention_mask"
|
| 1114 |
+
if mask_key not in model_kwargs:
|
| 1115 |
+
return model_kwargs
|
| 1116 |
+
|
| 1117 |
+
mask = model_kwargs[mask_key]
|
| 1118 |
+
mask_length_diff = new_length - mask.shape[1]
|
| 1119 |
+
|
| 1120 |
+
if mask_length_diff < 0:
|
| 1121 |
+
model_kwargs[mask_key] = mask[:, :mask_length_diff]
|
| 1122 |
+
elif mask_length_diff > 0:
|
| 1123 |
+
model_kwargs[mask_key] = torch.cat([mask, mask.new_ones((mask.shape[0], mask_length_diff))], dim=-1)
|
| 1124 |
+
|
| 1125 |
+
# Handle cross attention models
|
| 1126 |
+
if "cross_attention_mask" in model_kwargs:
|
| 1127 |
+
# Mllama case
|
| 1128 |
+
cross_mask = model_kwargs["cross_attention_mask"]
|
| 1129 |
+
if mask_length_diff < 0:
|
| 1130 |
+
model_kwargs["cross_attention_mask"] = cross_mask[:, :mask_length_diff]
|
| 1131 |
+
elif mask_length_diff > 0:
|
| 1132 |
+
new_mask = cross_mask[:, -1:, :, :].repeat(1, mask_length_diff, 1, 1)
|
| 1133 |
+
model_kwargs["cross_attention_mask"] = torch.cat([cross_mask, new_mask], dim=1)
|
| 1134 |
+
elif "image_attention_mask" in model_kwargs:
|
| 1135 |
+
# IDEFICS case
|
| 1136 |
+
cross_mask = model_kwargs["image_attention_mask"]
|
| 1137 |
+
if mask_length_diff < 0:
|
| 1138 |
+
model_kwargs["image_attention_mask"] = cross_mask[:, :mask_length_diff]
|
| 1139 |
+
elif mask_length_diff > 0:
|
| 1140 |
+
new_mask = cross_mask[:, -1:, :].repeat(1, mask_length_diff, 1)
|
| 1141 |
+
model_kwargs["image_attention_mask"] = torch.cat([cross_mask, new_mask], dim=1)
|
| 1142 |
+
|
| 1143 |
+
return model_kwargs
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
def _prepare_token_type_ids(model_kwargs: Dict[str, Any], new_length: int) -> Dict[str, Any]:
|
| 1147 |
+
"""Expands or crops the model's token_type_ids for decoding purposes, to the defined length"""
|
| 1148 |
+
if "token_type_ids" not in model_kwargs or model_kwargs["token_type_ids"] is None:
|
| 1149 |
+
return model_kwargs
|
| 1150 |
+
|
| 1151 |
+
token_type_ids = model_kwargs["token_type_ids"]
|
| 1152 |
+
final_token_type = token_type_ids[:, -1].unsqueeze(-1)
|
| 1153 |
+
type_length_diff = new_length - token_type_ids.shape[1]
|
| 1154 |
+
|
| 1155 |
+
if type_length_diff < 0:
|
| 1156 |
+
token_type_ids = token_type_ids[:, :type_length_diff]
|
| 1157 |
+
elif type_length_diff > 0:
|
| 1158 |
+
token_type_copies = final_token_type.repeat(1, type_length_diff)
|
| 1159 |
+
model_kwargs["token_type_ids"] = torch.cat([model_kwargs["token_type_ids"], token_type_copies], dim=-1)
|
| 1160 |
+
return model_kwargs
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/chat_template_utils.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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yright 2024 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 inspect
|
| 16 |
+
import json
|
| 17 |
+
import re
|
| 18 |
+
import types
|
| 19 |
+
from contextlib import contextmanager
|
| 20 |
+
from datetime import datetime
|
| 21 |
+
from functools import lru_cache
|
| 22 |
+
from typing import Any, Callable, Optional, Union, get_args, get_origin, get_type_hints
|
| 23 |
+
|
| 24 |
+
from packaging import version
|
| 25 |
+
|
| 26 |
+
from .import_utils import is_jinja_available, is_torch_available, is_vision_available
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_jinja_available():
|
| 30 |
+
import jinja2
|
| 31 |
+
from jinja2.ext import Extension
|
| 32 |
+
from jinja2.sandbox import ImmutableSandboxedEnvironment
|
| 33 |
+
else:
|
| 34 |
+
jinja2 = None
|
| 35 |
+
|
| 36 |
+
if is_vision_available():
|
| 37 |
+
from PIL.Image import Image
|
| 38 |
+
|
| 39 |
+
if is_torch_available():
|
| 40 |
+
from torch import Tensor
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
BASIC_TYPES = (int, float, str, bool, Any, type(None), ...)
|
| 44 |
+
# Extracts the initial segment of the docstring, containing the function description
|
| 45 |
+
description_re = re.compile(r"^(.*?)[\n\s]*(Args:|Returns:|Raises:|\Z)", re.DOTALL)
|
| 46 |
+
# Extracts the Args: block from the docstring
|
| 47 |
+
args_re = re.compile(r"\n\s*Args:\n\s*(.*?)[\n\s]*(Returns:|Raises:|\Z)", re.DOTALL)
|
| 48 |
+
# Splits the Args: block into individual arguments
|
| 49 |
+
args_split_re = re.compile(
|
| 50 |
+
r"""
|
| 51 |
+
(?:^|\n) # Match the start of the args block, or a newline
|
| 52 |
+
\s*(\w+):\s* # Capture the argument name and strip spacing
|
| 53 |
+
(.*?)\s* # Capture the argument description, which can span multiple lines, and strip trailing spacing
|
| 54 |
+
(?=\n\s*\w+:|\Z) # Stop when you hit the next argument or the end of the block
|
| 55 |
+
""",
|
| 56 |
+
re.DOTALL | re.VERBOSE,
|
| 57 |
+
)
|
| 58 |
+
# Extracts the Returns: block from the docstring, if present. Note that most chat templates ignore the return type/doc!
|
| 59 |
+
returns_re = re.compile(r"\n\s*Returns:\n\s*(.*?)[\n\s]*(Raises:|\Z)", re.DOTALL)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class TypeHintParsingException(Exception):
|
| 63 |
+
"""Exception raised for errors in parsing type hints to generate JSON schemas"""
|
| 64 |
+
|
| 65 |
+
pass
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class DocstringParsingException(Exception):
|
| 69 |
+
"""Exception raised for errors in parsing docstrings to generate JSON schemas"""
|
| 70 |
+
|
| 71 |
+
pass
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _get_json_schema_type(param_type: str) -> dict[str, str]:
|
| 75 |
+
type_mapping = {
|
| 76 |
+
int: {"type": "integer"},
|
| 77 |
+
float: {"type": "number"},
|
| 78 |
+
str: {"type": "string"},
|
| 79 |
+
bool: {"type": "boolean"},
|
| 80 |
+
type(None): {"type": "null"},
|
| 81 |
+
Any: {},
|
| 82 |
+
}
|
| 83 |
+
if is_vision_available():
|
| 84 |
+
type_mapping[Image] = {"type": "image"}
|
| 85 |
+
if is_torch_available():
|
| 86 |
+
type_mapping[Tensor] = {"type": "audio"}
|
| 87 |
+
return type_mapping.get(param_type, {"type": "object"})
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _parse_type_hint(hint: str) -> dict:
|
| 91 |
+
origin = get_origin(hint)
|
| 92 |
+
args = get_args(hint)
|
| 93 |
+
|
| 94 |
+
if origin is None:
|
| 95 |
+
try:
|
| 96 |
+
return _get_json_schema_type(hint)
|
| 97 |
+
except KeyError:
|
| 98 |
+
raise TypeHintParsingException(
|
| 99 |
+
"Couldn't parse this type hint, likely due to a custom class or object: ", hint
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
elif origin is Union or (hasattr(types, "UnionType") and origin is types.UnionType):
|
| 103 |
+
# Recurse into each of the subtypes in the Union, except None, which is handled separately at the end
|
| 104 |
+
subtypes = [_parse_type_hint(t) for t in args if t is not type(None)]
|
| 105 |
+
if len(subtypes) == 1:
|
| 106 |
+
# A single non-null type can be expressed directly
|
| 107 |
+
return_dict = subtypes[0]
|
| 108 |
+
elif all(isinstance(subtype["type"], str) for subtype in subtypes):
|
| 109 |
+
# A union of basic types can be expressed as a list in the schema
|
| 110 |
+
return_dict = {"type": sorted([subtype["type"] for subtype in subtypes])}
|
| 111 |
+
else:
|
| 112 |
+
# A union of more complex types requires "anyOf"
|
| 113 |
+
return_dict = {"anyOf": subtypes}
|
| 114 |
+
if type(None) in args:
|
| 115 |
+
return_dict["nullable"] = True
|
| 116 |
+
return return_dict
|
| 117 |
+
|
| 118 |
+
elif origin is list:
|
| 119 |
+
if not args:
|
| 120 |
+
return {"type": "array"}
|
| 121 |
+
else:
|
| 122 |
+
# Lists can only have a single type argument, so recurse into it
|
| 123 |
+
return {"type": "array", "items": _parse_type_hint(args[0])}
|
| 124 |
+
|
| 125 |
+
elif origin is tuple:
|
| 126 |
+
if not args:
|
| 127 |
+
return {"type": "array"}
|
| 128 |
+
if len(args) == 1:
|
| 129 |
+
raise TypeHintParsingException(
|
| 130 |
+
f"The type hint {str(hint).replace('typing.', '')} is a Tuple with a single element, which "
|
| 131 |
+
"we do not automatically convert to JSON schema as it is rarely necessary. If this input can contain "
|
| 132 |
+
"more than one element, we recommend "
|
| 133 |
+
"using a List[] type instead, or if it really is a single element, remove the Tuple[] wrapper and just "
|
| 134 |
+
"pass the element directly."
|
| 135 |
+
)
|
| 136 |
+
if ... in args:
|
| 137 |
+
raise TypeHintParsingException(
|
| 138 |
+
"Conversion of '...' is not supported in Tuple type hints. "
|
| 139 |
+
"Use List[] types for variable-length"
|
| 140 |
+
" inputs instead."
|
| 141 |
+
)
|
| 142 |
+
return {"type": "array", "prefixItems": [_parse_type_hint(t) for t in args]}
|
| 143 |
+
|
| 144 |
+
elif origin is dict:
|
| 145 |
+
# The JSON equivalent to a dict is 'object', which mandates that all keys are strings
|
| 146 |
+
# However, we can specify the type of the dict values with "additionalProperties"
|
| 147 |
+
out = {"type": "object"}
|
| 148 |
+
if len(args) == 2:
|
| 149 |
+
out["additionalProperties"] = _parse_type_hint(args[1])
|
| 150 |
+
return out
|
| 151 |
+
|
| 152 |
+
raise TypeHintParsingException("Couldn't parse this type hint, likely due to a custom class or object: ", hint)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _convert_type_hints_to_json_schema(func: Callable) -> dict:
|
| 156 |
+
type_hints = get_type_hints(func)
|
| 157 |
+
signature = inspect.signature(func)
|
| 158 |
+
required = []
|
| 159 |
+
for param_name, param in signature.parameters.items():
|
| 160 |
+
if param.annotation == inspect.Parameter.empty:
|
| 161 |
+
raise TypeHintParsingException(f"Argument {param.name} is missing a type hint in function {func.__name__}")
|
| 162 |
+
if param.default == inspect.Parameter.empty:
|
| 163 |
+
required.append(param_name)
|
| 164 |
+
|
| 165 |
+
properties = {}
|
| 166 |
+
for param_name, param_type in type_hints.items():
|
| 167 |
+
properties[param_name] = _parse_type_hint(param_type)
|
| 168 |
+
|
| 169 |
+
schema = {"type": "object", "properties": properties}
|
| 170 |
+
if required:
|
| 171 |
+
schema["required"] = required
|
| 172 |
+
|
| 173 |
+
return schema
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def parse_google_format_docstring(docstring: str) -> tuple[Optional[str], Optional[dict], Optional[str]]:
|
| 177 |
+
"""
|
| 178 |
+
Parses a Google-style docstring to extract the function description,
|
| 179 |
+
argument descriptions, and return description.
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
docstring (str): The docstring to parse.
|
| 183 |
+
|
| 184 |
+
Returns:
|
| 185 |
+
The function description, arguments, and return description.
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
# Extract the sections
|
| 189 |
+
description_match = description_re.search(docstring)
|
| 190 |
+
args_match = args_re.search(docstring)
|
| 191 |
+
returns_match = returns_re.search(docstring)
|
| 192 |
+
|
| 193 |
+
# Clean and store the sections
|
| 194 |
+
description = description_match.group(1).strip() if description_match else None
|
| 195 |
+
docstring_args = args_match.group(1).strip() if args_match else None
|
| 196 |
+
returns = returns_match.group(1).strip() if returns_match else None
|
| 197 |
+
|
| 198 |
+
# Parsing the arguments into a dictionary
|
| 199 |
+
if docstring_args is not None:
|
| 200 |
+
docstring_args = "\n".join([line for line in docstring_args.split("\n") if line.strip()]) # Remove blank lines
|
| 201 |
+
matches = args_split_re.findall(docstring_args)
|
| 202 |
+
args_dict = {match[0]: re.sub(r"\s*\n+\s*", " ", match[1].strip()) for match in matches}
|
| 203 |
+
else:
|
| 204 |
+
args_dict = {}
|
| 205 |
+
|
| 206 |
+
return description, args_dict, returns
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def get_json_schema(func: Callable) -> dict:
|
| 210 |
+
"""
|
| 211 |
+
This function generates a JSON schema for a given function, based on its docstring and type hints. This is
|
| 212 |
+
mostly used for passing lists of tools to a chat template. The JSON schema contains the name and description of
|
| 213 |
+
the function, as well as the names, types and descriptions for each of its arguments. `get_json_schema()` requires
|
| 214 |
+
that the function has a docstring, and that each argument has a description in the docstring, in the standard
|
| 215 |
+
Google docstring format shown below. It also requires that all the function arguments have a valid Python type hint.
|
| 216 |
+
|
| 217 |
+
Although it is not required, a `Returns` block can also be added, which will be included in the schema. This is
|
| 218 |
+
optional because most chat templates ignore the return value of the function.
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
func: The function to generate a JSON schema for.
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
A dictionary containing the JSON schema for the function.
|
| 225 |
+
|
| 226 |
+
Examples:
|
| 227 |
+
```python
|
| 228 |
+
>>> def multiply(x: float, y: float):
|
| 229 |
+
>>> '''
|
| 230 |
+
>>> A function that multiplies two numbers
|
| 231 |
+
>>>
|
| 232 |
+
>>> Args:
|
| 233 |
+
>>> x: The first number to multiply
|
| 234 |
+
>>> y: The second number to multiply
|
| 235 |
+
>>> '''
|
| 236 |
+
>>> return x * y
|
| 237 |
+
>>>
|
| 238 |
+
>>> print(get_json_schema(multiply))
|
| 239 |
+
{
|
| 240 |
+
"name": "multiply",
|
| 241 |
+
"description": "A function that multiplies two numbers",
|
| 242 |
+
"parameters": {
|
| 243 |
+
"type": "object",
|
| 244 |
+
"properties": {
|
| 245 |
+
"x": {"type": "number", "description": "The first number to multiply"},
|
| 246 |
+
"y": {"type": "number", "description": "The second number to multiply"}
|
| 247 |
+
},
|
| 248 |
+
"required": ["x", "y"]
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
```
|
| 252 |
+
|
| 253 |
+
The general use for these schemas is that they are used to generate tool descriptions for chat templates that
|
| 254 |
+
support them, like so:
|
| 255 |
+
|
| 256 |
+
```python
|
| 257 |
+
>>> from transformers import AutoTokenizer
|
| 258 |
+
>>> from transformers.utils import get_json_schema
|
| 259 |
+
>>>
|
| 260 |
+
>>> def multiply(x: float, y: float):
|
| 261 |
+
>>> '''
|
| 262 |
+
>>> A function that multiplies two numbers
|
| 263 |
+
>>>
|
| 264 |
+
>>> Args:
|
| 265 |
+
>>> x: The first number to multiply
|
| 266 |
+
>>> y: The second number to multiply
|
| 267 |
+
>>> return x * y
|
| 268 |
+
>>> '''
|
| 269 |
+
>>>
|
| 270 |
+
>>> multiply_schema = get_json_schema(multiply)
|
| 271 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
|
| 272 |
+
>>> messages = [{"role": "user", "content": "What is 179 x 4571?"}]
|
| 273 |
+
>>> formatted_chat = tokenizer.apply_chat_template(
|
| 274 |
+
>>> messages,
|
| 275 |
+
>>> tools=[multiply_schema],
|
| 276 |
+
>>> chat_template="tool_use",
|
| 277 |
+
>>> return_dict=True,
|
| 278 |
+
>>> return_tensors="pt",
|
| 279 |
+
>>> add_generation_prompt=True
|
| 280 |
+
>>> )
|
| 281 |
+
>>> # The formatted chat can now be passed to model.generate()
|
| 282 |
+
```
|
| 283 |
+
|
| 284 |
+
Each argument description can also have an optional `(choices: ...)` block at the end, such as
|
| 285 |
+
`(choices: ["tea", "coffee"])`, which will be parsed into an `enum` field in the schema. Note that this will
|
| 286 |
+
only be parsed correctly if it is at the end of the line:
|
| 287 |
+
|
| 288 |
+
```python
|
| 289 |
+
>>> def drink_beverage(beverage: str):
|
| 290 |
+
>>> '''
|
| 291 |
+
>>> A function that drinks a beverage
|
| 292 |
+
>>>
|
| 293 |
+
>>> Args:
|
| 294 |
+
>>> beverage: The beverage to drink (choices: ["tea", "coffee"])
|
| 295 |
+
>>> '''
|
| 296 |
+
>>> pass
|
| 297 |
+
>>>
|
| 298 |
+
>>> print(get_json_schema(drink_beverage))
|
| 299 |
+
```
|
| 300 |
+
{
|
| 301 |
+
'name': 'drink_beverage',
|
| 302 |
+
'description': 'A function that drinks a beverage',
|
| 303 |
+
'parameters': {
|
| 304 |
+
'type': 'object',
|
| 305 |
+
'properties': {
|
| 306 |
+
'beverage': {
|
| 307 |
+
'type': 'string',
|
| 308 |
+
'enum': ['tea', 'coffee'],
|
| 309 |
+
'description': 'The beverage to drink'
|
| 310 |
+
}
|
| 311 |
+
},
|
| 312 |
+
'required': ['beverage']
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
"""
|
| 316 |
+
doc = inspect.getdoc(func)
|
| 317 |
+
if not doc:
|
| 318 |
+
raise DocstringParsingException(
|
| 319 |
+
f"Cannot generate JSON schema for {func.__name__} because it has no docstring!"
|
| 320 |
+
)
|
| 321 |
+
doc = doc.strip()
|
| 322 |
+
main_doc, param_descriptions, return_doc = parse_google_format_docstring(doc)
|
| 323 |
+
|
| 324 |
+
json_schema = _convert_type_hints_to_json_schema(func)
|
| 325 |
+
if (return_dict := json_schema["properties"].pop("return", None)) is not None:
|
| 326 |
+
if return_doc is not None: # We allow a missing return docstring since most templates ignore it
|
| 327 |
+
return_dict["description"] = return_doc
|
| 328 |
+
for arg, schema in json_schema["properties"].items():
|
| 329 |
+
if arg not in param_descriptions:
|
| 330 |
+
raise DocstringParsingException(
|
| 331 |
+
f"Cannot generate JSON schema for {func.__name__} because the docstring has no description for the argument '{arg}'"
|
| 332 |
+
)
|
| 333 |
+
desc = param_descriptions[arg]
|
| 334 |
+
enum_choices = re.search(r"\(choices:\s*(.*?)\)\s*$", desc, flags=re.IGNORECASE)
|
| 335 |
+
if enum_choices:
|
| 336 |
+
schema["enum"] = [c.strip() for c in json.loads(enum_choices.group(1))]
|
| 337 |
+
desc = enum_choices.string[: enum_choices.start()].strip()
|
| 338 |
+
schema["description"] = desc
|
| 339 |
+
|
| 340 |
+
output = {"name": func.__name__, "description": main_doc, "parameters": json_schema}
|
| 341 |
+
if return_dict is not None:
|
| 342 |
+
output["return"] = return_dict
|
| 343 |
+
return {"type": "function", "function": output}
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def _render_with_assistant_indices(
|
| 347 |
+
compiled_template, messages, tools, documents, add_generation_prompt, **template_kwargs
|
| 348 |
+
):
|
| 349 |
+
rendered_blocks = []
|
| 350 |
+
generation_indices = []
|
| 351 |
+
with compiled_template.environment.activate_tracker(rendered_blocks, generation_indices):
|
| 352 |
+
for block in compiled_template.generate(
|
| 353 |
+
messages=messages,
|
| 354 |
+
tools=tools,
|
| 355 |
+
documents=documents,
|
| 356 |
+
add_generation_prompt=add_generation_prompt,
|
| 357 |
+
**template_kwargs,
|
| 358 |
+
):
|
| 359 |
+
rendered_blocks.append(block)
|
| 360 |
+
rendered_chat = "".join(rendered_blocks)
|
| 361 |
+
return rendered_chat, generation_indices
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
@lru_cache
|
| 365 |
+
def _compile_jinja_template(chat_template):
|
| 366 |
+
if not is_jinja_available():
|
| 367 |
+
raise ImportError(
|
| 368 |
+
"apply_chat_template requires jinja2 to be installed. Please install it using `pip install jinja2`."
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
class AssistantTracker(Extension):
|
| 372 |
+
# This extension is used to track the indices of assistant-generated tokens in the rendered chat
|
| 373 |
+
tags = {"generation"}
|
| 374 |
+
|
| 375 |
+
def __init__(self, environment: ImmutableSandboxedEnvironment):
|
| 376 |
+
# The class is only initiated by jinja.
|
| 377 |
+
super().__init__(environment)
|
| 378 |
+
environment.extend(activate_tracker=self.activate_tracker)
|
| 379 |
+
self._rendered_blocks = None
|
| 380 |
+
self._generation_indices = None
|
| 381 |
+
|
| 382 |
+
def parse(self, parser: jinja2.parser.Parser) -> jinja2.nodes.CallBlock:
|
| 383 |
+
lineno = next(parser.stream).lineno
|
| 384 |
+
body = parser.parse_statements(["name:endgeneration"], drop_needle=True)
|
| 385 |
+
return jinja2.nodes.CallBlock(self.call_method("_generation_support"), [], [], body).set_lineno(lineno)
|
| 386 |
+
|
| 387 |
+
@jinja2.pass_eval_context
|
| 388 |
+
def _generation_support(self, context: jinja2.nodes.EvalContext, caller: jinja2.runtime.Macro) -> str:
|
| 389 |
+
rv = caller()
|
| 390 |
+
if self.is_active():
|
| 391 |
+
# Only track generation indices if the tracker is active
|
| 392 |
+
start_index = len("".join(self._rendered_blocks))
|
| 393 |
+
end_index = start_index + len(rv)
|
| 394 |
+
self._generation_indices.append((start_index, end_index))
|
| 395 |
+
return rv
|
| 396 |
+
|
| 397 |
+
def is_active(self) -> bool:
|
| 398 |
+
return self._rendered_blocks or self._generation_indices
|
| 399 |
+
|
| 400 |
+
@contextmanager
|
| 401 |
+
def activate_tracker(self, rendered_blocks: list[int], generation_indices: list[int]):
|
| 402 |
+
try:
|
| 403 |
+
if self.is_active():
|
| 404 |
+
raise ValueError("AssistantTracker should not be reused before closed")
|
| 405 |
+
self._rendered_blocks = rendered_blocks
|
| 406 |
+
self._generation_indices = generation_indices
|
| 407 |
+
|
| 408 |
+
yield
|
| 409 |
+
finally:
|
| 410 |
+
self._rendered_blocks = None
|
| 411 |
+
self._generation_indices = None
|
| 412 |
+
|
| 413 |
+
if version.parse(jinja2.__version__) < version.parse("3.1.0"):
|
| 414 |
+
raise ImportError(
|
| 415 |
+
f"apply_chat_template requires jinja2>=3.1.0 to be installed. Your version is {jinja2.__version__}."
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
def raise_exception(message):
|
| 419 |
+
raise jinja2.exceptions.TemplateError(message)
|
| 420 |
+
|
| 421 |
+
def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
|
| 422 |
+
# We override the built-in tojson filter because Jinja's default filter escapes HTML characters
|
| 423 |
+
# We also expose some options like custom indents and separators
|
| 424 |
+
return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys)
|
| 425 |
+
|
| 426 |
+
def strftime_now(format):
|
| 427 |
+
return datetime.now().strftime(format)
|
| 428 |
+
|
| 429 |
+
jinja_env = ImmutableSandboxedEnvironment(
|
| 430 |
+
trim_blocks=True, lstrip_blocks=True, extensions=[AssistantTracker, jinja2.ext.loopcontrols]
|
| 431 |
+
)
|
| 432 |
+
jinja_env.filters["tojson"] = tojson
|
| 433 |
+
jinja_env.globals["raise_exception"] = raise_exception
|
| 434 |
+
jinja_env.globals["strftime_now"] = strftime_now
|
| 435 |
+
return jinja_env.from_string(chat_template)
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/config.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"Qwen3ForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoModel": "modeling_qwen3.Qwen3ForCausalLM",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_qwen3_hyp.Qwen3HypForCausalLM"
|
| 10 |
+
},
|
| 11 |
+
"bos_token_id": 151643,
|
| 12 |
+
"dtype": "bfloat16",
|
| 13 |
+
"eos_token_id": 151645,
|
| 14 |
+
"head_dim": 128,
|
| 15 |
+
"hidden_act": "silu",
|
| 16 |
+
"hidden_size": 256,
|
| 17 |
+
"initializer_range": 0.02,
|
| 18 |
+
"intermediate_size": 768,
|
| 19 |
+
"layer_types": [
|
| 20 |
+
"full_attention",
|
| 21 |
+
"full_attention",
|
| 22 |
+
"full_attention",
|
| 23 |
+
"full_attention",
|
| 24 |
+
"full_attention",
|
| 25 |
+
"full_attention",
|
| 26 |
+
"full_attention",
|
| 27 |
+
"full_attention"
|
| 28 |
+
],
|
| 29 |
+
"lorentz_k0": 1.0,
|
| 30 |
+
"max_position_embeddings": 40960,
|
| 31 |
+
"max_window_layers": 8,
|
| 32 |
+
"model_type": "qwen3",
|
| 33 |
+
"num_attention_heads": 4,
|
| 34 |
+
"num_hidden_layers": 8,
|
| 35 |
+
"num_key_value_heads": 2,
|
| 36 |
+
"rms_norm_eps": 1e-06,
|
| 37 |
+
"rope_scaling": null,
|
| 38 |
+
"rope_theta": 1000000,
|
| 39 |
+
"sliding_window": null,
|
| 40 |
+
"tie_word_embeddings": true,
|
| 41 |
+
"torch_dtype": "bfloat16",
|
| 42 |
+
"transformers_version": "4.51.3",
|
| 43 |
+
"use_cache": false,
|
| 44 |
+
"use_sliding_window": false,
|
| 45 |
+
"vocab_size": 151936
|
| 46 |
+
}
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/config.py
ADDED
|
@@ -0,0 +1,741 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 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 |
+
import copy
|
| 15 |
+
import dataclasses
|
| 16 |
+
import warnings
|
| 17 |
+
from abc import ABC, abstractmethod
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Mapping, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
from packaging import version
|
| 23 |
+
|
| 24 |
+
from ..utils import TensorType, is_torch_available, is_vision_available, logging
|
| 25 |
+
from .utils import ParameterFormat, compute_effective_axis_dimension, compute_serialized_parameters_size
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if TYPE_CHECKING:
|
| 29 |
+
from ..configuration_utils import PretrainedConfig
|
| 30 |
+
from ..feature_extraction_utils import FeatureExtractionMixin
|
| 31 |
+
from ..image_processing_utils import ImageProcessingMixin
|
| 32 |
+
from ..tokenization_utils_base import PreTrainedTokenizerBase
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if is_vision_available():
|
| 36 |
+
from PIL import Image
|
| 37 |
+
|
| 38 |
+
logger = logging.get_logger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
DEFAULT_ONNX_OPSET = 11
|
| 42 |
+
|
| 43 |
+
# 2 Gb
|
| 44 |
+
EXTERNAL_DATA_FORMAT_SIZE_LIMIT = 2 * 1024 * 1024 * 1024
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclasses.dataclass
|
| 48 |
+
class PatchingSpec:
|
| 49 |
+
"""
|
| 50 |
+
Data class that holds patching specifications.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
o: Module / object where the op to patch is located
|
| 54 |
+
name: Name of the op to monkey patch
|
| 55 |
+
custom_op: Custom op that patches the original op
|
| 56 |
+
orig_op: Original op that is being patched
|
| 57 |
+
op_wrapper: Wrapper (optional) that wraps both the original and custom ops.
|
| 58 |
+
It is useful for ops that are class or static methods for instance.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
o: Any
|
| 62 |
+
name: str
|
| 63 |
+
custom_op: Callable
|
| 64 |
+
orig_op: Optional[Callable] = None
|
| 65 |
+
op_wrapper: Optional[Callable] = None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class OnnxConfig(ABC):
|
| 69 |
+
"""
|
| 70 |
+
Base class for ONNX exportable model describing metadata on how to export the model through the ONNX format.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
default_fixed_batch = 2
|
| 74 |
+
default_fixed_sequence = 8
|
| 75 |
+
default_fixed_num_choices = 4
|
| 76 |
+
torch_onnx_minimum_version = version.parse("1.8")
|
| 77 |
+
_tasks_to_common_outputs = {
|
| 78 |
+
"causal-lm": OrderedDict({"logits": {0: "batch", 1: "sequence"}}),
|
| 79 |
+
"default": OrderedDict({"last_hidden_state": {0: "batch", 1: "sequence"}}),
|
| 80 |
+
"image-classification": OrderedDict({"logits": {0: "batch", 1: "sequence"}}),
|
| 81 |
+
"image-segmentation": OrderedDict(
|
| 82 |
+
{
|
| 83 |
+
"logits": {0: "batch", 1: "sequence"},
|
| 84 |
+
"pred_boxes": {0: "batch", 1: "sequence"},
|
| 85 |
+
"pred_masks": {0: "batch", 1: "sequence"},
|
| 86 |
+
}
|
| 87 |
+
),
|
| 88 |
+
"masked-im": OrderedDict({"logits": {0: "batch", 1: "sequence"}}),
|
| 89 |
+
"masked-lm": OrderedDict({"logits": {0: "batch", 1: "sequence"}}),
|
| 90 |
+
"multiple-choice": OrderedDict({"logits": {0: "batch"}}),
|
| 91 |
+
"object-detection": OrderedDict(
|
| 92 |
+
{
|
| 93 |
+
"logits": {0: "batch", 1: "sequence"},
|
| 94 |
+
"pred_boxes": {0: "batch", 1: "sequence"},
|
| 95 |
+
}
|
| 96 |
+
),
|
| 97 |
+
"question-answering": OrderedDict(
|
| 98 |
+
{
|
| 99 |
+
"start_logits": {0: "batch", 1: "sequence"},
|
| 100 |
+
"end_logits": {0: "batch", 1: "sequence"},
|
| 101 |
+
}
|
| 102 |
+
),
|
| 103 |
+
"semantic-segmentation": OrderedDict({"logits": {0: "batch", 1: "num_labels", 2: "height", 3: "width"}}),
|
| 104 |
+
"seq2seq-lm": OrderedDict({"logits": {0: "batch", 1: "decoder_sequence"}}),
|
| 105 |
+
"sequence-classification": OrderedDict({"logits": {0: "batch"}}),
|
| 106 |
+
"token-classification": OrderedDict({"logits": {0: "batch", 1: "sequence"}}),
|
| 107 |
+
"vision2seq-lm": OrderedDict({"logits": {0: "batch", 1: "sequence"}}),
|
| 108 |
+
"speech2seq-lm": OrderedDict({"logits": {0: "batch", 1: "sequence"}}),
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
def __init__(self, config: "PretrainedConfig", task: str = "default", patching_specs: List[PatchingSpec] = None):
|
| 112 |
+
self._config = config
|
| 113 |
+
|
| 114 |
+
if task not in self._tasks_to_common_outputs:
|
| 115 |
+
raise ValueError(
|
| 116 |
+
f"{task} is not a supported task, supported tasks: {self._tasks_to_common_outputs.keys()}"
|
| 117 |
+
)
|
| 118 |
+
self.task = task
|
| 119 |
+
|
| 120 |
+
self._patching_specs = []
|
| 121 |
+
for spec in patching_specs if patching_specs is not None else []:
|
| 122 |
+
final_spec = spec
|
| 123 |
+
if spec.orig_op is None:
|
| 124 |
+
final_spec = dataclasses.replace(spec, orig_op=getattr(spec.o, spec.name))
|
| 125 |
+
self._patching_specs.append(final_spec)
|
| 126 |
+
|
| 127 |
+
@classmethod
|
| 128 |
+
def from_model_config(cls, config: "PretrainedConfig", task: str = "default") -> "OnnxConfig":
|
| 129 |
+
"""
|
| 130 |
+
Instantiate a OnnxConfig for a specific model
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
config: The model's configuration to use when exporting to ONNX
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
OnnxConfig for this model
|
| 137 |
+
"""
|
| 138 |
+
return cls(config, task=task)
|
| 139 |
+
|
| 140 |
+
@property
|
| 141 |
+
@abstractmethod
|
| 142 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 143 |
+
"""
|
| 144 |
+
Mapping containing the axis definition of the input tensors to provide to the model
|
| 145 |
+
|
| 146 |
+
Returns:
|
| 147 |
+
For each input: its name associated to the axes symbolic name and the axis position within the tensor
|
| 148 |
+
"""
|
| 149 |
+
raise NotImplementedError()
|
| 150 |
+
|
| 151 |
+
@property
|
| 152 |
+
def outputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 153 |
+
"""
|
| 154 |
+
Mapping containing the axis definition of the output tensors to provide to the model
|
| 155 |
+
|
| 156 |
+
Returns:
|
| 157 |
+
For each output: its name associated to the axes symbolic name and the axis position within the tensor
|
| 158 |
+
"""
|
| 159 |
+
common_outputs = self._tasks_to_common_outputs[self.task]
|
| 160 |
+
return copy.deepcopy(common_outputs)
|
| 161 |
+
|
| 162 |
+
@property
|
| 163 |
+
def values_override(self) -> Optional[Mapping[str, Any]]:
|
| 164 |
+
"""
|
| 165 |
+
Dictionary of keys to override in the model's config before exporting
|
| 166 |
+
|
| 167 |
+
Returns:
|
| 168 |
+
Dictionary with the keys (and their corresponding values) to override
|
| 169 |
+
"""
|
| 170 |
+
if hasattr(self._config, "use_cache"):
|
| 171 |
+
return {"use_cache": False}
|
| 172 |
+
|
| 173 |
+
return None
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
def default_batch_size(self) -> int:
|
| 177 |
+
"""
|
| 178 |
+
The default batch size to use if no other indication
|
| 179 |
+
|
| 180 |
+
Returns:
|
| 181 |
+
Integer > 0
|
| 182 |
+
"""
|
| 183 |
+
# Using 2 avoid ONNX making assumption about single sample batch
|
| 184 |
+
return OnnxConfig.default_fixed_batch
|
| 185 |
+
|
| 186 |
+
@property
|
| 187 |
+
def default_sequence_length(self) -> int:
|
| 188 |
+
"""
|
| 189 |
+
The default sequence length to use if no other indication
|
| 190 |
+
|
| 191 |
+
Returns:
|
| 192 |
+
Integer > 0
|
| 193 |
+
"""
|
| 194 |
+
return OnnxConfig.default_fixed_sequence
|
| 195 |
+
|
| 196 |
+
@property
|
| 197 |
+
def default_num_choices(self) -> int:
|
| 198 |
+
"""
|
| 199 |
+
The default number of choices to use if no other indication
|
| 200 |
+
|
| 201 |
+
Returns:
|
| 202 |
+
Integer > 0
|
| 203 |
+
"""
|
| 204 |
+
return OnnxConfig.default_fixed_num_choices
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def default_onnx_opset(self) -> int:
|
| 208 |
+
"""
|
| 209 |
+
Which onnx opset to use when exporting the model
|
| 210 |
+
|
| 211 |
+
Returns:
|
| 212 |
+
Integer ONNX Opset version
|
| 213 |
+
"""
|
| 214 |
+
return DEFAULT_ONNX_OPSET
|
| 215 |
+
|
| 216 |
+
@property
|
| 217 |
+
def atol_for_validation(self) -> float:
|
| 218 |
+
"""
|
| 219 |
+
What absolute tolerance value to use during model conversion validation.
|
| 220 |
+
|
| 221 |
+
Returns:
|
| 222 |
+
Float absolute tolerance value.
|
| 223 |
+
"""
|
| 224 |
+
return 1e-5
|
| 225 |
+
|
| 226 |
+
@property
|
| 227 |
+
def is_torch_support_available(self) -> bool:
|
| 228 |
+
"""
|
| 229 |
+
The minimum PyTorch version required to export the model.
|
| 230 |
+
|
| 231 |
+
Returns:
|
| 232 |
+
`bool`: Whether the installed version of PyTorch is compatible with the model.
|
| 233 |
+
"""
|
| 234 |
+
if is_torch_available():
|
| 235 |
+
from transformers.utils import get_torch_version
|
| 236 |
+
|
| 237 |
+
return version.parse(get_torch_version()) >= self.torch_onnx_minimum_version
|
| 238 |
+
else:
|
| 239 |
+
return False
|
| 240 |
+
|
| 241 |
+
@staticmethod
|
| 242 |
+
def use_external_data_format(num_parameters: int) -> bool:
|
| 243 |
+
"""
|
| 244 |
+
Flag indicating if the model requires using external data format
|
| 245 |
+
|
| 246 |
+
Args:
|
| 247 |
+
num_parameters: Number of parameter on the model
|
| 248 |
+
|
| 249 |
+
Returns:
|
| 250 |
+
True if model.num_parameters() * size_of(float32) >= 2Gb False otherwise
|
| 251 |
+
"""
|
| 252 |
+
|
| 253 |
+
return (
|
| 254 |
+
compute_serialized_parameters_size(num_parameters, ParameterFormat.Float)
|
| 255 |
+
>= EXTERNAL_DATA_FORMAT_SIZE_LIMIT
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
def _generate_dummy_images(
|
| 259 |
+
self, batch_size: int = 2, num_channels: int = 3, image_height: int = 40, image_width: int = 40
|
| 260 |
+
):
|
| 261 |
+
images = []
|
| 262 |
+
for _ in range(batch_size):
|
| 263 |
+
data = np.random.rand(image_height, image_width, num_channels) * 255
|
| 264 |
+
images.append(Image.fromarray(data.astype("uint8")).convert("RGB"))
|
| 265 |
+
return images
|
| 266 |
+
|
| 267 |
+
def _generate_dummy_audio(
|
| 268 |
+
self, batch_size: int = 2, sampling_rate: int = 22050, time_duration: float = 5.0, frequency: int = 220
|
| 269 |
+
):
|
| 270 |
+
audio_data = []
|
| 271 |
+
for _ in range(batch_size):
|
| 272 |
+
# time variable
|
| 273 |
+
t = np.linspace(0, time_duration, int(time_duration * sampling_rate), endpoint=False)
|
| 274 |
+
|
| 275 |
+
# generate pure sine wave at `frequency` Hz
|
| 276 |
+
audio_data.append(0.5 * np.sin(2 * np.pi * frequency * t))
|
| 277 |
+
|
| 278 |
+
return audio_data
|
| 279 |
+
|
| 280 |
+
def generate_dummy_inputs(
|
| 281 |
+
self,
|
| 282 |
+
preprocessor: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin", "ImageProcessingMixin"],
|
| 283 |
+
batch_size: int = -1,
|
| 284 |
+
seq_length: int = -1,
|
| 285 |
+
num_choices: int = -1,
|
| 286 |
+
is_pair: bool = False,
|
| 287 |
+
framework: Optional[TensorType] = None,
|
| 288 |
+
num_channels: int = 3,
|
| 289 |
+
image_width: int = 40,
|
| 290 |
+
image_height: int = 40,
|
| 291 |
+
sampling_rate: int = 22050,
|
| 292 |
+
time_duration: float = 5.0,
|
| 293 |
+
frequency: int = 220,
|
| 294 |
+
tokenizer: Optional["PreTrainedTokenizerBase"] = None,
|
| 295 |
+
) -> Mapping[str, Any]:
|
| 296 |
+
"""
|
| 297 |
+
Generate inputs to provide to the ONNX exporter for the specific framework
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
preprocessor: ([`PreTrainedTokenizerBase`], [`FeatureExtractionMixin`], or [`ImageProcessingMixin`]):
|
| 301 |
+
The preprocessor associated with this model configuration.
|
| 302 |
+
batch_size (`int`, *optional*, defaults to -1):
|
| 303 |
+
The batch size to export the model for (-1 means dynamic axis).
|
| 304 |
+
num_choices (`int`, *optional*, defaults to -1):
|
| 305 |
+
The number of candidate answers provided for multiple choice task (-1 means dynamic axis).
|
| 306 |
+
seq_length (`int`, *optional*, defaults to -1):
|
| 307 |
+
The sequence length to export the model for (-1 means dynamic axis).
|
| 308 |
+
is_pair (`bool`, *optional*, defaults to `False`):
|
| 309 |
+
Indicate if the input is a pair (sentence 1, sentence 2)
|
| 310 |
+
framework (`TensorType`, *optional*, defaults to `None`):
|
| 311 |
+
The framework (PyTorch or TensorFlow) that the tokenizer will generate tensors for.
|
| 312 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 313 |
+
The number of channels of the generated images.
|
| 314 |
+
image_width (`int`, *optional*, defaults to 40):
|
| 315 |
+
The width of the generated images.
|
| 316 |
+
image_height (`int`, *optional*, defaults to 40):
|
| 317 |
+
The height of the generated images.
|
| 318 |
+
sampling_rate (`int`, *optional* defaults to 22050)
|
| 319 |
+
The sampling rate for audio data generation.
|
| 320 |
+
time_duration (`float`, *optional* defaults to 5.0)
|
| 321 |
+
Total seconds of sampling for audio data generation.
|
| 322 |
+
frequency (`int`, *optional* defaults to 220)
|
| 323 |
+
The desired natural frequency of generated audio.
|
| 324 |
+
|
| 325 |
+
Returns:
|
| 326 |
+
Mapping[str, Tensor] holding the kwargs to provide to the model's forward function
|
| 327 |
+
"""
|
| 328 |
+
from ..feature_extraction_utils import FeatureExtractionMixin
|
| 329 |
+
from ..image_processing_utils import ImageProcessingMixin
|
| 330 |
+
from ..tokenization_utils_base import PreTrainedTokenizerBase
|
| 331 |
+
|
| 332 |
+
if isinstance(preprocessor, PreTrainedTokenizerBase) and tokenizer is not None:
|
| 333 |
+
raise ValueError("You cannot provide both a tokenizer and a preprocessor to generate dummy inputs.")
|
| 334 |
+
if tokenizer is not None:
|
| 335 |
+
warnings.warn(
|
| 336 |
+
"The `tokenizer` argument is deprecated and will be removed in version 5 of Transformers. Use"
|
| 337 |
+
" `preprocessor` instead.",
|
| 338 |
+
FutureWarning,
|
| 339 |
+
)
|
| 340 |
+
logger.warning("Overwriting the `preprocessor` argument with `tokenizer` to generate dummy inputs.")
|
| 341 |
+
preprocessor = tokenizer
|
| 342 |
+
if isinstance(preprocessor, PreTrainedTokenizerBase):
|
| 343 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
|
| 344 |
+
batch_size = compute_effective_axis_dimension(
|
| 345 |
+
batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
|
| 346 |
+
)
|
| 347 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
|
| 348 |
+
token_to_add = preprocessor.num_special_tokens_to_add(is_pair)
|
| 349 |
+
seq_length = compute_effective_axis_dimension(
|
| 350 |
+
seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
|
| 351 |
+
)
|
| 352 |
+
# Generate dummy inputs according to compute batch and sequence
|
| 353 |
+
input_token = (
|
| 354 |
+
preprocessor.unk_token
|
| 355 |
+
if (preprocessor.unk_token is not None and len(preprocessor.unk_token) > 0)
|
| 356 |
+
else "0"
|
| 357 |
+
)
|
| 358 |
+
dummy_input = [" ".join([input_token]) * seq_length] * batch_size
|
| 359 |
+
if self.task == "multiple-choice":
|
| 360 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 4 candidate answers to avoid optimizations
|
| 361 |
+
# made by ONNX
|
| 362 |
+
num_choices = compute_effective_axis_dimension(
|
| 363 |
+
num_choices, fixed_dimension=OnnxConfig.default_fixed_num_choices, num_token_to_add=0
|
| 364 |
+
)
|
| 365 |
+
dummy_input = dummy_input * num_choices
|
| 366 |
+
# The shape of the tokenized inputs values is [batch_size * num_choices, seq_length]
|
| 367 |
+
tokenized_input = preprocessor(dummy_input, text_pair=dummy_input)
|
| 368 |
+
# Unflatten the tokenized inputs values expanding it to the shape [batch_size, num_choices, seq_length]
|
| 369 |
+
for k, v in tokenized_input.items():
|
| 370 |
+
tokenized_input[k] = [v[i : i + num_choices] for i in range(0, len(v), num_choices)]
|
| 371 |
+
return dict(tokenized_input.convert_to_tensors(tensor_type=framework))
|
| 372 |
+
return dict(preprocessor(dummy_input, return_tensors=framework))
|
| 373 |
+
elif isinstance(preprocessor, ImageProcessingMixin):
|
| 374 |
+
if preprocessor.model_input_names[0] != "pixel_values":
|
| 375 |
+
raise ValueError(
|
| 376 |
+
f"The `preprocessor` is an image processor ({preprocessor.__class__.__name__}) and expects"
|
| 377 |
+
f' `model_input_names[0]` to be "pixel_values", but got {preprocessor.model_input_names[0]}'
|
| 378 |
+
)
|
| 379 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
|
| 380 |
+
batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
|
| 381 |
+
dummy_input = self._generate_dummy_images(batch_size, num_channels, image_height, image_width)
|
| 382 |
+
return dict(preprocessor(images=dummy_input, return_tensors=framework))
|
| 383 |
+
elif isinstance(preprocessor, FeatureExtractionMixin) and preprocessor.model_input_names[0] == "pixel_values":
|
| 384 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
|
| 385 |
+
batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
|
| 386 |
+
dummy_input = self._generate_dummy_images(batch_size, num_channels, image_height, image_width)
|
| 387 |
+
return dict(preprocessor(images=dummy_input, return_tensors=framework))
|
| 388 |
+
elif (
|
| 389 |
+
isinstance(preprocessor, FeatureExtractionMixin) and preprocessor.model_input_names[0] == "input_features"
|
| 390 |
+
):
|
| 391 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
|
| 392 |
+
batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
|
| 393 |
+
dummy_input = self._generate_dummy_audio(batch_size, sampling_rate, time_duration, frequency)
|
| 394 |
+
return dict(preprocessor(dummy_input, return_tensors=framework))
|
| 395 |
+
else:
|
| 396 |
+
raise ValueError(
|
| 397 |
+
"Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor."
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
def generate_dummy_inputs_onnxruntime(self, reference_model_inputs: Mapping[str, Any]) -> Mapping[str, Any]:
|
| 401 |
+
"""
|
| 402 |
+
Generate inputs for ONNX Runtime using the reference model inputs. Override this to run inference with seq2seq
|
| 403 |
+
models which have the encoder and decoder exported as separate ONNX files.
|
| 404 |
+
|
| 405 |
+
Args:
|
| 406 |
+
reference_model_inputs ([`Mapping[str, Tensor]`):
|
| 407 |
+
Reference inputs for the model.
|
| 408 |
+
|
| 409 |
+
Returns:
|
| 410 |
+
`Mapping[str, Tensor]`: The mapping holding the kwargs to provide to the model's forward function
|
| 411 |
+
"""
|
| 412 |
+
return reference_model_inputs
|
| 413 |
+
|
| 414 |
+
def patch_ops(self):
|
| 415 |
+
for spec in self._patching_specs:
|
| 416 |
+
custom_op = spec.custom_op if spec.op_wrapper is None else spec.op_wrapper(spec.custom_op)
|
| 417 |
+
setattr(spec.o, spec.name, custom_op)
|
| 418 |
+
|
| 419 |
+
def restore_ops(self):
|
| 420 |
+
for spec in self._patching_specs:
|
| 421 |
+
orig_op = spec.orig_op if spec.op_wrapper is None else spec.op_wrapper(spec.orig_op)
|
| 422 |
+
setattr(spec.o, spec.name, orig_op)
|
| 423 |
+
|
| 424 |
+
@classmethod
|
| 425 |
+
def flatten_output_collection_property(cls, name: str, field: Iterable[Any]) -> Dict[str, Any]:
|
| 426 |
+
"""
|
| 427 |
+
Flatten any potential nested structure expanding the name of the field with the index of the element within the
|
| 428 |
+
structure.
|
| 429 |
+
|
| 430 |
+
Args:
|
| 431 |
+
name: The name of the nested structure
|
| 432 |
+
field: The structure to, potentially, be flattened
|
| 433 |
+
|
| 434 |
+
Returns:
|
| 435 |
+
(Dict[str, Any]): Outputs with flattened structure and key mapping this new structure.
|
| 436 |
+
|
| 437 |
+
"""
|
| 438 |
+
from itertools import chain
|
| 439 |
+
|
| 440 |
+
return {f"{name}.{idx}": item for idx, item in enumerate(chain.from_iterable(field))}
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
class OnnxConfigWithPast(OnnxConfig, ABC):
|
| 444 |
+
def __init__(
|
| 445 |
+
self,
|
| 446 |
+
config: "PretrainedConfig",
|
| 447 |
+
task: str = "default",
|
| 448 |
+
patching_specs: Optional[list[PatchingSpec]] = None,
|
| 449 |
+
use_past: bool = False,
|
| 450 |
+
):
|
| 451 |
+
super().__init__(config, task=task, patching_specs=patching_specs)
|
| 452 |
+
self.use_past = use_past
|
| 453 |
+
|
| 454 |
+
@classmethod
|
| 455 |
+
def with_past(cls, config: "PretrainedConfig", task: str = "default") -> "OnnxConfigWithPast":
|
| 456 |
+
"""
|
| 457 |
+
Instantiate a OnnxConfig with `use_past` attribute set to True
|
| 458 |
+
|
| 459 |
+
Args:
|
| 460 |
+
config: The underlying model's config to use when exporting to ONNX
|
| 461 |
+
|
| 462 |
+
Returns:
|
| 463 |
+
OnnxConfig with `.use_past = True`
|
| 464 |
+
"""
|
| 465 |
+
return cls(config, task=task, use_past=True)
|
| 466 |
+
|
| 467 |
+
@property
|
| 468 |
+
def outputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 469 |
+
common_outputs = super().outputs
|
| 470 |
+
if self.use_past:
|
| 471 |
+
self.fill_with_past_key_values_(common_outputs, direction="outputs")
|
| 472 |
+
|
| 473 |
+
return common_outputs
|
| 474 |
+
|
| 475 |
+
@property
|
| 476 |
+
def values_override(self) -> Optional[Mapping[str, Any]]:
|
| 477 |
+
if hasattr(self._config, "use_cache"):
|
| 478 |
+
return {"use_cache": self.use_past}
|
| 479 |
+
|
| 480 |
+
return None
|
| 481 |
+
|
| 482 |
+
@property
|
| 483 |
+
def num_layers(self) -> int:
|
| 484 |
+
"""
|
| 485 |
+
The number of layers attribute retrieved from the model config. Override this for model configs where the
|
| 486 |
+
number of layers attribute is not called `num_layers`.
|
| 487 |
+
"""
|
| 488 |
+
if not hasattr(self._config, "num_layers"):
|
| 489 |
+
raise AttributeError(
|
| 490 |
+
"could not find the number of layers attribute in the model configuration, override the num_layers"
|
| 491 |
+
" property of the model OnnxConfig to solve this"
|
| 492 |
+
)
|
| 493 |
+
return self._config.num_layers
|
| 494 |
+
|
| 495 |
+
@property
|
| 496 |
+
def num_attention_heads(self) -> int:
|
| 497 |
+
"""
|
| 498 |
+
The number of attention heads attribute retrieved from the model config. Override this for model configs where
|
| 499 |
+
the number of attention heads attribute is not called `num_attention_heads`.
|
| 500 |
+
"""
|
| 501 |
+
if not hasattr(self._config, "num_attention_heads"):
|
| 502 |
+
raise AttributeError(
|
| 503 |
+
"could not find the number of attention heads attribute in the model configuration, override the"
|
| 504 |
+
" num_attention_heads property of the model OnnxConfig to solve this"
|
| 505 |
+
)
|
| 506 |
+
return self._config.num_attention_heads
|
| 507 |
+
|
| 508 |
+
def generate_dummy_inputs(
|
| 509 |
+
self,
|
| 510 |
+
tokenizer: "PreTrainedTokenizerBase",
|
| 511 |
+
batch_size: int = -1,
|
| 512 |
+
seq_length: int = -1,
|
| 513 |
+
is_pair: bool = False,
|
| 514 |
+
framework: Optional[TensorType] = None,
|
| 515 |
+
) -> Mapping[str, Any]:
|
| 516 |
+
# TODO: should we set seq_length = 1 when self.use_past = True?
|
| 517 |
+
common_inputs = super().generate_dummy_inputs(
|
| 518 |
+
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
if self.use_past:
|
| 522 |
+
if not is_torch_available():
|
| 523 |
+
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
| 524 |
+
else:
|
| 525 |
+
import torch
|
| 526 |
+
|
| 527 |
+
batch, seqlen = common_inputs["input_ids"].shape
|
| 528 |
+
# Not using the same length for past_key_values
|
| 529 |
+
past_key_values_length = seqlen + 2
|
| 530 |
+
shape = (
|
| 531 |
+
batch,
|
| 532 |
+
self.num_attention_heads,
|
| 533 |
+
past_key_values_length,
|
| 534 |
+
self._config.hidden_size // self.num_attention_heads,
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
if "attention_mask" in common_inputs:
|
| 538 |
+
mask_dtype = common_inputs["attention_mask"].dtype
|
| 539 |
+
common_inputs["attention_mask"] = torch.cat(
|
| 540 |
+
[common_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)],
|
| 541 |
+
dim=1,
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
common_inputs["past_key_values"] = []
|
| 545 |
+
for _ in range(self.num_layers):
|
| 546 |
+
common_inputs["past_key_values"].append((torch.zeros(shape), torch.zeros(shape)))
|
| 547 |
+
|
| 548 |
+
return common_inputs
|
| 549 |
+
|
| 550 |
+
def fill_with_past_key_values_(
|
| 551 |
+
self, inputs_or_outputs: Mapping[str, Mapping[int, str]], direction: str, inverted_values_shape: bool = False
|
| 552 |
+
):
|
| 553 |
+
"""
|
| 554 |
+
Fill the input_or_outputs mapping with past_key_values dynamic axes considering.
|
| 555 |
+
|
| 556 |
+
Args:
|
| 557 |
+
inputs_or_outputs: The mapping to fill.
|
| 558 |
+
direction: either "inputs" or "outputs", it specifies whether input_or_outputs is the input mapping or the
|
| 559 |
+
output mapping, this is important for axes naming.
|
| 560 |
+
inverted_values_shape:
|
| 561 |
+
If `True`, store values on dynamic axis 1, else on axis 2.
|
| 562 |
+
|
| 563 |
+
"""
|
| 564 |
+
if direction not in ["inputs", "outputs"]:
|
| 565 |
+
raise ValueError(f'direction must either be "inputs" or "outputs", but {direction} was given')
|
| 566 |
+
|
| 567 |
+
name = "past_key_values" if direction == "inputs" else "present"
|
| 568 |
+
for i in range(self.num_layers):
|
| 569 |
+
inputs_or_outputs[f"{name}.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
|
| 570 |
+
if inverted_values_shape:
|
| 571 |
+
inputs_or_outputs[f"{name}.{i}.value"] = {0: "batch", 1: "past_sequence + sequence"}
|
| 572 |
+
else:
|
| 573 |
+
inputs_or_outputs[f"{name}.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
|
| 574 |
+
|
| 575 |
+
def _flatten_past_key_values_(self, flattened_output, name, idx, t):
|
| 576 |
+
flattened_output[f"{name}.{idx}.key"] = t[0]
|
| 577 |
+
flattened_output[f"{name}.{idx}.value"] = t[1]
|
| 578 |
+
|
| 579 |
+
def flatten_output_collection_property(self, name: str, field: Iterable[Any]) -> Dict[str, Any]:
|
| 580 |
+
flattened_output = {}
|
| 581 |
+
if name in ["present", "past_key_values"]:
|
| 582 |
+
for idx, t in enumerate(field):
|
| 583 |
+
self._flatten_past_key_values_(flattened_output, name, idx, t)
|
| 584 |
+
else:
|
| 585 |
+
flattened_output = super().flatten_output_collection_property(name, field)
|
| 586 |
+
|
| 587 |
+
return flattened_output
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
class OnnxSeq2SeqConfigWithPast(OnnxConfigWithPast):
|
| 591 |
+
@property
|
| 592 |
+
def outputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 593 |
+
common_outputs = super(OnnxConfigWithPast, self).outputs
|
| 594 |
+
# Renaming the outputs axes properly.
|
| 595 |
+
for name, axes_names in common_outputs.items():
|
| 596 |
+
sequence_name = "encoder_sequence" if "encoder" in name else "decoder_sequence"
|
| 597 |
+
for axis_idx, name in axes_names.items():
|
| 598 |
+
if "sequence" in name:
|
| 599 |
+
axes_names[axis_idx] = sequence_name
|
| 600 |
+
# We reset the value as the order in common_outputs (OrderedDict) is lost otherwise
|
| 601 |
+
else:
|
| 602 |
+
axes_names[axis_idx] = name
|
| 603 |
+
if self.use_past:
|
| 604 |
+
self.fill_with_past_key_values_(common_outputs, direction="outputs")
|
| 605 |
+
|
| 606 |
+
return common_outputs
|
| 607 |
+
|
| 608 |
+
@property
|
| 609 |
+
def num_layers(self) -> Tuple[int]:
|
| 610 |
+
try:
|
| 611 |
+
num_layers = super().num_layers
|
| 612 |
+
num_layers = (num_layers, num_layers)
|
| 613 |
+
except AttributeError:
|
| 614 |
+
if hasattr(self._config, "encoder_layers") and hasattr(self._config, "decoder_layers"):
|
| 615 |
+
num_layers = (self._config.encoder_layers, self._config.decoder_layers)
|
| 616 |
+
else:
|
| 617 |
+
raise AttributeError(
|
| 618 |
+
"could not find the number of encoder and decoder layers attributes in the model configuration,"
|
| 619 |
+
" override the num_layers property of the model OnnxConfig to solve this"
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
return num_layers
|
| 623 |
+
|
| 624 |
+
@property
|
| 625 |
+
def num_attention_heads(self) -> Tuple[int]:
|
| 626 |
+
try:
|
| 627 |
+
num_attention_heads = super().num_attention_heads
|
| 628 |
+
num_attention_heads = (num_attention_heads, num_attention_heads)
|
| 629 |
+
except AttributeError:
|
| 630 |
+
if hasattr(self._config, "encoder_attention_heads") and hasattr(self._config, "decoder_attention_heads"):
|
| 631 |
+
num_attention_heads = (self._config.encoder_attention_heads, self._config.decoder_attention_heads)
|
| 632 |
+
else:
|
| 633 |
+
raise AttributeError(
|
| 634 |
+
"could not find the number of attention heads for the encoder and the decoder attributes in the"
|
| 635 |
+
" model configuration, override the num_attention_heads property of the model OnnxConfig to solve"
|
| 636 |
+
" this"
|
| 637 |
+
)
|
| 638 |
+
return num_attention_heads
|
| 639 |
+
|
| 640 |
+
def generate_dummy_inputs(
|
| 641 |
+
self,
|
| 642 |
+
tokenizer: Optional["PreTrainedTokenizerBase"],
|
| 643 |
+
batch_size: int = -1,
|
| 644 |
+
seq_length: int = -1,
|
| 645 |
+
is_pair: bool = False,
|
| 646 |
+
framework: Optional[TensorType] = None,
|
| 647 |
+
) -> Mapping[str, Any]:
|
| 648 |
+
encoder_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
|
| 649 |
+
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
# Generate decoder inputs
|
| 653 |
+
decoder_seq_length = seq_length if not self.use_past else 1
|
| 654 |
+
decoder_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
|
| 655 |
+
tokenizer, batch_size=batch_size, seq_length=decoder_seq_length, is_pair=is_pair, framework=framework
|
| 656 |
+
)
|
| 657 |
+
decoder_inputs = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
|
| 658 |
+
common_inputs = dict(**encoder_inputs, **decoder_inputs)
|
| 659 |
+
|
| 660 |
+
if self.use_past:
|
| 661 |
+
if not is_torch_available():
|
| 662 |
+
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
| 663 |
+
else:
|
| 664 |
+
import torch
|
| 665 |
+
batch = common_inputs["input_ids"].shape[0]
|
| 666 |
+
encoder_seq_length = common_inputs["input_ids"].shape[1]
|
| 667 |
+
decoder_seq_length = common_inputs["decoder_input_ids"].shape[1]
|
| 668 |
+
num_encoder_attention_heads, num_decoder_attention_heads = self.num_attention_heads
|
| 669 |
+
encoder_shape = (
|
| 670 |
+
batch,
|
| 671 |
+
num_encoder_attention_heads,
|
| 672 |
+
encoder_seq_length,
|
| 673 |
+
self._config.hidden_size // num_encoder_attention_heads,
|
| 674 |
+
)
|
| 675 |
+
decoder_shape = (
|
| 676 |
+
batch,
|
| 677 |
+
num_decoder_attention_heads,
|
| 678 |
+
# Not using the same length for past_key_values
|
| 679 |
+
decoder_seq_length + 3,
|
| 680 |
+
self._config.hidden_size // num_decoder_attention_heads,
|
| 681 |
+
)
|
| 682 |
+
|
| 683 |
+
common_inputs["past_key_values"] = []
|
| 684 |
+
# If the number of encoder and decoder layers are present in the model configuration, both are considered
|
| 685 |
+
num_encoder_layers, num_decoder_layers = self.num_layers
|
| 686 |
+
min_num_layers = min(num_encoder_layers, num_decoder_layers)
|
| 687 |
+
max_num_layers = max(num_encoder_layers, num_decoder_layers) - min_num_layers
|
| 688 |
+
remaining_side_name = "encoder" if num_encoder_layers > num_decoder_layers else "decoder"
|
| 689 |
+
|
| 690 |
+
for _ in range(min_num_layers):
|
| 691 |
+
# For encoder-decoder models, past_key_values contains pre-computed values for both the encoder and the
|
| 692 |
+
# decoder layers, hence a tuple of 4 tensors instead of 2
|
| 693 |
+
common_inputs["past_key_values"].append(
|
| 694 |
+
(
|
| 695 |
+
torch.zeros(decoder_shape),
|
| 696 |
+
torch.zeros(decoder_shape),
|
| 697 |
+
torch.zeros(encoder_shape),
|
| 698 |
+
torch.zeros(encoder_shape),
|
| 699 |
+
)
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
# TODO: test this.
|
| 703 |
+
shape = encoder_shape if remaining_side_name == "encoder" else decoder_shape
|
| 704 |
+
for _ in range(min_num_layers, max_num_layers):
|
| 705 |
+
common_inputs["past_key_values"].append((torch.zeros(shape), torch.zeros(shape)))
|
| 706 |
+
|
| 707 |
+
return common_inputs
|
| 708 |
+
|
| 709 |
+
def fill_with_past_key_values_(self, inputs_or_outputs: Mapping[str, Mapping[int, str]], direction: str):
|
| 710 |
+
if direction not in ["inputs", "outputs"]:
|
| 711 |
+
raise ValueError(f'direction must either be "inputs" or "outputs", but {direction} was given')
|
| 712 |
+
|
| 713 |
+
name = "past_key_values" if direction == "inputs" else "present"
|
| 714 |
+
|
| 715 |
+
# If the number of encoder and decoder layers are present in the model configuration, both are considered
|
| 716 |
+
num_encoder_layers, num_decoder_layers = self.num_layers
|
| 717 |
+
min_num_layers = min(num_encoder_layers, num_decoder_layers)
|
| 718 |
+
max_num_layers = max(num_encoder_layers, num_decoder_layers) - min_num_layers
|
| 719 |
+
remaining_side_name = "encoder" if num_encoder_layers > num_decoder_layers else "decoder"
|
| 720 |
+
|
| 721 |
+
encoder_sequence = "past_encoder_sequence"
|
| 722 |
+
decoder_sequence = "past_decoder_sequence" if direction == "inputs" else "past_decoder_sequence + sequence"
|
| 723 |
+
|
| 724 |
+
for i in range(min_num_layers):
|
| 725 |
+
inputs_or_outputs[f"{name}.{i}.decoder.key"] = {0: "batch", 2: decoder_sequence}
|
| 726 |
+
inputs_or_outputs[f"{name}.{i}.decoder.value"] = {0: "batch", 2: decoder_sequence}
|
| 727 |
+
inputs_or_outputs[f"{name}.{i}.encoder.key"] = {0: "batch", 2: encoder_sequence}
|
| 728 |
+
inputs_or_outputs[f"{name}.{i}.encoder.value"] = {0: "batch", 2: encoder_sequence}
|
| 729 |
+
|
| 730 |
+
for i in range(min_num_layers, max_num_layers):
|
| 731 |
+
if remaining_side_name == "encoder":
|
| 732 |
+
axes_info = {0: "batch", 2: encoder_sequence}
|
| 733 |
+
else:
|
| 734 |
+
axes_info = {0: "batch", 2: decoder_sequence}
|
| 735 |
+
inputs_or_outputs[f"{name}.{i}.{remaining_side_name}.key"] = axes_info
|
| 736 |
+
|
| 737 |
+
def _flatten_past_key_values_(self, flattened_output, name, idx, t):
|
| 738 |
+
flattened_output[f"{name}.{idx}.decoder.key"] = t[0]
|
| 739 |
+
flattened_output[f"{name}.{idx}.decoder.value"] = t[1]
|
| 740 |
+
flattened_output[f"{name}.{idx}.encoder.key"] = t[2]
|
| 741 |
+
flattened_output[f"{name}.{idx}.encoder.value"] = t[3]
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_auto.py
ADDED
|
@@ -0,0 +1,1172 @@
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 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 |
+
"""Auto Config class."""
|
| 16 |
+
|
| 17 |
+
import importlib
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import warnings
|
| 21 |
+
from collections import OrderedDict
|
| 22 |
+
from typing import List, Union
|
| 23 |
+
|
| 24 |
+
from ...configuration_utils import PretrainedConfig
|
| 25 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
|
| 26 |
+
from ...utils import CONFIG_NAME, logging
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
CONFIG_MAPPING_NAMES = OrderedDict(
|
| 33 |
+
[
|
| 34 |
+
# Add configs here
|
| 35 |
+
("albert", "AlbertConfig"),
|
| 36 |
+
("align", "AlignConfig"),
|
| 37 |
+
("altclip", "AltCLIPConfig"),
|
| 38 |
+
("aria", "AriaConfig"),
|
| 39 |
+
("aria_text", "AriaTextConfig"),
|
| 40 |
+
("audio-spectrogram-transformer", "ASTConfig"),
|
| 41 |
+
("autoformer", "AutoformerConfig"),
|
| 42 |
+
("aya_vision", "AyaVisionConfig"),
|
| 43 |
+
("bamba", "BambaConfig"),
|
| 44 |
+
("bark", "BarkConfig"),
|
| 45 |
+
("bart", "BartConfig"),
|
| 46 |
+
("beit", "BeitConfig"),
|
| 47 |
+
("bert", "BertConfig"),
|
| 48 |
+
("bert-generation", "BertGenerationConfig"),
|
| 49 |
+
("big_bird", "BigBirdConfig"),
|
| 50 |
+
("bigbird_pegasus", "BigBirdPegasusConfig"),
|
| 51 |
+
("biogpt", "BioGptConfig"),
|
| 52 |
+
("bit", "BitConfig"),
|
| 53 |
+
("blenderbot", "BlenderbotConfig"),
|
| 54 |
+
("blenderbot-small", "BlenderbotSmallConfig"),
|
| 55 |
+
("blip", "BlipConfig"),
|
| 56 |
+
("blip-2", "Blip2Config"),
|
| 57 |
+
("bloom", "BloomConfig"),
|
| 58 |
+
("bridgetower", "BridgeTowerConfig"),
|
| 59 |
+
("bros", "BrosConfig"),
|
| 60 |
+
("camembert", "CamembertConfig"),
|
| 61 |
+
("canine", "CanineConfig"),
|
| 62 |
+
("chameleon", "ChameleonConfig"),
|
| 63 |
+
("chinese_clip", "ChineseCLIPConfig"),
|
| 64 |
+
("chinese_clip_vision_model", "ChineseCLIPVisionConfig"),
|
| 65 |
+
("clap", "ClapConfig"),
|
| 66 |
+
("clip", "CLIPConfig"),
|
| 67 |
+
("clip_text_model", "CLIPTextConfig"),
|
| 68 |
+
("clip_vision_model", "CLIPVisionConfig"),
|
| 69 |
+
("clipseg", "CLIPSegConfig"),
|
| 70 |
+
("clvp", "ClvpConfig"),
|
| 71 |
+
("code_llama", "LlamaConfig"),
|
| 72 |
+
("codegen", "CodeGenConfig"),
|
| 73 |
+
("cohere", "CohereConfig"),
|
| 74 |
+
("cohere2", "Cohere2Config"),
|
| 75 |
+
("colpali", "ColPaliConfig"),
|
| 76 |
+
("conditional_detr", "ConditionalDetrConfig"),
|
| 77 |
+
("convbert", "ConvBertConfig"),
|
| 78 |
+
("convnext", "ConvNextConfig"),
|
| 79 |
+
("convnextv2", "ConvNextV2Config"),
|
| 80 |
+
("cpmant", "CpmAntConfig"),
|
| 81 |
+
("ctrl", "CTRLConfig"),
|
| 82 |
+
("cvt", "CvtConfig"),
|
| 83 |
+
("dab-detr", "DabDetrConfig"),
|
| 84 |
+
("dac", "DacConfig"),
|
| 85 |
+
("data2vec-audio", "Data2VecAudioConfig"),
|
| 86 |
+
("data2vec-text", "Data2VecTextConfig"),
|
| 87 |
+
("data2vec-vision", "Data2VecVisionConfig"),
|
| 88 |
+
("dbrx", "DbrxConfig"),
|
| 89 |
+
("deberta", "DebertaConfig"),
|
| 90 |
+
("deberta-v2", "DebertaV2Config"),
|
| 91 |
+
("decision_transformer", "DecisionTransformerConfig"),
|
| 92 |
+
("deepseek_v3", "DeepseekV3Config"),
|
| 93 |
+
("deformable_detr", "DeformableDetrConfig"),
|
| 94 |
+
("deit", "DeiTConfig"),
|
| 95 |
+
("depth_anything", "DepthAnythingConfig"),
|
| 96 |
+
("depth_pro", "DepthProConfig"),
|
| 97 |
+
("deta", "DetaConfig"),
|
| 98 |
+
("detr", "DetrConfig"),
|
| 99 |
+
("diffllama", "DiffLlamaConfig"),
|
| 100 |
+
("dinat", "DinatConfig"),
|
| 101 |
+
("dinov2", "Dinov2Config"),
|
| 102 |
+
("dinov2_with_registers", "Dinov2WithRegistersConfig"),
|
| 103 |
+
("distilbert", "DistilBertConfig"),
|
| 104 |
+
("donut-swin", "DonutSwinConfig"),
|
| 105 |
+
("dpr", "DPRConfig"),
|
| 106 |
+
("dpt", "DPTConfig"),
|
| 107 |
+
("efficientformer", "EfficientFormerConfig"),
|
| 108 |
+
("efficientnet", "EfficientNetConfig"),
|
| 109 |
+
("electra", "ElectraConfig"),
|
| 110 |
+
("emu3", "Emu3Config"),
|
| 111 |
+
("encodec", "EncodecConfig"),
|
| 112 |
+
("encoder-decoder", "EncoderDecoderConfig"),
|
| 113 |
+
("ernie", "ErnieConfig"),
|
| 114 |
+
("ernie_m", "ErnieMConfig"),
|
| 115 |
+
("esm", "EsmConfig"),
|
| 116 |
+
("falcon", "FalconConfig"),
|
| 117 |
+
("falcon_mamba", "FalconMambaConfig"),
|
| 118 |
+
("fastspeech2_conformer", "FastSpeech2ConformerConfig"),
|
| 119 |
+
("flaubert", "FlaubertConfig"),
|
| 120 |
+
("flava", "FlavaConfig"),
|
| 121 |
+
("fnet", "FNetConfig"),
|
| 122 |
+
("focalnet", "FocalNetConfig"),
|
| 123 |
+
("fsmt", "FSMTConfig"),
|
| 124 |
+
("funnel", "FunnelConfig"),
|
| 125 |
+
("fuyu", "FuyuConfig"),
|
| 126 |
+
("gemma", "GemmaConfig"),
|
| 127 |
+
("gemma2", "Gemma2Config"),
|
| 128 |
+
("gemma3", "Gemma3Config"),
|
| 129 |
+
("gemma3_text", "Gemma3TextConfig"),
|
| 130 |
+
("git", "GitConfig"),
|
| 131 |
+
("glm", "GlmConfig"),
|
| 132 |
+
("glm4", "Glm4Config"),
|
| 133 |
+
("glpn", "GLPNConfig"),
|
| 134 |
+
("got_ocr2", "GotOcr2Config"),
|
| 135 |
+
("gpt-sw3", "GPT2Config"),
|
| 136 |
+
("gpt2", "GPT2Config"),
|
| 137 |
+
("gpt_bigcode", "GPTBigCodeConfig"),
|
| 138 |
+
("gpt_neo", "GPTNeoConfig"),
|
| 139 |
+
("gpt_neox", "GPTNeoXConfig"),
|
| 140 |
+
("gpt_neox_japanese", "GPTNeoXJapaneseConfig"),
|
| 141 |
+
("gptj", "GPTJConfig"),
|
| 142 |
+
("gptsan-japanese", "GPTSanJapaneseConfig"),
|
| 143 |
+
("granite", "GraniteConfig"),
|
| 144 |
+
("granitemoe", "GraniteMoeConfig"),
|
| 145 |
+
("granitemoeshared", "GraniteMoeSharedConfig"),
|
| 146 |
+
("granitevision", "LlavaNextConfig"),
|
| 147 |
+
("graphormer", "GraphormerConfig"),
|
| 148 |
+
("grounding-dino", "GroundingDinoConfig"),
|
| 149 |
+
("groupvit", "GroupViTConfig"),
|
| 150 |
+
("helium", "HeliumConfig"),
|
| 151 |
+
("hiera", "HieraConfig"),
|
| 152 |
+
("hubert", "HubertConfig"),
|
| 153 |
+
("ibert", "IBertConfig"),
|
| 154 |
+
("idefics", "IdeficsConfig"),
|
| 155 |
+
("idefics2", "Idefics2Config"),
|
| 156 |
+
("idefics3", "Idefics3Config"),
|
| 157 |
+
("idefics3_vision", "Idefics3VisionConfig"),
|
| 158 |
+
("ijepa", "IJepaConfig"),
|
| 159 |
+
("imagegpt", "ImageGPTConfig"),
|
| 160 |
+
("informer", "InformerConfig"),
|
| 161 |
+
("instructblip", "InstructBlipConfig"),
|
| 162 |
+
("instructblipvideo", "InstructBlipVideoConfig"),
|
| 163 |
+
("jamba", "JambaConfig"),
|
| 164 |
+
("jetmoe", "JetMoeConfig"),
|
| 165 |
+
("jukebox", "JukeboxConfig"),
|
| 166 |
+
("kosmos-2", "Kosmos2Config"),
|
| 167 |
+
("layoutlm", "LayoutLMConfig"),
|
| 168 |
+
("layoutlmv2", "LayoutLMv2Config"),
|
| 169 |
+
("layoutlmv3", "LayoutLMv3Config"),
|
| 170 |
+
("led", "LEDConfig"),
|
| 171 |
+
("levit", "LevitConfig"),
|
| 172 |
+
("lilt", "LiltConfig"),
|
| 173 |
+
("llama", "LlamaConfig"),
|
| 174 |
+
("llama4", "Llama4Config"),
|
| 175 |
+
("llama4_text", "Llama4TextConfig"),
|
| 176 |
+
("llava", "LlavaConfig"),
|
| 177 |
+
("llava_next", "LlavaNextConfig"),
|
| 178 |
+
("llava_next_video", "LlavaNextVideoConfig"),
|
| 179 |
+
("llava_onevision", "LlavaOnevisionConfig"),
|
| 180 |
+
("longformer", "LongformerConfig"),
|
| 181 |
+
("longt5", "LongT5Config"),
|
| 182 |
+
("luke", "LukeConfig"),
|
| 183 |
+
("lxmert", "LxmertConfig"),
|
| 184 |
+
("m2m_100", "M2M100Config"),
|
| 185 |
+
("mamba", "MambaConfig"),
|
| 186 |
+
("mamba2", "Mamba2Config"),
|
| 187 |
+
("marian", "MarianConfig"),
|
| 188 |
+
("markuplm", "MarkupLMConfig"),
|
| 189 |
+
("mask2former", "Mask2FormerConfig"),
|
| 190 |
+
("maskformer", "MaskFormerConfig"),
|
| 191 |
+
("maskformer-swin", "MaskFormerSwinConfig"),
|
| 192 |
+
("mbart", "MBartConfig"),
|
| 193 |
+
("mctct", "MCTCTConfig"),
|
| 194 |
+
("mega", "MegaConfig"),
|
| 195 |
+
("megatron-bert", "MegatronBertConfig"),
|
| 196 |
+
("mgp-str", "MgpstrConfig"),
|
| 197 |
+
("mimi", "MimiConfig"),
|
| 198 |
+
("mistral", "MistralConfig"),
|
| 199 |
+
("mistral3", "Mistral3Config"),
|
| 200 |
+
("mixtral", "MixtralConfig"),
|
| 201 |
+
("mllama", "MllamaConfig"),
|
| 202 |
+
("mobilebert", "MobileBertConfig"),
|
| 203 |
+
("mobilenet_v1", "MobileNetV1Config"),
|
| 204 |
+
("mobilenet_v2", "MobileNetV2Config"),
|
| 205 |
+
("mobilevit", "MobileViTConfig"),
|
| 206 |
+
("mobilevitv2", "MobileViTV2Config"),
|
| 207 |
+
("modernbert", "ModernBertConfig"),
|
| 208 |
+
("moonshine", "MoonshineConfig"),
|
| 209 |
+
("moshi", "MoshiConfig"),
|
| 210 |
+
("mpnet", "MPNetConfig"),
|
| 211 |
+
("mpt", "MptConfig"),
|
| 212 |
+
("mra", "MraConfig"),
|
| 213 |
+
("mt5", "MT5Config"),
|
| 214 |
+
("musicgen", "MusicgenConfig"),
|
| 215 |
+
("musicgen_melody", "MusicgenMelodyConfig"),
|
| 216 |
+
("mvp", "MvpConfig"),
|
| 217 |
+
("nat", "NatConfig"),
|
| 218 |
+
("nemotron", "NemotronConfig"),
|
| 219 |
+
("nezha", "NezhaConfig"),
|
| 220 |
+
("nllb-moe", "NllbMoeConfig"),
|
| 221 |
+
("nougat", "VisionEncoderDecoderConfig"),
|
| 222 |
+
("nystromformer", "NystromformerConfig"),
|
| 223 |
+
("olmo", "OlmoConfig"),
|
| 224 |
+
("olmo2", "Olmo2Config"),
|
| 225 |
+
("olmoe", "OlmoeConfig"),
|
| 226 |
+
("omdet-turbo", "OmDetTurboConfig"),
|
| 227 |
+
("oneformer", "OneFormerConfig"),
|
| 228 |
+
("open-llama", "OpenLlamaConfig"),
|
| 229 |
+
("openai-gpt", "OpenAIGPTConfig"),
|
| 230 |
+
("opt", "OPTConfig"),
|
| 231 |
+
("owlv2", "Owlv2Config"),
|
| 232 |
+
("owlvit", "OwlViTConfig"),
|
| 233 |
+
("paligemma", "PaliGemmaConfig"),
|
| 234 |
+
("patchtsmixer", "PatchTSMixerConfig"),
|
| 235 |
+
("patchtst", "PatchTSTConfig"),
|
| 236 |
+
("pegasus", "PegasusConfig"),
|
| 237 |
+
("pegasus_x", "PegasusXConfig"),
|
| 238 |
+
("perceiver", "PerceiverConfig"),
|
| 239 |
+
("persimmon", "PersimmonConfig"),
|
| 240 |
+
("phi", "PhiConfig"),
|
| 241 |
+
("phi3", "Phi3Config"),
|
| 242 |
+
("phi4_multimodal", "Phi4MultimodalConfig"),
|
| 243 |
+
("phimoe", "PhimoeConfig"),
|
| 244 |
+
("pix2struct", "Pix2StructConfig"),
|
| 245 |
+
("pixtral", "PixtralVisionConfig"),
|
| 246 |
+
("plbart", "PLBartConfig"),
|
| 247 |
+
("poolformer", "PoolFormerConfig"),
|
| 248 |
+
("pop2piano", "Pop2PianoConfig"),
|
| 249 |
+
("prompt_depth_anything", "PromptDepthAnythingConfig"),
|
| 250 |
+
("prophetnet", "ProphetNetConfig"),
|
| 251 |
+
("pvt", "PvtConfig"),
|
| 252 |
+
("pvt_v2", "PvtV2Config"),
|
| 253 |
+
("qdqbert", "QDQBertConfig"),
|
| 254 |
+
("qwen2", "Qwen2Config"),
|
| 255 |
+
("qwen2_5_vl", "Qwen2_5_VLConfig"),
|
| 256 |
+
("qwen2_audio", "Qwen2AudioConfig"),
|
| 257 |
+
("qwen2_audio_encoder", "Qwen2AudioEncoderConfig"),
|
| 258 |
+
("qwen2_moe", "Qwen2MoeConfig"),
|
| 259 |
+
("qwen2_vl", "Qwen2VLConfig"),
|
| 260 |
+
("qwen3", "Qwen3Config"),
|
| 261 |
+
("qwen3_moe", "Qwen3MoeConfig"),
|
| 262 |
+
("rag", "RagConfig"),
|
| 263 |
+
("realm", "RealmConfig"),
|
| 264 |
+
("recurrent_gemma", "RecurrentGemmaConfig"),
|
| 265 |
+
("reformer", "ReformerConfig"),
|
| 266 |
+
("regnet", "RegNetConfig"),
|
| 267 |
+
("rembert", "RemBertConfig"),
|
| 268 |
+
("resnet", "ResNetConfig"),
|
| 269 |
+
("retribert", "RetriBertConfig"),
|
| 270 |
+
("roberta", "RobertaConfig"),
|
| 271 |
+
("roberta-prelayernorm", "RobertaPreLayerNormConfig"),
|
| 272 |
+
("roc_bert", "RoCBertConfig"),
|
| 273 |
+
("roformer", "RoFormerConfig"),
|
| 274 |
+
("rt_detr", "RTDetrConfig"),
|
| 275 |
+
("rt_detr_resnet", "RTDetrResNetConfig"),
|
| 276 |
+
("rt_detr_v2", "RTDetrV2Config"),
|
| 277 |
+
("rwkv", "RwkvConfig"),
|
| 278 |
+
("sam", "SamConfig"),
|
| 279 |
+
("sam_vision_model", "SamVisionConfig"),
|
| 280 |
+
("seamless_m4t", "SeamlessM4TConfig"),
|
| 281 |
+
("seamless_m4t_v2", "SeamlessM4Tv2Config"),
|
| 282 |
+
("segformer", "SegformerConfig"),
|
| 283 |
+
("seggpt", "SegGptConfig"),
|
| 284 |
+
("sew", "SEWConfig"),
|
| 285 |
+
("sew-d", "SEWDConfig"),
|
| 286 |
+
("shieldgemma2", "ShieldGemma2Config"),
|
| 287 |
+
("siglip", "SiglipConfig"),
|
| 288 |
+
("siglip2", "Siglip2Config"),
|
| 289 |
+
("siglip_vision_model", "SiglipVisionConfig"),
|
| 290 |
+
("smolvlm", "SmolVLMConfig"),
|
| 291 |
+
("smolvlm_vision", "SmolVLMVisionConfig"),
|
| 292 |
+
("speech-encoder-decoder", "SpeechEncoderDecoderConfig"),
|
| 293 |
+
("speech_to_text", "Speech2TextConfig"),
|
| 294 |
+
("speech_to_text_2", "Speech2Text2Config"),
|
| 295 |
+
("speecht5", "SpeechT5Config"),
|
| 296 |
+
("splinter", "SplinterConfig"),
|
| 297 |
+
("squeezebert", "SqueezeBertConfig"),
|
| 298 |
+
("stablelm", "StableLmConfig"),
|
| 299 |
+
("starcoder2", "Starcoder2Config"),
|
| 300 |
+
("superglue", "SuperGlueConfig"),
|
| 301 |
+
("superpoint", "SuperPointConfig"),
|
| 302 |
+
("swiftformer", "SwiftFormerConfig"),
|
| 303 |
+
("swin", "SwinConfig"),
|
| 304 |
+
("swin2sr", "Swin2SRConfig"),
|
| 305 |
+
("swinv2", "Swinv2Config"),
|
| 306 |
+
("switch_transformers", "SwitchTransformersConfig"),
|
| 307 |
+
("t5", "T5Config"),
|
| 308 |
+
("table-transformer", "TableTransformerConfig"),
|
| 309 |
+
("tapas", "TapasConfig"),
|
| 310 |
+
("textnet", "TextNetConfig"),
|
| 311 |
+
("time_series_transformer", "TimeSeriesTransformerConfig"),
|
| 312 |
+
("timesformer", "TimesformerConfig"),
|
| 313 |
+
("timm_backbone", "TimmBackboneConfig"),
|
| 314 |
+
("timm_wrapper", "TimmWrapperConfig"),
|
| 315 |
+
("trajectory_transformer", "TrajectoryTransformerConfig"),
|
| 316 |
+
("transfo-xl", "TransfoXLConfig"),
|
| 317 |
+
("trocr", "TrOCRConfig"),
|
| 318 |
+
("tvlt", "TvltConfig"),
|
| 319 |
+
("tvp", "TvpConfig"),
|
| 320 |
+
("udop", "UdopConfig"),
|
| 321 |
+
("umt5", "UMT5Config"),
|
| 322 |
+
("unispeech", "UniSpeechConfig"),
|
| 323 |
+
("unispeech-sat", "UniSpeechSatConfig"),
|
| 324 |
+
("univnet", "UnivNetConfig"),
|
| 325 |
+
("upernet", "UperNetConfig"),
|
| 326 |
+
("van", "VanConfig"),
|
| 327 |
+
("video_llava", "VideoLlavaConfig"),
|
| 328 |
+
("videomae", "VideoMAEConfig"),
|
| 329 |
+
("vilt", "ViltConfig"),
|
| 330 |
+
("vipllava", "VipLlavaConfig"),
|
| 331 |
+
("vision-encoder-decoder", "VisionEncoderDecoderConfig"),
|
| 332 |
+
("vision-text-dual-encoder", "VisionTextDualEncoderConfig"),
|
| 333 |
+
("visual_bert", "VisualBertConfig"),
|
| 334 |
+
("vit", "ViTConfig"),
|
| 335 |
+
("vit_hybrid", "ViTHybridConfig"),
|
| 336 |
+
("vit_mae", "ViTMAEConfig"),
|
| 337 |
+
("vit_msn", "ViTMSNConfig"),
|
| 338 |
+
("vitdet", "VitDetConfig"),
|
| 339 |
+
("vitmatte", "VitMatteConfig"),
|
| 340 |
+
("vitpose", "VitPoseConfig"),
|
| 341 |
+
("vitpose_backbone", "VitPoseBackboneConfig"),
|
| 342 |
+
("vits", "VitsConfig"),
|
| 343 |
+
("vivit", "VivitConfig"),
|
| 344 |
+
("wav2vec2", "Wav2Vec2Config"),
|
| 345 |
+
("wav2vec2-bert", "Wav2Vec2BertConfig"),
|
| 346 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerConfig"),
|
| 347 |
+
("wavlm", "WavLMConfig"),
|
| 348 |
+
("whisper", "WhisperConfig"),
|
| 349 |
+
("xclip", "XCLIPConfig"),
|
| 350 |
+
("xglm", "XGLMConfig"),
|
| 351 |
+
("xlm", "XLMConfig"),
|
| 352 |
+
("xlm-prophetnet", "XLMProphetNetConfig"),
|
| 353 |
+
("xlm-roberta", "XLMRobertaConfig"),
|
| 354 |
+
("xlm-roberta-xl", "XLMRobertaXLConfig"),
|
| 355 |
+
("xlnet", "XLNetConfig"),
|
| 356 |
+
("xmod", "XmodConfig"),
|
| 357 |
+
("yolos", "YolosConfig"),
|
| 358 |
+
("yoso", "YosoConfig"),
|
| 359 |
+
("zamba", "ZambaConfig"),
|
| 360 |
+
("zamba2", "Zamba2Config"),
|
| 361 |
+
("zoedepth", "ZoeDepthConfig"),
|
| 362 |
+
]
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
MODEL_NAMES_MAPPING = OrderedDict(
|
| 367 |
+
[
|
| 368 |
+
# Add full (and cased) model names here
|
| 369 |
+
("albert", "ALBERT"),
|
| 370 |
+
("align", "ALIGN"),
|
| 371 |
+
("altclip", "AltCLIP"),
|
| 372 |
+
("aria", "Aria"),
|
| 373 |
+
("aria_text", "AriaText"),
|
| 374 |
+
("audio-spectrogram-transformer", "Audio Spectrogram Transformer"),
|
| 375 |
+
("autoformer", "Autoformer"),
|
| 376 |
+
("aya_vision", "AyaVision"),
|
| 377 |
+
("bamba", "Bamba"),
|
| 378 |
+
("bark", "Bark"),
|
| 379 |
+
("bart", "BART"),
|
| 380 |
+
("barthez", "BARThez"),
|
| 381 |
+
("bartpho", "BARTpho"),
|
| 382 |
+
("beit", "BEiT"),
|
| 383 |
+
("bert", "BERT"),
|
| 384 |
+
("bert-generation", "Bert Generation"),
|
| 385 |
+
("bert-japanese", "BertJapanese"),
|
| 386 |
+
("bertweet", "BERTweet"),
|
| 387 |
+
("big_bird", "BigBird"),
|
| 388 |
+
("bigbird_pegasus", "BigBird-Pegasus"),
|
| 389 |
+
("biogpt", "BioGpt"),
|
| 390 |
+
("bit", "BiT"),
|
| 391 |
+
("blenderbot", "Blenderbot"),
|
| 392 |
+
("blenderbot-small", "BlenderbotSmall"),
|
| 393 |
+
("blip", "BLIP"),
|
| 394 |
+
("blip-2", "BLIP-2"),
|
| 395 |
+
("bloom", "BLOOM"),
|
| 396 |
+
("bort", "BORT"),
|
| 397 |
+
("bridgetower", "BridgeTower"),
|
| 398 |
+
("bros", "BROS"),
|
| 399 |
+
("byt5", "ByT5"),
|
| 400 |
+
("camembert", "CamemBERT"),
|
| 401 |
+
("canine", "CANINE"),
|
| 402 |
+
("chameleon", "Chameleon"),
|
| 403 |
+
("chinese_clip", "Chinese-CLIP"),
|
| 404 |
+
("chinese_clip_vision_model", "ChineseCLIPVisionModel"),
|
| 405 |
+
("clap", "CLAP"),
|
| 406 |
+
("clip", "CLIP"),
|
| 407 |
+
("clip_text_model", "CLIPTextModel"),
|
| 408 |
+
("clip_vision_model", "CLIPVisionModel"),
|
| 409 |
+
("clipseg", "CLIPSeg"),
|
| 410 |
+
("clvp", "CLVP"),
|
| 411 |
+
("code_llama", "CodeLlama"),
|
| 412 |
+
("codegen", "CodeGen"),
|
| 413 |
+
("cohere", "Cohere"),
|
| 414 |
+
("cohere2", "Cohere2"),
|
| 415 |
+
("colpali", "ColPali"),
|
| 416 |
+
("conditional_detr", "Conditional DETR"),
|
| 417 |
+
("convbert", "ConvBERT"),
|
| 418 |
+
("convnext", "ConvNeXT"),
|
| 419 |
+
("convnextv2", "ConvNeXTV2"),
|
| 420 |
+
("cpm", "CPM"),
|
| 421 |
+
("cpmant", "CPM-Ant"),
|
| 422 |
+
("ctrl", "CTRL"),
|
| 423 |
+
("cvt", "CvT"),
|
| 424 |
+
("dab-detr", "DAB-DETR"),
|
| 425 |
+
("dac", "DAC"),
|
| 426 |
+
("data2vec-audio", "Data2VecAudio"),
|
| 427 |
+
("data2vec-text", "Data2VecText"),
|
| 428 |
+
("data2vec-vision", "Data2VecVision"),
|
| 429 |
+
("dbrx", "DBRX"),
|
| 430 |
+
("deberta", "DeBERTa"),
|
| 431 |
+
("deberta-v2", "DeBERTa-v2"),
|
| 432 |
+
("decision_transformer", "Decision Transformer"),
|
| 433 |
+
("deepseek_v3", "DeepSeek-V3"),
|
| 434 |
+
("deformable_detr", "Deformable DETR"),
|
| 435 |
+
("deit", "DeiT"),
|
| 436 |
+
("deplot", "DePlot"),
|
| 437 |
+
("depth_anything", "Depth Anything"),
|
| 438 |
+
("depth_anything_v2", "Depth Anything V2"),
|
| 439 |
+
("depth_pro", "DepthPro"),
|
| 440 |
+
("deta", "DETA"),
|
| 441 |
+
("detr", "DETR"),
|
| 442 |
+
("dialogpt", "DialoGPT"),
|
| 443 |
+
("diffllama", "DiffLlama"),
|
| 444 |
+
("dinat", "DiNAT"),
|
| 445 |
+
("dinov2", "DINOv2"),
|
| 446 |
+
("dinov2_with_registers", "DINOv2 with Registers"),
|
| 447 |
+
("distilbert", "DistilBERT"),
|
| 448 |
+
("dit", "DiT"),
|
| 449 |
+
("donut-swin", "DonutSwin"),
|
| 450 |
+
("dpr", "DPR"),
|
| 451 |
+
("dpt", "DPT"),
|
| 452 |
+
("efficientformer", "EfficientFormer"),
|
| 453 |
+
("efficientnet", "EfficientNet"),
|
| 454 |
+
("electra", "ELECTRA"),
|
| 455 |
+
("emu3", "Emu3"),
|
| 456 |
+
("encodec", "EnCodec"),
|
| 457 |
+
("encoder-decoder", "Encoder decoder"),
|
| 458 |
+
("ernie", "ERNIE"),
|
| 459 |
+
("ernie_m", "ErnieM"),
|
| 460 |
+
("esm", "ESM"),
|
| 461 |
+
("falcon", "Falcon"),
|
| 462 |
+
("falcon3", "Falcon3"),
|
| 463 |
+
("falcon_mamba", "FalconMamba"),
|
| 464 |
+
("fastspeech2_conformer", "FastSpeech2Conformer"),
|
| 465 |
+
("flan-t5", "FLAN-T5"),
|
| 466 |
+
("flan-ul2", "FLAN-UL2"),
|
| 467 |
+
("flaubert", "FlauBERT"),
|
| 468 |
+
("flava", "FLAVA"),
|
| 469 |
+
("fnet", "FNet"),
|
| 470 |
+
("focalnet", "FocalNet"),
|
| 471 |
+
("fsmt", "FairSeq Machine-Translation"),
|
| 472 |
+
("funnel", "Funnel Transformer"),
|
| 473 |
+
("fuyu", "Fuyu"),
|
| 474 |
+
("gemma", "Gemma"),
|
| 475 |
+
("gemma2", "Gemma2"),
|
| 476 |
+
("gemma3", "Gemma3ForConditionalGeneration"),
|
| 477 |
+
("gemma3_text", "Gemma3ForCausalLM"),
|
| 478 |
+
("git", "GIT"),
|
| 479 |
+
("glm", "GLM"),
|
| 480 |
+
("glm4", "glm4"),
|
| 481 |
+
("glpn", "GLPN"),
|
| 482 |
+
("got_ocr2", "GOT-OCR2"),
|
| 483 |
+
("gpt-sw3", "GPT-Sw3"),
|
| 484 |
+
("gpt2", "OpenAI GPT-2"),
|
| 485 |
+
("gpt_bigcode", "GPTBigCode"),
|
| 486 |
+
("gpt_neo", "GPT Neo"),
|
| 487 |
+
("gpt_neox", "GPT NeoX"),
|
| 488 |
+
("gpt_neox_japanese", "GPT NeoX Japanese"),
|
| 489 |
+
("gptj", "GPT-J"),
|
| 490 |
+
("gptsan-japanese", "GPTSAN-japanese"),
|
| 491 |
+
("granite", "Granite"),
|
| 492 |
+
("granitemoe", "GraniteMoeMoe"),
|
| 493 |
+
("granitemoeshared", "GraniteMoeSharedMoe"),
|
| 494 |
+
("granitevision", "LLaVA-NeXT"),
|
| 495 |
+
("graphormer", "Graphormer"),
|
| 496 |
+
("grounding-dino", "Grounding DINO"),
|
| 497 |
+
("groupvit", "GroupViT"),
|
| 498 |
+
("helium", "Helium"),
|
| 499 |
+
("herbert", "HerBERT"),
|
| 500 |
+
("hiera", "Hiera"),
|
| 501 |
+
("hubert", "Hubert"),
|
| 502 |
+
("ibert", "I-BERT"),
|
| 503 |
+
("idefics", "IDEFICS"),
|
| 504 |
+
("idefics2", "Idefics2"),
|
| 505 |
+
("idefics3", "Idefics3"),
|
| 506 |
+
("idefics3_vision", "Idefics3VisionTransformer"),
|
| 507 |
+
("ijepa", "I-JEPA"),
|
| 508 |
+
("imagegpt", "ImageGPT"),
|
| 509 |
+
("informer", "Informer"),
|
| 510 |
+
("instructblip", "InstructBLIP"),
|
| 511 |
+
("instructblipvideo", "InstructBlipVideo"),
|
| 512 |
+
("jamba", "Jamba"),
|
| 513 |
+
("jetmoe", "JetMoe"),
|
| 514 |
+
("jukebox", "Jukebox"),
|
| 515 |
+
("kosmos-2", "KOSMOS-2"),
|
| 516 |
+
("layoutlm", "LayoutLM"),
|
| 517 |
+
("layoutlmv2", "LayoutLMv2"),
|
| 518 |
+
("layoutlmv3", "LayoutLMv3"),
|
| 519 |
+
("layoutxlm", "LayoutXLM"),
|
| 520 |
+
("led", "LED"),
|
| 521 |
+
("levit", "LeViT"),
|
| 522 |
+
("lilt", "LiLT"),
|
| 523 |
+
("llama", "LLaMA"),
|
| 524 |
+
("llama2", "Llama2"),
|
| 525 |
+
("llama3", "Llama3"),
|
| 526 |
+
("llama4", "Llama4"),
|
| 527 |
+
("llama4_text", "Llama4ForCausalLM"),
|
| 528 |
+
("llava", "LLaVa"),
|
| 529 |
+
("llava_next", "LLaVA-NeXT"),
|
| 530 |
+
("llava_next_video", "LLaVa-NeXT-Video"),
|
| 531 |
+
("llava_onevision", "LLaVA-Onevision"),
|
| 532 |
+
("longformer", "Longformer"),
|
| 533 |
+
("longt5", "LongT5"),
|
| 534 |
+
("luke", "LUKE"),
|
| 535 |
+
("lxmert", "LXMERT"),
|
| 536 |
+
("m2m_100", "M2M100"),
|
| 537 |
+
("madlad-400", "MADLAD-400"),
|
| 538 |
+
("mamba", "Mamba"),
|
| 539 |
+
("mamba2", "mamba2"),
|
| 540 |
+
("marian", "Marian"),
|
| 541 |
+
("markuplm", "MarkupLM"),
|
| 542 |
+
("mask2former", "Mask2Former"),
|
| 543 |
+
("maskformer", "MaskFormer"),
|
| 544 |
+
("maskformer-swin", "MaskFormerSwin"),
|
| 545 |
+
("matcha", "MatCha"),
|
| 546 |
+
("mbart", "mBART"),
|
| 547 |
+
("mbart50", "mBART-50"),
|
| 548 |
+
("mctct", "M-CTC-T"),
|
| 549 |
+
("mega", "MEGA"),
|
| 550 |
+
("megatron-bert", "Megatron-BERT"),
|
| 551 |
+
("megatron_gpt2", "Megatron-GPT2"),
|
| 552 |
+
("mgp-str", "MGP-STR"),
|
| 553 |
+
("mimi", "Mimi"),
|
| 554 |
+
("mistral", "Mistral"),
|
| 555 |
+
("mistral3", "Mistral3"),
|
| 556 |
+
("mixtral", "Mixtral"),
|
| 557 |
+
("mllama", "Mllama"),
|
| 558 |
+
("mluke", "mLUKE"),
|
| 559 |
+
("mms", "MMS"),
|
| 560 |
+
("mobilebert", "MobileBERT"),
|
| 561 |
+
("mobilenet_v1", "MobileNetV1"),
|
| 562 |
+
("mobilenet_v2", "MobileNetV2"),
|
| 563 |
+
("mobilevit", "MobileViT"),
|
| 564 |
+
("mobilevitv2", "MobileViTV2"),
|
| 565 |
+
("modernbert", "ModernBERT"),
|
| 566 |
+
("moonshine", "Moonshine"),
|
| 567 |
+
("moshi", "Moshi"),
|
| 568 |
+
("mpnet", "MPNet"),
|
| 569 |
+
("mpt", "MPT"),
|
| 570 |
+
("mra", "MRA"),
|
| 571 |
+
("mt5", "MT5"),
|
| 572 |
+
("musicgen", "MusicGen"),
|
| 573 |
+
("musicgen_melody", "MusicGen Melody"),
|
| 574 |
+
("mvp", "MVP"),
|
| 575 |
+
("myt5", "myt5"),
|
| 576 |
+
("nat", "NAT"),
|
| 577 |
+
("nemotron", "Nemotron"),
|
| 578 |
+
("nezha", "Nezha"),
|
| 579 |
+
("nllb", "NLLB"),
|
| 580 |
+
("nllb-moe", "NLLB-MOE"),
|
| 581 |
+
("nougat", "Nougat"),
|
| 582 |
+
("nystromformer", "Nyströmformer"),
|
| 583 |
+
("olmo", "OLMo"),
|
| 584 |
+
("olmo2", "OLMo2"),
|
| 585 |
+
("olmoe", "OLMoE"),
|
| 586 |
+
("omdet-turbo", "OmDet-Turbo"),
|
| 587 |
+
("oneformer", "OneFormer"),
|
| 588 |
+
("open-llama", "OpenLlama"),
|
| 589 |
+
("openai-gpt", "OpenAI GPT"),
|
| 590 |
+
("opt", "OPT"),
|
| 591 |
+
("owlv2", "OWLv2"),
|
| 592 |
+
("owlvit", "OWL-ViT"),
|
| 593 |
+
("paligemma", "PaliGemma"),
|
| 594 |
+
("patchtsmixer", "PatchTSMixer"),
|
| 595 |
+
("patchtst", "PatchTST"),
|
| 596 |
+
("pegasus", "Pegasus"),
|
| 597 |
+
("pegasus_x", "PEGASUS-X"),
|
| 598 |
+
("perceiver", "Perceiver"),
|
| 599 |
+
("persimmon", "Persimmon"),
|
| 600 |
+
("phi", "Phi"),
|
| 601 |
+
("phi3", "Phi3"),
|
| 602 |
+
("phi4_multimodal", "Phi4Multimodal"),
|
| 603 |
+
("phimoe", "Phimoe"),
|
| 604 |
+
("phobert", "PhoBERT"),
|
| 605 |
+
("pix2struct", "Pix2Struct"),
|
| 606 |
+
("pixtral", "Pixtral"),
|
| 607 |
+
("plbart", "PLBart"),
|
| 608 |
+
("poolformer", "PoolFormer"),
|
| 609 |
+
("pop2piano", "Pop2Piano"),
|
| 610 |
+
("prompt_depth_anything", "PromptDepthAnything"),
|
| 611 |
+
("prophetnet", "ProphetNet"),
|
| 612 |
+
("pvt", "PVT"),
|
| 613 |
+
("pvt_v2", "PVTv2"),
|
| 614 |
+
("qdqbert", "QDQBert"),
|
| 615 |
+
("qwen2", "Qwen2"),
|
| 616 |
+
("qwen2_5_vl", "Qwen2_5_VL"),
|
| 617 |
+
("qwen2_audio", "Qwen2Audio"),
|
| 618 |
+
("qwen2_audio_encoder", "Qwen2AudioEncoder"),
|
| 619 |
+
("qwen2_moe", "Qwen2MoE"),
|
| 620 |
+
("qwen2_vl", "Qwen2VL"),
|
| 621 |
+
("qwen3", "Qwen3"),
|
| 622 |
+
("qwen3_moe", "Qwen3MoE"),
|
| 623 |
+
("rag", "RAG"),
|
| 624 |
+
("realm", "REALM"),
|
| 625 |
+
("recurrent_gemma", "RecurrentGemma"),
|
| 626 |
+
("reformer", "Reformer"),
|
| 627 |
+
("regnet", "RegNet"),
|
| 628 |
+
("rembert", "RemBERT"),
|
| 629 |
+
("resnet", "ResNet"),
|
| 630 |
+
("retribert", "RetriBERT"),
|
| 631 |
+
("roberta", "RoBERTa"),
|
| 632 |
+
("roberta-prelayernorm", "RoBERTa-PreLayerNorm"),
|
| 633 |
+
("roc_bert", "RoCBert"),
|
| 634 |
+
("roformer", "RoFormer"),
|
| 635 |
+
("rt_detr", "RT-DETR"),
|
| 636 |
+
("rt_detr_resnet", "RT-DETR-ResNet"),
|
| 637 |
+
("rt_detr_v2", "RT-DETRv2"),
|
| 638 |
+
("rwkv", "RWKV"),
|
| 639 |
+
("sam", "SAM"),
|
| 640 |
+
("sam_vision_model", "SamVisionModel"),
|
| 641 |
+
("seamless_m4t", "SeamlessM4T"),
|
| 642 |
+
("seamless_m4t_v2", "SeamlessM4Tv2"),
|
| 643 |
+
("segformer", "SegFormer"),
|
| 644 |
+
("seggpt", "SegGPT"),
|
| 645 |
+
("sew", "SEW"),
|
| 646 |
+
("sew-d", "SEW-D"),
|
| 647 |
+
("shieldgemma2", "Shieldgemma2"),
|
| 648 |
+
("siglip", "SigLIP"),
|
| 649 |
+
("siglip2", "SigLIP2"),
|
| 650 |
+
("siglip2_vision_model", "Siglip2VisionModel"),
|
| 651 |
+
("siglip_vision_model", "SiglipVisionModel"),
|
| 652 |
+
("smolvlm", "SmolVLM"),
|
| 653 |
+
("smolvlm_vision", "SmolVLMVisionTransformer"),
|
| 654 |
+
("speech-encoder-decoder", "Speech Encoder decoder"),
|
| 655 |
+
("speech_to_text", "Speech2Text"),
|
| 656 |
+
("speech_to_text_2", "Speech2Text2"),
|
| 657 |
+
("speecht5", "SpeechT5"),
|
| 658 |
+
("splinter", "Splinter"),
|
| 659 |
+
("squeezebert", "SqueezeBERT"),
|
| 660 |
+
("stablelm", "StableLm"),
|
| 661 |
+
("starcoder2", "Starcoder2"),
|
| 662 |
+
("superglue", "SuperGlue"),
|
| 663 |
+
("superpoint", "SuperPoint"),
|
| 664 |
+
("swiftformer", "SwiftFormer"),
|
| 665 |
+
("swin", "Swin Transformer"),
|
| 666 |
+
("swin2sr", "Swin2SR"),
|
| 667 |
+
("swinv2", "Swin Transformer V2"),
|
| 668 |
+
("switch_transformers", "SwitchTransformers"),
|
| 669 |
+
("t5", "T5"),
|
| 670 |
+
("t5v1.1", "T5v1.1"),
|
| 671 |
+
("table-transformer", "Table Transformer"),
|
| 672 |
+
("tapas", "TAPAS"),
|
| 673 |
+
("tapex", "TAPEX"),
|
| 674 |
+
("textnet", "TextNet"),
|
| 675 |
+
("time_series_transformer", "Time Series Transformer"),
|
| 676 |
+
("timesformer", "TimeSformer"),
|
| 677 |
+
("timm_backbone", "TimmBackbone"),
|
| 678 |
+
("timm_wrapper", "TimmWrapperModel"),
|
| 679 |
+
("trajectory_transformer", "Trajectory Transformer"),
|
| 680 |
+
("transfo-xl", "Transformer-XL"),
|
| 681 |
+
("trocr", "TrOCR"),
|
| 682 |
+
("tvlt", "TVLT"),
|
| 683 |
+
("tvp", "TVP"),
|
| 684 |
+
("udop", "UDOP"),
|
| 685 |
+
("ul2", "UL2"),
|
| 686 |
+
("umt5", "UMT5"),
|
| 687 |
+
("unispeech", "UniSpeech"),
|
| 688 |
+
("unispeech-sat", "UniSpeechSat"),
|
| 689 |
+
("univnet", "UnivNet"),
|
| 690 |
+
("upernet", "UPerNet"),
|
| 691 |
+
("van", "VAN"),
|
| 692 |
+
("video_llava", "VideoLlava"),
|
| 693 |
+
("videomae", "VideoMAE"),
|
| 694 |
+
("vilt", "ViLT"),
|
| 695 |
+
("vipllava", "VipLlava"),
|
| 696 |
+
("vision-encoder-decoder", "Vision Encoder decoder"),
|
| 697 |
+
("vision-text-dual-encoder", "VisionTextDualEncoder"),
|
| 698 |
+
("visual_bert", "VisualBERT"),
|
| 699 |
+
("vit", "ViT"),
|
| 700 |
+
("vit_hybrid", "ViT Hybrid"),
|
| 701 |
+
("vit_mae", "ViTMAE"),
|
| 702 |
+
("vit_msn", "ViTMSN"),
|
| 703 |
+
("vitdet", "VitDet"),
|
| 704 |
+
("vitmatte", "ViTMatte"),
|
| 705 |
+
("vitpose", "ViTPose"),
|
| 706 |
+
("vitpose_backbone", "ViTPoseBackbone"),
|
| 707 |
+
("vits", "VITS"),
|
| 708 |
+
("vivit", "ViViT"),
|
| 709 |
+
("wav2vec2", "Wav2Vec2"),
|
| 710 |
+
("wav2vec2-bert", "Wav2Vec2-BERT"),
|
| 711 |
+
("wav2vec2-conformer", "Wav2Vec2-Conformer"),
|
| 712 |
+
("wav2vec2_phoneme", "Wav2Vec2Phoneme"),
|
| 713 |
+
("wavlm", "WavLM"),
|
| 714 |
+
("whisper", "Whisper"),
|
| 715 |
+
("xclip", "X-CLIP"),
|
| 716 |
+
("xglm", "XGLM"),
|
| 717 |
+
("xlm", "XLM"),
|
| 718 |
+
("xlm-prophetnet", "XLM-ProphetNet"),
|
| 719 |
+
("xlm-roberta", "XLM-RoBERTa"),
|
| 720 |
+
("xlm-roberta-xl", "XLM-RoBERTa-XL"),
|
| 721 |
+
("xlm-v", "XLM-V"),
|
| 722 |
+
("xlnet", "XLNet"),
|
| 723 |
+
("xls_r", "XLS-R"),
|
| 724 |
+
("xlsr_wav2vec2", "XLSR-Wav2Vec2"),
|
| 725 |
+
("xmod", "X-MOD"),
|
| 726 |
+
("yolos", "YOLOS"),
|
| 727 |
+
("yoso", "YOSO"),
|
| 728 |
+
("zamba", "Zamba"),
|
| 729 |
+
("zamba2", "Zamba2"),
|
| 730 |
+
("zoedepth", "ZoeDepth"),
|
| 731 |
+
]
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
# This is tied to the processing `-` -> `_` in `model_type_to_module_name`. For example, instead of putting
|
| 735 |
+
# `transfo-xl` (as in `CONFIG_MAPPING_NAMES`), we should use `transfo_xl`.
|
| 736 |
+
DEPRECATED_MODELS = [
|
| 737 |
+
"bort",
|
| 738 |
+
"deta",
|
| 739 |
+
"efficientformer",
|
| 740 |
+
"ernie_m",
|
| 741 |
+
"gptsan_japanese",
|
| 742 |
+
"graphormer",
|
| 743 |
+
"jukebox",
|
| 744 |
+
"mctct",
|
| 745 |
+
"mega",
|
| 746 |
+
"mmbt",
|
| 747 |
+
"nat",
|
| 748 |
+
"nezha",
|
| 749 |
+
"open_llama",
|
| 750 |
+
"qdqbert",
|
| 751 |
+
"realm",
|
| 752 |
+
"retribert",
|
| 753 |
+
"speech_to_text_2",
|
| 754 |
+
"tapex",
|
| 755 |
+
"trajectory_transformer",
|
| 756 |
+
"transfo_xl",
|
| 757 |
+
"tvlt",
|
| 758 |
+
"van",
|
| 759 |
+
"vit_hybrid",
|
| 760 |
+
"xlm_prophetnet",
|
| 761 |
+
]
|
| 762 |
+
|
| 763 |
+
SPECIAL_MODEL_TYPE_TO_MODULE_NAME = OrderedDict(
|
| 764 |
+
[
|
| 765 |
+
("openai-gpt", "openai"),
|
| 766 |
+
("data2vec-audio", "data2vec"),
|
| 767 |
+
("data2vec-text", "data2vec"),
|
| 768 |
+
("data2vec-vision", "data2vec"),
|
| 769 |
+
("donut-swin", "donut"),
|
| 770 |
+
("kosmos-2", "kosmos2"),
|
| 771 |
+
("maskformer-swin", "maskformer"),
|
| 772 |
+
("xclip", "x_clip"),
|
| 773 |
+
("clip_vision_model", "clip"),
|
| 774 |
+
("qwen2_audio_encoder", "qwen2_audio"),
|
| 775 |
+
("clip_text_model", "clip"),
|
| 776 |
+
("aria_text", "aria"),
|
| 777 |
+
("gemma3_text", "gemma3"),
|
| 778 |
+
("idefics3_vision", "idefics3"),
|
| 779 |
+
("siglip_vision_model", "siglip"),
|
| 780 |
+
("smolvlm_vision", "smolvlm"),
|
| 781 |
+
("chinese_clip_vision_model", "chinese_clip"),
|
| 782 |
+
("rt_detr_resnet", "rt_detr"),
|
| 783 |
+
("granitevision", "llava_next"),
|
| 784 |
+
("sam_vision_model", "sam"),
|
| 785 |
+
("llama4_text", "llama4"),
|
| 786 |
+
]
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
def model_type_to_module_name(key):
|
| 791 |
+
"""Converts a config key to the corresponding module."""
|
| 792 |
+
# Special treatment
|
| 793 |
+
if key in SPECIAL_MODEL_TYPE_TO_MODULE_NAME:
|
| 794 |
+
key = SPECIAL_MODEL_TYPE_TO_MODULE_NAME[key]
|
| 795 |
+
|
| 796 |
+
if key in DEPRECATED_MODELS:
|
| 797 |
+
key = f"deprecated.{key}"
|
| 798 |
+
return key
|
| 799 |
+
|
| 800 |
+
key = key.replace("-", "_")
|
| 801 |
+
if key in DEPRECATED_MODELS:
|
| 802 |
+
key = f"deprecated.{key}"
|
| 803 |
+
|
| 804 |
+
return key
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
def config_class_to_model_type(config):
|
| 808 |
+
"""Converts a config class name to the corresponding model type"""
|
| 809 |
+
for key, cls in CONFIG_MAPPING_NAMES.items():
|
| 810 |
+
if cls == config:
|
| 811 |
+
return key
|
| 812 |
+
# if key not found check in extra content
|
| 813 |
+
for key, cls in CONFIG_MAPPING._extra_content.items():
|
| 814 |
+
if cls.__name__ == config:
|
| 815 |
+
return key
|
| 816 |
+
return None
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
class _LazyConfigMapping(OrderedDict):
|
| 820 |
+
"""
|
| 821 |
+
A dictionary that lazily load its values when they are requested.
|
| 822 |
+
"""
|
| 823 |
+
|
| 824 |
+
def __init__(self, mapping):
|
| 825 |
+
self._mapping = mapping
|
| 826 |
+
self._extra_content = {}
|
| 827 |
+
self._modules = {}
|
| 828 |
+
|
| 829 |
+
def __getitem__(self, key):
|
| 830 |
+
if key in self._extra_content:
|
| 831 |
+
return self._extra_content[key]
|
| 832 |
+
if key not in self._mapping:
|
| 833 |
+
raise KeyError(key)
|
| 834 |
+
value = self._mapping[key]
|
| 835 |
+
module_name = model_type_to_module_name(key)
|
| 836 |
+
if module_name not in self._modules:
|
| 837 |
+
self._modules[module_name] = importlib.import_module(f".{module_name}", "transformers.models")
|
| 838 |
+
if hasattr(self._modules[module_name], value):
|
| 839 |
+
return getattr(self._modules[module_name], value)
|
| 840 |
+
|
| 841 |
+
# Some of the mappings have entries model_type -> config of another model type. In that case we try to grab the
|
| 842 |
+
# object at the top level.
|
| 843 |
+
transformers_module = importlib.import_module("transformers")
|
| 844 |
+
return getattr(transformers_module, value)
|
| 845 |
+
|
| 846 |
+
def keys(self):
|
| 847 |
+
return list(self._mapping.keys()) + list(self._extra_content.keys())
|
| 848 |
+
|
| 849 |
+
def values(self):
|
| 850 |
+
return [self[k] for k in self._mapping.keys()] + list(self._extra_content.values())
|
| 851 |
+
|
| 852 |
+
def items(self):
|
| 853 |
+
return [(k, self[k]) for k in self._mapping.keys()] + list(self._extra_content.items())
|
| 854 |
+
|
| 855 |
+
def __iter__(self):
|
| 856 |
+
return iter(list(self._mapping.keys()) + list(self._extra_content.keys()))
|
| 857 |
+
|
| 858 |
+
def __contains__(self, item):
|
| 859 |
+
return item in self._mapping or item in self._extra_content
|
| 860 |
+
|
| 861 |
+
def register(self, key, value, exist_ok=False):
|
| 862 |
+
"""
|
| 863 |
+
Register a new configuration in this mapping.
|
| 864 |
+
"""
|
| 865 |
+
if key in self._mapping.keys() and not exist_ok:
|
| 866 |
+
raise ValueError(f"'{key}' is already used by a Transformers config, pick another name.")
|
| 867 |
+
self._extra_content[key] = value
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
CONFIG_MAPPING = _LazyConfigMapping(CONFIG_MAPPING_NAMES)
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
class _LazyLoadAllMappings(OrderedDict):
|
| 874 |
+
"""
|
| 875 |
+
A mapping that will load all pairs of key values at the first access (either by indexing, requestions keys, values,
|
| 876 |
+
etc.)
|
| 877 |
+
|
| 878 |
+
Args:
|
| 879 |
+
mapping: The mapping to load.
|
| 880 |
+
"""
|
| 881 |
+
|
| 882 |
+
def __init__(self, mapping):
|
| 883 |
+
self._mapping = mapping
|
| 884 |
+
self._initialized = False
|
| 885 |
+
self._data = {}
|
| 886 |
+
|
| 887 |
+
def _initialize(self):
|
| 888 |
+
if self._initialized:
|
| 889 |
+
return
|
| 890 |
+
|
| 891 |
+
for model_type, map_name in self._mapping.items():
|
| 892 |
+
module_name = model_type_to_module_name(model_type)
|
| 893 |
+
module = importlib.import_module(f".{module_name}", "transformers.models")
|
| 894 |
+
mapping = getattr(module, map_name)
|
| 895 |
+
self._data.update(mapping)
|
| 896 |
+
|
| 897 |
+
self._initialized = True
|
| 898 |
+
|
| 899 |
+
def __getitem__(self, key):
|
| 900 |
+
self._initialize()
|
| 901 |
+
return self._data[key]
|
| 902 |
+
|
| 903 |
+
def keys(self):
|
| 904 |
+
self._initialize()
|
| 905 |
+
return self._data.keys()
|
| 906 |
+
|
| 907 |
+
def values(self):
|
| 908 |
+
self._initialize()
|
| 909 |
+
return self._data.values()
|
| 910 |
+
|
| 911 |
+
def items(self):
|
| 912 |
+
self._initialize()
|
| 913 |
+
return self._data.keys()
|
| 914 |
+
|
| 915 |
+
def __iter__(self):
|
| 916 |
+
self._initialize()
|
| 917 |
+
return iter(self._data)
|
| 918 |
+
|
| 919 |
+
def __contains__(self, item):
|
| 920 |
+
self._initialize()
|
| 921 |
+
return item in self._data
|
| 922 |
+
|
| 923 |
+
|
| 924 |
+
def _get_class_name(model_class: Union[str, List[str]]):
|
| 925 |
+
if isinstance(model_class, (list, tuple)):
|
| 926 |
+
return " or ".join([f"[`{c}`]" for c in model_class if c is not None])
|
| 927 |
+
return f"[`{model_class}`]"
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
def _list_model_options(indent, config_to_class=None, use_model_types=True):
|
| 931 |
+
if config_to_class is None and not use_model_types:
|
| 932 |
+
raise ValueError("Using `use_model_types=False` requires a `config_to_class` dictionary.")
|
| 933 |
+
if use_model_types:
|
| 934 |
+
if config_to_class is None:
|
| 935 |
+
model_type_to_name = {model_type: f"[`{config}`]" for model_type, config in CONFIG_MAPPING_NAMES.items()}
|
| 936 |
+
else:
|
| 937 |
+
model_type_to_name = {
|
| 938 |
+
model_type: _get_class_name(model_class)
|
| 939 |
+
for model_type, model_class in config_to_class.items()
|
| 940 |
+
if model_type in MODEL_NAMES_MAPPING
|
| 941 |
+
}
|
| 942 |
+
lines = [
|
| 943 |
+
f"{indent}- **{model_type}** -- {model_type_to_name[model_type]} ({MODEL_NAMES_MAPPING[model_type]} model)"
|
| 944 |
+
for model_type in sorted(model_type_to_name.keys())
|
| 945 |
+
]
|
| 946 |
+
else:
|
| 947 |
+
config_to_name = {
|
| 948 |
+
CONFIG_MAPPING_NAMES[config]: _get_class_name(clas)
|
| 949 |
+
for config, clas in config_to_class.items()
|
| 950 |
+
if config in CONFIG_MAPPING_NAMES
|
| 951 |
+
}
|
| 952 |
+
config_to_model_name = {
|
| 953 |
+
config: MODEL_NAMES_MAPPING[model_type] for model_type, config in CONFIG_MAPPING_NAMES.items()
|
| 954 |
+
}
|
| 955 |
+
lines = [
|
| 956 |
+
f"{indent}- [`{config_name}`] configuration class:"
|
| 957 |
+
f" {config_to_name[config_name]} ({config_to_model_name[config_name]} model)"
|
| 958 |
+
for config_name in sorted(config_to_name.keys())
|
| 959 |
+
]
|
| 960 |
+
return "\n".join(lines)
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
def replace_list_option_in_docstrings(config_to_class=None, use_model_types=True):
|
| 964 |
+
def docstring_decorator(fn):
|
| 965 |
+
docstrings = fn.__doc__
|
| 966 |
+
if docstrings is None:
|
| 967 |
+
# Example: -OO
|
| 968 |
+
return fn
|
| 969 |
+
lines = docstrings.split("\n")
|
| 970 |
+
i = 0
|
| 971 |
+
while i < len(lines) and re.search(r"^(\s*)List options\s*$", lines[i]) is None:
|
| 972 |
+
i += 1
|
| 973 |
+
if i < len(lines):
|
| 974 |
+
indent = re.search(r"^(\s*)List options\s*$", lines[i]).groups()[0]
|
| 975 |
+
if use_model_types:
|
| 976 |
+
indent = f"{indent} "
|
| 977 |
+
lines[i] = _list_model_options(indent, config_to_class=config_to_class, use_model_types=use_model_types)
|
| 978 |
+
docstrings = "\n".join(lines)
|
| 979 |
+
else:
|
| 980 |
+
raise ValueError(
|
| 981 |
+
f"The function {fn} should have an empty 'List options' in its docstring as placeholder, current"
|
| 982 |
+
f" docstring is:\n{docstrings}"
|
| 983 |
+
)
|
| 984 |
+
fn.__doc__ = docstrings
|
| 985 |
+
return fn
|
| 986 |
+
|
| 987 |
+
return docstring_decorator
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
class AutoConfig:
|
| 991 |
+
r"""
|
| 992 |
+
This is a generic configuration class that will be instantiated as one of the configuration classes of the library
|
| 993 |
+
when created with the [`~AutoConfig.from_pretrained`] class method.
|
| 994 |
+
|
| 995 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 996 |
+
"""
|
| 997 |
+
|
| 998 |
+
def __init__(self):
|
| 999 |
+
raise EnvironmentError(
|
| 1000 |
+
"AutoConfig is designed to be instantiated "
|
| 1001 |
+
"using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method."
|
| 1002 |
+
)
|
| 1003 |
+
|
| 1004 |
+
@classmethod
|
| 1005 |
+
def for_model(cls, model_type: str, *args, **kwargs):
|
| 1006 |
+
if model_type in CONFIG_MAPPING:
|
| 1007 |
+
config_class = CONFIG_MAPPING[model_type]
|
| 1008 |
+
return config_class(*args, **kwargs)
|
| 1009 |
+
raise ValueError(
|
| 1010 |
+
f"Unrecognized model identifier: {model_type}. Should contain one of {', '.join(CONFIG_MAPPING.keys())}"
|
| 1011 |
+
)
|
| 1012 |
+
|
| 1013 |
+
@classmethod
|
| 1014 |
+
@replace_list_option_in_docstrings()
|
| 1015 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 1016 |
+
r"""
|
| 1017 |
+
Instantiate one of the configuration classes of the library from a pretrained model configuration.
|
| 1018 |
+
|
| 1019 |
+
The configuration class to instantiate is selected based on the `model_type` property of the config object that
|
| 1020 |
+
is loaded, or when it's missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 1021 |
+
|
| 1022 |
+
List options
|
| 1023 |
+
|
| 1024 |
+
Args:
|
| 1025 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 1026 |
+
Can be either:
|
| 1027 |
+
|
| 1028 |
+
- A string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
| 1029 |
+
huggingface.co.
|
| 1030 |
+
- A path to a *directory* containing a configuration file saved using the
|
| 1031 |
+
[`~PretrainedConfig.save_pretrained`] method, or the [`~PreTrainedModel.save_pretrained`] method,
|
| 1032 |
+
e.g., `./my_model_directory/`.
|
| 1033 |
+
- A path or url to a saved configuration JSON *file*, e.g.,
|
| 1034 |
+
`./my_model_directory/configuration.json`.
|
| 1035 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 1036 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 1037 |
+
standard cache should not be used.
|
| 1038 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 1039 |
+
Whether or not to force the (re-)download the model weights and configuration files and override the
|
| 1040 |
+
cached versions if they exist.
|
| 1041 |
+
resume_download:
|
| 1042 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 1043 |
+
Will be removed in v5 of Transformers.
|
| 1044 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 1045 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 1046 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 1047 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 1048 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 1049 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 1050 |
+
identifier allowed by git.
|
| 1051 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 1052 |
+
If `False`, then this function returns just the final configuration object.
|
| 1053 |
+
|
| 1054 |
+
If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
|
| 1055 |
+
dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
|
| 1056 |
+
part of `kwargs` which has not been used to update `config` and is otherwise ignored.
|
| 1057 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 1058 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 1059 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 1060 |
+
execute code present on the Hub on your local machine.
|
| 1061 |
+
kwargs(additional keyword arguments, *optional*):
|
| 1062 |
+
The values in kwargs of any keys which are configuration attributes will be used to override the loaded
|
| 1063 |
+
values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
|
| 1064 |
+
by the `return_unused_kwargs` keyword parameter.
|
| 1065 |
+
|
| 1066 |
+
Examples:
|
| 1067 |
+
|
| 1068 |
+
```python
|
| 1069 |
+
>>> from transformers import AutoConfig
|
| 1070 |
+
|
| 1071 |
+
>>> # Download configuration from huggingface.co and cache.
|
| 1072 |
+
>>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased")
|
| 1073 |
+
|
| 1074 |
+
>>> # Download configuration from huggingface.co (user-uploaded) and cache.
|
| 1075 |
+
>>> config = AutoConfig.from_pretrained("dbmdz/bert-base-german-cased")
|
| 1076 |
+
|
| 1077 |
+
>>> # If configuration file is in a directory (e.g., was saved using *save_pretrained('./test/saved_model/')*).
|
| 1078 |
+
>>> config = AutoConfig.from_pretrained("./test/bert_saved_model/")
|
| 1079 |
+
|
| 1080 |
+
>>> # Load a specific configuration file.
|
| 1081 |
+
>>> config = AutoConfig.from_pretrained("./test/bert_saved_model/my_configuration.json")
|
| 1082 |
+
|
| 1083 |
+
>>> # Change some config attributes when loading a pretrained config.
|
| 1084 |
+
>>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False)
|
| 1085 |
+
>>> config.output_attentions
|
| 1086 |
+
True
|
| 1087 |
+
|
| 1088 |
+
>>> config, unused_kwargs = AutoConfig.from_pretrained(
|
| 1089 |
+
... "google-bert/bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True
|
| 1090 |
+
... )
|
| 1091 |
+
>>> config.output_attentions
|
| 1092 |
+
True
|
| 1093 |
+
|
| 1094 |
+
>>> unused_kwargs
|
| 1095 |
+
{'foo': False}
|
| 1096 |
+
```"""
|
| 1097 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 1098 |
+
if use_auth_token is not None:
|
| 1099 |
+
warnings.warn(
|
| 1100 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 1101 |
+
FutureWarning,
|
| 1102 |
+
)
|
| 1103 |
+
if kwargs.get("token", None) is not None:
|
| 1104 |
+
raise ValueError(
|
| 1105 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 1106 |
+
)
|
| 1107 |
+
kwargs["token"] = use_auth_token
|
| 1108 |
+
|
| 1109 |
+
kwargs["_from_auto"] = True
|
| 1110 |
+
kwargs["name_or_path"] = pretrained_model_name_or_path
|
| 1111 |
+
trust_remote_code = kwargs.pop("trust_remote_code", None)
|
| 1112 |
+
code_revision = kwargs.pop("code_revision", None)
|
| 1113 |
+
|
| 1114 |
+
config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 1115 |
+
has_remote_code = "auto_map" in config_dict and "AutoConfig" in config_dict["auto_map"]
|
| 1116 |
+
has_local_code = "model_type" in config_dict and config_dict["model_type"] in CONFIG_MAPPING
|
| 1117 |
+
trust_remote_code = resolve_trust_remote_code(
|
| 1118 |
+
trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
|
| 1119 |
+
)
|
| 1120 |
+
|
| 1121 |
+
if has_remote_code and trust_remote_code:
|
| 1122 |
+
class_ref = config_dict["auto_map"]["AutoConfig"]
|
| 1123 |
+
config_class = get_class_from_dynamic_module(
|
| 1124 |
+
class_ref, pretrained_model_name_or_path, code_revision=code_revision, **kwargs
|
| 1125 |
+
)
|
| 1126 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
| 1127 |
+
config_class.register_for_auto_class()
|
| 1128 |
+
return config_class.from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 1129 |
+
elif "model_type" in config_dict:
|
| 1130 |
+
try:
|
| 1131 |
+
config_class = CONFIG_MAPPING[config_dict["model_type"]]
|
| 1132 |
+
except KeyError:
|
| 1133 |
+
raise ValueError(
|
| 1134 |
+
f"The checkpoint you are trying to load has model type `{config_dict['model_type']}` "
|
| 1135 |
+
"but Transformers does not recognize this architecture. This could be because of an "
|
| 1136 |
+
"issue with the checkpoint, or because your version of Transformers is out of date.\n\n"
|
| 1137 |
+
"You can update Transformers with the command `pip install --upgrade transformers`. If this "
|
| 1138 |
+
"does not work, and the checkpoint is very new, then there may not be a release version "
|
| 1139 |
+
"that supports this model yet. In this case, you can get the most up-to-date code by installing "
|
| 1140 |
+
"Transformers from source with the command "
|
| 1141 |
+
"`pip install git+https://github.com/huggingface/transformers.git`"
|
| 1142 |
+
)
|
| 1143 |
+
return config_class.from_dict(config_dict, **unused_kwargs)
|
| 1144 |
+
else:
|
| 1145 |
+
# Fallback: use pattern matching on the string.
|
| 1146 |
+
# We go from longer names to shorter names to catch roberta before bert (for instance)
|
| 1147 |
+
for pattern in sorted(CONFIG_MAPPING.keys(), key=len, reverse=True):
|
| 1148 |
+
if pattern in str(pretrained_model_name_or_path):
|
| 1149 |
+
return CONFIG_MAPPING[pattern].from_dict(config_dict, **unused_kwargs)
|
| 1150 |
+
|
| 1151 |
+
raise ValueError(
|
| 1152 |
+
f"Unrecognized model in {pretrained_model_name_or_path}. "
|
| 1153 |
+
f"Should have a `model_type` key in its {CONFIG_NAME}, or contain one of the following strings "
|
| 1154 |
+
f"in its name: {', '.join(CONFIG_MAPPING.keys())}"
|
| 1155 |
+
)
|
| 1156 |
+
|
| 1157 |
+
@staticmethod
|
| 1158 |
+
def register(model_type, config, exist_ok=False):
|
| 1159 |
+
"""
|
| 1160 |
+
Register a new configuration for this class.
|
| 1161 |
+
|
| 1162 |
+
Args:
|
| 1163 |
+
model_type (`str`): The model type like "bert" or "gpt".
|
| 1164 |
+
config ([`PretrainedConfig`]): The config to register.
|
| 1165 |
+
"""
|
| 1166 |
+
if issubclass(config, PretrainedConfig) and config.model_type != model_type:
|
| 1167 |
+
raise ValueError(
|
| 1168 |
+
"The config you are passing has a `model_type` attribute that is not consistent with the model type "
|
| 1169 |
+
f"you passed (config has {config.model_type} and you passed {model_type}. Fix one of those so they "
|
| 1170 |
+
"match!"
|
| 1171 |
+
)
|
| 1172 |
+
CONFIG_MAPPING.register(model_type, config, exist_ok=exist_ok)
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_bert.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""BERT model configuration"""
|
| 17 |
+
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
from typing import Mapping
|
| 20 |
+
|
| 21 |
+
from ...configuration_utils import PretrainedConfig
|
| 22 |
+
from ...onnx import OnnxConfig
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class BertConfig(PretrainedConfig):
|
| 30 |
+
r"""
|
| 31 |
+
This is the configuration class to store the configuration of a [`BertModel`] or a [`TFBertModel`]. It is used to
|
| 32 |
+
instantiate a BERT model according to the specified arguments, defining the model architecture. Instantiating a
|
| 33 |
+
configuration with the defaults will yield a similar configuration to that of the BERT
|
| 34 |
+
[google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased) architecture.
|
| 35 |
+
|
| 36 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 37 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 42 |
+
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
|
| 43 |
+
`inputs_ids` passed when calling [`BertModel`] or [`TFBertModel`].
|
| 44 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 45 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 46 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 47 |
+
Number of hidden layers in the Transformer encoder.
|
| 48 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 49 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 50 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 51 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 52 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
| 53 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 54 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 55 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 56 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 57 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 58 |
+
The dropout ratio for the attention probabilities.
|
| 59 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 60 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 61 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 62 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 63 |
+
The vocabulary size of the `token_type_ids` passed when calling [`BertModel`] or [`TFBertModel`].
|
| 64 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 65 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 66 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 67 |
+
The epsilon used by the layer normalization layers.
|
| 68 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 69 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 70 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 71 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 72 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 73 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 74 |
+
is_decoder (`bool`, *optional*, defaults to `False`):
|
| 75 |
+
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
|
| 76 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 77 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 78 |
+
relevant if `config.is_decoder=True`.
|
| 79 |
+
classifier_dropout (`float`, *optional*):
|
| 80 |
+
The dropout ratio for the classification head.
|
| 81 |
+
|
| 82 |
+
Examples:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
>>> from transformers import BertConfig, BertModel
|
| 86 |
+
|
| 87 |
+
>>> # Initializing a BERT google-bert/bert-base-uncased style configuration
|
| 88 |
+
>>> configuration = BertConfig()
|
| 89 |
+
|
| 90 |
+
>>> # Initializing a model (with random weights) from the google-bert/bert-base-uncased style configuration
|
| 91 |
+
>>> model = BertModel(configuration)
|
| 92 |
+
|
| 93 |
+
>>> # Accessing the model configuration
|
| 94 |
+
>>> configuration = model.config
|
| 95 |
+
```"""
|
| 96 |
+
|
| 97 |
+
model_type = "bert"
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
vocab_size=30522,
|
| 102 |
+
hidden_size=768,
|
| 103 |
+
num_hidden_layers=12,
|
| 104 |
+
num_attention_heads=12,
|
| 105 |
+
intermediate_size=3072,
|
| 106 |
+
hidden_act="gelu",
|
| 107 |
+
hidden_dropout_prob=0.1,
|
| 108 |
+
attention_probs_dropout_prob=0.1,
|
| 109 |
+
max_position_embeddings=512,
|
| 110 |
+
type_vocab_size=2,
|
| 111 |
+
initializer_range=0.02,
|
| 112 |
+
layer_norm_eps=1e-12,
|
| 113 |
+
pad_token_id=0,
|
| 114 |
+
position_embedding_type="absolute",
|
| 115 |
+
use_cache=True,
|
| 116 |
+
classifier_dropout=None,
|
| 117 |
+
**kwargs,
|
| 118 |
+
):
|
| 119 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
| 120 |
+
|
| 121 |
+
self.vocab_size = vocab_size
|
| 122 |
+
self.hidden_size = hidden_size
|
| 123 |
+
self.num_hidden_layers = num_hidden_layers
|
| 124 |
+
self.num_attention_heads = num_attention_heads
|
| 125 |
+
self.hidden_act = hidden_act
|
| 126 |
+
self.intermediate_size = intermediate_size
|
| 127 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 128 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 129 |
+
self.max_position_embeddings = max_position_embeddings
|
| 130 |
+
self.type_vocab_size = type_vocab_size
|
| 131 |
+
self.initializer_range = initializer_range
|
| 132 |
+
self.layer_norm_eps = layer_norm_eps
|
| 133 |
+
self.position_embedding_type = position_embedding_type
|
| 134 |
+
self.use_cache = use_cache
|
| 135 |
+
self.classifier_dropout = classifier_dropout
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class BertOnnxConfig(OnnxConfig):
|
| 139 |
+
@property
|
| 140 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 141 |
+
if self.task == "multiple-choice":
|
| 142 |
+
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
|
| 143 |
+
else:
|
| 144 |
+
dynamic_axis = {0: "batch", 1: "sequence"}
|
| 145 |
+
return OrderedDict(
|
| 146 |
+
[
|
| 147 |
+
("input_ids", dynamic_axis),
|
| 148 |
+
("attention_mask", dynamic_axis),
|
| 149 |
+
("token_type_ids", dynamic_axis),
|
| 150 |
+
]
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
__all__ = ["BertConfig", "BertOnnxConfig"]
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_encoder_decoder.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PretrainedConfig
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
from ..auto import AutoConfig
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class EncoderDecoderConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
[`EncoderDecoderConfig`] is the configuration class to store the configuration of a [`EncoderDecoderModel`]. It is
|
| 29 |
+
used to instantiate an Encoder Decoder model according to the specified arguments, defining the encoder and decoder
|
| 30 |
+
configs.
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
kwargs (*optional*):
|
| 37 |
+
Dictionary of keyword arguments. Notably:
|
| 38 |
+
|
| 39 |
+
- **encoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines
|
| 40 |
+
the encoder config.
|
| 41 |
+
- **decoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines
|
| 42 |
+
the decoder config.
|
| 43 |
+
|
| 44 |
+
Examples:
|
| 45 |
+
|
| 46 |
+
```python
|
| 47 |
+
>>> from transformers import BertConfig, EncoderDecoderConfig, EncoderDecoderModel
|
| 48 |
+
|
| 49 |
+
>>> # Initializing a BERT google-bert/bert-base-uncased style configuration
|
| 50 |
+
>>> config_encoder = BertConfig()
|
| 51 |
+
>>> config_decoder = BertConfig()
|
| 52 |
+
|
| 53 |
+
>>> config = EncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)
|
| 54 |
+
|
| 55 |
+
>>> # Initializing a Bert2Bert model (with random weights) from the google-bert/bert-base-uncased style configurations
|
| 56 |
+
>>> model = EncoderDecoderModel(config=config)
|
| 57 |
+
|
| 58 |
+
>>> # Accessing the model configuration
|
| 59 |
+
>>> config_encoder = model.config.encoder
|
| 60 |
+
>>> config_decoder = model.config.decoder
|
| 61 |
+
>>> # set decoder config to causal lm
|
| 62 |
+
>>> config_decoder.is_decoder = True
|
| 63 |
+
>>> config_decoder.add_cross_attention = True
|
| 64 |
+
|
| 65 |
+
>>> # Saving the model, including its configuration
|
| 66 |
+
>>> model.save_pretrained("my-model")
|
| 67 |
+
|
| 68 |
+
>>> # loading model and config from pretrained folder
|
| 69 |
+
>>> encoder_decoder_config = EncoderDecoderConfig.from_pretrained("my-model")
|
| 70 |
+
>>> model = EncoderDecoderModel.from_pretrained("my-model", config=encoder_decoder_config)
|
| 71 |
+
```"""
|
| 72 |
+
|
| 73 |
+
model_type = "encoder-decoder"
|
| 74 |
+
sub_configs = {"encoder": AutoConfig, "decoder": AutoConfig}
|
| 75 |
+
is_composition = True
|
| 76 |
+
|
| 77 |
+
def __init__(self, **kwargs):
|
| 78 |
+
super().__init__(**kwargs)
|
| 79 |
+
if "encoder" not in kwargs or "decoder" not in kwargs:
|
| 80 |
+
raise ValueError(
|
| 81 |
+
f"A configuraton of type {self.model_type} cannot be instantiated because "
|
| 82 |
+
f"both `encoder` and `decoder` sub-configurations were not passed, only {kwargs}"
|
| 83 |
+
)
|
| 84 |
+
encoder_config = kwargs.pop("encoder")
|
| 85 |
+
encoder_model_type = encoder_config.pop("model_type")
|
| 86 |
+
decoder_config = kwargs.pop("decoder")
|
| 87 |
+
decoder_model_type = decoder_config.pop("model_type")
|
| 88 |
+
|
| 89 |
+
self.encoder = AutoConfig.for_model(encoder_model_type, **encoder_config)
|
| 90 |
+
self.decoder = AutoConfig.for_model(decoder_model_type, **decoder_config)
|
| 91 |
+
self.is_encoder_decoder = True
|
| 92 |
+
|
| 93 |
+
@classmethod
|
| 94 |
+
def from_encoder_decoder_configs(
|
| 95 |
+
cls, encoder_config: PretrainedConfig, decoder_config: PretrainedConfig, **kwargs
|
| 96 |
+
) -> PretrainedConfig:
|
| 97 |
+
r"""
|
| 98 |
+
Instantiate a [`EncoderDecoderConfig`] (or a derived class) from a pre-trained encoder model configuration and
|
| 99 |
+
decoder model configuration.
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
[`EncoderDecoderConfig`]: An instance of a configuration object
|
| 103 |
+
"""
|
| 104 |
+
logger.info("Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config")
|
| 105 |
+
decoder_config.is_decoder = True
|
| 106 |
+
decoder_config.add_cross_attention = True
|
| 107 |
+
|
| 108 |
+
return cls(encoder=encoder_config.to_dict(), decoder=decoder_config.to_dict(), **kwargs)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
__all__ = ["EncoderDecoderConfig"]
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_qwen3.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Qwen team, Alibaba Group 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 |
+
"""Qwen3 model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...modeling_rope_utils import rope_config_validation
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Qwen3Config(PretrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`Qwen3Model`]. It is used to instantiate a
|
| 28 |
+
Qwen3 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 29 |
+
with the defaults will yield a similar configuration to that of
|
| 30 |
+
Qwen3-8B [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B).
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
vocab_size (`int`, *optional*, defaults to 151936):
|
| 38 |
+
Vocabulary size of the Qwen3 model. Defines the number of different tokens that can be represented by the
|
| 39 |
+
`inputs_ids` passed when calling [`Qwen3Model`]
|
| 40 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 41 |
+
Dimension of the hidden representations.
|
| 42 |
+
intermediate_size (`int`, *optional*, defaults to 22016):
|
| 43 |
+
Dimension of the MLP representations.
|
| 44 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 45 |
+
Number of hidden layers in the Transformer encoder.
|
| 46 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 47 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 48 |
+
num_key_value_heads (`int`, *optional*, defaults to 32):
|
| 49 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 50 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 51 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 52 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 53 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 54 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
|
| 55 |
+
head_dim (`int`, *optional*, defaults to 128):
|
| 56 |
+
The attention head dimension.
|
| 57 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 58 |
+
The non-linear activation function (function or string) in the decoder.
|
| 59 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
| 60 |
+
The maximum sequence length that this model might ever be used with.
|
| 61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 63 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 64 |
+
The epsilon used by the rms normalization layers.
|
| 65 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 66 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 67 |
+
relevant if `config.is_decoder=True`.
|
| 68 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 69 |
+
Whether the model's input and output word embeddings should be tied.
|
| 70 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 71 |
+
The base period of the RoPE embeddings.
|
| 72 |
+
rope_scaling (`Dict`, *optional*):
|
| 73 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
| 74 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
| 75 |
+
accordingly.
|
| 76 |
+
Expected contents:
|
| 77 |
+
`rope_type` (`str`):
|
| 78 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
| 79 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
| 80 |
+
`factor` (`float`, *optional*):
|
| 81 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
| 82 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
| 83 |
+
original maximum pre-trained length.
|
| 84 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
| 85 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
| 86 |
+
pretraining.
|
| 87 |
+
`attention_factor` (`float`, *optional*):
|
| 88 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
| 89 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
| 90 |
+
`factor` field to infer the suggested value.
|
| 91 |
+
`beta_fast` (`float`, *optional*):
|
| 92 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
| 93 |
+
ramp function. If unspecified, it defaults to 32.
|
| 94 |
+
`beta_slow` (`float`, *optional*):
|
| 95 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
| 96 |
+
ramp function. If unspecified, it defaults to 1.
|
| 97 |
+
`short_factor` (`List[float]`, *optional*):
|
| 98 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
| 99 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 100 |
+
size divided by the number of attention heads divided by 2
|
| 101 |
+
`long_factor` (`List[float]`, *optional*):
|
| 102 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
| 103 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 104 |
+
size divided by the number of attention heads divided by 2
|
| 105 |
+
`low_freq_factor` (`float`, *optional*):
|
| 106 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
| 107 |
+
`high_freq_factor` (`float`, *optional*):
|
| 108 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
| 109 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
| 110 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 111 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
| 112 |
+
Whether to use sliding window attention.
|
| 113 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
| 114 |
+
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
| 115 |
+
max_window_layers (`int`, *optional*, defaults to 28):
|
| 116 |
+
The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
|
| 117 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 118 |
+
The dropout ratio for the attention probabilities.
|
| 119 |
+
|
| 120 |
+
```python
|
| 121 |
+
>>> from transformers import Qwen3Model, Qwen3Config
|
| 122 |
+
|
| 123 |
+
>>> # Initializing a Qwen3 style configuration
|
| 124 |
+
>>> configuration = Qwen3Config()
|
| 125 |
+
|
| 126 |
+
>>> # Initializing a model from the Qwen3-8B style configuration
|
| 127 |
+
>>> model = Qwen3Model(configuration)
|
| 128 |
+
|
| 129 |
+
>>> # Accessing the model configuration
|
| 130 |
+
>>> configuration = model.config
|
| 131 |
+
```"""
|
| 132 |
+
|
| 133 |
+
model_type = "qwen3"
|
| 134 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 135 |
+
|
| 136 |
+
# Default tensor parallel plan for base model `Qwen3`
|
| 137 |
+
base_model_tp_plan = {
|
| 138 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 139 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 140 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 141 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 142 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 143 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 144 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 145 |
+
}
|
| 146 |
+
base_model_pp_plan = {
|
| 147 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 148 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 149 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
def __init__(
|
| 153 |
+
self,
|
| 154 |
+
vocab_size=151936,
|
| 155 |
+
hidden_size=4096,
|
| 156 |
+
intermediate_size=22016,
|
| 157 |
+
num_hidden_layers=32,
|
| 158 |
+
num_attention_heads=32,
|
| 159 |
+
num_key_value_heads=32,
|
| 160 |
+
head_dim=128,
|
| 161 |
+
hidden_act="silu",
|
| 162 |
+
max_position_embeddings=32768,
|
| 163 |
+
initializer_range=0.02,
|
| 164 |
+
rms_norm_eps=1e-6,
|
| 165 |
+
use_cache=True,
|
| 166 |
+
tie_word_embeddings=False,
|
| 167 |
+
rope_theta=10000.0,
|
| 168 |
+
rope_scaling=None,
|
| 169 |
+
attention_bias=False,
|
| 170 |
+
use_sliding_window=False,
|
| 171 |
+
sliding_window=4096,
|
| 172 |
+
max_window_layers=28,
|
| 173 |
+
attention_dropout=0.0,
|
| 174 |
+
**kwargs,
|
| 175 |
+
):
|
| 176 |
+
self.vocab_size = vocab_size
|
| 177 |
+
self.max_position_embeddings = max_position_embeddings
|
| 178 |
+
self.hidden_size = hidden_size
|
| 179 |
+
self.intermediate_size = intermediate_size
|
| 180 |
+
self.num_hidden_layers = num_hidden_layers
|
| 181 |
+
self.num_attention_heads = num_attention_heads
|
| 182 |
+
self.use_sliding_window = use_sliding_window
|
| 183 |
+
self.sliding_window = sliding_window # we check `use_sliding_window` in the modeling code
|
| 184 |
+
self.max_window_layers = max_window_layers
|
| 185 |
+
|
| 186 |
+
# for backward compatibility
|
| 187 |
+
if num_key_value_heads is None:
|
| 188 |
+
num_key_value_heads = num_attention_heads
|
| 189 |
+
|
| 190 |
+
self.num_key_value_heads = num_key_value_heads
|
| 191 |
+
self.head_dim = head_dim
|
| 192 |
+
self.hidden_act = hidden_act
|
| 193 |
+
self.initializer_range = initializer_range
|
| 194 |
+
self.rms_norm_eps = rms_norm_eps
|
| 195 |
+
self.use_cache = use_cache
|
| 196 |
+
self.rope_theta = rope_theta
|
| 197 |
+
self.rope_scaling = rope_scaling
|
| 198 |
+
self.attention_bias = attention_bias
|
| 199 |
+
self.attention_dropout = attention_dropout
|
| 200 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 201 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
| 202 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 203 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 204 |
+
rope_config_validation(self)
|
| 205 |
+
|
| 206 |
+
super().__init__(
|
| 207 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 208 |
+
**kwargs,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
__all__ = ["Qwen3Config"]
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_timm_backbone.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 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 |
+
|
| 16 |
+
"""Configuration for Backbone models"""
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PretrainedConfig
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TimmBackboneConfig(PretrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
This is the configuration class to store the configuration for a timm backbone [`TimmBackbone`].
|
| 28 |
+
|
| 29 |
+
It is used to instantiate a timm backbone model according to the specified arguments, defining the model.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
backbone (`str`, *optional*):
|
| 36 |
+
The timm checkpoint to load.
|
| 37 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 38 |
+
The number of input channels.
|
| 39 |
+
features_only (`bool`, *optional*, defaults to `True`):
|
| 40 |
+
Whether to output only the features or also the logits.
|
| 41 |
+
use_pretrained_backbone (`bool`, *optional*, defaults to `True`):
|
| 42 |
+
Whether to use a pretrained backbone.
|
| 43 |
+
out_indices (`List[int]`, *optional*):
|
| 44 |
+
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
|
| 45 |
+
many stages the model has). Will default to the last stage if unset.
|
| 46 |
+
freeze_batch_norm_2d (`bool`, *optional*, defaults to `False`):
|
| 47 |
+
Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`.
|
| 48 |
+
|
| 49 |
+
Example:
|
| 50 |
+
```python
|
| 51 |
+
>>> from transformers import TimmBackboneConfig, TimmBackbone
|
| 52 |
+
|
| 53 |
+
>>> # Initializing a timm backbone
|
| 54 |
+
>>> configuration = TimmBackboneConfig("resnet50")
|
| 55 |
+
|
| 56 |
+
>>> # Initializing a model from the configuration
|
| 57 |
+
>>> model = TimmBackbone(configuration)
|
| 58 |
+
|
| 59 |
+
>>> # Accessing the model configuration
|
| 60 |
+
>>> configuration = model.config
|
| 61 |
+
```
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
model_type = "timm_backbone"
|
| 65 |
+
|
| 66 |
+
def __init__(
|
| 67 |
+
self,
|
| 68 |
+
backbone=None,
|
| 69 |
+
num_channels=3,
|
| 70 |
+
features_only=True,
|
| 71 |
+
use_pretrained_backbone=True,
|
| 72 |
+
out_indices=None,
|
| 73 |
+
freeze_batch_norm_2d=False,
|
| 74 |
+
**kwargs,
|
| 75 |
+
):
|
| 76 |
+
super().__init__(**kwargs)
|
| 77 |
+
self.backbone = backbone
|
| 78 |
+
self.num_channels = num_channels
|
| 79 |
+
self.features_only = features_only
|
| 80 |
+
self.use_pretrained_backbone = use_pretrained_backbone
|
| 81 |
+
self.use_timm_backbone = True
|
| 82 |
+
self.out_indices = out_indices if out_indices is not None else [-1]
|
| 83 |
+
self.freeze_batch_norm_2d = freeze_batch_norm_2d
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
__all__ = ["TimmBackboneConfig"]
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/configuration_utils.py
ADDED
|
@@ -0,0 +1,1632 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Generation configuration class and utilities."""
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import warnings
|
| 21 |
+
from abc import ABC, abstractmethod
|
| 22 |
+
from dataclasses import dataclass, is_dataclass
|
| 23 |
+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
|
| 24 |
+
|
| 25 |
+
from .. import __version__
|
| 26 |
+
from ..configuration_utils import PretrainedConfig
|
| 27 |
+
from ..utils import (
|
| 28 |
+
GENERATION_CONFIG_NAME,
|
| 29 |
+
ExplicitEnum,
|
| 30 |
+
PushToHubMixin,
|
| 31 |
+
cached_file,
|
| 32 |
+
download_url,
|
| 33 |
+
extract_commit_hash,
|
| 34 |
+
is_remote_url,
|
| 35 |
+
is_torch_available,
|
| 36 |
+
logging,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if TYPE_CHECKING:
|
| 41 |
+
from ..modeling_utils import PreTrainedModel
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
METADATA_FIELDS = ("_from_model_config", "_commit_hash", "_original_object_hash", "transformers_version")
|
| 46 |
+
CACHE_CONFIG_MAPPING = {}
|
| 47 |
+
NEED_SETUP_CACHE_CLASSES_MAPPING = {}
|
| 48 |
+
QUANT_BACKEND_CLASSES_MAPPING = {}
|
| 49 |
+
ALL_CACHE_IMPLEMENTATIONS = []
|
| 50 |
+
|
| 51 |
+
if is_torch_available():
|
| 52 |
+
from ..cache_utils import (
|
| 53 |
+
HQQQuantizedCache,
|
| 54 |
+
HybridCache,
|
| 55 |
+
HybridChunkedCache,
|
| 56 |
+
MambaCache,
|
| 57 |
+
OffloadedStaticCache,
|
| 58 |
+
QuantizedCacheConfig,
|
| 59 |
+
QuantoQuantizedCache,
|
| 60 |
+
SlidingWindowCache,
|
| 61 |
+
StaticCache,
|
| 62 |
+
StaticCacheConfig,
|
| 63 |
+
)
|
| 64 |
+
from .logits_process import SynthIDTextWatermarkLogitsProcessor, WatermarkLogitsProcessor
|
| 65 |
+
|
| 66 |
+
CACHE_CONFIG_MAPPING["quantized"] = QuantizedCacheConfig
|
| 67 |
+
CACHE_CONFIG_MAPPING["static"] = StaticCacheConfig
|
| 68 |
+
NEED_SETUP_CACHE_CLASSES_MAPPING = {
|
| 69 |
+
"static": StaticCache,
|
| 70 |
+
"offloaded_static": OffloadedStaticCache,
|
| 71 |
+
"sliding_window": SlidingWindowCache,
|
| 72 |
+
"hybrid": HybridCache,
|
| 73 |
+
"hybrid_chunked": HybridChunkedCache,
|
| 74 |
+
"mamba": MambaCache,
|
| 75 |
+
}
|
| 76 |
+
QUANT_BACKEND_CLASSES_MAPPING = {"quanto": QuantoQuantizedCache, "HQQ": HQQQuantizedCache}
|
| 77 |
+
ALL_CACHE_IMPLEMENTATIONS = (
|
| 78 |
+
list(NEED_SETUP_CACHE_CLASSES_MAPPING.keys()) + list(CACHE_CONFIG_MAPPING.keys()) + ["offloaded", "dynamic"]
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class GenerationMode(ExplicitEnum):
|
| 83 |
+
"""
|
| 84 |
+
Possible generation modes, downstream of the [`~generation.GenerationMixin.generate`] method.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
# Non-beam methods
|
| 88 |
+
CONTRASTIVE_SEARCH = "contrastive_search"
|
| 89 |
+
GREEDY_SEARCH = "greedy_search"
|
| 90 |
+
SAMPLE = "sample"
|
| 91 |
+
ASSISTED_GENERATION = "assisted_generation"
|
| 92 |
+
DOLA_GENERATION = "dola_generation"
|
| 93 |
+
# Beam methods
|
| 94 |
+
BEAM_SEARCH = "beam_search"
|
| 95 |
+
BEAM_SAMPLE = "beam_sample"
|
| 96 |
+
CONSTRAINED_BEAM_SEARCH = "constrained_beam_search"
|
| 97 |
+
GROUP_BEAM_SEARCH = "group_beam_search"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class GenerationConfig(PushToHubMixin):
|
| 101 |
+
# no-format
|
| 102 |
+
"""
|
| 103 |
+
Class that holds a configuration for a generation task. A `generate` call supports the following generation methods
|
| 104 |
+
for text-decoder, text-to-text, speech-to-text, and vision-to-text models:
|
| 105 |
+
|
| 106 |
+
- *greedy decoding* if `num_beams=1` and `do_sample=False`
|
| 107 |
+
- *contrastive search* if `penalty_alpha>0.` and `top_k>1`
|
| 108 |
+
- *multinomial sampling* if `num_beams=1` and `do_sample=True`
|
| 109 |
+
- *beam-search decoding* if `num_beams>1` and `do_sample=False`
|
| 110 |
+
- *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`
|
| 111 |
+
- *diverse beam-search decoding* if `num_beams>1` and `num_beam_groups>1`
|
| 112 |
+
- *constrained beam-search decoding* if `constraints!=None` or `force_words_ids!=None`
|
| 113 |
+
- *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`
|
| 114 |
+
- *dola decoding* if `dola_layers` is passed to `.generate()`
|
| 115 |
+
|
| 116 |
+
To learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
|
| 117 |
+
|
| 118 |
+
<Tip>
|
| 119 |
+
|
| 120 |
+
A large number of these flags control the logits or the stopping criteria of the generation. Make sure you check
|
| 121 |
+
the [generate-related classes](https://huggingface.co/docs/transformers/internal/generation_utils) for a full
|
| 122 |
+
description of the possible manipulations, as well as examples of their usage.
|
| 123 |
+
|
| 124 |
+
</Tip>
|
| 125 |
+
|
| 126 |
+
Arg:
|
| 127 |
+
> Parameters that control the length of the output
|
| 128 |
+
|
| 129 |
+
max_length (`int`, *optional*, defaults to 20):
|
| 130 |
+
The maximum length the generated tokens can have. Corresponds to the length of the input prompt +
|
| 131 |
+
`max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set.
|
| 132 |
+
max_new_tokens (`int`, *optional*):
|
| 133 |
+
The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
|
| 134 |
+
min_length (`int`, *optional*, defaults to 0):
|
| 135 |
+
The minimum length of the sequence to be generated. Corresponds to the length of the input prompt +
|
| 136 |
+
`min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set.
|
| 137 |
+
min_new_tokens (`int`, *optional*):
|
| 138 |
+
The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.
|
| 139 |
+
early_stopping (`bool` or `str`, *optional*, defaults to `False`):
|
| 140 |
+
Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
|
| 141 |
+
`True`, where the generation stops as soon as there are `num_beams` complete candidates; `False`, where an
|
| 142 |
+
heuristic is applied and the generation stops when is it very unlikely to find better candidates;
|
| 143 |
+
`"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical
|
| 144 |
+
beam search algorithm).
|
| 145 |
+
max_time (`float`, *optional*):
|
| 146 |
+
The maximum amount of time you allow the computation to run for in seconds. generation will still finish
|
| 147 |
+
the current pass after allocated time has been passed.
|
| 148 |
+
stop_strings (`str or List[str]`, *optional*):
|
| 149 |
+
A string or a list of strings that should terminate generation if the model outputs them.
|
| 150 |
+
|
| 151 |
+
> Parameters that control the generation strategy used
|
| 152 |
+
|
| 153 |
+
do_sample (`bool`, *optional*, defaults to `False`):
|
| 154 |
+
Whether or not to use sampling ; use greedy decoding otherwise.
|
| 155 |
+
num_beams (`int`, *optional*, defaults to 1):
|
| 156 |
+
Number of beams for beam search. 1 means no beam search.
|
| 157 |
+
num_beam_groups (`int`, *optional*, defaults to 1):
|
| 158 |
+
Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
|
| 159 |
+
[this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
|
| 160 |
+
penalty_alpha (`float`, *optional*):
|
| 161 |
+
The values balance the model confidence and the degeneration penalty in contrastive search decoding.
|
| 162 |
+
dola_layers (`str` or `List[int]`, *optional*):
|
| 163 |
+
The layers to use for DoLa decoding. If `None`, DoLa decoding is not used. If a string, it must
|
| 164 |
+
be one of "low" or "high", which means using the lower part or higher part of the model layers, respectively.
|
| 165 |
+
"low" means the first half of the layers up to the first 20 layers, and "high" means the last half of the
|
| 166 |
+
layers up to the last 20 layers.
|
| 167 |
+
If a list of integers, it must contain the indices of the layers to use for candidate premature layers in DoLa.
|
| 168 |
+
The 0-th layer is the word embedding layer of the model. Set to `'low'` to improve long-answer reasoning tasks,
|
| 169 |
+
`'high'` to improve short-answer tasks. Check the [documentation](https://github.com/huggingface/transformers/blob/main/docs/source/en/generation_strategies.md)
|
| 170 |
+
or [the paper](https://arxiv.org/abs/2309.03883) for more details.
|
| 171 |
+
|
| 172 |
+
> Parameters that control the cache
|
| 173 |
+
|
| 174 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 175 |
+
Whether or not the model should use the past last key/values attentions (if applicable to the model) to
|
| 176 |
+
speed up decoding.
|
| 177 |
+
cache_implementation (`str`, *optional*, default to `None`):
|
| 178 |
+
Name of the cache class that will be instantiated in `generate`, for faster decoding. Possible values are:
|
| 179 |
+
|
| 180 |
+
- `"dynamic"`: [`DynamicCache`]
|
| 181 |
+
- `"static"`: [`StaticCache`]
|
| 182 |
+
- `"offloaded_static"`: [`OffloadedStaticCache`]
|
| 183 |
+
- `"sliding_window"`: [`SlidingWindowCache`]
|
| 184 |
+
- `"hybrid"`: [`HybridCache`]
|
| 185 |
+
- `"mamba"`: [`MambaCache`]
|
| 186 |
+
- `"quantized"`: [`QuantizedCache`]
|
| 187 |
+
|
| 188 |
+
If none is specified, we will use the default cache for the model (which is often [`DynamicCache`]). See
|
| 189 |
+
our [cache documentation](https://huggingface.co/docs/transformers/en/kv_cache) for further information.
|
| 190 |
+
cache_config (`CacheConfig` or `dict`, *optional*, default to `None`):
|
| 191 |
+
Arguments used in the key-value cache class can be passed in `cache_config`. Can be passed as a `Dict` and
|
| 192 |
+
it will be converted to its repsective `CacheConfig` internally.
|
| 193 |
+
Otherwise can be passed as a `CacheConfig` class matching the indicated `cache_implementation`.
|
| 194 |
+
return_legacy_cache (`bool`, *optional*, default to `True`):
|
| 195 |
+
Whether to return the legacy or new format of the cache when `DynamicCache` is used by default.
|
| 196 |
+
|
| 197 |
+
> Parameters for manipulation of the model output logits
|
| 198 |
+
|
| 199 |
+
temperature (`float`, *optional*, defaults to 1.0):
|
| 200 |
+
The value used to module the next token probabilities. This value is set in a model's `generation_config.json` file. If it isn't set, the default value is 1.0
|
| 201 |
+
top_k (`int`, *optional*, defaults to 50):
|
| 202 |
+
The number of highest probability vocabulary tokens to keep for top-k-filtering. This value is set in a model's `generation_config.json` file. If it isn't set, the default value is 50.
|
| 203 |
+
top_p (`float`, *optional*, defaults to 1.0):
|
| 204 |
+
If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to
|
| 205 |
+
`top_p` or higher are kept for generation. This value is set in a model's `generation_config.json` file. If it isn't set, the default value is 1.0
|
| 206 |
+
min_p (`float`, *optional*):
|
| 207 |
+
Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
|
| 208 |
+
value between 0 and 1. Typical values are in the 0.01-0.2 range, comparably selective as setting `top_p` in
|
| 209 |
+
the 0.99-0.8 range (use the opposite of normal `top_p` values).
|
| 210 |
+
typical_p (`float`, *optional*, defaults to 1.0):
|
| 211 |
+
Local typicality measures how similar the conditional probability of predicting a target token next is to
|
| 212 |
+
the expected conditional probability of predicting a random token next, given the partial text already
|
| 213 |
+
generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that
|
| 214 |
+
add up to `typical_p` or higher are kept for generation. See [this
|
| 215 |
+
paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.
|
| 216 |
+
epsilon_cutoff (`float`, *optional*, defaults to 0.0):
|
| 217 |
+
If set to float strictly between 0 and 1, only tokens with a conditional probability greater than
|
| 218 |
+
`epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the
|
| 219 |
+
size of the model. See [Truncation Sampling as Language Model
|
| 220 |
+
Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
|
| 221 |
+
eta_cutoff (`float`, *optional*, defaults to 0.0):
|
| 222 |
+
Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between
|
| 223 |
+
0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) *
|
| 224 |
+
exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token
|
| 225 |
+
probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3,
|
| 226 |
+
depending on the size of the model. See [Truncation Sampling as Language Model
|
| 227 |
+
Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
|
| 228 |
+
diversity_penalty (`float`, *optional*, defaults to 0.0):
|
| 229 |
+
This value is subtracted from a beam's score if it generates a token same as any beam from other group at a
|
| 230 |
+
particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
|
| 231 |
+
repetition_penalty (`float`, *optional*, defaults to 1.0):
|
| 232 |
+
The parameter for repetition penalty. 1.0 means no penalty. See [this
|
| 233 |
+
paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
|
| 234 |
+
encoder_repetition_penalty (`float`, *optional*, defaults to 1.0):
|
| 235 |
+
The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the
|
| 236 |
+
original input. 1.0 means no penalty.
|
| 237 |
+
length_penalty (`float`, *optional*, defaults to 1.0):
|
| 238 |
+
Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
|
| 239 |
+
the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log
|
| 240 |
+
likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while
|
| 241 |
+
`length_penalty` < 0.0 encourages shorter sequences.
|
| 242 |
+
no_repeat_ngram_size (`int`, *optional*, defaults to 0):
|
| 243 |
+
If set to int > 0, all ngrams of that size can only occur once.
|
| 244 |
+
bad_words_ids (`List[List[int]]`, *optional*):
|
| 245 |
+
List of list of token ids that are not allowed to be generated. Check
|
| 246 |
+
[`~generation.NoBadWordsLogitsProcessor`] for further documentation and examples.
|
| 247 |
+
force_words_ids (`List[List[int]]` or `List[List[List[int]]]`, *optional*):
|
| 248 |
+
List of token ids that must be generated. If given a `List[List[int]]`, this is treated as a simple list of
|
| 249 |
+
words that must be included, the opposite to `bad_words_ids`. If given `List[List[List[int]]]`, this
|
| 250 |
+
triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one
|
| 251 |
+
can allow different forms of each word.
|
| 252 |
+
renormalize_logits (`bool`, *optional*, defaults to `False`):
|
| 253 |
+
Whether to renormalize the logits after applying all the logits processors (including the custom
|
| 254 |
+
ones). It's highly recommended to set this flag to `True` as the search algorithms suppose the score logits
|
| 255 |
+
are normalized but some logit processors break the normalization.
|
| 256 |
+
constraints (`List[Constraint]`, *optional*):
|
| 257 |
+
Custom constraints that can be added to the generation to ensure that the output will contain the use of
|
| 258 |
+
certain tokens as defined by `Constraint` objects, in the most sensible way possible.
|
| 259 |
+
forced_bos_token_id (`int`, *optional*, defaults to `model.config.forced_bos_token_id`):
|
| 260 |
+
The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for
|
| 261 |
+
multilingual models like [mBART](../model_doc/mbart) where the first generated token needs to be the target
|
| 262 |
+
language token.
|
| 263 |
+
forced_eos_token_id (`int` or List[int]`, *optional*, defaults to `model.config.forced_eos_token_id`):
|
| 264 |
+
The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a
|
| 265 |
+
list to set multiple *end-of-sequence* tokens.
|
| 266 |
+
remove_invalid_values (`bool`, *optional*, defaults to `model.config.remove_invalid_values`):
|
| 267 |
+
Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash.
|
| 268 |
+
Note that using `remove_invalid_values` can slow down generation.
|
| 269 |
+
exponential_decay_length_penalty (`tuple(int, float)`, *optional*):
|
| 270 |
+
This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been
|
| 271 |
+
generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where
|
| 272 |
+
penalty starts and `decay_factor` represents the factor of exponential decay
|
| 273 |
+
suppress_tokens (`List[int]`, *optional*):
|
| 274 |
+
A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their
|
| 275 |
+
log probs to `-inf` so that they are not sampled.
|
| 276 |
+
begin_suppress_tokens (`List[int]`, *optional*):
|
| 277 |
+
A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit
|
| 278 |
+
processor will set their log probs to `-inf` so that they are not sampled.
|
| 279 |
+
forced_decoder_ids (`List[List[int]]`, *optional*):
|
| 280 |
+
A list of pairs of integers which indicates a mapping from generation indices to token indices that will be
|
| 281 |
+
forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token
|
| 282 |
+
of index 123.
|
| 283 |
+
sequence_bias (`Dict[Tuple[int], float]`, *optional*)):
|
| 284 |
+
Dictionary that maps a sequence of tokens to its bias term. Positive biases increase the odds of the
|
| 285 |
+
sequence being selected, while negative biases do the opposite. Check
|
| 286 |
+
[`~generation.SequenceBiasLogitsProcessor`] for further documentation and examples.
|
| 287 |
+
token_healing (`bool`, *optional*, defaults to `False`):
|
| 288 |
+
Heal tail tokens of prompts by replacing them with their appropriate extensions.
|
| 289 |
+
This enhances the quality of completions for prompts affected by greedy tokenization bias.
|
| 290 |
+
guidance_scale (`float`, *optional*):
|
| 291 |
+
The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.
|
| 292 |
+
Higher guidance scale encourages the model to generate samples that are more closely linked to the input
|
| 293 |
+
prompt, usually at the expense of poorer quality.
|
| 294 |
+
low_memory (`bool`, *optional*):
|
| 295 |
+
Switch to sequential beam search and sequential topk for contrastive search to reduce peak memory.
|
| 296 |
+
Used with beam search and contrastive search.
|
| 297 |
+
watermarking_config (`BaseWatermarkingConfig` or `dict`, *optional*):
|
| 298 |
+
Arguments used to watermark the model outputs by adding a small bias to randomly selected set of "green"
|
| 299 |
+
tokens. See the docs of [`SynthIDTextWatermarkingConfig`] and [`WatermarkingConfig`] for more
|
| 300 |
+
details. If passed as `Dict`, it will be converted to a `WatermarkingConfig` internally.
|
| 301 |
+
|
| 302 |
+
> Parameters that define the output variables of generate
|
| 303 |
+
|
| 304 |
+
num_return_sequences (`int`, *optional*, defaults to 1):
|
| 305 |
+
The number of independently computed returned sequences for each element in the batch.
|
| 306 |
+
output_attentions (`bool`, *optional*, defaults to `False`):
|
| 307 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 308 |
+
tensors for more details.
|
| 309 |
+
output_hidden_states (`bool`, *optional*, defaults to `False`):
|
| 310 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 311 |
+
more details.
|
| 312 |
+
output_scores (`bool`, *optional*, defaults to `False`):
|
| 313 |
+
Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
|
| 314 |
+
output_logits (`bool`, *optional*):
|
| 315 |
+
Whether or not to return the unprocessed prediction logit scores. See `logits` under returned tensors for
|
| 316 |
+
more details.
|
| 317 |
+
return_dict_in_generate (`bool`, *optional*, defaults to `False`):
|
| 318 |
+
Whether or not to return a [`~utils.ModelOutput`], as opposed to returning exclusively the generated
|
| 319 |
+
sequence. This flag must be set to `True` to return the generation cache (when `use_cache` is `True`)
|
| 320 |
+
or optional outputs (see flags starting with `output_`)
|
| 321 |
+
|
| 322 |
+
> Special tokens that can be used at generation time
|
| 323 |
+
|
| 324 |
+
pad_token_id (`int`, *optional*):
|
| 325 |
+
The id of the *padding* token.
|
| 326 |
+
bos_token_id (`int`, *optional*):
|
| 327 |
+
The id of the *beginning-of-sequence* token.
|
| 328 |
+
eos_token_id (`Union[int, List[int]]`, *optional*):
|
| 329 |
+
The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
|
| 330 |
+
|
| 331 |
+
> Generation parameters exclusive to encoder-decoder models
|
| 332 |
+
|
| 333 |
+
encoder_no_repeat_ngram_size (`int`, *optional*, defaults to 0):
|
| 334 |
+
If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the
|
| 335 |
+
`decoder_input_ids`.
|
| 336 |
+
decoder_start_token_id (`int` or `List[int]`, *optional*):
|
| 337 |
+
If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token or a list of length
|
| 338 |
+
`batch_size`. Indicating a list enables different start ids for each element in the batch
|
| 339 |
+
(e.g. multilingual models with different target languages in one batch)
|
| 340 |
+
|
| 341 |
+
> Generation parameters exclusive to assistant generation
|
| 342 |
+
is_assistant (`bool`, *optional*, defaults to `False`):
|
| 343 |
+
Whether the model is an assistant (draft) model.
|
| 344 |
+
num_assistant_tokens (`int`, *optional*, defaults to 20):
|
| 345 |
+
Defines the number of _speculative tokens_ that shall be generated by the assistant model before being
|
| 346 |
+
checked by the target model at each iteration. Higher values for `num_assistant_tokens` make the generation
|
| 347 |
+
more _speculative_ : If the assistant model is performant larger speed-ups can be reached, if the assistant
|
| 348 |
+
model requires lots of corrections, lower speed-ups are reached.
|
| 349 |
+
num_assistant_tokens_schedule (`str`, *optional*, defaults to `"constant"`):
|
| 350 |
+
Defines the schedule at which max assistant tokens shall be changed during inference.
|
| 351 |
+
- `"heuristic"`: When all speculative tokens are correct, increase `num_assistant_tokens` by 2 else
|
| 352 |
+
reduce by 1. `num_assistant_tokens` value is persistent over multiple generation calls with the same assistant model.
|
| 353 |
+
- `"heuristic_transient"`: Same as `"heuristic"` but `num_assistant_tokens` is reset to its initial value after each generation call.
|
| 354 |
+
- `"constant"`: `num_assistant_tokens` stays unchanged during generation
|
| 355 |
+
assistant_confidence_threshold (`float`, *optional*, defaults to 0.4):
|
| 356 |
+
The confidence threshold for the assistant model. If the assistant model's confidence in its prediction for the current token is lower
|
| 357 |
+
than this threshold, the assistant model stops the current token generation iteration, even if the number of _speculative tokens_
|
| 358 |
+
(defined by `num_assistant_tokens`) is not yet reached. The assistant's confidence threshold is adjusted throughout the speculative iterations to reduce the number of unnecessary draft and target forward passes, biased towards avoiding false negatives.
|
| 359 |
+
`assistant_confidence_threshold` value is persistent over multiple generation calls with the same assistant model.
|
| 360 |
+
It is an unsupervised version of the dynamic speculation lookahead
|
| 361 |
+
from Dynamic Speculation Lookahead Accelerates Speculative Decoding of Large Language Models <https://arxiv.org/abs/2405.04304>.
|
| 362 |
+
prompt_lookup_num_tokens (`int`, *optional*):
|
| 363 |
+
The number of tokens to be output as candidate tokens.
|
| 364 |
+
max_matching_ngram_size (`int`, *optional*):
|
| 365 |
+
The maximum ngram size to be considered for matching in the prompt. Default to 2 if not provided.
|
| 366 |
+
assistant_early_exit(`int`, *optional*):
|
| 367 |
+
If set to a positive integer, early exit of the model will be used as an assistant. Can only be used with
|
| 368 |
+
models that support early exit (i.e. models where logits from intermediate layers can be interpreted by the LM head).
|
| 369 |
+
assistant_lookbehind(`int`, *optional*, defaults to 10):
|
| 370 |
+
If set to a positive integer, the re-encodeing process will additionally consider the last `assistant_lookbehind` assistant tokens
|
| 371 |
+
to correctly align tokens. Can only be used with different tokenizers in speculative decoding.
|
| 372 |
+
See this [blog](https://huggingface.co/blog/universal_assisted_generation) for more details.
|
| 373 |
+
target_lookbehind(`int`, *optional*, defaults to 10):
|
| 374 |
+
If set to a positive integer, the re-encodeing process will additionally consider the last `target_lookbehind` target tokens
|
| 375 |
+
to correctly align tokens. Can only be used with different tokenizers in speculative decoding.
|
| 376 |
+
See this [blog](https://huggingface.co/blog/universal_assisted_generation) for more details.
|
| 377 |
+
|
| 378 |
+
> Parameters related to performances and compilation
|
| 379 |
+
|
| 380 |
+
compile_config (CompileConfig, *optional*):
|
| 381 |
+
If using a static cache, this controls how `generate` will `compile` the forward pass for performance
|
| 382 |
+
gains.
|
| 383 |
+
|
| 384 |
+
disable_compile (`bool`, *optional*): Whether to disable the automatic compilation of the forward pass. Automatic compilation happens when specific criteria are met, including using a compileable cache. Please open an issue if you find the need to use this flag.
|
| 385 |
+
|
| 386 |
+
> Wild card
|
| 387 |
+
|
| 388 |
+
generation_kwargs:
|
| 389 |
+
Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not
|
| 390 |
+
present in `generate`'s signature will be used in the model forward pass.
|
| 391 |
+
"""
|
| 392 |
+
|
| 393 |
+
extra_output_flags = ("output_attentions", "output_hidden_states", "output_scores", "output_logits")
|
| 394 |
+
|
| 395 |
+
def __init__(self, **kwargs):
|
| 396 |
+
# Parameters that control the length of the output
|
| 397 |
+
self.max_length = kwargs.pop("max_length", 20)
|
| 398 |
+
self.max_new_tokens = kwargs.pop("max_new_tokens", None)
|
| 399 |
+
self.min_length = kwargs.pop("min_length", 0)
|
| 400 |
+
self.min_new_tokens = kwargs.pop("min_new_tokens", None)
|
| 401 |
+
self.early_stopping = kwargs.pop("early_stopping", False)
|
| 402 |
+
self.max_time = kwargs.pop("max_time", None)
|
| 403 |
+
self.stop_strings = kwargs.pop("stop_strings", None)
|
| 404 |
+
|
| 405 |
+
# Parameters that control the generation strategy used
|
| 406 |
+
self.do_sample = kwargs.pop("do_sample", False)
|
| 407 |
+
self.num_beams = kwargs.pop("num_beams", 1)
|
| 408 |
+
self.num_beam_groups = kwargs.pop("num_beam_groups", 1)
|
| 409 |
+
self.penalty_alpha = kwargs.pop("penalty_alpha", None)
|
| 410 |
+
self.dola_layers = kwargs.pop("dola_layers", None)
|
| 411 |
+
|
| 412 |
+
# Parameters that control the cache
|
| 413 |
+
self.use_cache = kwargs.pop("use_cache", True)
|
| 414 |
+
self.cache_implementation = kwargs.pop("cache_implementation", None)
|
| 415 |
+
self.cache_config = kwargs.pop("cache_config", None)
|
| 416 |
+
if self.cache_implementation is not None and self.cache_implementation in CACHE_CONFIG_MAPPING:
|
| 417 |
+
cache_config_class = CACHE_CONFIG_MAPPING[self.cache_implementation]
|
| 418 |
+
if isinstance(self.cache_config, dict):
|
| 419 |
+
self.cache_config = cache_config_class.from_dict(self.cache_config)
|
| 420 |
+
self.return_legacy_cache = kwargs.pop("return_legacy_cache", None)
|
| 421 |
+
self.prefill_chunk_size = kwargs.pop("prefill_chunk_size", None)
|
| 422 |
+
|
| 423 |
+
# Parameters for manipulation of the model output logits
|
| 424 |
+
self.temperature = kwargs.pop("temperature", 1.0)
|
| 425 |
+
self.top_k = kwargs.pop("top_k", 50)
|
| 426 |
+
self.top_p = kwargs.pop("top_p", 1.0)
|
| 427 |
+
self.min_p = kwargs.pop("min_p", None)
|
| 428 |
+
self.typical_p = kwargs.pop("typical_p", 1.0)
|
| 429 |
+
self.epsilon_cutoff = kwargs.pop("epsilon_cutoff", 0.0)
|
| 430 |
+
self.eta_cutoff = kwargs.pop("eta_cutoff", 0.0)
|
| 431 |
+
self.diversity_penalty = kwargs.pop("diversity_penalty", 0.0)
|
| 432 |
+
self.repetition_penalty = kwargs.pop("repetition_penalty", 1.0)
|
| 433 |
+
self.encoder_repetition_penalty = kwargs.pop("encoder_repetition_penalty", 1.0)
|
| 434 |
+
self.length_penalty = kwargs.pop("length_penalty", 1.0)
|
| 435 |
+
self.no_repeat_ngram_size = kwargs.pop("no_repeat_ngram_size", 0)
|
| 436 |
+
self.bad_words_ids = kwargs.pop("bad_words_ids", None)
|
| 437 |
+
self.force_words_ids = kwargs.pop("force_words_ids", None)
|
| 438 |
+
self.renormalize_logits = kwargs.pop("renormalize_logits", False)
|
| 439 |
+
self.constraints = kwargs.pop("constraints", None)
|
| 440 |
+
self.forced_bos_token_id = kwargs.pop("forced_bos_token_id", None)
|
| 441 |
+
self.forced_eos_token_id = kwargs.pop("forced_eos_token_id", None)
|
| 442 |
+
self.remove_invalid_values = kwargs.pop("remove_invalid_values", False)
|
| 443 |
+
self.exponential_decay_length_penalty = kwargs.pop("exponential_decay_length_penalty", None)
|
| 444 |
+
self.suppress_tokens = kwargs.pop("suppress_tokens", None)
|
| 445 |
+
self.begin_suppress_tokens = kwargs.pop("begin_suppress_tokens", None)
|
| 446 |
+
self.forced_decoder_ids = kwargs.pop("forced_decoder_ids", None)
|
| 447 |
+
self.sequence_bias = kwargs.pop("sequence_bias", None)
|
| 448 |
+
self.token_healing = kwargs.pop("token_healing", False)
|
| 449 |
+
self.guidance_scale = kwargs.pop("guidance_scale", None)
|
| 450 |
+
self.low_memory = kwargs.pop("low_memory", None)
|
| 451 |
+
watermarking_config = kwargs.pop("watermarking_config", None)
|
| 452 |
+
if watermarking_config is None:
|
| 453 |
+
self.watermarking_config = None
|
| 454 |
+
elif isinstance(watermarking_config, BaseWatermarkingConfig):
|
| 455 |
+
self.watermarking_config = watermarking_config
|
| 456 |
+
else:
|
| 457 |
+
self.watermarking_config = WatermarkingConfig.from_dict(watermarking_config)
|
| 458 |
+
|
| 459 |
+
# Parameters that define the output variables of `generate`
|
| 460 |
+
self.num_return_sequences = kwargs.pop("num_return_sequences", 1)
|
| 461 |
+
self.output_attentions = kwargs.pop("output_attentions", False)
|
| 462 |
+
self.output_hidden_states = kwargs.pop("output_hidden_states", False)
|
| 463 |
+
self.output_scores = kwargs.pop("output_scores", False)
|
| 464 |
+
self.output_logits = kwargs.pop("output_logits", None)
|
| 465 |
+
self.return_dict_in_generate = kwargs.pop("return_dict_in_generate", False)
|
| 466 |
+
|
| 467 |
+
# Special tokens that can be used at generation time
|
| 468 |
+
self.pad_token_id = kwargs.pop("pad_token_id", None)
|
| 469 |
+
self.bos_token_id = kwargs.pop("bos_token_id", None)
|
| 470 |
+
self.eos_token_id = kwargs.pop("eos_token_id", None)
|
| 471 |
+
|
| 472 |
+
# Generation parameters exclusive to encoder-decoder models
|
| 473 |
+
self.encoder_no_repeat_ngram_size = kwargs.pop("encoder_no_repeat_ngram_size", 0)
|
| 474 |
+
self.decoder_start_token_id = kwargs.pop("decoder_start_token_id", None)
|
| 475 |
+
|
| 476 |
+
# Assistant generation
|
| 477 |
+
self.is_assistant = False
|
| 478 |
+
self.num_assistant_tokens = kwargs.pop("num_assistant_tokens", 20)
|
| 479 |
+
self.num_assistant_tokens_schedule = kwargs.pop("num_assistant_tokens_schedule", "constant")
|
| 480 |
+
self.assistant_confidence_threshold = kwargs.pop("assistant_confidence_threshold", 0.4)
|
| 481 |
+
self.prompt_lookup_num_tokens = kwargs.pop("prompt_lookup_num_tokens", None)
|
| 482 |
+
self.max_matching_ngram_size = kwargs.pop("max_matching_ngram_size", None)
|
| 483 |
+
self.assistant_early_exit = kwargs.pop("assistant_early_exit", None)
|
| 484 |
+
## assistant generation for different tokenizers, the windows size for assistant/target model
|
| 485 |
+
self.assistant_lookbehind = kwargs.pop("assistant_lookbehind", 10)
|
| 486 |
+
self.target_lookbehind = kwargs.pop("target_lookbehind", 10)
|
| 487 |
+
|
| 488 |
+
# Performance
|
| 489 |
+
self.compile_config = kwargs.pop("compile_config", CompileConfig())
|
| 490 |
+
self.disable_compile = kwargs.pop("disable_compile", False)
|
| 491 |
+
# Wild card
|
| 492 |
+
self.generation_kwargs = kwargs.pop("generation_kwargs", {})
|
| 493 |
+
|
| 494 |
+
# The remaining attributes do not parametrize `.generate()`, but are informative and/or used by the hub
|
| 495 |
+
# interface.
|
| 496 |
+
self._from_model_config = kwargs.pop("_from_model_config", False)
|
| 497 |
+
self._commit_hash = kwargs.pop("_commit_hash", None)
|
| 498 |
+
self.transformers_version = kwargs.pop("transformers_version", __version__)
|
| 499 |
+
|
| 500 |
+
# Additional attributes without default values
|
| 501 |
+
if not self._from_model_config:
|
| 502 |
+
# we don't want to copy values from the model config if we're initializing a `GenerationConfig` from a
|
| 503 |
+
# model's default configuration file
|
| 504 |
+
for key, value in kwargs.items():
|
| 505 |
+
try:
|
| 506 |
+
setattr(self, key, value)
|
| 507 |
+
except AttributeError as err:
|
| 508 |
+
logger.error(f"Can't set {key} with value {value} for {self}")
|
| 509 |
+
raise err
|
| 510 |
+
|
| 511 |
+
# Validate the values of the attributes
|
| 512 |
+
self.validate(is_init=True)
|
| 513 |
+
|
| 514 |
+
def __hash__(self):
|
| 515 |
+
return hash(self.to_json_string(ignore_metadata=True))
|
| 516 |
+
|
| 517 |
+
def __eq__(self, other):
|
| 518 |
+
if not isinstance(other, GenerationConfig):
|
| 519 |
+
return False
|
| 520 |
+
|
| 521 |
+
self_without_metadata = self.to_json_string(use_diff=False, ignore_metadata=True)
|
| 522 |
+
other_without_metadata = other.to_json_string(use_diff=False, ignore_metadata=True)
|
| 523 |
+
return self_without_metadata == other_without_metadata
|
| 524 |
+
|
| 525 |
+
def __repr__(self):
|
| 526 |
+
return f"{self.__class__.__name__} {self.to_json_string(ignore_metadata=True)}"
|
| 527 |
+
|
| 528 |
+
def get_generation_mode(self, assistant_model: Optional["PreTrainedModel"] = None) -> GenerationMode:
|
| 529 |
+
"""
|
| 530 |
+
Returns the generation mode triggered by the [`GenerationConfig`] instance.
|
| 531 |
+
|
| 532 |
+
Arg:
|
| 533 |
+
assistant_model (`PreTrainedModel`, *optional*):
|
| 534 |
+
The assistant model to be used for assisted generation. If set, the generation mode will be
|
| 535 |
+
assisted generation.
|
| 536 |
+
|
| 537 |
+
Returns:
|
| 538 |
+
`GenerationMode`: The generation mode triggered by the instance.
|
| 539 |
+
"""
|
| 540 |
+
# TODO joao: find out a way of not depending on external fields (e.g. `assistant_model`), then make this a
|
| 541 |
+
# property and part of the `__repr__`
|
| 542 |
+
if self.constraints is not None or self.force_words_ids is not None:
|
| 543 |
+
generation_mode = GenerationMode.CONSTRAINED_BEAM_SEARCH
|
| 544 |
+
elif self.num_beams == 1:
|
| 545 |
+
if self.do_sample is False:
|
| 546 |
+
if (
|
| 547 |
+
self.top_k is not None
|
| 548 |
+
and self.top_k > 1
|
| 549 |
+
and self.penalty_alpha is not None
|
| 550 |
+
and self.penalty_alpha > 0
|
| 551 |
+
):
|
| 552 |
+
generation_mode = GenerationMode.CONTRASTIVE_SEARCH
|
| 553 |
+
else:
|
| 554 |
+
generation_mode = GenerationMode.GREEDY_SEARCH
|
| 555 |
+
else:
|
| 556 |
+
generation_mode = GenerationMode.SAMPLE
|
| 557 |
+
else:
|
| 558 |
+
if self.num_beam_groups > 1:
|
| 559 |
+
generation_mode = GenerationMode.GROUP_BEAM_SEARCH
|
| 560 |
+
elif self.do_sample is True:
|
| 561 |
+
generation_mode = GenerationMode.BEAM_SAMPLE
|
| 562 |
+
else:
|
| 563 |
+
generation_mode = GenerationMode.BEAM_SEARCH
|
| 564 |
+
|
| 565 |
+
# Assisted generation may extend some generation modes
|
| 566 |
+
if (
|
| 567 |
+
assistant_model is not None
|
| 568 |
+
or self.prompt_lookup_num_tokens is not None
|
| 569 |
+
or self.assistant_early_exit is not None
|
| 570 |
+
):
|
| 571 |
+
if generation_mode in ("greedy_search", "sample"):
|
| 572 |
+
generation_mode = GenerationMode.ASSISTED_GENERATION
|
| 573 |
+
else:
|
| 574 |
+
raise ValueError(
|
| 575 |
+
"You've set `assistant_model`, which triggers assisted generate. Currently, assisted generate "
|
| 576 |
+
"is only supported with Greedy Search and Sample."
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
# DoLa generation may extend some generation modes
|
| 580 |
+
if self.dola_layers is not None:
|
| 581 |
+
if generation_mode in ("greedy_search", "sample"):
|
| 582 |
+
generation_mode = GenerationMode.DOLA_GENERATION
|
| 583 |
+
else:
|
| 584 |
+
raise ValueError(
|
| 585 |
+
"You've set `dola_layers`, which triggers DoLa generate. Currently, DoLa generate "
|
| 586 |
+
"is only supported with Greedy Search and Sample."
|
| 587 |
+
)
|
| 588 |
+
return generation_mode
|
| 589 |
+
|
| 590 |
+
def validate(self, is_init=False):
|
| 591 |
+
"""
|
| 592 |
+
Validates the values of the attributes of the [`GenerationConfig`] instance. Raises exceptions in the presence
|
| 593 |
+
of parameterization that can be detected as incorrect from the configuration instance alone.
|
| 594 |
+
|
| 595 |
+
Note that some parameters not validated here are best validated at generate runtime, as they may depend on
|
| 596 |
+
other inputs and/or the model, such as parameters related to the generation length.
|
| 597 |
+
|
| 598 |
+
Arg:
|
| 599 |
+
is_init (`bool`, *optional*, defaults to `False`):
|
| 600 |
+
Whether the validation is performed during the initialization of the instance.
|
| 601 |
+
"""
|
| 602 |
+
|
| 603 |
+
# Validation of individual attributes
|
| 604 |
+
if self.early_stopping not in {True, False, "never"}:
|
| 605 |
+
raise ValueError(f"`early_stopping` must be a boolean or 'never', but is {self.early_stopping}.")
|
| 606 |
+
if self.max_new_tokens is not None and self.max_new_tokens <= 0:
|
| 607 |
+
raise ValueError(f"`max_new_tokens` must be greater than 0, but is {self.max_new_tokens}.")
|
| 608 |
+
if self.pad_token_id is not None and self.pad_token_id < 0:
|
| 609 |
+
warnings.warn(
|
| 610 |
+
f"`pad_token_id` should be positive but got {self.pad_token_id}. This will cause errors when batch "
|
| 611 |
+
"generating, if there is padding. Please set `pad_token_id` explicitly as "
|
| 612 |
+
"`model.generation_config.pad_token_id=PAD_TOKEN_ID` to avoid errors in generation"
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
# Validation of attribute relations:
|
| 616 |
+
fix_location = ""
|
| 617 |
+
if is_init:
|
| 618 |
+
fix_location = (
|
| 619 |
+
" This was detected when initializing the generation config instance, which means the corresponding "
|
| 620 |
+
"file may hold incorrect parameterization and should be fixed."
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
# 1. detect sampling-only parameterization when not in sampling mode
|
| 624 |
+
if self.do_sample is False:
|
| 625 |
+
greedy_wrong_parameter_msg = (
|
| 626 |
+
"`do_sample` is set to `False`. However, `{flag_name}` is set to `{flag_value}` -- this flag is only "
|
| 627 |
+
"used in sample-based generation modes. You should set `do_sample=True` or unset `{flag_name}`."
|
| 628 |
+
+ fix_location
|
| 629 |
+
)
|
| 630 |
+
if self.temperature is not None and self.temperature != 1.0:
|
| 631 |
+
warnings.warn(
|
| 632 |
+
greedy_wrong_parameter_msg.format(flag_name="temperature", flag_value=self.temperature),
|
| 633 |
+
UserWarning,
|
| 634 |
+
)
|
| 635 |
+
if self.top_p is not None and self.top_p != 1.0:
|
| 636 |
+
warnings.warn(
|
| 637 |
+
greedy_wrong_parameter_msg.format(flag_name="top_p", flag_value=self.top_p),
|
| 638 |
+
UserWarning,
|
| 639 |
+
)
|
| 640 |
+
if self.min_p is not None:
|
| 641 |
+
warnings.warn(
|
| 642 |
+
greedy_wrong_parameter_msg.format(flag_name="min_p", flag_value=self.min_p),
|
| 643 |
+
UserWarning,
|
| 644 |
+
)
|
| 645 |
+
if self.typical_p is not None and self.typical_p != 1.0:
|
| 646 |
+
warnings.warn(
|
| 647 |
+
greedy_wrong_parameter_msg.format(flag_name="typical_p", flag_value=self.typical_p),
|
| 648 |
+
UserWarning,
|
| 649 |
+
)
|
| 650 |
+
if (
|
| 651 |
+
self.top_k is not None and self.top_k != 50 and self.penalty_alpha is None
|
| 652 |
+
): # contrastive search uses top_k
|
| 653 |
+
warnings.warn(
|
| 654 |
+
greedy_wrong_parameter_msg.format(flag_name="top_k", flag_value=self.top_k),
|
| 655 |
+
UserWarning,
|
| 656 |
+
)
|
| 657 |
+
if self.epsilon_cutoff is not None and self.epsilon_cutoff != 0.0:
|
| 658 |
+
warnings.warn(
|
| 659 |
+
greedy_wrong_parameter_msg.format(flag_name="epsilon_cutoff", flag_value=self.epsilon_cutoff),
|
| 660 |
+
UserWarning,
|
| 661 |
+
)
|
| 662 |
+
if self.eta_cutoff is not None and self.eta_cutoff != 0.0:
|
| 663 |
+
warnings.warn(
|
| 664 |
+
greedy_wrong_parameter_msg.format(flag_name="eta_cutoff", flag_value=self.eta_cutoff),
|
| 665 |
+
UserWarning,
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
# 2. detect beam-only parameterization when not in beam mode
|
| 669 |
+
if self.num_beams is None:
|
| 670 |
+
warnings.warn("`num_beams` is set to None - defaulting to 1.", UserWarning)
|
| 671 |
+
self.num_beams = 1
|
| 672 |
+
|
| 673 |
+
if self.num_beams == 1:
|
| 674 |
+
single_beam_wrong_parameter_msg = (
|
| 675 |
+
"`num_beams` is set to 1. However, `{flag_name}` is set to `{flag_value}` -- this flag is only used "
|
| 676 |
+
"in beam-based generation modes. You should set `num_beams>1` or unset `{flag_name}`." + fix_location
|
| 677 |
+
)
|
| 678 |
+
if self.early_stopping is not False:
|
| 679 |
+
warnings.warn(
|
| 680 |
+
single_beam_wrong_parameter_msg.format(flag_name="early_stopping", flag_value=self.early_stopping),
|
| 681 |
+
UserWarning,
|
| 682 |
+
)
|
| 683 |
+
if self.num_beam_groups is not None and self.num_beam_groups != 1:
|
| 684 |
+
warnings.warn(
|
| 685 |
+
single_beam_wrong_parameter_msg.format(
|
| 686 |
+
flag_name="num_beam_groups", flag_value=self.num_beam_groups
|
| 687 |
+
),
|
| 688 |
+
UserWarning,
|
| 689 |
+
)
|
| 690 |
+
if self.diversity_penalty is not None and self.diversity_penalty != 0.0:
|
| 691 |
+
warnings.warn(
|
| 692 |
+
single_beam_wrong_parameter_msg.format(
|
| 693 |
+
flag_name="diversity_penalty", flag_value=self.diversity_penalty
|
| 694 |
+
),
|
| 695 |
+
UserWarning,
|
| 696 |
+
)
|
| 697 |
+
if self.length_penalty is not None and self.length_penalty != 1.0:
|
| 698 |
+
warnings.warn(
|
| 699 |
+
single_beam_wrong_parameter_msg.format(flag_name="length_penalty", flag_value=self.length_penalty),
|
| 700 |
+
UserWarning,
|
| 701 |
+
)
|
| 702 |
+
if self.constraints is not None:
|
| 703 |
+
warnings.warn(
|
| 704 |
+
single_beam_wrong_parameter_msg.format(flag_name="constraints", flag_value=self.constraints),
|
| 705 |
+
UserWarning,
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
# 3. detect incorrect paramaterization specific to advanced beam modes
|
| 709 |
+
else:
|
| 710 |
+
# constrained beam search
|
| 711 |
+
if self.constraints is not None or self.force_words_ids is not None:
|
| 712 |
+
constrained_wrong_parameter_msg = (
|
| 713 |
+
"one of `constraints`, `force_words_ids` is not `None`, triggering constrained beam search. However, "
|
| 714 |
+
"`{flag_name}` is set to `{flag_value}`, which is incompatible with this generation mode. Set "
|
| 715 |
+
"`constraints` and `force_words_ids` to `None` or unset `{flag_name}` to continue." + fix_location
|
| 716 |
+
)
|
| 717 |
+
if self.do_sample is True:
|
| 718 |
+
raise ValueError(
|
| 719 |
+
constrained_wrong_parameter_msg.format(flag_name="do_sample", flag_value=self.do_sample)
|
| 720 |
+
)
|
| 721 |
+
if self.num_beam_groups is not None and self.num_beam_groups != 1:
|
| 722 |
+
raise ValueError(
|
| 723 |
+
constrained_wrong_parameter_msg.format(
|
| 724 |
+
flag_name="num_beam_groups", flag_value=self.num_beam_groups
|
| 725 |
+
)
|
| 726 |
+
)
|
| 727 |
+
# group beam search
|
| 728 |
+
if self.diversity_penalty != 0.0 or self.num_beam_groups != 1:
|
| 729 |
+
group_error_prefix = (
|
| 730 |
+
"`diversity_penalty` is not 0.0 or `num_beam_groups` is not 1, triggering group beam search. In "
|
| 731 |
+
"this generation mode, "
|
| 732 |
+
)
|
| 733 |
+
if self.do_sample is True:
|
| 734 |
+
raise ValueError(group_error_prefix + "`do_sample` must be set to `False`")
|
| 735 |
+
if self.num_beams % self.num_beam_groups != 0:
|
| 736 |
+
raise ValueError(group_error_prefix + "`num_beams` should be divisible by `num_beam_groups`")
|
| 737 |
+
if self.diversity_penalty == 0.0:
|
| 738 |
+
raise ValueError(
|
| 739 |
+
group_error_prefix
|
| 740 |
+
+ "`diversity_penalty` should be greater than `0.0`, otherwise your groups will be identical."
|
| 741 |
+
)
|
| 742 |
+
# DoLa generation
|
| 743 |
+
if self.dola_layers is not None and (self.repetition_penalty is None or self.repetition_penalty < 1.2):
|
| 744 |
+
warnings.warn(
|
| 745 |
+
"`dola_layers` is set to trigger DoLa decoding, but `repetition_penalty` is set to a value of "
|
| 746 |
+
f"{self.repetition_penalty}, which could induce unwanted repetition. The recommended value for "
|
| 747 |
+
"DoLa decoding is `repetition_penalty>=1.2`.",
|
| 748 |
+
UserWarning,
|
| 749 |
+
)
|
| 750 |
+
|
| 751 |
+
# 4. check `num_return_sequences`
|
| 752 |
+
if self.num_return_sequences != 1:
|
| 753 |
+
if self.num_beams == 1:
|
| 754 |
+
if self.do_sample is False:
|
| 755 |
+
raise ValueError(
|
| 756 |
+
"Greedy methods without beam search do not support `num_return_sequences` different than 1 "
|
| 757 |
+
f"(got {self.num_return_sequences})."
|
| 758 |
+
)
|
| 759 |
+
elif self.num_return_sequences > self.num_beams:
|
| 760 |
+
raise ValueError(
|
| 761 |
+
f"`num_return_sequences` ({self.num_return_sequences}) has to be smaller or equal to `num_beams` "
|
| 762 |
+
f"({self.num_beams})."
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
# 5. check cache-related arguments
|
| 766 |
+
if self.cache_implementation is not None and self.cache_implementation not in ALL_CACHE_IMPLEMENTATIONS:
|
| 767 |
+
raise ValueError(
|
| 768 |
+
f"Invalid `cache_implementation` ({self.cache_implementation}). Choose one of: "
|
| 769 |
+
f"{ALL_CACHE_IMPLEMENTATIONS}"
|
| 770 |
+
)
|
| 771 |
+
if self.cache_config is not None:
|
| 772 |
+
cache_class = CACHE_CONFIG_MAPPING.get(self.cache_implementation)
|
| 773 |
+
if cache_class is None:
|
| 774 |
+
raise ValueError(
|
| 775 |
+
"You provided a `cache_config` but the cache implementation you are using "
|
| 776 |
+
f"({self.cache_implementation}) does not require any config. Make sure to use the "
|
| 777 |
+
"correct cache implementation matching your cache config."
|
| 778 |
+
)
|
| 779 |
+
if not isinstance(self.cache_config, cache_class):
|
| 780 |
+
self.cache_config = cache_class.from_dict(self.cache_config)
|
| 781 |
+
self.cache_config.validate()
|
| 782 |
+
if self.use_cache is False:
|
| 783 |
+
# In this case, all cache-related arguments should be unset. However, since `use_cache=False` is often used
|
| 784 |
+
# passed to `generate` directly to hot-fix cache issues, let's raise a warning instead of an error
|
| 785 |
+
# (otherwise a user might need to overwrite several parameters).
|
| 786 |
+
no_cache_warning = (
|
| 787 |
+
"You have set `use_cache` to `False`, but {cache_arg} is set to {cache_arg_value}. {cache_arg} will "
|
| 788 |
+
"have no effect."
|
| 789 |
+
)
|
| 790 |
+
for arg_name in ("cache_implementation", "cache_config", "return_legacy_cache"):
|
| 791 |
+
if getattr(self, arg_name) is not None:
|
| 792 |
+
logger.warning_once(
|
| 793 |
+
no_cache_warning.format(cache_arg=arg_name, cache_arg_value=getattr(self, arg_name))
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
# 6. check watermarking arguments
|
| 797 |
+
if self.watermarking_config is not None:
|
| 798 |
+
if not (
|
| 799 |
+
isinstance(self.watermarking_config, WatermarkingConfig)
|
| 800 |
+
or isinstance(self.watermarking_config, SynthIDTextWatermarkingConfig)
|
| 801 |
+
):
|
| 802 |
+
warnings.warn(
|
| 803 |
+
"`watermarking_config` as a dict is deprecated. Please construct `watermarking_config` object with "
|
| 804 |
+
"`WatermarkingConfig` or `SynthIDTextWatermarkingConfig` class.",
|
| 805 |
+
FutureWarning,
|
| 806 |
+
)
|
| 807 |
+
self.watermarking_config = WatermarkingConfig.from_dict(self.watermarking_config)
|
| 808 |
+
self.watermarking_config.validate()
|
| 809 |
+
|
| 810 |
+
# 7. performances arguments
|
| 811 |
+
if not isinstance(self.compile_config, CompileConfig):
|
| 812 |
+
raise ValueError(
|
| 813 |
+
f"You provided `compile_config` as an instance of {type(self.compile_config)}, but it must be an instance of `CompileConfig`."
|
| 814 |
+
)
|
| 815 |
+
|
| 816 |
+
# 8. other incorrect combinations
|
| 817 |
+
if self.return_dict_in_generate is not True:
|
| 818 |
+
for extra_output_flag in self.extra_output_flags:
|
| 819 |
+
if getattr(self, extra_output_flag) is True:
|
| 820 |
+
warnings.warn(
|
| 821 |
+
f"`return_dict_in_generate` is NOT set to `True`, but `{extra_output_flag}` is. When "
|
| 822 |
+
f"`return_dict_in_generate` is not `True`, `{extra_output_flag}` is ignored.",
|
| 823 |
+
UserWarning,
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
# 8. check common issue: passing `generate` arguments inside the generation config
|
| 827 |
+
generate_arguments = (
|
| 828 |
+
"logits_processor",
|
| 829 |
+
"stopping_criteria",
|
| 830 |
+
"prefix_allowed_tokens_fn",
|
| 831 |
+
"synced_gpus",
|
| 832 |
+
"assistant_model",
|
| 833 |
+
"streamer",
|
| 834 |
+
"negative_prompt_ids",
|
| 835 |
+
"negative_prompt_attention_mask",
|
| 836 |
+
)
|
| 837 |
+
for arg in generate_arguments:
|
| 838 |
+
if hasattr(self, arg):
|
| 839 |
+
raise ValueError(
|
| 840 |
+
f"Argument `{arg}` is not a valid argument of `GenerationConfig`. It should be passed to "
|
| 841 |
+
"`generate()` (or a pipeline) directly."
|
| 842 |
+
)
|
| 843 |
+
|
| 844 |
+
def save_pretrained(
|
| 845 |
+
self,
|
| 846 |
+
save_directory: Union[str, os.PathLike],
|
| 847 |
+
config_file_name: Optional[Union[str, os.PathLike]] = None,
|
| 848 |
+
push_to_hub: bool = False,
|
| 849 |
+
**kwargs,
|
| 850 |
+
):
|
| 851 |
+
r"""
|
| 852 |
+
Save a generation configuration object to the directory `save_directory`, so that it can be re-loaded using the
|
| 853 |
+
[`~GenerationConfig.from_pretrained`] class method.
|
| 854 |
+
|
| 855 |
+
Args:
|
| 856 |
+
save_directory (`str` or `os.PathLike`):
|
| 857 |
+
Directory where the configuration JSON file will be saved (will be created if it does not exist).
|
| 858 |
+
config_file_name (`str` or `os.PathLike`, *optional*, defaults to `"generation_config.json"`):
|
| 859 |
+
Name of the generation configuration JSON file to be saved in `save_directory`.
|
| 860 |
+
push_to_hub (`bool`, *optional*, defaults to `False`):
|
| 861 |
+
Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
|
| 862 |
+
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
|
| 863 |
+
namespace).
|
| 864 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 865 |
+
Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
|
| 866 |
+
"""
|
| 867 |
+
|
| 868 |
+
# At save time, validate the instance -- if any warning/exception is thrown, we refuse to save the instance.
|
| 869 |
+
# This strictness is enforced to prevent bad configurations from being saved and re-used.
|
| 870 |
+
try:
|
| 871 |
+
with warnings.catch_warnings(record=True) as caught_warnings:
|
| 872 |
+
self.validate()
|
| 873 |
+
if len(caught_warnings) > 0:
|
| 874 |
+
raise ValueError(str([w.message for w in caught_warnings]))
|
| 875 |
+
except ValueError as exc:
|
| 876 |
+
raise ValueError(
|
| 877 |
+
"The generation config instance is invalid -- `.validate()` throws warnings and/or exceptions. "
|
| 878 |
+
"Fix these issues to save the configuration.\n\nThrown during validation:\n" + str(exc)
|
| 879 |
+
)
|
| 880 |
+
|
| 881 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 882 |
+
|
| 883 |
+
if use_auth_token is not None:
|
| 884 |
+
warnings.warn(
|
| 885 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. "
|
| 886 |
+
"Please use `token` instead.",
|
| 887 |
+
FutureWarning,
|
| 888 |
+
)
|
| 889 |
+
if kwargs.get("token", None) is not None:
|
| 890 |
+
raise ValueError(
|
| 891 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 892 |
+
)
|
| 893 |
+
kwargs["token"] = use_auth_token
|
| 894 |
+
|
| 895 |
+
config_file_name = config_file_name if config_file_name is not None else GENERATION_CONFIG_NAME
|
| 896 |
+
|
| 897 |
+
if os.path.isfile(save_directory):
|
| 898 |
+
raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
|
| 899 |
+
|
| 900 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 901 |
+
|
| 902 |
+
if push_to_hub:
|
| 903 |
+
commit_message = kwargs.pop("commit_message", None)
|
| 904 |
+
repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
|
| 905 |
+
repo_id = self._create_repo(repo_id, **kwargs)
|
| 906 |
+
files_timestamps = self._get_files_timestamps(save_directory)
|
| 907 |
+
|
| 908 |
+
output_config_file = os.path.join(save_directory, config_file_name)
|
| 909 |
+
|
| 910 |
+
self.to_json_file(output_config_file, use_diff=True)
|
| 911 |
+
logger.info(f"Configuration saved in {output_config_file}")
|
| 912 |
+
|
| 913 |
+
if push_to_hub:
|
| 914 |
+
self._upload_modified_files(
|
| 915 |
+
save_directory,
|
| 916 |
+
repo_id,
|
| 917 |
+
files_timestamps,
|
| 918 |
+
commit_message=commit_message,
|
| 919 |
+
token=kwargs.get("token"),
|
| 920 |
+
)
|
| 921 |
+
|
| 922 |
+
@classmethod
|
| 923 |
+
def from_pretrained(
|
| 924 |
+
cls,
|
| 925 |
+
pretrained_model_name: Union[str, os.PathLike],
|
| 926 |
+
config_file_name: Optional[Union[str, os.PathLike]] = None,
|
| 927 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 928 |
+
force_download: bool = False,
|
| 929 |
+
local_files_only: bool = False,
|
| 930 |
+
token: Optional[Union[str, bool]] = None,
|
| 931 |
+
revision: str = "main",
|
| 932 |
+
**kwargs,
|
| 933 |
+
) -> "GenerationConfig":
|
| 934 |
+
r"""
|
| 935 |
+
Instantiate a [`GenerationConfig`] from a generation configuration file.
|
| 936 |
+
|
| 937 |
+
Args:
|
| 938 |
+
pretrained_model_name (`str` or `os.PathLike`):
|
| 939 |
+
This can be either:
|
| 940 |
+
|
| 941 |
+
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
| 942 |
+
huggingface.co.
|
| 943 |
+
- a path to a *directory* containing a configuration file saved using the
|
| 944 |
+
[`~GenerationConfig.save_pretrained`] method, e.g., `./my_model_directory/`.
|
| 945 |
+
config_file_name (`str` or `os.PathLike`, *optional*, defaults to `"generation_config.json"`):
|
| 946 |
+
Name of the generation configuration JSON file to be loaded from `pretrained_model_name`.
|
| 947 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 948 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 949 |
+
standard cache should not be used.
|
| 950 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 951 |
+
Whether or not to force to (re-)download the configuration files and override the cached versions if
|
| 952 |
+
they exist.
|
| 953 |
+
resume_download:
|
| 954 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 955 |
+
Will be removed in v5 of Transformers.
|
| 956 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 957 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 958 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 959 |
+
token (`str` or `bool`, *optional*):
|
| 960 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
|
| 961 |
+
the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 962 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 963 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 964 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 965 |
+
identifier allowed by git.
|
| 966 |
+
|
| 967 |
+
<Tip>
|
| 968 |
+
|
| 969 |
+
To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.
|
| 970 |
+
|
| 971 |
+
</Tip>
|
| 972 |
+
|
| 973 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 974 |
+
If `False`, then this function returns just the final configuration object.
|
| 975 |
+
|
| 976 |
+
If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
|
| 977 |
+
dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
|
| 978 |
+
part of `kwargs` which has not been used to update `config` and is otherwise ignored.
|
| 979 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
| 980 |
+
In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
|
| 981 |
+
specify the folder name here.
|
| 982 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 983 |
+
The values in kwargs of any keys which are configuration attributes will be used to override the loaded
|
| 984 |
+
values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
|
| 985 |
+
by the `return_unused_kwargs` keyword parameter.
|
| 986 |
+
|
| 987 |
+
Returns:
|
| 988 |
+
[`GenerationConfig`]: The configuration object instantiated from this pretrained model.
|
| 989 |
+
|
| 990 |
+
Examples:
|
| 991 |
+
|
| 992 |
+
```python
|
| 993 |
+
>>> from transformers import GenerationConfig
|
| 994 |
+
|
| 995 |
+
>>> # Download configuration from huggingface.co and cache.
|
| 996 |
+
>>> generation_config = GenerationConfig.from_pretrained("openai-community/gpt2")
|
| 997 |
+
|
| 998 |
+
>>> # E.g. config was saved using *save_pretrained('./test/saved_model/')*
|
| 999 |
+
>>> generation_config.save_pretrained("./test/saved_model/")
|
| 1000 |
+
>>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/")
|
| 1001 |
+
|
| 1002 |
+
>>> # You can also specify configuration names to your generation configuration file
|
| 1003 |
+
>>> generation_config.save_pretrained("./test/saved_model/", config_file_name="my_configuration.json")
|
| 1004 |
+
>>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/", "my_configuration.json")
|
| 1005 |
+
|
| 1006 |
+
>>> # If you'd like to try a minor variation to an existing configuration, you can also pass generation
|
| 1007 |
+
>>> # arguments to `.from_pretrained()`. Be mindful that typos and unused arguments will be ignored
|
| 1008 |
+
>>> generation_config, unused_kwargs = GenerationConfig.from_pretrained(
|
| 1009 |
+
... "openai-community/gpt2", top_k=1, foo=False, do_sample=True, return_unused_kwargs=True
|
| 1010 |
+
... )
|
| 1011 |
+
>>> generation_config.top_k
|
| 1012 |
+
1
|
| 1013 |
+
|
| 1014 |
+
>>> unused_kwargs
|
| 1015 |
+
{'foo': False}
|
| 1016 |
+
```"""
|
| 1017 |
+
config_file_name = config_file_name if config_file_name is not None else GENERATION_CONFIG_NAME
|
| 1018 |
+
|
| 1019 |
+
resume_download = kwargs.pop("resume_download", None)
|
| 1020 |
+
proxies = kwargs.pop("proxies", None)
|
| 1021 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 1022 |
+
subfolder = kwargs.pop("subfolder", "")
|
| 1023 |
+
from_pipeline = kwargs.pop("_from_pipeline", None)
|
| 1024 |
+
from_auto_class = kwargs.pop("_from_auto", False)
|
| 1025 |
+
commit_hash = kwargs.pop("_commit_hash", None)
|
| 1026 |
+
|
| 1027 |
+
if use_auth_token is not None:
|
| 1028 |
+
warnings.warn(
|
| 1029 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 1030 |
+
FutureWarning,
|
| 1031 |
+
)
|
| 1032 |
+
if token is not None:
|
| 1033 |
+
raise ValueError(
|
| 1034 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 1035 |
+
)
|
| 1036 |
+
token = use_auth_token
|
| 1037 |
+
|
| 1038 |
+
user_agent = {"file_type": "config", "from_auto_class": from_auto_class}
|
| 1039 |
+
if from_pipeline is not None:
|
| 1040 |
+
user_agent["using_pipeline"] = from_pipeline
|
| 1041 |
+
|
| 1042 |
+
config_path = os.path.join(pretrained_model_name, config_file_name)
|
| 1043 |
+
config_path = str(config_path)
|
| 1044 |
+
|
| 1045 |
+
is_local = os.path.exists(config_path)
|
| 1046 |
+
if os.path.isfile(os.path.join(subfolder, config_path)):
|
| 1047 |
+
# Special case when config_path is a local file
|
| 1048 |
+
resolved_config_file = config_path
|
| 1049 |
+
is_local = True
|
| 1050 |
+
elif is_remote_url(config_path):
|
| 1051 |
+
configuration_file = config_path
|
| 1052 |
+
resolved_config_file = download_url(config_path)
|
| 1053 |
+
else:
|
| 1054 |
+
configuration_file = config_file_name
|
| 1055 |
+
try:
|
| 1056 |
+
# Load from local folder or from cache or download from model Hub and cache
|
| 1057 |
+
resolved_config_file = cached_file(
|
| 1058 |
+
pretrained_model_name,
|
| 1059 |
+
configuration_file,
|
| 1060 |
+
cache_dir=cache_dir,
|
| 1061 |
+
force_download=force_download,
|
| 1062 |
+
proxies=proxies,
|
| 1063 |
+
resume_download=resume_download,
|
| 1064 |
+
local_files_only=local_files_only,
|
| 1065 |
+
token=token,
|
| 1066 |
+
user_agent=user_agent,
|
| 1067 |
+
revision=revision,
|
| 1068 |
+
subfolder=subfolder,
|
| 1069 |
+
_commit_hash=commit_hash,
|
| 1070 |
+
)
|
| 1071 |
+
commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
|
| 1072 |
+
except EnvironmentError:
|
| 1073 |
+
# Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
|
| 1074 |
+
# the original exception.
|
| 1075 |
+
raise
|
| 1076 |
+
except Exception:
|
| 1077 |
+
# For any other exception, we throw a generic error.
|
| 1078 |
+
raise EnvironmentError(
|
| 1079 |
+
f"Can't load the configuration of '{pretrained_model_name}'. If you were trying to load it"
|
| 1080 |
+
" from 'https://huggingface.co/models', make sure you don't have a local directory with the same"
|
| 1081 |
+
f" name. Otherwise, make sure '{pretrained_model_name}' is the correct path to a directory"
|
| 1082 |
+
f" containing a {configuration_file} file"
|
| 1083 |
+
)
|
| 1084 |
+
|
| 1085 |
+
try:
|
| 1086 |
+
# Load config dict
|
| 1087 |
+
config_dict = cls._dict_from_json_file(resolved_config_file)
|
| 1088 |
+
config_dict["_commit_hash"] = commit_hash
|
| 1089 |
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
| 1090 |
+
raise EnvironmentError(
|
| 1091 |
+
f"It looks like the config file at '{resolved_config_file}' is not a valid JSON file."
|
| 1092 |
+
)
|
| 1093 |
+
|
| 1094 |
+
if is_local:
|
| 1095 |
+
logger.info(f"loading configuration file {resolved_config_file}")
|
| 1096 |
+
else:
|
| 1097 |
+
logger.info(f"loading configuration file {configuration_file} from cache at {resolved_config_file}")
|
| 1098 |
+
|
| 1099 |
+
if kwargs.get("return_unused_kwargs") is True:
|
| 1100 |
+
config, unused_kwargs = cls.from_dict(config_dict, **kwargs)
|
| 1101 |
+
config._original_object_hash = hash(config) # Hash to detect whether the instance was modified
|
| 1102 |
+
return config, unused_kwargs
|
| 1103 |
+
else:
|
| 1104 |
+
config = cls.from_dict(config_dict, **kwargs)
|
| 1105 |
+
config._original_object_hash = hash(config) # Hash to detect whether the instance was modified
|
| 1106 |
+
return config
|
| 1107 |
+
|
| 1108 |
+
@classmethod
|
| 1109 |
+
def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
|
| 1110 |
+
with open(json_file, "r", encoding="utf-8") as reader:
|
| 1111 |
+
text = reader.read()
|
| 1112 |
+
return json.loads(text)
|
| 1113 |
+
|
| 1114 |
+
@classmethod
|
| 1115 |
+
def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "GenerationConfig":
|
| 1116 |
+
"""
|
| 1117 |
+
Instantiates a [`GenerationConfig`] from a Python dictionary of parameters.
|
| 1118 |
+
|
| 1119 |
+
Args:
|
| 1120 |
+
config_dict (`Dict[str, Any]`):
|
| 1121 |
+
Dictionary that will be used to instantiate the configuration object.
|
| 1122 |
+
kwargs (`Dict[str, Any]`):
|
| 1123 |
+
Additional parameters from which to initialize the configuration object.
|
| 1124 |
+
|
| 1125 |
+
Returns:
|
| 1126 |
+
[`GenerationConfig`]: The configuration object instantiated from those parameters.
|
| 1127 |
+
"""
|
| 1128 |
+
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
|
| 1129 |
+
# Those arguments may be passed along for our internal telemetry.
|
| 1130 |
+
# We remove them so they don't appear in `return_unused_kwargs`.
|
| 1131 |
+
kwargs.pop("_from_auto", None)
|
| 1132 |
+
kwargs.pop("_from_pipeline", None)
|
| 1133 |
+
# The commit hash might have been updated in the `config_dict`, we don't want the kwargs to erase that update.
|
| 1134 |
+
if "_commit_hash" in kwargs and "_commit_hash" in config_dict:
|
| 1135 |
+
kwargs["_commit_hash"] = config_dict["_commit_hash"]
|
| 1136 |
+
|
| 1137 |
+
# The line below allows model-specific config to be loaded as well through kwargs, with safety checks.
|
| 1138 |
+
# See https://github.com/huggingface/transformers/pull/21269
|
| 1139 |
+
config = cls(**{**config_dict, **kwargs})
|
| 1140 |
+
unused_kwargs = config.update(**kwargs)
|
| 1141 |
+
|
| 1142 |
+
logger.info(f"Generate config {config}")
|
| 1143 |
+
if return_unused_kwargs:
|
| 1144 |
+
return config, unused_kwargs
|
| 1145 |
+
else:
|
| 1146 |
+
return config
|
| 1147 |
+
|
| 1148 |
+
def dict_torch_dtype_to_str(self, d: Dict[str, Any]) -> None:
|
| 1149 |
+
"""
|
| 1150 |
+
Checks whether the passed dictionary and its nested dicts have a *torch_dtype* key and if it's not None,
|
| 1151 |
+
converts torch.dtype to a string of just the type. For example, `torch.float32` get converted into *"float32"*
|
| 1152 |
+
string, which can then be stored in the json format.
|
| 1153 |
+
"""
|
| 1154 |
+
if d.get("torch_dtype", None) is not None and not isinstance(d["torch_dtype"], str):
|
| 1155 |
+
d["torch_dtype"] = str(d["torch_dtype"]).split(".")[1]
|
| 1156 |
+
for value in d.values():
|
| 1157 |
+
if isinstance(value, dict):
|
| 1158 |
+
self.dict_torch_dtype_to_str(value)
|
| 1159 |
+
|
| 1160 |
+
def to_diff_dict(self) -> Dict[str, Any]:
|
| 1161 |
+
"""
|
| 1162 |
+
Removes all attributes from config which correspond to the default config attributes for better readability and
|
| 1163 |
+
serializes to a Python dictionary.
|
| 1164 |
+
|
| 1165 |
+
Returns:
|
| 1166 |
+
`Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
|
| 1167 |
+
"""
|
| 1168 |
+
config_dict = self.to_dict()
|
| 1169 |
+
|
| 1170 |
+
# get the default config dict
|
| 1171 |
+
default_config_dict = GenerationConfig().to_dict()
|
| 1172 |
+
|
| 1173 |
+
serializable_config_dict = {}
|
| 1174 |
+
|
| 1175 |
+
# only serialize values that differ from the default config
|
| 1176 |
+
for key, value in config_dict.items():
|
| 1177 |
+
if key not in default_config_dict or key == "transformers_version" or value != default_config_dict[key]:
|
| 1178 |
+
serializable_config_dict[key] = value
|
| 1179 |
+
|
| 1180 |
+
self.dict_torch_dtype_to_str(serializable_config_dict)
|
| 1181 |
+
return serializable_config_dict
|
| 1182 |
+
|
| 1183 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 1184 |
+
"""
|
| 1185 |
+
Serializes this instance to a Python dictionary.
|
| 1186 |
+
|
| 1187 |
+
Returns:
|
| 1188 |
+
`Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
|
| 1189 |
+
"""
|
| 1190 |
+
output = copy.deepcopy(self.__dict__)
|
| 1191 |
+
|
| 1192 |
+
# Fields to ignore at serialization time
|
| 1193 |
+
if "_commit_hash" in output:
|
| 1194 |
+
del output["_commit_hash"]
|
| 1195 |
+
if "_original_object_hash" in output:
|
| 1196 |
+
del output["_original_object_hash"]
|
| 1197 |
+
if "compile_config" in output:
|
| 1198 |
+
del output["compile_config"]
|
| 1199 |
+
|
| 1200 |
+
# Transformers version when serializing this file
|
| 1201 |
+
output["transformers_version"] = __version__
|
| 1202 |
+
|
| 1203 |
+
self.dict_torch_dtype_to_str(output)
|
| 1204 |
+
return output
|
| 1205 |
+
|
| 1206 |
+
def to_json_string(self, use_diff: bool = True, ignore_metadata: bool = False) -> str:
|
| 1207 |
+
"""
|
| 1208 |
+
Serializes this instance to a JSON string.
|
| 1209 |
+
|
| 1210 |
+
Args:
|
| 1211 |
+
use_diff (`bool`, *optional*, defaults to `True`):
|
| 1212 |
+
If set to `True`, only the difference between the config instance and the default `GenerationConfig()`
|
| 1213 |
+
is serialized to JSON string.
|
| 1214 |
+
ignore_metadata (`bool`, *optional*, defaults to `False`):
|
| 1215 |
+
Whether to ignore the metadata fields present in the instance
|
| 1216 |
+
|
| 1217 |
+
Returns:
|
| 1218 |
+
`str`: String containing all the attributes that make up this configuration instance in JSON format.
|
| 1219 |
+
"""
|
| 1220 |
+
if use_diff is True:
|
| 1221 |
+
config_dict = self.to_diff_dict()
|
| 1222 |
+
else:
|
| 1223 |
+
config_dict = self.to_dict()
|
| 1224 |
+
|
| 1225 |
+
if ignore_metadata:
|
| 1226 |
+
for metadata_field in METADATA_FIELDS:
|
| 1227 |
+
config_dict.pop(metadata_field, None)
|
| 1228 |
+
|
| 1229 |
+
def convert_keys_to_string(obj):
|
| 1230 |
+
if isinstance(obj, dict):
|
| 1231 |
+
return {str(key): convert_keys_to_string(value) for key, value in obj.items()}
|
| 1232 |
+
elif isinstance(obj, list):
|
| 1233 |
+
return [convert_keys_to_string(item) for item in obj]
|
| 1234 |
+
else:
|
| 1235 |
+
return obj
|
| 1236 |
+
|
| 1237 |
+
def convert_dataclass_to_dict(obj):
|
| 1238 |
+
if isinstance(obj, dict):
|
| 1239 |
+
return {key: convert_dataclass_to_dict(value) for key, value in obj.items()}
|
| 1240 |
+
elif is_dataclass(obj):
|
| 1241 |
+
return obj.to_dict()
|
| 1242 |
+
else:
|
| 1243 |
+
return obj
|
| 1244 |
+
|
| 1245 |
+
config_dict = convert_keys_to_string(config_dict)
|
| 1246 |
+
config_dict = convert_dataclass_to_dict(config_dict)
|
| 1247 |
+
|
| 1248 |
+
return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
|
| 1249 |
+
|
| 1250 |
+
def to_json_file(self, json_file_path: Union[str, os.PathLike], use_diff: bool = True):
|
| 1251 |
+
"""
|
| 1252 |
+
Save this instance to a JSON file.
|
| 1253 |
+
|
| 1254 |
+
Args:
|
| 1255 |
+
json_file_path (`str` or `os.PathLike`):
|
| 1256 |
+
Path to the JSON file in which this configuration instance's parameters will be saved.
|
| 1257 |
+
use_diff (`bool`, *optional*, defaults to `True`):
|
| 1258 |
+
If set to `True`, only the difference between the config instance and the default `GenerationConfig()`
|
| 1259 |
+
is serialized to JSON file.
|
| 1260 |
+
"""
|
| 1261 |
+
with open(json_file_path, "w", encoding="utf-8") as writer:
|
| 1262 |
+
writer.write(self.to_json_string(use_diff=use_diff))
|
| 1263 |
+
|
| 1264 |
+
@classmethod
|
| 1265 |
+
def from_model_config(cls, model_config: PretrainedConfig) -> "GenerationConfig":
|
| 1266 |
+
"""
|
| 1267 |
+
Instantiates a [`GenerationConfig`] from a [`PretrainedConfig`]. This function is useful to convert legacy
|
| 1268 |
+
[`PretrainedConfig`] objects, which may contain generation parameters, into a stand-alone [`GenerationConfig`].
|
| 1269 |
+
|
| 1270 |
+
Args:
|
| 1271 |
+
model_config (`PretrainedConfig`):
|
| 1272 |
+
The model config that will be used to instantiate the generation config.
|
| 1273 |
+
|
| 1274 |
+
Returns:
|
| 1275 |
+
[`GenerationConfig`]: The configuration object instantiated from those parameters.
|
| 1276 |
+
"""
|
| 1277 |
+
config_dict = model_config.to_dict()
|
| 1278 |
+
config_dict.pop("_from_model_config", None)
|
| 1279 |
+
|
| 1280 |
+
# Removes all `None` from the model config dict -- this lets the generation config defaults to take hold
|
| 1281 |
+
config_dict = {key: value for key, value in config_dict.items() if value is not None}
|
| 1282 |
+
|
| 1283 |
+
generation_config = cls.from_dict(config_dict, return_unused_kwargs=False, _from_model_config=True)
|
| 1284 |
+
|
| 1285 |
+
# Special case: some models have generation attributes set in the decoder. Use them if still unset in the
|
| 1286 |
+
# generation config (which in turn is defined from the outer attributes of model config).
|
| 1287 |
+
decoder_config = model_config.get_text_config(decoder=True)
|
| 1288 |
+
if decoder_config is not model_config:
|
| 1289 |
+
default_generation_config = GenerationConfig()
|
| 1290 |
+
decoder_config_dict = decoder_config.to_dict()
|
| 1291 |
+
for attr in generation_config.to_dict().keys():
|
| 1292 |
+
is_unset = getattr(generation_config, attr) == getattr(default_generation_config, attr)
|
| 1293 |
+
if attr in decoder_config_dict and is_unset:
|
| 1294 |
+
setattr(generation_config, attr, decoder_config_dict[attr])
|
| 1295 |
+
|
| 1296 |
+
# If any `output_...` flag is set to `True`, we ensure `return_dict_in_generate` is set to `True`.
|
| 1297 |
+
if generation_config.return_dict_in_generate is False:
|
| 1298 |
+
if any(
|
| 1299 |
+
getattr(generation_config, extra_output_flag, False)
|
| 1300 |
+
for extra_output_flag in generation_config.extra_output_flags
|
| 1301 |
+
):
|
| 1302 |
+
generation_config.return_dict_in_generate = True
|
| 1303 |
+
|
| 1304 |
+
# Hash to detect whether the instance was modified
|
| 1305 |
+
generation_config._original_object_hash = hash(generation_config)
|
| 1306 |
+
return generation_config
|
| 1307 |
+
|
| 1308 |
+
def update(self, **kwargs):
|
| 1309 |
+
"""
|
| 1310 |
+
Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes,
|
| 1311 |
+
returning all the unused kwargs.
|
| 1312 |
+
|
| 1313 |
+
Args:
|
| 1314 |
+
kwargs (`Dict[str, Any]`):
|
| 1315 |
+
Dictionary of attributes to tentatively update this class.
|
| 1316 |
+
|
| 1317 |
+
Returns:
|
| 1318 |
+
`Dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance.
|
| 1319 |
+
"""
|
| 1320 |
+
to_remove = []
|
| 1321 |
+
for key, value in kwargs.items():
|
| 1322 |
+
if hasattr(self, key):
|
| 1323 |
+
setattr(self, key, value)
|
| 1324 |
+
to_remove.append(key)
|
| 1325 |
+
|
| 1326 |
+
# Confirm that the updated instance is still valid
|
| 1327 |
+
self.validate()
|
| 1328 |
+
|
| 1329 |
+
# Remove all the attributes that were updated, without modifying the input dict
|
| 1330 |
+
unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove}
|
| 1331 |
+
return unused_kwargs
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
@dataclass
|
| 1335 |
+
class BaseWatermarkingConfig(ABC):
|
| 1336 |
+
"""Generic watermarking config"""
|
| 1337 |
+
|
| 1338 |
+
@classmethod
|
| 1339 |
+
def from_dict(cls, config_dict, **kwargs):
|
| 1340 |
+
"""
|
| 1341 |
+
Constructs a BaseWatermarkingConfig instance from a dictionary of parameters.
|
| 1342 |
+
|
| 1343 |
+
Args:
|
| 1344 |
+
config_dict (Dict[str, Any]): Dictionary containing configuration parameters.
|
| 1345 |
+
**kwargs: Additional keyword arguments to override dictionary values.
|
| 1346 |
+
|
| 1347 |
+
Returns:
|
| 1348 |
+
BaseWatermarkingConfig: Instance of BaseWatermarkingConfig constructed from the dictionary.
|
| 1349 |
+
"""
|
| 1350 |
+
config = cls(**config_dict)
|
| 1351 |
+
to_remove = []
|
| 1352 |
+
for key, value in kwargs.items():
|
| 1353 |
+
if hasattr(config, key):
|
| 1354 |
+
setattr(config, key, value)
|
| 1355 |
+
to_remove.append(key)
|
| 1356 |
+
for key in to_remove:
|
| 1357 |
+
kwargs.pop(key, None)
|
| 1358 |
+
return config
|
| 1359 |
+
|
| 1360 |
+
def to_json_file(self, json_file_path: Union[str, os.PathLike]):
|
| 1361 |
+
"""
|
| 1362 |
+
Save this instance to a JSON file.
|
| 1363 |
+
|
| 1364 |
+
Args:
|
| 1365 |
+
json_file_path (Union[str, os.PathLike]): Path to the JSON file in which this configuration instance's parameters will be saved.
|
| 1366 |
+
"""
|
| 1367 |
+
with open(json_file_path, "w", encoding="utf-8") as writer:
|
| 1368 |
+
config_dict = self.to_dict()
|
| 1369 |
+
json_string = json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
|
| 1370 |
+
|
| 1371 |
+
writer.write(json_string)
|
| 1372 |
+
|
| 1373 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 1374 |
+
"""
|
| 1375 |
+
Serializes this instance to a Python dictionary.
|
| 1376 |
+
|
| 1377 |
+
Returns:
|
| 1378 |
+
Dict[str, Any]: Dictionary of all the attributes that make up this configuration instance.
|
| 1379 |
+
"""
|
| 1380 |
+
output = copy.deepcopy(self.__dict__)
|
| 1381 |
+
return output
|
| 1382 |
+
|
| 1383 |
+
def __iter__(self):
|
| 1384 |
+
for attr, value in copy.deepcopy(self.__dict__).items():
|
| 1385 |
+
yield attr, value
|
| 1386 |
+
|
| 1387 |
+
def __repr__(self):
|
| 1388 |
+
return f"{self.__class__.__name__} {self.to_json_string()}"
|
| 1389 |
+
|
| 1390 |
+
def to_json_string(self):
|
| 1391 |
+
"""
|
| 1392 |
+
Serializes this instance to a JSON formatted string.
|
| 1393 |
+
|
| 1394 |
+
Returns:
|
| 1395 |
+
str: JSON formatted string representing the configuration instance.
|
| 1396 |
+
"""
|
| 1397 |
+
return json.dumps(self.__dict__, indent=2) + "\n"
|
| 1398 |
+
|
| 1399 |
+
def update(self, **kwargs):
|
| 1400 |
+
"""
|
| 1401 |
+
Update the configuration attributes with new values.
|
| 1402 |
+
|
| 1403 |
+
Args:
|
| 1404 |
+
**kwargs: Keyword arguments representing configuration attributes and their new values.
|
| 1405 |
+
"""
|
| 1406 |
+
for key, value in kwargs.items():
|
| 1407 |
+
if hasattr(self, key):
|
| 1408 |
+
setattr(self, key, value)
|
| 1409 |
+
|
| 1410 |
+
@abstractmethod
|
| 1411 |
+
def validate(self): ...
|
| 1412 |
+
|
| 1413 |
+
@abstractmethod
|
| 1414 |
+
def construct_processor(self, vocab_size): ...
|
| 1415 |
+
|
| 1416 |
+
|
| 1417 |
+
@dataclass
|
| 1418 |
+
class WatermarkingConfig(BaseWatermarkingConfig):
|
| 1419 |
+
"""
|
| 1420 |
+
Class that holds arguments for watermark generation and should be passed into `GenerationConfig` during `generate`.
|
| 1421 |
+
See [this paper](https://arxiv.org/abs/2306.04634) for more details on the arguments.
|
| 1422 |
+
|
| 1423 |
+
Accepts the following keys:
|
| 1424 |
+
- greenlist_ratio (`float`):
|
| 1425 |
+
Used for watermarking. The ratio of "green" tokens used to the vocabulary size. Defaults to 0.25.
|
| 1426 |
+
- bias (`float`):
|
| 1427 |
+
Used with watermarking. The bias added to the selected "green" tokens' logits. Defaults to 2.0.
|
| 1428 |
+
- hashing_key (`int`):
|
| 1429 |
+
Hashing key used for watermarking. Defaults to 15485863 (the millionth prime).
|
| 1430 |
+
- seeding_scheme (`str`):
|
| 1431 |
+
Algorithm to use for watermarking. Accepts values:
|
| 1432 |
+
- "lefthash" (default): "green" tokens selection depend on the last token (Algorithm 2 from the paper)
|
| 1433 |
+
- "selfhash": "green" tokens selection depends on the current token itself (Algorithm 3 from the paper)
|
| 1434 |
+
The downside of this scheme is that it considers all possible next tokens and can be slower than "lefthash".
|
| 1435 |
+
- context_width(`int`):
|
| 1436 |
+
The context length of previous tokens to use in seeding. Higher context length makes watermarking more robust.
|
| 1437 |
+
"""
|
| 1438 |
+
|
| 1439 |
+
def __init__(
|
| 1440 |
+
self,
|
| 1441 |
+
greenlist_ratio: Optional[float] = 0.25,
|
| 1442 |
+
bias: Optional[float] = 2.0,
|
| 1443 |
+
hashing_key: Optional[int] = 15485863,
|
| 1444 |
+
seeding_scheme: Optional[str] = "lefthash",
|
| 1445 |
+
context_width: Optional[int] = 1,
|
| 1446 |
+
):
|
| 1447 |
+
self.greenlist_ratio = greenlist_ratio
|
| 1448 |
+
self.bias = bias
|
| 1449 |
+
self.hashing_key = hashing_key
|
| 1450 |
+
self.seeding_scheme = seeding_scheme
|
| 1451 |
+
self.context_width = context_width
|
| 1452 |
+
|
| 1453 |
+
def validate(self):
|
| 1454 |
+
watermark_missing_arg_msg = (
|
| 1455 |
+
"Some of the keys in `watermarking_config` are defined incorrectly. `{key}` should be {correct_value}` "
|
| 1456 |
+
"but found {found_value}"
|
| 1457 |
+
)
|
| 1458 |
+
if self.seeding_scheme not in ["selfhash", "lefthash"]:
|
| 1459 |
+
raise ValueError(
|
| 1460 |
+
watermark_missing_arg_msg.format(
|
| 1461 |
+
key="seeding_scheme",
|
| 1462 |
+
correct_value="[`selfhash`, `lefthash`]",
|
| 1463 |
+
found_value=self.seeding_scheme,
|
| 1464 |
+
),
|
| 1465 |
+
)
|
| 1466 |
+
if not 0.0 <= self.greenlist_ratio <= 1.0:
|
| 1467 |
+
raise ValueError(
|
| 1468 |
+
watermark_missing_arg_msg.format(
|
| 1469 |
+
key="greenlist_ratio",
|
| 1470 |
+
correct_value="in range between 0.0 and 1.0",
|
| 1471 |
+
found_value=self.seeding_scheme,
|
| 1472 |
+
),
|
| 1473 |
+
)
|
| 1474 |
+
if not self.context_width >= 1:
|
| 1475 |
+
raise ValueError(
|
| 1476 |
+
watermark_missing_arg_msg.format(
|
| 1477 |
+
key="context_width",
|
| 1478 |
+
correct_value="a positive integer",
|
| 1479 |
+
found_value=self.context_width,
|
| 1480 |
+
),
|
| 1481 |
+
)
|
| 1482 |
+
|
| 1483 |
+
def construct_processor(self, vocab_size: int, device) -> "WatermarkLogitsProcessor":
|
| 1484 |
+
return WatermarkLogitsProcessor(
|
| 1485 |
+
vocab_size=vocab_size,
|
| 1486 |
+
device=device,
|
| 1487 |
+
greenlist_ratio=self.greenlist_ratio,
|
| 1488 |
+
bias=self.bias,
|
| 1489 |
+
hashing_key=self.hashing_key,
|
| 1490 |
+
seeding_scheme=self.seeding_scheme,
|
| 1491 |
+
context_width=self.context_width,
|
| 1492 |
+
)
|
| 1493 |
+
|
| 1494 |
+
|
| 1495 |
+
@dataclass
|
| 1496 |
+
class SynthIDTextWatermarkingConfig(BaseWatermarkingConfig):
|
| 1497 |
+
"""
|
| 1498 |
+
Class that holds arguments for watermark generation and should be passed into `GenerationConfig` during `generate`.
|
| 1499 |
+
See [this paper](https://www.nature.com/articles/s41586-024-08025-4) for more details on the arguments.
|
| 1500 |
+
|
| 1501 |
+
Args:
|
| 1502 |
+
ngram_len (`int`):
|
| 1503 |
+
Ngram length.
|
| 1504 |
+
keys (`List[int]`):
|
| 1505 |
+
A sequence of watermarking keys, one for each depth.
|
| 1506 |
+
context_history_size (`int`, *optional*, defaults to 1024):
|
| 1507 |
+
Size of the tensor to keep track of seen contexts.
|
| 1508 |
+
sampling_table_seed (`int`, *optional*, defaults to 0):
|
| 1509 |
+
Random seed to generate the sampling table.
|
| 1510 |
+
sampling_table_size (`int`, *optional*, defaults to 65536):
|
| 1511 |
+
Size of the sampling table.
|
| 1512 |
+
skip_first_ngram_calls (`bool`, *optional*, defaults to `False`):
|
| 1513 |
+
Whether to skip first ngram calls.
|
| 1514 |
+
debug_mode (`bool`, optional, *optional*, defaults to `False`):
|
| 1515 |
+
Logits are modified to uniform one got before watermarking modification is applied. This is to test the
|
| 1516 |
+
implementation.
|
| 1517 |
+
|
| 1518 |
+
Examples:
|
| 1519 |
+
```python
|
| 1520 |
+
>>> from transformers import AutoModelForCausalLM, AutoTokenizer, SynthIDTextWatermarkingConfig
|
| 1521 |
+
|
| 1522 |
+
>>> tokenizer = AutoTokenizer.from_pretrained('google/gemma-2-2b', padding_side="left")
|
| 1523 |
+
>>> model = AutoModelForCausalLM.from_pretrained('google/gemma-2-2b')
|
| 1524 |
+
|
| 1525 |
+
>>> # SynthID Text configuration
|
| 1526 |
+
>>> watermarking_config = SynthIDTextWatermarkingConfig(
|
| 1527 |
+
... keys=[654, 400, 836, 123, 340, 443, 597, 160, 57],
|
| 1528 |
+
... ngram_len=5,
|
| 1529 |
+
... )
|
| 1530 |
+
|
| 1531 |
+
>>> # Generation with watermarking
|
| 1532 |
+
>>> tokenized_prompts = tokenizer(["Once upon a time, "], return_tensors="pt", padding=True)
|
| 1533 |
+
>>> output_sequences = model.generate(
|
| 1534 |
+
... **tokenized_prompts, watermarking_config=watermarking_config, do_sample=True, max_new_tokens=10
|
| 1535 |
+
... )
|
| 1536 |
+
>>> watermarked_text = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)
|
| 1537 |
+
```
|
| 1538 |
+
"""
|
| 1539 |
+
|
| 1540 |
+
def __init__(
|
| 1541 |
+
self,
|
| 1542 |
+
ngram_len: int,
|
| 1543 |
+
keys: List[int],
|
| 1544 |
+
context_history_size: int = 1024,
|
| 1545 |
+
sampling_table_seed: int = 0,
|
| 1546 |
+
sampling_table_size: int = 2**16,
|
| 1547 |
+
skip_first_ngram_calls: bool = False,
|
| 1548 |
+
debug_mode: bool = False,
|
| 1549 |
+
):
|
| 1550 |
+
self.ngram_len = ngram_len
|
| 1551 |
+
self.keys = keys
|
| 1552 |
+
self.sampling_table_size = sampling_table_size
|
| 1553 |
+
self.sampling_table_seed = sampling_table_seed
|
| 1554 |
+
self.context_history_size = context_history_size
|
| 1555 |
+
self.skip_first_ngram_calls = skip_first_ngram_calls
|
| 1556 |
+
self.debug_mode = debug_mode
|
| 1557 |
+
|
| 1558 |
+
def validate(self):
|
| 1559 |
+
watermark_missing_arg_msg = (
|
| 1560 |
+
"Some of the keys in `watermarking_config` are defined incorrectly. `{key}` should be {correct_value}` "
|
| 1561 |
+
"but found {found_value}"
|
| 1562 |
+
)
|
| 1563 |
+
if self.sampling_table_size > 2**24:
|
| 1564 |
+
raise ValueError(
|
| 1565 |
+
watermark_missing_arg_msg.format(
|
| 1566 |
+
key="sampling_table_size",
|
| 1567 |
+
correct_value="< 2**24",
|
| 1568 |
+
found_value=self.sampling_table_size,
|
| 1569 |
+
),
|
| 1570 |
+
)
|
| 1571 |
+
|
| 1572 |
+
def construct_processor(self, vocab_size: int, device) -> "WatermarkLogitsProcessor":
|
| 1573 |
+
return SynthIDTextWatermarkLogitsProcessor(
|
| 1574 |
+
ngram_len=self.ngram_len,
|
| 1575 |
+
keys=self.keys,
|
| 1576 |
+
sampling_table_size=self.sampling_table_size,
|
| 1577 |
+
sampling_table_seed=self.sampling_table_seed,
|
| 1578 |
+
context_history_size=self.context_history_size,
|
| 1579 |
+
device=device,
|
| 1580 |
+
skip_first_ngram_calls=self.skip_first_ngram_calls,
|
| 1581 |
+
debug_mode=self.debug_mode,
|
| 1582 |
+
)
|
| 1583 |
+
|
| 1584 |
+
|
| 1585 |
+
@dataclass
|
| 1586 |
+
class CompileConfig:
|
| 1587 |
+
"""
|
| 1588 |
+
Class that holds arguments relative to `torch.compile` behavior, when using automatic compilation in `generate`.
|
| 1589 |
+
See [`torch.compile`](https://pytorch.org/docs/stable/generated/torch.compile.html) for more details on the arguments.
|
| 1590 |
+
|
| 1591 |
+
Args:
|
| 1592 |
+
fullgraph (`bool`, *optional*, defaults to `True`):
|
| 1593 |
+
If `True`, requires that the whole forward be capturable in a single graph.
|
| 1594 |
+
dynamic (`bool` or `None`, *optional*):
|
| 1595 |
+
Whether to try to use dynamic shape graphs.
|
| 1596 |
+
backend (`str` or `Callable`, *optional*, defaults to `"inductor"`):
|
| 1597 |
+
Backend to be used.
|
| 1598 |
+
mode (`str`, *optional*, defaults to `"reduce-overhead"`):
|
| 1599 |
+
Controls balance between performance and overhead.
|
| 1600 |
+
options (`dict`, *optional*):
|
| 1601 |
+
A dictionary of options to pass to the backend.
|
| 1602 |
+
|
| 1603 |
+
Examples:
|
| 1604 |
+
```python
|
| 1605 |
+
>>> from transformers import AutoModelForCausalLM, AutoTokenizer, CompileConfig
|
| 1606 |
+
|
| 1607 |
+
>>> tokenizer = AutoTokenizer.from_pretrained('google/gemma-2-2b')
|
| 1608 |
+
>>> model = AutoModelForCausalLM.from_pretrained('google/gemma-2-2b').cuda()
|
| 1609 |
+
|
| 1610 |
+
>>> # Automatic compile configuration, used with static cache
|
| 1611 |
+
>>> compile_config = CompileConfig(dynamic=True)
|
| 1612 |
+
|
| 1613 |
+
>>> # Generation with static cache and compile config
|
| 1614 |
+
>>> input = tokenizer.encode("Hello there, how", return_tensors="pt").cuda()
|
| 1615 |
+
>>> output = model.generate(
|
| 1616 |
+
... input, do_sample=False, max_new_tokens=300, cache_implementation="static", compile_config=compile_config
|
| 1617 |
+
... )
|
| 1618 |
+
>>> output_text = tokenizer.batch_decode(output, skip_special_tokens=True)[0]
|
| 1619 |
+
```
|
| 1620 |
+
"""
|
| 1621 |
+
|
| 1622 |
+
fullgraph: bool = True
|
| 1623 |
+
dynamic: Optional[bool] = None
|
| 1624 |
+
backend: Union[str, Callable] = "inductor"
|
| 1625 |
+
mode: str = "reduce-overhead"
|
| 1626 |
+
options: Optional[dict] = None
|
| 1627 |
+
# Used to flag our `generate` call to compile on e.g. CPU. Often not optimal, but useful for testing purposes.
|
| 1628 |
+
_compile_all_devices = None
|
| 1629 |
+
|
| 1630 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 1631 |
+
"""Serializes this instance to a Python dictionary."""
|
| 1632 |
+
return copy.deepcopy({key: value for key, value in self.__dict__.items() if key != "_compile_all_devices"})
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/constants.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
IMAGENET_DEFAULT_MEAN = [0.485, 0.456, 0.406]
|
| 2 |
+
IMAGENET_DEFAULT_STD = [0.229, 0.224, 0.225]
|
| 3 |
+
IMAGENET_STANDARD_MEAN = [0.5, 0.5, 0.5]
|
| 4 |
+
IMAGENET_STANDARD_STD = [0.5, 0.5, 0.5]
|
| 5 |
+
OPENAI_CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073]
|
| 6 |
+
OPENAI_CLIP_STD = [0.26862954, 0.26130258, 0.27577711]
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/convert.py
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 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 warnings
|
| 16 |
+
from inspect import signature
|
| 17 |
+
from itertools import chain
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
from packaging.version import Version, parse
|
| 23 |
+
|
| 24 |
+
from ..tokenization_utils_base import PreTrainedTokenizerBase
|
| 25 |
+
from ..utils import (
|
| 26 |
+
TensorType,
|
| 27 |
+
is_tf_available,
|
| 28 |
+
is_torch_available,
|
| 29 |
+
logging,
|
| 30 |
+
)
|
| 31 |
+
from .config import OnnxConfig
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if is_torch_available():
|
| 35 |
+
from ..modeling_utils import PreTrainedModel
|
| 36 |
+
|
| 37 |
+
if is_tf_available():
|
| 38 |
+
from ..modeling_tf_utils import TFPreTrainedModel
|
| 39 |
+
|
| 40 |
+
if TYPE_CHECKING:
|
| 41 |
+
from ..feature_extraction_utils import FeatureExtractionMixin
|
| 42 |
+
from ..processing_utils import ProcessorMixin
|
| 43 |
+
from ..tokenization_utils import PreTrainedTokenizer
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# This is the minimal required version to support some ONNX Runtime features
|
| 50 |
+
ORT_QUANTIZE_MINIMUM_VERSION = parse("1.4.0")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def check_onnxruntime_requirements(minimum_version: Version):
|
| 54 |
+
"""
|
| 55 |
+
Check onnxruntime is installed and if the installed version match is recent enough
|
| 56 |
+
|
| 57 |
+
Raises:
|
| 58 |
+
ImportError: If onnxruntime is not installed or too old version is found
|
| 59 |
+
"""
|
| 60 |
+
try:
|
| 61 |
+
import onnxruntime
|
| 62 |
+
|
| 63 |
+
# Parse the version of the installed onnxruntime
|
| 64 |
+
ort_version = parse(onnxruntime.__version__)
|
| 65 |
+
|
| 66 |
+
# We require 1.4.0 minimum
|
| 67 |
+
if ort_version < ORT_QUANTIZE_MINIMUM_VERSION:
|
| 68 |
+
raise ImportError(
|
| 69 |
+
f"We found an older version of onnxruntime ({onnxruntime.__version__}) "
|
| 70 |
+
f"but we require onnxruntime to be >= {minimum_version} to enable all the conversions options.\n"
|
| 71 |
+
"Please update onnxruntime by running `pip install --upgrade onnxruntime`"
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
except ImportError:
|
| 75 |
+
raise ImportError(
|
| 76 |
+
"onnxruntime doesn't seem to be currently installed. "
|
| 77 |
+
"Please install the onnxruntime by running `pip install onnxruntime`"
|
| 78 |
+
" and relaunch the conversion."
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def export_pytorch(
|
| 83 |
+
preprocessor: Union["PreTrainedTokenizer", "FeatureExtractionMixin", "ProcessorMixin"],
|
| 84 |
+
model: "PreTrainedModel",
|
| 85 |
+
config: OnnxConfig,
|
| 86 |
+
opset: int,
|
| 87 |
+
output: Path,
|
| 88 |
+
tokenizer: Optional["PreTrainedTokenizer"] = None,
|
| 89 |
+
device: str = "cpu",
|
| 90 |
+
) -> Tuple[List[str], List[str]]:
|
| 91 |
+
"""
|
| 92 |
+
Export a PyTorch model to an ONNX Intermediate Representation (IR)
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
preprocessor: ([`PreTrainedTokenizer`], [`FeatureExtractionMixin`] or [`ProcessorMixin`]):
|
| 96 |
+
The preprocessor used for encoding the data.
|
| 97 |
+
model ([`PreTrainedModel`]):
|
| 98 |
+
The model to export.
|
| 99 |
+
config ([`~onnx.config.OnnxConfig`]):
|
| 100 |
+
The ONNX configuration associated with the exported model.
|
| 101 |
+
opset (`int`):
|
| 102 |
+
The version of the ONNX operator set to use.
|
| 103 |
+
output (`Path`):
|
| 104 |
+
Directory to store the exported ONNX model.
|
| 105 |
+
device (`str`, *optional*, defaults to `cpu`):
|
| 106 |
+
The device on which the ONNX model will be exported. Either `cpu` or `cuda`.
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
`Tuple[List[str], List[str]]`: A tuple with an ordered list of the model's inputs, and the named inputs from
|
| 110 |
+
the ONNX configuration.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
if isinstance(preprocessor, PreTrainedTokenizerBase) and tokenizer is not None:
|
| 114 |
+
raise ValueError("You cannot provide both a tokenizer and a preprocessor to export the model.")
|
| 115 |
+
if tokenizer is not None:
|
| 116 |
+
warnings.warn(
|
| 117 |
+
"The `tokenizer` argument is deprecated and will be removed in version 5 of Transformers. Use"
|
| 118 |
+
" `preprocessor` instead.",
|
| 119 |
+
FutureWarning,
|
| 120 |
+
)
|
| 121 |
+
logger.info("Overwriting the `preprocessor` argument with `tokenizer` to generate dummy inputs.")
|
| 122 |
+
preprocessor = tokenizer
|
| 123 |
+
|
| 124 |
+
if issubclass(type(model), PreTrainedModel):
|
| 125 |
+
import torch
|
| 126 |
+
from torch.onnx import export as onnx_export
|
| 127 |
+
|
| 128 |
+
logger.info(f"Using framework PyTorch: {torch.__version__}")
|
| 129 |
+
with torch.no_grad():
|
| 130 |
+
model.config.return_dict = True
|
| 131 |
+
model.eval()
|
| 132 |
+
|
| 133 |
+
# Check if we need to override certain configuration item
|
| 134 |
+
if config.values_override is not None:
|
| 135 |
+
logger.info(f"Overriding {len(config.values_override)} configuration item(s)")
|
| 136 |
+
for override_config_key, override_config_value in config.values_override.items():
|
| 137 |
+
logger.info(f"\t- {override_config_key} -> {override_config_value}")
|
| 138 |
+
setattr(model.config, override_config_key, override_config_value)
|
| 139 |
+
|
| 140 |
+
# Ensure inputs match
|
| 141 |
+
# TODO: Check when exporting QA we provide "is_pair=True"
|
| 142 |
+
model_inputs = config.generate_dummy_inputs(preprocessor, framework=TensorType.PYTORCH)
|
| 143 |
+
device = torch.device(device)
|
| 144 |
+
if device.type == "cuda" and torch.cuda.is_available():
|
| 145 |
+
model.to(device)
|
| 146 |
+
model_inputs_device = {}
|
| 147 |
+
for k, v in model_inputs.items():
|
| 148 |
+
if isinstance(v, Tuple):
|
| 149 |
+
model_inputs_device[k] = tuple(
|
| 150 |
+
x.to(device) if isinstance(x, torch.Tensor) else None for x in v
|
| 151 |
+
)
|
| 152 |
+
elif isinstance(v, List):
|
| 153 |
+
model_inputs_device[k] = [
|
| 154 |
+
tuple(x.to(device) if isinstance(x, torch.Tensor) else None for x in t) for t in v
|
| 155 |
+
]
|
| 156 |
+
else:
|
| 157 |
+
model_inputs_device[k] = v.to(device)
|
| 158 |
+
|
| 159 |
+
model_inputs = model_inputs_device
|
| 160 |
+
|
| 161 |
+
inputs_match, matched_inputs = ensure_model_and_config_inputs_match(model, model_inputs.keys())
|
| 162 |
+
onnx_outputs = list(config.outputs.keys())
|
| 163 |
+
|
| 164 |
+
if not inputs_match:
|
| 165 |
+
raise ValueError("Model and config inputs doesn't match")
|
| 166 |
+
|
| 167 |
+
config.patch_ops()
|
| 168 |
+
|
| 169 |
+
onnx_export(
|
| 170 |
+
model,
|
| 171 |
+
(model_inputs,),
|
| 172 |
+
f=output.as_posix(),
|
| 173 |
+
input_names=list(config.inputs.keys()),
|
| 174 |
+
output_names=onnx_outputs,
|
| 175 |
+
dynamic_axes=dict(chain(config.inputs.items(), config.outputs.items())),
|
| 176 |
+
do_constant_folding=True,
|
| 177 |
+
opset_version=opset,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
config.restore_ops()
|
| 181 |
+
|
| 182 |
+
return matched_inputs, onnx_outputs
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def export_tensorflow(
|
| 186 |
+
preprocessor: Union["PreTrainedTokenizer", "FeatureExtractionMixin"],
|
| 187 |
+
model: "TFPreTrainedModel",
|
| 188 |
+
config: OnnxConfig,
|
| 189 |
+
opset: int,
|
| 190 |
+
output: Path,
|
| 191 |
+
tokenizer: Optional["PreTrainedTokenizer"] = None,
|
| 192 |
+
) -> Tuple[List[str], List[str]]:
|
| 193 |
+
"""
|
| 194 |
+
Export a TensorFlow model to an ONNX Intermediate Representation (IR)
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
preprocessor: ([`PreTrainedTokenizer`] or [`FeatureExtractionMixin`]):
|
| 198 |
+
The preprocessor used for encoding the data.
|
| 199 |
+
model ([`TFPreTrainedModel`]):
|
| 200 |
+
The model to export.
|
| 201 |
+
config ([`~onnx.config.OnnxConfig`]):
|
| 202 |
+
The ONNX configuration associated with the exported model.
|
| 203 |
+
opset (`int`):
|
| 204 |
+
The version of the ONNX operator set to use.
|
| 205 |
+
output (`Path`):
|
| 206 |
+
Directory to store the exported ONNX model.
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
`Tuple[List[str], List[str]]`: A tuple with an ordered list of the model's inputs, and the named inputs from
|
| 210 |
+
the ONNX configuration.
|
| 211 |
+
"""
|
| 212 |
+
import onnx
|
| 213 |
+
import tensorflow as tf
|
| 214 |
+
import tf2onnx
|
| 215 |
+
|
| 216 |
+
if isinstance(preprocessor, PreTrainedTokenizerBase) and tokenizer is not None:
|
| 217 |
+
raise ValueError("You cannot provide both a tokenizer and preprocessor to export the model.")
|
| 218 |
+
if tokenizer is not None:
|
| 219 |
+
warnings.warn(
|
| 220 |
+
"The `tokenizer` argument is deprecated and will be removed in version 5 of Transformers. Use"
|
| 221 |
+
" `preprocessor` instead.",
|
| 222 |
+
FutureWarning,
|
| 223 |
+
)
|
| 224 |
+
logger.info("Overwriting the `preprocessor` argument with `tokenizer` to generate dummy inputs.")
|
| 225 |
+
preprocessor = tokenizer
|
| 226 |
+
|
| 227 |
+
model.config.return_dict = True
|
| 228 |
+
|
| 229 |
+
# Check if we need to override certain configuration item
|
| 230 |
+
if config.values_override is not None:
|
| 231 |
+
logger.info(f"Overriding {len(config.values_override)} configuration item(s)")
|
| 232 |
+
for override_config_key, override_config_value in config.values_override.items():
|
| 233 |
+
logger.info(f"\t- {override_config_key} -> {override_config_value}")
|
| 234 |
+
setattr(model.config, override_config_key, override_config_value)
|
| 235 |
+
|
| 236 |
+
# Ensure inputs match
|
| 237 |
+
model_inputs = config.generate_dummy_inputs(preprocessor, framework=TensorType.TENSORFLOW)
|
| 238 |
+
inputs_match, matched_inputs = ensure_model_and_config_inputs_match(model, model_inputs.keys())
|
| 239 |
+
onnx_outputs = list(config.outputs.keys())
|
| 240 |
+
|
| 241 |
+
input_signature = [
|
| 242 |
+
tf.TensorSpec([None] * tensor.ndim, dtype=tensor.dtype, name=key) for key, tensor in model_inputs.items()
|
| 243 |
+
]
|
| 244 |
+
onnx_model, _ = tf2onnx.convert.from_keras(model, input_signature, opset=opset)
|
| 245 |
+
onnx.save(onnx_model, output.as_posix())
|
| 246 |
+
config.restore_ops()
|
| 247 |
+
|
| 248 |
+
return matched_inputs, onnx_outputs
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def export(
|
| 252 |
+
preprocessor: Union["PreTrainedTokenizer", "FeatureExtractionMixin", "ProcessorMixin"],
|
| 253 |
+
model: Union["PreTrainedModel", "TFPreTrainedModel"],
|
| 254 |
+
config: OnnxConfig,
|
| 255 |
+
opset: int,
|
| 256 |
+
output: Path,
|
| 257 |
+
tokenizer: Optional["PreTrainedTokenizer"] = None,
|
| 258 |
+
device: str = "cpu",
|
| 259 |
+
) -> Tuple[List[str], List[str]]:
|
| 260 |
+
"""
|
| 261 |
+
Export a Pytorch or TensorFlow model to an ONNX Intermediate Representation (IR)
|
| 262 |
+
|
| 263 |
+
Args:
|
| 264 |
+
preprocessor: ([`PreTrainedTokenizer`], [`FeatureExtractionMixin`] or [`ProcessorMixin`]):
|
| 265 |
+
The preprocessor used for encoding the data.
|
| 266 |
+
model ([`PreTrainedModel`] or [`TFPreTrainedModel`]):
|
| 267 |
+
The model to export.
|
| 268 |
+
config ([`~onnx.config.OnnxConfig`]):
|
| 269 |
+
The ONNX configuration associated with the exported model.
|
| 270 |
+
opset (`int`):
|
| 271 |
+
The version of the ONNX operator set to use.
|
| 272 |
+
output (`Path`):
|
| 273 |
+
Directory to store the exported ONNX model.
|
| 274 |
+
device (`str`, *optional*, defaults to `cpu`):
|
| 275 |
+
The device on which the ONNX model will be exported. Either `cpu` or `cuda`. Only PyTorch is supported for
|
| 276 |
+
export on CUDA devices.
|
| 277 |
+
|
| 278 |
+
Returns:
|
| 279 |
+
`Tuple[List[str], List[str]]`: A tuple with an ordered list of the model's inputs, and the named inputs from
|
| 280 |
+
the ONNX configuration.
|
| 281 |
+
"""
|
| 282 |
+
if not (is_torch_available() or is_tf_available()):
|
| 283 |
+
raise ImportError(
|
| 284 |
+
"Cannot convert because neither PyTorch nor TensorFlow are not installed. "
|
| 285 |
+
"Please install torch or tensorflow first."
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
if is_tf_available() and isinstance(model, TFPreTrainedModel) and device == "cuda":
|
| 289 |
+
raise RuntimeError("`tf2onnx` does not support export on CUDA device.")
|
| 290 |
+
|
| 291 |
+
if isinstance(preprocessor, PreTrainedTokenizerBase) and tokenizer is not None:
|
| 292 |
+
raise ValueError("You cannot provide both a tokenizer and a preprocessor to export the model.")
|
| 293 |
+
if tokenizer is not None:
|
| 294 |
+
warnings.warn(
|
| 295 |
+
"The `tokenizer` argument is deprecated and will be removed in version 5 of Transformers. Use"
|
| 296 |
+
" `preprocessor` instead.",
|
| 297 |
+
FutureWarning,
|
| 298 |
+
)
|
| 299 |
+
logger.info("Overwriting the `preprocessor` argument with `tokenizer` to generate dummy inputs.")
|
| 300 |
+
preprocessor = tokenizer
|
| 301 |
+
|
| 302 |
+
if is_torch_available():
|
| 303 |
+
from ..utils import get_torch_version
|
| 304 |
+
|
| 305 |
+
if not config.is_torch_support_available:
|
| 306 |
+
logger.warning(
|
| 307 |
+
f"Unsupported PyTorch version for this model. Minimum required is {config.torch_onnx_minimum_version},"
|
| 308 |
+
f" got: {get_torch_version()}"
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
if is_torch_available() and issubclass(type(model), PreTrainedModel):
|
| 312 |
+
return export_pytorch(preprocessor, model, config, opset, output, tokenizer=tokenizer, device=device)
|
| 313 |
+
elif is_tf_available() and issubclass(type(model), TFPreTrainedModel):
|
| 314 |
+
return export_tensorflow(preprocessor, model, config, opset, output, tokenizer=tokenizer)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def validate_model_outputs(
|
| 318 |
+
config: OnnxConfig,
|
| 319 |
+
preprocessor: Union["PreTrainedTokenizer", "FeatureExtractionMixin", "ProcessorMixin"],
|
| 320 |
+
reference_model: Union["PreTrainedModel", "TFPreTrainedModel"],
|
| 321 |
+
onnx_model: Path,
|
| 322 |
+
onnx_named_outputs: List[str],
|
| 323 |
+
atol: float,
|
| 324 |
+
tokenizer: Optional["PreTrainedTokenizer"] = None,
|
| 325 |
+
):
|
| 326 |
+
from onnxruntime import InferenceSession, SessionOptions
|
| 327 |
+
|
| 328 |
+
logger.info("Validating ONNX model...")
|
| 329 |
+
|
| 330 |
+
if isinstance(preprocessor, PreTrainedTokenizerBase) and tokenizer is not None:
|
| 331 |
+
raise ValueError("You cannot provide both a tokenizer and a preprocessor to validate the model outputs.")
|
| 332 |
+
if tokenizer is not None:
|
| 333 |
+
warnings.warn(
|
| 334 |
+
"The `tokenizer` argument is deprecated and will be removed in version 5 of Transformers. Use"
|
| 335 |
+
" `preprocessor` instead.",
|
| 336 |
+
FutureWarning,
|
| 337 |
+
)
|
| 338 |
+
logger.info("Overwriting the `preprocessor` argument with `tokenizer` to generate dummy inputs.")
|
| 339 |
+
preprocessor = tokenizer
|
| 340 |
+
|
| 341 |
+
# generate inputs with a different batch_size and seq_len that was used for conversion to properly test
|
| 342 |
+
# dynamic input shapes.
|
| 343 |
+
if is_torch_available() and issubclass(type(reference_model), PreTrainedModel):
|
| 344 |
+
reference_model_inputs = config.generate_dummy_inputs(
|
| 345 |
+
preprocessor,
|
| 346 |
+
batch_size=config.default_fixed_batch + 1,
|
| 347 |
+
seq_length=config.default_fixed_sequence + 1,
|
| 348 |
+
framework=TensorType.PYTORCH,
|
| 349 |
+
)
|
| 350 |
+
else:
|
| 351 |
+
reference_model_inputs = config.generate_dummy_inputs(
|
| 352 |
+
preprocessor,
|
| 353 |
+
batch_size=config.default_fixed_batch + 1,
|
| 354 |
+
seq_length=config.default_fixed_sequence + 1,
|
| 355 |
+
framework=TensorType.TENSORFLOW,
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
# Create ONNX Runtime session
|
| 359 |
+
options = SessionOptions()
|
| 360 |
+
session = InferenceSession(onnx_model.as_posix(), options, providers=["CPUExecutionProvider"])
|
| 361 |
+
|
| 362 |
+
# Compute outputs from the reference model
|
| 363 |
+
if is_torch_available() and issubclass(type(reference_model), PreTrainedModel):
|
| 364 |
+
reference_model.to("cpu")
|
| 365 |
+
ref_outputs = reference_model(**reference_model_inputs)
|
| 366 |
+
ref_outputs_dict = {}
|
| 367 |
+
|
| 368 |
+
# We flatten potential collection of outputs (i.e. past_keys) to a flat structure
|
| 369 |
+
for name, value in ref_outputs.items():
|
| 370 |
+
# Overwriting the output name as "present" since it is the name used for the ONNX outputs
|
| 371 |
+
# ("past_key_values" being taken for the ONNX inputs)
|
| 372 |
+
if name == "past_key_values":
|
| 373 |
+
name = "present"
|
| 374 |
+
if isinstance(value, (list, tuple)):
|
| 375 |
+
value = config.flatten_output_collection_property(name, value)
|
| 376 |
+
ref_outputs_dict.update(value)
|
| 377 |
+
else:
|
| 378 |
+
ref_outputs_dict[name] = value
|
| 379 |
+
|
| 380 |
+
# Create onnxruntime inputs from the reference model inputs
|
| 381 |
+
reference_model_inputs_onnxruntime = config.generate_dummy_inputs_onnxruntime(reference_model_inputs)
|
| 382 |
+
|
| 383 |
+
# We flatten potential collection of inputs (i.e. past_keys)
|
| 384 |
+
onnx_inputs = {}
|
| 385 |
+
for name, value in reference_model_inputs_onnxruntime.items():
|
| 386 |
+
if isinstance(value, (list, tuple)):
|
| 387 |
+
value = config.flatten_output_collection_property(name, value)
|
| 388 |
+
onnx_inputs.update({tensor_name: pt_tensor.numpy() for tensor_name, pt_tensor in value.items()})
|
| 389 |
+
else:
|
| 390 |
+
onnx_inputs[name] = value.numpy()
|
| 391 |
+
|
| 392 |
+
# Compute outputs from the ONNX model
|
| 393 |
+
onnx_outputs = session.run(onnx_named_outputs, onnx_inputs)
|
| 394 |
+
|
| 395 |
+
# Check we have a subset of the keys into onnx_outputs against ref_outputs
|
| 396 |
+
ref_outputs_set, onnx_outputs_set = set(ref_outputs_dict.keys()), set(onnx_named_outputs)
|
| 397 |
+
if not onnx_outputs_set.issubset(ref_outputs_set):
|
| 398 |
+
logger.info(
|
| 399 |
+
f"\t-[x] ONNX model output names {onnx_outputs_set} do not match reference model {ref_outputs_set}"
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
raise ValueError(
|
| 403 |
+
"Outputs doesn't match between reference model and ONNX exported model: "
|
| 404 |
+
f"{onnx_outputs_set.difference(ref_outputs_set)}"
|
| 405 |
+
)
|
| 406 |
+
else:
|
| 407 |
+
logger.info(f"\t-[✓] ONNX model output names match reference model ({onnx_outputs_set})")
|
| 408 |
+
|
| 409 |
+
# Check the shape and values match
|
| 410 |
+
for name, ort_value in zip(onnx_named_outputs, onnx_outputs):
|
| 411 |
+
if is_torch_available() and issubclass(type(reference_model), PreTrainedModel):
|
| 412 |
+
ref_value = ref_outputs_dict[name].detach().numpy()
|
| 413 |
+
else:
|
| 414 |
+
ref_value = ref_outputs_dict[name].numpy()
|
| 415 |
+
logger.info(f'\t- Validating ONNX Model output "{name}":')
|
| 416 |
+
|
| 417 |
+
# Shape
|
| 418 |
+
if not ort_value.shape == ref_value.shape:
|
| 419 |
+
logger.info(f"\t\t-[x] shape {ort_value.shape} doesn't match {ref_value.shape}")
|
| 420 |
+
raise ValueError(
|
| 421 |
+
"Outputs shape doesn't match between reference model and ONNX exported model: "
|
| 422 |
+
f"Got {ref_value.shape} (reference) and {ort_value.shape} (ONNX)"
|
| 423 |
+
)
|
| 424 |
+
else:
|
| 425 |
+
logger.info(f"\t\t-[✓] {ort_value.shape} matches {ref_value.shape}")
|
| 426 |
+
|
| 427 |
+
# Values
|
| 428 |
+
if not np.allclose(ref_value, ort_value, atol=atol):
|
| 429 |
+
bad_indices = np.logical_not(np.isclose(ref_value, ort_value, atol=atol))
|
| 430 |
+
logger.info(f"\t\t-[x] values not close enough (atol: {atol})")
|
| 431 |
+
raise ValueError(
|
| 432 |
+
"Outputs values doesn't match between reference model and ONNX exported model: "
|
| 433 |
+
f"Got max absolute difference of: {np.amax(np.abs(ref_value - ort_value))} for "
|
| 434 |
+
f"{ref_value[bad_indices]} vs {ort_value[bad_indices]}"
|
| 435 |
+
)
|
| 436 |
+
else:
|
| 437 |
+
logger.info(f"\t\t-[✓] all values close (atol: {atol})")
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def ensure_model_and_config_inputs_match(
|
| 441 |
+
model: Union["PreTrainedModel", "TFPreTrainedModel"], model_inputs: Iterable[str]
|
| 442 |
+
) -> Tuple[bool, List[str]]:
|
| 443 |
+
"""
|
| 444 |
+
|
| 445 |
+
:param model_inputs: :param config_inputs: :return:
|
| 446 |
+
"""
|
| 447 |
+
if is_torch_available() and issubclass(type(model), PreTrainedModel):
|
| 448 |
+
forward_parameters = signature(model.forward).parameters
|
| 449 |
+
else:
|
| 450 |
+
forward_parameters = signature(model.call).parameters
|
| 451 |
+
model_inputs_set = set(model_inputs)
|
| 452 |
+
|
| 453 |
+
# We are fine if config_inputs has more keys than model_inputs
|
| 454 |
+
forward_inputs_set = set(forward_parameters.keys())
|
| 455 |
+
is_ok = model_inputs_set.issubset(forward_inputs_set)
|
| 456 |
+
|
| 457 |
+
# Make sure the input order match (VERY IMPORTANT !!!!)
|
| 458 |
+
matching_inputs = forward_inputs_set.intersection(model_inputs_set)
|
| 459 |
+
ordered_inputs = [parameter for parameter in forward_parameters.keys() if parameter in matching_inputs]
|
| 460 |
+
return is_ok, ordered_inputs
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/convert_slow_tokenizer.py
ADDED
|
@@ -0,0 +1,1736 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 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 |
+
Utilities to convert slow tokenizers in their fast tokenizers counterparts.
|
| 16 |
+
|
| 17 |
+
All the conversions are grouped here to gather SentencePiece dependencies outside of the fast tokenizers files and
|
| 18 |
+
allow to make our dependency on SentencePiece optional.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import warnings
|
| 22 |
+
|
| 23 |
+
from packaging import version
|
| 24 |
+
from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
|
| 25 |
+
from tokenizers.models import BPE, Unigram, WordPiece
|
| 26 |
+
|
| 27 |
+
from .utils import is_protobuf_available, is_sentencepiece_available, logging, requires_backends
|
| 28 |
+
from .utils.import_utils import PROTOBUF_IMPORT_ERROR
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def import_protobuf(error_message=""):
|
| 35 |
+
if is_sentencepiece_available():
|
| 36 |
+
from sentencepiece import sentencepiece_model_pb2
|
| 37 |
+
|
| 38 |
+
return sentencepiece_model_pb2
|
| 39 |
+
if is_protobuf_available():
|
| 40 |
+
import google.protobuf
|
| 41 |
+
|
| 42 |
+
if version.parse(google.protobuf.__version__) < version.parse("4.0.0"):
|
| 43 |
+
from transformers.utils import sentencepiece_model_pb2
|
| 44 |
+
else:
|
| 45 |
+
from transformers.utils import sentencepiece_model_pb2_new as sentencepiece_model_pb2
|
| 46 |
+
return sentencepiece_model_pb2
|
| 47 |
+
else:
|
| 48 |
+
raise ImportError(PROTOBUF_IMPORT_ERROR.format(error_message))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _get_prepend_scheme(add_prefix_space: bool, original_tokenizer) -> str:
|
| 52 |
+
if add_prefix_space:
|
| 53 |
+
prepend_scheme = "always"
|
| 54 |
+
if not getattr(original_tokenizer, "legacy", True):
|
| 55 |
+
prepend_scheme = "first"
|
| 56 |
+
else:
|
| 57 |
+
prepend_scheme = "never"
|
| 58 |
+
return prepend_scheme
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def generate_merges(vocab, vocab_scores):
|
| 62 |
+
reverse = vocab_scores is not None
|
| 63 |
+
vocab_scores = dict(vocab_scores) if reverse else vocab
|
| 64 |
+
|
| 65 |
+
merges = []
|
| 66 |
+
for merge, piece_score in vocab_scores.items():
|
| 67 |
+
local = []
|
| 68 |
+
for index in range(1, len(merge)):
|
| 69 |
+
piece_l, piece_r = merge[:index], merge[index:]
|
| 70 |
+
if piece_l in vocab and piece_r in vocab:
|
| 71 |
+
local.append((piece_l, piece_r, piece_score))
|
| 72 |
+
local = sorted(local, key=lambda x: (vocab[x[0]], vocab[x[1]]))
|
| 73 |
+
merges.extend(local)
|
| 74 |
+
|
| 75 |
+
merges = sorted(merges, key=lambda val: (val[2], len(val[0]), len(val[1])), reverse=reverse)
|
| 76 |
+
merges = [(val[0], val[1]) for val in merges]
|
| 77 |
+
return merges
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class SentencePieceExtractor:
|
| 81 |
+
"""
|
| 82 |
+
Extractor implementation for SentencePiece trained models. https://github.com/google/sentencepiece
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
def __init__(self, model: str):
|
| 86 |
+
requires_backends(self, "sentencepiece")
|
| 87 |
+
from sentencepiece import SentencePieceProcessor
|
| 88 |
+
|
| 89 |
+
self.sp = SentencePieceProcessor()
|
| 90 |
+
self.sp.Load(model)
|
| 91 |
+
|
| 92 |
+
def extract(self, vocab_scores=None) -> tuple[dict[str, int], list[tuple]]:
|
| 93 |
+
"""
|
| 94 |
+
By default will return vocab and merges with respect to their order, by sending `vocab_scores` we're going to
|
| 95 |
+
order the merges with respect to the piece scores instead.
|
| 96 |
+
"""
|
| 97 |
+
sp = self.sp
|
| 98 |
+
vocab = {sp.id_to_piece(index): index for index in range(sp.GetPieceSize())}
|
| 99 |
+
|
| 100 |
+
merges = generate_merges(vocab, vocab_scores)
|
| 101 |
+
|
| 102 |
+
return vocab, merges
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class GemmaSentencePieceExtractor(SentencePieceExtractor):
|
| 106 |
+
def extract(self, vocab_scores=None) -> tuple[dict[str, int], list[tuple]]:
|
| 107 |
+
"""
|
| 108 |
+
By default will return vocab and merges with respect to their order, by sending `vocab_scores` we're going to
|
| 109 |
+
order the merges with respect to the piece scores instead.
|
| 110 |
+
"""
|
| 111 |
+
sp = self.sp
|
| 112 |
+
vocab = {sp.id_to_piece(index): index for index in range(sp.GetPieceSize())}
|
| 113 |
+
|
| 114 |
+
# If "\t" is missing in the vocab, we have to do this to support merges
|
| 115 |
+
# "<0x09>" is the bytefallback for `\t`
|
| 116 |
+
if "\t" not in vocab:
|
| 117 |
+
vocab["\t"] = vocab.get("<0x09>")
|
| 118 |
+
merges = generate_merges(vocab, vocab_scores)
|
| 119 |
+
return vocab, merges
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def check_number_comma(piece: str) -> bool:
|
| 123 |
+
return len(piece) < 2 or piece[-1] != "," or not piece[-2].isdigit()
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class Converter:
|
| 127 |
+
def __init__(self, original_tokenizer):
|
| 128 |
+
self.original_tokenizer = original_tokenizer
|
| 129 |
+
|
| 130 |
+
def converted(self) -> Tokenizer:
|
| 131 |
+
raise NotImplementedError()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class BertConverter(Converter):
|
| 135 |
+
def converted(self) -> Tokenizer:
|
| 136 |
+
vocab = self.original_tokenizer.vocab
|
| 137 |
+
tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token)))
|
| 138 |
+
|
| 139 |
+
tokenize_chinese_chars = False
|
| 140 |
+
strip_accents = False
|
| 141 |
+
do_lower_case = False
|
| 142 |
+
if hasattr(self.original_tokenizer, "basic_tokenizer"):
|
| 143 |
+
tokenize_chinese_chars = self.original_tokenizer.basic_tokenizer.tokenize_chinese_chars
|
| 144 |
+
strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents
|
| 145 |
+
do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case
|
| 146 |
+
|
| 147 |
+
tokenizer.normalizer = normalizers.BertNormalizer(
|
| 148 |
+
clean_text=True,
|
| 149 |
+
handle_chinese_chars=tokenize_chinese_chars,
|
| 150 |
+
strip_accents=strip_accents,
|
| 151 |
+
lowercase=do_lower_case,
|
| 152 |
+
)
|
| 153 |
+
tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
|
| 154 |
+
|
| 155 |
+
cls = str(self.original_tokenizer.cls_token)
|
| 156 |
+
sep = str(self.original_tokenizer.sep_token)
|
| 157 |
+
cls_token_id = self.original_tokenizer.cls_token_id
|
| 158 |
+
sep_token_id = self.original_tokenizer.sep_token_id
|
| 159 |
+
|
| 160 |
+
tokenizer.post_processor = processors.TemplateProcessing(
|
| 161 |
+
single=f"{cls}:0 $A:0 {sep}:0",
|
| 162 |
+
pair=f"{cls}:0 $A:0 {sep}:0 $B:1 {sep}:1",
|
| 163 |
+
special_tokens=[
|
| 164 |
+
(cls, cls_token_id),
|
| 165 |
+
(sep, sep_token_id),
|
| 166 |
+
],
|
| 167 |
+
)
|
| 168 |
+
tokenizer.decoder = decoders.WordPiece(prefix="##")
|
| 169 |
+
|
| 170 |
+
return tokenizer
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class SplinterConverter(Converter):
|
| 174 |
+
def converted(self) -> Tokenizer:
|
| 175 |
+
vocab = self.original_tokenizer.vocab
|
| 176 |
+
tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token)))
|
| 177 |
+
|
| 178 |
+
tokenize_chinese_chars = False
|
| 179 |
+
strip_accents = False
|
| 180 |
+
do_lower_case = False
|
| 181 |
+
if hasattr(self.original_tokenizer, "basic_tokenizer"):
|
| 182 |
+
tokenize_chinese_chars = self.original_tokenizer.basic_tokenizer.tokenize_chinese_chars
|
| 183 |
+
strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents
|
| 184 |
+
do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case
|
| 185 |
+
|
| 186 |
+
tokenizer.normalizer = normalizers.BertNormalizer(
|
| 187 |
+
clean_text=True,
|
| 188 |
+
handle_chinese_chars=tokenize_chinese_chars,
|
| 189 |
+
strip_accents=strip_accents,
|
| 190 |
+
lowercase=do_lower_case,
|
| 191 |
+
)
|
| 192 |
+
tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
|
| 193 |
+
|
| 194 |
+
cls = str(self.original_tokenizer.cls_token)
|
| 195 |
+
sep = str(self.original_tokenizer.sep_token)
|
| 196 |
+
question = str(self.original_tokenizer.question_token)
|
| 197 |
+
dot = "."
|
| 198 |
+
cls_token_id = self.original_tokenizer.cls_token_id
|
| 199 |
+
sep_token_id = self.original_tokenizer.sep_token_id
|
| 200 |
+
question_token_id = self.original_tokenizer.question_token_id
|
| 201 |
+
dot_token_id = self.original_tokenizer.convert_tokens_to_ids(".")
|
| 202 |
+
|
| 203 |
+
if self.original_tokenizer.padding_side == "right":
|
| 204 |
+
pair = f"{cls}:0 $A:0 {question} {dot} {sep}:0 $B:1 {sep}:1"
|
| 205 |
+
else:
|
| 206 |
+
pair = f"{cls}:0 $A:0 {sep}:0 $B:1 {question} {dot} {sep}:1"
|
| 207 |
+
|
| 208 |
+
tokenizer.post_processor = processors.TemplateProcessing(
|
| 209 |
+
single=f"{cls}:0 $A:0 {sep}:0",
|
| 210 |
+
pair=pair,
|
| 211 |
+
special_tokens=[
|
| 212 |
+
(cls, cls_token_id),
|
| 213 |
+
(sep, sep_token_id),
|
| 214 |
+
(question, question_token_id),
|
| 215 |
+
(dot, dot_token_id),
|
| 216 |
+
],
|
| 217 |
+
)
|
| 218 |
+
tokenizer.decoder = decoders.WordPiece(prefix="##")
|
| 219 |
+
|
| 220 |
+
return tokenizer
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class FunnelConverter(Converter):
|
| 224 |
+
def converted(self) -> Tokenizer:
|
| 225 |
+
vocab = self.original_tokenizer.vocab
|
| 226 |
+
tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token)))
|
| 227 |
+
|
| 228 |
+
tokenize_chinese_chars = False
|
| 229 |
+
strip_accents = False
|
| 230 |
+
do_lower_case = False
|
| 231 |
+
if hasattr(self.original_tokenizer, "basic_tokenizer"):
|
| 232 |
+
tokenize_chinese_chars = self.original_tokenizer.basic_tokenizer.tokenize_chinese_chars
|
| 233 |
+
strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents
|
| 234 |
+
do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case
|
| 235 |
+
|
| 236 |
+
tokenizer.normalizer = normalizers.BertNormalizer(
|
| 237 |
+
clean_text=True,
|
| 238 |
+
handle_chinese_chars=tokenize_chinese_chars,
|
| 239 |
+
strip_accents=strip_accents,
|
| 240 |
+
lowercase=do_lower_case,
|
| 241 |
+
)
|
| 242 |
+
tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
|
| 243 |
+
|
| 244 |
+
cls = str(self.original_tokenizer.cls_token)
|
| 245 |
+
sep = str(self.original_tokenizer.sep_token)
|
| 246 |
+
cls_token_id = self.original_tokenizer.cls_token_id
|
| 247 |
+
sep_token_id = self.original_tokenizer.sep_token_id
|
| 248 |
+
|
| 249 |
+
tokenizer.post_processor = processors.TemplateProcessing(
|
| 250 |
+
single=f"{cls}:2 $A:0 {sep}:0", # token_type_id is 2 for Funnel transformer
|
| 251 |
+
pair=f"{cls}:2 $A:0 {sep}:0 $B:1 {sep}:1",
|
| 252 |
+
special_tokens=[
|
| 253 |
+
(cls, cls_token_id),
|
| 254 |
+
(sep, sep_token_id),
|
| 255 |
+
],
|
| 256 |
+
)
|
| 257 |
+
tokenizer.decoder = decoders.WordPiece(prefix="##")
|
| 258 |
+
|
| 259 |
+
return tokenizer
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class MPNetConverter(Converter):
|
| 263 |
+
def converted(self) -> Tokenizer:
|
| 264 |
+
vocab = self.original_tokenizer.vocab
|
| 265 |
+
tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token)))
|
| 266 |
+
|
| 267 |
+
tokenize_chinese_chars = False
|
| 268 |
+
strip_accents = False
|
| 269 |
+
do_lower_case = False
|
| 270 |
+
if hasattr(self.original_tokenizer, "basic_tokenizer"):
|
| 271 |
+
tokenize_chinese_chars = self.original_tokenizer.basic_tokenizer.tokenize_chinese_chars
|
| 272 |
+
strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents
|
| 273 |
+
do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case
|
| 274 |
+
|
| 275 |
+
tokenizer.normalizer = normalizers.BertNormalizer(
|
| 276 |
+
clean_text=True,
|
| 277 |
+
handle_chinese_chars=tokenize_chinese_chars,
|
| 278 |
+
strip_accents=strip_accents,
|
| 279 |
+
lowercase=do_lower_case,
|
| 280 |
+
)
|
| 281 |
+
tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
|
| 282 |
+
|
| 283 |
+
cls = str(self.original_tokenizer.cls_token)
|
| 284 |
+
sep = str(self.original_tokenizer.sep_token)
|
| 285 |
+
cls_token_id = self.original_tokenizer.cls_token_id
|
| 286 |
+
sep_token_id = self.original_tokenizer.sep_token_id
|
| 287 |
+
|
| 288 |
+
tokenizer.post_processor = processors.TemplateProcessing(
|
| 289 |
+
single=f"{cls}:0 $A:0 {sep}:0",
|
| 290 |
+
pair=f"{cls}:0 $A:0 {sep}:0 {sep}:0 $B:1 {sep}:1", # MPNet uses two [SEP] tokens
|
| 291 |
+
special_tokens=[
|
| 292 |
+
(cls, cls_token_id),
|
| 293 |
+
(sep, sep_token_id),
|
| 294 |
+
],
|
| 295 |
+
)
|
| 296 |
+
tokenizer.decoder = decoders.WordPiece(prefix="##")
|
| 297 |
+
|
| 298 |
+
return tokenizer
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class OpenAIGPTConverter(Converter):
|
| 302 |
+
def converted(self) -> Tokenizer:
|
| 303 |
+
vocab = self.original_tokenizer.encoder
|
| 304 |
+
merges = list(self.original_tokenizer.bpe_ranks.keys())
|
| 305 |
+
unk_token = self.original_tokenizer.unk_token
|
| 306 |
+
|
| 307 |
+
tokenizer = Tokenizer(
|
| 308 |
+
BPE(
|
| 309 |
+
vocab=vocab,
|
| 310 |
+
merges=merges,
|
| 311 |
+
dropout=None,
|
| 312 |
+
unk_token=str(unk_token),
|
| 313 |
+
end_of_word_suffix="</w>",
|
| 314 |
+
fuse_unk=False,
|
| 315 |
+
)
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
if tokenizer.token_to_id(str(unk_token)) is not None:
|
| 319 |
+
tokenizer.add_special_tokens([str(unk_token)])
|
| 320 |
+
|
| 321 |
+
tokenizer.normalizer = normalizers.BertNormalizer(lowercase=True)
|
| 322 |
+
tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
|
| 323 |
+
tokenizer.decoder = decoders.BPEDecoder(suffix="</w>")
|
| 324 |
+
|
| 325 |
+
return tokenizer
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class GPT2Converter(Converter):
|
| 329 |
+
def converted(self, vocab: dict[str, int] = None, merges: list[tuple[str, str]] = None) -> Tokenizer:
|
| 330 |
+
if not vocab:
|
| 331 |
+
vocab = self.original_tokenizer.encoder
|
| 332 |
+
if not merges:
|
| 333 |
+
merges = list(self.original_tokenizer.bpe_ranks)
|
| 334 |
+
|
| 335 |
+
tokenizer = Tokenizer(
|
| 336 |
+
BPE(
|
| 337 |
+
vocab=vocab,
|
| 338 |
+
merges=merges,
|
| 339 |
+
dropout=None,
|
| 340 |
+
continuing_subword_prefix="",
|
| 341 |
+
end_of_word_suffix="",
|
| 342 |
+
fuse_unk=False,
|
| 343 |
+
)
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
add_prefix_space = getattr(self.original_tokenizer, "add_prefix_space", False)
|
| 347 |
+
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
|
| 348 |
+
tokenizer.decoder = decoders.ByteLevel()
|
| 349 |
+
if getattr(self.original_tokenizer, "add_bos_token", False):
|
| 350 |
+
bos = self.original_tokenizer.bos_token
|
| 351 |
+
bos_token_id = self.original_tokenizer.bos_token_id
|
| 352 |
+
tokenizer.post_processor = processors.TemplateProcessing(
|
| 353 |
+
single=f"{bos}:0 $A:0",
|
| 354 |
+
pair=f"{bos}:0 $A:0 $B:1",
|
| 355 |
+
special_tokens=[
|
| 356 |
+
(bos, bos_token_id),
|
| 357 |
+
],
|
| 358 |
+
)
|
| 359 |
+
else:
|
| 360 |
+
# XXX trim_offsets=False actually means this post_processor doesn't
|
| 361 |
+
# really do anything.
|
| 362 |
+
tokenizer.post_processor = processors.ByteLevel(trim_offsets=False)
|
| 363 |
+
return tokenizer
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
class HerbertConverter(Converter):
|
| 367 |
+
def converted(self) -> Tokenizer:
|
| 368 |
+
tokenizer_info_str = "#version:"
|
| 369 |
+
token_suffix = "</w>"
|
| 370 |
+
|
| 371 |
+
vocab = self.original_tokenizer.encoder
|
| 372 |
+
merges = list(self.original_tokenizer.bpe_ranks.keys())
|
| 373 |
+
if tokenizer_info_str in merges[0][0]:
|
| 374 |
+
merges = merges[1:]
|
| 375 |
+
|
| 376 |
+
tokenizer = Tokenizer(
|
| 377 |
+
BPE(
|
| 378 |
+
vocab,
|
| 379 |
+
merges,
|
| 380 |
+
dropout=None,
|
| 381 |
+
unk_token=self.original_tokenizer.unk_token,
|
| 382 |
+
end_of_word_suffix=token_suffix,
|
| 383 |
+
)
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
tokenizer.normalizer = normalizers.BertNormalizer(lowercase=False, strip_accents=False)
|
| 387 |
+
tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
|
| 388 |
+
tokenizer.decoder = decoders.BPEDecoder(suffix=token_suffix)
|
| 389 |
+
tokenizer.post_processor = processors.BertProcessing(
|
| 390 |
+
sep=(self.original_tokenizer.sep_token, self.original_tokenizer.sep_token_id),
|
| 391 |
+
cls=(self.original_tokenizer.cls_token, self.original_tokenizer.cls_token_id),
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
return tokenizer
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
class Qwen2Converter(Converter):
|
| 398 |
+
def converted(self, vocab: dict[str, int] = None, merges: list[tuple[str, str]] = None) -> Tokenizer:
|
| 399 |
+
if not vocab:
|
| 400 |
+
vocab = self.original_tokenizer.encoder
|
| 401 |
+
if not merges:
|
| 402 |
+
merges = list(self.original_tokenizer.bpe_ranks.keys())
|
| 403 |
+
|
| 404 |
+
tokenizer = Tokenizer(
|
| 405 |
+
BPE(
|
| 406 |
+
vocab=vocab,
|
| 407 |
+
merges=merges,
|
| 408 |
+
dropout=None,
|
| 409 |
+
unk_token=None,
|
| 410 |
+
continuing_subword_prefix="",
|
| 411 |
+
end_of_word_suffix="",
|
| 412 |
+
fuse_unk=False,
|
| 413 |
+
byte_fallback=False,
|
| 414 |
+
)
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
tokenizer.normalizer = normalizers.NFC()
|
| 418 |
+
|
| 419 |
+
tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
|
| 420 |
+
[
|
| 421 |
+
pre_tokenizers.Split(
|
| 422 |
+
Regex(
|
| 423 |
+
r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
|
| 424 |
+
),
|
| 425 |
+
behavior="isolated",
|
| 426 |
+
invert=False,
|
| 427 |
+
),
|
| 428 |
+
pre_tokenizers.ByteLevel(
|
| 429 |
+
add_prefix_space=getattr(self.original_tokenizer, "add_prefix_space", False),
|
| 430 |
+
use_regex=False,
|
| 431 |
+
),
|
| 432 |
+
]
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
tokenizer.decoder = decoders.ByteLevel()
|
| 436 |
+
tokenizer.post_processor = processors.ByteLevel(trim_offsets=False)
|
| 437 |
+
|
| 438 |
+
return tokenizer
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
class RobertaConverter(Converter):
|
| 442 |
+
def converted(self) -> Tokenizer:
|
| 443 |
+
ot = self.original_tokenizer
|
| 444 |
+
vocab = ot.encoder
|
| 445 |
+
merges = list(ot.bpe_ranks.keys())
|
| 446 |
+
|
| 447 |
+
tokenizer = Tokenizer(
|
| 448 |
+
BPE(
|
| 449 |
+
vocab=vocab,
|
| 450 |
+
merges=merges,
|
| 451 |
+
dropout=None,
|
| 452 |
+
continuing_subword_prefix="",
|
| 453 |
+
end_of_word_suffix="",
|
| 454 |
+
fuse_unk=False,
|
| 455 |
+
)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=ot.add_prefix_space)
|
| 459 |
+
tokenizer.decoder = decoders.ByteLevel()
|
| 460 |
+
tokenizer.post_processor = processors.RobertaProcessing(
|
| 461 |
+
sep=(ot.sep_token, ot.sep_token_id),
|
| 462 |
+
cls=(ot.cls_token, ot.cls_token_id),
|
| 463 |
+
add_prefix_space=ot.add_prefix_space,
|
| 464 |
+
trim_offsets=True, # True by default on Roberta (historical)
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
return tokenizer
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
class RoFormerConverter(Converter):
|
| 471 |
+
def converted(self) -> Tokenizer:
|
| 472 |
+
from .models.roformer.tokenization_utils import JiebaPreTokenizer
|
| 473 |
+
|
| 474 |
+
vocab = self.original_tokenizer.vocab
|
| 475 |
+
tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token)))
|
| 476 |
+
|
| 477 |
+
strip_accents = False
|
| 478 |
+
do_lower_case = False
|
| 479 |
+
if hasattr(self.original_tokenizer, "basic_tokenizer"):
|
| 480 |
+
strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents
|
| 481 |
+
do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case
|
| 482 |
+
|
| 483 |
+
tokenizer.normalizer = normalizers.BertNormalizer(
|
| 484 |
+
clean_text=True,
|
| 485 |
+
handle_chinese_chars=False,
|
| 486 |
+
strip_accents=strip_accents,
|
| 487 |
+
lowercase=do_lower_case,
|
| 488 |
+
)
|
| 489 |
+
tokenizer.pre_tokenizer = pre_tokenizers.PreTokenizer.custom(JiebaPreTokenizer(vocab))
|
| 490 |
+
|
| 491 |
+
cls = str(self.original_tokenizer.cls_token)
|
| 492 |
+
sep = str(self.original_tokenizer.sep_token)
|
| 493 |
+
cls_token_id = self.original_tokenizer.cls_token_id
|
| 494 |
+
sep_token_id = self.original_tokenizer.sep_token_id
|
| 495 |
+
|
| 496 |
+
tokenizer.post_processor = processors.TemplateProcessing(
|
| 497 |
+
single=f"{cls}:0 $A:0 {sep}:0",
|
| 498 |
+
pair=f"{cls}:0 $A:0 {sep}:0 $B:1 {sep}:1",
|
| 499 |
+
special_tokens=[
|
| 500 |
+
(cls, cls_token_id),
|
| 501 |
+
(sep, sep_token_id),
|
| 502 |
+
],
|
| 503 |
+
)
|
| 504 |
+
tokenizer.decoder = decoders.WordPiece(prefix="##")
|
| 505 |
+
|
| 506 |
+
return tokenizer
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
class DebertaConverter(Converter):
|
| 510 |
+
def converted(self) -> Tokenizer:
|
| 511 |
+
ot = self.original_tokenizer
|
| 512 |
+
vocab = ot.encoder
|
| 513 |
+
merges = list(ot.bpe_ranks.keys())
|
| 514 |
+
|
| 515 |
+
tokenizer = Tokenizer(
|
| 516 |
+
BPE(
|
| 517 |
+
vocab=vocab,
|
| 518 |
+
merges=merges,
|
| 519 |
+
dropout=None,
|
| 520 |
+
continuing_subword_prefix="",
|
| 521 |
+
end_of_word_suffix="",
|
| 522 |
+
fuse_unk=False,
|
| 523 |
+
)
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=ot.add_prefix_space)
|
| 527 |
+
tokenizer.decoder = decoders.ByteLevel()
|
| 528 |
+
tokenizer.post_processor = processors.TemplateProcessing(
|
| 529 |
+
single="[CLS]:0 $A:0 [SEP]:0",
|
| 530 |
+
pair="[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1",
|
| 531 |
+
special_tokens=[
|
| 532 |
+
("[CLS]", self.original_tokenizer.convert_tokens_to_ids("[CLS]")),
|
| 533 |
+
("[SEP]", self.original_tokenizer.convert_tokens_to_ids("[SEP]")),
|
| 534 |
+
],
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
return tokenizer
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
class SpmConverter(Converter):
|
| 541 |
+
handle_byte_fallback = False
|
| 542 |
+
SpmExtractor = SentencePieceExtractor
|
| 543 |
+
special_tokens = {}
|
| 544 |
+
|
| 545 |
+
def __init__(self, *args):
|
| 546 |
+
requires_backends(self, "protobuf")
|
| 547 |
+
|
| 548 |
+
super().__init__(*args)
|
| 549 |
+
|
| 550 |
+
# from .utils import sentencepiece_model_pb2 as model_pb2
|
| 551 |
+
model_pb2 = import_protobuf()
|
| 552 |
+
|
| 553 |
+
m = model_pb2.ModelProto()
|
| 554 |
+
with open(self.original_tokenizer.vocab_file, "rb") as f:
|
| 555 |
+
m.ParseFromString(f.read())
|
| 556 |
+
self.proto = m
|
| 557 |
+
|
| 558 |
+
if self.proto.trainer_spec.byte_fallback and not self.handle_byte_fallback:
|
| 559 |
+
warnings.warn(
|
| 560 |
+
"The sentencepiece tokenizer that you are converting to a fast tokenizer uses the byte fallback option"
|
| 561 |
+
" which is not implemented in the fast tokenizers. In practice this means that the fast version of the"
|
| 562 |
+
" tokenizer can produce unknown tokens whereas the sentencepiece version would have converted these "
|
| 563 |
+
"unknown tokens into a sequence of byte tokens matching the original piece of text."
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
def vocab(self, proto):
|
| 567 |
+
return [(piece.piece, piece.score) for piece in proto.pieces]
|
| 568 |
+
|
| 569 |
+
def unk_id(self, proto):
|
| 570 |
+
return proto.trainer_spec.unk_id
|
| 571 |
+
|
| 572 |
+
def tokenizer(self, proto):
|
| 573 |
+
model_type = proto.trainer_spec.model_type
|
| 574 |
+
vocab_scores = self.vocab(proto)
|
| 575 |
+
|
| 576 |
+
if model_type == 1:
|
| 577 |
+
tokenizer = Tokenizer(
|
| 578 |
+
Unigram(
|
| 579 |
+
vocab_scores,
|
| 580 |
+
unk_id=self.unk_id(proto),
|
| 581 |
+
byte_fallback=self.handle_byte_fallback,
|
| 582 |
+
)
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
elif model_type == 2:
|
| 586 |
+
_, merges = self.SpmExtractor(self.original_tokenizer.vocab_file).extract(vocab_scores)
|
| 587 |
+
bpe_vocab = {word: i for i, (word, score) in enumerate(vocab_scores)}
|
| 588 |
+
tokenizer = Tokenizer(
|
| 589 |
+
BPE(
|
| 590 |
+
bpe_vocab,
|
| 591 |
+
merges,
|
| 592 |
+
unk_token=proto.trainer_spec.unk_piece,
|
| 593 |
+
fuse_unk=True,
|
| 594 |
+
byte_fallback=self.handle_byte_fallback,
|
| 595 |
+
dropout=None,
|
| 596 |
+
)
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
else:
|
| 600 |
+
raise Exception(
|
| 601 |
+
"You're trying to run a `Unigram` model but you're file was trained with a different algorithm"
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
# control tokens are special
|
| 605 |
+
# user defined symbols are not
|
| 606 |
+
# both user and control tokens are AddedTokens
|
| 607 |
+
# Add user defined symbols (type == 4) from sentencepiece (https://github.com/google/sentencepiece/blob/6225e08edb2577757163b3f5dbba4c0b670ef445/src/sentencepiece_model.proto#L299C29-L299C33)
|
| 608 |
+
spm_added_tokens = [
|
| 609 |
+
(id, p.piece, p.type == 3 or p.piece in self.special_tokens)
|
| 610 |
+
for id, p in enumerate(proto.pieces)
|
| 611 |
+
if p.type in [3, 4]
|
| 612 |
+
]
|
| 613 |
+
tokenizer.add_tokens(
|
| 614 |
+
[
|
| 615 |
+
AddedToken(token, normalized=False, special=special)
|
| 616 |
+
for id, token, special in sorted(spm_added_tokens, key=lambda x: x[0])
|
| 617 |
+
]
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
return tokenizer
|
| 621 |
+
|
| 622 |
+
def normalizer(self, proto):
|
| 623 |
+
precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap
|
| 624 |
+
_normalizers = [
|
| 625 |
+
normalizers.Strip(left=False, right=True), # stripping is important
|
| 626 |
+
normalizers.Replace(Regex(" {2,}"), "▁"),
|
| 627 |
+
]
|
| 628 |
+
if not precompiled_charsmap:
|
| 629 |
+
return normalizers.Sequence(_normalizers)
|
| 630 |
+
else:
|
| 631 |
+
return normalizers.Sequence([normalizers.Precompiled(precompiled_charsmap)] + _normalizers)
|
| 632 |
+
|
| 633 |
+
def pre_tokenizer(self, replacement, add_prefix_space):
|
| 634 |
+
prepend_scheme = _get_prepend_scheme(add_prefix_space, self.original_tokenizer)
|
| 635 |
+
return pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme)
|
| 636 |
+
|
| 637 |
+
def post_processor(self):
|
| 638 |
+
return None
|
| 639 |
+
|
| 640 |
+
def decoder(self, replacement, add_prefix_space):
|
| 641 |
+
prepend_scheme = _get_prepend_scheme(add_prefix_space, self.original_tokenizer)
|
| 642 |
+
return decoders.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme)
|
| 643 |
+
|
| 644 |
+
def converted(self) -> Tokenizer:
|
| 645 |
+
tokenizer = self.tokenizer(self.proto)
|
| 646 |
+
|
| 647 |
+
# Tokenizer assemble
|
| 648 |
+
normalizer = self.normalizer(self.proto)
|
| 649 |
+
if normalizer is not None:
|
| 650 |
+
tokenizer.normalizer = normalizer
|
| 651 |
+
|
| 652 |
+
replacement = "▁"
|
| 653 |
+
add_prefix_space = True
|
| 654 |
+
if hasattr(self.original_tokenizer, "add_prefix_space"):
|
| 655 |
+
add_prefix_space = self.original_tokenizer.add_prefix_space
|
| 656 |
+
|
| 657 |
+
pre_tokenizer = self.pre_tokenizer(replacement, add_prefix_space)
|
| 658 |
+
if pre_tokenizer is not None:
|
| 659 |
+
tokenizer.pre_tokenizer = pre_tokenizer
|
| 660 |
+
|
| 661 |
+
tokenizer.decoder = self.decoder(replacement, add_prefix_space)
|
| 662 |
+
post_processor = self.post_processor()
|
| 663 |
+
if post_processor:
|
| 664 |
+
tokenizer.post_processor = post_processor
|
| 665 |
+
|
| 666 |
+
return tokenizer
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
class AlbertConverter(SpmConverter):
|
| 670 |
+
def vocab(self, proto):
|
| 671 |
+
return [
|
| 672 |
+
(piece.piece, piece.score) if check_number_comma(piece.piece) else (piece.piece, piece.score - 100)
|
| 673 |
+
for piece in proto.pieces
|
| 674 |
+
]
|
| 675 |
+
|
| 676 |
+
def normalizer(self, proto):
|
| 677 |
+
list_normalizers = [
|
| 678 |
+
normalizers.Replace("``", '"'),
|
| 679 |
+
normalizers.Replace("''", '"'),
|
| 680 |
+
]
|
| 681 |
+
if not self.original_tokenizer.keep_accents:
|
| 682 |
+
list_normalizers.append(normalizers.NFKD())
|
| 683 |
+
list_normalizers.append(normalizers.StripAccents())
|
| 684 |
+
if self.original_tokenizer.do_lower_case:
|
| 685 |
+
list_normalizers.append(normalizers.Lowercase())
|
| 686 |
+
|
| 687 |
+
precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap
|
| 688 |
+
|
| 689 |
+
if precompiled_charsmap:
|
| 690 |
+
list_normalizers.append(normalizers.Precompiled(precompiled_charsmap))
|
| 691 |
+
|
| 692 |
+
list_normalizers.append(normalizers.Replace(Regex(" {2,}"), " "))
|
| 693 |
+
return normalizers.Sequence(list_normalizers)
|
| 694 |
+
|
| 695 |
+
def post_processor(self):
|
| 696 |
+
return processors.TemplateProcessing(
|
| 697 |
+
single="[CLS]:0 $A:0 [SEP]:0",
|
| 698 |
+
pair="[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1",
|
| 699 |
+
special_tokens=[
|
| 700 |
+
("[CLS]", self.original_tokenizer.convert_tokens_to_ids("[CLS]")),
|
| 701 |
+
("[SEP]", self.original_tokenizer.convert_tokens_to_ids("[SEP]")),
|
| 702 |
+
],
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
class BarthezConverter(SpmConverter):
|
| 707 |
+
def unk_id(self, proto):
|
| 708 |
+
unk_id = 3
|
| 709 |
+
return unk_id
|
| 710 |
+
|
| 711 |
+
def post_processor(self):
|
| 712 |
+
return processors.TemplateProcessing(
|
| 713 |
+
single="<s> $A </s>",
|
| 714 |
+
pair="<s> $A </s> </s> $B </s>",
|
| 715 |
+
special_tokens=[
|
| 716 |
+
("<s>", self.original_tokenizer.convert_tokens_to_ids("<s>")),
|
| 717 |
+
("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")),
|
| 718 |
+
],
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
class CamembertConverter(SpmConverter):
|
| 723 |
+
def vocab(self, proto):
|
| 724 |
+
vocab = [
|
| 725 |
+
("<s>NOTUSED", 0.0),
|
| 726 |
+
("<pad>", 0.0),
|
| 727 |
+
("</s>NOTUSED", 0.0),
|
| 728 |
+
("<unk>", 0.0),
|
| 729 |
+
("<unk>NOTUSED", -100),
|
| 730 |
+
]
|
| 731 |
+
# We down-grade the original SentencePiece by -100 to avoid using it and use our added token instead
|
| 732 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[1:]]
|
| 733 |
+
vocab += [("<mask>", 0.0)]
|
| 734 |
+
return vocab
|
| 735 |
+
|
| 736 |
+
def unk_id(self, proto):
|
| 737 |
+
# See vocab unk position
|
| 738 |
+
return 3
|
| 739 |
+
|
| 740 |
+
def post_processor(self):
|
| 741 |
+
return processors.TemplateProcessing(
|
| 742 |
+
single="<s> $A </s>",
|
| 743 |
+
pair="<s> $A </s> </s> $B </s>",
|
| 744 |
+
special_tokens=[
|
| 745 |
+
("<s>", self.original_tokenizer.convert_tokens_to_ids("<s>")),
|
| 746 |
+
("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")),
|
| 747 |
+
],
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
class DebertaV2Converter(SpmConverter):
|
| 752 |
+
def pre_tokenizer(self, replacement, add_prefix_space):
|
| 753 |
+
list_pretokenizers = []
|
| 754 |
+
if self.original_tokenizer.split_by_punct:
|
| 755 |
+
list_pretokenizers.append(pre_tokenizers.Punctuation(behavior="isolated"))
|
| 756 |
+
prepend_scheme = _get_prepend_scheme(add_prefix_space, self.original_tokenizer)
|
| 757 |
+
list_pretokenizers.append(pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme))
|
| 758 |
+
return pre_tokenizers.Sequence(list_pretokenizers)
|
| 759 |
+
|
| 760 |
+
def normalizer(self, proto):
|
| 761 |
+
list_normalizers = []
|
| 762 |
+
if self.original_tokenizer.do_lower_case:
|
| 763 |
+
list_normalizers.append(normalizers.Lowercase())
|
| 764 |
+
list_normalizers.append(normalizers.Strip())
|
| 765 |
+
|
| 766 |
+
precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap
|
| 767 |
+
if precompiled_charsmap:
|
| 768 |
+
list_normalizers.append(normalizers.Precompiled(precompiled_charsmap))
|
| 769 |
+
list_normalizers.append(normalizers.Replace(Regex(" {2,}"), " "))
|
| 770 |
+
|
| 771 |
+
return normalizers.Sequence(list_normalizers)
|
| 772 |
+
|
| 773 |
+
def post_processor(self):
|
| 774 |
+
return processors.TemplateProcessing(
|
| 775 |
+
single="[CLS]:0 $A:0 [SEP]:0",
|
| 776 |
+
pair="[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1",
|
| 777 |
+
special_tokens=[
|
| 778 |
+
("[CLS]", self.original_tokenizer.convert_tokens_to_ids("[CLS]")),
|
| 779 |
+
("[SEP]", self.original_tokenizer.convert_tokens_to_ids("[SEP]")),
|
| 780 |
+
],
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
class MBartConverter(SpmConverter):
|
| 785 |
+
def vocab(self, proto):
|
| 786 |
+
vocab = [
|
| 787 |
+
("<s>", 0.0),
|
| 788 |
+
("<pad>", 0.0),
|
| 789 |
+
("</s>", 0.0),
|
| 790 |
+
("<unk>", 0.0),
|
| 791 |
+
]
|
| 792 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
|
| 793 |
+
vocab += [
|
| 794 |
+
("ar_AR", 0.0),
|
| 795 |
+
("cs_CZ", 0.0),
|
| 796 |
+
("de_DE", 0.0),
|
| 797 |
+
("en_XX", 0.0),
|
| 798 |
+
("es_XX", 0.0),
|
| 799 |
+
("et_EE", 0.0),
|
| 800 |
+
("fi_FI", 0.0),
|
| 801 |
+
("fr_XX", 0.0),
|
| 802 |
+
("gu_IN", 0.0),
|
| 803 |
+
("hi_IN", 0.0),
|
| 804 |
+
("it_IT", 0.0),
|
| 805 |
+
("ja_XX", 0.0),
|
| 806 |
+
("kk_KZ", 0.0),
|
| 807 |
+
("ko_KR", 0.0),
|
| 808 |
+
("lt_LT", 0.0),
|
| 809 |
+
("lv_LV", 0.0),
|
| 810 |
+
("my_MM", 0.0),
|
| 811 |
+
("ne_NP", 0.0),
|
| 812 |
+
("nl_XX", 0.0),
|
| 813 |
+
("ro_RO", 0.0),
|
| 814 |
+
("ru_RU", 0.0),
|
| 815 |
+
("si_LK", 0.0),
|
| 816 |
+
("tr_TR", 0.0),
|
| 817 |
+
("vi_VN", 0.0),
|
| 818 |
+
("zh_CN", 0.0),
|
| 819 |
+
]
|
| 820 |
+
vocab += [("<mask>", 0.0)]
|
| 821 |
+
return vocab
|
| 822 |
+
|
| 823 |
+
def unk_id(self, proto):
|
| 824 |
+
return 3
|
| 825 |
+
|
| 826 |
+
def post_processor(self):
|
| 827 |
+
return processors.TemplateProcessing(
|
| 828 |
+
single="$A </s> en_XX",
|
| 829 |
+
pair="$A $B </s> en_XX",
|
| 830 |
+
special_tokens=[
|
| 831 |
+
("en_XX", self.original_tokenizer.convert_tokens_to_ids("en_XX")),
|
| 832 |
+
("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")),
|
| 833 |
+
],
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
|
| 837 |
+
class MBart50Converter(SpmConverter):
|
| 838 |
+
def vocab(self, proto):
|
| 839 |
+
vocab = [
|
| 840 |
+
("<s>", 0.0),
|
| 841 |
+
("<pad>", 0.0),
|
| 842 |
+
("</s>", 0.0),
|
| 843 |
+
("<unk>", 0.0),
|
| 844 |
+
]
|
| 845 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
|
| 846 |
+
vocab += [("ar_AR", 0.0), ("cs_CZ", 0.0), ("de_DE", 0.0), ("en_XX", 0.0), ("es_XX", 0.0), ("et_EE", 0.0), ("fi_FI", 0.0), ("fr_XX", 0.0), ("gu_IN", 0.0), ("hi_IN", 0.0), ("it_IT", 0.0), ("ja_XX", 0.0), ("kk_KZ", 0.0), ("ko_KR", 0.0), ("lt_LT", 0.0), ("lv_LV", 0.0), ("my_MM", 0.0), ("ne_NP", 0.0), ("nl_XX", 0.0), ("ro_RO", 0.0), ("ru_RU", 0.0), ("si_LK", 0.0), ("tr_TR", 0.0), ("vi_VN", 0.0), ("zh_CN", 0.0), ("af_ZA", 0.0), ("az_AZ", 0.0), ("bn_IN", 0.0), ("fa_IR", 0.0), ("he_IL", 0.0), ("hr_HR", 0.0), ("id_ID", 0.0), ("ka_GE", 0.0), ("km_KH", 0.0), ("mk_MK", 0.0), ("ml_IN", 0.0), ("mn_MN", 0.0), ("mr_IN", 0.0), ("pl_PL", 0.0), ("ps_AF", 0.0), ("pt_XX", 0.0), ("sv_SE", 0.0), ("sw_KE", 0.0), ("ta_IN", 0.0), ("te_IN", 0.0), ("th_TH", 0.0), ("tl_XX", 0.0), ("uk_UA", 0.0), ("ur_PK", 0.0), ("xh_ZA", 0.0), ("gl_ES", 0.0), ("sl_SI", 0.0)] # fmt: skip
|
| 847 |
+
vocab += [("<mask>", 0.0)]
|
| 848 |
+
return vocab
|
| 849 |
+
|
| 850 |
+
def unk_id(self, proto):
|
| 851 |
+
return 3
|
| 852 |
+
|
| 853 |
+
def post_processor(self):
|
| 854 |
+
return processors.TemplateProcessing(
|
| 855 |
+
single="en_XX $A </s>",
|
| 856 |
+
pair="en_XX $A $B </s>",
|
| 857 |
+
special_tokens=[
|
| 858 |
+
("en_XX", self.original_tokenizer.convert_tokens_to_ids("en_XX")),
|
| 859 |
+
("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")),
|
| 860 |
+
],
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
class NllbConverter(SpmConverter):
|
| 865 |
+
def vocab(self, proto):
|
| 866 |
+
vocab = [
|
| 867 |
+
("<s>", 0.0),
|
| 868 |
+
("<pad>", 0.0),
|
| 869 |
+
("</s>", 0.0),
|
| 870 |
+
("<unk>", 0.0),
|
| 871 |
+
]
|
| 872 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
|
| 873 |
+
return vocab
|
| 874 |
+
|
| 875 |
+
def unk_id(self, proto):
|
| 876 |
+
return 3
|
| 877 |
+
|
| 878 |
+
def post_processor(self):
|
| 879 |
+
return processors.TemplateProcessing(
|
| 880 |
+
single="eng_Latn $A </s>",
|
| 881 |
+
pair="eng_Latn $A $B </s>",
|
| 882 |
+
special_tokens=[
|
| 883 |
+
("eng_Latn", self.original_tokenizer.convert_tokens_to_ids("eng_Latn")),
|
| 884 |
+
("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")),
|
| 885 |
+
],
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
class SeamlessM4TConverter(SpmConverter):
|
| 890 |
+
def vocab(self, proto):
|
| 891 |
+
vocab = [
|
| 892 |
+
("<pad>", 0.0),
|
| 893 |
+
("<unk>", 0.0),
|
| 894 |
+
("<s>", 0.0),
|
| 895 |
+
("</s>", 0.0),
|
| 896 |
+
]
|
| 897 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
|
| 898 |
+
return vocab
|
| 899 |
+
|
| 900 |
+
def unk_id(self, proto):
|
| 901 |
+
return self.original_tokenizer.unk_token_id
|
| 902 |
+
|
| 903 |
+
def post_processor(self):
|
| 904 |
+
return processors.TemplateProcessing(
|
| 905 |
+
single="__eng__ $A </s>",
|
| 906 |
+
pair="__eng__ $A $B </s>",
|
| 907 |
+
special_tokens=[
|
| 908 |
+
("__eng__", self.original_tokenizer.convert_tokens_to_ids("__eng__")),
|
| 909 |
+
("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")),
|
| 910 |
+
],
|
| 911 |
+
)
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
class XLMRobertaConverter(SpmConverter):
|
| 915 |
+
def vocab(self, proto):
|
| 916 |
+
vocab = [
|
| 917 |
+
("<s>", 0.0),
|
| 918 |
+
("<pad>", 0.0),
|
| 919 |
+
("</s>", 0.0),
|
| 920 |
+
("<unk>", 0.0),
|
| 921 |
+
]
|
| 922 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
|
| 923 |
+
vocab += [("<mask>", 0.0)]
|
| 924 |
+
return vocab
|
| 925 |
+
|
| 926 |
+
def unk_id(self, proto):
|
| 927 |
+
unk_id = 3
|
| 928 |
+
return unk_id
|
| 929 |
+
|
| 930 |
+
def post_processor(self):
|
| 931 |
+
return processors.TemplateProcessing(
|
| 932 |
+
single="<s> $A </s>",
|
| 933 |
+
pair="<s> $A </s> </s> $B </s>",
|
| 934 |
+
special_tokens=[
|
| 935 |
+
("<s>", self.original_tokenizer.convert_tokens_to_ids("<s>")),
|
| 936 |
+
("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")),
|
| 937 |
+
],
|
| 938 |
+
)
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
class XLNetConverter(SpmConverter):
|
| 942 |
+
def vocab(self, proto):
|
| 943 |
+
return [
|
| 944 |
+
(piece.piece, piece.score) if check_number_comma(piece.piece) else (piece.piece, piece.score - 100)
|
| 945 |
+
for piece in proto.pieces
|
| 946 |
+
]
|
| 947 |
+
|
| 948 |
+
def normalizer(self, proto):
|
| 949 |
+
list_normalizers = [
|
| 950 |
+
normalizers.Replace("``", '"'),
|
| 951 |
+
normalizers.Replace("''", '"'),
|
| 952 |
+
]
|
| 953 |
+
if not self.original_tokenizer.keep_accents:
|
| 954 |
+
list_normalizers.append(normalizers.NFKD())
|
| 955 |
+
list_normalizers.append(normalizers.StripAccents())
|
| 956 |
+
if self.original_tokenizer.do_lower_case:
|
| 957 |
+
list_normalizers.append(normalizers.Lowercase())
|
| 958 |
+
|
| 959 |
+
precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap
|
| 960 |
+
|
| 961 |
+
if precompiled_charsmap:
|
| 962 |
+
list_normalizers.append(normalizers.Precompiled(precompiled_charsmap))
|
| 963 |
+
|
| 964 |
+
list_normalizers.append(normalizers.Replace(Regex(" {2,}"), " "))
|
| 965 |
+
return normalizers.Sequence(list_normalizers)
|
| 966 |
+
|
| 967 |
+
def post_processor(self):
|
| 968 |
+
return processors.TemplateProcessing(
|
| 969 |
+
single="$A:0 <sep>:0 <cls>:2",
|
| 970 |
+
pair="$A:0 <sep>:0 $B:1 <sep>:1 <cls>:2",
|
| 971 |
+
special_tokens=[
|
| 972 |
+
("<sep>", self.original_tokenizer.convert_tokens_to_ids("<sep>")),
|
| 973 |
+
("<cls>", self.original_tokenizer.convert_tokens_to_ids("<cls>")),
|
| 974 |
+
],
|
| 975 |
+
)
|
| 976 |
+
|
| 977 |
+
|
| 978 |
+
class ReformerConverter(SpmConverter):
|
| 979 |
+
pass
|
| 980 |
+
|
| 981 |
+
|
| 982 |
+
class RemBertConverter(SpmConverter):
|
| 983 |
+
# Inspired from AlbertConverter
|
| 984 |
+
def normalizer(self, proto):
|
| 985 |
+
list_normalizers = [
|
| 986 |
+
normalizers.Replace("``", '"'),
|
| 987 |
+
normalizers.Replace("''", '"'),
|
| 988 |
+
normalizers.Replace(Regex(" {2,}"), " "),
|
| 989 |
+
]
|
| 990 |
+
if not self.original_tokenizer.keep_accents:
|
| 991 |
+
list_normalizers.append(normalizers.NFKD())
|
| 992 |
+
list_normalizers.append(normalizers.StripAccents())
|
| 993 |
+
if self.original_tokenizer.do_lower_case:
|
| 994 |
+
list_normalizers.append(normalizers.Lowercase())
|
| 995 |
+
|
| 996 |
+
precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap
|
| 997 |
+
|
| 998 |
+
if precompiled_charsmap:
|
| 999 |
+
list_normalizers.append(normalizers.Precompiled(precompiled_charsmap))
|
| 1000 |
+
|
| 1001 |
+
return normalizers.Sequence(list_normalizers)
|
| 1002 |
+
|
| 1003 |
+
def post_processor(self):
|
| 1004 |
+
return processors.TemplateProcessing(
|
| 1005 |
+
single="[CLS]:0 $A:0 [SEP]:0",
|
| 1006 |
+
pair="[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1",
|
| 1007 |
+
special_tokens=[
|
| 1008 |
+
("[CLS]", self.original_tokenizer.convert_tokens_to_ids("[CLS]")),
|
| 1009 |
+
("[SEP]", self.original_tokenizer.convert_tokens_to_ids("[SEP]")),
|
| 1010 |
+
],
|
| 1011 |
+
)
|
| 1012 |
+
|
| 1013 |
+
|
| 1014 |
+
class BertGenerationConverter(SpmConverter):
|
| 1015 |
+
pass
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
class PegasusConverter(SpmConverter):
|
| 1019 |
+
def vocab(self, proto):
|
| 1020 |
+
vocab = [
|
| 1021 |
+
(self.original_tokenizer.pad_token, 0.0),
|
| 1022 |
+
(self.original_tokenizer.eos_token, 0.0),
|
| 1023 |
+
]
|
| 1024 |
+
|
| 1025 |
+
if self.original_tokenizer.mask_token_sent is not None:
|
| 1026 |
+
vocab += [(self.original_tokenizer.mask_token_sent, 0.0)]
|
| 1027 |
+
|
| 1028 |
+
if (
|
| 1029 |
+
self.original_tokenizer.mask_token is not None
|
| 1030 |
+
and self.original_tokenizer.mask_token_id < self.original_tokenizer.offset
|
| 1031 |
+
):
|
| 1032 |
+
vocab += [(self.original_tokenizer.mask_token, 0.0)]
|
| 1033 |
+
|
| 1034 |
+
vocab += [(f"<unk_{i}>", -100.0) for i in range(2, self.original_tokenizer.offset)]
|
| 1035 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[2:]]
|
| 1036 |
+
return vocab
|
| 1037 |
+
|
| 1038 |
+
def unk_id(self, proto):
|
| 1039 |
+
return proto.trainer_spec.unk_id + self.original_tokenizer.offset
|
| 1040 |
+
|
| 1041 |
+
def pre_tokenizer(self, replacement, add_prefix_space):
|
| 1042 |
+
prepend_scheme = _get_prepend_scheme(add_prefix_space, self.original_tokenizer)
|
| 1043 |
+
return pre_tokenizers.Sequence(
|
| 1044 |
+
[
|
| 1045 |
+
pre_tokenizers.WhitespaceSplit(),
|
| 1046 |
+
pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme),
|
| 1047 |
+
]
|
| 1048 |
+
)
|
| 1049 |
+
|
| 1050 |
+
def post_processor(self):
|
| 1051 |
+
eos = self.original_tokenizer.eos_token
|
| 1052 |
+
special_tokens = [
|
| 1053 |
+
(eos, self.original_tokenizer.eos_token_id),
|
| 1054 |
+
]
|
| 1055 |
+
return processors.TemplateProcessing(single=["$A", eos], pair=["$A", "$B", eos], special_tokens=special_tokens)
|
| 1056 |
+
|
| 1057 |
+
|
| 1058 |
+
class T5Converter(SpmConverter):
|
| 1059 |
+
def vocab(self, proto):
|
| 1060 |
+
num_extra_ids = self.original_tokenizer._extra_ids
|
| 1061 |
+
vocab = [(piece.piece, piece.score) for piece in proto.pieces]
|
| 1062 |
+
vocab += [(f"<extra_id_{i}>", 0.0) for i in range(num_extra_ids - 1, -1, -1)]
|
| 1063 |
+
return vocab
|
| 1064 |
+
|
| 1065 |
+
def post_processor(self):
|
| 1066 |
+
return processors.TemplateProcessing(
|
| 1067 |
+
single=["$A", "</s>"],
|
| 1068 |
+
pair=["$A", "</s>", "$B", "</s>"],
|
| 1069 |
+
special_tokens=[
|
| 1070 |
+
("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")),
|
| 1071 |
+
],
|
| 1072 |
+
)
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
class UdopConverter(SpmConverter):
|
| 1076 |
+
def post_processor(self):
|
| 1077 |
+
return processors.TemplateProcessing(
|
| 1078 |
+
single=["$A", "</s>"],
|
| 1079 |
+
pair=["$A", "</s>", "$B", "</s>"],
|
| 1080 |
+
special_tokens=[
|
| 1081 |
+
("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")),
|
| 1082 |
+
],
|
| 1083 |
+
)
|
| 1084 |
+
|
| 1085 |
+
|
| 1086 |
+
class WhisperConverter(Converter):
|
| 1087 |
+
def converted(self) -> Tokenizer:
|
| 1088 |
+
vocab = self.original_tokenizer.encoder
|
| 1089 |
+
merges = list(self.original_tokenizer.bpe_ranks.keys())
|
| 1090 |
+
|
| 1091 |
+
tokenizer = Tokenizer(
|
| 1092 |
+
BPE(
|
| 1093 |
+
vocab=vocab,
|
| 1094 |
+
merges=merges,
|
| 1095 |
+
dropout=None,
|
| 1096 |
+
continuing_subword_prefix="",
|
| 1097 |
+
end_of_word_suffix="",
|
| 1098 |
+
fuse_unk=False,
|
| 1099 |
+
)
|
| 1100 |
+
)
|
| 1101 |
+
|
| 1102 |
+
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=self.original_tokenizer.add_prefix_space)
|
| 1103 |
+
tokenizer.decoder = decoders.ByteLevel()
|
| 1104 |
+
|
| 1105 |
+
prefix_token_ids = self.original_tokenizer.prefix_tokens
|
| 1106 |
+
prefixes = self.original_tokenizer.convert_ids_to_tokens(prefix_token_ids)
|
| 1107 |
+
eos = self.original_tokenizer.eos_token
|
| 1108 |
+
eos_token_id = self.original_tokenizer.eos_token_id
|
| 1109 |
+
prefix_template = " ".join([f"{token}:0" for token in prefixes])
|
| 1110 |
+
tokenizer.post_processor = processors.TemplateProcessing(
|
| 1111 |
+
single=f"{prefix_template} $A:0 {eos}:0",
|
| 1112 |
+
pair=f"{prefix_template} $A:0 $B:1 {eos}:1",
|
| 1113 |
+
special_tokens=[
|
| 1114 |
+
(eos, eos_token_id),
|
| 1115 |
+
*zip(prefixes, prefix_token_ids),
|
| 1116 |
+
],
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
return tokenizer
|
| 1120 |
+
|
| 1121 |
+
|
| 1122 |
+
class BigBirdConverter(SpmConverter):
|
| 1123 |
+
def post_processor(self):
|
| 1124 |
+
return processors.TemplateProcessing(
|
| 1125 |
+
single="[CLS]:0 $A:0 [SEP]:0",
|
| 1126 |
+
pair="[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1",
|
| 1127 |
+
special_tokens=[
|
| 1128 |
+
("[CLS]", self.original_tokenizer.convert_tokens_to_ids("[CLS]")),
|
| 1129 |
+
("[SEP]", self.original_tokenizer.convert_tokens_to_ids("[SEP]")),
|
| 1130 |
+
],
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
|
| 1134 |
+
class CLIPConverter(Converter):
|
| 1135 |
+
def converted(self) -> Tokenizer:
|
| 1136 |
+
vocab = self.original_tokenizer.encoder
|
| 1137 |
+
merges = list(self.original_tokenizer.bpe_ranks.keys())
|
| 1138 |
+
unk_token = self.original_tokenizer.unk_token
|
| 1139 |
+
|
| 1140 |
+
tokenizer = Tokenizer(
|
| 1141 |
+
BPE(
|
| 1142 |
+
vocab=vocab,
|
| 1143 |
+
merges=merges,
|
| 1144 |
+
dropout=None,
|
| 1145 |
+
continuing_subword_prefix="",
|
| 1146 |
+
end_of_word_suffix="</w>",
|
| 1147 |
+
fuse_unk=False,
|
| 1148 |
+
unk_token=str(unk_token),
|
| 1149 |
+
)
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
tokenizer.normalizer = normalizers.Sequence(
|
| 1153 |
+
[normalizers.NFC(), normalizers.Replace(Regex(r"\s+"), " "), normalizers.Lowercase()]
|
| 1154 |
+
)
|
| 1155 |
+
tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
|
| 1156 |
+
[
|
| 1157 |
+
pre_tokenizers.Split(
|
| 1158 |
+
Regex(r"""'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+"""),
|
| 1159 |
+
behavior="removed",
|
| 1160 |
+
invert=True,
|
| 1161 |
+
),
|
| 1162 |
+
pre_tokenizers.ByteLevel(add_prefix_space=False),
|
| 1163 |
+
]
|
| 1164 |
+
)
|
| 1165 |
+
tokenizer.decoder = decoders.ByteLevel()
|
| 1166 |
+
|
| 1167 |
+
# Hack to have a ByteLevel and TemplaceProcessor
|
| 1168 |
+
tokenizer.post_processor = processors.RobertaProcessing(
|
| 1169 |
+
sep=(self.original_tokenizer.eos_token, self.original_tokenizer.eos_token_id),
|
| 1170 |
+
cls=(self.original_tokenizer.bos_token, self.original_tokenizer.bos_token_id),
|
| 1171 |
+
add_prefix_space=False,
|
| 1172 |
+
trim_offsets=False,
|
| 1173 |
+
)
|
| 1174 |
+
return tokenizer
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
+
class LayoutLMv2Converter(Converter):
|
| 1178 |
+
def converted(self) -> Tokenizer:
|
| 1179 |
+
vocab = self.original_tokenizer.vocab
|
| 1180 |
+
tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token)))
|
| 1181 |
+
|
| 1182 |
+
tokenize_chinese_chars = False
|
| 1183 |
+
strip_accents = False
|
| 1184 |
+
do_lower_case = True
|
| 1185 |
+
if hasattr(self.original_tokenizer, "basic_tokenizer"):
|
| 1186 |
+
tokenize_chinese_chars = self.original_tokenizer.basic_tokenizer.tokenize_chinese_chars
|
| 1187 |
+
strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents
|
| 1188 |
+
do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case
|
| 1189 |
+
|
| 1190 |
+
tokenizer.normalizer = normalizers.BertNormalizer(
|
| 1191 |
+
clean_text=True,
|
| 1192 |
+
handle_chinese_chars=tokenize_chinese_chars,
|
| 1193 |
+
strip_accents=strip_accents,
|
| 1194 |
+
lowercase=do_lower_case,
|
| 1195 |
+
)
|
| 1196 |
+
tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
|
| 1197 |
+
|
| 1198 |
+
cls = str(self.original_tokenizer.cls_token)
|
| 1199 |
+
sep = str(self.original_tokenizer.sep_token)
|
| 1200 |
+
cls_token_id = self.original_tokenizer.cls_token_id
|
| 1201 |
+
sep_token_id = self.original_tokenizer.sep_token_id
|
| 1202 |
+
|
| 1203 |
+
tokenizer.post_processor = processors.TemplateProcessing(
|
| 1204 |
+
single=f"{cls}:0 $A:0 {sep}:0",
|
| 1205 |
+
pair=f"{cls}:0 $A:0 {sep}:0 $B:1 {sep}:1",
|
| 1206 |
+
special_tokens=[
|
| 1207 |
+
(cls, cls_token_id),
|
| 1208 |
+
(sep, sep_token_id),
|
| 1209 |
+
],
|
| 1210 |
+
)
|
| 1211 |
+
tokenizer.decoder = decoders.WordPiece(prefix="##")
|
| 1212 |
+
|
| 1213 |
+
return tokenizer
|
| 1214 |
+
|
| 1215 |
+
|
| 1216 |
+
class BlenderbotConverter(Converter):
|
| 1217 |
+
def converted(self) -> Tokenizer:
|
| 1218 |
+
ot = self.original_tokenizer
|
| 1219 |
+
vocab = ot.encoder
|
| 1220 |
+
merges = list(ot.bpe_ranks.keys())
|
| 1221 |
+
|
| 1222 |
+
tokenizer = Tokenizer(
|
| 1223 |
+
BPE(
|
| 1224 |
+
vocab=vocab,
|
| 1225 |
+
merges=merges,
|
| 1226 |
+
dropout=None,
|
| 1227 |
+
continuing_subword_prefix="",
|
| 1228 |
+
end_of_word_suffix="",
|
| 1229 |
+
fuse_unk=False,
|
| 1230 |
+
)
|
| 1231 |
+
)
|
| 1232 |
+
|
| 1233 |
+
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=ot.add_prefix_space)
|
| 1234 |
+
tokenizer.decoder = decoders.ByteLevel()
|
| 1235 |
+
tokenizer.post_processor = processors.TemplateProcessing(
|
| 1236 |
+
single=f"$A:0 {ot.eos_token}:0",
|
| 1237 |
+
special_tokens=[
|
| 1238 |
+
(ot.eos_token, ot.eos_token_id),
|
| 1239 |
+
],
|
| 1240 |
+
)
|
| 1241 |
+
|
| 1242 |
+
return tokenizer
|
| 1243 |
+
|
| 1244 |
+
|
| 1245 |
+
class XGLMConverter(SpmConverter):
|
| 1246 |
+
def vocab(self, proto):
|
| 1247 |
+
vocab = [
|
| 1248 |
+
("<s>", 0.0),
|
| 1249 |
+
("<pad>", 0.0),
|
| 1250 |
+
("</s>", 0.0),
|
| 1251 |
+
("<unk>", 0.0),
|
| 1252 |
+
]
|
| 1253 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
|
| 1254 |
+
vocab += [("<madeupword0>", 0.0), ("<madeupword1>", 0.0), ("<madeupword2>", 0.0), ("<madeupword3>", 0.0), ("<madeupword4>", 0.0), ("<madeupword5>", 0.0), ("<madeupword6>", 0.0)] # fmt: skip
|
| 1255 |
+
return vocab
|
| 1256 |
+
|
| 1257 |
+
def unk_id(self, proto):
|
| 1258 |
+
unk_id = 3
|
| 1259 |
+
return unk_id
|
| 1260 |
+
|
| 1261 |
+
def post_processor(self):
|
| 1262 |
+
return processors.TemplateProcessing(
|
| 1263 |
+
single="</s> $A",
|
| 1264 |
+
pair="</s> $A </s> </s> $B",
|
| 1265 |
+
special_tokens=[
|
| 1266 |
+
("<s>", self.original_tokenizer.convert_tokens_to_ids("<s>")),
|
| 1267 |
+
("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")),
|
| 1268 |
+
],
|
| 1269 |
+
)
|
| 1270 |
+
|
| 1271 |
+
|
| 1272 |
+
class GemmaConverter(SpmConverter):
|
| 1273 |
+
handle_byte_fallback = True
|
| 1274 |
+
SpmExtractor = GemmaSentencePieceExtractor
|
| 1275 |
+
# start and end of turn tokens must be marked as special
|
| 1276 |
+
special_tokens = {"<start_of_turn>", "<end_of_turn>"}
|
| 1277 |
+
|
| 1278 |
+
""""
|
| 1279 |
+
split_by_unicode_script: true
|
| 1280 |
+
split_by_number: true
|
| 1281 |
+
split_by_whitespace: true
|
| 1282 |
+
treat_whitespace_as_suffix: false
|
| 1283 |
+
allow_whitespace_only_pieces: true
|
| 1284 |
+
split_digits: true
|
| 1285 |
+
byte_fallback: true
|
| 1286 |
+
"""
|
| 1287 |
+
|
| 1288 |
+
def normalizer(self, proto):
|
| 1289 |
+
return normalizers.Replace(" ", "▁")
|
| 1290 |
+
|
| 1291 |
+
def vocab(self, proto):
|
| 1292 |
+
vocab = [
|
| 1293 |
+
(self.original_tokenizer.pad_token, 0.0),
|
| 1294 |
+
(self.original_tokenizer.eos_token, 0.0),
|
| 1295 |
+
(self.original_tokenizer.bos_token, 0.0),
|
| 1296 |
+
]
|
| 1297 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
|
| 1298 |
+
|
| 1299 |
+
# Older gemma tokenizers had a missing tab token, so we fix that here
|
| 1300 |
+
if not any(x[0] == "\t" for x in vocab):
|
| 1301 |
+
override_index = next((i for i, x in enumerate(vocab) if x[0] == "<0x09>"), None)
|
| 1302 |
+
if override_index is not None:
|
| 1303 |
+
vocab[override_index] = ("\t", 0.0)
|
| 1304 |
+
|
| 1305 |
+
return vocab
|
| 1306 |
+
|
| 1307 |
+
def pre_tokenizer(self, replacement, add_prefix_space):
|
| 1308 |
+
return pre_tokenizers.Split(" ", "merged_with_previous")
|
| 1309 |
+
|
| 1310 |
+
def unk_id(self, proto):
|
| 1311 |
+
unk_id = 3
|
| 1312 |
+
return unk_id
|
| 1313 |
+
|
| 1314 |
+
def decoder(self, replacement, add_prefix_space):
|
| 1315 |
+
return decoders.Sequence(
|
| 1316 |
+
[
|
| 1317 |
+
decoders.Replace("▁", " "),
|
| 1318 |
+
decoders.ByteFallback(),
|
| 1319 |
+
decoders.Fuse(),
|
| 1320 |
+
]
|
| 1321 |
+
)
|
| 1322 |
+
|
| 1323 |
+
|
| 1324 |
+
class LlamaConverter(SpmConverter):
|
| 1325 |
+
handle_byte_fallback = True
|
| 1326 |
+
|
| 1327 |
+
def vocab(self, proto):
|
| 1328 |
+
vocab = [
|
| 1329 |
+
(self.original_tokenizer.convert_ids_to_tokens(0), 0.0),
|
| 1330 |
+
(self.original_tokenizer.convert_ids_to_tokens(1), 0.0),
|
| 1331 |
+
(self.original_tokenizer.convert_ids_to_tokens(2), 0.0),
|
| 1332 |
+
]
|
| 1333 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
|
| 1334 |
+
return vocab
|
| 1335 |
+
|
| 1336 |
+
def unk_id(self, proto):
|
| 1337 |
+
unk_id = 0
|
| 1338 |
+
return unk_id
|
| 1339 |
+
|
| 1340 |
+
def decoder(self, replacement, add_prefix_space):
|
| 1341 |
+
sequence = [
|
| 1342 |
+
decoders.Replace("▁", " "),
|
| 1343 |
+
decoders.ByteFallback(),
|
| 1344 |
+
decoders.Fuse(),
|
| 1345 |
+
]
|
| 1346 |
+
if add_prefix_space:
|
| 1347 |
+
sequence += [decoders.Strip(content=" ", left=1)]
|
| 1348 |
+
return decoders.Sequence(sequence)
|
| 1349 |
+
|
| 1350 |
+
def normalizer(self, proto):
|
| 1351 |
+
if getattr(self.original_tokenizer, "legacy", True):
|
| 1352 |
+
sequence = []
|
| 1353 |
+
if getattr(self.original_tokenizer, "add_prefix_space", True):
|
| 1354 |
+
sequence += [normalizers.Prepend(prepend="▁")]
|
| 1355 |
+
sequence += [normalizers.Replace(pattern=" ", content="▁")]
|
| 1356 |
+
return normalizers.Sequence(sequence)
|
| 1357 |
+
return None # non-legacy, no normalizer
|
| 1358 |
+
|
| 1359 |
+
def pre_tokenizer(self, replacement, add_prefix_space):
|
| 1360 |
+
if not getattr(self.original_tokenizer, "legacy", True): # non-legacy, we need a replace
|
| 1361 |
+
prepend_scheme = _get_prepend_scheme(add_prefix_space, self.original_tokenizer)
|
| 1362 |
+
return pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme, split=False)
|
| 1363 |
+
return None
|
| 1364 |
+
|
| 1365 |
+
def post_processor(self):
|
| 1366 |
+
# the processor is defined in the LlamaTokenizerFast class.
|
| 1367 |
+
return None
|
| 1368 |
+
|
| 1369 |
+
|
| 1370 |
+
class MarkupLMConverter(Converter):
|
| 1371 |
+
def converted(self) -> Tokenizer:
|
| 1372 |
+
ot = self.original_tokenizer
|
| 1373 |
+
vocab = ot.encoder
|
| 1374 |
+
merges = list(ot.bpe_ranks.keys())
|
| 1375 |
+
|
| 1376 |
+
tokenizer = Tokenizer(
|
| 1377 |
+
BPE(
|
| 1378 |
+
vocab=vocab,
|
| 1379 |
+
merges=merges,
|
| 1380 |
+
dropout=None,
|
| 1381 |
+
continuing_subword_prefix="",
|
| 1382 |
+
end_of_word_suffix="",
|
| 1383 |
+
fuse_unk=False,
|
| 1384 |
+
unk_token=self.original_tokenizer.unk_token,
|
| 1385 |
+
)
|
| 1386 |
+
)
|
| 1387 |
+
|
| 1388 |
+
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=ot.add_prefix_space)
|
| 1389 |
+
tokenizer.decoder = decoders.ByteLevel()
|
| 1390 |
+
|
| 1391 |
+
cls = str(self.original_tokenizer.cls_token)
|
| 1392 |
+
sep = str(self.original_tokenizer.sep_token)
|
| 1393 |
+
cls_token_id = self.original_tokenizer.cls_token_id
|
| 1394 |
+
sep_token_id = self.original_tokenizer.sep_token_id
|
| 1395 |
+
|
| 1396 |
+
tokenizer.post_processor = processors.TemplateProcessing(
|
| 1397 |
+
single=f"{cls} $A {sep}",
|
| 1398 |
+
pair=f"{cls} $A {sep} $B {sep}",
|
| 1399 |
+
special_tokens=[
|
| 1400 |
+
(cls, cls_token_id),
|
| 1401 |
+
(sep, sep_token_id),
|
| 1402 |
+
],
|
| 1403 |
+
)
|
| 1404 |
+
|
| 1405 |
+
return tokenizer
|
| 1406 |
+
|
| 1407 |
+
|
| 1408 |
+
class MoshiConverter(SpmConverter):
|
| 1409 |
+
handle_byte_fallback = True
|
| 1410 |
+
|
| 1411 |
+
def __init__(self, vocab_file, model_max_length=None, **kwargs):
|
| 1412 |
+
requires_backends(self, "protobuf")
|
| 1413 |
+
|
| 1414 |
+
Converter.__init__(self, vocab_file)
|
| 1415 |
+
|
| 1416 |
+
# from .utils import sentencepiece_model_pb2 as model_pb2
|
| 1417 |
+
model_pb2 = import_protobuf()
|
| 1418 |
+
|
| 1419 |
+
m = model_pb2.ModelProto()
|
| 1420 |
+
with open(vocab_file, "rb") as f:
|
| 1421 |
+
m.ParseFromString(f.read())
|
| 1422 |
+
self.proto = m
|
| 1423 |
+
|
| 1424 |
+
def normalizer(self, proto):
|
| 1425 |
+
precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap
|
| 1426 |
+
_normalizers = [
|
| 1427 |
+
normalizers.Replace(" ", "▁"),
|
| 1428 |
+
]
|
| 1429 |
+
if not precompiled_charsmap:
|
| 1430 |
+
return normalizers.Sequence(_normalizers)
|
| 1431 |
+
else:
|
| 1432 |
+
return normalizers.Sequence([normalizers.Precompiled(precompiled_charsmap)] + _normalizers)
|
| 1433 |
+
|
| 1434 |
+
def decoder(self, replacement, add_prefix_space):
|
| 1435 |
+
sequence = [
|
| 1436 |
+
decoders.Replace("▁", " "),
|
| 1437 |
+
decoders.ByteFallback(),
|
| 1438 |
+
decoders.Fuse(),
|
| 1439 |
+
]
|
| 1440 |
+
if add_prefix_space:
|
| 1441 |
+
sequence += [decoders.Strip(content=" ", left=1)]
|
| 1442 |
+
return decoders.Sequence(sequence)
|
| 1443 |
+
|
| 1444 |
+
def pre_tokenizer(self, replacement, add_prefix_space):
|
| 1445 |
+
prepend_scheme = "first"
|
| 1446 |
+
return pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme, split=False)
|
| 1447 |
+
|
| 1448 |
+
|
| 1449 |
+
class HeliumConverter(SpmConverter):
|
| 1450 |
+
handle_byte_fallback = True
|
| 1451 |
+
|
| 1452 |
+
def __init__(self, vocab_file=None, *args):
|
| 1453 |
+
requires_backends(self, "protobuf")
|
| 1454 |
+
|
| 1455 |
+
Converter.__init__(self, vocab_file)
|
| 1456 |
+
|
| 1457 |
+
model_pb2 = import_protobuf()
|
| 1458 |
+
|
| 1459 |
+
m = model_pb2.ModelProto()
|
| 1460 |
+
with open(vocab_file, "rb") as f:
|
| 1461 |
+
m.ParseFromString(f.read())
|
| 1462 |
+
self.proto = m
|
| 1463 |
+
|
| 1464 |
+
def tokenizer(self, proto):
|
| 1465 |
+
vocab_scores = self.vocab(proto)
|
| 1466 |
+
tokenizer = Tokenizer(
|
| 1467 |
+
Unigram(
|
| 1468 |
+
vocab_scores,
|
| 1469 |
+
unk_id=self.unk_id(proto),
|
| 1470 |
+
byte_fallback=self.handle_byte_fallback,
|
| 1471 |
+
)
|
| 1472 |
+
)
|
| 1473 |
+
# control tokens are special
|
| 1474 |
+
# user defined symbols are not
|
| 1475 |
+
# both user and control tokens are AddedTokens
|
| 1476 |
+
# Add user defined symbols (type == 4) from sentencepiece (https://github.com/google/sentencepiece/blob/6225e08edb2577757163b3f5dbba4c0b670ef445/src/sentencepiece_model.proto#L299C29-L299C33)
|
| 1477 |
+
spm_added_tokens = [
|
| 1478 |
+
(id, p.piece, p.type == 3 or p.piece in self.special_tokens)
|
| 1479 |
+
for id, p in enumerate(proto.pieces)
|
| 1480 |
+
if p.type in [3, 4]
|
| 1481 |
+
]
|
| 1482 |
+
tokenizer.add_tokens(
|
| 1483 |
+
[
|
| 1484 |
+
AddedToken(token, normalized=False, special=special, single_word=True)
|
| 1485 |
+
for id, token, special in sorted(spm_added_tokens, key=lambda x: x[0])
|
| 1486 |
+
]
|
| 1487 |
+
)
|
| 1488 |
+
tokenizer.add_tokens([AddedToken("\n", normalized=False, special=False)])
|
| 1489 |
+
tokenizer.enable_padding(pad_token="<pad>", pad_id=3)
|
| 1490 |
+
return tokenizer
|
| 1491 |
+
|
| 1492 |
+
def vocab(self, proto):
|
| 1493 |
+
vocab = []
|
| 1494 |
+
for piece in proto.pieces:
|
| 1495 |
+
if piece.piece == "<0x0A>":
|
| 1496 |
+
vocab += [("\n", piece.score)]
|
| 1497 |
+
else:
|
| 1498 |
+
vocab += [(piece.piece, piece.score)]
|
| 1499 |
+
return vocab
|
| 1500 |
+
|
| 1501 |
+
def unk_id(self, proto):
|
| 1502 |
+
unk_id = 0
|
| 1503 |
+
return unk_id
|
| 1504 |
+
|
| 1505 |
+
def decoder(self, replacement, add_prefix_space):
|
| 1506 |
+
sequence = [
|
| 1507 |
+
decoders.Replace("▁", " "),
|
| 1508 |
+
decoders.ByteFallback(),
|
| 1509 |
+
decoders.Fuse(),
|
| 1510 |
+
]
|
| 1511 |
+
sequence += [decoders.Strip(content=" ", left=1)]
|
| 1512 |
+
return decoders.Sequence(sequence)
|
| 1513 |
+
|
| 1514 |
+
def normalizer(self, proto):
|
| 1515 |
+
return normalizers.Sequence([normalizers.Prepend(" "), normalizers.Replace(r" ", "▁")])
|
| 1516 |
+
|
| 1517 |
+
def pre_tokenizer(self, replacement, add_prefix_space):
|
| 1518 |
+
return pre_tokenizers.Sequence([pre_tokenizers.Split("\n", "contiguous")])
|
| 1519 |
+
|
| 1520 |
+
def post_processor(self):
|
| 1521 |
+
return processors.TemplateProcessing(
|
| 1522 |
+
single=[
|
| 1523 |
+
"<s>",
|
| 1524 |
+
"$A",
|
| 1525 |
+
],
|
| 1526 |
+
pair=[
|
| 1527 |
+
"<s>",
|
| 1528 |
+
"$A",
|
| 1529 |
+
"<s>",
|
| 1530 |
+
"$B",
|
| 1531 |
+
],
|
| 1532 |
+
special_tokens=[
|
| 1533 |
+
("<s>", 1),
|
| 1534 |
+
],
|
| 1535 |
+
)
|
| 1536 |
+
|
| 1537 |
+
|
| 1538 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
|
| 1539 |
+
def bytes_to_unicode():
|
| 1540 |
+
"""
|
| 1541 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
| 1542 |
+
characters the bpe code barfs on.
|
| 1543 |
+
|
| 1544 |
+
The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
|
| 1545 |
+
if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
|
| 1546 |
+
decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
|
| 1547 |
+
tables between utf-8 bytes and unicode strings.
|
| 1548 |
+
"""
|
| 1549 |
+
bs = (
|
| 1550 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
| 1551 |
+
)
|
| 1552 |
+
cs = bs[:]
|
| 1553 |
+
n = 0
|
| 1554 |
+
for b in range(2**8):
|
| 1555 |
+
if b not in bs:
|
| 1556 |
+
bs.append(b)
|
| 1557 |
+
cs.append(2**8 + n)
|
| 1558 |
+
n += 1
|
| 1559 |
+
cs = [chr(n) for n in cs]
|
| 1560 |
+
return dict(zip(bs, cs))
|
| 1561 |
+
|
| 1562 |
+
|
| 1563 |
+
class TikTokenConverter:
|
| 1564 |
+
"""
|
| 1565 |
+
A general tiktoken converter.
|
| 1566 |
+
"""
|
| 1567 |
+
|
| 1568 |
+
def __init__(
|
| 1569 |
+
self,
|
| 1570 |
+
vocab_file=None,
|
| 1571 |
+
pattern=r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+""",
|
| 1572 |
+
add_prefix_space=False,
|
| 1573 |
+
additional_special_tokens=None,
|
| 1574 |
+
*args,
|
| 1575 |
+
**kwargs,
|
| 1576 |
+
):
|
| 1577 |
+
super().__init__(*args)
|
| 1578 |
+
self.vocab_file = vocab_file
|
| 1579 |
+
self.pattern = pattern
|
| 1580 |
+
self.add_prefix_space = add_prefix_space
|
| 1581 |
+
self.additional_special_tokens = (
|
| 1582 |
+
additional_special_tokens.keys() if type(additional_special_tokens) is dict else additional_special_tokens
|
| 1583 |
+
)
|
| 1584 |
+
|
| 1585 |
+
def extract_vocab_merges_from_model(self, tiktoken_url: str):
|
| 1586 |
+
try:
|
| 1587 |
+
from tiktoken.load import load_tiktoken_bpe
|
| 1588 |
+
except Exception:
|
| 1589 |
+
raise ValueError(
|
| 1590 |
+
"`tiktoken` is required to read a `tiktoken` file. Install it with `pip install tiktoken`."
|
| 1591 |
+
)
|
| 1592 |
+
|
| 1593 |
+
bpe_ranks = load_tiktoken_bpe(tiktoken_url)
|
| 1594 |
+
byte_encoder = bytes_to_unicode()
|
| 1595 |
+
|
| 1596 |
+
def token_bytes_to_string(b):
|
| 1597 |
+
return "".join([byte_encoder[ord(char)] for char in b.decode("latin-1")])
|
| 1598 |
+
|
| 1599 |
+
merges = []
|
| 1600 |
+
vocab = {}
|
| 1601 |
+
for token, rank in bpe_ranks.items():
|
| 1602 |
+
vocab[token_bytes_to_string(token)] = rank
|
| 1603 |
+
if len(token) == 1:
|
| 1604 |
+
continue
|
| 1605 |
+
local = []
|
| 1606 |
+
for index in range(1, len(token)):
|
| 1607 |
+
piece_l, piece_r = token[:index], token[index:]
|
| 1608 |
+
if piece_l in bpe_ranks and piece_r in bpe_ranks and (piece_l + piece_r) in bpe_ranks:
|
| 1609 |
+
local.append((piece_l, piece_r, rank))
|
| 1610 |
+
local = sorted(local, key=lambda x: (bpe_ranks[x[0]], bpe_ranks[x[1]]), reverse=False)
|
| 1611 |
+
merges.extend(local)
|
| 1612 |
+
merges = sorted(merges, key=lambda val: val[2], reverse=False)
|
| 1613 |
+
merges = [(token_bytes_to_string(val[0]), token_bytes_to_string(val[1])) for val in merges]
|
| 1614 |
+
return vocab, merges
|
| 1615 |
+
|
| 1616 |
+
def tokenizer(self):
|
| 1617 |
+
vocab_scores, merges = self.extract_vocab_merges_from_model(self.vocab_file)
|
| 1618 |
+
tokenizer = Tokenizer(BPE(vocab_scores, merges, fuse_unk=False))
|
| 1619 |
+
if hasattr(tokenizer.model, "ignore_merges"):
|
| 1620 |
+
tokenizer.model.ignore_merges = True
|
| 1621 |
+
return tokenizer
|
| 1622 |
+
|
| 1623 |
+
def converted(self) -> Tokenizer:
|
| 1624 |
+
tokenizer = self.tokenizer()
|
| 1625 |
+
tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
|
| 1626 |
+
[
|
| 1627 |
+
pre_tokenizers.Split(Regex(self.pattern), behavior="isolated", invert=False),
|
| 1628 |
+
pre_tokenizers.ByteLevel(add_prefix_space=self.add_prefix_space, use_regex=False),
|
| 1629 |
+
]
|
| 1630 |
+
)
|
| 1631 |
+
tokenizer.decoder = decoders.ByteLevel()
|
| 1632 |
+
|
| 1633 |
+
tokenizer.add_special_tokens(
|
| 1634 |
+
[AddedToken(token, normalized=False, special=True) for token in self.additional_special_tokens]
|
| 1635 |
+
)
|
| 1636 |
+
|
| 1637 |
+
tokenizer.post_processor = processors.ByteLevel(trim_offsets=False)
|
| 1638 |
+
|
| 1639 |
+
return tokenizer
|
| 1640 |
+
|
| 1641 |
+
|
| 1642 |
+
SLOW_TO_FAST_CONVERTERS = {
|
| 1643 |
+
"AlbertTokenizer": AlbertConverter,
|
| 1644 |
+
"BartTokenizer": RobertaConverter,
|
| 1645 |
+
"BarthezTokenizer": BarthezConverter,
|
| 1646 |
+
"BertTokenizer": BertConverter,
|
| 1647 |
+
"BigBirdTokenizer": BigBirdConverter,
|
| 1648 |
+
"BlenderbotTokenizer": BlenderbotConverter,
|
| 1649 |
+
"CamembertTokenizer": CamembertConverter,
|
| 1650 |
+
"CLIPTokenizer": CLIPConverter,
|
| 1651 |
+
"CodeGenTokenizer": GPT2Converter,
|
| 1652 |
+
"ConvBertTokenizer": BertConverter,
|
| 1653 |
+
"DebertaTokenizer": DebertaConverter,
|
| 1654 |
+
"DebertaV2Tokenizer": DebertaV2Converter,
|
| 1655 |
+
"DistilBertTokenizer": BertConverter,
|
| 1656 |
+
"DPRReaderTokenizer": BertConverter,
|
| 1657 |
+
"DPRQuestionEncoderTokenizer": BertConverter,
|
| 1658 |
+
"DPRContextEncoderTokenizer": BertConverter,
|
| 1659 |
+
"ElectraTokenizer": BertConverter,
|
| 1660 |
+
"FNetTokenizer": AlbertConverter,
|
| 1661 |
+
"FunnelTokenizer": FunnelConverter,
|
| 1662 |
+
"GPT2Tokenizer": GPT2Converter,
|
| 1663 |
+
"HerbertTokenizer": HerbertConverter,
|
| 1664 |
+
"LayoutLMTokenizer": BertConverter,
|
| 1665 |
+
"LayoutLMv2Tokenizer": BertConverter,
|
| 1666 |
+
"LayoutLMv3Tokenizer": RobertaConverter,
|
| 1667 |
+
"LayoutXLMTokenizer": XLMRobertaConverter,
|
| 1668 |
+
"LongformerTokenizer": RobertaConverter,
|
| 1669 |
+
"LEDTokenizer": RobertaConverter,
|
| 1670 |
+
"LxmertTokenizer": BertConverter,
|
| 1671 |
+
"MarkupLMTokenizer": MarkupLMConverter,
|
| 1672 |
+
"MBartTokenizer": MBartConverter,
|
| 1673 |
+
"MBart50Tokenizer": MBart50Converter,
|
| 1674 |
+
"MPNetTokenizer": MPNetConverter,
|
| 1675 |
+
"MobileBertTokenizer": BertConverter,
|
| 1676 |
+
"MvpTokenizer": RobertaConverter,
|
| 1677 |
+
"NllbTokenizer": NllbConverter,
|
| 1678 |
+
"OpenAIGPTTokenizer": OpenAIGPTConverter,
|
| 1679 |
+
"PegasusTokenizer": PegasusConverter,
|
| 1680 |
+
"Qwen2Tokenizer": Qwen2Converter,
|
| 1681 |
+
"RealmTokenizer": BertConverter,
|
| 1682 |
+
"ReformerTokenizer": ReformerConverter,
|
| 1683 |
+
"RemBertTokenizer": RemBertConverter,
|
| 1684 |
+
"RetriBertTokenizer": BertConverter,
|
| 1685 |
+
"RobertaTokenizer": RobertaConverter,
|
| 1686 |
+
"RoFormerTokenizer": RoFormerConverter,
|
| 1687 |
+
"SeamlessM4TTokenizer": SeamlessM4TConverter,
|
| 1688 |
+
"SqueezeBertTokenizer": BertConverter,
|
| 1689 |
+
"T5Tokenizer": T5Converter,
|
| 1690 |
+
"UdopTokenizer": UdopConverter,
|
| 1691 |
+
"WhisperTokenizer": WhisperConverter,
|
| 1692 |
+
"XLMRobertaTokenizer": XLMRobertaConverter,
|
| 1693 |
+
"XLNetTokenizer": XLNetConverter,
|
| 1694 |
+
"SplinterTokenizer": SplinterConverter,
|
| 1695 |
+
"XGLMTokenizer": XGLMConverter,
|
| 1696 |
+
"LlamaTokenizer": LlamaConverter,
|
| 1697 |
+
"CodeLlamaTokenizer": LlamaConverter,
|
| 1698 |
+
"GemmaTokenizer": GemmaConverter,
|
| 1699 |
+
"Phi3Tokenizer": LlamaConverter,
|
| 1700 |
+
}
|
| 1701 |
+
|
| 1702 |
+
|
| 1703 |
+
def convert_slow_tokenizer(transformer_tokenizer, from_tiktoken=False) -> Tokenizer:
|
| 1704 |
+
"""
|
| 1705 |
+
Utilities to convert a slow tokenizer instance in a fast tokenizer instance.
|
| 1706 |
+
|
| 1707 |
+
Args:
|
| 1708 |
+
transformer_tokenizer ([`~tokenization_utils_base.PreTrainedTokenizer`]):
|
| 1709 |
+
Instance of a slow tokenizer to convert in the backend tokenizer for
|
| 1710 |
+
[`~tokenization_utils_base.PreTrainedTokenizerFast`].
|
| 1711 |
+
from_tiktoken (bool, optional): Whether to use the `tiktoken` library to convert the tokenizer instead of sentencepiece.
|
| 1712 |
+
Defaults to False.
|
| 1713 |
+
|
| 1714 |
+
Return:
|
| 1715 |
+
A instance of [`~tokenizers.Tokenizer`] to be used as the backend tokenizer of a
|
| 1716 |
+
[`~tokenization_utils_base.PreTrainedTokenizerFast`]
|
| 1717 |
+
"""
|
| 1718 |
+
|
| 1719 |
+
tokenizer_class_name = transformer_tokenizer.__class__.__name__
|
| 1720 |
+
if tokenizer_class_name in SLOW_TO_FAST_CONVERTERS and not from_tiktoken:
|
| 1721 |
+
converter_class = SLOW_TO_FAST_CONVERTERS[tokenizer_class_name]
|
| 1722 |
+
return converter_class(transformer_tokenizer).converted()
|
| 1723 |
+
|
| 1724 |
+
else:
|
| 1725 |
+
try:
|
| 1726 |
+
logger.info("Converting from Tiktoken")
|
| 1727 |
+
return TikTokenConverter(
|
| 1728 |
+
vocab_file=transformer_tokenizer.vocab_file,
|
| 1729 |
+
additional_special_tokens=transformer_tokenizer.additional_special_tokens,
|
| 1730 |
+
).converted()
|
| 1731 |
+
except Exception:
|
| 1732 |
+
raise ValueError(
|
| 1733 |
+
f"Converting from SentencePiece and Tiktoken failed, if a converter for SentencePiece is available, provide a model path "
|
| 1734 |
+
f"with a SentencePiece tokenizer.model file."
|
| 1735 |
+
f"Currently available slow->fast converters: {list(SLOW_TO_FAST_CONVERTERS.keys())}"
|
| 1736 |
+
)
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/data_collator.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/debug_utils.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 collections
|
| 16 |
+
|
| 17 |
+
from .utils import ExplicitEnum, is_torch_available, logging
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if is_torch_available():
|
| 21 |
+
import torch
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class DebugUnderflowOverflow:
|
| 28 |
+
"""
|
| 29 |
+
This debug class helps detect and understand where the model starts getting very large or very small, and more
|
| 30 |
+
importantly `nan` or `inf` weight and activation elements.
|
| 31 |
+
|
| 32 |
+
There are 2 working modes:
|
| 33 |
+
|
| 34 |
+
1. Underflow/overflow detection (default)
|
| 35 |
+
2. Specific batch absolute min/max tracing without detection
|
| 36 |
+
|
| 37 |
+
Mode 1: Underflow/overflow detection
|
| 38 |
+
|
| 39 |
+
To activate the underflow/overflow detection, initialize the object with the model :
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
debug_overflow = DebugUnderflowOverflow(model)
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
then run the training as normal and if `nan` or `inf` gets detected in at least one of the weight, input or output
|
| 46 |
+
elements this module will throw an exception and will print `max_frames_to_save` frames that lead to this event,
|
| 47 |
+
each frame reporting
|
| 48 |
+
|
| 49 |
+
1. the fully qualified module name plus the class name whose `forward` was run
|
| 50 |
+
2. the absolute min and max value of all elements for each module weights, and the inputs and output
|
| 51 |
+
|
| 52 |
+
For example, here is the header and the last few frames in detection report for `google/mt5-small` run in fp16
|
| 53 |
+
mixed precision :
|
| 54 |
+
|
| 55 |
+
```
|
| 56 |
+
Detected inf/nan during batch_number=0
|
| 57 |
+
Last 21 forward frames:
|
| 58 |
+
abs min abs max metadata
|
| 59 |
+
[...]
|
| 60 |
+
encoder.block.2.layer.1.DenseReluDense.wi_0 Linear
|
| 61 |
+
2.17e-07 4.50e+00 weight
|
| 62 |
+
1.79e-06 4.65e+00 input[0]
|
| 63 |
+
2.68e-06 3.70e+01 output
|
| 64 |
+
encoder.block.2.layer.1.DenseReluDense.wi_1 Linear
|
| 65 |
+
8.08e-07 2.66e+01 weight
|
| 66 |
+
1.79e-06 4.65e+00 input[0]
|
| 67 |
+
1.27e-04 2.37e+02 output
|
| 68 |
+
encoder.block.2.layer.1.DenseReluDense.wo Linear
|
| 69 |
+
1.01e-06 6.44e+00 weight
|
| 70 |
+
0.00e+00 9.74e+03 input[0]
|
| 71 |
+
3.18e-04 6.27e+04 output
|
| 72 |
+
encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
|
| 73 |
+
1.79e-06 4.65e+00 input[0]
|
| 74 |
+
3.18e-04 6.27e+04 output
|
| 75 |
+
encoder.block.2.layer.1.dropout Dropout
|
| 76 |
+
3.18e-04 6.27e+04 input[0]
|
| 77 |
+
0.00e+00 inf output
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
You can see here, that `T5DenseGatedGeluDense.forward` resulted in output activations, whose absolute max value was
|
| 81 |
+
around 62.7K, which is very close to fp16's top limit of 64K. In the next frame we have `Dropout` which
|
| 82 |
+
renormalizes the weights, after it zeroed some of the elements, which pushes the absolute max value to more than
|
| 83 |
+
64K, and we get an overlow.
|
| 84 |
+
|
| 85 |
+
As you can see it's the previous frames that we need to look into when the numbers start going into very large for
|
| 86 |
+
fp16 numbers.
|
| 87 |
+
|
| 88 |
+
The tracking is done in a forward hook, which gets invoked immediately after `forward` has completed.
|
| 89 |
+
|
| 90 |
+
By default the last 21 frames are printed. You can change the default to adjust for your needs. For example :
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100)
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
To validate that you have set up this debugging feature correctly, and you intend to use it in a training that
|
| 97 |
+
may take hours to complete, first run it with normal tracing enabled for one of a few batches as explained in
|
| 98 |
+
the next section.
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
Mode 2. Specific batch absolute min/max tracing without detection
|
| 102 |
+
|
| 103 |
+
The second work mode is per-batch tracing with the underflow/overflow detection feature turned off.
|
| 104 |
+
|
| 105 |
+
Let's say you want to watch the absolute min and max values for all the ingredients of each `forward` call of a
|
| 106 |
+
given batch, and only do that for batches 1 and 3. Then you instantiate this class as :
|
| 107 |
+
|
| 108 |
+
```python
|
| 109 |
+
debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3])
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
And now full batches 1 and 3 will be traced using the same format as explained above. Batches are 0-indexed.
|
| 113 |
+
|
| 114 |
+
This is helpful if you know that the program starts misbehaving after a certain batch number, so you can
|
| 115 |
+
fast-forward right to that area.
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
Early stopping:
|
| 119 |
+
|
| 120 |
+
You can also specify the batch number after which to stop the training, with :
|
| 121 |
+
|
| 122 |
+
```python
|
| 123 |
+
debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3)
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
This feature is mainly useful in the tracing mode, but you can use it for any mode.
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
**Performance**:
|
| 130 |
+
|
| 131 |
+
As this module measures absolute `min`/``max` of each weight of the model on every forward it'll slow the training
|
| 132 |
+
down. Therefore remember to turn it off once the debugging needs have been met.
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
model (`nn.Module`):
|
| 136 |
+
The model to debug.
|
| 137 |
+
max_frames_to_save (`int`, *optional*, defaults to 21):
|
| 138 |
+
How many frames back to record
|
| 139 |
+
trace_batch_nums(`List[int]`, *optional*, defaults to `[]`):
|
| 140 |
+
Which batch numbers to trace (turns detection off)
|
| 141 |
+
abort_after_batch_num (`int``, *optional*):
|
| 142 |
+
Whether to abort after a certain batch number has finished
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
def __init__(self, model, max_frames_to_save=21, trace_batch_nums=[], abort_after_batch_num=None):
|
| 146 |
+
self.model = model
|
| 147 |
+
self.trace_batch_nums = trace_batch_nums
|
| 148 |
+
self.abort_after_batch_num = abort_after_batch_num
|
| 149 |
+
|
| 150 |
+
# keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence
|
| 151 |
+
self.frames = collections.deque([], max_frames_to_save)
|
| 152 |
+
self.frame = []
|
| 153 |
+
self.batch_number = 0
|
| 154 |
+
self.total_calls = 0
|
| 155 |
+
self.detected_overflow = False
|
| 156 |
+
self.prefix = " "
|
| 157 |
+
|
| 158 |
+
self.analyse_model()
|
| 159 |
+
|
| 160 |
+
self.register_forward_hook()
|
| 161 |
+
|
| 162 |
+
def save_frame(self, frame=None):
|
| 163 |
+
if frame is not None:
|
| 164 |
+
self.expand_frame(frame)
|
| 165 |
+
self.frames.append("\n".join(self.frame))
|
| 166 |
+
self.frame = [] # start a new frame
|
| 167 |
+
|
| 168 |
+
def expand_frame(self, line):
|
| 169 |
+
self.frame.append(line)
|
| 170 |
+
|
| 171 |
+
def trace_frames(self):
|
| 172 |
+
print("\n".join(self.frames))
|
| 173 |
+
self.frames = []
|
| 174 |
+
|
| 175 |
+
def reset_saved_frames(self):
|
| 176 |
+
self.frames = []
|
| 177 |
+
|
| 178 |
+
def dump_saved_frames(self):
|
| 179 |
+
print(f"\nDetected inf/nan during batch_number={self.batch_number}")
|
| 180 |
+
print(f"Last {len(self.frames)} forward frames:")
|
| 181 |
+
print(f"{'abs min':8} {'abs max':8} metadata")
|
| 182 |
+
print("\n".join(self.frames))
|
| 183 |
+
print("\n\n")
|
| 184 |
+
self.frames = []
|
| 185 |
+
|
| 186 |
+
def analyse_model(self):
|
| 187 |
+
# extract the fully qualified module names, to be able to report at run time. e.g.:
|
| 188 |
+
# encoder.block.2.layer.0.SelfAttention.o
|
| 189 |
+
#
|
| 190 |
+
# for shared weights only the first shared module name will be registered
|
| 191 |
+
self.module_names = {m: name for name, m in self.model.named_modules()}
|
| 192 |
+
# self.longest_module_name = max(len(v) for v in self.module_names.values())
|
| 193 |
+
|
| 194 |
+
def analyse_variable(self, var, ctx):
|
| 195 |
+
if torch.is_tensor(var):
|
| 196 |
+
self.expand_frame(get_abs_min_max(var, ctx))
|
| 197 |
+
if detect_overflow(var, ctx):
|
| 198 |
+
self.detected_overflow = True
|
| 199 |
+
elif var is None:
|
| 200 |
+
self.expand_frame(f"{'None':>17} {ctx}")
|
| 201 |
+
else:
|
| 202 |
+
self.expand_frame(f"{'not a tensor':>17} {ctx}")
|
| 203 |
+
|
| 204 |
+
def batch_start_frame(self):
|
| 205 |
+
self.expand_frame(f"\n\n{self.prefix} *** Starting batch number={self.batch_number} ***")
|
| 206 |
+
self.expand_frame(f"{'abs min':8} {'abs max':8} metadata")
|
| 207 |
+
|
| 208 |
+
def batch_end_frame(self):
|
| 209 |
+
self.expand_frame(f"{self.prefix} *** Finished batch number={self.batch_number - 1} ***\n\n")
|
| 210 |
+
|
| 211 |
+
def create_frame(self, module, input, output):
|
| 212 |
+
self.expand_frame(f"{self.prefix} {self.module_names[module]} {module.__class__.__name__}")
|
| 213 |
+
|
| 214 |
+
# params
|
| 215 |
+
for name, p in module.named_parameters(recurse=False):
|
| 216 |
+
self.analyse_variable(p, name)
|
| 217 |
+
|
| 218 |
+
# inputs
|
| 219 |
+
if isinstance(input, tuple):
|
| 220 |
+
for i, x in enumerate(input):
|
| 221 |
+
self.analyse_variable(x, f"input[{i}]")
|
| 222 |
+
else:
|
| 223 |
+
self.analyse_variable(input, "input")
|
| 224 |
+
|
| 225 |
+
# outputs
|
| 226 |
+
if isinstance(output, tuple):
|
| 227 |
+
for i, x in enumerate(output):
|
| 228 |
+
# possibly a tuple of tuples
|
| 229 |
+
if isinstance(x, tuple):
|
| 230 |
+
for j, y in enumerate(x):
|
| 231 |
+
self.analyse_variable(y, f"output[{i}][{j}]")
|
| 232 |
+
else:
|
| 233 |
+
self.analyse_variable(x, f"output[{i}]")
|
| 234 |
+
else:
|
| 235 |
+
self.analyse_variable(output, "output")
|
| 236 |
+
|
| 237 |
+
self.save_frame()
|
| 238 |
+
|
| 239 |
+
def register_forward_hook(self):
|
| 240 |
+
self.model.apply(self._register_forward_hook)
|
| 241 |
+
|
| 242 |
+
def _register_forward_hook(self, module):
|
| 243 |
+
module.register_forward_hook(self.forward_hook)
|
| 244 |
+
|
| 245 |
+
def forward_hook(self, module, input, output):
|
| 246 |
+
# - input is a tuple of packed inputs (could be non-Tensors)
|
| 247 |
+
# - output could be a Tensor or a tuple of Tensors and non-Tensors
|
| 248 |
+
|
| 249 |
+
last_frame_of_batch = False
|
| 250 |
+
|
| 251 |
+
trace_mode = True if self.batch_number in self.trace_batch_nums else False
|
| 252 |
+
if trace_mode:
|
| 253 |
+
self.reset_saved_frames()
|
| 254 |
+
|
| 255 |
+
if self.total_calls == 0:
|
| 256 |
+
self.batch_start_frame()
|
| 257 |
+
self.total_calls += 1
|
| 258 |
+
|
| 259 |
+
# count batch numbers - the very first forward hook of the batch will be called when the
|
| 260 |
+
# batch completes - i.e. it gets called very last - we know this batch has finished
|
| 261 |
+
if module == self.model:
|
| 262 |
+
self.batch_number += 1
|
| 263 |
+
last_frame_of_batch = True
|
| 264 |
+
|
| 265 |
+
self.create_frame(module, input, output)
|
| 266 |
+
|
| 267 |
+
# if last_frame_of_batch:
|
| 268 |
+
# self.batch_end_frame()
|
| 269 |
+
|
| 270 |
+
if trace_mode:
|
| 271 |
+
self.trace_frames()
|
| 272 |
+
|
| 273 |
+
if last_frame_of_batch:
|
| 274 |
+
self.batch_start_frame()
|
| 275 |
+
|
| 276 |
+
if self.detected_overflow and not trace_mode:
|
| 277 |
+
self.dump_saved_frames()
|
| 278 |
+
|
| 279 |
+
# now we can abort, as it's pointless to continue running
|
| 280 |
+
raise ValueError(
|
| 281 |
+
"DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. "
|
| 282 |
+
"Please scroll up above this traceback to see the activation values prior to this event."
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
# abort after certain batch if requested to do so
|
| 286 |
+
if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num:
|
| 287 |
+
raise ValueError(
|
| 288 |
+
f"DebugUnderflowOverflow: aborting after {self.batch_number} batches due to"
|
| 289 |
+
f" `abort_after_batch_num={self.abort_after_batch_num}` arg"
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def get_abs_min_max(var, ctx):
|
| 294 |
+
abs_var = var.abs()
|
| 295 |
+
return f"{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}"
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def detect_overflow(var, ctx):
|
| 299 |
+
"""
|
| 300 |
+
Report whether the tensor contains any `nan` or `inf` entries.
|
| 301 |
+
|
| 302 |
+
This is useful for detecting overflows/underflows and best to call right after the function that did some math that
|
| 303 |
+
modified the tensor in question.
|
| 304 |
+
|
| 305 |
+
This function contains a few other helper features that you can enable and tweak directly if you want to track
|
| 306 |
+
various other things.
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
var: the tensor variable to check
|
| 310 |
+
ctx: the message to print as a context
|
| 311 |
+
|
| 312 |
+
Return:
|
| 313 |
+
`True` if `inf` or `nan` was detected, `False` otherwise
|
| 314 |
+
"""
|
| 315 |
+
detected = False
|
| 316 |
+
if torch.isnan(var).any().item():
|
| 317 |
+
detected = True
|
| 318 |
+
print(f"{ctx} has nans")
|
| 319 |
+
if torch.isinf(var).any().item():
|
| 320 |
+
detected = True
|
| 321 |
+
print(f"{ctx} has infs")
|
| 322 |
+
|
| 323 |
+
# if needed to monitor large elements can enable the following
|
| 324 |
+
if 0: # and detected:
|
| 325 |
+
n100 = var[torch.ge(var.abs(), 100)]
|
| 326 |
+
if n100.numel() > 0:
|
| 327 |
+
print(f"{ctx}: n100={n100.numel()}")
|
| 328 |
+
n1000 = var[torch.ge(var.abs(), 1000)]
|
| 329 |
+
if n1000.numel() > 0:
|
| 330 |
+
print(f"{ctx}: n1000={n1000.numel()}")
|
| 331 |
+
n10000 = var[torch.ge(var.abs(), 10000)]
|
| 332 |
+
if n10000.numel() > 0:
|
| 333 |
+
print(f"{ctx}: n10000={n10000.numel()}")
|
| 334 |
+
|
| 335 |
+
if 0:
|
| 336 |
+
print(f"min={var.min():9.2e} max={var.max():9.2e}")
|
| 337 |
+
|
| 338 |
+
if 0:
|
| 339 |
+
print(f"min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})")
|
| 340 |
+
|
| 341 |
+
return detected
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class DebugOption(ExplicitEnum):
|
| 345 |
+
UNDERFLOW_OVERFLOW = "underflow_overflow"
|
| 346 |
+
TPU_METRICS_DEBUG = "tpu_metrics_debug"
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/deepspeed.py
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 |
+
Integration with Deepspeed
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import copy
|
| 19 |
+
import importlib.metadata as importlib_metadata
|
| 20 |
+
import importlib.util
|
| 21 |
+
import weakref
|
| 22 |
+
from functools import partialmethod
|
| 23 |
+
|
| 24 |
+
from ..dependency_versions_check import dep_version_check
|
| 25 |
+
from ..utils import is_accelerate_available, is_torch_available, logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_torch_available():
|
| 29 |
+
import torch
|
| 30 |
+
from torch import nn
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def is_deepspeed_available():
|
| 37 |
+
package_exists = importlib.util.find_spec("deepspeed") is not None
|
| 38 |
+
|
| 39 |
+
# Check we're not importing a "deepspeed" directory somewhere but the actual library by trying to grab the version
|
| 40 |
+
# AND checking it has an author field in the metadata that is HuggingFace.
|
| 41 |
+
if package_exists:
|
| 42 |
+
try:
|
| 43 |
+
_ = importlib_metadata.metadata("deepspeed")
|
| 44 |
+
return True
|
| 45 |
+
except importlib_metadata.PackageNotFoundError:
|
| 46 |
+
return False
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if is_accelerate_available() and is_deepspeed_available():
|
| 50 |
+
from accelerate.utils.deepspeed import HfDeepSpeedConfig as DeepSpeedConfig
|
| 51 |
+
else:
|
| 52 |
+
# Inherits from a dummy `object` if accelerate is not available, so that python succeeds to import this file.
|
| 53 |
+
# Deepspeed glue code will never inherit this dummy object as it checks if accelerate is available.
|
| 54 |
+
from builtins import object as DeepSpeedConfig
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class HfDeepSpeedConfig(DeepSpeedConfig):
|
| 58 |
+
"""
|
| 59 |
+
This object contains a DeepSpeed configuration dictionary and can be quickly queried for things like zero stage.
|
| 60 |
+
|
| 61 |
+
A `weakref` of this object is stored in the module's globals to be able to access the config from areas where
|
| 62 |
+
things like the Trainer object is not available (e.g. `from_pretrained` and `_get_resized_embeddings`). Therefore
|
| 63 |
+
it's important that this object remains alive while the program is still running.
|
| 64 |
+
|
| 65 |
+
[`Trainer`] uses the `HfTrainerDeepSpeedConfig` subclass instead. That subclass has logic to sync the configuration
|
| 66 |
+
with values of [`TrainingArguments`] by replacing special placeholder values: `"auto"`. Without this special logic
|
| 67 |
+
the DeepSpeed configuration is not modified in any way.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
config_file_or_dict (`Union[str, Dict]`): path to DeepSpeed config file or dict.
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(self, config_file_or_dict):
|
| 75 |
+
# set global weakref object
|
| 76 |
+
set_hf_deepspeed_config(self)
|
| 77 |
+
dep_version_check("accelerate")
|
| 78 |
+
dep_version_check("deepspeed")
|
| 79 |
+
super().__init__(config_file_or_dict)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class HfTrainerDeepSpeedConfig(HfDeepSpeedConfig):
|
| 83 |
+
"""
|
| 84 |
+
The `HfTrainerDeepSpeedConfig` object is meant to be created during `TrainingArguments` object creation and has the
|
| 85 |
+
same lifespan as the latter.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
def __init__(self, config_file_or_dict):
|
| 89 |
+
super().__init__(config_file_or_dict)
|
| 90 |
+
self._dtype = None
|
| 91 |
+
self.mismatches = []
|
| 92 |
+
|
| 93 |
+
def dtype(self):
|
| 94 |
+
if self._dtype is None:
|
| 95 |
+
raise ValueError("trainer_config_process() wasn't called yet to tell dtype")
|
| 96 |
+
return self._dtype
|
| 97 |
+
|
| 98 |
+
def is_auto(self, ds_key_long):
|
| 99 |
+
val = self.get_value(ds_key_long)
|
| 100 |
+
if val is None:
|
| 101 |
+
return False
|
| 102 |
+
else:
|
| 103 |
+
return val == "auto"
|
| 104 |
+
|
| 105 |
+
def fill_match(self, ds_key_long, hf_val, hf_key=None, must_match=True):
|
| 106 |
+
"""
|
| 107 |
+
A utility method that massages the config file and can optionally verify that the values match.
|
| 108 |
+
|
| 109 |
+
1. Replace "auto" values with `TrainingArguments` value.
|
| 110 |
+
|
| 111 |
+
2. If it wasn't "auto" and `must_match` is true, then check that DS config matches Trainer
|
| 112 |
+
config values and if mismatched add the entry to `self.mismatched` - will assert during
|
| 113 |
+
`trainer_config_finalize` for one or more mismatches.
|
| 114 |
+
|
| 115 |
+
"""
|
| 116 |
+
config, ds_key = self.find_config_node(ds_key_long)
|
| 117 |
+
if config is None:
|
| 118 |
+
return
|
| 119 |
+
|
| 120 |
+
if config.get(ds_key) == "auto":
|
| 121 |
+
config[ds_key] = hf_val
|
| 122 |
+
return
|
| 123 |
+
|
| 124 |
+
if not must_match:
|
| 125 |
+
return
|
| 126 |
+
|
| 127 |
+
ds_val = config.get(ds_key)
|
| 128 |
+
if ds_val is not None and ds_val != hf_val:
|
| 129 |
+
self.mismatches.append(f"- ds {ds_key_long}={ds_val} vs hf {hf_key}={hf_val}")
|
| 130 |
+
|
| 131 |
+
fill_only = partialmethod(fill_match, must_match=False)
|
| 132 |
+
|
| 133 |
+
def trainer_config_process(self, args, auto_find_batch_size=False):
|
| 134 |
+
"""
|
| 135 |
+
Adjust the config with `TrainingArguments` values. This stage is run during `TrainingArguments` object
|
| 136 |
+
creation.
|
| 137 |
+
"""
|
| 138 |
+
# DeepSpeed does:
|
| 139 |
+
# train_batch_size = world_size * train_micro_batch_size_per_gpu * gradient_accumulation_steps
|
| 140 |
+
train_batch_size = args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps
|
| 141 |
+
self.fill_match(
|
| 142 |
+
"train_micro_batch_size_per_gpu",
|
| 143 |
+
args.per_device_train_batch_size,
|
| 144 |
+
"per_device_train_batch_size",
|
| 145 |
+
not auto_find_batch_size,
|
| 146 |
+
)
|
| 147 |
+
self.fill_match(
|
| 148 |
+
"gradient_accumulation_steps",
|
| 149 |
+
args.gradient_accumulation_steps,
|
| 150 |
+
"gradient_accumulation_steps",
|
| 151 |
+
)
|
| 152 |
+
self.fill_match(
|
| 153 |
+
"train_batch_size",
|
| 154 |
+
train_batch_size,
|
| 155 |
+
"train_batch_size (calculated)",
|
| 156 |
+
not auto_find_batch_size,
|
| 157 |
+
)
|
| 158 |
+
self.fill_match("gradient_clipping", args.max_grad_norm, "max_grad_norm")
|
| 159 |
+
|
| 160 |
+
self.fill_match("optimizer.params.lr", args.learning_rate, "learning_rate")
|
| 161 |
+
self.fill_match(
|
| 162 |
+
"optimizer.params.betas",
|
| 163 |
+
[args.adam_beta1, args.adam_beta2],
|
| 164 |
+
"adam_beta1+adam_beta2",
|
| 165 |
+
)
|
| 166 |
+
self.fill_match("optimizer.params.eps", args.adam_epsilon, "adam_epsilon")
|
| 167 |
+
self.fill_match("optimizer.params.weight_decay", args.weight_decay, "weight_decay")
|
| 168 |
+
|
| 169 |
+
self.fill_only("scheduler.params.warmup_min_lr", 0) # not a trainer arg
|
| 170 |
+
self.fill_match("scheduler.params.warmup_max_lr", args.learning_rate, "learning_rate")
|
| 171 |
+
# total_num_steps - will get set in trainer_config_finalize
|
| 172 |
+
|
| 173 |
+
# fp16
|
| 174 |
+
if args.fp16 or args.fp16_full_eval:
|
| 175 |
+
fp16_backend = "apex" if args.fp16_backend == "apex" else "amp"
|
| 176 |
+
else:
|
| 177 |
+
fp16_backend = None
|
| 178 |
+
|
| 179 |
+
if args.save_on_each_node:
|
| 180 |
+
# deepspeed uses shared storage by default. Let's override this setting if save_on_each_node == True
|
| 181 |
+
self.config["checkpoint"] = self.config.get("checkpoint", {})
|
| 182 |
+
self.config["checkpoint"]["use_node_local_storage"] = args.save_on_each_node
|
| 183 |
+
|
| 184 |
+
# amp: similar to the pytorch native amp - it has a bunch of optional params but we won't set
|
| 185 |
+
# any here unless the user did the work
|
| 186 |
+
self.fill_match(
|
| 187 |
+
"fp16.enabled",
|
| 188 |
+
((args.fp16 or args.fp16_full_eval) and fp16_backend == "amp"),
|
| 189 |
+
"fp16|fp16_full_eval+fp16_backend(amp)",
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
# apex: delegates amp work to apex (which needs to be available), but it cannot be used with any
|
| 193 |
+
# ZeRO features
|
| 194 |
+
self.fill_match("amp.enabled", fp16_backend == "apex", "fp16+fp16_backend(apex)")
|
| 195 |
+
self.fill_match("amp.opt_level", args.fp16_opt_level, "fp16_opt_level")
|
| 196 |
+
|
| 197 |
+
self.fill_match("bf16.enabled", (args.bf16 or args.bf16_full_eval), "bf16|bf16_full_eval")
|
| 198 |
+
|
| 199 |
+
# deepspeed's default mode is fp16 unless there is a config that says differently
|
| 200 |
+
if self.is_true("bf16.enabled"):
|
| 201 |
+
self._dtype = torch.bfloat16
|
| 202 |
+
elif self.is_false("fp16.enabled"):
|
| 203 |
+
self._dtype = torch.float32
|
| 204 |
+
else:
|
| 205 |
+
self._dtype = torch.float16
|
| 206 |
+
|
| 207 |
+
def trainer_config_finalize(self, args, model, num_training_steps):
|
| 208 |
+
"""
|
| 209 |
+
This stage is run after we have the model and know num_training_steps.
|
| 210 |
+
|
| 211 |
+
Now we can complete the configuration process.
|
| 212 |
+
"""
|
| 213 |
+
# zero
|
| 214 |
+
|
| 215 |
+
# deal with config keys that use `auto` value and rely on model's hidden_size
|
| 216 |
+
hidden_size_based_keys = [
|
| 217 |
+
"zero_optimization.reduce_bucket_size",
|
| 218 |
+
"zero_optimization.stage3_prefetch_bucket_size",
|
| 219 |
+
"zero_optimization.stage3_param_persistence_threshold",
|
| 220 |
+
]
|
| 221 |
+
hidden_size_auto_keys = [x for x in hidden_size_based_keys if self.is_auto(x)]
|
| 222 |
+
|
| 223 |
+
if len(hidden_size_auto_keys) > 0:
|
| 224 |
+
if hasattr(model.config, "hidden_size"):
|
| 225 |
+
hidden_size = model.config.hidden_size
|
| 226 |
+
elif hasattr(model.config, "hidden_sizes"):
|
| 227 |
+
# if there are many hidden sizes pick the largest one
|
| 228 |
+
hidden_size = max(model.config.hidden_sizes)
|
| 229 |
+
elif hasattr(model.config, "text_config") and hasattr(model.config.text_config, "hidden_size"):
|
| 230 |
+
hidden_size = model.config.text_config.hidden_size
|
| 231 |
+
elif hasattr(model.config, "text_config") and hasattr(model.config.text_config, "hidden_sizes"):
|
| 232 |
+
# if there are many hidden sizes pick the largest one
|
| 233 |
+
hidden_size = max(model.config.text_config.hidden_sizes)
|
| 234 |
+
else:
|
| 235 |
+
raise ValueError(
|
| 236 |
+
"The model's config file has neither `hidden_size` nor `hidden_sizes` entry, "
|
| 237 |
+
"therefore it's not possible to automatically fill out the following `auto` entries "
|
| 238 |
+
f"in the DeepSpeed config file: {hidden_size_auto_keys}. You can fix that by replacing "
|
| 239 |
+
"`auto` values for these keys with an integer value of your choice."
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
self.fill_only("zero_optimization.reduce_bucket_size", hidden_size * hidden_size)
|
| 243 |
+
if self.is_zero3():
|
| 244 |
+
# automatically assign the optimal config values based on model config
|
| 245 |
+
self.fill_only(
|
| 246 |
+
"zero_optimization.stage3_prefetch_bucket_size",
|
| 247 |
+
int(0.9 * hidden_size * hidden_size),
|
| 248 |
+
)
|
| 249 |
+
self.fill_only(
|
| 250 |
+
"zero_optimization.stage3_param_persistence_threshold",
|
| 251 |
+
10 * hidden_size,
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
# scheduler
|
| 255 |
+
self.fill_match(
|
| 256 |
+
"scheduler.params.total_num_steps",
|
| 257 |
+
num_training_steps,
|
| 258 |
+
"num_training_steps (calculated)",
|
| 259 |
+
)
|
| 260 |
+
self.fill_match(
|
| 261 |
+
"scheduler.params.warmup_num_steps",
|
| 262 |
+
args.get_warmup_steps(num_training_steps),
|
| 263 |
+
"warmup_steps",
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
if len(self.mismatches) > 0:
|
| 267 |
+
mismatches = "\n".join(self.mismatches)
|
| 268 |
+
raise ValueError(
|
| 269 |
+
"Please correct the following DeepSpeed config values that mismatch TrainingArguments"
|
| 270 |
+
f" values:\n{mismatches}\nThe easiest method is to set these DeepSpeed config values to 'auto'."
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
# keep the config object global to be able to access it anywhere during TrainingArguments life-cycle
|
| 275 |
+
_hf_deepspeed_config_weak_ref = None
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def set_hf_deepspeed_config(hf_deepspeed_config_obj):
|
| 279 |
+
# this is a special weakref global object to allow us to get to Deepspeed config from APIs
|
| 280 |
+
# that don't have an easy way to get to the Deepspeed config outside of the Trainer domain.
|
| 281 |
+
global _hf_deepspeed_config_weak_ref
|
| 282 |
+
# will go away automatically when HfDeepSpeedConfig is destroyed (when TrainingArguments is destroyed)
|
| 283 |
+
_hf_deepspeed_config_weak_ref = weakref.ref(hf_deepspeed_config_obj)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def unset_hf_deepspeed_config():
|
| 287 |
+
# useful for unit tests to ensure the global state doesn't leak - call from `tearDown` method
|
| 288 |
+
global _hf_deepspeed_config_weak_ref
|
| 289 |
+
_hf_deepspeed_config_weak_ref = None
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def is_deepspeed_zero3_enabled():
|
| 293 |
+
if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
|
| 294 |
+
return _hf_deepspeed_config_weak_ref().is_zero3()
|
| 295 |
+
else:
|
| 296 |
+
return False
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def deepspeed_config():
|
| 300 |
+
if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
|
| 301 |
+
return _hf_deepspeed_config_weak_ref().config
|
| 302 |
+
else:
|
| 303 |
+
return None
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def _load_state_dict_into_zero3_model(model_to_load, state_dict):
|
| 307 |
+
"""
|
| 308 |
+
Loads state dict into a model specifically for Zero3, since DeepSpeed does not support the `transformers`
|
| 309 |
+
tensor parallelism API.
|
| 310 |
+
|
| 311 |
+
Nearly identical code to PyTorch's `_load_from_state_dict`
|
| 312 |
+
"""
|
| 313 |
+
# copy state_dict so `_load_state_dict_into_zero3_model` can modify it
|
| 314 |
+
metadata = getattr(state_dict, "_metadata", None)
|
| 315 |
+
state_dict = state_dict.copy()
|
| 316 |
+
if metadata is not None:
|
| 317 |
+
state_dict._metadata = metadata
|
| 318 |
+
|
| 319 |
+
error_msgs = []
|
| 320 |
+
|
| 321 |
+
# PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants
|
| 322 |
+
# so we need to apply the function recursively.
|
| 323 |
+
def load(module: nn.Module, state_dict, prefix="", assign_to_params_buffers=False):
|
| 324 |
+
local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
|
| 325 |
+
local_metadata["assign_to_params_buffers"] = assign_to_params_buffers
|
| 326 |
+
|
| 327 |
+
args = (state_dict, prefix, local_metadata, True, [], [], error_msgs)
|
| 328 |
+
# Parameters of module and children will start with prefix. We can exit early if there are none in this
|
| 329 |
+
# state_dict
|
| 330 |
+
if is_deepspeed_zero3_enabled() and len([key for key in state_dict if key.startswith(prefix)]) > 0:
|
| 331 |
+
import deepspeed
|
| 332 |
+
|
| 333 |
+
# In sharded models, each shard has only part of the full state_dict, so only gather
|
| 334 |
+
# parameters that are in the current state_dict.
|
| 335 |
+
named_parameters = dict(module.named_parameters(prefix=prefix[:-1], recurse=False))
|
| 336 |
+
params_to_gather = [named_parameters[k] for k in state_dict.keys() if k in named_parameters]
|
| 337 |
+
if len(params_to_gather) > 0:
|
| 338 |
+
# because zero3 puts placeholders in model params, this context
|
| 339 |
+
# manager gathers (unpartitions) the params of the current layer, then loads from
|
| 340 |
+
# the state dict and then re-partitions them again
|
| 341 |
+
with deepspeed.zero.GatheredParameters(params_to_gather, modifier_rank=0):
|
| 342 |
+
if torch.distributed.get_rank() == 0:
|
| 343 |
+
module._load_from_state_dict(*args)
|
| 344 |
+
|
| 345 |
+
for name, child in module._modules.items():
|
| 346 |
+
if child is not None:
|
| 347 |
+
load(child, state_dict, prefix + name + ".", assign_to_params_buffers)
|
| 348 |
+
|
| 349 |
+
load(model_to_load, state_dict, assign_to_params_buffers=False)
|
| 350 |
+
|
| 351 |
+
return error_msgs
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps, model_parameters):
|
| 355 |
+
"""
|
| 356 |
+
A convenience wrapper that deals with optimizer and lr scheduler configuration.
|
| 357 |
+
"""
|
| 358 |
+
from accelerate.utils import DummyOptim, DummyScheduler
|
| 359 |
+
|
| 360 |
+
config = hf_deepspeed_config.config
|
| 361 |
+
|
| 362 |
+
# Mixing and matching DS schedulers and optimizers is supported unless Offload is enabled in which case it's:
|
| 363 |
+
# 1. DS scheduler + DS optimizer: Yes
|
| 364 |
+
# 2. HF scheduler + HF optimizer: Mostly*
|
| 365 |
+
# 3. DS scheduler + HF optimizer: Mostly*
|
| 366 |
+
# 4. HF scheduler + DS optimizer: Yes
|
| 367 |
+
#
|
| 368 |
+
# Mostly*: All non-native DeepSpeed optimizers that have both CPU and GPU implementation should work (except LAMB)
|
| 369 |
+
|
| 370 |
+
optimizer = None
|
| 371 |
+
if "optimizer" in config:
|
| 372 |
+
if args.adafactor:
|
| 373 |
+
raise ValueError(
|
| 374 |
+
"--adafactor was passed, but also found `optimizer` configured in the DeepSpeed config. "
|
| 375 |
+
"Only one optimizer can be configured."
|
| 376 |
+
)
|
| 377 |
+
optimizer = DummyOptim(params=model_parameters)
|
| 378 |
+
else:
|
| 379 |
+
if hf_deepspeed_config.is_offload():
|
| 380 |
+
logger.info(
|
| 381 |
+
"Detected ZeRO Offload and non-DeepSpeed optimizers: This combination should work as long as the"
|
| 382 |
+
" custom optimizer has both CPU and GPU implementation (except LAMB)"
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
# ds supports Adam, OneBitAdam, and Lamb optimizers and can import other optimizers from torch.
|
| 386 |
+
# But trainer uses AdamW by default.
|
| 387 |
+
optimizer = trainer.create_optimizer()
|
| 388 |
+
# To use other optimizers requires voiding warranty with: `zero_allow_untested_optimizer`
|
| 389 |
+
config["zero_allow_untested_optimizer"] = True
|
| 390 |
+
|
| 391 |
+
lr_scheduler = None
|
| 392 |
+
if "scheduler" in config:
|
| 393 |
+
lr_scheduler = DummyScheduler(optimizer)
|
| 394 |
+
else:
|
| 395 |
+
if isinstance(optimizer, DummyOptim):
|
| 396 |
+
|
| 397 |
+
def _lr_scheduler_callable(optimizer):
|
| 398 |
+
# create a shallow copy first, so later modifications do not affect original trainer
|
| 399 |
+
trainer_copy = copy.copy(trainer)
|
| 400 |
+
# at the time _lr_scheduler_callable is called, trainer.lr_scheduler has been set
|
| 401 |
+
# update it to None so that we can re-create a new scheduler
|
| 402 |
+
trainer_copy.lr_scheduler = None
|
| 403 |
+
lr_scheduler = trainer_copy.create_scheduler(
|
| 404 |
+
num_training_steps=num_training_steps, optimizer=optimizer
|
| 405 |
+
)
|
| 406 |
+
return lr_scheduler
|
| 407 |
+
|
| 408 |
+
lr_scheduler = DummyScheduler(optimizer, lr_scheduler_callable=_lr_scheduler_callable)
|
| 409 |
+
else:
|
| 410 |
+
lr_scheduler = trainer.create_scheduler(num_training_steps=num_training_steps, optimizer=optimizer)
|
| 411 |
+
|
| 412 |
+
return optimizer, lr_scheduler
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def deepspeed_init(trainer, num_training_steps, inference=False):
|
| 416 |
+
"""
|
| 417 |
+
Init DeepSpeed, after updating the DeepSpeed configuration with any relevant Trainer's args.
|
| 418 |
+
|
| 419 |
+
If `resume_from_checkpoint` was passed then an attempt to resume from a previously saved checkpoint will be made.
|
| 420 |
+
|
| 421 |
+
Args:
|
| 422 |
+
trainer: Trainer object
|
| 423 |
+
num_training_steps: per single gpu
|
| 424 |
+
resume_from_checkpoint: path to a checkpoint if to resume from after normal DeepSpeedEngine load
|
| 425 |
+
inference: launch in inference mode (no optimizer and no lr scheduler)
|
| 426 |
+
auto_find_batch_size: whether to ignore the `train_micro_batch_size_per_gpu` argument as it's being
|
| 427 |
+
set automatically by the auto batch size finder
|
| 428 |
+
|
| 429 |
+
Returns: optimizer, lr_scheduler
|
| 430 |
+
|
| 431 |
+
We may use `deepspeed_init` more than once during the life of Trainer, when we do - it's a temp hack based on:
|
| 432 |
+
https://github.com/deepspeedai/DeepSpeed/issues/1394#issuecomment-937405374 until Deepspeed fixes a bug where it
|
| 433 |
+
can't resume from a checkpoint after it did some stepping https://github.com/deepspeedai/DeepSpeed/issues/1612
|
| 434 |
+
|
| 435 |
+
"""
|
| 436 |
+
from deepspeed.utils import logger as ds_logger
|
| 437 |
+
|
| 438 |
+
model = trainer.model
|
| 439 |
+
args = trainer.args
|
| 440 |
+
|
| 441 |
+
hf_deepspeed_config = trainer.accelerator.state.deepspeed_plugin.hf_ds_config
|
| 442 |
+
|
| 443 |
+
# resume config update - some bits like `model` and `num_training_steps` only become available during train
|
| 444 |
+
hf_deepspeed_config.trainer_config_finalize(args, model, num_training_steps)
|
| 445 |
+
|
| 446 |
+
# set the Deepspeed log level consistent with the Trainer
|
| 447 |
+
ds_logger.setLevel(args.get_process_log_level())
|
| 448 |
+
|
| 449 |
+
if inference:
|
| 450 |
+
# only Z3 makes sense for the inference
|
| 451 |
+
if not hf_deepspeed_config.is_zero3():
|
| 452 |
+
raise ValueError("ZeRO inference only makes sense with ZeRO Stage 3 - please adjust your config")
|
| 453 |
+
|
| 454 |
+
# in case the training config is re-used for inference
|
| 455 |
+
hf_deepspeed_config.del_config_sub_tree("optimizer")
|
| 456 |
+
hf_deepspeed_config.del_config_sub_tree("lr_scheduler")
|
| 457 |
+
optimizer, lr_scheduler = None, None
|
| 458 |
+
model_parameters = None
|
| 459 |
+
else:
|
| 460 |
+
trainer.optimizer = None # important for when deepspeed_init is used as re-init
|
| 461 |
+
tp_size = hf_deepspeed_config.config.get("tensor_parallel", {}).get("autotp_size", 0)
|
| 462 |
+
if tp_size > 1:
|
| 463 |
+
import deepspeed
|
| 464 |
+
|
| 465 |
+
model = deepspeed.tp_model_init(model=model, tp_size=tp_size, dtype=hf_deepspeed_config.dtype())
|
| 466 |
+
model_parameters = list(filter(lambda p: p.requires_grad, model.parameters()))
|
| 467 |
+
optimizer, lr_scheduler = deepspeed_optim_sched(
|
| 468 |
+
trainer, hf_deepspeed_config, args, num_training_steps, model_parameters
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
# keep for quick debug:
|
| 472 |
+
# from pprint import pprint; pprint(config)
|
| 473 |
+
|
| 474 |
+
return optimizer, lr_scheduler
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def deepspeed_load_checkpoint(deepspeed_engine, checkpoint_path, load_module_strict=True):
|
| 478 |
+
# it's possible that the user is trying to resume from model_path, which doesn't necessarily
|
| 479 |
+
# contain a deepspeed checkpoint. e.g. examples just check if the dir exists and assume it's
|
| 480 |
+
# a resume from a checkpoint and not just a local pretrained weight. So we check here if the
|
| 481 |
+
# path contains what looks like a deepspeed checkpoint
|
| 482 |
+
import glob
|
| 483 |
+
|
| 484 |
+
deepspeed_checkpoint_dirs = sorted(glob.glob(f"{checkpoint_path}/global_step*"))
|
| 485 |
+
|
| 486 |
+
if len(deepspeed_checkpoint_dirs) > 0:
|
| 487 |
+
logger.info(f"Attempting to resume from {checkpoint_path}")
|
| 488 |
+
# this magically updates self.optimizer and self.lr_scheduler
|
| 489 |
+
load_path, _ = deepspeed_engine.load_checkpoint(
|
| 490 |
+
checkpoint_path,
|
| 491 |
+
load_module_strict=load_module_strict,
|
| 492 |
+
load_optimizer_states=True,
|
| 493 |
+
load_lr_scheduler_states=True,
|
| 494 |
+
)
|
| 495 |
+
if load_path is None:
|
| 496 |
+
raise ValueError(f"[deepspeed] failed to resume from checkpoint {checkpoint_path}")
|
| 497 |
+
else:
|
| 498 |
+
raise ValueError(f"Can't find a valid checkpoint at {checkpoint_path}")
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/dependency_versions_check.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 .dependency_versions_table import deps
|
| 16 |
+
from .utils.versions import require_version, require_version_core
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# define which module versions we always want to check at run time
|
| 20 |
+
# (usually the ones defined in `install_requires` in setup.py)
|
| 21 |
+
#
|
| 22 |
+
# order specific notes:
|
| 23 |
+
# - tqdm must be checked before tokenizers
|
| 24 |
+
|
| 25 |
+
pkgs_to_check_at_runtime = [
|
| 26 |
+
"python",
|
| 27 |
+
"tqdm",
|
| 28 |
+
"regex",
|
| 29 |
+
"requests",
|
| 30 |
+
"packaging",
|
| 31 |
+
"filelock",
|
| 32 |
+
"numpy",
|
| 33 |
+
"tokenizers",
|
| 34 |
+
"huggingface-hub",
|
| 35 |
+
"safetensors",
|
| 36 |
+
"accelerate",
|
| 37 |
+
"pyyaml",
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
for pkg in pkgs_to_check_at_runtime:
|
| 41 |
+
if pkg in deps:
|
| 42 |
+
if pkg == "tokenizers":
|
| 43 |
+
# must be loaded here, or else tqdm check may fail
|
| 44 |
+
from .utils import is_tokenizers_available
|
| 45 |
+
|
| 46 |
+
if not is_tokenizers_available():
|
| 47 |
+
continue # not required, check version only if installed
|
| 48 |
+
elif pkg == "accelerate":
|
| 49 |
+
# must be loaded here, or else tqdm check may fail
|
| 50 |
+
from .utils import is_accelerate_available
|
| 51 |
+
|
| 52 |
+
# Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of
|
| 53 |
+
# Transformers with PyTorch
|
| 54 |
+
if not is_accelerate_available():
|
| 55 |
+
continue # not required, check version only if installed
|
| 56 |
+
|
| 57 |
+
require_version_core(deps[pkg])
|
| 58 |
+
else:
|
| 59 |
+
raise ValueError(f"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def dep_version_check(pkg, hint=None):
|
| 63 |
+
require_version(deps[pkg], hint)
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/dependency_versions_table.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# THIS FILE HAS BEEN AUTOGENERATED. To update:
|
| 2 |
+
# 1. modify the `_deps` dict in setup.py
|
| 3 |
+
# 2. run `make deps_table_update``
|
| 4 |
+
deps = {
|
| 5 |
+
"Pillow": "Pillow>=10.0.1,<=15.0",
|
| 6 |
+
"accelerate": "accelerate>=0.26.0",
|
| 7 |
+
"av": "av",
|
| 8 |
+
"beautifulsoup4": "beautifulsoup4",
|
| 9 |
+
"blobfile": "blobfile",
|
| 10 |
+
"codecarbon": "codecarbon>=2.8.1",
|
| 11 |
+
"cookiecutter": "cookiecutter==1.7.3",
|
| 12 |
+
"dataclasses": "dataclasses",
|
| 13 |
+
"datasets": "datasets!=2.5.0",
|
| 14 |
+
"deepspeed": "deepspeed>=0.9.3",
|
| 15 |
+
"diffusers": "diffusers",
|
| 16 |
+
"dill": "dill<0.3.5",
|
| 17 |
+
"evaluate": "evaluate>=0.2.0",
|
| 18 |
+
"faiss-cpu": "faiss-cpu",
|
| 19 |
+
"fastapi": "fastapi",
|
| 20 |
+
"filelock": "filelock",
|
| 21 |
+
"flax": "flax>=0.4.1,<=0.7.0",
|
| 22 |
+
"fsspec": "fsspec<2023.10.0",
|
| 23 |
+
"ftfy": "ftfy",
|
| 24 |
+
"fugashi": "fugashi>=1.0",
|
| 25 |
+
"GitPython": "GitPython<3.1.19",
|
| 26 |
+
"hf-doc-builder": "hf-doc-builder>=0.3.0",
|
| 27 |
+
"hf_xet": "hf_xet",
|
| 28 |
+
"huggingface-hub": "huggingface-hub>=0.30.0,<1.0",
|
| 29 |
+
"importlib_metadata": "importlib_metadata",
|
| 30 |
+
"ipadic": "ipadic>=1.0.0,<2.0",
|
| 31 |
+
"isort": "isort>=5.5.4",
|
| 32 |
+
"jax": "jax>=0.4.1,<=0.4.13",
|
| 33 |
+
"jaxlib": "jaxlib>=0.4.1,<=0.4.13",
|
| 34 |
+
"jieba": "jieba",
|
| 35 |
+
"jinja2": "jinja2>=3.1.0",
|
| 36 |
+
"kenlm@git+https://github.com/ydshieh/kenlm@78f664fb3dafe1468d868d71faf19534530698d5": "kenlm@git+https://github.com/ydshieh/kenlm@78f664fb3dafe1468d868d71faf19534530698d5",
|
| 37 |
+
"keras": "keras>2.9,<2.16",
|
| 38 |
+
"keras-nlp": "keras-nlp>=0.3.1,<0.14.0",
|
| 39 |
+
"kernels": "kernels>=0.3.2,<0.4",
|
| 40 |
+
"librosa": "librosa",
|
| 41 |
+
"natten": "natten>=0.14.6,<0.15.0",
|
| 42 |
+
"nltk": "nltk<=3.8.1",
|
| 43 |
+
"num2words": "num2words",
|
| 44 |
+
"numpy": "numpy>=1.17",
|
| 45 |
+
"onnxconverter-common": "onnxconverter-common",
|
| 46 |
+
"onnxruntime-tools": "onnxruntime-tools>=1.4.2",
|
| 47 |
+
"onnxruntime": "onnxruntime>=1.4.0",
|
| 48 |
+
"opencv-python": "opencv-python",
|
| 49 |
+
"optimum-benchmark": "optimum-benchmark>=0.3.0",
|
| 50 |
+
"optuna": "optuna",
|
| 51 |
+
"optax": "optax>=0.0.8,<=0.1.4",
|
| 52 |
+
"packaging": "packaging>=20.0",
|
| 53 |
+
"parameterized": "parameterized",
|
| 54 |
+
"phonemizer": "phonemizer",
|
| 55 |
+
"protobuf": "protobuf",
|
| 56 |
+
"psutil": "psutil",
|
| 57 |
+
"pyyaml": "pyyaml>=5.1",
|
| 58 |
+
"pydantic": "pydantic",
|
| 59 |
+
"pytest": "pytest>=7.2.0,<8.0.0",
|
| 60 |
+
"pytest-asyncio": "pytest-asyncio",
|
| 61 |
+
"pytest-rerunfailures": "pytest-rerunfailures",
|
| 62 |
+
"pytest-timeout": "pytest-timeout",
|
| 63 |
+
"pytest-xdist": "pytest-xdist",
|
| 64 |
+
"pytest-order": "pytest-order",
|
| 65 |
+
"python": "python>=3.9.0",
|
| 66 |
+
"ray[tune]": "ray[tune]>=2.7.0",
|
| 67 |
+
"regex": "regex!=2019.12.17",
|
| 68 |
+
"requests": "requests",
|
| 69 |
+
"rhoknp": "rhoknp>=1.1.0,<1.3.1",
|
| 70 |
+
"rjieba": "rjieba",
|
| 71 |
+
"rouge-score": "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1",
|
| 72 |
+
"ruff": "ruff==0.11.2",
|
| 73 |
+
"sacrebleu": "sacrebleu>=1.4.12,<2.0.0",
|
| 74 |
+
"sacremoses": "sacremoses",
|
| 75 |
+
"safetensors": "safetensors>=0.4.3",
|
| 76 |
+
"sagemaker": "sagemaker>=2.31.0",
|
| 77 |
+
"schedulefree": "schedulefree>=1.2.6",
|
| 78 |
+
"scikit-learn": "scikit-learn",
|
| 79 |
+
"scipy": "scipy<1.13.0",
|
| 80 |
+
"sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
|
| 81 |
+
"sigopt": "sigopt",
|
| 82 |
+
"starlette": "starlette",
|
| 83 |
+
"sudachipy": "sudachipy>=0.6.6",
|
| 84 |
+
"sudachidict_core": "sudachidict_core>=20220729",
|
| 85 |
+
"tensorboard": "tensorboard",
|
| 86 |
+
"tensorflow-cpu": "tensorflow-cpu>2.9,<2.16",
|
| 87 |
+
"tensorflow": "tensorflow>2.9,<2.16",
|
| 88 |
+
"tensorflow-text": "tensorflow-text<2.16",
|
| 89 |
+
"tensorflow-probability": "tensorflow-probability<0.24",
|
| 90 |
+
"tf2onnx": "tf2onnx",
|
| 91 |
+
"timeout-decorator": "timeout-decorator",
|
| 92 |
+
"tiktoken": "tiktoken",
|
| 93 |
+
"timm": "timm<=1.0.11",
|
| 94 |
+
"tokenizers": "tokenizers>=0.21,<0.22",
|
| 95 |
+
"torch": "torch>=2.0",
|
| 96 |
+
"torchaudio": "torchaudio",
|
| 97 |
+
"torchvision": "torchvision",
|
| 98 |
+
"pyctcdecode": "pyctcdecode>=0.4.0",
|
| 99 |
+
"tqdm": "tqdm>=4.27",
|
| 100 |
+
"unidic": "unidic>=1.0.2",
|
| 101 |
+
"unidic_lite": "unidic_lite>=1.0.7",
|
| 102 |
+
"urllib3": "urllib3<2.0.0",
|
| 103 |
+
"uvicorn": "uvicorn",
|
| 104 |
+
"pytest-rich": "pytest-rich",
|
| 105 |
+
"libcst": "libcst",
|
| 106 |
+
"rich": "rich",
|
| 107 |
+
}
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/deprecation.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
import inspect
|
| 15 |
+
import warnings
|
| 16 |
+
from functools import wraps
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
import packaging.version
|
| 20 |
+
|
| 21 |
+
from .. import __version__
|
| 22 |
+
from . import ExplicitEnum, is_torch_available, is_torchdynamo_compiling
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# This is needed in case we deprecate a kwarg of a function/method being compiled
|
| 26 |
+
if is_torch_available():
|
| 27 |
+
import torch # noqa: F401
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Action(ExplicitEnum):
|
| 31 |
+
NONE = "none"
|
| 32 |
+
NOTIFY = "notify"
|
| 33 |
+
NOTIFY_ALWAYS = "notify_always"
|
| 34 |
+
RAISE = "raise"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def deprecate_kwarg(
|
| 38 |
+
old_name: str,
|
| 39 |
+
version: str,
|
| 40 |
+
new_name: Optional[str] = None,
|
| 41 |
+
warn_if_greater_or_equal_version: bool = False,
|
| 42 |
+
raise_if_greater_or_equal_version: bool = False,
|
| 43 |
+
raise_if_both_names: bool = False,
|
| 44 |
+
additional_message: Optional[str] = None,
|
| 45 |
+
):
|
| 46 |
+
"""
|
| 47 |
+
Function or method decorator to notify users about deprecated keyword arguments, replacing them with a new name if specified.
|
| 48 |
+
Note that is decorator is `torch.compile`-safe, i.e. it will not cause graph breaks (but no warning will be displayed if compiling).
|
| 49 |
+
|
| 50 |
+
This decorator allows you to:
|
| 51 |
+
- Notify users when a keyword argument is deprecated.
|
| 52 |
+
- Automatically replace deprecated keyword arguments with new ones.
|
| 53 |
+
- Raise an error if deprecated arguments are used, depending on the specified conditions.
|
| 54 |
+
|
| 55 |
+
By default, the decorator notifies the user about the deprecated argument while the `transformers.__version__` < specified `version`
|
| 56 |
+
in the decorator. To keep notifications with any version `warn_if_greater_or_equal_version=True` can be set.
|
| 57 |
+
|
| 58 |
+
Parameters:
|
| 59 |
+
old_name (`str`):
|
| 60 |
+
Name of the deprecated keyword argument.
|
| 61 |
+
version (`str`):
|
| 62 |
+
The version in which the keyword argument was (or will be) deprecated.
|
| 63 |
+
new_name (`Optional[str]`, *optional*):
|
| 64 |
+
The new name for the deprecated keyword argument. If specified, the deprecated keyword argument will be replaced with this new name.
|
| 65 |
+
warn_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`):
|
| 66 |
+
Whether to show warning if current `transformers` version is greater or equal to the deprecated version.
|
| 67 |
+
raise_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`):
|
| 68 |
+
Whether to raise `ValueError` if current `transformers` version is greater or equal to the deprecated version.
|
| 69 |
+
raise_if_both_names (`bool`, *optional*, defaults to `False`):
|
| 70 |
+
Whether to raise `ValueError` if both deprecated and new keyword arguments are set.
|
| 71 |
+
additional_message (`Optional[str]`, *optional*):
|
| 72 |
+
An additional message to append to the default deprecation message.
|
| 73 |
+
|
| 74 |
+
Raises:
|
| 75 |
+
ValueError:
|
| 76 |
+
If raise_if_greater_or_equal_version is True and the current version is greater than or equal to the deprecated version, or if raise_if_both_names is True and both old and new keyword arguments are provided.
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
Callable:
|
| 80 |
+
A wrapped function that handles the deprecated keyword arguments according to the specified parameters.
|
| 81 |
+
|
| 82 |
+
Example usage with renaming argument:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
@deprecate_kwarg("reduce_labels", new_name="do_reduce_labels", version="6.0.0")
|
| 86 |
+
def my_function(do_reduce_labels):
|
| 87 |
+
print(do_reduce_labels)
|
| 88 |
+
|
| 89 |
+
my_function(reduce_labels=True) # Will show a deprecation warning and use do_reduce_labels=True
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
Example usage without renaming argument:
|
| 93 |
+
|
| 94 |
+
```python
|
| 95 |
+
@deprecate_kwarg("max_size", version="6.0.0")
|
| 96 |
+
def my_function(max_size):
|
| 97 |
+
print(max_size)
|
| 98 |
+
|
| 99 |
+
my_function(max_size=1333) # Will show a deprecation warning
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
deprecated_version = packaging.version.parse(version)
|
| 105 |
+
current_version = packaging.version.parse(__version__)
|
| 106 |
+
is_greater_or_equal_version = current_version >= deprecated_version
|
| 107 |
+
|
| 108 |
+
if is_greater_or_equal_version:
|
| 109 |
+
version_message = f"and removed starting from version {version}"
|
| 110 |
+
else:
|
| 111 |
+
version_message = f"and will be removed in version {version}"
|
| 112 |
+
|
| 113 |
+
def wrapper(func):
|
| 114 |
+
# Required for better warning message
|
| 115 |
+
sig = inspect.signature(func)
|
| 116 |
+
function_named_args = set(sig.parameters.keys())
|
| 117 |
+
is_instance_method = "self" in function_named_args
|
| 118 |
+
is_class_method = "cls" in function_named_args
|
| 119 |
+
|
| 120 |
+
@wraps(func)
|
| 121 |
+
def wrapped_func(*args, **kwargs):
|
| 122 |
+
# Get class + function name (just for better warning message)
|
| 123 |
+
func_name = func.__name__
|
| 124 |
+
if is_instance_method:
|
| 125 |
+
func_name = f"{args[0].__class__.__name__}.{func_name}"
|
| 126 |
+
elif is_class_method:
|
| 127 |
+
func_name = f"{args[0].__name__}.{func_name}"
|
| 128 |
+
|
| 129 |
+
minimum_action = Action.NONE
|
| 130 |
+
message = None
|
| 131 |
+
|
| 132 |
+
# deprecated kwarg and its new version are set for function call -> replace it with new name
|
| 133 |
+
if old_name in kwargs and new_name in kwargs:
|
| 134 |
+
minimum_action = Action.RAISE if raise_if_both_names else Action.NOTIFY_ALWAYS
|
| 135 |
+
message = f"Both `{old_name}` and `{new_name}` are set for `{func_name}`. Using `{new_name}={kwargs[new_name]}` and ignoring deprecated `{old_name}={kwargs[old_name]}`."
|
| 136 |
+
kwargs.pop(old_name)
|
| 137 |
+
|
| 138 |
+
# only deprecated kwarg is set for function call -> replace it with new name
|
| 139 |
+
elif old_name in kwargs and new_name is not None and new_name not in kwargs:
|
| 140 |
+
minimum_action = Action.NOTIFY
|
| 141 |
+
message = f"`{old_name}` is deprecated {version_message} for `{func_name}`. Use `{new_name}` instead."
|
| 142 |
+
kwargs[new_name] = kwargs.pop(old_name)
|
| 143 |
+
|
| 144 |
+
# deprecated kwarg is not set for function call and new name is not specified -> just notify
|
| 145 |
+
elif old_name in kwargs:
|
| 146 |
+
minimum_action = Action.NOTIFY
|
| 147 |
+
message = f"`{old_name}` is deprecated {version_message} for `{func_name}`."
|
| 148 |
+
|
| 149 |
+
if message is not None and additional_message is not None:
|
| 150 |
+
message = f"{message} {additional_message}"
|
| 151 |
+
|
| 152 |
+
# update minimum_action if argument is ALREADY deprecated (current version >= deprecated version)
|
| 153 |
+
if is_greater_or_equal_version:
|
| 154 |
+
# change to (NOTIFY, NOTIFY_ALWAYS) -> RAISE if specified
|
| 155 |
+
# in case we want to raise error for already deprecated arguments
|
| 156 |
+
if raise_if_greater_or_equal_version and minimum_action != Action.NONE:
|
| 157 |
+
minimum_action = Action.RAISE
|
| 158 |
+
|
| 159 |
+
# change to NOTIFY -> NONE if specified (NOTIFY_ALWAYS can't be changed to NONE)
|
| 160 |
+
# in case we want to ignore notifications for already deprecated arguments
|
| 161 |
+
elif not warn_if_greater_or_equal_version and minimum_action == Action.NOTIFY:
|
| 162 |
+
minimum_action = Action.NONE
|
| 163 |
+
|
| 164 |
+
# raise error or notify user
|
| 165 |
+
if minimum_action == Action.RAISE:
|
| 166 |
+
raise ValueError(message)
|
| 167 |
+
# If we are compiling, we do not raise the warning as it would break compilation
|
| 168 |
+
elif minimum_action in (Action.NOTIFY, Action.NOTIFY_ALWAYS) and not is_torchdynamo_compiling():
|
| 169 |
+
# DeprecationWarning is ignored by default, so we use FutureWarning instead
|
| 170 |
+
warnings.warn(message, FutureWarning, stacklevel=2)
|
| 171 |
+
|
| 172 |
+
return func(*args, **kwargs)
|
| 173 |
+
|
| 174 |
+
return wrapped_func
|
| 175 |
+
|
| 176 |
+
return wrapper
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/doc.py
ADDED
|
@@ -0,0 +1,1218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""
|
| 15 |
+
Doc utilities: Utilities related to documentation
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import functools
|
| 19 |
+
import inspect
|
| 20 |
+
import re
|
| 21 |
+
import textwrap
|
| 22 |
+
import types
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_docstring_indentation_level(func):
|
| 26 |
+
"""Return the indentation level of the start of the docstring of a class or function (or method)."""
|
| 27 |
+
# We assume classes are always defined in the global scope
|
| 28 |
+
if inspect.isclass(func):
|
| 29 |
+
return 4
|
| 30 |
+
source = inspect.getsource(func)
|
| 31 |
+
first_line = source.splitlines()[0]
|
| 32 |
+
function_def_level = len(first_line) - len(first_line.lstrip())
|
| 33 |
+
return 4 + function_def_level
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def add_start_docstrings(*docstr):
|
| 37 |
+
def docstring_decorator(fn):
|
| 38 |
+
fn.__doc__ = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
|
| 39 |
+
return fn
|
| 40 |
+
|
| 41 |
+
return docstring_decorator
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def add_start_docstrings_to_model_forward(*docstr):
|
| 45 |
+
def docstring_decorator(fn):
|
| 46 |
+
class_name = f"[`{fn.__qualname__.split('.')[0]}`]"
|
| 47 |
+
intro = rf""" The {class_name} forward method, overrides the `__call__` special method.
|
| 48 |
+
|
| 49 |
+
<Tip>
|
| 50 |
+
|
| 51 |
+
Although the recipe for forward pass needs to be defined within this function, one should call the [`Module`]
|
| 52 |
+
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
|
| 53 |
+
the latter silently ignores them.
|
| 54 |
+
|
| 55 |
+
</Tip>
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
correct_indentation = get_docstring_indentation_level(fn)
|
| 59 |
+
current_doc = fn.__doc__ if fn.__doc__ is not None else ""
|
| 60 |
+
try:
|
| 61 |
+
first_non_empty = next(line for line in current_doc.splitlines() if line.strip() != "")
|
| 62 |
+
doc_indentation = len(first_non_empty) - len(first_non_empty.lstrip())
|
| 63 |
+
except StopIteration:
|
| 64 |
+
doc_indentation = correct_indentation
|
| 65 |
+
|
| 66 |
+
docs = docstr
|
| 67 |
+
# In this case, the correct indentation level (class method, 2 Python levels) was respected, and we should
|
| 68 |
+
# correctly reindent everything. Otherwise, the doc uses a single indentation level
|
| 69 |
+
if doc_indentation == 4 + correct_indentation:
|
| 70 |
+
docs = [textwrap.indent(textwrap.dedent(doc), " " * correct_indentation) for doc in docstr]
|
| 71 |
+
intro = textwrap.indent(textwrap.dedent(intro), " " * correct_indentation)
|
| 72 |
+
|
| 73 |
+
docstring = "".join(docs) + current_doc
|
| 74 |
+
fn.__doc__ = intro + docstring
|
| 75 |
+
return fn
|
| 76 |
+
|
| 77 |
+
return docstring_decorator
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def add_end_docstrings(*docstr):
|
| 81 |
+
def docstring_decorator(fn):
|
| 82 |
+
fn.__doc__ = (fn.__doc__ if fn.__doc__ is not None else "") + "".join(docstr)
|
| 83 |
+
return fn
|
| 84 |
+
|
| 85 |
+
return docstring_decorator
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
PT_RETURN_INTRODUCTION = r"""
|
| 89 |
+
Returns:
|
| 90 |
+
[`{full_output_type}`] or `tuple(torch.FloatTensor)`: A [`{full_output_type}`] or a tuple of
|
| 91 |
+
`torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
|
| 92 |
+
elements depending on the configuration ([`{config_class}`]) and inputs.
|
| 93 |
+
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
TF_RETURN_INTRODUCTION = r"""
|
| 98 |
+
Returns:
|
| 99 |
+
[`{full_output_type}`] or `tuple(tf.Tensor)`: A [`{full_output_type}`] or a tuple of `tf.Tensor` (if
|
| 100 |
+
`return_dict=False` is passed or when `config.return_dict=False`) comprising various elements depending on the
|
| 101 |
+
configuration ([`{config_class}`]) and inputs.
|
| 102 |
+
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _get_indent(t):
|
| 107 |
+
"""Returns the indentation in the first line of t"""
|
| 108 |
+
search = re.search(r"^(\s*)\S", t)
|
| 109 |
+
return "" if search is None else search.groups()[0]
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _convert_output_args_doc(output_args_doc):
|
| 113 |
+
"""Convert output_args_doc to display properly."""
|
| 114 |
+
# Split output_arg_doc in blocks argument/description
|
| 115 |
+
indent = _get_indent(output_args_doc)
|
| 116 |
+
blocks = []
|
| 117 |
+
current_block = ""
|
| 118 |
+
for line in output_args_doc.split("\n"):
|
| 119 |
+
# If the indent is the same as the beginning, the line is the name of new arg.
|
| 120 |
+
if _get_indent(line) == indent:
|
| 121 |
+
if len(current_block) > 0:
|
| 122 |
+
blocks.append(current_block[:-1])
|
| 123 |
+
current_block = f"{line}\n"
|
| 124 |
+
else:
|
| 125 |
+
# Otherwise it's part of the description of the current arg.
|
| 126 |
+
# We need to remove 2 spaces to the indentation.
|
| 127 |
+
current_block += f"{line[2:]}\n"
|
| 128 |
+
blocks.append(current_block[:-1])
|
| 129 |
+
|
| 130 |
+
# Format each block for proper rendering
|
| 131 |
+
for i in range(len(blocks)):
|
| 132 |
+
blocks[i] = re.sub(r"^(\s+)(\S+)(\s+)", r"\1- **\2**\3", blocks[i])
|
| 133 |
+
blocks[i] = re.sub(r":\s*\n\s*(\S)", r" -- \1", blocks[i])
|
| 134 |
+
|
| 135 |
+
return "\n".join(blocks)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _prepare_output_docstrings(output_type, config_class, min_indent=None):
|
| 139 |
+
"""
|
| 140 |
+
Prepares the return part of the docstring using `output_type`.
|
| 141 |
+
"""
|
| 142 |
+
output_docstring = output_type.__doc__
|
| 143 |
+
|
| 144 |
+
# Remove the head of the docstring to keep the list of args only
|
| 145 |
+
lines = output_docstring.split("\n")
|
| 146 |
+
i = 0
|
| 147 |
+
while i < len(lines) and re.search(r"^\s*(Args|Parameters):\s*$", lines[i]) is None:
|
| 148 |
+
i += 1
|
| 149 |
+
if i < len(lines):
|
| 150 |
+
params_docstring = "\n".join(lines[(i + 1) :])
|
| 151 |
+
params_docstring = _convert_output_args_doc(params_docstring)
|
| 152 |
+
else:
|
| 153 |
+
raise ValueError(
|
| 154 |
+
f"No `Args` or `Parameters` section is found in the docstring of `{output_type.__name__}`. Make sure it has "
|
| 155 |
+
"docstring and contain either `Args` or `Parameters`."
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
# Add the return introduction
|
| 159 |
+
full_output_type = f"{output_type.__module__}.{output_type.__name__}"
|
| 160 |
+
intro = TF_RETURN_INTRODUCTION if output_type.__name__.startswith("TF") else PT_RETURN_INTRODUCTION
|
| 161 |
+
intro = intro.format(full_output_type=full_output_type, config_class=config_class)
|
| 162 |
+
result = intro + params_docstring
|
| 163 |
+
|
| 164 |
+
# Apply minimum indent if necessary
|
| 165 |
+
if min_indent is not None:
|
| 166 |
+
lines = result.split("\n")
|
| 167 |
+
# Find the indent of the first nonempty line
|
| 168 |
+
i = 0
|
| 169 |
+
while len(lines[i]) == 0:
|
| 170 |
+
i += 1
|
| 171 |
+
indent = len(_get_indent(lines[i]))
|
| 172 |
+
# If too small, add indentation to all nonempty lines
|
| 173 |
+
if indent < min_indent:
|
| 174 |
+
to_add = " " * (min_indent - indent)
|
| 175 |
+
lines = [(f"{to_add}{line}" if len(line) > 0 else line) for line in lines]
|
| 176 |
+
result = "\n".join(lines)
|
| 177 |
+
|
| 178 |
+
return result
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
FAKE_MODEL_DISCLAIMER = """
|
| 182 |
+
<Tip warning={true}>
|
| 183 |
+
|
| 184 |
+
This example uses a random model as the real ones are all very big. To get proper results, you should use
|
| 185 |
+
{real_checkpoint} instead of {fake_checkpoint}. If you get out-of-memory when loading that checkpoint, you can try
|
| 186 |
+
adding `device_map="auto"` in the `from_pretrained` call.
|
| 187 |
+
|
| 188 |
+
</Tip>
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
PT_TOKEN_CLASSIFICATION_SAMPLE = r"""
|
| 193 |
+
Example:
|
| 194 |
+
|
| 195 |
+
```python
|
| 196 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 197 |
+
>>> import torch
|
| 198 |
+
|
| 199 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 200 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 201 |
+
|
| 202 |
+
>>> inputs = tokenizer(
|
| 203 |
+
... "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
|
| 204 |
+
... )
|
| 205 |
+
|
| 206 |
+
>>> with torch.no_grad():
|
| 207 |
+
... logits = model(**inputs).logits
|
| 208 |
+
|
| 209 |
+
>>> predicted_token_class_ids = logits.argmax(-1)
|
| 210 |
+
|
| 211 |
+
>>> # Note that tokens are classified rather then input words which means that
|
| 212 |
+
>>> # there might be more predicted token classes than words.
|
| 213 |
+
>>> # Multiple token classes might account for the same word
|
| 214 |
+
>>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]
|
| 215 |
+
>>> predicted_tokens_classes
|
| 216 |
+
{expected_output}
|
| 217 |
+
|
| 218 |
+
>>> labels = predicted_token_class_ids
|
| 219 |
+
>>> loss = model(**inputs, labels=labels).loss
|
| 220 |
+
>>> round(loss.item(), 2)
|
| 221 |
+
{expected_loss}
|
| 222 |
+
```
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
PT_QUESTION_ANSWERING_SAMPLE = r"""
|
| 226 |
+
Example:
|
| 227 |
+
|
| 228 |
+
```python
|
| 229 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 230 |
+
>>> import torch
|
| 231 |
+
|
| 232 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 233 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 234 |
+
|
| 235 |
+
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
|
| 236 |
+
|
| 237 |
+
>>> inputs = tokenizer(question, text, return_tensors="pt")
|
| 238 |
+
>>> with torch.no_grad():
|
| 239 |
+
... outputs = model(**inputs)
|
| 240 |
+
|
| 241 |
+
>>> answer_start_index = outputs.start_logits.argmax()
|
| 242 |
+
>>> answer_end_index = outputs.end_logits.argmax()
|
| 243 |
+
|
| 244 |
+
>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
|
| 245 |
+
>>> tokenizer.decode(predict_answer_tokens, skip_special_tokens=True)
|
| 246 |
+
{expected_output}
|
| 247 |
+
|
| 248 |
+
>>> # target is "nice puppet"
|
| 249 |
+
>>> target_start_index = torch.tensor([{qa_target_start_index}])
|
| 250 |
+
>>> target_end_index = torch.tensor([{qa_target_end_index}])
|
| 251 |
+
|
| 252 |
+
>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
|
| 253 |
+
>>> loss = outputs.loss
|
| 254 |
+
>>> round(loss.item(), 2)
|
| 255 |
+
{expected_loss}
|
| 256 |
+
```
|
| 257 |
+
"""
|
| 258 |
+
|
| 259 |
+
PT_SEQUENCE_CLASSIFICATION_SAMPLE = r"""
|
| 260 |
+
Example of single-label classification:
|
| 261 |
+
|
| 262 |
+
```python
|
| 263 |
+
>>> import torch
|
| 264 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 265 |
+
|
| 266 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 267 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 268 |
+
|
| 269 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 270 |
+
|
| 271 |
+
>>> with torch.no_grad():
|
| 272 |
+
... logits = model(**inputs).logits
|
| 273 |
+
|
| 274 |
+
>>> predicted_class_id = logits.argmax().item()
|
| 275 |
+
>>> model.config.id2label[predicted_class_id]
|
| 276 |
+
{expected_output}
|
| 277 |
+
|
| 278 |
+
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
|
| 279 |
+
>>> num_labels = len(model.config.id2label)
|
| 280 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}", num_labels=num_labels)
|
| 281 |
+
|
| 282 |
+
>>> labels = torch.tensor([1])
|
| 283 |
+
>>> loss = model(**inputs, labels=labels).loss
|
| 284 |
+
>>> round(loss.item(), 2)
|
| 285 |
+
{expected_loss}
|
| 286 |
+
```
|
| 287 |
+
|
| 288 |
+
Example of multi-label classification:
|
| 289 |
+
|
| 290 |
+
```python
|
| 291 |
+
>>> import torch
|
| 292 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 293 |
+
|
| 294 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 295 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}", problem_type="multi_label_classification")
|
| 296 |
+
|
| 297 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 298 |
+
|
| 299 |
+
>>> with torch.no_grad():
|
| 300 |
+
... logits = model(**inputs).logits
|
| 301 |
+
|
| 302 |
+
>>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]
|
| 303 |
+
|
| 304 |
+
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
|
| 305 |
+
>>> num_labels = len(model.config.id2label)
|
| 306 |
+
>>> model = {model_class}.from_pretrained(
|
| 307 |
+
... "{checkpoint}", num_labels=num_labels, problem_type="multi_label_classification"
|
| 308 |
+
... )
|
| 309 |
+
|
| 310 |
+
>>> labels = torch.sum(
|
| 311 |
+
... torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1
|
| 312 |
+
... ).to(torch.float)
|
| 313 |
+
>>> loss = model(**inputs, labels=labels).loss
|
| 314 |
+
```
|
| 315 |
+
"""
|
| 316 |
+
|
| 317 |
+
PT_MASKED_LM_SAMPLE = r"""
|
| 318 |
+
Example:
|
| 319 |
+
|
| 320 |
+
```python
|
| 321 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 322 |
+
>>> import torch
|
| 323 |
+
|
| 324 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 325 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 326 |
+
|
| 327 |
+
>>> inputs = tokenizer("The capital of France is {mask}.", return_tensors="pt")
|
| 328 |
+
|
| 329 |
+
>>> with torch.no_grad():
|
| 330 |
+
... logits = model(**inputs).logits
|
| 331 |
+
|
| 332 |
+
>>> # retrieve index of {mask}
|
| 333 |
+
>>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]
|
| 334 |
+
|
| 335 |
+
>>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)
|
| 336 |
+
>>> tokenizer.decode(predicted_token_id)
|
| 337 |
+
{expected_output}
|
| 338 |
+
|
| 339 |
+
>>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
|
| 340 |
+
>>> # mask labels of non-{mask} tokens
|
| 341 |
+
>>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
|
| 342 |
+
|
| 343 |
+
>>> outputs = model(**inputs, labels=labels)
|
| 344 |
+
>>> round(outputs.loss.item(), 2)
|
| 345 |
+
{expected_loss}
|
| 346 |
+
```
|
| 347 |
+
"""
|
| 348 |
+
|
| 349 |
+
PT_BASE_MODEL_SAMPLE = r"""
|
| 350 |
+
Example:
|
| 351 |
+
|
| 352 |
+
```python
|
| 353 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 354 |
+
>>> import torch
|
| 355 |
+
|
| 356 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 357 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 358 |
+
|
| 359 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 360 |
+
>>> outputs = model(**inputs)
|
| 361 |
+
|
| 362 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 363 |
+
```
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
PT_MULTIPLE_CHOICE_SAMPLE = r"""
|
| 367 |
+
Example:
|
| 368 |
+
|
| 369 |
+
```python
|
| 370 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 371 |
+
>>> import torch
|
| 372 |
+
|
| 373 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 374 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 375 |
+
|
| 376 |
+
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
|
| 377 |
+
>>> choice0 = "It is eaten with a fork and a knife."
|
| 378 |
+
>>> choice1 = "It is eaten while held in the hand."
|
| 379 |
+
>>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1
|
| 380 |
+
|
| 381 |
+
>>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="pt", padding=True)
|
| 382 |
+
>>> outputs = model(**{{k: v.unsqueeze(0) for k, v in encoding.items()}}, labels=labels) # batch size is 1
|
| 383 |
+
|
| 384 |
+
>>> # the linear classifier still needs to be trained
|
| 385 |
+
>>> loss = outputs.loss
|
| 386 |
+
>>> logits = outputs.logits
|
| 387 |
+
```
|
| 388 |
+
"""
|
| 389 |
+
|
| 390 |
+
PT_CAUSAL_LM_SAMPLE = r"""
|
| 391 |
+
Example:
|
| 392 |
+
|
| 393 |
+
```python
|
| 394 |
+
>>> import torch
|
| 395 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 396 |
+
|
| 397 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 398 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 399 |
+
|
| 400 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 401 |
+
>>> outputs = model(**inputs, labels=inputs["input_ids"])
|
| 402 |
+
>>> loss = outputs.loss
|
| 403 |
+
>>> logits = outputs.logits
|
| 404 |
+
```
|
| 405 |
+
"""
|
| 406 |
+
|
| 407 |
+
PT_SPEECH_BASE_MODEL_SAMPLE = r"""
|
| 408 |
+
Example:
|
| 409 |
+
|
| 410 |
+
```python
|
| 411 |
+
>>> from transformers import AutoProcessor, {model_class}
|
| 412 |
+
>>> import torch
|
| 413 |
+
>>> from datasets import load_dataset
|
| 414 |
+
|
| 415 |
+
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation", trust_remote_code=True)
|
| 416 |
+
>>> dataset = dataset.sort("id")
|
| 417 |
+
>>> sampling_rate = dataset.features["audio"].sampling_rate
|
| 418 |
+
|
| 419 |
+
>>> processor = AutoProcessor.from_pretrained("{checkpoint}")
|
| 420 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 421 |
+
|
| 422 |
+
>>> # audio file is decoded on the fly
|
| 423 |
+
>>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
|
| 424 |
+
>>> with torch.no_grad():
|
| 425 |
+
... outputs = model(**inputs)
|
| 426 |
+
|
| 427 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 428 |
+
>>> list(last_hidden_states.shape)
|
| 429 |
+
{expected_output}
|
| 430 |
+
```
|
| 431 |
+
"""
|
| 432 |
+
|
| 433 |
+
PT_SPEECH_CTC_SAMPLE = r"""
|
| 434 |
+
Example:
|
| 435 |
+
|
| 436 |
+
```python
|
| 437 |
+
>>> from transformers import AutoProcessor, {model_class}
|
| 438 |
+
>>> from datasets import load_dataset
|
| 439 |
+
>>> import torch
|
| 440 |
+
|
| 441 |
+
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation", trust_remote_code=True)
|
| 442 |
+
>>> dataset = dataset.sort("id")
|
| 443 |
+
>>> sampling_rate = dataset.features["audio"].sampling_rate
|
| 444 |
+
|
| 445 |
+
>>> processor = AutoProcessor.from_pretrained("{checkpoint}")
|
| 446 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 447 |
+
|
| 448 |
+
>>> # audio file is decoded on the fly
|
| 449 |
+
>>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
|
| 450 |
+
>>> with torch.no_grad():
|
| 451 |
+
... logits = model(**inputs).logits
|
| 452 |
+
>>> predicted_ids = torch.argmax(logits, dim=-1)
|
| 453 |
+
|
| 454 |
+
>>> # transcribe speech
|
| 455 |
+
>>> transcription = processor.batch_decode(predicted_ids)
|
| 456 |
+
>>> transcription[0]
|
| 457 |
+
{expected_output}
|
| 458 |
+
|
| 459 |
+
>>> inputs["labels"] = processor(text=dataset[0]["text"], return_tensors="pt").input_ids
|
| 460 |
+
|
| 461 |
+
>>> # compute loss
|
| 462 |
+
>>> loss = model(**inputs).loss
|
| 463 |
+
>>> round(loss.item(), 2)
|
| 464 |
+
{expected_loss}
|
| 465 |
+
```
|
| 466 |
+
"""
|
| 467 |
+
|
| 468 |
+
PT_SPEECH_SEQ_CLASS_SAMPLE = r"""
|
| 469 |
+
Example:
|
| 470 |
+
|
| 471 |
+
```python
|
| 472 |
+
>>> from transformers import AutoFeatureExtractor, {model_class}
|
| 473 |
+
>>> from datasets import load_dataset
|
| 474 |
+
>>> import torch
|
| 475 |
+
|
| 476 |
+
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation", trust_remote_code=True)
|
| 477 |
+
>>> dataset = dataset.sort("id")
|
| 478 |
+
>>> sampling_rate = dataset.features["audio"].sampling_rate
|
| 479 |
+
|
| 480 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("{checkpoint}")
|
| 481 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 482 |
+
|
| 483 |
+
>>> # audio file is decoded on the fly
|
| 484 |
+
>>> inputs = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
|
| 485 |
+
|
| 486 |
+
>>> with torch.no_grad():
|
| 487 |
+
... logits = model(**inputs).logits
|
| 488 |
+
|
| 489 |
+
>>> predicted_class_ids = torch.argmax(logits, dim=-1).item()
|
| 490 |
+
>>> predicted_label = model.config.id2label[predicted_class_ids]
|
| 491 |
+
>>> predicted_label
|
| 492 |
+
{expected_output}
|
| 493 |
+
|
| 494 |
+
>>> # compute loss - target_label is e.g. "down"
|
| 495 |
+
>>> target_label = model.config.id2label[0]
|
| 496 |
+
>>> inputs["labels"] = torch.tensor([model.config.label2id[target_label]])
|
| 497 |
+
>>> loss = model(**inputs).loss
|
| 498 |
+
>>> round(loss.item(), 2)
|
| 499 |
+
{expected_loss}
|
| 500 |
+
```
|
| 501 |
+
"""
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
PT_SPEECH_FRAME_CLASS_SAMPLE = r"""
|
| 505 |
+
Example:
|
| 506 |
+
|
| 507 |
+
```python
|
| 508 |
+
>>> from transformers import AutoFeatureExtractor, {model_class}
|
| 509 |
+
>>> from datasets import load_dataset
|
| 510 |
+
>>> import torch
|
| 511 |
+
|
| 512 |
+
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation", trust_remote_code=True)
|
| 513 |
+
>>> dataset = dataset.sort("id")
|
| 514 |
+
>>> sampling_rate = dataset.features["audio"].sampling_rate
|
| 515 |
+
|
| 516 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("{checkpoint}")
|
| 517 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 518 |
+
|
| 519 |
+
>>> # audio file is decoded on the fly
|
| 520 |
+
>>> inputs = feature_extractor(dataset[0]["audio"]["array"], return_tensors="pt", sampling_rate=sampling_rate)
|
| 521 |
+
>>> with torch.no_grad():
|
| 522 |
+
... logits = model(**inputs).logits
|
| 523 |
+
|
| 524 |
+
>>> probabilities = torch.sigmoid(logits[0])
|
| 525 |
+
>>> # labels is a one-hot array of shape (num_frames, num_speakers)
|
| 526 |
+
>>> labels = (probabilities > 0.5).long()
|
| 527 |
+
>>> labels[0].tolist()
|
| 528 |
+
{expected_output}
|
| 529 |
+
```
|
| 530 |
+
"""
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
PT_SPEECH_XVECTOR_SAMPLE = r"""
|
| 534 |
+
Example:
|
| 535 |
+
|
| 536 |
+
```python
|
| 537 |
+
>>> from transformers import AutoFeatureExtractor, {model_class}
|
| 538 |
+
>>> from datasets import load_dataset
|
| 539 |
+
>>> import torch
|
| 540 |
+
|
| 541 |
+
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation", trust_remote_code=True)
|
| 542 |
+
>>> dataset = dataset.sort("id")
|
| 543 |
+
>>> sampling_rate = dataset.features["audio"].sampling_rate
|
| 544 |
+
|
| 545 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("{checkpoint}")
|
| 546 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 547 |
+
|
| 548 |
+
>>> # audio file is decoded on the fly
|
| 549 |
+
>>> inputs = feature_extractor(
|
| 550 |
+
... [d["array"] for d in dataset[:2]["audio"]], sampling_rate=sampling_rate, return_tensors="pt", padding=True
|
| 551 |
+
... )
|
| 552 |
+
>>> with torch.no_grad():
|
| 553 |
+
... embeddings = model(**inputs).embeddings
|
| 554 |
+
|
| 555 |
+
>>> embeddings = torch.nn.functional.normalize(embeddings, dim=-1).cpu()
|
| 556 |
+
|
| 557 |
+
>>> # the resulting embeddings can be used for cosine similarity-based retrieval
|
| 558 |
+
>>> cosine_sim = torch.nn.CosineSimilarity(dim=-1)
|
| 559 |
+
>>> similarity = cosine_sim(embeddings[0], embeddings[1])
|
| 560 |
+
>>> threshold = 0.7 # the optimal threshold is dataset-dependent
|
| 561 |
+
>>> if similarity < threshold:
|
| 562 |
+
... print("Speakers are not the same!")
|
| 563 |
+
>>> round(similarity.item(), 2)
|
| 564 |
+
{expected_output}
|
| 565 |
+
```
|
| 566 |
+
"""
|
| 567 |
+
|
| 568 |
+
PT_VISION_BASE_MODEL_SAMPLE = r"""
|
| 569 |
+
Example:
|
| 570 |
+
|
| 571 |
+
```python
|
| 572 |
+
>>> from transformers import AutoImageProcessor, {model_class}
|
| 573 |
+
>>> import torch
|
| 574 |
+
>>> from datasets import load_dataset
|
| 575 |
+
|
| 576 |
+
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
|
| 577 |
+
>>> image = dataset["test"]["image"][0]
|
| 578 |
+
|
| 579 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("{checkpoint}")
|
| 580 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 581 |
+
|
| 582 |
+
>>> inputs = image_processor(image, return_tensors="pt")
|
| 583 |
+
|
| 584 |
+
>>> with torch.no_grad():
|
| 585 |
+
... outputs = model(**inputs)
|
| 586 |
+
|
| 587 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 588 |
+
>>> list(last_hidden_states.shape)
|
| 589 |
+
{expected_output}
|
| 590 |
+
```
|
| 591 |
+
"""
|
| 592 |
+
|
| 593 |
+
PT_VISION_SEQ_CLASS_SAMPLE = r"""
|
| 594 |
+
Example:
|
| 595 |
+
|
| 596 |
+
```python
|
| 597 |
+
>>> from transformers import AutoImageProcessor, {model_class}
|
| 598 |
+
>>> import torch
|
| 599 |
+
>>> from datasets import load_dataset
|
| 600 |
+
|
| 601 |
+
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
|
| 602 |
+
>>> image = dataset["test"]["image"][0]
|
| 603 |
+
|
| 604 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("{checkpoint}")
|
| 605 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 606 |
+
|
| 607 |
+
>>> inputs = image_processor(image, return_tensors="pt")
|
| 608 |
+
|
| 609 |
+
>>> with torch.no_grad():
|
| 610 |
+
... logits = model(**inputs).logits
|
| 611 |
+
|
| 612 |
+
>>> # model predicts one of the 1000 ImageNet classes
|
| 613 |
+
>>> predicted_label = logits.argmax(-1).item()
|
| 614 |
+
>>> print(model.config.id2label[predicted_label])
|
| 615 |
+
{expected_output}
|
| 616 |
+
```
|
| 617 |
+
"""
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
PT_SAMPLE_DOCSTRINGS = {
|
| 621 |
+
"SequenceClassification": PT_SEQUENCE_CLASSIFICATION_SAMPLE,
|
| 622 |
+
"QuestionAnswering": PT_QUESTION_ANSWERING_SAMPLE,
|
| 623 |
+
"TokenClassification": PT_TOKEN_CLASSIFICATION_SAMPLE,
|
| 624 |
+
"MultipleChoice": PT_MULTIPLE_CHOICE_SAMPLE,
|
| 625 |
+
"MaskedLM": PT_MASKED_LM_SAMPLE,
|
| 626 |
+
"LMHead": PT_CAUSAL_LM_SAMPLE,
|
| 627 |
+
"BaseModel": PT_BASE_MODEL_SAMPLE,
|
| 628 |
+
"SpeechBaseModel": PT_SPEECH_BASE_MODEL_SAMPLE,
|
| 629 |
+
"CTC": PT_SPEECH_CTC_SAMPLE,
|
| 630 |
+
"AudioClassification": PT_SPEECH_SEQ_CLASS_SAMPLE,
|
| 631 |
+
"AudioFrameClassification": PT_SPEECH_FRAME_CLASS_SAMPLE,
|
| 632 |
+
"AudioXVector": PT_SPEECH_XVECTOR_SAMPLE,
|
| 633 |
+
"VisionBaseModel": PT_VISION_BASE_MODEL_SAMPLE,
|
| 634 |
+
"ImageClassification": PT_VISION_SEQ_CLASS_SAMPLE,
|
| 635 |
+
}
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
TF_TOKEN_CLASSIFICATION_SAMPLE = r"""
|
| 639 |
+
Example:
|
| 640 |
+
|
| 641 |
+
```python
|
| 642 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 643 |
+
>>> import tensorflow as tf
|
| 644 |
+
|
| 645 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 646 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 647 |
+
|
| 648 |
+
>>> inputs = tokenizer(
|
| 649 |
+
... "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="tf"
|
| 650 |
+
... )
|
| 651 |
+
|
| 652 |
+
>>> logits = model(**inputs).logits
|
| 653 |
+
>>> predicted_token_class_ids = tf.math.argmax(logits, axis=-1)
|
| 654 |
+
|
| 655 |
+
>>> # Note that tokens are classified rather then input words which means that
|
| 656 |
+
>>> # there might be more predicted token classes than words.
|
| 657 |
+
>>> # Multiple token classes might account for the same word
|
| 658 |
+
>>> predicted_tokens_classes = [model.config.id2label[t] for t in predicted_token_class_ids[0].numpy().tolist()]
|
| 659 |
+
>>> predicted_tokens_classes
|
| 660 |
+
{expected_output}
|
| 661 |
+
```
|
| 662 |
+
|
| 663 |
+
```python
|
| 664 |
+
>>> labels = predicted_token_class_ids
|
| 665 |
+
>>> loss = tf.math.reduce_mean(model(**inputs, labels=labels).loss)
|
| 666 |
+
>>> round(float(loss), 2)
|
| 667 |
+
{expected_loss}
|
| 668 |
+
```
|
| 669 |
+
"""
|
| 670 |
+
|
| 671 |
+
TF_QUESTION_ANSWERING_SAMPLE = r"""
|
| 672 |
+
Example:
|
| 673 |
+
|
| 674 |
+
```python
|
| 675 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 676 |
+
>>> import tensorflow as tf
|
| 677 |
+
|
| 678 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 679 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 680 |
+
|
| 681 |
+
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
|
| 682 |
+
|
| 683 |
+
>>> inputs = tokenizer(question, text, return_tensors="tf")
|
| 684 |
+
>>> outputs = model(**inputs)
|
| 685 |
+
|
| 686 |
+
>>> answer_start_index = int(tf.math.argmax(outputs.start_logits, axis=-1)[0])
|
| 687 |
+
>>> answer_end_index = int(tf.math.argmax(outputs.end_logits, axis=-1)[0])
|
| 688 |
+
|
| 689 |
+
>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
|
| 690 |
+
>>> tokenizer.decode(predict_answer_tokens)
|
| 691 |
+
{expected_output}
|
| 692 |
+
```
|
| 693 |
+
|
| 694 |
+
```python
|
| 695 |
+
>>> # target is "nice puppet"
|
| 696 |
+
>>> target_start_index = tf.constant([{qa_target_start_index}])
|
| 697 |
+
>>> target_end_index = tf.constant([{qa_target_end_index}])
|
| 698 |
+
|
| 699 |
+
>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
|
| 700 |
+
>>> loss = tf.math.reduce_mean(outputs.loss)
|
| 701 |
+
>>> round(float(loss), 2)
|
| 702 |
+
{expected_loss}
|
| 703 |
+
```
|
| 704 |
+
"""
|
| 705 |
+
|
| 706 |
+
TF_SEQUENCE_CLASSIFICATION_SAMPLE = r"""
|
| 707 |
+
Example:
|
| 708 |
+
|
| 709 |
+
```python
|
| 710 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 711 |
+
>>> import tensorflow as tf
|
| 712 |
+
|
| 713 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 714 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 715 |
+
|
| 716 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
|
| 717 |
+
|
| 718 |
+
>>> logits = model(**inputs).logits
|
| 719 |
+
|
| 720 |
+
>>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0])
|
| 721 |
+
>>> model.config.id2label[predicted_class_id]
|
| 722 |
+
{expected_output}
|
| 723 |
+
```
|
| 724 |
+
|
| 725 |
+
```python
|
| 726 |
+
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
|
| 727 |
+
>>> num_labels = len(model.config.id2label)
|
| 728 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}", num_labels=num_labels)
|
| 729 |
+
|
| 730 |
+
>>> labels = tf.constant(1)
|
| 731 |
+
>>> loss = model(**inputs, labels=labels).loss
|
| 732 |
+
>>> round(float(loss), 2)
|
| 733 |
+
{expected_loss}
|
| 734 |
+
```
|
| 735 |
+
"""
|
| 736 |
+
|
| 737 |
+
TF_MASKED_LM_SAMPLE = r"""
|
| 738 |
+
Example:
|
| 739 |
+
|
| 740 |
+
```python
|
| 741 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 742 |
+
>>> import tensorflow as tf
|
| 743 |
+
|
| 744 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 745 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 746 |
+
|
| 747 |
+
>>> inputs = tokenizer("The capital of France is {mask}.", return_tensors="tf")
|
| 748 |
+
>>> logits = model(**inputs).logits
|
| 749 |
+
|
| 750 |
+
>>> # retrieve index of {mask}
|
| 751 |
+
>>> mask_token_index = tf.where((inputs.input_ids == tokenizer.mask_token_id)[0])
|
| 752 |
+
>>> selected_logits = tf.gather_nd(logits[0], indices=mask_token_index)
|
| 753 |
+
|
| 754 |
+
>>> predicted_token_id = tf.math.argmax(selected_logits, axis=-1)
|
| 755 |
+
>>> tokenizer.decode(predicted_token_id)
|
| 756 |
+
{expected_output}
|
| 757 |
+
```
|
| 758 |
+
|
| 759 |
+
```python
|
| 760 |
+
>>> labels = tokenizer("The capital of France is Paris.", return_tensors="tf")["input_ids"]
|
| 761 |
+
>>> # mask labels of non-{mask} tokens
|
| 762 |
+
>>> labels = tf.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
|
| 763 |
+
|
| 764 |
+
>>> outputs = model(**inputs, labels=labels)
|
| 765 |
+
>>> round(float(outputs.loss), 2)
|
| 766 |
+
{expected_loss}
|
| 767 |
+
```
|
| 768 |
+
"""
|
| 769 |
+
|
| 770 |
+
TF_BASE_MODEL_SAMPLE = r"""
|
| 771 |
+
Example:
|
| 772 |
+
|
| 773 |
+
```python
|
| 774 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 775 |
+
>>> import tensorflow as tf
|
| 776 |
+
|
| 777 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 778 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 779 |
+
|
| 780 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
|
| 781 |
+
>>> outputs = model(inputs)
|
| 782 |
+
|
| 783 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 784 |
+
```
|
| 785 |
+
"""
|
| 786 |
+
|
| 787 |
+
TF_MULTIPLE_CHOICE_SAMPLE = r"""
|
| 788 |
+
Example:
|
| 789 |
+
|
| 790 |
+
```python
|
| 791 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 792 |
+
>>> import tensorflow as tf
|
| 793 |
+
|
| 794 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 795 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 796 |
+
|
| 797 |
+
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
|
| 798 |
+
>>> choice0 = "It is eaten with a fork and a knife."
|
| 799 |
+
>>> choice1 = "It is eaten while held in the hand."
|
| 800 |
+
|
| 801 |
+
>>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="tf", padding=True)
|
| 802 |
+
>>> inputs = {{k: tf.expand_dims(v, 0) for k, v in encoding.items()}}
|
| 803 |
+
>>> outputs = model(inputs) # batch size is 1
|
| 804 |
+
|
| 805 |
+
>>> # the linear classifier still needs to be trained
|
| 806 |
+
>>> logits = outputs.logits
|
| 807 |
+
```
|
| 808 |
+
"""
|
| 809 |
+
|
| 810 |
+
TF_CAUSAL_LM_SAMPLE = r"""
|
| 811 |
+
Example:
|
| 812 |
+
|
| 813 |
+
```python
|
| 814 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 815 |
+
>>> import tensorflow as tf
|
| 816 |
+
|
| 817 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 818 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 819 |
+
|
| 820 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
|
| 821 |
+
>>> outputs = model(inputs)
|
| 822 |
+
>>> logits = outputs.logits
|
| 823 |
+
```
|
| 824 |
+
"""
|
| 825 |
+
|
| 826 |
+
TF_SPEECH_BASE_MODEL_SAMPLE = r"""
|
| 827 |
+
Example:
|
| 828 |
+
|
| 829 |
+
```python
|
| 830 |
+
>>> from transformers import AutoProcessor, {model_class}
|
| 831 |
+
>>> from datasets import load_dataset
|
| 832 |
+
|
| 833 |
+
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation", trust_remote_code=True)
|
| 834 |
+
>>> dataset = dataset.sort("id")
|
| 835 |
+
>>> sampling_rate = dataset.features["audio"].sampling_rate
|
| 836 |
+
|
| 837 |
+
>>> processor = AutoProcessor.from_pretrained("{checkpoint}")
|
| 838 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 839 |
+
|
| 840 |
+
>>> # audio file is decoded on the fly
|
| 841 |
+
>>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="tf")
|
| 842 |
+
>>> outputs = model(**inputs)
|
| 843 |
+
|
| 844 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 845 |
+
>>> list(last_hidden_states.shape)
|
| 846 |
+
{expected_output}
|
| 847 |
+
```
|
| 848 |
+
"""
|
| 849 |
+
|
| 850 |
+
TF_SPEECH_CTC_SAMPLE = r"""
|
| 851 |
+
Example:
|
| 852 |
+
|
| 853 |
+
```python
|
| 854 |
+
>>> from transformers import AutoProcessor, {model_class}
|
| 855 |
+
>>> from datasets import load_dataset
|
| 856 |
+
>>> import tensorflow as tf
|
| 857 |
+
|
| 858 |
+
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation", trust_remote_code=True)
|
| 859 |
+
>>> dataset = dataset.sort("id")
|
| 860 |
+
>>> sampling_rate = dataset.features["audio"].sampling_rate
|
| 861 |
+
|
| 862 |
+
>>> processor = AutoProcessor.from_pretrained("{checkpoint}")
|
| 863 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 864 |
+
|
| 865 |
+
>>> # audio file is decoded on the fly
|
| 866 |
+
>>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="tf")
|
| 867 |
+
>>> logits = model(**inputs).logits
|
| 868 |
+
>>> predicted_ids = tf.math.argmax(logits, axis=-1)
|
| 869 |
+
|
| 870 |
+
>>> # transcribe speech
|
| 871 |
+
>>> transcription = processor.batch_decode(predicted_ids)
|
| 872 |
+
>>> transcription[0]
|
| 873 |
+
{expected_output}
|
| 874 |
+
```
|
| 875 |
+
|
| 876 |
+
```python
|
| 877 |
+
>>> inputs["labels"] = processor(text=dataset[0]["text"], return_tensors="tf").input_ids
|
| 878 |
+
|
| 879 |
+
>>> # compute loss
|
| 880 |
+
>>> loss = model(**inputs).loss
|
| 881 |
+
>>> round(float(loss), 2)
|
| 882 |
+
{expected_loss}
|
| 883 |
+
```
|
| 884 |
+
"""
|
| 885 |
+
|
| 886 |
+
TF_VISION_BASE_MODEL_SAMPLE = r"""
|
| 887 |
+
Example:
|
| 888 |
+
|
| 889 |
+
```python
|
| 890 |
+
>>> from transformers import AutoImageProcessor, {model_class}
|
| 891 |
+
>>> from datasets import load_dataset
|
| 892 |
+
|
| 893 |
+
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
|
| 894 |
+
>>> image = dataset["test"]["image"][0]
|
| 895 |
+
|
| 896 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("{checkpoint}")
|
| 897 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 898 |
+
|
| 899 |
+
>>> inputs = image_processor(image, return_tensors="tf")
|
| 900 |
+
>>> outputs = model(**inputs)
|
| 901 |
+
|
| 902 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 903 |
+
>>> list(last_hidden_states.shape)
|
| 904 |
+
{expected_output}
|
| 905 |
+
```
|
| 906 |
+
"""
|
| 907 |
+
|
| 908 |
+
TF_VISION_SEQ_CLASS_SAMPLE = r"""
|
| 909 |
+
Example:
|
| 910 |
+
|
| 911 |
+
```python
|
| 912 |
+
>>> from transformers import AutoImageProcessor, {model_class}
|
| 913 |
+
>>> import tensorflow as tf
|
| 914 |
+
>>> from datasets import load_dataset
|
| 915 |
+
|
| 916 |
+
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
|
| 917 |
+
>>> image = dataset["test"]["image"][0]
|
| 918 |
+
|
| 919 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("{checkpoint}")
|
| 920 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 921 |
+
|
| 922 |
+
>>> inputs = image_processor(image, return_tensors="tf")
|
| 923 |
+
>>> logits = model(**inputs).logits
|
| 924 |
+
|
| 925 |
+
>>> # model predicts one of the 1000 ImageNet classes
|
| 926 |
+
>>> predicted_label = int(tf.math.argmax(logits, axis=-1))
|
| 927 |
+
>>> print(model.config.id2label[predicted_label])
|
| 928 |
+
{expected_output}
|
| 929 |
+
```
|
| 930 |
+
"""
|
| 931 |
+
|
| 932 |
+
TF_SAMPLE_DOCSTRINGS = {
|
| 933 |
+
"SequenceClassification": TF_SEQUENCE_CLASSIFICATION_SAMPLE,
|
| 934 |
+
"QuestionAnswering": TF_QUESTION_ANSWERING_SAMPLE,
|
| 935 |
+
"TokenClassification": TF_TOKEN_CLASSIFICATION_SAMPLE,
|
| 936 |
+
"MultipleChoice": TF_MULTIPLE_CHOICE_SAMPLE,
|
| 937 |
+
"MaskedLM": TF_MASKED_LM_SAMPLE,
|
| 938 |
+
"LMHead": TF_CAUSAL_LM_SAMPLE,
|
| 939 |
+
"BaseModel": TF_BASE_MODEL_SAMPLE,
|
| 940 |
+
"SpeechBaseModel": TF_SPEECH_BASE_MODEL_SAMPLE,
|
| 941 |
+
"CTC": TF_SPEECH_CTC_SAMPLE,
|
| 942 |
+
"VisionBaseModel": TF_VISION_BASE_MODEL_SAMPLE,
|
| 943 |
+
"ImageClassification": TF_VISION_SEQ_CLASS_SAMPLE,
|
| 944 |
+
}
|
| 945 |
+
|
| 946 |
+
|
| 947 |
+
FLAX_TOKEN_CLASSIFICATION_SAMPLE = r"""
|
| 948 |
+
Example:
|
| 949 |
+
|
| 950 |
+
```python
|
| 951 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 952 |
+
|
| 953 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 954 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 955 |
+
|
| 956 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
|
| 957 |
+
|
| 958 |
+
>>> outputs = model(**inputs)
|
| 959 |
+
>>> logits = outputs.logits
|
| 960 |
+
```
|
| 961 |
+
"""
|
| 962 |
+
|
| 963 |
+
FLAX_QUESTION_ANSWERING_SAMPLE = r"""
|
| 964 |
+
Example:
|
| 965 |
+
|
| 966 |
+
```python
|
| 967 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 968 |
+
|
| 969 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 970 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 971 |
+
|
| 972 |
+
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
|
| 973 |
+
>>> inputs = tokenizer(question, text, return_tensors="jax")
|
| 974 |
+
|
| 975 |
+
>>> outputs = model(**inputs)
|
| 976 |
+
>>> start_scores = outputs.start_logits
|
| 977 |
+
>>> end_scores = outputs.end_logits
|
| 978 |
+
```
|
| 979 |
+
"""
|
| 980 |
+
|
| 981 |
+
FLAX_SEQUENCE_CLASSIFICATION_SAMPLE = r"""
|
| 982 |
+
Example:
|
| 983 |
+
|
| 984 |
+
```python
|
| 985 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 986 |
+
|
| 987 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 988 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 989 |
+
|
| 990 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
|
| 991 |
+
|
| 992 |
+
>>> outputs = model(**inputs)
|
| 993 |
+
>>> logits = outputs.logits
|
| 994 |
+
```
|
| 995 |
+
"""
|
| 996 |
+
|
| 997 |
+
FLAX_MASKED_LM_SAMPLE = r"""
|
| 998 |
+
Example:
|
| 999 |
+
|
| 1000 |
+
```python
|
| 1001 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 1002 |
+
|
| 1003 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 1004 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 1005 |
+
|
| 1006 |
+
>>> inputs = tokenizer("The capital of France is {mask}.", return_tensors="jax")
|
| 1007 |
+
|
| 1008 |
+
>>> outputs = model(**inputs)
|
| 1009 |
+
>>> logits = outputs.logits
|
| 1010 |
+
```
|
| 1011 |
+
"""
|
| 1012 |
+
|
| 1013 |
+
FLAX_BASE_MODEL_SAMPLE = r"""
|
| 1014 |
+
Example:
|
| 1015 |
+
|
| 1016 |
+
```python
|
| 1017 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 1018 |
+
|
| 1019 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 1020 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 1021 |
+
|
| 1022 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
|
| 1023 |
+
>>> outputs = model(**inputs)
|
| 1024 |
+
|
| 1025 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 1026 |
+
```
|
| 1027 |
+
"""
|
| 1028 |
+
|
| 1029 |
+
FLAX_MULTIPLE_CHOICE_SAMPLE = r"""
|
| 1030 |
+
Example:
|
| 1031 |
+
|
| 1032 |
+
```python
|
| 1033 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 1034 |
+
|
| 1035 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 1036 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 1037 |
+
|
| 1038 |
+
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
|
| 1039 |
+
>>> choice0 = "It is eaten with a fork and a knife."
|
| 1040 |
+
>>> choice1 = "It is eaten while held in the hand."
|
| 1041 |
+
|
| 1042 |
+
>>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="jax", padding=True)
|
| 1043 |
+
>>> outputs = model(**{{k: v[None, :] for k, v in encoding.items()}})
|
| 1044 |
+
|
| 1045 |
+
>>> logits = outputs.logits
|
| 1046 |
+
```
|
| 1047 |
+
"""
|
| 1048 |
+
|
| 1049 |
+
FLAX_CAUSAL_LM_SAMPLE = r"""
|
| 1050 |
+
Example:
|
| 1051 |
+
|
| 1052 |
+
```python
|
| 1053 |
+
>>> from transformers import AutoTokenizer, {model_class}
|
| 1054 |
+
|
| 1055 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
|
| 1056 |
+
>>> model = {model_class}.from_pretrained("{checkpoint}")
|
| 1057 |
+
|
| 1058 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
|
| 1059 |
+
>>> outputs = model(**inputs)
|
| 1060 |
+
|
| 1061 |
+
>>> # retrieve logts for next token
|
| 1062 |
+
>>> next_token_logits = outputs.logits[:, -1]
|
| 1063 |
+
```
|
| 1064 |
+
"""
|
| 1065 |
+
|
| 1066 |
+
FLAX_SAMPLE_DOCSTRINGS = {
|
| 1067 |
+
"SequenceClassification": FLAX_SEQUENCE_CLASSIFICATION_SAMPLE,
|
| 1068 |
+
"QuestionAnswering": FLAX_QUESTION_ANSWERING_SAMPLE,
|
| 1069 |
+
"TokenClassification": FLAX_TOKEN_CLASSIFICATION_SAMPLE,
|
| 1070 |
+
"MultipleChoice": FLAX_MULTIPLE_CHOICE_SAMPLE,
|
| 1071 |
+
"MaskedLM": FLAX_MASKED_LM_SAMPLE,
|
| 1072 |
+
"BaseModel": FLAX_BASE_MODEL_SAMPLE,
|
| 1073 |
+
"LMHead": FLAX_CAUSAL_LM_SAMPLE,
|
| 1074 |
+
}
|
| 1075 |
+
|
| 1076 |
+
|
| 1077 |
+
def filter_outputs_from_example(docstring, **kwargs):
|
| 1078 |
+
"""
|
| 1079 |
+
Removes the lines testing an output with the doctest syntax in a code sample when it's set to `None`.
|
| 1080 |
+
"""
|
| 1081 |
+
for key, value in kwargs.items():
|
| 1082 |
+
if value is not None:
|
| 1083 |
+
continue
|
| 1084 |
+
|
| 1085 |
+
doc_key = "{" + key + "}"
|
| 1086 |
+
docstring = re.sub(rf"\n([^\n]+)\n\s+{doc_key}\n", "\n", docstring)
|
| 1087 |
+
|
| 1088 |
+
return docstring
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
+
def add_code_sample_docstrings(
|
| 1092 |
+
*docstr,
|
| 1093 |
+
processor_class=None,
|
| 1094 |
+
checkpoint=None,
|
| 1095 |
+
output_type=None,
|
| 1096 |
+
config_class=None,
|
| 1097 |
+
mask="[MASK]",
|
| 1098 |
+
qa_target_start_index=14,
|
| 1099 |
+
qa_target_end_index=15,
|
| 1100 |
+
model_cls=None,
|
| 1101 |
+
modality=None,
|
| 1102 |
+
expected_output=None,
|
| 1103 |
+
expected_loss=None,
|
| 1104 |
+
real_checkpoint=None,
|
| 1105 |
+
revision=None,
|
| 1106 |
+
):
|
| 1107 |
+
def docstring_decorator(fn):
|
| 1108 |
+
# model_class defaults to function's class if not specified otherwise
|
| 1109 |
+
model_class = fn.__qualname__.split(".")[0] if model_cls is None else model_cls
|
| 1110 |
+
|
| 1111 |
+
if model_class[:2] == "TF":
|
| 1112 |
+
sample_docstrings = TF_SAMPLE_DOCSTRINGS
|
| 1113 |
+
elif model_class[:4] == "Flax":
|
| 1114 |
+
sample_docstrings = FLAX_SAMPLE_DOCSTRINGS
|
| 1115 |
+
else:
|
| 1116 |
+
sample_docstrings = PT_SAMPLE_DOCSTRINGS
|
| 1117 |
+
|
| 1118 |
+
# putting all kwargs for docstrings in a dict to be used
|
| 1119 |
+
# with the `.format(**doc_kwargs)`. Note that string might
|
| 1120 |
+
# be formatted with non-existing keys, which is fine.
|
| 1121 |
+
doc_kwargs = {
|
| 1122 |
+
"model_class": model_class,
|
| 1123 |
+
"processor_class": processor_class,
|
| 1124 |
+
"checkpoint": checkpoint,
|
| 1125 |
+
"mask": mask,
|
| 1126 |
+
"qa_target_start_index": qa_target_start_index,
|
| 1127 |
+
"qa_target_end_index": qa_target_end_index,
|
| 1128 |
+
"expected_output": expected_output,
|
| 1129 |
+
"expected_loss": expected_loss,
|
| 1130 |
+
"real_checkpoint": real_checkpoint,
|
| 1131 |
+
"fake_checkpoint": checkpoint,
|
| 1132 |
+
"true": "{true}", # For <Tip warning={true}> syntax that conflicts with formatting.
|
| 1133 |
+
}
|
| 1134 |
+
|
| 1135 |
+
if ("SequenceClassification" in model_class or "AudioClassification" in model_class) and modality == "audio":
|
| 1136 |
+
code_sample = sample_docstrings["AudioClassification"]
|
| 1137 |
+
elif "SequenceClassification" in model_class:
|
| 1138 |
+
code_sample = sample_docstrings["SequenceClassification"]
|
| 1139 |
+
elif "QuestionAnswering" in model_class:
|
| 1140 |
+
code_sample = sample_docstrings["QuestionAnswering"]
|
| 1141 |
+
elif "TokenClassification" in model_class:
|
| 1142 |
+
code_sample = sample_docstrings["TokenClassification"]
|
| 1143 |
+
elif "MultipleChoice" in model_class:
|
| 1144 |
+
code_sample = sample_docstrings["MultipleChoice"]
|
| 1145 |
+
elif "MaskedLM" in model_class or model_class in ["FlaubertWithLMHeadModel", "XLMWithLMHeadModel"]:
|
| 1146 |
+
code_sample = sample_docstrings["MaskedLM"]
|
| 1147 |
+
elif "LMHead" in model_class or "CausalLM" in model_class:
|
| 1148 |
+
code_sample = sample_docstrings["LMHead"]
|
| 1149 |
+
elif "CTC" in model_class:
|
| 1150 |
+
code_sample = sample_docstrings["CTC"]
|
| 1151 |
+
elif "AudioFrameClassification" in model_class:
|
| 1152 |
+
code_sample = sample_docstrings["AudioFrameClassification"]
|
| 1153 |
+
elif "XVector" in model_class and modality == "audio":
|
| 1154 |
+
code_sample = sample_docstrings["AudioXVector"]
|
| 1155 |
+
elif "Model" in model_class and modality == "audio":
|
| 1156 |
+
code_sample = sample_docstrings["SpeechBaseModel"]
|
| 1157 |
+
elif "Model" in model_class and modality == "vision":
|
| 1158 |
+
code_sample = sample_docstrings["VisionBaseModel"]
|
| 1159 |
+
elif "Model" in model_class or "Encoder" in model_class:
|
| 1160 |
+
code_sample = sample_docstrings["BaseModel"]
|
| 1161 |
+
elif "ImageClassification" in model_class:
|
| 1162 |
+
code_sample = sample_docstrings["ImageClassification"]
|
| 1163 |
+
else:
|
| 1164 |
+
raise ValueError(f"Docstring can't be built for model {model_class}")
|
| 1165 |
+
|
| 1166 |
+
code_sample = filter_outputs_from_example(
|
| 1167 |
+
code_sample, expected_output=expected_output, expected_loss=expected_loss
|
| 1168 |
+
)
|
| 1169 |
+
if real_checkpoint is not None:
|
| 1170 |
+
code_sample = FAKE_MODEL_DISCLAIMER + code_sample
|
| 1171 |
+
func_doc = (fn.__doc__ or "") + "".join(docstr)
|
| 1172 |
+
output_doc = "" if output_type is None else _prepare_output_docstrings(output_type, config_class)
|
| 1173 |
+
built_doc = code_sample.format(**doc_kwargs)
|
| 1174 |
+
if revision is not None:
|
| 1175 |
+
if re.match(r"^refs/pr/\\d+", revision):
|
| 1176 |
+
raise ValueError(
|
| 1177 |
+
f"The provided revision '{revision}' is incorrect. It should point to"
|
| 1178 |
+
" a pull request reference on the hub like 'refs/pr/6'"
|
| 1179 |
+
)
|
| 1180 |
+
built_doc = built_doc.replace(
|
| 1181 |
+
f'from_pretrained("{checkpoint}")', f'from_pretrained("{checkpoint}", revision="{revision}")'
|
| 1182 |
+
)
|
| 1183 |
+
|
| 1184 |
+
fn.__doc__ = func_doc + output_doc + built_doc
|
| 1185 |
+
return fn
|
| 1186 |
+
|
| 1187 |
+
return docstring_decorator
|
| 1188 |
+
|
| 1189 |
+
|
| 1190 |
+
def replace_return_docstrings(output_type=None, config_class=None):
|
| 1191 |
+
def docstring_decorator(fn):
|
| 1192 |
+
func_doc = fn.__doc__
|
| 1193 |
+
lines = func_doc.split("\n")
|
| 1194 |
+
i = 0
|
| 1195 |
+
while i < len(lines) and re.search(r"^\s*Returns?:\s*$", lines[i]) is None:
|
| 1196 |
+
i += 1
|
| 1197 |
+
if i < len(lines):
|
| 1198 |
+
indent = len(_get_indent(lines[i]))
|
| 1199 |
+
lines[i] = _prepare_output_docstrings(output_type, config_class, min_indent=indent)
|
| 1200 |
+
func_doc = "\n".join(lines)
|
| 1201 |
+
else:
|
| 1202 |
+
raise ValueError(
|
| 1203 |
+
f"The function {fn} should have an empty 'Return:' or 'Returns:' in its docstring as placeholder, "
|
| 1204 |
+
f"current docstring is:\n{func_doc}"
|
| 1205 |
+
)
|
| 1206 |
+
fn.__doc__ = func_doc
|
| 1207 |
+
return fn
|
| 1208 |
+
|
| 1209 |
+
return docstring_decorator
|
| 1210 |
+
|
| 1211 |
+
|
| 1212 |
+
def copy_func(f):
|
| 1213 |
+
"""Returns a copy of a function f."""
|
| 1214 |
+
# Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)
|
| 1215 |
+
g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__)
|
| 1216 |
+
g = functools.update_wrapper(g, f)
|
| 1217 |
+
g.__kwdefaults__ = f.__kwdefaults__
|
| 1218 |
+
return g
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/dynamic_module_utils.py
ADDED
|
@@ -0,0 +1,702 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 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 |
+
"""Utilities to dynamically load objects from the Hub."""
|
| 15 |
+
|
| 16 |
+
import ast
|
| 17 |
+
import filecmp
|
| 18 |
+
import hashlib
|
| 19 |
+
import importlib
|
| 20 |
+
import importlib.util
|
| 21 |
+
import os
|
| 22 |
+
import re
|
| 23 |
+
import shutil
|
| 24 |
+
import signal
|
| 25 |
+
import sys
|
| 26 |
+
import threading
|
| 27 |
+
import warnings
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from types import ModuleType
|
| 30 |
+
from typing import Any, Optional, Union
|
| 31 |
+
|
| 32 |
+
from huggingface_hub import try_to_load_from_cache
|
| 33 |
+
|
| 34 |
+
from .utils import (
|
| 35 |
+
HF_MODULES_CACHE,
|
| 36 |
+
TRANSFORMERS_DYNAMIC_MODULE_NAME,
|
| 37 |
+
cached_file,
|
| 38 |
+
extract_commit_hash,
|
| 39 |
+
is_offline_mode,
|
| 40 |
+
logging,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 45 |
+
_HF_REMOTE_CODE_LOCK = threading.Lock()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def init_hf_modules():
|
| 49 |
+
"""
|
| 50 |
+
Creates the cache directory for modules with an init, and adds it to the Python path.
|
| 51 |
+
"""
|
| 52 |
+
# This function has already been executed if HF_MODULES_CACHE already is in the Python path.
|
| 53 |
+
if HF_MODULES_CACHE in sys.path:
|
| 54 |
+
return
|
| 55 |
+
|
| 56 |
+
sys.path.append(HF_MODULES_CACHE)
|
| 57 |
+
os.makedirs(HF_MODULES_CACHE, exist_ok=True)
|
| 58 |
+
init_path = Path(HF_MODULES_CACHE) / "__init__.py"
|
| 59 |
+
if not init_path.exists():
|
| 60 |
+
init_path.touch()
|
| 61 |
+
importlib.invalidate_caches()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def create_dynamic_module(name: Union[str, os.PathLike]) -> None:
|
| 65 |
+
"""
|
| 66 |
+
Creates a dynamic module in the cache directory for modules.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
name (`str` or `os.PathLike`):
|
| 70 |
+
The name of the dynamic module to create.
|
| 71 |
+
"""
|
| 72 |
+
init_hf_modules()
|
| 73 |
+
dynamic_module_path = (Path(HF_MODULES_CACHE) / name).resolve()
|
| 74 |
+
# If the parent module does not exist yet, recursively create it.
|
| 75 |
+
if not dynamic_module_path.parent.exists():
|
| 76 |
+
create_dynamic_module(dynamic_module_path.parent)
|
| 77 |
+
os.makedirs(dynamic_module_path, exist_ok=True)
|
| 78 |
+
init_path = dynamic_module_path / "__init__.py"
|
| 79 |
+
if not init_path.exists():
|
| 80 |
+
init_path.touch()
|
| 81 |
+
# It is extremely important to invalidate the cache when we change stuff in those modules, or users end up
|
| 82 |
+
# with errors about module that do not exist. Same for all other `invalidate_caches` in this file.
|
| 83 |
+
importlib.invalidate_caches()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def get_relative_imports(module_file: Union[str, os.PathLike]) -> list[str]:
|
| 87 |
+
"""
|
| 88 |
+
Get the list of modules that are relatively imported in a module file.
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
module_file (`str` or `os.PathLike`): The module file to inspect.
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
`list[str]`: The list of relative imports in the module.
|
| 95 |
+
"""
|
| 96 |
+
with open(module_file, encoding="utf-8") as f:
|
| 97 |
+
content = f.read()
|
| 98 |
+
|
| 99 |
+
# Imports of the form `import .xxx`
|
| 100 |
+
relative_imports = re.findall(r"^\s*import\s+\.(\S+)\s*$", content, flags=re.MULTILINE)
|
| 101 |
+
# Imports of the form `from .xxx import yyy`
|
| 102 |
+
relative_imports += re.findall(r"^\s*from\s+\.(\S+)\s+import", content, flags=re.MULTILINE)
|
| 103 |
+
# Unique-ify
|
| 104 |
+
return list(set(relative_imports))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def get_relative_import_files(module_file: Union[str, os.PathLike]) -> list[str]:
|
| 108 |
+
"""
|
| 109 |
+
Get the list of all files that are needed for a given module. Note that this function recurses through the relative
|
| 110 |
+
imports (if a imports b and b imports c, it will return module files for b and c).
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
module_file (`str` or `os.PathLike`): The module file to inspect.
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
`list[str]`: The list of all relative imports a given module needs (recursively), which will give us the list
|
| 117 |
+
of module files a given module needs.
|
| 118 |
+
"""
|
| 119 |
+
no_change = False
|
| 120 |
+
files_to_check = [module_file]
|
| 121 |
+
all_relative_imports = []
|
| 122 |
+
|
| 123 |
+
# Let's recurse through all relative imports
|
| 124 |
+
while not no_change:
|
| 125 |
+
new_imports = []
|
| 126 |
+
for f in files_to_check:
|
| 127 |
+
new_imports.extend(get_relative_imports(f))
|
| 128 |
+
|
| 129 |
+
module_path = Path(module_file).parent
|
| 130 |
+
new_import_files = [str(module_path / m) for m in new_imports]
|
| 131 |
+
new_import_files = [f for f in new_import_files if f not in all_relative_imports]
|
| 132 |
+
files_to_check = [f"{f}.py" for f in new_import_files]
|
| 133 |
+
|
| 134 |
+
no_change = len(new_import_files) == 0
|
| 135 |
+
all_relative_imports.extend(files_to_check)
|
| 136 |
+
|
| 137 |
+
return all_relative_imports
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def get_imports(filename: Union[str, os.PathLike]) -> list[str]:
|
| 141 |
+
"""
|
| 142 |
+
Extracts all the libraries (not relative imports this time) that are imported in a file.
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
filename (`str` or `os.PathLike`): The module file to inspect.
|
| 146 |
+
|
| 147 |
+
Returns:
|
| 148 |
+
`list[str]`: The list of all packages required to use the input module.
|
| 149 |
+
"""
|
| 150 |
+
with open(filename, encoding="utf-8") as f:
|
| 151 |
+
content = f.read()
|
| 152 |
+
imported_modules = set()
|
| 153 |
+
|
| 154 |
+
def recursive_look_for_imports(node):
|
| 155 |
+
if isinstance(node, ast.Try):
|
| 156 |
+
return # Don't recurse into Try blocks and ignore imports in them
|
| 157 |
+
elif isinstance(node, ast.If):
|
| 158 |
+
test = node.test
|
| 159 |
+
for condition_node in ast.walk(test):
|
| 160 |
+
if isinstance(condition_node, ast.Call) and getattr(condition_node.func, "id", "").startswith(
|
| 161 |
+
"is_flash_attn"
|
| 162 |
+
):
|
| 163 |
+
# Don't recurse into "if flash_attn_available()" blocks and ignore imports in them
|
| 164 |
+
return
|
| 165 |
+
elif isinstance(node, ast.Import):
|
| 166 |
+
# Handle 'import x' statements
|
| 167 |
+
for alias in node.names:
|
| 168 |
+
top_module = alias.name.split(".")[0]
|
| 169 |
+
if top_module:
|
| 170 |
+
imported_modules.add(top_module)
|
| 171 |
+
elif isinstance(node, ast.ImportFrom):
|
| 172 |
+
# Handle 'from x import y' statements, ignoring relative imports
|
| 173 |
+
if node.level == 0 and node.module:
|
| 174 |
+
top_module = node.module.split(".")[0]
|
| 175 |
+
if top_module:
|
| 176 |
+
imported_modules.add(top_module)
|
| 177 |
+
|
| 178 |
+
# Recursively visit all children
|
| 179 |
+
for child in ast.iter_child_nodes(node):
|
| 180 |
+
recursive_look_for_imports(child)
|
| 181 |
+
|
| 182 |
+
tree = ast.parse(content)
|
| 183 |
+
recursive_look_for_imports(tree)
|
| 184 |
+
|
| 185 |
+
return sorted(imported_modules)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def check_imports(filename: Union[str, os.PathLike]) -> list[str]:
|
| 189 |
+
"""
|
| 190 |
+
Check if the current Python environment contains all the libraries that are imported in a file. Will raise if a
|
| 191 |
+
library is missing.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
filename (`str` or `os.PathLike`): The module file to check.
|
| 195 |
+
|
| 196 |
+
Returns:
|
| 197 |
+
`list[str]`: The list of relative imports in the file.
|
| 198 |
+
"""
|
| 199 |
+
imports = get_imports(filename)
|
| 200 |
+
missing_packages = []
|
| 201 |
+
for imp in imports:
|
| 202 |
+
try:
|
| 203 |
+
importlib.import_module(imp)
|
| 204 |
+
except ImportError as exception:
|
| 205 |
+
logger.warning(f"Encountered exception while importing {imp}: {exception}")
|
| 206 |
+
# Some packages can fail with an ImportError because of a dependency issue.
|
| 207 |
+
# This check avoids hiding such errors.
|
| 208 |
+
# See https://github.com/huggingface/transformers/issues/33604
|
| 209 |
+
if "No module named" in str(exception):
|
| 210 |
+
missing_packages.append(imp)
|
| 211 |
+
else:
|
| 212 |
+
raise
|
| 213 |
+
|
| 214 |
+
if len(missing_packages) > 0:
|
| 215 |
+
raise ImportError(
|
| 216 |
+
"This modeling file requires the following packages that were not found in your environment: "
|
| 217 |
+
f"{', '.join(missing_packages)}. Run `pip install {' '.join(missing_packages)}`"
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
return get_relative_imports(filename)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def get_class_in_module(
|
| 224 |
+
class_name: str,
|
| 225 |
+
module_path: Union[str, os.PathLike],
|
| 226 |
+
*,
|
| 227 |
+
force_reload: bool = False,
|
| 228 |
+
) -> type:
|
| 229 |
+
"""
|
| 230 |
+
Import a module on the cache directory for modules and extract a class from it.
|
| 231 |
+
|
| 232 |
+
Args:
|
| 233 |
+
class_name (`str`): The name of the class to import.
|
| 234 |
+
module_path (`str` or `os.PathLike`): The path to the module to import.
|
| 235 |
+
force_reload (`bool`, *optional*, defaults to `False`):
|
| 236 |
+
Whether to reload the dynamic module from file if it already exists in `sys.modules`.
|
| 237 |
+
Otherwise, the module is only reloaded if the file has changed.
|
| 238 |
+
|
| 239 |
+
Returns:
|
| 240 |
+
`typing.Type`: The class looked for.
|
| 241 |
+
"""
|
| 242 |
+
name = os.path.normpath(module_path)
|
| 243 |
+
if name.endswith(".py"):
|
| 244 |
+
name = name[:-3]
|
| 245 |
+
name = name.replace(os.path.sep, ".")
|
| 246 |
+
module_file: Path = Path(HF_MODULES_CACHE) / module_path
|
| 247 |
+
with _HF_REMOTE_CODE_LOCK:
|
| 248 |
+
if force_reload:
|
| 249 |
+
sys.modules.pop(name, None)
|
| 250 |
+
importlib.invalidate_caches()
|
| 251 |
+
cached_module: Optional[ModuleType] = sys.modules.get(name)
|
| 252 |
+
module_spec = importlib.util.spec_from_file_location(name, location=module_file)
|
| 253 |
+
|
| 254 |
+
# Hash the module file and all its relative imports to check if we need to reload it
|
| 255 |
+
module_files: list[Path] = [module_file] + sorted(map(Path, get_relative_import_files(module_file)))
|
| 256 |
+
module_hash: str = hashlib.sha256(b"".join(bytes(f) + f.read_bytes() for f in module_files)).hexdigest()
|
| 257 |
+
|
| 258 |
+
module: ModuleType
|
| 259 |
+
if cached_module is None:
|
| 260 |
+
module = importlib.util.module_from_spec(module_spec)
|
| 261 |
+
# insert it into sys.modules before any loading begins
|
| 262 |
+
sys.modules[name] = module
|
| 263 |
+
else:
|
| 264 |
+
module = cached_module
|
| 265 |
+
# reload in both cases, unless the module is already imported and the hash hits
|
| 266 |
+
if getattr(module, "__transformers_module_hash__", "") != module_hash:
|
| 267 |
+
module_spec.loader.exec_module(module)
|
| 268 |
+
module.__transformers_module_hash__ = module_hash
|
| 269 |
+
return getattr(module, class_name)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def get_cached_module_file(
|
| 273 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 274 |
+
module_file: str,
|
| 275 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 276 |
+
force_download: bool = False,
|
| 277 |
+
resume_download: Optional[bool] = None,
|
| 278 |
+
proxies: Optional[dict[str, str]] = None,
|
| 279 |
+
token: Optional[Union[bool, str]] = None,
|
| 280 |
+
revision: Optional[str] = None,
|
| 281 |
+
local_files_only: bool = False,
|
| 282 |
+
repo_type: Optional[str] = None,
|
| 283 |
+
_commit_hash: Optional[str] = None,
|
| 284 |
+
**deprecated_kwargs,
|
| 285 |
+
) -> str:
|
| 286 |
+
"""
|
| 287 |
+
Prepares Downloads a module from a local folder or a distant repo and returns its path inside the cached
|
| 288 |
+
Transformers module.
|
| 289 |
+
|
| 290 |
+
Args:
|
| 291 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 292 |
+
This can be either:
|
| 293 |
+
|
| 294 |
+
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
| 295 |
+
huggingface.co.
|
| 296 |
+
- a path to a *directory* containing a configuration file saved using the
|
| 297 |
+
[`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
|
| 298 |
+
|
| 299 |
+
module_file (`str`):
|
| 300 |
+
The name of the module file containing the class to look for.
|
| 301 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 302 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
|
| 303 |
+
cache should not be used.
|
| 304 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 305 |
+
Whether or not to force to (re-)download the configuration files and override the cached versions if they
|
| 306 |
+
exist.
|
| 307 |
+
resume_download:
|
| 308 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 309 |
+
Will be removed in v5 of Transformers.
|
| 310 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 311 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 312 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 313 |
+
token (`str` or *bool*, *optional*):
|
| 314 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 315 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 316 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 317 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 318 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 319 |
+
identifier allowed by git.
|
| 320 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 321 |
+
If `True`, will only try to load the tokenizer configuration from local files.
|
| 322 |
+
repo_type (`str`, *optional*):
|
| 323 |
+
Specify the repo type (useful when downloading from a space for instance).
|
| 324 |
+
|
| 325 |
+
<Tip>
|
| 326 |
+
|
| 327 |
+
Passing `token=True` is required when you want to use a private model.
|
| 328 |
+
|
| 329 |
+
</Tip>
|
| 330 |
+
|
| 331 |
+
Returns:
|
| 332 |
+
`str`: The path to the module inside the cache.
|
| 333 |
+
"""
|
| 334 |
+
use_auth_token = deprecated_kwargs.pop("use_auth_token", None)
|
| 335 |
+
if use_auth_token is not None:
|
| 336 |
+
warnings.warn(
|
| 337 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 338 |
+
FutureWarning,
|
| 339 |
+
)
|
| 340 |
+
if token is not None:
|
| 341 |
+
raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
|
| 342 |
+
token = use_auth_token
|
| 343 |
+
|
| 344 |
+
if is_offline_mode() and not local_files_only:
|
| 345 |
+
logger.info("Offline mode: forcing local_files_only=True")
|
| 346 |
+
local_files_only = True
|
| 347 |
+
|
| 348 |
+
# Download and cache module_file from the repo `pretrained_model_name_or_path` of grab it if it's a local file.
|
| 349 |
+
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
|
| 350 |
+
is_local = os.path.isdir(pretrained_model_name_or_path)
|
| 351 |
+
if is_local:
|
| 352 |
+
submodule = os.path.basename(pretrained_model_name_or_path)
|
| 353 |
+
else:
|
| 354 |
+
submodule = pretrained_model_name_or_path.replace("/", os.path.sep)
|
| 355 |
+
cached_module = try_to_load_from_cache(
|
| 356 |
+
pretrained_model_name_or_path, module_file, cache_dir=cache_dir, revision=_commit_hash, repo_type=repo_type
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
new_files = []
|
| 360 |
+
try:
|
| 361 |
+
# Load from URL or cache if already cached
|
| 362 |
+
resolved_module_file = cached_file(
|
| 363 |
+
pretrained_model_name_or_path,
|
| 364 |
+
module_file,
|
| 365 |
+
cache_dir=cache_dir,
|
| 366 |
+
force_download=force_download,
|
| 367 |
+
proxies=proxies,
|
| 368 |
+
resume_download=resume_download,
|
| 369 |
+
local_files_only=local_files_only,
|
| 370 |
+
token=token,
|
| 371 |
+
revision=revision,
|
| 372 |
+
repo_type=repo_type,
|
| 373 |
+
_commit_hash=_commit_hash,
|
| 374 |
+
)
|
| 375 |
+
if not is_local and cached_module != resolved_module_file:
|
| 376 |
+
new_files.append(module_file)
|
| 377 |
+
|
| 378 |
+
except OSError:
|
| 379 |
+
logger.error(f"Could not locate the {module_file} inside {pretrained_model_name_or_path}.")
|
| 380 |
+
raise
|
| 381 |
+
|
| 382 |
+
# Check we have all the requirements in our environment
|
| 383 |
+
modules_needed = check_imports(resolved_module_file)
|
| 384 |
+
|
| 385 |
+
# Now we move the module inside our cached dynamic modules.
|
| 386 |
+
full_submodule = TRANSFORMERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
|
| 387 |
+
create_dynamic_module(full_submodule)
|
| 388 |
+
submodule_path = Path(HF_MODULES_CACHE) / full_submodule
|
| 389 |
+
if submodule == os.path.basename(pretrained_model_name_or_path):
|
| 390 |
+
# We copy local files to avoid putting too many folders in sys.path. This copy is done when the file is new or
|
| 391 |
+
# has changed since last copy.
|
| 392 |
+
if not (submodule_path / module_file).exists() or not filecmp.cmp(
|
| 393 |
+
resolved_module_file, str(submodule_path / module_file)
|
| 394 |
+
):
|
| 395 |
+
shutil.copy(resolved_module_file, submodule_path / module_file)
|
| 396 |
+
importlib.invalidate_caches()
|
| 397 |
+
for module_needed in modules_needed:
|
| 398 |
+
module_needed = f"{module_needed}.py"
|
| 399 |
+
module_needed_file = os.path.join(pretrained_model_name_or_path, module_needed)
|
| 400 |
+
if not (submodule_path / module_needed).exists() or not filecmp.cmp(
|
| 401 |
+
module_needed_file, str(submodule_path / module_needed)
|
| 402 |
+
):
|
| 403 |
+
shutil.copy(module_needed_file, submodule_path / module_needed)
|
| 404 |
+
importlib.invalidate_caches()
|
| 405 |
+
else:
|
| 406 |
+
# Get the commit hash
|
| 407 |
+
commit_hash = extract_commit_hash(resolved_module_file, _commit_hash)
|
| 408 |
+
|
| 409 |
+
# The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
|
| 410 |
+
# benefit of versioning.
|
| 411 |
+
submodule_path = submodule_path / commit_hash
|
| 412 |
+
full_submodule = full_submodule + os.path.sep + commit_hash
|
| 413 |
+
create_dynamic_module(full_submodule)
|
| 414 |
+
|
| 415 |
+
if not (submodule_path / module_file).exists():
|
| 416 |
+
shutil.copy(resolved_module_file, submodule_path / module_file)
|
| 417 |
+
importlib.invalidate_caches()
|
| 418 |
+
# Make sure we also have every file with relative
|
| 419 |
+
for module_needed in modules_needed:
|
| 420 |
+
if not (submodule_path / f"{module_needed}.py").exists():
|
| 421 |
+
get_cached_module_file(
|
| 422 |
+
pretrained_model_name_or_path,
|
| 423 |
+
f"{module_needed}.py",
|
| 424 |
+
cache_dir=cache_dir,
|
| 425 |
+
force_download=force_download,
|
| 426 |
+
resume_download=resume_download,
|
| 427 |
+
proxies=proxies,
|
| 428 |
+
token=token,
|
| 429 |
+
revision=revision,
|
| 430 |
+
local_files_only=local_files_only,
|
| 431 |
+
_commit_hash=commit_hash,
|
| 432 |
+
)
|
| 433 |
+
new_files.append(f"{module_needed}.py")
|
| 434 |
+
|
| 435 |
+
if len(new_files) > 0 and revision is None:
|
| 436 |
+
new_files = "\n".join([f"- {f}" for f in new_files])
|
| 437 |
+
repo_type_str = "" if repo_type is None else f"{repo_type}s/"
|
| 438 |
+
url = f"https://huggingface.co/{repo_type_str}{pretrained_model_name_or_path}"
|
| 439 |
+
logger.warning(
|
| 440 |
+
f"A new version of the following files was downloaded from {url}:\n{new_files}"
|
| 441 |
+
"\n. Make sure to double-check they do not contain any added malicious code. To avoid downloading new "
|
| 442 |
+
"versions of the code file, you can pin a revision."
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
return os.path.join(full_submodule, module_file)
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def get_class_from_dynamic_module(
|
| 449 |
+
class_reference: str,
|
| 450 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 451 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 452 |
+
force_download: bool = False,
|
| 453 |
+
resume_download: Optional[bool] = None,
|
| 454 |
+
proxies: Optional[dict[str, str]] = None,
|
| 455 |
+
token: Optional[Union[bool, str]] = None,
|
| 456 |
+
revision: Optional[str] = None,
|
| 457 |
+
local_files_only: bool = False,
|
| 458 |
+
repo_type: Optional[str] = None,
|
| 459 |
+
code_revision: Optional[str] = None,
|
| 460 |
+
**kwargs,
|
| 461 |
+
) -> type:
|
| 462 |
+
"""
|
| 463 |
+
Extracts a class from a module file, present in the local folder or repository of a model.
|
| 464 |
+
|
| 465 |
+
<Tip warning={true}>
|
| 466 |
+
|
| 467 |
+
Calling this function will execute the code in the module file found locally or downloaded from the Hub. It should
|
| 468 |
+
therefore only be called on trusted repos.
|
| 469 |
+
|
| 470 |
+
</Tip>
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
Args:
|
| 475 |
+
class_reference (`str`):
|
| 476 |
+
The full name of the class to load, including its module and optionally its repo.
|
| 477 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 478 |
+
This can be either:
|
| 479 |
+
|
| 480 |
+
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
| 481 |
+
huggingface.co.
|
| 482 |
+
- a path to a *directory* containing a configuration file saved using the
|
| 483 |
+
[`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
|
| 484 |
+
|
| 485 |
+
This is used when `class_reference` does not specify another repo.
|
| 486 |
+
module_file (`str`):
|
| 487 |
+
The name of the module file containing the class to look for.
|
| 488 |
+
class_name (`str`):
|
| 489 |
+
The name of the class to import in the module.
|
| 490 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 491 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
|
| 492 |
+
cache should not be used.
|
| 493 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 494 |
+
Whether or not to force to (re-)download the configuration files and override the cached versions if they
|
| 495 |
+
exist.
|
| 496 |
+
resume_download:
|
| 497 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 498 |
+
Will be removed in v5 of Transformers.
|
| 499 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 500 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 501 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 502 |
+
token (`str` or `bool`, *optional*):
|
| 503 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 504 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 505 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 506 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 507 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 508 |
+
identifier allowed by git.
|
| 509 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 510 |
+
If `True`, will only try to load the tokenizer configuration from local files.
|
| 511 |
+
repo_type (`str`, *optional*):
|
| 512 |
+
Specify the repo type (useful when downloading from a space for instance).
|
| 513 |
+
code_revision (`str`, *optional*, defaults to `"main"`):
|
| 514 |
+
The specific revision to use for the code on the Hub, if the code leaves in a different repository than the
|
| 515 |
+
rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for
|
| 516 |
+
storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
|
| 517 |
+
|
| 518 |
+
<Tip>
|
| 519 |
+
|
| 520 |
+
Passing `token=True` is required when you want to use a private model.
|
| 521 |
+
|
| 522 |
+
</Tip>
|
| 523 |
+
|
| 524 |
+
Returns:
|
| 525 |
+
`typing.Type`: The class, dynamically imported from the module.
|
| 526 |
+
|
| 527 |
+
Examples:
|
| 528 |
+
|
| 529 |
+
```python
|
| 530 |
+
# Download module `modeling.py` from huggingface.co and cache then extract the class `MyBertModel` from this
|
| 531 |
+
# module.
|
| 532 |
+
cls = get_class_from_dynamic_module("modeling.MyBertModel", "sgugger/my-bert-model")
|
| 533 |
+
|
| 534 |
+
# Download module `modeling.py` from a given repo and cache then extract the class `MyBertModel` from this
|
| 535 |
+
# module.
|
| 536 |
+
cls = get_class_from_dynamic_module("sgugger/my-bert-model--modeling.MyBertModel", "sgugger/another-bert-model")
|
| 537 |
+
```"""
|
| 538 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 539 |
+
if use_auth_token is not None:
|
| 540 |
+
warnings.warn(
|
| 541 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 542 |
+
FutureWarning,
|
| 543 |
+
)
|
| 544 |
+
if token is not None:
|
| 545 |
+
raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
|
| 546 |
+
token = use_auth_token
|
| 547 |
+
|
| 548 |
+
# Catch the name of the repo if it's specified in `class_reference`
|
| 549 |
+
if "--" in class_reference:
|
| 550 |
+
repo_id, class_reference = class_reference.split("--")
|
| 551 |
+
else:
|
| 552 |
+
repo_id = pretrained_model_name_or_path
|
| 553 |
+
module_file, class_name = class_reference.split(".")
|
| 554 |
+
|
| 555 |
+
if code_revision is None and pretrained_model_name_or_path == repo_id:
|
| 556 |
+
code_revision = revision
|
| 557 |
+
# And lastly we get the class inside our newly created module
|
| 558 |
+
final_module = get_cached_module_file(
|
| 559 |
+
repo_id,
|
| 560 |
+
module_file + ".py",
|
| 561 |
+
cache_dir=cache_dir,
|
| 562 |
+
force_download=force_download,
|
| 563 |
+
resume_download=resume_download,
|
| 564 |
+
proxies=proxies,
|
| 565 |
+
token=token,
|
| 566 |
+
revision=code_revision,
|
| 567 |
+
local_files_only=local_files_only,
|
| 568 |
+
repo_type=repo_type,
|
| 569 |
+
)
|
| 570 |
+
return get_class_in_module(class_name, final_module, force_reload=force_download)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def custom_object_save(obj: Any, folder: Union[str, os.PathLike], config: Optional[dict] = None) -> list[str]:
|
| 574 |
+
"""
|
| 575 |
+
Save the modeling files corresponding to a custom model/configuration/tokenizer etc. in a given folder. Optionally
|
| 576 |
+
adds the proper fields in a config.
|
| 577 |
+
|
| 578 |
+
Args:
|
| 579 |
+
obj (`Any`): The object for which to save the module files.
|
| 580 |
+
folder (`str` or `os.PathLike`): The folder where to save.
|
| 581 |
+
config (`PretrainedConfig` or dictionary, `optional`):
|
| 582 |
+
A config in which to register the auto_map corresponding to this custom object.
|
| 583 |
+
|
| 584 |
+
Returns:
|
| 585 |
+
`List[str]`: The list of files saved.
|
| 586 |
+
"""
|
| 587 |
+
if obj.__module__ == "__main__":
|
| 588 |
+
logger.warning(
|
| 589 |
+
f"We can't save the code defining {obj} in {folder} as it's been defined in __main__. You should put "
|
| 590 |
+
"this code in a separate module so we can include it in the saved folder and make it easier to share via "
|
| 591 |
+
"the Hub."
|
| 592 |
+
)
|
| 593 |
+
return
|
| 594 |
+
|
| 595 |
+
def _set_auto_map_in_config(_config):
|
| 596 |
+
module_name = obj.__class__.__module__
|
| 597 |
+
last_module = module_name.split(".")[-1]
|
| 598 |
+
full_name = f"{last_module}.{obj.__class__.__name__}"
|
| 599 |
+
# Special handling for tokenizers
|
| 600 |
+
if "Tokenizer" in full_name:
|
| 601 |
+
slow_tokenizer_class = None
|
| 602 |
+
fast_tokenizer_class = None
|
| 603 |
+
if obj.__class__.__name__.endswith("Fast"):
|
| 604 |
+
# Fast tokenizer: we have the fast tokenizer class and we may have the slow one has an attribute.
|
| 605 |
+
fast_tokenizer_class = f"{last_module}.{obj.__class__.__name__}"
|
| 606 |
+
if getattr(obj, "slow_tokenizer_class", None) is not None:
|
| 607 |
+
slow_tokenizer = getattr(obj, "slow_tokenizer_class")
|
| 608 |
+
slow_tok_module_name = slow_tokenizer.__module__
|
| 609 |
+
last_slow_tok_module = slow_tok_module_name.split(".")[-1]
|
| 610 |
+
slow_tokenizer_class = f"{last_slow_tok_module}.{slow_tokenizer.__name__}"
|
| 611 |
+
else:
|
| 612 |
+
# Slow tokenizer: no way to have the fast class
|
| 613 |
+
slow_tokenizer_class = f"{last_module}.{obj.__class__.__name__}"
|
| 614 |
+
|
| 615 |
+
full_name = (slow_tokenizer_class, fast_tokenizer_class)
|
| 616 |
+
|
| 617 |
+
if isinstance(_config, dict):
|
| 618 |
+
auto_map = _config.get("auto_map", {})
|
| 619 |
+
auto_map[obj._auto_class] = full_name
|
| 620 |
+
_config["auto_map"] = auto_map
|
| 621 |
+
elif getattr(_config, "auto_map", None) is not None:
|
| 622 |
+
_config.auto_map[obj._auto_class] = full_name
|
| 623 |
+
else:
|
| 624 |
+
_config.auto_map = {obj._auto_class: full_name}
|
| 625 |
+
|
| 626 |
+
# Add object class to the config auto_map
|
| 627 |
+
if isinstance(config, (list, tuple)):
|
| 628 |
+
for cfg in config:
|
| 629 |
+
_set_auto_map_in_config(cfg)
|
| 630 |
+
elif config is not None:
|
| 631 |
+
_set_auto_map_in_config(config)
|
| 632 |
+
|
| 633 |
+
result = []
|
| 634 |
+
# Copy module file to the output folder.
|
| 635 |
+
object_file = sys.modules[obj.__module__].__file__
|
| 636 |
+
dest_file = Path(folder) / (Path(object_file).name)
|
| 637 |
+
shutil.copy(object_file, dest_file)
|
| 638 |
+
result.append(dest_file)
|
| 639 |
+
|
| 640 |
+
# Gather all relative imports recursively and make sure they are copied as well.
|
| 641 |
+
for needed_file in get_relative_import_files(object_file):
|
| 642 |
+
dest_file = Path(folder) / (Path(needed_file).name)
|
| 643 |
+
shutil.copy(needed_file, dest_file)
|
| 644 |
+
result.append(dest_file)
|
| 645 |
+
|
| 646 |
+
return result
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def _raise_timeout_error(signum, frame):
|
| 650 |
+
raise ValueError(
|
| 651 |
+
"Loading this model requires you to execute custom code contained in the model repository on your local "
|
| 652 |
+
"machine. Please set the option `trust_remote_code=True` to permit loading of this model."
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
TIME_OUT_REMOTE_CODE = 15
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def resolve_trust_remote_code(trust_remote_code, model_name, has_local_code, has_remote_code):
|
| 660 |
+
if trust_remote_code is None:
|
| 661 |
+
if has_local_code:
|
| 662 |
+
trust_remote_code = False
|
| 663 |
+
elif has_remote_code and TIME_OUT_REMOTE_CODE > 0:
|
| 664 |
+
prev_sig_handler = None
|
| 665 |
+
try:
|
| 666 |
+
prev_sig_handler = signal.signal(signal.SIGALRM, _raise_timeout_error)
|
| 667 |
+
signal.alarm(TIME_OUT_REMOTE_CODE)
|
| 668 |
+
while trust_remote_code is None:
|
| 669 |
+
answer = input(
|
| 670 |
+
f"The repository for {model_name} contains custom code which must be executed to correctly "
|
| 671 |
+
f"load the model. You can inspect the repository content at https://hf.co/{model_name}.\n"
|
| 672 |
+
f"You can avoid this prompt in future by passing the argument `trust_remote_code=True`.\n\n"
|
| 673 |
+
f"Do you wish to run the custom code? [y/N] "
|
| 674 |
+
)
|
| 675 |
+
if answer.lower() in ["yes", "y", "1"]:
|
| 676 |
+
trust_remote_code = True
|
| 677 |
+
elif answer.lower() in ["no", "n", "0", ""]:
|
| 678 |
+
trust_remote_code = False
|
| 679 |
+
signal.alarm(0)
|
| 680 |
+
except Exception:
|
| 681 |
+
# OS which does not support signal.SIGALRM
|
| 682 |
+
raise ValueError(
|
| 683 |
+
f"The repository for {model_name} contains custom code which must be executed to correctly "
|
| 684 |
+
f"load the model. You can inspect the repository content at https://hf.co/{model_name}.\n"
|
| 685 |
+
f"Please pass the argument `trust_remote_code=True` to allow custom code to be run."
|
| 686 |
+
)
|
| 687 |
+
finally:
|
| 688 |
+
if prev_sig_handler is not None:
|
| 689 |
+
signal.signal(signal.SIGALRM, prev_sig_handler)
|
| 690 |
+
signal.alarm(0)
|
| 691 |
+
elif has_remote_code:
|
| 692 |
+
# For the CI which puts the timeout at 0
|
| 693 |
+
_raise_timeout_error(None, None)
|
| 694 |
+
|
| 695 |
+
if has_remote_code and not has_local_code and not trust_remote_code:
|
| 696 |
+
raise ValueError(
|
| 697 |
+
f"Loading {model_name} requires you to execute the configuration file in that"
|
| 698 |
+
" repo on your local machine. Make sure you have read the code there to avoid malicious use, then"
|
| 699 |
+
" set the option `trust_remote_code=True` to remove this error."
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
return trust_remote_code
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/eetq.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 NetEase, Inc. 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 |
+
from ..utils import is_accelerate_available, is_eetq_available, logging
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if is_eetq_available():
|
| 19 |
+
import eetq
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
|
| 22 |
+
if is_accelerate_available():
|
| 23 |
+
from accelerate import init_empty_weights
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _replace_with_eetq_linear(
|
| 29 |
+
model,
|
| 30 |
+
modules_to_not_convert=None,
|
| 31 |
+
current_key_name=None,
|
| 32 |
+
quantization_config=None,
|
| 33 |
+
has_been_replaced=False,
|
| 34 |
+
pre_quantized=False,
|
| 35 |
+
):
|
| 36 |
+
"""
|
| 37 |
+
Private method that wraps the recursion for module replacement.
|
| 38 |
+
|
| 39 |
+
Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
|
| 40 |
+
"""
|
| 41 |
+
if current_key_name is None:
|
| 42 |
+
current_key_name = []
|
| 43 |
+
|
| 44 |
+
for name, module in model.named_children():
|
| 45 |
+
current_key_name.append(name)
|
| 46 |
+
|
| 47 |
+
if (isinstance(module, nn.Linear)) and name not in modules_to_not_convert:
|
| 48 |
+
# Check if the current key is not in the `modules_to_not_convert`
|
| 49 |
+
current_key_name_str = ".".join(current_key_name)
|
| 50 |
+
if not any(
|
| 51 |
+
(key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
|
| 52 |
+
):
|
| 53 |
+
with init_empty_weights():
|
| 54 |
+
in_features = module.in_features
|
| 55 |
+
out_features = module.out_features
|
| 56 |
+
model._modules[name] = eetq.EetqLinear(
|
| 57 |
+
in_features, out_features, module.bias is not None, module.weight.device
|
| 58 |
+
)
|
| 59 |
+
if pre_quantized:
|
| 60 |
+
model._modules[name].register_scale(module.weight.device)
|
| 61 |
+
has_been_replaced = True
|
| 62 |
+
|
| 63 |
+
# Force requires grad to False to avoid unexpected errors
|
| 64 |
+
model._modules[name].requires_grad_(False)
|
| 65 |
+
if len(list(module.children())) > 0:
|
| 66 |
+
_, has_been_replaced = _replace_with_eetq_linear(
|
| 67 |
+
module,
|
| 68 |
+
modules_to_not_convert,
|
| 69 |
+
current_key_name,
|
| 70 |
+
quantization_config,
|
| 71 |
+
has_been_replaced=has_been_replaced,
|
| 72 |
+
pre_quantized=pre_quantized,
|
| 73 |
+
)
|
| 74 |
+
# Remove the last key for recursion
|
| 75 |
+
current_key_name.pop(-1)
|
| 76 |
+
return model, has_been_replaced
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def replace_with_eetq_linear(
|
| 80 |
+
model, modules_to_not_convert=None, current_key_name=None, quantization_config=None, pre_quantized=False
|
| 81 |
+
):
|
| 82 |
+
"""
|
| 83 |
+
A helper function to replace all `torch.nn.Linear` modules by `eetq.EetqLinear` modules from the `eetq`
|
| 84 |
+
library. This will enable running your models using high performance int8 weight-only gemm kerner from
|
| 85 |
+
FasterTransformer and TensorRT-LLM. Make sure `eetq` compiled with the correct CUDA
|
| 86 |
+
version of your hardware is installed before running this function. EETQ shall be installed via the source
|
| 87 |
+
'https://github.com/NetEase-FuXi/EETQ'
|
| 88 |
+
|
| 89 |
+
The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
|
| 90 |
+
be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
|
| 91 |
+
CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
|
| 92 |
+
|
| 93 |
+
Parameters:
|
| 94 |
+
model (`torch.nn.Module`):
|
| 95 |
+
Input model or `torch.nn.Module` as the function is run recursively.
|
| 96 |
+
modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
|
| 97 |
+
Names of the modules to not convert in `EetqLinear`. In practice we keep the `lm_head` in full precision
|
| 98 |
+
for numerical stability reasons.
|
| 99 |
+
current_key_name (`List[`str`]`, *optional*):
|
| 100 |
+
An array to track the current key of the recursion. This is used to check whether the current key (part of
|
| 101 |
+
it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
|
| 102 |
+
`disk`).
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
|
| 106 |
+
|
| 107 |
+
if quantization_config.modules_to_not_convert is not None:
|
| 108 |
+
modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
|
| 109 |
+
modules_to_not_convert = list(set(modules_to_not_convert))
|
| 110 |
+
model, has_been_replaced = _replace_with_eetq_linear(
|
| 111 |
+
model, modules_to_not_convert, current_key_name, quantization_config, pre_quantized=pre_quantized
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
if not has_been_replaced:
|
| 115 |
+
logger.warning(
|
| 116 |
+
"You are loading your model using eetq but no linear modules were found in your model."
|
| 117 |
+
" Please double check your model architecture, or submit an issue on github if you think this is"
|
| 118 |
+
" a bug."
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
return model
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/eval_results.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"epoch": 0.007551029617484695,
|
| 3 |
+
"eval_loss": 8.239520072937012,
|
| 4 |
+
"eval_perplexity": 3787.722041573,
|
| 5 |
+
"eval_runtime": 9.0399,
|
| 6 |
+
"eval_samples_per_second": 468.808,
|
| 7 |
+
"eval_steps_per_second": 29.314
|
| 8 |
+
}
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/executorch.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 5 |
+
# the License. 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 distributed under the License is distributed on
|
| 10 |
+
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 11 |
+
# specific language governing permissions and limitations under the License.
|
| 12 |
+
|
| 13 |
+
from typing import Optional
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
from transformers.generation.configuration_utils import GenerationConfig
|
| 18 |
+
|
| 19 |
+
from ..utils.import_utils import is_torch_available
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if is_torch_available():
|
| 23 |
+
from transformers import PreTrainedModel, StaticCache
|
| 24 |
+
from transformers.pytorch_utils import is_torch_greater_or_equal, is_torch_greater_or_equal_than_2_3
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class TorchExportableModuleWithStaticCache(torch.nn.Module):
|
| 28 |
+
"""
|
| 29 |
+
A wrapper module designed to make a `PreTrainedModel` exportable with `torch.export`,
|
| 30 |
+
specifically for use with static caching. This module ensures that the exported model
|
| 31 |
+
is compatible with further lowering and execution in `ExecuTorch`.
|
| 32 |
+
|
| 33 |
+
Note:
|
| 34 |
+
This class is specifically designed to support export process using `torch.export`
|
| 35 |
+
in a way that ensures the model can be further lowered and run efficiently in `ExecuTorch`.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(self, model: PreTrainedModel):
|
| 39 |
+
"""
|
| 40 |
+
Initializes the wrapper module with the pretrained model.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
model (`PreTrainedModel`): The pretrained model to wrap. The model must have caching
|
| 44 |
+
enabled and use a 'static' caching implementation.
|
| 45 |
+
|
| 46 |
+
Raises:
|
| 47 |
+
AssertionError: If the pretrained model does not have caching enabled or if it does
|
| 48 |
+
not use a 'static' caching implementation in `model.generation_config`.
|
| 49 |
+
"""
|
| 50 |
+
super().__init__()
|
| 51 |
+
|
| 52 |
+
# Sanity checks
|
| 53 |
+
if model.generation_config is None:
|
| 54 |
+
raise AssertionError(
|
| 55 |
+
"The model must have a generation config to be exported with static caching. "
|
| 56 |
+
"Please set `generation_config`."
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
if not model.generation_config.use_cache:
|
| 60 |
+
raise AssertionError(
|
| 61 |
+
"The model must have caching enabled to be exported with static caching. "
|
| 62 |
+
"Please set `generation_config.use_cache=True`."
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
if model.generation_config.cache_implementation != "static":
|
| 66 |
+
raise AssertionError(
|
| 67 |
+
"The model must use a 'static' caching implementation to be exported with static caching. "
|
| 68 |
+
"Please set `generation_config.cache_implementation='static'`."
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
self.model = model
|
| 72 |
+
self.static_cache = StaticCache(
|
| 73 |
+
config=self.model.config,
|
| 74 |
+
max_batch_size=self.model.generation_config.cache_config.batch_size,
|
| 75 |
+
max_cache_len=self.model.generation_config.cache_config.max_cache_len,
|
| 76 |
+
device=self.model.generation_config.cache_config.device,
|
| 77 |
+
dtype=self.model.dtype,
|
| 78 |
+
)
|
| 79 |
+
for i in range(len(self.static_cache.key_cache)):
|
| 80 |
+
self.register_buffer(f"key_cache_{i}", self.static_cache.key_cache[i], persistent=False)
|
| 81 |
+
self.register_buffer(f"value_cache_{i}", self.static_cache.value_cache[i], persistent=False)
|
| 82 |
+
|
| 83 |
+
self.is_causal = any("CausalLM" in arch for arch in self.model.config.architectures)
|
| 84 |
+
if self.is_causal:
|
| 85 |
+
causal_mask = torch.tril(
|
| 86 |
+
torch.ones(
|
| 87 |
+
self.static_cache.max_cache_len,
|
| 88 |
+
self.static_cache.max_cache_len,
|
| 89 |
+
dtype=torch.bool,
|
| 90 |
+
)
|
| 91 |
+
)
|
| 92 |
+
self.register_buffer("mask", causal_mask, persistent=False)
|
| 93 |
+
|
| 94 |
+
def forward(self, input_ids: torch.Tensor, cache_position: torch.Tensor):
|
| 95 |
+
"""
|
| 96 |
+
Forward pass of the module, which is compatible with the ExecuTorch runtime.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
input_ids (`torch.Tensor`): Tensor representing current input token id to the module.
|
| 100 |
+
cache_position (`torch.Tensor`): Tensor representing current input position in the cache.
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
torch.Tensor: Logits output from the model.
|
| 104 |
+
|
| 105 |
+
This forward adapter serves two primary purposes:
|
| 106 |
+
|
| 107 |
+
1. **Making the Model `torch.export`-Compatible**:
|
| 108 |
+
The adapter hides unsupported objects, such as the `Cache`, from the graph inputs and outputs,
|
| 109 |
+
enabling the model to be exportable using `torch.export` without encountering issues.
|
| 110 |
+
|
| 111 |
+
2. **Ensuring Compatibility with `ExecuTorch` runtime**:
|
| 112 |
+
The adapter matches the model's forward signature with that in `executorch/extension/llm/runner`,
|
| 113 |
+
ensuring that the exported model can be executed in `ExecuTorch` out-of-the-box.
|
| 114 |
+
"""
|
| 115 |
+
_, seqlen = input_ids.shape
|
| 116 |
+
attn_mask = self.mask[cache_position, :seqlen] if self.is_causal else None
|
| 117 |
+
position_ids = cache_position.unsqueeze(0)
|
| 118 |
+
past_key_values = self.static_cache
|
| 119 |
+
|
| 120 |
+
outs = self.model(
|
| 121 |
+
input_ids=input_ids,
|
| 122 |
+
attention_mask=attn_mask,
|
| 123 |
+
position_ids=position_ids,
|
| 124 |
+
cache_position=cache_position,
|
| 125 |
+
past_key_values=past_key_values,
|
| 126 |
+
use_cache=True,
|
| 127 |
+
)
|
| 128 |
+
return outs.logits
|
| 129 |
+
|
| 130 |
+
@staticmethod
|
| 131 |
+
def generate(
|
| 132 |
+
exported_program: torch.export.ExportedProgram, prompt_token_ids: torch.Tensor, max_new_tokens: int
|
| 133 |
+
) -> torch.Tensor:
|
| 134 |
+
"""
|
| 135 |
+
Generate a sequence of tokens using an exported program.
|
| 136 |
+
|
| 137 |
+
This util function is designed to test exported models by simulating the generation process.
|
| 138 |
+
It processes the input prompt tokens sequentially (no parallel prefill).
|
| 139 |
+
This generate function is not intended to replace the original `generate` method, and the support
|
| 140 |
+
for leveraging the original `generate` is potentially planed!
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
exported_program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
|
| 144 |
+
prompt_token_ids (`torch.Tensor`): Tensor representing the input prompt token IDs.
|
| 145 |
+
max_new_tokens (`int`): Maximum number of new tokens to generate. Note that the total generation
|
| 146 |
+
length is limited by both `max_new_tokens` and the model's cache size.
|
| 147 |
+
|
| 148 |
+
Returns:
|
| 149 |
+
torch.Tensor: A tensor containing the generated sequence of token IDs, including the original prompt tokens.
|
| 150 |
+
"""
|
| 151 |
+
prompt_token_len = prompt_token_ids.shape[-1]
|
| 152 |
+
max_generation_length = prompt_token_len + max_new_tokens
|
| 153 |
+
for buffer_name, buffer in exported_program.named_buffers():
|
| 154 |
+
if buffer_name.startswith("key_cache"):
|
| 155 |
+
max_cache_len = buffer.shape[2]
|
| 156 |
+
max_generation_length = min(max_generation_length, max_cache_len)
|
| 157 |
+
break
|
| 158 |
+
|
| 159 |
+
response_tokens = []
|
| 160 |
+
for input_pos in range(min(max_generation_length, prompt_token_len)):
|
| 161 |
+
result = exported_program.module().forward(
|
| 162 |
+
input_ids=prompt_token_ids[:, input_pos : input_pos + 1],
|
| 163 |
+
cache_position=torch.tensor([input_pos], dtype=torch.long),
|
| 164 |
+
)
|
| 165 |
+
response_tokens.append(prompt_token_ids[0][input_pos].item())
|
| 166 |
+
|
| 167 |
+
current_token = torch.argmax(result[:, -1, :], dim=-1).item()
|
| 168 |
+
response_tokens.append(current_token)
|
| 169 |
+
|
| 170 |
+
while len(response_tokens) < max_generation_length:
|
| 171 |
+
result = exported_program.module().forward(
|
| 172 |
+
input_ids=torch.tensor([[current_token]], dtype=torch.long),
|
| 173 |
+
cache_position=torch.tensor([len(response_tokens)], dtype=torch.long),
|
| 174 |
+
)
|
| 175 |
+
current_token = torch.argmax(result[:, -1, :], dim=-1).item()
|
| 176 |
+
response_tokens.append(current_token)
|
| 177 |
+
|
| 178 |
+
return torch.tensor([response_tokens], dtype=torch.long)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def convert_and_export_with_cache(
|
| 182 |
+
model: PreTrainedModel,
|
| 183 |
+
example_input_ids: Optional[torch.Tensor] = None,
|
| 184 |
+
example_cache_position: Optional[torch.Tensor] = None,
|
| 185 |
+
):
|
| 186 |
+
"""
|
| 187 |
+
Convert a `PreTrainedModel` into an exportable module and export it using `torch.export`,
|
| 188 |
+
ensuring the exported model is compatible with `ExecuTorch`.
|
| 189 |
+
|
| 190 |
+
Args:
|
| 191 |
+
model (`PreTrainedModel`): The pretrained model to be exported.
|
| 192 |
+
example_input_ids (`torch.Tensor`): Example input token id used by `torch.export`.
|
| 193 |
+
example_cache_position (`torch.Tensor`): Example current cache position used by `torch.export`.
|
| 194 |
+
|
| 195 |
+
Returns:
|
| 196 |
+
Exported program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
|
| 197 |
+
"""
|
| 198 |
+
if not is_torch_greater_or_equal_than_2_3:
|
| 199 |
+
raise ImportError("torch >= 2.3 is required.")
|
| 200 |
+
|
| 201 |
+
import torch.export._trace
|
| 202 |
+
|
| 203 |
+
with torch.no_grad():
|
| 204 |
+
# TODO: The default inputs only work for text models. We need to add support for vision/audio models.
|
| 205 |
+
example_input_ids = (
|
| 206 |
+
example_input_ids if example_input_ids is not None else torch.tensor([[1]], dtype=torch.long)
|
| 207 |
+
)
|
| 208 |
+
example_cache_position = (
|
| 209 |
+
example_cache_position if example_cache_position is not None else torch.tensor([0], dtype=torch.long)
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
if is_torch_greater_or_equal("2.5.0"):
|
| 213 |
+
exported_program = torch.export.export(
|
| 214 |
+
TorchExportableModuleWithStaticCache(model),
|
| 215 |
+
args=(example_input_ids,),
|
| 216 |
+
kwargs={"cache_position": example_cache_position},
|
| 217 |
+
strict=True,
|
| 218 |
+
)
|
| 219 |
+
else:
|
| 220 |
+
# We have to keep this path for BC.
|
| 221 |
+
#
|
| 222 |
+
# Due to issue https://github.com/pytorch/pytorch/issues/128394, we need to switch to use an internal
|
| 223 |
+
# export API and pre_dispatch=False. Switch to use the public API once the issue is included in 2.5 release.
|
| 224 |
+
exported_program = torch.export._trace._export(
|
| 225 |
+
TorchExportableModuleWithStaticCache(model),
|
| 226 |
+
args=(example_input_ids,),
|
| 227 |
+
kwargs={"cache_position": example_cache_position},
|
| 228 |
+
pre_dispatch=False,
|
| 229 |
+
strict=True,
|
| 230 |
+
)
|
| 231 |
+
return exported_program
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class Seq2SeqLMEncoderExportableModule(torch.nn.Module):
|
| 235 |
+
"""
|
| 236 |
+
A wrapper module designed to make a Seq2Seq LM encoder exportable with `torch.export`.
|
| 237 |
+
This module ensures that the exported encoder model is compatible with ExecuTorch.
|
| 238 |
+
"""
|
| 239 |
+
|
| 240 |
+
def __init__(self, encoder_model):
|
| 241 |
+
super().__init__()
|
| 242 |
+
self.encoder = encoder_model
|
| 243 |
+
|
| 244 |
+
def forward(self, input_ids):
|
| 245 |
+
return self.encoder(input_ids=input_ids).last_hidden_state
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class Seq2SeqLMDecoderExportableModuleWithStaticCache(torch.nn.Module):
|
| 249 |
+
"""
|
| 250 |
+
A wrapper module designed to make a Seq2Seq LM decoder exportable with `torch.export`,
|
| 251 |
+
specifically for use with static caching. This module ensures the exported decoder
|
| 252 |
+
is compatible with ExecuTorch.
|
| 253 |
+
"""
|
| 254 |
+
|
| 255 |
+
def __init__(self, model, max_static_cache_length, batch_size):
|
| 256 |
+
super().__init__()
|
| 257 |
+
|
| 258 |
+
# Get the decoder component
|
| 259 |
+
self.decoder = model.get_decoder()
|
| 260 |
+
self.lm_head = model.lm_head
|
| 261 |
+
self.config = model.config
|
| 262 |
+
|
| 263 |
+
# Initialize static cache
|
| 264 |
+
self.static_cache = StaticCache(
|
| 265 |
+
config=self.config,
|
| 266 |
+
max_batch_size=batch_size,
|
| 267 |
+
max_cache_len=max_static_cache_length,
|
| 268 |
+
device="cpu",
|
| 269 |
+
dtype=torch.float32,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
# Register cache buffers to make them exportable
|
| 273 |
+
for i in range(len(self.static_cache.key_cache)):
|
| 274 |
+
self.register_buffer(f"key_cache_{i}", self.static_cache.key_cache[i], persistent=False)
|
| 275 |
+
self.register_buffer(f"value_cache_{i}", self.static_cache.value_cache[i], persistent=False)
|
| 276 |
+
|
| 277 |
+
def forward(self, decoder_input_ids, encoder_hidden_states, cache_position):
|
| 278 |
+
# Get outputs from decoder
|
| 279 |
+
outputs = self.decoder(
|
| 280 |
+
input_ids=decoder_input_ids,
|
| 281 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 282 |
+
past_key_values=self.static_cache,
|
| 283 |
+
use_cache=True,
|
| 284 |
+
cache_position=cache_position,
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
# Apply language model head
|
| 288 |
+
lm_logits = self.lm_head(outputs[0])
|
| 289 |
+
|
| 290 |
+
return lm_logits
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class Seq2SeqLMExportableModule(torch.nn.Module):
|
| 294 |
+
def __init__(
|
| 295 |
+
self, model, batch_size=1, max_hidden_seq_length=4096, cache_implementation="static", max_cache_length=1024
|
| 296 |
+
):
|
| 297 |
+
super().__init__()
|
| 298 |
+
|
| 299 |
+
self.full_model = model
|
| 300 |
+
self.encoder = model.get_encoder()
|
| 301 |
+
self.config = model.config
|
| 302 |
+
self.max_hidden_seq_length = max_hidden_seq_length
|
| 303 |
+
self.generation_config = GenerationConfig(
|
| 304 |
+
use_cache=True,
|
| 305 |
+
max_length=max_cache_length,
|
| 306 |
+
cache_implementation=cache_implementation,
|
| 307 |
+
cache_config={
|
| 308 |
+
"batch_size": batch_size,
|
| 309 |
+
"max_cache_len": max_cache_length,
|
| 310 |
+
},
|
| 311 |
+
)
|
| 312 |
+
self.exported_encoder = None
|
| 313 |
+
self.exported_decoder = None
|
| 314 |
+
|
| 315 |
+
def _export_encoder(self, encoder_input_ids):
|
| 316 |
+
wrapped_encoder = Seq2SeqLMEncoderExportableModule(self.encoder).to("cpu").eval()
|
| 317 |
+
|
| 318 |
+
# Define dynamic sequence length for encoder
|
| 319 |
+
seq_len_dim = torch.export.Dim("encoder_seq_length", max=self.max_hidden_seq_length)
|
| 320 |
+
|
| 321 |
+
# Export the encoder
|
| 322 |
+
with torch.no_grad():
|
| 323 |
+
exported_encoder = torch.export.export(
|
| 324 |
+
wrapped_encoder, (encoder_input_ids,), dynamic_shapes={"input_ids": {1: seq_len_dim}}, strict=True
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
return exported_encoder
|
| 328 |
+
|
| 329 |
+
def _export_decoder(self, decoder_input_ids, encoder_hidden_states, cache_position):
|
| 330 |
+
wrapped_decoder = (
|
| 331 |
+
Seq2SeqLMDecoderExportableModuleWithStaticCache(
|
| 332 |
+
model=self.full_model,
|
| 333 |
+
max_static_cache_length=self.generation_config.cache_config.max_cache_len,
|
| 334 |
+
batch_size=self.generation_config.cache_config.batch_size,
|
| 335 |
+
)
|
| 336 |
+
.to("cpu")
|
| 337 |
+
.eval()
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
# Define dynamic dimension for encoder output sequence length
|
| 341 |
+
encoder_seq_len_dim = torch.export.Dim("encoder_hidden_seq_length", max=self.max_hidden_seq_length)
|
| 342 |
+
|
| 343 |
+
# Export the decoder
|
| 344 |
+
with torch.no_grad():
|
| 345 |
+
exported_decoder = torch.export.export(
|
| 346 |
+
wrapped_decoder,
|
| 347 |
+
(decoder_input_ids, encoder_hidden_states, cache_position),
|
| 348 |
+
dynamic_shapes={
|
| 349 |
+
"decoder_input_ids": None,
|
| 350 |
+
"encoder_hidden_states": {1: encoder_seq_len_dim},
|
| 351 |
+
"cache_position": None,
|
| 352 |
+
},
|
| 353 |
+
strict=True,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
return exported_decoder
|
| 357 |
+
|
| 358 |
+
def export(self, encoder_input_ids=None, decoder_input_ids=None, encoder_hidden_states=None, cache_position=None):
|
| 359 |
+
example_encoder_input_ids = (
|
| 360 |
+
encoder_input_ids if encoder_input_ids is not None else torch.ones((1, 10), dtype=torch.long)
|
| 361 |
+
)
|
| 362 |
+
example_decoder_input_ids = (
|
| 363 |
+
decoder_input_ids if decoder_input_ids is not None else torch.tensor([[0]], dtype=torch.long)
|
| 364 |
+
) # Start token
|
| 365 |
+
example_cache_position = cache_position if cache_position is not None else torch.tensor([0], dtype=torch.long)
|
| 366 |
+
example_encoder_hidden_states = (
|
| 367 |
+
encoder_hidden_states
|
| 368 |
+
if encoder_hidden_states is not None
|
| 369 |
+
else torch.zeros(
|
| 370 |
+
(self.generation_config.cache_config.batch_size, 10, self.config.d_model), dtype=torch.float32
|
| 371 |
+
)
|
| 372 |
+
)
|
| 373 |
+
self.exported_encoder = self._export_encoder(example_encoder_input_ids)
|
| 374 |
+
self.exported_decoder = self._export_decoder(
|
| 375 |
+
example_decoder_input_ids, example_encoder_hidden_states, example_cache_position
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
# Return self to allow chaining
|
| 379 |
+
return self
|
| 380 |
+
|
| 381 |
+
def generate(self, prompt_token_ids, max_new_tokens):
|
| 382 |
+
with torch.no_grad():
|
| 383 |
+
# Run encoder
|
| 384 |
+
encoder_output = self.exported_encoder.module()(prompt_token_ids)
|
| 385 |
+
|
| 386 |
+
# Initialize with start token (0 for T5)
|
| 387 |
+
decoder_input_ids = torch.tensor([[0]], dtype=torch.long)
|
| 388 |
+
generated_ids = [0]
|
| 389 |
+
|
| 390 |
+
# Generate tokens one by one
|
| 391 |
+
for i in range(max_new_tokens - 1):
|
| 392 |
+
# Run decoder for next token prediction
|
| 393 |
+
logits = self.exported_decoder.module()(
|
| 394 |
+
decoder_input_ids, encoder_output, torch.tensor([i], dtype=torch.long)
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
# Get next token
|
| 398 |
+
next_token = torch.argmax(logits[:, -1, :], dim=-1).item()
|
| 399 |
+
generated_ids.append(next_token)
|
| 400 |
+
|
| 401 |
+
# Update input for next iteration
|
| 402 |
+
decoder_input_ids = torch.tensor([[next_token]], dtype=torch.long)
|
| 403 |
+
|
| 404 |
+
# Check if EOS token
|
| 405 |
+
if next_token == self.config.eos_token_id:
|
| 406 |
+
break
|
| 407 |
+
|
| 408 |
+
return generated_ids
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/fbgemm_fp8.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 ..activations import ACT2FN
|
| 16 |
+
from ..utils import is_accelerate_available, is_fbgemm_gpu_available, is_torch_available, logging
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if is_torch_available():
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
if is_accelerate_available():
|
| 24 |
+
from accelerate import init_empty_weights
|
| 25 |
+
|
| 26 |
+
if is_fbgemm_gpu_available():
|
| 27 |
+
import fbgemm_gpu.experimental.gen_ai # noqa: F401
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class FbgemmFp8Linear(torch.nn.Linear):
|
| 33 |
+
def __init__(self, in_features, out_features, bias, weight_dtype=torch.float32):
|
| 34 |
+
super().__init__(in_features, out_features, bias)
|
| 35 |
+
self.in_features = in_features
|
| 36 |
+
self.out_features = out_features
|
| 37 |
+
|
| 38 |
+
self.weight = torch.nn.Parameter(torch.zeros((out_features, in_features), dtype=torch.float8_e4m3fn))
|
| 39 |
+
self.weight_scale = torch.nn.Parameter(torch.zeros((out_features, 1), dtype=weight_dtype))
|
| 40 |
+
self.register_buffer("input_scale_ub", torch.zeros([1], dtype=torch.float), persistent=False)
|
| 41 |
+
|
| 42 |
+
if bias:
|
| 43 |
+
self.bias = torch.nn.Parameter(torch.zeros((self.out_features), dtype=weight_dtype))
|
| 44 |
+
else:
|
| 45 |
+
self.bias = None
|
| 46 |
+
|
| 47 |
+
def forward(self, x):
|
| 48 |
+
# quantize_fp8_per_row will squash the leading dimensions, so save the desired shape here
|
| 49 |
+
output_shape = (*x.shape[:-1], -1)
|
| 50 |
+
# x_quantized and x_scale are not necessarily on the same device as x, this is an issue.
|
| 51 |
+
# https://github.com/pytorch/FBGEMM/blob/e08af8539c391437f447173863df0f3f6f6f1855/fbgemm_gpu/experimental/gen_ai/src/quantize/quantize.cu#L1237C3-L1237C45
|
| 52 |
+
x_quantized, x_scale = torch.ops.fbgemm.quantize_fp8_per_row(
|
| 53 |
+
x.view(-1, x.shape[-1]).contiguous(), scale_ub=self.input_scale_ub
|
| 54 |
+
)
|
| 55 |
+
# moving x_quantized, x_scale here creates glibberish output ... However, if we move the output, it works
|
| 56 |
+
# x_quantized, x_scale = x_quantized.to(x.device), x_scale.to(x.device)
|
| 57 |
+
|
| 58 |
+
# The computation still happens on the device where self.weight is even if x_quantized is not on the same device as self.weight
|
| 59 |
+
weight_scale_float32 = self.weight_scale.to(torch.float32)
|
| 60 |
+
output = torch.ops.fbgemm.f8f8bf16_rowwise(
|
| 61 |
+
x_quantized, self.weight, x_scale, weight_scale_float32, use_fast_accum=True
|
| 62 |
+
)
|
| 63 |
+
output = output + self.bias if self.bias is not None else output
|
| 64 |
+
# Hacky for now, we have the output to the device of x
|
| 65 |
+
output = output.to(x.device)
|
| 66 |
+
output = output.reshape(output_shape)
|
| 67 |
+
del x_quantized, x_scale
|
| 68 |
+
return output
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class FbgemmFp8Llama4TextExperts(nn.Module):
|
| 72 |
+
def __init__(self, config, dtype=torch.float32):
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.num_experts = config.num_local_experts
|
| 75 |
+
self.intermediate_size = config.intermediate_size
|
| 76 |
+
self.hidden_size = config.hidden_size
|
| 77 |
+
self.expert_dim = self.intermediate_size
|
| 78 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 79 |
+
# Register FP8 buffers for gate_up_proj
|
| 80 |
+
self.gate_up_proj = torch.nn.Parameter(
|
| 81 |
+
torch.zeros((self.num_experts, self.hidden_size, 2 * self.expert_dim), dtype=torch.float8_e4m3fn)
|
| 82 |
+
)
|
| 83 |
+
self.gate_up_proj_scale = torch.nn.Parameter(
|
| 84 |
+
torch.zeros((self.num_experts, 1, self.expert_dim * 2), dtype=torch.float32)
|
| 85 |
+
)
|
| 86 |
+
# Register FP8 buffers for down_proj
|
| 87 |
+
self.down_proj = torch.nn.Parameter(
|
| 88 |
+
torch.zeros((self.num_experts, self.expert_dim, self.hidden_size), dtype=torch.float8_e4m3fn)
|
| 89 |
+
)
|
| 90 |
+
self.down_proj_scale = torch.nn.Parameter(
|
| 91 |
+
torch.zeros((self.num_experts, self.hidden_size, 1), dtype=torch.float32)
|
| 92 |
+
)
|
| 93 |
+
# Register input scale upper bound
|
| 94 |
+
self.register_buffer("input_scale_ub", torch.zeros([1], dtype=torch.float), persistent=False)
|
| 95 |
+
|
| 96 |
+
def forward(self, hidden_states):
|
| 97 |
+
"""
|
| 98 |
+
Args:
|
| 99 |
+
hidden_states (torch.Tensor): (batch_size * token_num, hidden_size)
|
| 100 |
+
Returns:
|
| 101 |
+
torch.Tensor: (batch_size * token_num, hidden_size)
|
| 102 |
+
"""
|
| 103 |
+
# Reshape hidden states for expert computation
|
| 104 |
+
hidden_states = hidden_states.view(self.num_experts, -1, self.hidden_size)
|
| 105 |
+
num_tokens = None
|
| 106 |
+
|
| 107 |
+
# Pre-allocate tensor for all expert outputs with same shape as hidden_states
|
| 108 |
+
next_states = torch.empty_like(hidden_states)
|
| 109 |
+
|
| 110 |
+
for i in range(self.num_experts):
|
| 111 |
+
# Extract expert's hidden states
|
| 112 |
+
expert_hidden = hidden_states[i]
|
| 113 |
+
expert_hidden_reshaped = expert_hidden.reshape(-1, self.hidden_size)
|
| 114 |
+
# Quantize for this expert
|
| 115 |
+
expert_quantized, expert_scale = torch.ops.fbgemm.quantize_fp8_per_row(
|
| 116 |
+
expert_hidden_reshaped, num_tokens, self.input_scale_ub
|
| 117 |
+
)
|
| 118 |
+
sharded_expert_dim = self.gate_up_proj.shape[-1] // 2
|
| 119 |
+
gate_up_proj_scale_float32 = self.gate_up_proj_scale.to(torch.float32)
|
| 120 |
+
|
| 121 |
+
gate = torch.ops.fbgemm.f8f8bf16_rowwise(
|
| 122 |
+
expert_quantized,
|
| 123 |
+
self.gate_up_proj[i].transpose(0, 1)[:sharded_expert_dim].contiguous(),
|
| 124 |
+
expert_scale,
|
| 125 |
+
gate_up_proj_scale_float32[i][0][:sharded_expert_dim].view(-1, 1).contiguous(),
|
| 126 |
+
use_fast_accum=True,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
up = torch.ops.fbgemm.f8f8bf16_rowwise(
|
| 130 |
+
expert_quantized,
|
| 131 |
+
self.gate_up_proj[i].transpose(0, 1)[sharded_expert_dim:].contiguous(),
|
| 132 |
+
expert_scale,
|
| 133 |
+
gate_up_proj_scale_float32[i][0][sharded_expert_dim:].view(-1, 1).contiguous(),
|
| 134 |
+
use_fast_accum=True,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
activated = up * self.act_fn(gate)
|
| 138 |
+
|
| 139 |
+
activated_quantized, activated_scale = torch.ops.fbgemm.quantize_fp8_per_row(
|
| 140 |
+
activated, num_tokens, self.input_scale_ub
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
down_proj_scale_float32 = self.down_proj_scale.to(torch.float32)
|
| 144 |
+
expert_output = torch.ops.fbgemm.f8f8bf16_rowwise(
|
| 145 |
+
activated_quantized,
|
| 146 |
+
self.down_proj[i].transpose(0, 1).contiguous(),
|
| 147 |
+
activated_scale,
|
| 148 |
+
down_proj_scale_float32[i].view(-1, 1).contiguous(),
|
| 149 |
+
use_fast_accum=True,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
next_states[i] = expert_output
|
| 153 |
+
next_states = next_states.to(hidden_states.device)
|
| 154 |
+
return next_states.view(-1, self.hidden_size)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _replace_with_fbgemm_fp8_linear(
|
| 158 |
+
model,
|
| 159 |
+
modules_to_not_convert=None,
|
| 160 |
+
current_key_name=None,
|
| 161 |
+
quantization_config=None,
|
| 162 |
+
has_been_replaced=False,
|
| 163 |
+
pre_quantized=False,
|
| 164 |
+
config=None,
|
| 165 |
+
tp_plan=None,
|
| 166 |
+
):
|
| 167 |
+
"""
|
| 168 |
+
Private method that wraps the recursion for module replacement.
|
| 169 |
+
|
| 170 |
+
Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
import re
|
| 174 |
+
|
| 175 |
+
if current_key_name is None:
|
| 176 |
+
current_key_name = []
|
| 177 |
+
|
| 178 |
+
for name, module in model.named_children():
|
| 179 |
+
current_key_name.append(name)
|
| 180 |
+
|
| 181 |
+
if (isinstance(module, nn.Linear)) and name not in modules_to_not_convert:
|
| 182 |
+
# Check if the current key is not in the `modules_to_not_convert`
|
| 183 |
+
current_key_name_str = ".".join(current_key_name)
|
| 184 |
+
if not any(
|
| 185 |
+
(key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
|
| 186 |
+
):
|
| 187 |
+
with init_empty_weights(include_buffers=True):
|
| 188 |
+
in_features = module.in_features
|
| 189 |
+
out_features = module.out_features
|
| 190 |
+
model._modules[name] = FbgemmFp8Linear(
|
| 191 |
+
in_features,
|
| 192 |
+
out_features,
|
| 193 |
+
module.bias is not None,
|
| 194 |
+
)
|
| 195 |
+
has_been_replaced = True
|
| 196 |
+
|
| 197 |
+
# Force requires grad to False to avoid unexpected errors
|
| 198 |
+
model._modules[name].requires_grad_(False)
|
| 199 |
+
# set non persistant buffer outside of init_empty_weights
|
| 200 |
+
model._modules[name].input_scale_ub = torch.tensor(
|
| 201 |
+
[quantization_config.activation_scale_ub],
|
| 202 |
+
dtype=torch.float,
|
| 203 |
+
)
|
| 204 |
+
if module.__class__.__name__ == "Llama4TextExperts" and name not in modules_to_not_convert:
|
| 205 |
+
current_key_name_str = ".".join(current_key_name)
|
| 206 |
+
if not any(
|
| 207 |
+
(key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
|
| 208 |
+
):
|
| 209 |
+
with init_empty_weights(include_buffers=True):
|
| 210 |
+
tp_plan[re.sub(r"\d+", "*", current_key_name_str + ".down_proj_scale")] = None
|
| 211 |
+
model._modules[name] = FbgemmFp8Llama4TextExperts(
|
| 212 |
+
config.text_config,
|
| 213 |
+
)
|
| 214 |
+
model._modules[name].input_scale_ub = torch.tensor(
|
| 215 |
+
[quantization_config.activation_scale_ub], dtype=torch.float
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
if len(list(module.children())) > 0:
|
| 219 |
+
_, has_been_replaced = _replace_with_fbgemm_fp8_linear(
|
| 220 |
+
module,
|
| 221 |
+
modules_to_not_convert,
|
| 222 |
+
current_key_name,
|
| 223 |
+
quantization_config,
|
| 224 |
+
has_been_replaced=has_been_replaced,
|
| 225 |
+
pre_quantized=pre_quantized,
|
| 226 |
+
config=config,
|
| 227 |
+
tp_plan=tp_plan,
|
| 228 |
+
)
|
| 229 |
+
# Remove the last key for recursion
|
| 230 |
+
current_key_name.pop(-1)
|
| 231 |
+
return model, has_been_replaced
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def replace_with_fbgemm_fp8_linear(
|
| 235 |
+
model,
|
| 236 |
+
modules_to_not_convert=None,
|
| 237 |
+
current_key_name=None,
|
| 238 |
+
quantization_config=None,
|
| 239 |
+
pre_quantized=False,
|
| 240 |
+
config=None,
|
| 241 |
+
tp_plan=None,
|
| 242 |
+
):
|
| 243 |
+
"""
|
| 244 |
+
A helper function to replace all `torch.nn.Linear` modules by `FbgemmFp8Linear` modules.
|
| 245 |
+
This will enable running your models using high performance fp8 kernel from FBGEMM library.
|
| 246 |
+
|
| 247 |
+
The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
|
| 248 |
+
be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
|
| 249 |
+
CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
|
| 250 |
+
|
| 251 |
+
Parameters:
|
| 252 |
+
model (`torch.nn.Module`):
|
| 253 |
+
Input model or `torch.nn.Module` as the function is run recursively.
|
| 254 |
+
modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
|
| 255 |
+
Names of the modules to not convert in `FP8Linear`. In practice we keep the `lm_head` in full precision
|
| 256 |
+
for numerical stability reasons.
|
| 257 |
+
current_key_name (`List[`str`]`, *optional*):
|
| 258 |
+
An array to track the current key of the recursion. This is used to check whether the current key (part of
|
| 259 |
+
it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
|
| 260 |
+
`disk`).
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
|
| 264 |
+
|
| 265 |
+
if quantization_config.modules_to_not_convert is not None:
|
| 266 |
+
modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
|
| 267 |
+
modules_to_not_convert = list(set(modules_to_not_convert))
|
| 268 |
+
model, has_been_replaced = _replace_with_fbgemm_fp8_linear(
|
| 269 |
+
model,
|
| 270 |
+
modules_to_not_convert,
|
| 271 |
+
current_key_name,
|
| 272 |
+
quantization_config,
|
| 273 |
+
pre_quantized=pre_quantized,
|
| 274 |
+
config=config,
|
| 275 |
+
tp_plan=tp_plan,
|
| 276 |
+
)
|
| 277 |
+
if not has_been_replaced:
|
| 278 |
+
logger.warning(
|
| 279 |
+
"You are loading your model using FP8 quantization but no linear modules were found in your model."
|
| 280 |
+
" Please double check your model architecture, or submit an issue on github if you think this is"
|
| 281 |
+
" a bug."
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
return model
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/feature_extraction_auto.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 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 |
+
"""AutoFeatureExtractor class."""
|
| 16 |
+
|
| 17 |
+
import importlib
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import warnings
|
| 21 |
+
from collections import OrderedDict
|
| 22 |
+
from typing import Dict, Optional, Union
|
| 23 |
+
|
| 24 |
+
# Build the list of all feature extractors
|
| 25 |
+
from ...configuration_utils import PretrainedConfig
|
| 26 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
|
| 27 |
+
from ...feature_extraction_utils import FeatureExtractionMixin
|
| 28 |
+
from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, cached_file, logging
|
| 29 |
+
from .auto_factory import _LazyAutoMapping
|
| 30 |
+
from .configuration_auto import (
|
| 31 |
+
CONFIG_MAPPING_NAMES,
|
| 32 |
+
AutoConfig,
|
| 33 |
+
model_type_to_module_name,
|
| 34 |
+
replace_list_option_in_docstrings,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
logger = logging.get_logger(__name__)
|
| 39 |
+
|
| 40 |
+
FEATURE_EXTRACTOR_MAPPING_NAMES = OrderedDict(
|
| 41 |
+
[
|
| 42 |
+
("audio-spectrogram-transformer", "ASTFeatureExtractor"),
|
| 43 |
+
("beit", "BeitFeatureExtractor"),
|
| 44 |
+
("chinese_clip", "ChineseCLIPFeatureExtractor"),
|
| 45 |
+
("clap", "ClapFeatureExtractor"),
|
| 46 |
+
("clip", "CLIPFeatureExtractor"),
|
| 47 |
+
("clipseg", "ViTFeatureExtractor"),
|
| 48 |
+
("clvp", "ClvpFeatureExtractor"),
|
| 49 |
+
("conditional_detr", "ConditionalDetrFeatureExtractor"),
|
| 50 |
+
("convnext", "ConvNextFeatureExtractor"),
|
| 51 |
+
("cvt", "ConvNextFeatureExtractor"),
|
| 52 |
+
("dac", "DacFeatureExtractor"),
|
| 53 |
+
("data2vec-audio", "Wav2Vec2FeatureExtractor"),
|
| 54 |
+
("data2vec-vision", "BeitFeatureExtractor"),
|
| 55 |
+
("deformable_detr", "DeformableDetrFeatureExtractor"),
|
| 56 |
+
("deit", "DeiTFeatureExtractor"),
|
| 57 |
+
("detr", "DetrFeatureExtractor"),
|
| 58 |
+
("dinat", "ViTFeatureExtractor"),
|
| 59 |
+
("donut-swin", "DonutFeatureExtractor"),
|
| 60 |
+
("dpt", "DPTFeatureExtractor"),
|
| 61 |
+
("encodec", "EncodecFeatureExtractor"),
|
| 62 |
+
("flava", "FlavaFeatureExtractor"),
|
| 63 |
+
("glpn", "GLPNFeatureExtractor"),
|
| 64 |
+
("groupvit", "CLIPFeatureExtractor"),
|
| 65 |
+
("hubert", "Wav2Vec2FeatureExtractor"),
|
| 66 |
+
("imagegpt", "ImageGPTFeatureExtractor"),
|
| 67 |
+
("layoutlmv2", "LayoutLMv2FeatureExtractor"),
|
| 68 |
+
("layoutlmv3", "LayoutLMv3FeatureExtractor"),
|
| 69 |
+
("levit", "LevitFeatureExtractor"),
|
| 70 |
+
("maskformer", "MaskFormerFeatureExtractor"),
|
| 71 |
+
("mctct", "MCTCTFeatureExtractor"),
|
| 72 |
+
("mimi", "EncodecFeatureExtractor"),
|
| 73 |
+
("mobilenet_v1", "MobileNetV1FeatureExtractor"),
|
| 74 |
+
("mobilenet_v2", "MobileNetV2FeatureExtractor"),
|
| 75 |
+
("mobilevit", "MobileViTFeatureExtractor"),
|
| 76 |
+
("moonshine", "Wav2Vec2FeatureExtractor"),
|
| 77 |
+
("moshi", "EncodecFeatureExtractor"),
|
| 78 |
+
("nat", "ViTFeatureExtractor"),
|
| 79 |
+
("owlvit", "OwlViTFeatureExtractor"),
|
| 80 |
+
("perceiver", "PerceiverFeatureExtractor"),
|
| 81 |
+
("phi4_multimodal", "Phi4MultimodalFeatureExtractor"),
|
| 82 |
+
("poolformer", "PoolFormerFeatureExtractor"),
|
| 83 |
+
("pop2piano", "Pop2PianoFeatureExtractor"),
|
| 84 |
+
("regnet", "ConvNextFeatureExtractor"),
|
| 85 |
+
("resnet", "ConvNextFeatureExtractor"),
|
| 86 |
+
("seamless_m4t", "SeamlessM4TFeatureExtractor"),
|
| 87 |
+
("seamless_m4t_v2", "SeamlessM4TFeatureExtractor"),
|
| 88 |
+
("segformer", "SegformerFeatureExtractor"),
|
| 89 |
+
("sew", "Wav2Vec2FeatureExtractor"),
|
| 90 |
+
("sew-d", "Wav2Vec2FeatureExtractor"),
|
| 91 |
+
("speech_to_text", "Speech2TextFeatureExtractor"),
|
| 92 |
+
("speecht5", "SpeechT5FeatureExtractor"),
|
| 93 |
+
("swiftformer", "ViTFeatureExtractor"),
|
| 94 |
+
("swin", "ViTFeatureExtractor"),
|
| 95 |
+
("swinv2", "ViTFeatureExtractor"),
|
| 96 |
+
("table-transformer", "DetrFeatureExtractor"),
|
| 97 |
+
("timesformer", "VideoMAEFeatureExtractor"),
|
| 98 |
+
("tvlt", "TvltFeatureExtractor"),
|
| 99 |
+
("unispeech", "Wav2Vec2FeatureExtractor"),
|
| 100 |
+
("unispeech-sat", "Wav2Vec2FeatureExtractor"),
|
| 101 |
+
("univnet", "UnivNetFeatureExtractor"),
|
| 102 |
+
("van", "ConvNextFeatureExtractor"),
|
| 103 |
+
("videomae", "VideoMAEFeatureExtractor"),
|
| 104 |
+
("vilt", "ViltFeatureExtractor"),
|
| 105 |
+
("vit", "ViTFeatureExtractor"),
|
| 106 |
+
("vit_mae", "ViTFeatureExtractor"),
|
| 107 |
+
("vit_msn", "ViTFeatureExtractor"),
|
| 108 |
+
("wav2vec2", "Wav2Vec2FeatureExtractor"),
|
| 109 |
+
("wav2vec2-bert", "Wav2Vec2FeatureExtractor"),
|
| 110 |
+
("wav2vec2-conformer", "Wav2Vec2FeatureExtractor"),
|
| 111 |
+
("wavlm", "Wav2Vec2FeatureExtractor"),
|
| 112 |
+
("whisper", "WhisperFeatureExtractor"),
|
| 113 |
+
("xclip", "CLIPFeatureExtractor"),
|
| 114 |
+
("yolos", "YolosFeatureExtractor"),
|
| 115 |
+
]
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
FEATURE_EXTRACTOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def feature_extractor_class_from_name(class_name: str):
|
| 122 |
+
for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
|
| 123 |
+
if class_name in extractors:
|
| 124 |
+
module_name = model_type_to_module_name(module_name)
|
| 125 |
+
|
| 126 |
+
module = importlib.import_module(f".{module_name}", "transformers.models")
|
| 127 |
+
try:
|
| 128 |
+
return getattr(module, class_name)
|
| 129 |
+
except AttributeError:
|
| 130 |
+
continue
|
| 131 |
+
|
| 132 |
+
for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
|
| 133 |
+
if getattr(extractor, "__name__", None) == class_name:
|
| 134 |
+
return extractor
|
| 135 |
+
|
| 136 |
+
# We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
|
| 137 |
+
# init and we return the proper dummy to get an appropriate error message.
|
| 138 |
+
main_module = importlib.import_module("transformers")
|
| 139 |
+
if hasattr(main_module, class_name):
|
| 140 |
+
return getattr(main_module, class_name)
|
| 141 |
+
|
| 142 |
+
return None
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def get_feature_extractor_config(
|
| 146 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 147 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 148 |
+
force_download: bool = False,
|
| 149 |
+
resume_download: Optional[bool] = None,
|
| 150 |
+
proxies: Optional[Dict[str, str]] = None,
|
| 151 |
+
token: Optional[Union[bool, str]] = None,
|
| 152 |
+
revision: Optional[str] = None,
|
| 153 |
+
local_files_only: bool = False,
|
| 154 |
+
**kwargs,
|
| 155 |
+
):
|
| 156 |
+
"""
|
| 157 |
+
Loads the tokenizer configuration from a pretrained model tokenizer configuration.
|
| 158 |
+
|
| 159 |
+
Args:
|
| 160 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 161 |
+
This can be either:
|
| 162 |
+
|
| 163 |
+
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
| 164 |
+
huggingface.co.
|
| 165 |
+
- a path to a *directory* containing a configuration file saved using the
|
| 166 |
+
[`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
|
| 167 |
+
|
| 168 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 169 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
|
| 170 |
+
cache should not be used.
|
| 171 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 172 |
+
Whether or not to force to (re-)download the configuration files and override the cached versions if they
|
| 173 |
+
exist.
|
| 174 |
+
resume_download:
|
| 175 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 176 |
+
Will be removed in v5 of Transformers.
|
| 177 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 178 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 179 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 180 |
+
token (`str` or *bool*, *optional*):
|
| 181 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 182 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 183 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 184 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 185 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 186 |
+
identifier allowed by git.
|
| 187 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 188 |
+
If `True`, will only try to load the tokenizer configuration from local files.
|
| 189 |
+
|
| 190 |
+
<Tip>
|
| 191 |
+
|
| 192 |
+
Passing `token=True` is required when you want to use a private model.
|
| 193 |
+
|
| 194 |
+
</Tip>
|
| 195 |
+
|
| 196 |
+
Returns:
|
| 197 |
+
`Dict`: The configuration of the tokenizer.
|
| 198 |
+
|
| 199 |
+
Examples:
|
| 200 |
+
|
| 201 |
+
```python
|
| 202 |
+
# Download configuration from huggingface.co and cache.
|
| 203 |
+
tokenizer_config = get_tokenizer_config("google-bert/bert-base-uncased")
|
| 204 |
+
# This model does not have a tokenizer config so the result will be an empty dict.
|
| 205 |
+
tokenizer_config = get_tokenizer_config("FacebookAI/xlm-roberta-base")
|
| 206 |
+
|
| 207 |
+
# Save a pretrained tokenizer locally and you can reload its config
|
| 208 |
+
from transformers import AutoTokenizer
|
| 209 |
+
|
| 210 |
+
tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
|
| 211 |
+
tokenizer.save_pretrained("tokenizer-test")
|
| 212 |
+
tokenizer_config = get_tokenizer_config("tokenizer-test")
|
| 213 |
+
```"""
|
| 214 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 215 |
+
if use_auth_token is not None:
|
| 216 |
+
warnings.warn(
|
| 217 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 218 |
+
FutureWarning,
|
| 219 |
+
)
|
| 220 |
+
if token is not None:
|
| 221 |
+
raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
|
| 222 |
+
token = use_auth_token
|
| 223 |
+
|
| 224 |
+
resolved_config_file = cached_file(
|
| 225 |
+
pretrained_model_name_or_path,
|
| 226 |
+
FEATURE_EXTRACTOR_NAME,
|
| 227 |
+
cache_dir=cache_dir,
|
| 228 |
+
force_download=force_download,
|
| 229 |
+
resume_download=resume_download,
|
| 230 |
+
proxies=proxies,
|
| 231 |
+
token=token,
|
| 232 |
+
revision=revision,
|
| 233 |
+
local_files_only=local_files_only,
|
| 234 |
+
_raise_exceptions_for_gated_repo=False,
|
| 235 |
+
_raise_exceptions_for_missing_entries=False,
|
| 236 |
+
_raise_exceptions_for_connection_errors=False,
|
| 237 |
+
)
|
| 238 |
+
if resolved_config_file is None:
|
| 239 |
+
logger.info(
|
| 240 |
+
"Could not locate the feature extractor configuration file, will try to use the model config instead."
|
| 241 |
+
)
|
| 242 |
+
return {}
|
| 243 |
+
|
| 244 |
+
with open(resolved_config_file, encoding="utf-8") as reader:
|
| 245 |
+
return json.load(reader)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class AutoFeatureExtractor:
|
| 249 |
+
r"""
|
| 250 |
+
This is a generic feature extractor class that will be instantiated as one of the feature extractor classes of the
|
| 251 |
+
library when created with the [`AutoFeatureExtractor.from_pretrained`] class method.
|
| 252 |
+
|
| 253 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
def __init__(self):
|
| 257 |
+
raise EnvironmentError(
|
| 258 |
+
"AutoFeatureExtractor is designed to be instantiated "
|
| 259 |
+
"using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method."
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
@classmethod
|
| 263 |
+
@replace_list_option_in_docstrings(FEATURE_EXTRACTOR_MAPPING_NAMES)
|
| 264 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 265 |
+
r"""
|
| 266 |
+
Instantiate one of the feature extractor classes of the library from a pretrained model vocabulary.
|
| 267 |
+
|
| 268 |
+
The feature extractor class to instantiate is selected based on the `model_type` property of the config object
|
| 269 |
+
(either passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's
|
| 270 |
+
missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 271 |
+
|
| 272 |
+
List options
|
| 273 |
+
|
| 274 |
+
Params:
|
| 275 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 276 |
+
This can be either:
|
| 277 |
+
|
| 278 |
+
- a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
|
| 279 |
+
huggingface.co.
|
| 280 |
+
- a path to a *directory* containing a feature extractor file saved using the
|
| 281 |
+
[`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] method, e.g.,
|
| 282 |
+
`./my_model_directory/`.
|
| 283 |
+
- a path or url to a saved feature extractor JSON *file*, e.g.,
|
| 284 |
+
`./my_model_directory/preprocessor_config.json`.
|
| 285 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 286 |
+
Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
|
| 287 |
+
standard cache should not be used.
|
| 288 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 289 |
+
Whether or not to force to (re-)download the feature extractor files and override the cached versions
|
| 290 |
+
if they exist.
|
| 291 |
+
resume_download:
|
| 292 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 293 |
+
Will be removed in v5 of Transformers.
|
| 294 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 295 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 296 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 297 |
+
token (`str` or *bool*, *optional*):
|
| 298 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 299 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 300 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 301 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 302 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 303 |
+
identifier allowed by git.
|
| 304 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 305 |
+
If `False`, then this function returns just the final feature extractor object. If `True`, then this
|
| 306 |
+
functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
|
| 307 |
+
consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
|
| 308 |
+
`kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
|
| 309 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 310 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 311 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 312 |
+
execute code present on the Hub on your local machine.
|
| 313 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 314 |
+
The values in kwargs of any keys which are feature extractor attributes will be used to override the
|
| 315 |
+
loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
|
| 316 |
+
controlled by the `return_unused_kwargs` keyword parameter.
|
| 317 |
+
|
| 318 |
+
<Tip>
|
| 319 |
+
|
| 320 |
+
Passing `token=True` is required when you want to use a private model.
|
| 321 |
+
|
| 322 |
+
</Tip>
|
| 323 |
+
|
| 324 |
+
Examples:
|
| 325 |
+
|
| 326 |
+
```python
|
| 327 |
+
>>> from transformers import AutoFeatureExtractor
|
| 328 |
+
|
| 329 |
+
>>> # Download feature extractor from huggingface.co and cache.
|
| 330 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h")
|
| 331 |
+
|
| 332 |
+
>>> # If feature extractor files are in a directory (e.g. feature extractor was saved using *save_pretrained('./test/saved_model/')*)
|
| 333 |
+
>>> # feature_extractor = AutoFeatureExtractor.from_pretrained("./test/saved_model/")
|
| 334 |
+
```"""
|
| 335 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 336 |
+
if use_auth_token is not None:
|
| 337 |
+
warnings.warn(
|
| 338 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 339 |
+
FutureWarning,
|
| 340 |
+
)
|
| 341 |
+
if kwargs.get("token", None) is not None:
|
| 342 |
+
raise ValueError(
|
| 343 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 344 |
+
)
|
| 345 |
+
kwargs["token"] = use_auth_token
|
| 346 |
+
|
| 347 |
+
config = kwargs.pop("config", None)
|
| 348 |
+
trust_remote_code = kwargs.pop("trust_remote_code", None)
|
| 349 |
+
kwargs["_from_auto"] = True
|
| 350 |
+
|
| 351 |
+
config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs)
|
| 352 |
+
feature_extractor_class = config_dict.get("feature_extractor_type", None)
|
| 353 |
+
feature_extractor_auto_map = None
|
| 354 |
+
if "AutoFeatureExtractor" in config_dict.get("auto_map", {}):
|
| 355 |
+
feature_extractor_auto_map = config_dict["auto_map"]["AutoFeatureExtractor"]
|
| 356 |
+
|
| 357 |
+
# If we don't find the feature extractor class in the feature extractor config, let's try the model config.
|
| 358 |
+
if feature_extractor_class is None and feature_extractor_auto_map is None:
|
| 359 |
+
if not isinstance(config, PretrainedConfig):
|
| 360 |
+
config = AutoConfig.from_pretrained(
|
| 361 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 362 |
+
)
|
| 363 |
+
# It could be in `config.feature_extractor_type``
|
| 364 |
+
feature_extractor_class = getattr(config, "feature_extractor_type", None)
|
| 365 |
+
if hasattr(config, "auto_map") and "AutoFeatureExtractor" in config.auto_map:
|
| 366 |
+
feature_extractor_auto_map = config.auto_map["AutoFeatureExtractor"]
|
| 367 |
+
|
| 368 |
+
if feature_extractor_class is not None:
|
| 369 |
+
feature_extractor_class = feature_extractor_class_from_name(feature_extractor_class)
|
| 370 |
+
|
| 371 |
+
has_remote_code = feature_extractor_auto_map is not None
|
| 372 |
+
has_local_code = feature_extractor_class is not None or type(config) in FEATURE_EXTRACTOR_MAPPING
|
| 373 |
+
trust_remote_code = resolve_trust_remote_code(
|
| 374 |
+
trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
if has_remote_code and trust_remote_code:
|
| 378 |
+
feature_extractor_class = get_class_from_dynamic_module(
|
| 379 |
+
feature_extractor_auto_map, pretrained_model_name_or_path, **kwargs
|
| 380 |
+
)
|
| 381 |
+
_ = kwargs.pop("code_revision", None)
|
| 382 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
| 383 |
+
feature_extractor_class.register_for_auto_class()
|
| 384 |
+
return feature_extractor_class.from_dict(config_dict, **kwargs)
|
| 385 |
+
elif feature_extractor_class is not None:
|
| 386 |
+
return feature_extractor_class.from_dict(config_dict, **kwargs)
|
| 387 |
+
# Last try: we use the FEATURE_EXTRACTOR_MAPPING.
|
| 388 |
+
elif type(config) in FEATURE_EXTRACTOR_MAPPING:
|
| 389 |
+
feature_extractor_class = FEATURE_EXTRACTOR_MAPPING[type(config)]
|
| 390 |
+
return feature_extractor_class.from_dict(config_dict, **kwargs)
|
| 391 |
+
|
| 392 |
+
raise ValueError(
|
| 393 |
+
f"Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a "
|
| 394 |
+
f"`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following "
|
| 395 |
+
f"`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys())}"
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
@staticmethod
|
| 399 |
+
def register(config_class, feature_extractor_class, exist_ok=False):
|
| 400 |
+
"""
|
| 401 |
+
Register a new feature extractor for this class.
|
| 402 |
+
|
| 403 |
+
Args:
|
| 404 |
+
config_class ([`PretrainedConfig`]):
|
| 405 |
+
The configuration corresponding to the model to register.
|
| 406 |
+
feature_extractor_class ([`FeatureExtractorMixin`]): The feature extractor to register.
|
| 407 |
+
"""
|
| 408 |
+
FEATURE_EXTRACTOR_MAPPING.register(config_class, feature_extractor_class, exist_ok=exist_ok)
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 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 |
+
Sequence feature extraction class for common feature extractors to preprocess sequences.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
|
| 23 |
+
from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class SequenceFeatureExtractor(FeatureExtractionMixin):
|
| 30 |
+
"""
|
| 31 |
+
This is a general feature extraction class for speech recognition.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
feature_size (`int`):
|
| 35 |
+
The feature dimension of the extracted features.
|
| 36 |
+
sampling_rate (`int`):
|
| 37 |
+
The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
|
| 38 |
+
padding_value (`float`):
|
| 39 |
+
The value that is used to fill the padding values / vectors.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(self, feature_size: int, sampling_rate: int, padding_value: float, **kwargs):
|
| 43 |
+
self.feature_size = feature_size
|
| 44 |
+
self.sampling_rate = sampling_rate
|
| 45 |
+
self.padding_value = padding_value
|
| 46 |
+
|
| 47 |
+
self.padding_side = kwargs.pop("padding_side", "right")
|
| 48 |
+
self.return_attention_mask = kwargs.pop("return_attention_mask", True)
|
| 49 |
+
|
| 50 |
+
super().__init__(**kwargs)
|
| 51 |
+
|
| 52 |
+
def pad(
|
| 53 |
+
self,
|
| 54 |
+
processed_features: Union[
|
| 55 |
+
BatchFeature,
|
| 56 |
+
list[BatchFeature],
|
| 57 |
+
dict[str, BatchFeature],
|
| 58 |
+
dict[str, list[BatchFeature]],
|
| 59 |
+
list[dict[str, BatchFeature]],
|
| 60 |
+
],
|
| 61 |
+
padding: Union[bool, str, PaddingStrategy] = True,
|
| 62 |
+
max_length: Optional[int] = None,
|
| 63 |
+
truncation: bool = False,
|
| 64 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 65 |
+
return_attention_mask: Optional[bool] = None,
|
| 66 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 67 |
+
) -> BatchFeature:
|
| 68 |
+
"""
|
| 69 |
+
Pad input values / input vectors or a batch of input values / input vectors up to predefined length or to the
|
| 70 |
+
max sequence length in the batch.
|
| 71 |
+
|
| 72 |
+
Padding side (left/right) padding values are defined at the feature extractor level (with `self.padding_side`,
|
| 73 |
+
`self.padding_value`)
|
| 74 |
+
|
| 75 |
+
<Tip>
|
| 76 |
+
|
| 77 |
+
If the `processed_features` passed are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the
|
| 78 |
+
result will use the same type unless you provide a different tensor type with `return_tensors`. In the case of
|
| 79 |
+
PyTorch tensors, you will lose the specific device of your tensors however.
|
| 80 |
+
|
| 81 |
+
</Tip>
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
processed_features ([`BatchFeature`], list of [`BatchFeature`], `Dict[str, List[float]]`, `Dict[str, List[List[float]]` or `List[Dict[str, List[float]]]`):
|
| 85 |
+
Processed inputs. Can represent one input ([`BatchFeature`] or `Dict[str, List[float]]`) or a batch of
|
| 86 |
+
input values / vectors (list of [`BatchFeature`], *Dict[str, List[List[float]]]* or *List[Dict[str,
|
| 87 |
+
List[float]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader
|
| 88 |
+
collate function.
|
| 89 |
+
|
| 90 |
+
Instead of `List[float]` you can have tensors (numpy arrays, PyTorch tensors or TensorFlow tensors),
|
| 91 |
+
see the note above for the return type.
|
| 92 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
|
| 93 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
| 94 |
+
index) among:
|
| 95 |
+
|
| 96 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 97 |
+
sequence if provided).
|
| 98 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 99 |
+
acceptable input length for the model if that argument is not provided.
|
| 100 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 101 |
+
lengths).
|
| 102 |
+
max_length (`int`, *optional*):
|
| 103 |
+
Maximum length of the returned list and optionally padding length (see above).
|
| 104 |
+
truncation (`bool`):
|
| 105 |
+
Activates truncation to cut input sequences longer than `max_length` to `max_length`.
|
| 106 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 107 |
+
If set will pad the sequence to a multiple of the provided value.
|
| 108 |
+
|
| 109 |
+
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
|
| 110 |
+
`>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
|
| 111 |
+
return_attention_mask (`bool`, *optional*):
|
| 112 |
+
Whether to return the attention mask. If left to the default, will return the attention mask according
|
| 113 |
+
to the specific feature_extractor's default.
|
| 114 |
+
|
| 115 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 116 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 117 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 118 |
+
|
| 119 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 120 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 121 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 122 |
+
"""
|
| 123 |
+
# If we have a list of dicts, let's convert it in a dict of lists
|
| 124 |
+
# We do this to allow using this method as a collate_fn function in PyTorch Dataloader
|
| 125 |
+
if isinstance(processed_features, (list, tuple)) and isinstance(processed_features[0], (dict, BatchFeature)):
|
| 126 |
+
processed_features = {
|
| 127 |
+
key: [example[key] for example in processed_features] for key in processed_features[0].keys()
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
# The model's main input name, usually `input_values`, has be passed for padding
|
| 131 |
+
if self.model_input_names[0] not in processed_features:
|
| 132 |
+
raise ValueError(
|
| 133 |
+
"You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`"
|
| 134 |
+
f" to this method that includes {self.model_input_names[0]}, but you provided"
|
| 135 |
+
f" {list(processed_features.keys())}"
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
required_input = processed_features[self.model_input_names[0]]
|
| 139 |
+
return_attention_mask = (
|
| 140 |
+
return_attention_mask if return_attention_mask is not None else self.return_attention_mask
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
if len(required_input) == 0:
|
| 144 |
+
if return_attention_mask:
|
| 145 |
+
processed_features["attention_mask"] = []
|
| 146 |
+
return processed_features
|
| 147 |
+
|
| 148 |
+
# If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays
|
| 149 |
+
# and rebuild them afterwards if no return_tensors is specified
|
| 150 |
+
# Note that we lose the specific device the tensor may be on for PyTorch
|
| 151 |
+
|
| 152 |
+
first_element = required_input[0]
|
| 153 |
+
if isinstance(first_element, (list, tuple)):
|
| 154 |
+
# first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
|
| 155 |
+
index = 0
|
| 156 |
+
while len(required_input[index]) == 0:
|
| 157 |
+
index += 1
|
| 158 |
+
if index < len(required_input):
|
| 159 |
+
first_element = required_input[index][0]
|
| 160 |
+
|
| 161 |
+
if return_tensors is None:
|
| 162 |
+
if is_tf_tensor(first_element):
|
| 163 |
+
return_tensors = "tf"
|
| 164 |
+
elif is_torch_tensor(first_element):
|
| 165 |
+
return_tensors = "pt"
|
| 166 |
+
elif isinstance(first_element, (int, float, list, tuple, np.ndarray)):
|
| 167 |
+
return_tensors = "np"
|
| 168 |
+
else:
|
| 169 |
+
raise ValueError(
|
| 170 |
+
f"type of {first_element} unknown: {type(first_element)}. "
|
| 171 |
+
"Should be one of a python, numpy, pytorch or tensorflow object."
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
for key, value in processed_features.items():
|
| 175 |
+
if isinstance(value[0], (int, float)):
|
| 176 |
+
processed_features[key] = to_numpy(value)
|
| 177 |
+
else:
|
| 178 |
+
processed_features[key] = [to_numpy(v) for v in value]
|
| 179 |
+
|
| 180 |
+
# Convert padding_strategy in PaddingStrategy
|
| 181 |
+
padding_strategy = self._get_padding_strategies(padding=padding, max_length=max_length)
|
| 182 |
+
|
| 183 |
+
required_input = processed_features[self.model_input_names[0]]
|
| 184 |
+
|
| 185 |
+
batch_size = len(required_input)
|
| 186 |
+
if not all(len(v) == batch_size for v in processed_features.values()):
|
| 187 |
+
raise ValueError("Some items in the output dictionary have a different batch size than others.")
|
| 188 |
+
|
| 189 |
+
truncated_inputs = []
|
| 190 |
+
for i in range(batch_size):
|
| 191 |
+
inputs = {k: v[i] for k, v in processed_features.items()}
|
| 192 |
+
# truncation
|
| 193 |
+
inputs_slice = self._truncate(
|
| 194 |
+
inputs,
|
| 195 |
+
max_length=max_length,
|
| 196 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 197 |
+
truncation=truncation,
|
| 198 |
+
)
|
| 199 |
+
truncated_inputs.append(inputs_slice)
|
| 200 |
+
|
| 201 |
+
if padding_strategy == PaddingStrategy.LONGEST:
|
| 202 |
+
# make sure that `max_length` cannot be longer than the longest truncated length
|
| 203 |
+
max_length = max(len(input_slice[self.model_input_names[0]]) for input_slice in truncated_inputs)
|
| 204 |
+
padding_strategy = PaddingStrategy.MAX_LENGTH
|
| 205 |
+
|
| 206 |
+
batch_outputs = {}
|
| 207 |
+
for i in range(batch_size):
|
| 208 |
+
# padding
|
| 209 |
+
outputs = self._pad(
|
| 210 |
+
truncated_inputs[i],
|
| 211 |
+
max_length=max_length,
|
| 212 |
+
padding_strategy=padding_strategy,
|
| 213 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 214 |
+
return_attention_mask=return_attention_mask,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
for key, value in outputs.items():
|
| 218 |
+
if key not in batch_outputs:
|
| 219 |
+
batch_outputs[key] = []
|
| 220 |
+
if value.dtype is np.dtype(np.float64):
|
| 221 |
+
value = value.astype(np.float32)
|
| 222 |
+
batch_outputs[key].append(value)
|
| 223 |
+
|
| 224 |
+
return BatchFeature(batch_outputs, tensor_type=return_tensors)
|
| 225 |
+
|
| 226 |
+
def _pad(
|
| 227 |
+
self,
|
| 228 |
+
processed_features: Union[dict[str, np.ndarray], BatchFeature],
|
| 229 |
+
max_length: Optional[int] = None,
|
| 230 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 231 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 232 |
+
return_attention_mask: Optional[bool] = None,
|
| 233 |
+
) -> dict:
|
| 234 |
+
"""
|
| 235 |
+
Pad inputs (on left/right and up to predefined length or max length in the batch)
|
| 236 |
+
|
| 237 |
+
Args:
|
| 238 |
+
processed_features (`Union[Dict[str, np.ndarray], BatchFeature]`):
|
| 239 |
+
Dictionary of input values (`np.ndarray[float]`) / input vectors (`List[np.ndarray[float]]`) or batch
|
| 240 |
+
of inputs values (`List[np.ndarray[int]]`) / input vectors (`List[np.ndarray[int]]`)
|
| 241 |
+
max_length (`int`, *optional*):
|
| 242 |
+
Maximum length of the returned list and optionally padding length (see below)
|
| 243 |
+
padding_strategy (`PaddingStrategy`, *optional*, default to `PaddingStrategy.DO_NOT_PAD`):
|
| 244 |
+
PaddingStrategy to use for padding.
|
| 245 |
+
|
| 246 |
+
- PaddingStrategy.LONGEST Pad to the longest sequence in the batch
|
| 247 |
+
- PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
|
| 248 |
+
- PaddingStrategy.DO_NOT_PAD: Do not pad
|
| 249 |
+
The feature_extractor padding sides are defined in self.padding_side:
|
| 250 |
+
|
| 251 |
+
- 'left': pads on the left of the sequences
|
| 252 |
+
- 'right': pads on the right of the sequences
|
| 253 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 254 |
+
Integer if set will pad the sequence to a multiple of the provided value. This is especially useful to
|
| 255 |
+
enable the use of Tensor Core on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs
|
| 256 |
+
which benefit from having sequence lengths be a multiple of 128.
|
| 257 |
+
return_attention_mask (`bool`, *optional*):
|
| 258 |
+
Set to False to avoid returning attention mask (default: set to model specifics)
|
| 259 |
+
"""
|
| 260 |
+
required_input = processed_features[self.model_input_names[0]]
|
| 261 |
+
|
| 262 |
+
if padding_strategy == PaddingStrategy.LONGEST:
|
| 263 |
+
max_length = len(required_input)
|
| 264 |
+
|
| 265 |
+
if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
|
| 266 |
+
max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
|
| 267 |
+
|
| 268 |
+
needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) < max_length
|
| 269 |
+
|
| 270 |
+
if return_attention_mask and "attention_mask" not in processed_features:
|
| 271 |
+
processed_features["attention_mask"] = np.ones(len(required_input), dtype=np.int32)
|
| 272 |
+
|
| 273 |
+
if needs_to_be_padded:
|
| 274 |
+
difference = max_length - len(required_input)
|
| 275 |
+
if self.padding_side == "right":
|
| 276 |
+
if return_attention_mask:
|
| 277 |
+
processed_features["attention_mask"] = np.pad(
|
| 278 |
+
processed_features["attention_mask"], (0, difference)
|
| 279 |
+
)
|
| 280 |
+
padding_shape = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
|
| 281 |
+
processed_features[self.model_input_names[0]] = np.pad(
|
| 282 |
+
required_input, padding_shape, "constant", constant_values=self.padding_value
|
| 283 |
+
)
|
| 284 |
+
elif self.padding_side == "left":
|
| 285 |
+
if return_attention_mask:
|
| 286 |
+
processed_features["attention_mask"] = np.pad(
|
| 287 |
+
processed_features["attention_mask"], (difference, 0)
|
| 288 |
+
)
|
| 289 |
+
padding_shape = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
|
| 290 |
+
processed_features[self.model_input_names[0]] = np.pad(
|
| 291 |
+
required_input, padding_shape, "constant", constant_values=self.padding_value
|
| 292 |
+
)
|
| 293 |
+
else:
|
| 294 |
+
raise ValueError("Invalid padding strategy:" + str(self.padding_side))
|
| 295 |
+
|
| 296 |
+
return processed_features
|
| 297 |
+
|
| 298 |
+
def _truncate(
|
| 299 |
+
self,
|
| 300 |
+
processed_features: Union[dict[str, np.ndarray], BatchFeature],
|
| 301 |
+
max_length: Optional[int] = None,
|
| 302 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 303 |
+
truncation: Optional[bool] = None,
|
| 304 |
+
):
|
| 305 |
+
"""
|
| 306 |
+
Truncate inputs to predefined length or max length in the batch
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
processed_features(`Union[Dict[str, np.ndarray], BatchFeature]`):
|
| 310 |
+
Dictionary of input values (`np.ndarray[float]`) / input vectors (`List[np.ndarray[float]]`) or batch
|
| 311 |
+
of inputs values (`List[np.ndarray[int]]`) / input vectors (`List[np.ndarray[int]]`)
|
| 312 |
+
max_length (`int`, *optional*):
|
| 313 |
+
maximum length of the returned list and optionally padding length (see below)
|
| 314 |
+
pad_to_multiple_of (`int`, *optional*) :
|
| 315 |
+
Integer if set will pad the sequence to a multiple of the provided value. This is especially useful to
|
| 316 |
+
enable the use of Tensor Core on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs
|
| 317 |
+
which benefit from having sequence lengths be a multiple of 128.
|
| 318 |
+
truncation (`bool`, *optional*):
|
| 319 |
+
Activates truncation to cut input sequences longer than `max_length` to `max_length`.
|
| 320 |
+
"""
|
| 321 |
+
if not truncation:
|
| 322 |
+
return processed_features
|
| 323 |
+
elif truncation and max_length is None:
|
| 324 |
+
raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined.")
|
| 325 |
+
|
| 326 |
+
required_input = processed_features[self.model_input_names[0]]
|
| 327 |
+
|
| 328 |
+
# find `max_length` that fits `pad_to_multiple_of`
|
| 329 |
+
if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
|
| 330 |
+
max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
|
| 331 |
+
|
| 332 |
+
needs_to_be_truncated = len(required_input) > max_length
|
| 333 |
+
|
| 334 |
+
if needs_to_be_truncated:
|
| 335 |
+
processed_features[self.model_input_names[0]] = processed_features[self.model_input_names[0]][:max_length]
|
| 336 |
+
if "attention_mask" in processed_features:
|
| 337 |
+
processed_features["attention_mask"] = processed_features["attention_mask"][:max_length]
|
| 338 |
+
|
| 339 |
+
return processed_features
|
| 340 |
+
|
| 341 |
+
def _get_padding_strategies(self, padding=False, max_length=None):
|
| 342 |
+
"""
|
| 343 |
+
Find the correct padding strategy
|
| 344 |
+
"""
|
| 345 |
+
|
| 346 |
+
# Get padding strategy
|
| 347 |
+
if padding is not False:
|
| 348 |
+
if padding is True:
|
| 349 |
+
padding_strategy = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch
|
| 350 |
+
elif not isinstance(padding, PaddingStrategy):
|
| 351 |
+
padding_strategy = PaddingStrategy(padding)
|
| 352 |
+
elif isinstance(padding, PaddingStrategy):
|
| 353 |
+
padding_strategy = padding
|
| 354 |
+
else:
|
| 355 |
+
padding_strategy = PaddingStrategy.DO_NOT_PAD
|
| 356 |
+
|
| 357 |
+
# Set max length if needed
|
| 358 |
+
if max_length is None:
|
| 359 |
+
if padding_strategy == PaddingStrategy.MAX_LENGTH:
|
| 360 |
+
raise ValueError(
|
| 361 |
+
f"When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined"
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
# Test if we have a padding value
|
| 365 |
+
if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):
|
| 366 |
+
raise ValueError(
|
| 367 |
+
"Asking to pad but the feature_extractor does not have a padding value. Please select a value to use"
|
| 368 |
+
" as `padding_value`. For example: `feature_extractor.padding_value = 0.0`."
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
return padding_strategy
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/feature_extraction_utils.py
ADDED
|
@@ -0,0 +1,701 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 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 |
+
Feature extraction saving/loading class for common feature extractors.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import copy
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import warnings
|
| 22 |
+
from collections import UserDict
|
| 23 |
+
from typing import TYPE_CHECKING, Any, Optional, Union
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
from .dynamic_module_utils import custom_object_save
|
| 28 |
+
from .utils import (
|
| 29 |
+
FEATURE_EXTRACTOR_NAME,
|
| 30 |
+
PushToHubMixin,
|
| 31 |
+
TensorType,
|
| 32 |
+
add_model_info_to_auto_map,
|
| 33 |
+
add_model_info_to_custom_pipelines,
|
| 34 |
+
cached_file,
|
| 35 |
+
copy_func,
|
| 36 |
+
download_url,
|
| 37 |
+
is_flax_available,
|
| 38 |
+
is_jax_tensor,
|
| 39 |
+
is_numpy_array,
|
| 40 |
+
is_offline_mode,
|
| 41 |
+
is_remote_url,
|
| 42 |
+
is_tf_available,
|
| 43 |
+
is_torch_available,
|
| 44 |
+
is_torch_device,
|
| 45 |
+
is_torch_dtype,
|
| 46 |
+
logging,
|
| 47 |
+
requires_backends,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if TYPE_CHECKING:
|
| 52 |
+
if is_torch_available():
|
| 53 |
+
import torch # noqa
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
logger = logging.get_logger(__name__)
|
| 57 |
+
|
| 58 |
+
PreTrainedFeatureExtractor = Union["SequenceFeatureExtractor"] # noqa: F821
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class BatchFeature(UserDict):
|
| 62 |
+
r"""
|
| 63 |
+
Holds the output of the [`~SequenceFeatureExtractor.pad`] and feature extractor specific `__call__` methods.
|
| 64 |
+
|
| 65 |
+
This class is derived from a python dictionary and can be used as a dictionary.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
data (`dict`, *optional*):
|
| 69 |
+
Dictionary of lists/arrays/tensors returned by the __call__/pad methods ('input_values', 'attention_mask',
|
| 70 |
+
etc.).
|
| 71 |
+
tensor_type (`Union[None, str, TensorType]`, *optional*):
|
| 72 |
+
You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at
|
| 73 |
+
initialization.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def __init__(self, data: Optional[dict[str, Any]] = None, tensor_type: Union[None, str, TensorType] = None):
|
| 77 |
+
super().__init__(data)
|
| 78 |
+
self.convert_to_tensors(tensor_type=tensor_type)
|
| 79 |
+
|
| 80 |
+
def __getitem__(self, item: str) -> Union[Any]:
|
| 81 |
+
"""
|
| 82 |
+
If the key is a string, returns the value of the dict associated to `key` ('input_values', 'attention_mask',
|
| 83 |
+
etc.).
|
| 84 |
+
"""
|
| 85 |
+
if isinstance(item, str):
|
| 86 |
+
return self.data[item]
|
| 87 |
+
else:
|
| 88 |
+
raise KeyError("Indexing with integers is not available when using Python based feature extractors")
|
| 89 |
+
|
| 90 |
+
def __getattr__(self, item: str):
|
| 91 |
+
try:
|
| 92 |
+
return self.data[item]
|
| 93 |
+
except KeyError:
|
| 94 |
+
raise AttributeError
|
| 95 |
+
|
| 96 |
+
def __getstate__(self):
|
| 97 |
+
return {"data": self.data}
|
| 98 |
+
|
| 99 |
+
def __setstate__(self, state):
|
| 100 |
+
if "data" in state:
|
| 101 |
+
self.data = state["data"]
|
| 102 |
+
|
| 103 |
+
# Copied from transformers.tokenization_utils_base.BatchEncoding.keys
|
| 104 |
+
def keys(self):
|
| 105 |
+
return self.data.keys()
|
| 106 |
+
|
| 107 |
+
# Copied from transformers.tokenization_utils_base.BatchEncoding.values
|
| 108 |
+
def values(self):
|
| 109 |
+
return self.data.values()
|
| 110 |
+
|
| 111 |
+
# Copied from transformers.tokenization_utils_base.BatchEncoding.items
|
| 112 |
+
def items(self):
|
| 113 |
+
return self.data.items()
|
| 114 |
+
|
| 115 |
+
def _get_is_as_tensor_fns(self, tensor_type: Optional[Union[str, TensorType]] = None):
|
| 116 |
+
if tensor_type is None:
|
| 117 |
+
return None, None
|
| 118 |
+
|
| 119 |
+
# Convert to TensorType
|
| 120 |
+
if not isinstance(tensor_type, TensorType):
|
| 121 |
+
tensor_type = TensorType(tensor_type)
|
| 122 |
+
|
| 123 |
+
# Get a function reference for the correct framework
|
| 124 |
+
if tensor_type == TensorType.TENSORFLOW:
|
| 125 |
+
if not is_tf_available():
|
| 126 |
+
raise ImportError(
|
| 127 |
+
"Unable to convert output to TensorFlow tensors format, TensorFlow is not installed."
|
| 128 |
+
)
|
| 129 |
+
import tensorflow as tf
|
| 130 |
+
|
| 131 |
+
as_tensor = tf.constant
|
| 132 |
+
is_tensor = tf.is_tensor
|
| 133 |
+
elif tensor_type == TensorType.PYTORCH:
|
| 134 |
+
if not is_torch_available():
|
| 135 |
+
raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed.")
|
| 136 |
+
import torch # noqa
|
| 137 |
+
|
| 138 |
+
def as_tensor(value):
|
| 139 |
+
if isinstance(value, (list, tuple)) and len(value) > 0:
|
| 140 |
+
if isinstance(value[0], np.ndarray):
|
| 141 |
+
value = np.array(value)
|
| 142 |
+
elif (
|
| 143 |
+
isinstance(value[0], (list, tuple))
|
| 144 |
+
and len(value[0]) > 0
|
| 145 |
+
and isinstance(value[0][0], np.ndarray)
|
| 146 |
+
):
|
| 147 |
+
value = np.array(value)
|
| 148 |
+
if isinstance(value, np.ndarray):
|
| 149 |
+
return torch.from_numpy(value)
|
| 150 |
+
else:
|
| 151 |
+
return torch.tensor(value)
|
| 152 |
+
|
| 153 |
+
is_tensor = torch.is_tensor
|
| 154 |
+
elif tensor_type == TensorType.JAX:
|
| 155 |
+
if not is_flax_available():
|
| 156 |
+
raise ImportError("Unable to convert output to JAX tensors format, JAX is not installed.")
|
| 157 |
+
import jax.numpy as jnp # noqa: F811
|
| 158 |
+
|
| 159 |
+
as_tensor = jnp.array
|
| 160 |
+
is_tensor = is_jax_tensor
|
| 161 |
+
else:
|
| 162 |
+
|
| 163 |
+
def as_tensor(value, dtype=None):
|
| 164 |
+
if isinstance(value, (list, tuple)) and isinstance(value[0], (list, tuple, np.ndarray)):
|
| 165 |
+
value_lens = [len(val) for val in value]
|
| 166 |
+
if len(set(value_lens)) > 1 and dtype is None:
|
| 167 |
+
# we have a ragged list so handle explicitly
|
| 168 |
+
value = as_tensor([np.asarray(val) for val in value], dtype=object)
|
| 169 |
+
return np.asarray(value, dtype=dtype)
|
| 170 |
+
|
| 171 |
+
is_tensor = is_numpy_array
|
| 172 |
+
return is_tensor, as_tensor
|
| 173 |
+
|
| 174 |
+
def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]] = None):
|
| 175 |
+
"""
|
| 176 |
+
Convert the inner content to tensors.
|
| 177 |
+
|
| 178 |
+
Args:
|
| 179 |
+
tensor_type (`str` or [`~utils.TensorType`], *optional*):
|
| 180 |
+
The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If
|
| 181 |
+
`None`, no modification is done.
|
| 182 |
+
"""
|
| 183 |
+
if tensor_type is None:
|
| 184 |
+
return self
|
| 185 |
+
|
| 186 |
+
is_tensor, as_tensor = self._get_is_as_tensor_fns(tensor_type)
|
| 187 |
+
|
| 188 |
+
# Do the tensor conversion in batch
|
| 189 |
+
for key, value in self.items():
|
| 190 |
+
try:
|
| 191 |
+
if not is_tensor(value):
|
| 192 |
+
tensor = as_tensor(value)
|
| 193 |
+
|
| 194 |
+
self[key] = tensor
|
| 195 |
+
except: # noqa E722
|
| 196 |
+
if key == "overflowing_values":
|
| 197 |
+
raise ValueError("Unable to create tensor returning overflowing values of different lengths. ")
|
| 198 |
+
raise ValueError(
|
| 199 |
+
"Unable to create tensor, you should probably activate padding "
|
| 200 |
+
"with 'padding=True' to have batched tensors with the same length."
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
return self
|
| 204 |
+
|
| 205 |
+
def to(self, *args, **kwargs) -> "BatchFeature":
|
| 206 |
+
"""
|
| 207 |
+
Send all values to device by calling `v.to(*args, **kwargs)` (PyTorch only). This should support casting in
|
| 208 |
+
different `dtypes` and sending the `BatchFeature` to a different `device`.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
args (`Tuple`):
|
| 212 |
+
Will be passed to the `to(...)` function of the tensors.
|
| 213 |
+
kwargs (`Dict`, *optional*):
|
| 214 |
+
Will be passed to the `to(...)` function of the tensors.
|
| 215 |
+
To enable asynchronous data transfer, set the `non_blocking` flag in `kwargs` (defaults to `False`).
|
| 216 |
+
|
| 217 |
+
Returns:
|
| 218 |
+
[`BatchFeature`]: The same instance after modification.
|
| 219 |
+
"""
|
| 220 |
+
requires_backends(self, ["torch"])
|
| 221 |
+
import torch # noqa
|
| 222 |
+
|
| 223 |
+
new_data = {}
|
| 224 |
+
device = kwargs.get("device")
|
| 225 |
+
non_blocking = kwargs.get("non_blocking", False)
|
| 226 |
+
# Check if the args are a device or a dtype
|
| 227 |
+
if device is None and len(args) > 0:
|
| 228 |
+
# device should be always the first argument
|
| 229 |
+
arg = args[0]
|
| 230 |
+
if is_torch_dtype(arg):
|
| 231 |
+
# The first argument is a dtype
|
| 232 |
+
pass
|
| 233 |
+
elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int):
|
| 234 |
+
device = arg
|
| 235 |
+
else:
|
| 236 |
+
# it's something else
|
| 237 |
+
raise ValueError(f"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.")
|
| 238 |
+
# We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor`
|
| 239 |
+
for k, v in self.items():
|
| 240 |
+
# check if v is a floating point
|
| 241 |
+
if isinstance(v, torch.Tensor) and torch.is_floating_point(v):
|
| 242 |
+
# cast and send to device
|
| 243 |
+
new_data[k] = v.to(*args, **kwargs)
|
| 244 |
+
elif isinstance(v, torch.Tensor) and device is not None:
|
| 245 |
+
new_data[k] = v.to(device=device, non_blocking=non_blocking)
|
| 246 |
+
else:
|
| 247 |
+
new_data[k] = v
|
| 248 |
+
self.data = new_data
|
| 249 |
+
return self
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class FeatureExtractionMixin(PushToHubMixin):
|
| 253 |
+
"""
|
| 254 |
+
This is a feature extraction mixin used to provide saving/loading functionality for sequential and image feature
|
| 255 |
+
extractors.
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
_auto_class = None
|
| 259 |
+
|
| 260 |
+
def __init__(self, **kwargs):
|
| 261 |
+
"""Set elements of `kwargs` as attributes."""
|
| 262 |
+
# Pop "processor_class" as it should be saved as private attribute
|
| 263 |
+
self._processor_class = kwargs.pop("processor_class", None)
|
| 264 |
+
# Additional attributes without default values
|
| 265 |
+
for key, value in kwargs.items():
|
| 266 |
+
try:
|
| 267 |
+
setattr(self, key, value)
|
| 268 |
+
except AttributeError as err:
|
| 269 |
+
logger.error(f"Can't set {key} with value {value} for {self}")
|
| 270 |
+
raise err
|
| 271 |
+
|
| 272 |
+
def _set_processor_class(self, processor_class: str):
|
| 273 |
+
"""Sets processor class as an attribute."""
|
| 274 |
+
self._processor_class = processor_class
|
| 275 |
+
|
| 276 |
+
@classmethod
|
| 277 |
+
def from_pretrained(
|
| 278 |
+
cls,
|
| 279 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 280 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 281 |
+
force_download: bool = False,
|
| 282 |
+
local_files_only: bool = False,
|
| 283 |
+
token: Optional[Union[str, bool]] = None,
|
| 284 |
+
revision: str = "main",
|
| 285 |
+
**kwargs,
|
| 286 |
+
):
|
| 287 |
+
r"""
|
| 288 |
+
Instantiate a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a feature extractor, *e.g.* a
|
| 289 |
+
derived class of [`SequenceFeatureExtractor`].
|
| 290 |
+
|
| 291 |
+
Args:
|
| 292 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 293 |
+
This can be either:
|
| 294 |
+
|
| 295 |
+
- a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
|
| 296 |
+
huggingface.co.
|
| 297 |
+
- a path to a *directory* containing a feature extractor file saved using the
|
| 298 |
+
[`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] method, e.g.,
|
| 299 |
+
`./my_model_directory/`.
|
| 300 |
+
- a path or url to a saved feature extractor JSON *file*, e.g.,
|
| 301 |
+
`./my_model_directory/preprocessor_config.json`.
|
| 302 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 303 |
+
Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
|
| 304 |
+
standard cache should not be used.
|
| 305 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 306 |
+
Whether or not to force to (re-)download the feature extractor files and override the cached versions
|
| 307 |
+
if they exist.
|
| 308 |
+
resume_download:
|
| 309 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 310 |
+
Will be removed in v5 of Transformers.
|
| 311 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 312 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 313 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 314 |
+
token (`str` or `bool`, *optional*):
|
| 315 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
|
| 316 |
+
the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 317 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 318 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 319 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 320 |
+
identifier allowed by git.
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
<Tip>
|
| 324 |
+
|
| 325 |
+
To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.
|
| 326 |
+
|
| 327 |
+
</Tip>
|
| 328 |
+
|
| 329 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 330 |
+
If `False`, then this function returns just the final feature extractor object. If `True`, then this
|
| 331 |
+
functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
|
| 332 |
+
consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
|
| 333 |
+
`kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
|
| 334 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 335 |
+
The values in kwargs of any keys which are feature extractor attributes will be used to override the
|
| 336 |
+
loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
|
| 337 |
+
controlled by the `return_unused_kwargs` keyword parameter.
|
| 338 |
+
|
| 339 |
+
Returns:
|
| 340 |
+
A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`].
|
| 341 |
+
|
| 342 |
+
Examples:
|
| 343 |
+
|
| 344 |
+
```python
|
| 345 |
+
# We can't instantiate directly the base class *FeatureExtractionMixin* nor *SequenceFeatureExtractor* so let's show the examples on a
|
| 346 |
+
# derived class: *Wav2Vec2FeatureExtractor*
|
| 347 |
+
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
|
| 348 |
+
"facebook/wav2vec2-base-960h"
|
| 349 |
+
) # Download feature_extraction_config from huggingface.co and cache.
|
| 350 |
+
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
|
| 351 |
+
"./test/saved_model/"
|
| 352 |
+
) # E.g. feature_extractor (or model) was saved using *save_pretrained('./test/saved_model/')*
|
| 353 |
+
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("./test/saved_model/preprocessor_config.json")
|
| 354 |
+
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
|
| 355 |
+
"facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False
|
| 356 |
+
)
|
| 357 |
+
assert feature_extractor.return_attention_mask is False
|
| 358 |
+
feature_extractor, unused_kwargs = Wav2Vec2FeatureExtractor.from_pretrained(
|
| 359 |
+
"facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False, return_unused_kwargs=True
|
| 360 |
+
)
|
| 361 |
+
assert feature_extractor.return_attention_mask is False
|
| 362 |
+
assert unused_kwargs == {"foo": False}
|
| 363 |
+
```"""
|
| 364 |
+
kwargs["cache_dir"] = cache_dir
|
| 365 |
+
kwargs["force_download"] = force_download
|
| 366 |
+
kwargs["local_files_only"] = local_files_only
|
| 367 |
+
kwargs["revision"] = revision
|
| 368 |
+
|
| 369 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 370 |
+
if use_auth_token is not None:
|
| 371 |
+
warnings.warn(
|
| 372 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 373 |
+
FutureWarning,
|
| 374 |
+
)
|
| 375 |
+
if token is not None:
|
| 376 |
+
raise ValueError(
|
| 377 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 378 |
+
)
|
| 379 |
+
token = use_auth_token
|
| 380 |
+
|
| 381 |
+
if token is not None:
|
| 382 |
+
kwargs["token"] = token
|
| 383 |
+
|
| 384 |
+
feature_extractor_dict, kwargs = cls.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs)
|
| 385 |
+
|
| 386 |
+
return cls.from_dict(feature_extractor_dict, **kwargs)
|
| 387 |
+
|
| 388 |
+
def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
|
| 389 |
+
"""
|
| 390 |
+
Save a feature_extractor object to the directory `save_directory`, so that it can be re-loaded using the
|
| 391 |
+
[`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`] class method.
|
| 392 |
+
|
| 393 |
+
Args:
|
| 394 |
+
save_directory (`str` or `os.PathLike`):
|
| 395 |
+
Directory where the feature extractor JSON file will be saved (will be created if it does not exist).
|
| 396 |
+
push_to_hub (`bool`, *optional*, defaults to `False`):
|
| 397 |
+
Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
|
| 398 |
+
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
|
| 399 |
+
namespace).
|
| 400 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 401 |
+
Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
|
| 402 |
+
"""
|
| 403 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 404 |
+
|
| 405 |
+
if use_auth_token is not None:
|
| 406 |
+
warnings.warn(
|
| 407 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 408 |
+
FutureWarning,
|
| 409 |
+
)
|
| 410 |
+
if kwargs.get("token", None) is not None:
|
| 411 |
+
raise ValueError(
|
| 412 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 413 |
+
)
|
| 414 |
+
kwargs["token"] = use_auth_token
|
| 415 |
+
|
| 416 |
+
if os.path.isfile(save_directory):
|
| 417 |
+
raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
|
| 418 |
+
|
| 419 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 420 |
+
|
| 421 |
+
if push_to_hub:
|
| 422 |
+
commit_message = kwargs.pop("commit_message", None)
|
| 423 |
+
repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
|
| 424 |
+
repo_id = self._create_repo(repo_id, **kwargs)
|
| 425 |
+
files_timestamps = self._get_files_timestamps(save_directory)
|
| 426 |
+
|
| 427 |
+
# If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
|
| 428 |
+
# loaded from the Hub.
|
| 429 |
+
if self._auto_class is not None:
|
| 430 |
+
custom_object_save(self, save_directory, config=self)
|
| 431 |
+
|
| 432 |
+
# If we save using the predefined names, we can load using `from_pretrained`
|
| 433 |
+
output_feature_extractor_file = os.path.join(save_directory, FEATURE_EXTRACTOR_NAME)
|
| 434 |
+
|
| 435 |
+
self.to_json_file(output_feature_extractor_file)
|
| 436 |
+
logger.info(f"Feature extractor saved in {output_feature_extractor_file}")
|
| 437 |
+
|
| 438 |
+
if push_to_hub:
|
| 439 |
+
self._upload_modified_files(
|
| 440 |
+
save_directory,
|
| 441 |
+
repo_id,
|
| 442 |
+
files_timestamps,
|
| 443 |
+
commit_message=commit_message,
|
| 444 |
+
token=kwargs.get("token"),
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
return [output_feature_extractor_file]
|
| 448 |
+
|
| 449 |
+
@classmethod
|
| 450 |
+
def get_feature_extractor_dict(
|
| 451 |
+
cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
|
| 452 |
+
) -> tuple[dict[str, Any], dict[str, Any]]:
|
| 453 |
+
"""
|
| 454 |
+
From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
|
| 455 |
+
feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] using `from_dict`.
|
| 456 |
+
|
| 457 |
+
Parameters:
|
| 458 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 459 |
+
The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.
|
| 460 |
+
|
| 461 |
+
Returns:
|
| 462 |
+
`Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the feature extractor object.
|
| 463 |
+
"""
|
| 464 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
| 465 |
+
force_download = kwargs.pop("force_download", False)
|
| 466 |
+
resume_download = kwargs.pop("resume_download", None)
|
| 467 |
+
proxies = kwargs.pop("proxies", None)
|
| 468 |
+
subfolder = kwargs.pop("subfolder", None)
|
| 469 |
+
token = kwargs.pop("token", None)
|
| 470 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 471 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
| 472 |
+
revision = kwargs.pop("revision", None)
|
| 473 |
+
|
| 474 |
+
if use_auth_token is not None:
|
| 475 |
+
warnings.warn(
|
| 476 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 477 |
+
FutureWarning,
|
| 478 |
+
)
|
| 479 |
+
if token is not None:
|
| 480 |
+
raise ValueError(
|
| 481 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 482 |
+
)
|
| 483 |
+
token = use_auth_token
|
| 484 |
+
|
| 485 |
+
from_pipeline = kwargs.pop("_from_pipeline", None)
|
| 486 |
+
from_auto_class = kwargs.pop("_from_auto", False)
|
| 487 |
+
|
| 488 |
+
user_agent = {"file_type": "feature extractor", "from_auto_class": from_auto_class}
|
| 489 |
+
if from_pipeline is not None:
|
| 490 |
+
user_agent["using_pipeline"] = from_pipeline
|
| 491 |
+
|
| 492 |
+
if is_offline_mode() and not local_files_only:
|
| 493 |
+
logger.info("Offline mode: forcing local_files_only=True")
|
| 494 |
+
local_files_only = True
|
| 495 |
+
|
| 496 |
+
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
|
| 497 |
+
is_local = os.path.isdir(pretrained_model_name_or_path)
|
| 498 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
| 499 |
+
feature_extractor_file = os.path.join(pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME)
|
| 500 |
+
if os.path.isfile(pretrained_model_name_or_path):
|
| 501 |
+
resolved_feature_extractor_file = pretrained_model_name_or_path
|
| 502 |
+
is_local = True
|
| 503 |
+
elif is_remote_url(pretrained_model_name_or_path):
|
| 504 |
+
feature_extractor_file = pretrained_model_name_or_path
|
| 505 |
+
resolved_feature_extractor_file = download_url(pretrained_model_name_or_path)
|
| 506 |
+
else:
|
| 507 |
+
feature_extractor_file = FEATURE_EXTRACTOR_NAME
|
| 508 |
+
try:
|
| 509 |
+
# Load from local folder or from cache or download from model Hub and cache
|
| 510 |
+
resolved_feature_extractor_file = cached_file(
|
| 511 |
+
pretrained_model_name_or_path,
|
| 512 |
+
feature_extractor_file,
|
| 513 |
+
cache_dir=cache_dir,
|
| 514 |
+
force_download=force_download,
|
| 515 |
+
proxies=proxies,
|
| 516 |
+
resume_download=resume_download,
|
| 517 |
+
local_files_only=local_files_only,
|
| 518 |
+
subfolder=subfolder,
|
| 519 |
+
token=token,
|
| 520 |
+
user_agent=user_agent,
|
| 521 |
+
revision=revision,
|
| 522 |
+
)
|
| 523 |
+
except OSError:
|
| 524 |
+
# Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
|
| 525 |
+
# the original exception.
|
| 526 |
+
raise
|
| 527 |
+
except Exception:
|
| 528 |
+
# For any other exception, we throw a generic error.
|
| 529 |
+
raise OSError(
|
| 530 |
+
f"Can't load feature extractor for '{pretrained_model_name_or_path}'. If you were trying to load"
|
| 531 |
+
" it from 'https://huggingface.co/models', make sure you don't have a local directory with the"
|
| 532 |
+
f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
|
| 533 |
+
f" directory containing a {FEATURE_EXTRACTOR_NAME} file"
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
try:
|
| 537 |
+
# Load feature_extractor dict
|
| 538 |
+
with open(resolved_feature_extractor_file, encoding="utf-8") as reader:
|
| 539 |
+
text = reader.read()
|
| 540 |
+
feature_extractor_dict = json.loads(text)
|
| 541 |
+
|
| 542 |
+
except json.JSONDecodeError:
|
| 543 |
+
raise OSError(
|
| 544 |
+
f"It looks like the config file at '{resolved_feature_extractor_file}' is not a valid JSON file."
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
if is_local:
|
| 548 |
+
logger.info(f"loading configuration file {resolved_feature_extractor_file}")
|
| 549 |
+
else:
|
| 550 |
+
logger.info(
|
| 551 |
+
f"loading configuration file {feature_extractor_file} from cache at {resolved_feature_extractor_file}"
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
if not is_local:
|
| 555 |
+
if "auto_map" in feature_extractor_dict:
|
| 556 |
+
feature_extractor_dict["auto_map"] = add_model_info_to_auto_map(
|
| 557 |
+
feature_extractor_dict["auto_map"], pretrained_model_name_or_path
|
| 558 |
+
)
|
| 559 |
+
if "custom_pipelines" in feature_extractor_dict:
|
| 560 |
+
feature_extractor_dict["custom_pipelines"] = add_model_info_to_custom_pipelines(
|
| 561 |
+
feature_extractor_dict["custom_pipelines"], pretrained_model_name_or_path
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
return feature_extractor_dict, kwargs
|
| 565 |
+
|
| 566 |
+
@classmethod
|
| 567 |
+
def from_dict(cls, feature_extractor_dict: dict[str, Any], **kwargs) -> PreTrainedFeatureExtractor:
|
| 568 |
+
"""
|
| 569 |
+
Instantiates a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a Python dictionary of
|
| 570 |
+
parameters.
|
| 571 |
+
|
| 572 |
+
Args:
|
| 573 |
+
feature_extractor_dict (`Dict[str, Any]`):
|
| 574 |
+
Dictionary that will be used to instantiate the feature extractor object. Such a dictionary can be
|
| 575 |
+
retrieved from a pretrained checkpoint by leveraging the
|
| 576 |
+
[`~feature_extraction_utils.FeatureExtractionMixin.to_dict`] method.
|
| 577 |
+
kwargs (`Dict[str, Any]`):
|
| 578 |
+
Additional parameters from which to initialize the feature extractor object.
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
[`~feature_extraction_utils.FeatureExtractionMixin`]: The feature extractor object instantiated from those
|
| 582 |
+
parameters.
|
| 583 |
+
"""
|
| 584 |
+
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
|
| 585 |
+
|
| 586 |
+
# Update feature_extractor with kwargs if needed
|
| 587 |
+
to_remove = []
|
| 588 |
+
for key, value in kwargs.items():
|
| 589 |
+
if key in feature_extractor_dict:
|
| 590 |
+
feature_extractor_dict[key] = value
|
| 591 |
+
to_remove.append(key)
|
| 592 |
+
for key in to_remove:
|
| 593 |
+
kwargs.pop(key, None)
|
| 594 |
+
|
| 595 |
+
feature_extractor = cls(**feature_extractor_dict)
|
| 596 |
+
|
| 597 |
+
logger.info(f"Feature extractor {feature_extractor}")
|
| 598 |
+
if return_unused_kwargs:
|
| 599 |
+
return feature_extractor, kwargs
|
| 600 |
+
else:
|
| 601 |
+
return feature_extractor
|
| 602 |
+
|
| 603 |
+
def to_dict(self) -> dict[str, Any]:
|
| 604 |
+
"""
|
| 605 |
+
Serializes this instance to a Python dictionary. Returns:
|
| 606 |
+
`Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
|
| 607 |
+
"""
|
| 608 |
+
output = copy.deepcopy(self.__dict__)
|
| 609 |
+
output["feature_extractor_type"] = self.__class__.__name__
|
| 610 |
+
if "mel_filters" in output:
|
| 611 |
+
del output["mel_filters"]
|
| 612 |
+
if "window" in output:
|
| 613 |
+
del output["window"]
|
| 614 |
+
return output
|
| 615 |
+
|
| 616 |
+
@classmethod
|
| 617 |
+
def from_json_file(cls, json_file: Union[str, os.PathLike]) -> PreTrainedFeatureExtractor:
|
| 618 |
+
"""
|
| 619 |
+
Instantiates a feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] from the path to
|
| 620 |
+
a JSON file of parameters.
|
| 621 |
+
|
| 622 |
+
Args:
|
| 623 |
+
json_file (`str` or `os.PathLike`):
|
| 624 |
+
Path to the JSON file containing the parameters.
|
| 625 |
+
|
| 626 |
+
Returns:
|
| 627 |
+
A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature_extractor
|
| 628 |
+
object instantiated from that JSON file.
|
| 629 |
+
"""
|
| 630 |
+
with open(json_file, encoding="utf-8") as reader:
|
| 631 |
+
text = reader.read()
|
| 632 |
+
feature_extractor_dict = json.loads(text)
|
| 633 |
+
return cls(**feature_extractor_dict)
|
| 634 |
+
|
| 635 |
+
def to_json_string(self) -> str:
|
| 636 |
+
"""
|
| 637 |
+
Serializes this instance to a JSON string.
|
| 638 |
+
|
| 639 |
+
Returns:
|
| 640 |
+
`str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
|
| 641 |
+
"""
|
| 642 |
+
dictionary = self.to_dict()
|
| 643 |
+
|
| 644 |
+
for key, value in dictionary.items():
|
| 645 |
+
if isinstance(value, np.ndarray):
|
| 646 |
+
dictionary[key] = value.tolist()
|
| 647 |
+
|
| 648 |
+
# make sure private name "_processor_class" is correctly
|
| 649 |
+
# saved as "processor_class"
|
| 650 |
+
_processor_class = dictionary.pop("_processor_class", None)
|
| 651 |
+
if _processor_class is not None:
|
| 652 |
+
dictionary["processor_class"] = _processor_class
|
| 653 |
+
|
| 654 |
+
return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
|
| 655 |
+
|
| 656 |
+
def to_json_file(self, json_file_path: Union[str, os.PathLike]):
|
| 657 |
+
"""
|
| 658 |
+
Save this instance to a JSON file.
|
| 659 |
+
|
| 660 |
+
Args:
|
| 661 |
+
json_file_path (`str` or `os.PathLike`):
|
| 662 |
+
Path to the JSON file in which this feature_extractor instance's parameters will be saved.
|
| 663 |
+
"""
|
| 664 |
+
with open(json_file_path, "w", encoding="utf-8") as writer:
|
| 665 |
+
writer.write(self.to_json_string())
|
| 666 |
+
|
| 667 |
+
def __repr__(self):
|
| 668 |
+
return f"{self.__class__.__name__} {self.to_json_string()}"
|
| 669 |
+
|
| 670 |
+
@classmethod
|
| 671 |
+
def register_for_auto_class(cls, auto_class="AutoFeatureExtractor"):
|
| 672 |
+
"""
|
| 673 |
+
Register this class with a given auto class. This should only be used for custom feature extractors as the ones
|
| 674 |
+
in the library are already mapped with `AutoFeatureExtractor`.
|
| 675 |
+
|
| 676 |
+
<Tip warning={true}>
|
| 677 |
+
|
| 678 |
+
This API is experimental and may have some slight breaking changes in the next releases.
|
| 679 |
+
|
| 680 |
+
</Tip>
|
| 681 |
+
|
| 682 |
+
Args:
|
| 683 |
+
auto_class (`str` or `type`, *optional*, defaults to `"AutoFeatureExtractor"`):
|
| 684 |
+
The auto class to register this new feature extractor with.
|
| 685 |
+
"""
|
| 686 |
+
if not isinstance(auto_class, str):
|
| 687 |
+
auto_class = auto_class.__name__
|
| 688 |
+
|
| 689 |
+
import transformers.models.auto as auto_module
|
| 690 |
+
|
| 691 |
+
if not hasattr(auto_module, auto_class):
|
| 692 |
+
raise ValueError(f"{auto_class} is not a valid auto class.")
|
| 693 |
+
|
| 694 |
+
cls._auto_class = auto_class
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
FeatureExtractionMixin.push_to_hub = copy_func(FeatureExtractionMixin.push_to_hub)
|
| 698 |
+
if FeatureExtractionMixin.push_to_hub.__doc__ is not None:
|
| 699 |
+
FeatureExtractionMixin.push_to_hub.__doc__ = FeatureExtractionMixin.push_to_hub.__doc__.format(
|
| 700 |
+
object="feature extractor", object_class="AutoFeatureExtractor", object_files="feature extractor file"
|
| 701 |
+
)
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/features.py
ADDED
|
@@ -0,0 +1,749 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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union
|
| 4 |
+
|
| 5 |
+
import transformers
|
| 6 |
+
|
| 7 |
+
from .. import PretrainedConfig, is_tf_available, is_torch_available
|
| 8 |
+
from ..utils import TF2_WEIGHTS_NAME, WEIGHTS_NAME, logging
|
| 9 |
+
from .config import OnnxConfig
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
from transformers import PreTrainedModel, TFPreTrainedModel
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 17 |
+
|
| 18 |
+
if is_torch_available():
|
| 19 |
+
from transformers.models.auto import (
|
| 20 |
+
AutoModel,
|
| 21 |
+
AutoModelForCausalLM,
|
| 22 |
+
AutoModelForImageClassification,
|
| 23 |
+
AutoModelForImageSegmentation,
|
| 24 |
+
AutoModelForMaskedImageModeling,
|
| 25 |
+
AutoModelForMaskedLM,
|
| 26 |
+
AutoModelForMultipleChoice,
|
| 27 |
+
AutoModelForObjectDetection,
|
| 28 |
+
AutoModelForQuestionAnswering,
|
| 29 |
+
AutoModelForSemanticSegmentation,
|
| 30 |
+
AutoModelForSeq2SeqLM,
|
| 31 |
+
AutoModelForSequenceClassification,
|
| 32 |
+
AutoModelForSpeechSeq2Seq,
|
| 33 |
+
AutoModelForTokenClassification,
|
| 34 |
+
AutoModelForVision2Seq,
|
| 35 |
+
)
|
| 36 |
+
if is_tf_available():
|
| 37 |
+
from transformers.models.auto import (
|
| 38 |
+
TFAutoModel,
|
| 39 |
+
TFAutoModelForCausalLM,
|
| 40 |
+
TFAutoModelForMaskedLM,
|
| 41 |
+
TFAutoModelForMultipleChoice,
|
| 42 |
+
TFAutoModelForQuestionAnswering,
|
| 43 |
+
TFAutoModelForSemanticSegmentation,
|
| 44 |
+
TFAutoModelForSeq2SeqLM,
|
| 45 |
+
TFAutoModelForSequenceClassification,
|
| 46 |
+
TFAutoModelForTokenClassification,
|
| 47 |
+
)
|
| 48 |
+
if not is_torch_available() and not is_tf_available():
|
| 49 |
+
logger.warning(
|
| 50 |
+
"The ONNX export features are only supported for PyTorch or TensorFlow. You will not be able to export models"
|
| 51 |
+
" without one of these libraries installed."
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def supported_features_mapping(
|
| 56 |
+
*supported_features: str, onnx_config_cls: Optional[str] = None
|
| 57 |
+
) -> Dict[str, Callable[[PretrainedConfig], OnnxConfig]]:
|
| 58 |
+
"""
|
| 59 |
+
Generate the mapping between supported the features and their corresponding OnnxConfig for a given model.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
*supported_features: The names of the supported features.
|
| 63 |
+
onnx_config_cls: The OnnxConfig full name corresponding to the model.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
The dictionary mapping a feature to an OnnxConfig constructor.
|
| 67 |
+
"""
|
| 68 |
+
if onnx_config_cls is None:
|
| 69 |
+
raise ValueError("A OnnxConfig class must be provided")
|
| 70 |
+
|
| 71 |
+
config_cls = transformers
|
| 72 |
+
for attr_name in onnx_config_cls.split("."):
|
| 73 |
+
config_cls = getattr(config_cls, attr_name)
|
| 74 |
+
mapping = {}
|
| 75 |
+
for feature in supported_features:
|
| 76 |
+
if "-with-past" in feature:
|
| 77 |
+
task = feature.replace("-with-past", "")
|
| 78 |
+
mapping[feature] = partial(config_cls.with_past, task=task)
|
| 79 |
+
else:
|
| 80 |
+
mapping[feature] = partial(config_cls.from_model_config, task=feature)
|
| 81 |
+
|
| 82 |
+
return mapping
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class FeaturesManager:
|
| 86 |
+
_TASKS_TO_AUTOMODELS = {}
|
| 87 |
+
_TASKS_TO_TF_AUTOMODELS = {}
|
| 88 |
+
if is_torch_available():
|
| 89 |
+
_TASKS_TO_AUTOMODELS = {
|
| 90 |
+
"default": AutoModel,
|
| 91 |
+
"masked-lm": AutoModelForMaskedLM,
|
| 92 |
+
"causal-lm": AutoModelForCausalLM,
|
| 93 |
+
"seq2seq-lm": AutoModelForSeq2SeqLM,
|
| 94 |
+
"sequence-classification": AutoModelForSequenceClassification,
|
| 95 |
+
"token-classification": AutoModelForTokenClassification,
|
| 96 |
+
"multiple-choice": AutoModelForMultipleChoice,
|
| 97 |
+
"object-detection": AutoModelForObjectDetection,
|
| 98 |
+
"question-answering": AutoModelForQuestionAnswering,
|
| 99 |
+
"image-classification": AutoModelForImageClassification,
|
| 100 |
+
"image-segmentation": AutoModelForImageSegmentation,
|
| 101 |
+
"masked-im": AutoModelForMaskedImageModeling,
|
| 102 |
+
"semantic-segmentation": AutoModelForSemanticSegmentation,
|
| 103 |
+
"vision2seq-lm": AutoModelForVision2Seq,
|
| 104 |
+
"speech2seq-lm": AutoModelForSpeechSeq2Seq,
|
| 105 |
+
}
|
| 106 |
+
if is_tf_available():
|
| 107 |
+
_TASKS_TO_TF_AUTOMODELS = {
|
| 108 |
+
"default": TFAutoModel,
|
| 109 |
+
"masked-lm": TFAutoModelForMaskedLM,
|
| 110 |
+
"causal-lm": TFAutoModelForCausalLM,
|
| 111 |
+
"seq2seq-lm": TFAutoModelForSeq2SeqLM,
|
| 112 |
+
"sequence-classification": TFAutoModelForSequenceClassification,
|
| 113 |
+
"token-classification": TFAutoModelForTokenClassification,
|
| 114 |
+
"multiple-choice": TFAutoModelForMultipleChoice,
|
| 115 |
+
"question-answering": TFAutoModelForQuestionAnswering,
|
| 116 |
+
"semantic-segmentation": TFAutoModelForSemanticSegmentation,
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
# Set of model topologies we support associated to the features supported by each topology and the factory
|
| 120 |
+
_SUPPORTED_MODEL_TYPE = {
|
| 121 |
+
"albert": supported_features_mapping(
|
| 122 |
+
"default",
|
| 123 |
+
"masked-lm",
|
| 124 |
+
"sequence-classification",
|
| 125 |
+
"multiple-choice",
|
| 126 |
+
"token-classification",
|
| 127 |
+
"question-answering",
|
| 128 |
+
onnx_config_cls="models.albert.AlbertOnnxConfig",
|
| 129 |
+
),
|
| 130 |
+
"bart": supported_features_mapping(
|
| 131 |
+
"default",
|
| 132 |
+
"default-with-past",
|
| 133 |
+
"causal-lm",
|
| 134 |
+
"causal-lm-with-past",
|
| 135 |
+
"seq2seq-lm",
|
| 136 |
+
"seq2seq-lm-with-past",
|
| 137 |
+
"sequence-classification",
|
| 138 |
+
"question-answering",
|
| 139 |
+
onnx_config_cls="models.bart.BartOnnxConfig",
|
| 140 |
+
),
|
| 141 |
+
# BEiT cannot be used with the masked image modeling autoclass, so this feature is excluded here
|
| 142 |
+
"beit": supported_features_mapping(
|
| 143 |
+
"default", "image-classification", onnx_config_cls="models.beit.BeitOnnxConfig"
|
| 144 |
+
),
|
| 145 |
+
"bert": supported_features_mapping(
|
| 146 |
+
"default",
|
| 147 |
+
"masked-lm",
|
| 148 |
+
"causal-lm",
|
| 149 |
+
"sequence-classification",
|
| 150 |
+
"multiple-choice",
|
| 151 |
+
"token-classification",
|
| 152 |
+
"question-answering",
|
| 153 |
+
onnx_config_cls="models.bert.BertOnnxConfig",
|
| 154 |
+
),
|
| 155 |
+
"big-bird": supported_features_mapping(
|
| 156 |
+
"default",
|
| 157 |
+
"masked-lm",
|
| 158 |
+
"causal-lm",
|
| 159 |
+
"sequence-classification",
|
| 160 |
+
"multiple-choice",
|
| 161 |
+
"token-classification",
|
| 162 |
+
"question-answering",
|
| 163 |
+
onnx_config_cls="models.big_bird.BigBirdOnnxConfig",
|
| 164 |
+
),
|
| 165 |
+
"bigbird-pegasus": supported_features_mapping(
|
| 166 |
+
"default",
|
| 167 |
+
"default-with-past",
|
| 168 |
+
"causal-lm",
|
| 169 |
+
"causal-lm-with-past",
|
| 170 |
+
"seq2seq-lm",
|
| 171 |
+
"seq2seq-lm-with-past",
|
| 172 |
+
"sequence-classification",
|
| 173 |
+
"question-answering",
|
| 174 |
+
onnx_config_cls="models.bigbird_pegasus.BigBirdPegasusOnnxConfig",
|
| 175 |
+
),
|
| 176 |
+
"blenderbot": supported_features_mapping(
|
| 177 |
+
"default",
|
| 178 |
+
"default-with-past",
|
| 179 |
+
"causal-lm",
|
| 180 |
+
"causal-lm-with-past",
|
| 181 |
+
"seq2seq-lm",
|
| 182 |
+
"seq2seq-lm-with-past",
|
| 183 |
+
onnx_config_cls="models.blenderbot.BlenderbotOnnxConfig",
|
| 184 |
+
),
|
| 185 |
+
"blenderbot-small": supported_features_mapping(
|
| 186 |
+
"default",
|
| 187 |
+
"default-with-past",
|
| 188 |
+
"causal-lm",
|
| 189 |
+
"causal-lm-with-past",
|
| 190 |
+
"seq2seq-lm",
|
| 191 |
+
"seq2seq-lm-with-past",
|
| 192 |
+
onnx_config_cls="models.blenderbot_small.BlenderbotSmallOnnxConfig",
|
| 193 |
+
),
|
| 194 |
+
"bloom": supported_features_mapping(
|
| 195 |
+
"default",
|
| 196 |
+
"default-with-past",
|
| 197 |
+
"causal-lm",
|
| 198 |
+
"causal-lm-with-past",
|
| 199 |
+
"sequence-classification",
|
| 200 |
+
"token-classification",
|
| 201 |
+
onnx_config_cls="models.bloom.BloomOnnxConfig",
|
| 202 |
+
),
|
| 203 |
+
"camembert": supported_features_mapping(
|
| 204 |
+
"default",
|
| 205 |
+
"masked-lm",
|
| 206 |
+
"causal-lm",
|
| 207 |
+
"sequence-classification",
|
| 208 |
+
"multiple-choice",
|
| 209 |
+
"token-classification",
|
| 210 |
+
"question-answering",
|
| 211 |
+
onnx_config_cls="models.camembert.CamembertOnnxConfig",
|
| 212 |
+
),
|
| 213 |
+
"clip": supported_features_mapping(
|
| 214 |
+
"default",
|
| 215 |
+
onnx_config_cls="models.clip.CLIPOnnxConfig",
|
| 216 |
+
),
|
| 217 |
+
"codegen": supported_features_mapping(
|
| 218 |
+
"default",
|
| 219 |
+
"causal-lm",
|
| 220 |
+
onnx_config_cls="models.codegen.CodeGenOnnxConfig",
|
| 221 |
+
),
|
| 222 |
+
"convbert": supported_features_mapping(
|
| 223 |
+
"default",
|
| 224 |
+
"masked-lm",
|
| 225 |
+
"sequence-classification",
|
| 226 |
+
"multiple-choice",
|
| 227 |
+
"token-classification",
|
| 228 |
+
"question-answering",
|
| 229 |
+
onnx_config_cls="models.convbert.ConvBertOnnxConfig",
|
| 230 |
+
),
|
| 231 |
+
"convnext": supported_features_mapping(
|
| 232 |
+
"default",
|
| 233 |
+
"image-classification",
|
| 234 |
+
onnx_config_cls="models.convnext.ConvNextOnnxConfig",
|
| 235 |
+
),
|
| 236 |
+
"data2vec-text": supported_features_mapping(
|
| 237 |
+
"default",
|
| 238 |
+
"masked-lm",
|
| 239 |
+
"sequence-classification",
|
| 240 |
+
"multiple-choice",
|
| 241 |
+
"token-classification",
|
| 242 |
+
"question-answering",
|
| 243 |
+
onnx_config_cls="models.data2vec.Data2VecTextOnnxConfig",
|
| 244 |
+
),
|
| 245 |
+
"data2vec-vision": supported_features_mapping(
|
| 246 |
+
"default",
|
| 247 |
+
"image-classification",
|
| 248 |
+
# ONNX doesn't support `adaptive_avg_pool2d` yet
|
| 249 |
+
# "semantic-segmentation",
|
| 250 |
+
onnx_config_cls="models.data2vec.Data2VecVisionOnnxConfig",
|
| 251 |
+
),
|
| 252 |
+
"deberta": supported_features_mapping(
|
| 253 |
+
"default",
|
| 254 |
+
"masked-lm",
|
| 255 |
+
"sequence-classification",
|
| 256 |
+
"token-classification",
|
| 257 |
+
"question-answering",
|
| 258 |
+
onnx_config_cls="models.deberta.DebertaOnnxConfig",
|
| 259 |
+
),
|
| 260 |
+
"deberta-v2": supported_features_mapping(
|
| 261 |
+
"default",
|
| 262 |
+
"masked-lm",
|
| 263 |
+
"sequence-classification",
|
| 264 |
+
"multiple-choice",
|
| 265 |
+
"token-classification",
|
| 266 |
+
"question-answering",
|
| 267 |
+
onnx_config_cls="models.deberta_v2.DebertaV2OnnxConfig",
|
| 268 |
+
),
|
| 269 |
+
"deit": supported_features_mapping(
|
| 270 |
+
"default", "image-classification", onnx_config_cls="models.deit.DeiTOnnxConfig"
|
| 271 |
+
),
|
| 272 |
+
"detr": supported_features_mapping(
|
| 273 |
+
"default",
|
| 274 |
+
"object-detection",
|
| 275 |
+
"image-segmentation",
|
| 276 |
+
onnx_config_cls="models.detr.DetrOnnxConfig",
|
| 277 |
+
),
|
| 278 |
+
"distilbert": supported_features_mapping(
|
| 279 |
+
"default",
|
| 280 |
+
"masked-lm",
|
| 281 |
+
"sequence-classification",
|
| 282 |
+
"multiple-choice",
|
| 283 |
+
"token-classification",
|
| 284 |
+
"question-answering",
|
| 285 |
+
onnx_config_cls="models.distilbert.DistilBertOnnxConfig",
|
| 286 |
+
),
|
| 287 |
+
"electra": supported_features_mapping(
|
| 288 |
+
"default",
|
| 289 |
+
"masked-lm",
|
| 290 |
+
"causal-lm",
|
| 291 |
+
"sequence-classification",
|
| 292 |
+
"multiple-choice",
|
| 293 |
+
"token-classification",
|
| 294 |
+
"question-answering",
|
| 295 |
+
onnx_config_cls="models.electra.ElectraOnnxConfig",
|
| 296 |
+
),
|
| 297 |
+
"flaubert": supported_features_mapping(
|
| 298 |
+
"default",
|
| 299 |
+
"masked-lm",
|
| 300 |
+
"causal-lm",
|
| 301 |
+
"sequence-classification",
|
| 302 |
+
"multiple-choice",
|
| 303 |
+
"token-classification",
|
| 304 |
+
"question-answering",
|
| 305 |
+
onnx_config_cls="models.flaubert.FlaubertOnnxConfig",
|
| 306 |
+
),
|
| 307 |
+
"gpt2": supported_features_mapping(
|
| 308 |
+
"default",
|
| 309 |
+
"default-with-past",
|
| 310 |
+
"causal-lm",
|
| 311 |
+
"causal-lm-with-past",
|
| 312 |
+
"sequence-classification",
|
| 313 |
+
"token-classification",
|
| 314 |
+
onnx_config_cls="models.gpt2.GPT2OnnxConfig",
|
| 315 |
+
),
|
| 316 |
+
"gptj": supported_features_mapping(
|
| 317 |
+
"default",
|
| 318 |
+
"default-with-past",
|
| 319 |
+
"causal-lm",
|
| 320 |
+
"causal-lm-with-past",
|
| 321 |
+
"question-answering",
|
| 322 |
+
"sequence-classification",
|
| 323 |
+
onnx_config_cls="models.gptj.GPTJOnnxConfig",
|
| 324 |
+
),
|
| 325 |
+
"gpt-neo": supported_features_mapping(
|
| 326 |
+
"default",
|
| 327 |
+
"default-with-past",
|
| 328 |
+
"causal-lm",
|
| 329 |
+
"causal-lm-with-past",
|
| 330 |
+
"sequence-classification",
|
| 331 |
+
onnx_config_cls="models.gpt_neo.GPTNeoOnnxConfig",
|
| 332 |
+
),
|
| 333 |
+
"groupvit": supported_features_mapping(
|
| 334 |
+
"default",
|
| 335 |
+
onnx_config_cls="models.groupvit.GroupViTOnnxConfig",
|
| 336 |
+
),
|
| 337 |
+
"ibert": supported_features_mapping(
|
| 338 |
+
"default",
|
| 339 |
+
"masked-lm",
|
| 340 |
+
"sequence-classification",
|
| 341 |
+
"multiple-choice",
|
| 342 |
+
"token-classification",
|
| 343 |
+
"question-answering",
|
| 344 |
+
onnx_config_cls="models.ibert.IBertOnnxConfig",
|
| 345 |
+
),
|
| 346 |
+
"imagegpt": supported_features_mapping(
|
| 347 |
+
"default", "image-classification", onnx_config_cls="models.imagegpt.ImageGPTOnnxConfig"
|
| 348 |
+
),
|
| 349 |
+
"layoutlm": supported_features_mapping(
|
| 350 |
+
"default",
|
| 351 |
+
"masked-lm",
|
| 352 |
+
"sequence-classification",
|
| 353 |
+
"token-classification",
|
| 354 |
+
onnx_config_cls="models.layoutlm.LayoutLMOnnxConfig",
|
| 355 |
+
),
|
| 356 |
+
"layoutlmv3": supported_features_mapping(
|
| 357 |
+
"default",
|
| 358 |
+
"question-answering",
|
| 359 |
+
"sequence-classification",
|
| 360 |
+
"token-classification",
|
| 361 |
+
onnx_config_cls="models.layoutlmv3.LayoutLMv3OnnxConfig",
|
| 362 |
+
),
|
| 363 |
+
"levit": supported_features_mapping(
|
| 364 |
+
"default", "image-classification", onnx_config_cls="models.levit.LevitOnnxConfig"
|
| 365 |
+
),
|
| 366 |
+
"longt5": supported_features_mapping(
|
| 367 |
+
"default",
|
| 368 |
+
"default-with-past",
|
| 369 |
+
"seq2seq-lm",
|
| 370 |
+
"seq2seq-lm-with-past",
|
| 371 |
+
onnx_config_cls="models.longt5.LongT5OnnxConfig",
|
| 372 |
+
),
|
| 373 |
+
"longformer": supported_features_mapping(
|
| 374 |
+
"default",
|
| 375 |
+
"masked-lm",
|
| 376 |
+
"multiple-choice",
|
| 377 |
+
"question-answering",
|
| 378 |
+
"sequence-classification",
|
| 379 |
+
"token-classification",
|
| 380 |
+
onnx_config_cls="models.longformer.LongformerOnnxConfig",
|
| 381 |
+
),
|
| 382 |
+
"marian": supported_features_mapping(
|
| 383 |
+
"default",
|
| 384 |
+
"default-with-past",
|
| 385 |
+
"seq2seq-lm",
|
| 386 |
+
"seq2seq-lm-with-past",
|
| 387 |
+
"causal-lm",
|
| 388 |
+
"causal-lm-with-past",
|
| 389 |
+
onnx_config_cls="models.marian.MarianOnnxConfig",
|
| 390 |
+
),
|
| 391 |
+
"mbart": supported_features_mapping(
|
| 392 |
+
"default",
|
| 393 |
+
"default-with-past",
|
| 394 |
+
"causal-lm",
|
| 395 |
+
"causal-lm-with-past",
|
| 396 |
+
"seq2seq-lm",
|
| 397 |
+
"seq2seq-lm-with-past",
|
| 398 |
+
"sequence-classification",
|
| 399 |
+
"question-answering",
|
| 400 |
+
onnx_config_cls="models.mbart.MBartOnnxConfig",
|
| 401 |
+
),
|
| 402 |
+
"mobilebert": supported_features_mapping(
|
| 403 |
+
"default",
|
| 404 |
+
"masked-lm",
|
| 405 |
+
"sequence-classification",
|
| 406 |
+
"multiple-choice",
|
| 407 |
+
"token-classification",
|
| 408 |
+
"question-answering",
|
| 409 |
+
onnx_config_cls="models.mobilebert.MobileBertOnnxConfig",
|
| 410 |
+
),
|
| 411 |
+
"mobilenet-v1": supported_features_mapping(
|
| 412 |
+
"default",
|
| 413 |
+
"image-classification",
|
| 414 |
+
onnx_config_cls="models.mobilenet_v1.MobileNetV1OnnxConfig",
|
| 415 |
+
),
|
| 416 |
+
"mobilenet-v2": supported_features_mapping(
|
| 417 |
+
"default",
|
| 418 |
+
"image-classification",
|
| 419 |
+
onnx_config_cls="models.mobilenet_v2.MobileNetV2OnnxConfig",
|
| 420 |
+
),
|
| 421 |
+
"mobilevit": supported_features_mapping(
|
| 422 |
+
"default",
|
| 423 |
+
"image-classification",
|
| 424 |
+
onnx_config_cls="models.mobilevit.MobileViTOnnxConfig",
|
| 425 |
+
),
|
| 426 |
+
"mt5": supported_features_mapping(
|
| 427 |
+
"default",
|
| 428 |
+
"default-with-past",
|
| 429 |
+
"seq2seq-lm",
|
| 430 |
+
"seq2seq-lm-with-past",
|
| 431 |
+
onnx_config_cls="models.mt5.MT5OnnxConfig",
|
| 432 |
+
),
|
| 433 |
+
"m2m-100": supported_features_mapping(
|
| 434 |
+
"default",
|
| 435 |
+
"default-with-past",
|
| 436 |
+
"seq2seq-lm",
|
| 437 |
+
"seq2seq-lm-with-past",
|
| 438 |
+
onnx_config_cls="models.m2m_100.M2M100OnnxConfig",
|
| 439 |
+
),
|
| 440 |
+
"owlvit": supported_features_mapping(
|
| 441 |
+
"default",
|
| 442 |
+
onnx_config_cls="models.owlvit.OwlViTOnnxConfig",
|
| 443 |
+
),
|
| 444 |
+
"perceiver": supported_features_mapping(
|
| 445 |
+
"image-classification",
|
| 446 |
+
"masked-lm",
|
| 447 |
+
"sequence-classification",
|
| 448 |
+
onnx_config_cls="models.perceiver.PerceiverOnnxConfig",
|
| 449 |
+
),
|
| 450 |
+
"poolformer": supported_features_mapping(
|
| 451 |
+
"default", "image-classification", onnx_config_cls="models.poolformer.PoolFormerOnnxConfig"
|
| 452 |
+
),
|
| 453 |
+
"rembert": supported_features_mapping(
|
| 454 |
+
"default",
|
| 455 |
+
"masked-lm",
|
| 456 |
+
"causal-lm",
|
| 457 |
+
"sequence-classification",
|
| 458 |
+
"multiple-choice",
|
| 459 |
+
"token-classification",
|
| 460 |
+
"question-answering",
|
| 461 |
+
onnx_config_cls="models.rembert.RemBertOnnxConfig",
|
| 462 |
+
),
|
| 463 |
+
"resnet": supported_features_mapping(
|
| 464 |
+
"default",
|
| 465 |
+
"image-classification",
|
| 466 |
+
onnx_config_cls="models.resnet.ResNetOnnxConfig",
|
| 467 |
+
),
|
| 468 |
+
"roberta": supported_features_mapping(
|
| 469 |
+
"default",
|
| 470 |
+
"masked-lm",
|
| 471 |
+
"causal-lm",
|
| 472 |
+
"sequence-classification",
|
| 473 |
+
"multiple-choice",
|
| 474 |
+
"token-classification",
|
| 475 |
+
"question-answering",
|
| 476 |
+
onnx_config_cls="models.roberta.RobertaOnnxConfig",
|
| 477 |
+
),
|
| 478 |
+
"roformer": supported_features_mapping(
|
| 479 |
+
"default",
|
| 480 |
+
"masked-lm",
|
| 481 |
+
"causal-lm",
|
| 482 |
+
"sequence-classification",
|
| 483 |
+
"token-classification",
|
| 484 |
+
"multiple-choice",
|
| 485 |
+
"question-answering",
|
| 486 |
+
"token-classification",
|
| 487 |
+
onnx_config_cls="models.roformer.RoFormerOnnxConfig",
|
| 488 |
+
),
|
| 489 |
+
"segformer": supported_features_mapping(
|
| 490 |
+
"default",
|
| 491 |
+
"image-classification",
|
| 492 |
+
"semantic-segmentation",
|
| 493 |
+
onnx_config_cls="models.segformer.SegformerOnnxConfig",
|
| 494 |
+
),
|
| 495 |
+
"squeezebert": supported_features_mapping(
|
| 496 |
+
"default",
|
| 497 |
+
"masked-lm",
|
| 498 |
+
"sequence-classification",
|
| 499 |
+
"multiple-choice",
|
| 500 |
+
"token-classification",
|
| 501 |
+
"question-answering",
|
| 502 |
+
onnx_config_cls="models.squeezebert.SqueezeBertOnnxConfig",
|
| 503 |
+
),
|
| 504 |
+
"swin": supported_features_mapping(
|
| 505 |
+
"default", "image-classification", onnx_config_cls="models.swin.SwinOnnxConfig"
|
| 506 |
+
),
|
| 507 |
+
"t5": supported_features_mapping(
|
| 508 |
+
"default",
|
| 509 |
+
"default-with-past",
|
| 510 |
+
"seq2seq-lm",
|
| 511 |
+
"seq2seq-lm-with-past",
|
| 512 |
+
onnx_config_cls="models.t5.T5OnnxConfig",
|
| 513 |
+
),
|
| 514 |
+
"vision-encoder-decoder": supported_features_mapping(
|
| 515 |
+
"vision2seq-lm", onnx_config_cls="models.vision_encoder_decoder.VisionEncoderDecoderOnnxConfig"
|
| 516 |
+
),
|
| 517 |
+
"vit": supported_features_mapping(
|
| 518 |
+
"default", "image-classification", onnx_config_cls="models.vit.ViTOnnxConfig"
|
| 519 |
+
),
|
| 520 |
+
"whisper": supported_features_mapping(
|
| 521 |
+
"default",
|
| 522 |
+
"default-with-past",
|
| 523 |
+
"speech2seq-lm",
|
| 524 |
+
"speech2seq-lm-with-past",
|
| 525 |
+
onnx_config_cls="models.whisper.WhisperOnnxConfig",
|
| 526 |
+
),
|
| 527 |
+
"xlm": supported_features_mapping(
|
| 528 |
+
"default",
|
| 529 |
+
"masked-lm",
|
| 530 |
+
"causal-lm",
|
| 531 |
+
"sequence-classification",
|
| 532 |
+
"multiple-choice",
|
| 533 |
+
"token-classification",
|
| 534 |
+
"question-answering",
|
| 535 |
+
onnx_config_cls="models.xlm.XLMOnnxConfig",
|
| 536 |
+
),
|
| 537 |
+
"xlm-roberta": supported_features_mapping(
|
| 538 |
+
"default",
|
| 539 |
+
"masked-lm",
|
| 540 |
+
"causal-lm",
|
| 541 |
+
"sequence-classification",
|
| 542 |
+
"multiple-choice",
|
| 543 |
+
"token-classification",
|
| 544 |
+
"question-answering",
|
| 545 |
+
onnx_config_cls="models.xlm_roberta.XLMRobertaOnnxConfig",
|
| 546 |
+
),
|
| 547 |
+
"yolos": supported_features_mapping(
|
| 548 |
+
"default",
|
| 549 |
+
"object-detection",
|
| 550 |
+
onnx_config_cls="models.yolos.YolosOnnxConfig",
|
| 551 |
+
),
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
AVAILABLE_FEATURES = sorted(reduce(lambda s1, s2: s1 | s2, (v.keys() for v in _SUPPORTED_MODEL_TYPE.values())))
|
| 555 |
+
|
| 556 |
+
@staticmethod
|
| 557 |
+
def get_supported_features_for_model_type(
|
| 558 |
+
model_type: str, model_name: Optional[str] = None
|
| 559 |
+
) -> Dict[str, Callable[[PretrainedConfig], OnnxConfig]]:
|
| 560 |
+
"""
|
| 561 |
+
Tries to retrieve the feature -> OnnxConfig constructor map from the model type.
|
| 562 |
+
|
| 563 |
+
Args:
|
| 564 |
+
model_type (`str`):
|
| 565 |
+
The model type to retrieve the supported features for.
|
| 566 |
+
model_name (`str`, *optional*):
|
| 567 |
+
The name attribute of the model object, only used for the exception message.
|
| 568 |
+
|
| 569 |
+
Returns:
|
| 570 |
+
The dictionary mapping each feature to a corresponding OnnxConfig constructor.
|
| 571 |
+
"""
|
| 572 |
+
model_type = model_type.lower()
|
| 573 |
+
if model_type not in FeaturesManager._SUPPORTED_MODEL_TYPE:
|
| 574 |
+
model_type_and_model_name = f"{model_type} ({model_name})" if model_name else model_type
|
| 575 |
+
raise KeyError(
|
| 576 |
+
f"{model_type_and_model_name} is not supported yet. "
|
| 577 |
+
f"Only {list(FeaturesManager._SUPPORTED_MODEL_TYPE.keys())} are supported. "
|
| 578 |
+
f"If you want to support {model_type} please propose a PR or open up an issue."
|
| 579 |
+
)
|
| 580 |
+
return FeaturesManager._SUPPORTED_MODEL_TYPE[model_type]
|
| 581 |
+
|
| 582 |
+
@staticmethod
|
| 583 |
+
def feature_to_task(feature: str) -> str:
|
| 584 |
+
return feature.replace("-with-past", "")
|
| 585 |
+
|
| 586 |
+
@staticmethod
|
| 587 |
+
def _validate_framework_choice(framework: str):
|
| 588 |
+
"""
|
| 589 |
+
Validates if the framework requested for the export is both correct and available, otherwise throws an
|
| 590 |
+
exception.
|
| 591 |
+
"""
|
| 592 |
+
if framework not in ["pt", "tf"]:
|
| 593 |
+
raise ValueError(
|
| 594 |
+
f"Only two frameworks are supported for ONNX export: pt or tf, but {framework} was provided."
|
| 595 |
+
)
|
| 596 |
+
elif framework == "pt" and not is_torch_available():
|
| 597 |
+
raise RuntimeError("Cannot export model to ONNX using PyTorch because no PyTorch package was found.")
|
| 598 |
+
elif framework == "tf" and not is_tf_available():
|
| 599 |
+
raise RuntimeError("Cannot export model to ONNX using TensorFlow because no TensorFlow package was found.")
|
| 600 |
+
|
| 601 |
+
@staticmethod
|
| 602 |
+
def get_model_class_for_feature(feature: str, framework: str = "pt") -> Type:
|
| 603 |
+
"""
|
| 604 |
+
Attempts to retrieve an AutoModel class from a feature name.
|
| 605 |
+
|
| 606 |
+
Args:
|
| 607 |
+
feature (`str`):
|
| 608 |
+
The feature required.
|
| 609 |
+
framework (`str`, *optional*, defaults to `"pt"`):
|
| 610 |
+
The framework to use for the export.
|
| 611 |
+
|
| 612 |
+
Returns:
|
| 613 |
+
The AutoModel class corresponding to the feature.
|
| 614 |
+
"""
|
| 615 |
+
task = FeaturesManager.feature_to_task(feature)
|
| 616 |
+
FeaturesManager._validate_framework_choice(framework)
|
| 617 |
+
if framework == "pt":
|
| 618 |
+
task_to_automodel = FeaturesManager._TASKS_TO_AUTOMODELS
|
| 619 |
+
else:
|
| 620 |
+
task_to_automodel = FeaturesManager._TASKS_TO_TF_AUTOMODELS
|
| 621 |
+
if task not in task_to_automodel:
|
| 622 |
+
raise KeyError(
|
| 623 |
+
f"Unknown task: {feature}. Possible values are {list(FeaturesManager._TASKS_TO_AUTOMODELS.values())}"
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
return task_to_automodel[task]
|
| 627 |
+
|
| 628 |
+
@staticmethod
|
| 629 |
+
def determine_framework(model: str, framework: Optional[str] = None) -> str:
|
| 630 |
+
"""
|
| 631 |
+
Determines the framework to use for the export.
|
| 632 |
+
|
| 633 |
+
The priority is in the following order:
|
| 634 |
+
1. User input via `framework`.
|
| 635 |
+
2. If local checkpoint is provided, use the same framework as the checkpoint.
|
| 636 |
+
3. Available framework in environment, with priority given to PyTorch
|
| 637 |
+
|
| 638 |
+
Args:
|
| 639 |
+
model (`str`):
|
| 640 |
+
The name of the model to export.
|
| 641 |
+
framework (`str`, *optional*, defaults to `None`):
|
| 642 |
+
The framework to use for the export. See above for priority if none provided.
|
| 643 |
+
|
| 644 |
+
Returns:
|
| 645 |
+
The framework to use for the export.
|
| 646 |
+
|
| 647 |
+
"""
|
| 648 |
+
if framework is not None:
|
| 649 |
+
return framework
|
| 650 |
+
|
| 651 |
+
framework_map = {"pt": "PyTorch", "tf": "TensorFlow"}
|
| 652 |
+
exporter_map = {"pt": "torch", "tf": "tf2onnx"}
|
| 653 |
+
|
| 654 |
+
if os.path.isdir(model):
|
| 655 |
+
if os.path.isfile(os.path.join(model, WEIGHTS_NAME)):
|
| 656 |
+
framework = "pt"
|
| 657 |
+
elif os.path.isfile(os.path.join(model, TF2_WEIGHTS_NAME)):
|
| 658 |
+
framework = "tf"
|
| 659 |
+
else:
|
| 660 |
+
raise FileNotFoundError(
|
| 661 |
+
"Cannot determine framework from given checkpoint location."
|
| 662 |
+
f" There should be a {WEIGHTS_NAME} for PyTorch"
|
| 663 |
+
f" or {TF2_WEIGHTS_NAME} for TensorFlow."
|
| 664 |
+
)
|
| 665 |
+
logger.info(f"Local {framework_map[framework]} model found.")
|
| 666 |
+
else:
|
| 667 |
+
if is_torch_available():
|
| 668 |
+
framework = "pt"
|
| 669 |
+
elif is_tf_available():
|
| 670 |
+
framework = "tf"
|
| 671 |
+
else:
|
| 672 |
+
raise EnvironmentError("Neither PyTorch nor TensorFlow found in environment. Cannot export to ONNX.")
|
| 673 |
+
|
| 674 |
+
logger.info(f"Framework not requested. Using {exporter_map[framework]} to export to ONNX.")
|
| 675 |
+
|
| 676 |
+
return framework
|
| 677 |
+
|
| 678 |
+
@staticmethod
|
| 679 |
+
def get_model_from_feature(
|
| 680 |
+
feature: str, model: str, framework: Optional[str] = None, cache_dir: Optional[str] = None
|
| 681 |
+
) -> Union["PreTrainedModel", "TFPreTrainedModel"]:
|
| 682 |
+
"""
|
| 683 |
+
Attempts to retrieve a model from a model's name and the feature to be enabled.
|
| 684 |
+
|
| 685 |
+
Args:
|
| 686 |
+
feature (`str`):
|
| 687 |
+
The feature required.
|
| 688 |
+
model (`str`):
|
| 689 |
+
The name of the model to export.
|
| 690 |
+
framework (`str`, *optional*, defaults to `None`):
|
| 691 |
+
The framework to use for the export. See `FeaturesManager.determine_framework` for the priority should
|
| 692 |
+
none be provided.
|
| 693 |
+
|
| 694 |
+
Returns:
|
| 695 |
+
The instance of the model.
|
| 696 |
+
|
| 697 |
+
"""
|
| 698 |
+
framework = FeaturesManager.determine_framework(model, framework)
|
| 699 |
+
model_class = FeaturesManager.get_model_class_for_feature(feature, framework)
|
| 700 |
+
try:
|
| 701 |
+
model = model_class.from_pretrained(model, cache_dir=cache_dir)
|
| 702 |
+
except OSError:
|
| 703 |
+
if framework == "pt":
|
| 704 |
+
logger.info("Loading TensorFlow model in PyTorch before exporting to ONNX.")
|
| 705 |
+
model = model_class.from_pretrained(model, from_tf=True, cache_dir=cache_dir)
|
| 706 |
+
else:
|
| 707 |
+
logger.info("Loading PyTorch model in TensorFlow before exporting to ONNX.")
|
| 708 |
+
model = model_class.from_pretrained(model, from_pt=True, cache_dir=cache_dir)
|
| 709 |
+
return model
|
| 710 |
+
|
| 711 |
+
@staticmethod
|
| 712 |
+
def check_supported_model_or_raise(
|
| 713 |
+
model: Union["PreTrainedModel", "TFPreTrainedModel"], feature: str = "default"
|
| 714 |
+
) -> Tuple[str, Callable]:
|
| 715 |
+
"""
|
| 716 |
+
Check whether or not the model has the requested features.
|
| 717 |
+
|
| 718 |
+
Args:
|
| 719 |
+
model: The model to export.
|
| 720 |
+
feature: The name of the feature to check if it is available.
|
| 721 |
+
|
| 722 |
+
Returns:
|
| 723 |
+
(str) The type of the model (OnnxConfig) The OnnxConfig instance holding the model export properties.
|
| 724 |
+
|
| 725 |
+
"""
|
| 726 |
+
model_type = model.config.model_type.replace("_", "-")
|
| 727 |
+
model_name = getattr(model, "name", "")
|
| 728 |
+
model_features = FeaturesManager.get_supported_features_for_model_type(model_type, model_name=model_name)
|
| 729 |
+
if feature not in model_features:
|
| 730 |
+
raise ValueError(
|
| 731 |
+
f"{model.config.model_type} doesn't support feature {feature}. Supported values are: {model_features}"
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
return model.config.model_type, FeaturesManager._SUPPORTED_MODEL_TYPE[model_type][feature]
|
| 735 |
+
|
| 736 |
+
def get_config(model_type: str, feature: str) -> OnnxConfig:
|
| 737 |
+
"""
|
| 738 |
+
Gets the OnnxConfig for a model_type and feature combination.
|
| 739 |
+
|
| 740 |
+
Args:
|
| 741 |
+
model_type (`str`):
|
| 742 |
+
The model type to retrieve the config for.
|
| 743 |
+
feature (`str`):
|
| 744 |
+
The feature to retrieve the config for.
|
| 745 |
+
|
| 746 |
+
Returns:
|
| 747 |
+
`OnnxConfig`: config for the combination
|
| 748 |
+
"""
|
| 749 |
+
return FeaturesManager._SUPPORTED_MODEL_TYPE[model_type][feature]
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/file_utils.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 |
+
File utilities: utilities related to download and cache models
|
| 16 |
+
|
| 17 |
+
This module should not be update anymore and is only left for backward compatibility.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from huggingface_hub import get_full_repo_name # for backward compatibility
|
| 21 |
+
from huggingface_hub.constants import HF_HUB_DISABLE_TELEMETRY as DISABLE_TELEMETRY # for backward compatibility
|
| 22 |
+
|
| 23 |
+
from . import __version__
|
| 24 |
+
|
| 25 |
+
# Backward compatibility imports, to make sure all those objects can be found in file_utils
|
| 26 |
+
from .utils import (
|
| 27 |
+
CLOUDFRONT_DISTRIB_PREFIX,
|
| 28 |
+
CONFIG_NAME,
|
| 29 |
+
DUMMY_INPUTS,
|
| 30 |
+
DUMMY_MASK,
|
| 31 |
+
ENV_VARS_TRUE_AND_AUTO_VALUES,
|
| 32 |
+
ENV_VARS_TRUE_VALUES,
|
| 33 |
+
FEATURE_EXTRACTOR_NAME,
|
| 34 |
+
FLAX_WEIGHTS_NAME,
|
| 35 |
+
HF_MODULES_CACHE,
|
| 36 |
+
HUGGINGFACE_CO_PREFIX,
|
| 37 |
+
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
|
| 38 |
+
MODEL_CARD_NAME,
|
| 39 |
+
MULTIPLE_CHOICE_DUMMY_INPUTS,
|
| 40 |
+
PYTORCH_PRETRAINED_BERT_CACHE,
|
| 41 |
+
PYTORCH_TRANSFORMERS_CACHE,
|
| 42 |
+
S3_BUCKET_PREFIX,
|
| 43 |
+
SENTENCEPIECE_UNDERLINE,
|
| 44 |
+
SPIECE_UNDERLINE,
|
| 45 |
+
TF2_WEIGHTS_NAME,
|
| 46 |
+
TF_WEIGHTS_NAME,
|
| 47 |
+
TORCH_FX_REQUIRED_VERSION,
|
| 48 |
+
TRANSFORMERS_CACHE,
|
| 49 |
+
TRANSFORMERS_DYNAMIC_MODULE_NAME,
|
| 50 |
+
USE_JAX,
|
| 51 |
+
USE_TF,
|
| 52 |
+
USE_TORCH,
|
| 53 |
+
WEIGHTS_INDEX_NAME,
|
| 54 |
+
WEIGHTS_NAME,
|
| 55 |
+
ContextManagers,
|
| 56 |
+
DummyObject,
|
| 57 |
+
EntryNotFoundError,
|
| 58 |
+
ExplicitEnum,
|
| 59 |
+
ModelOutput,
|
| 60 |
+
PaddingStrategy,
|
| 61 |
+
PushToHubMixin,
|
| 62 |
+
RepositoryNotFoundError,
|
| 63 |
+
RevisionNotFoundError,
|
| 64 |
+
TensorType,
|
| 65 |
+
_LazyModule,
|
| 66 |
+
add_code_sample_docstrings,
|
| 67 |
+
add_end_docstrings,
|
| 68 |
+
add_start_docstrings,
|
| 69 |
+
add_start_docstrings_to_model_forward,
|
| 70 |
+
cached_property,
|
| 71 |
+
copy_func,
|
| 72 |
+
default_cache_path,
|
| 73 |
+
define_sagemaker_information,
|
| 74 |
+
get_torch_version,
|
| 75 |
+
has_file,
|
| 76 |
+
http_user_agent,
|
| 77 |
+
is_apex_available,
|
| 78 |
+
is_bs4_available,
|
| 79 |
+
is_coloredlogs_available,
|
| 80 |
+
is_datasets_available,
|
| 81 |
+
is_detectron2_available,
|
| 82 |
+
is_faiss_available,
|
| 83 |
+
is_flax_available,
|
| 84 |
+
is_ftfy_available,
|
| 85 |
+
is_g2p_en_available,
|
| 86 |
+
is_in_notebook,
|
| 87 |
+
is_ipex_available,
|
| 88 |
+
is_librosa_available,
|
| 89 |
+
is_offline_mode,
|
| 90 |
+
is_onnx_available,
|
| 91 |
+
is_pandas_available,
|
| 92 |
+
is_phonemizer_available,
|
| 93 |
+
is_protobuf_available,
|
| 94 |
+
is_psutil_available,
|
| 95 |
+
is_py3nvml_available,
|
| 96 |
+
is_pyctcdecode_available,
|
| 97 |
+
is_pytesseract_available,
|
| 98 |
+
is_pytorch_quantization_available,
|
| 99 |
+
is_rjieba_available,
|
| 100 |
+
is_sagemaker_dp_enabled,
|
| 101 |
+
is_sagemaker_mp_enabled,
|
| 102 |
+
is_scipy_available,
|
| 103 |
+
is_sentencepiece_available,
|
| 104 |
+
is_seqio_available,
|
| 105 |
+
is_sklearn_available,
|
| 106 |
+
is_soundfile_available,
|
| 107 |
+
is_spacy_available,
|
| 108 |
+
is_speech_available,
|
| 109 |
+
is_tensor,
|
| 110 |
+
is_tensorflow_probability_available,
|
| 111 |
+
is_tf2onnx_available,
|
| 112 |
+
is_tf_available,
|
| 113 |
+
is_timm_available,
|
| 114 |
+
is_tokenizers_available,
|
| 115 |
+
is_torch_available,
|
| 116 |
+
is_torch_bf16_available,
|
| 117 |
+
is_torch_cuda_available,
|
| 118 |
+
is_torch_fx_available,
|
| 119 |
+
is_torch_fx_proxy,
|
| 120 |
+
is_torch_mps_available,
|
| 121 |
+
is_torch_tf32_available,
|
| 122 |
+
is_torch_xla_available,
|
| 123 |
+
is_torchaudio_available,
|
| 124 |
+
is_training_run_on_sagemaker,
|
| 125 |
+
is_vision_available,
|
| 126 |
+
replace_return_docstrings,
|
| 127 |
+
requires_backends,
|
| 128 |
+
to_numpy,
|
| 129 |
+
to_py_obj,
|
| 130 |
+
torch_only_method,
|
| 131 |
+
)
|
qian_sg_backup/qwen3_hyp/qwen3_hyp_p047m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260310_043623/finegrained_fp8.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 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 |
+
|
| 16 |
+
from typing import List, Optional, Tuple
|
| 17 |
+
|
| 18 |
+
from ..utils import is_accelerate_available, is_torch_available, logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if is_torch_available():
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn as nn
|
| 24 |
+
import triton
|
| 25 |
+
import triton.language as tl
|
| 26 |
+
from torch.nn import functional as F
|
| 27 |
+
|
| 28 |
+
if is_accelerate_available():
|
| 29 |
+
from accelerate import init_empty_weights
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# Copied from https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/inference/kernel.py
|
| 36 |
+
@triton.jit
|
| 37 |
+
def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr):
|
| 38 |
+
pid = tl.program_id(axis=0)
|
| 39 |
+
offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
| 40 |
+
x = tl.load(x_ptr + offs).to(tl.float32)
|
| 41 |
+
s = tl.max(tl.abs(x)) / 448.0
|
| 42 |
+
y = x / s
|
| 43 |
+
y = y.to(y_ptr.dtype.element_ty)
|
| 44 |
+
tl.store(y_ptr + offs, y)
|
| 45 |
+
tl.store(s_ptr + pid, s)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def act_quant(x: torch.Tensor, block_size: int = 128) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 49 |
+
assert x.is_contiguous()
|
| 50 |
+
assert x.shape[-1] % block_size == 0
|
| 51 |
+
y = torch.empty_like(x, dtype=torch.float8_e4m3fn)
|
| 52 |
+
s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
|
| 53 |
+
|
| 54 |
+
def grid(meta):
|
| 55 |
+
return (triton.cdiv(x.numel(), meta["BLOCK_SIZE"]),)
|
| 56 |
+
|
| 57 |
+
act_quant_kernel[grid](x, y, s, BLOCK_SIZE=block_size)
|
| 58 |
+
return y, s
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Adapted from https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/quantization/fp8_kernel.py
|
| 62 |
+
@triton.jit
|
| 63 |
+
def _w8a8_block_fp8_matmul(
|
| 64 |
+
# Pointers to inputs and output
|
| 65 |
+
A,
|
| 66 |
+
B,
|
| 67 |
+
C,
|
| 68 |
+
As,
|
| 69 |
+
Bs,
|
| 70 |
+
# Shape for matmul
|
| 71 |
+
M,
|
| 72 |
+
N,
|
| 73 |
+
K,
|
| 74 |
+
# Block size for block-wise quantization
|
| 75 |
+
group_n,
|
| 76 |
+
group_k,
|
| 77 |
+
# Stride for inputs and output
|
| 78 |
+
stride_am,
|
| 79 |
+
stride_ak,
|
| 80 |
+
stride_bk,
|
| 81 |
+
stride_bn,
|
| 82 |
+
stride_cm,
|
| 83 |
+
stride_cn,
|
| 84 |
+
stride_As_m,
|
| 85 |
+
stride_As_k,
|
| 86 |
+
stride_Bs_k,
|
| 87 |
+
stride_Bs_n,
|
| 88 |
+
# Meta-parameters
|
| 89 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 90 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 91 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 92 |
+
GROUP_SIZE_M: tl.constexpr,
|
| 93 |
+
):
|
| 94 |
+
"""Triton-accelerated function used to perform linear operations (dot
|
| 95 |
+
product) on input tensors `A` and `B` with block-wise quantization, and
|
| 96 |
+
store the result in output tensor `C`.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
pid = tl.program_id(axis=0)
|
| 100 |
+
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 101 |
+
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 102 |
+
num_pid_in_group = GROUP_SIZE_M * num_pid_n
|
| 103 |
+
group_id = pid // num_pid_in_group
|
| 104 |
+
first_pid_m = group_id * GROUP_SIZE_M
|
| 105 |
+
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
|
| 106 |
+
pid_m = first_pid_m + (pid % group_size_m)
|
| 107 |
+
pid_n = (pid % num_pid_in_group) // group_size_m
|
| 108 |
+
|
| 109 |
+
offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
|
| 110 |
+
offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
|
| 111 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 112 |
+
a_ptrs = A + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak)
|
| 113 |
+
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 114 |
+
|
| 115 |
+
As_ptrs = As + offs_am * stride_As_m
|
| 116 |
+
offs_bsn = offs_bn // group_n
|
| 117 |
+
Bs_ptrs = Bs + offs_bsn * stride_Bs_n
|
| 118 |
+
|
| 119 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 120 |
+
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 121 |
+
a = tl.load(a_ptrs, mask=offs_k[None, :] < K - k * BLOCK_SIZE_K, other=0.0)
|
| 122 |
+
b = tl.load(b_ptrs, mask=offs_k[:, None] < K - k * BLOCK_SIZE_K, other=0.0)
|
| 123 |
+
|
| 124 |
+
k_start = k * BLOCK_SIZE_K
|
| 125 |
+
offs_ks = k_start // group_k
|
| 126 |
+
a_s = tl.load(As_ptrs + offs_ks * stride_As_k)
|
| 127 |
+
b_s = tl.load(Bs_ptrs + offs_ks * stride_Bs_k)
|
| 128 |
+
|
| 129 |
+
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 130 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 131 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 132 |
+
|
| 133 |
+
if C.dtype.element_ty == tl.bfloat16:
|
| 134 |
+
c = accumulator.to(tl.bfloat16)
|
| 135 |
+
elif C.dtype.element_ty == tl.float16:
|
| 136 |
+
c = accumulator.to(tl.float16)
|
| 137 |
+
else:
|
| 138 |
+
c = accumulator.to(tl.float32)
|
| 139 |
+
|
| 140 |
+
offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 141 |
+
offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 142 |
+
c_ptrs = C + stride_cm * offs_cm[:, None] + stride_cn * offs_cn[None, :]
|
| 143 |
+
c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < N)
|
| 144 |
+
tl.store(c_ptrs, c, mask=c_mask)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def w8a8_block_fp8_matmul_triton(
|
| 148 |
+
A: torch.Tensor,
|
| 149 |
+
B: torch.Tensor,
|
| 150 |
+
As: torch.Tensor,
|
| 151 |
+
Bs: torch.Tensor,
|
| 152 |
+
block_size: List[int],
|
| 153 |
+
output_dtype: torch.dtype = torch.float32,
|
| 154 |
+
) -> torch.Tensor:
|
| 155 |
+
"""This function performs matrix multiplication with block-wise
|
| 156 |
+
quantization.
|
| 157 |
+
It takes two input tensors `A` and `B` with scales `As` and `Bs`.
|
| 158 |
+
The output is returned in the specified `output_dtype`.
|
| 159 |
+
Args:
|
| 160 |
+
A: The input tensor, e.g., activation.
|
| 161 |
+
B: The input tensor, e.g., weight.
|
| 162 |
+
As: The per-token-group quantization scale for `A`.
|
| 163 |
+
Bs: The per-block quantization scale for `B`.
|
| 164 |
+
block_size: The block size for per-block quantization. It should
|
| 165 |
+
be 2-dim, e.g., [128, 128].
|
| 166 |
+
output_dytpe: The dtype of the returned tensor.
|
| 167 |
+
Returns:
|
| 168 |
+
torch.Tensor: The result of matmul.
|
| 169 |
+
"""
|
| 170 |
+
assert len(block_size) == 2
|
| 171 |
+
block_n, block_k = block_size[0], block_size[1]
|
| 172 |
+
|
| 173 |
+
assert A.shape[-1] == B.shape[-1]
|
| 174 |
+
assert A.shape[:-1] == As.shape[:-1] and A.is_contiguous()
|
| 175 |
+
assert triton.cdiv(A.shape[-1], block_k) == As.shape[-1]
|
| 176 |
+
M = A.numel() // A.shape[-1]
|
| 177 |
+
|
| 178 |
+
assert B.ndim == 2 and B.is_contiguous() and Bs.ndim == 2
|
| 179 |
+
N, K = B.shape
|
| 180 |
+
assert triton.cdiv(N, block_n) == Bs.shape[0]
|
| 181 |
+
assert triton.cdiv(K, block_k) == Bs.shape[1]
|
| 182 |
+
|
| 183 |
+
C_shape = A.shape[:-1] + (N,)
|
| 184 |
+
C = A.new_empty(C_shape, dtype=output_dtype)
|
| 185 |
+
|
| 186 |
+
BLOCK_SIZE_M = 128
|
| 187 |
+
if M < BLOCK_SIZE_M:
|
| 188 |
+
BLOCK_SIZE_M = triton.next_power_of_2(M)
|
| 189 |
+
BLOCK_SIZE_M = max(BLOCK_SIZE_M, 16)
|
| 190 |
+
BLOCK_SIZE_K = block_k
|
| 191 |
+
assert block_k % BLOCK_SIZE_K == 0
|
| 192 |
+
BLOCK_SIZE_N = block_n
|
| 193 |
+
|
| 194 |
+
def grid(META):
|
| 195 |
+
return (triton.cdiv(M, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]),)
|
| 196 |
+
|
| 197 |
+
_w8a8_block_fp8_matmul[grid](
|
| 198 |
+
A,
|
| 199 |
+
B,
|
| 200 |
+
C,
|
| 201 |
+
As,
|
| 202 |
+
Bs,
|
| 203 |
+
M,
|
| 204 |
+
N,
|
| 205 |
+
K,
|
| 206 |
+
block_n,
|
| 207 |
+
block_k,
|
| 208 |
+
A.stride(-2),
|
| 209 |
+
A.stride(-1),
|
| 210 |
+
B.stride(1),
|
| 211 |
+
B.stride(0),
|
| 212 |
+
C.stride(-2),
|
| 213 |
+
C.stride(-1),
|
| 214 |
+
As.stride(-2),
|
| 215 |
+
As.stride(-1),
|
| 216 |
+
Bs.stride(1),
|
| 217 |
+
Bs.stride(0),
|
| 218 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 219 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 220 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 221 |
+
GROUP_SIZE_M=8,
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
return C
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
# Python version of the above triton function, it's much slower than the triton version, for testing
|
| 228 |
+
@torch.compile
|
| 229 |
+
def w8a8_block_fp8_matmul_compile(
|
| 230 |
+
input_q: torch.Tensor, # [batch, seq_len, hidden_dim]
|
| 231 |
+
weight_q: torch.Tensor, # [out_features, hidden_dim]
|
| 232 |
+
input_scale: torch.Tensor, # [batch * seq_len, num_input_groups]
|
| 233 |
+
weight_scale: torch.Tensor, # [num_weight_blocks_m, num_weight_blocks_n]
|
| 234 |
+
block_size: Optional[Tuple[int, int]] = None, # (M=128, N=128) for weights for example
|
| 235 |
+
output_dtype: torch.dtype = torch.float32,
|
| 236 |
+
) -> torch.Tensor:
|
| 237 |
+
"""
|
| 238 |
+
Performs blocked matrix multiplication with FP8 quantized matrices.
|
| 239 |
+
|
| 240 |
+
Args:
|
| 241 |
+
input_q: Quantized input tensor with 1x128 block quantization
|
| 242 |
+
weight_q: Quantized weight tensor with 128x128 block quantization
|
| 243 |
+
input_scale: Scaling factors for input blocks
|
| 244 |
+
weight_scale: Scaling factors for weight blocks
|
| 245 |
+
block_size: Tuple of (M, N) for weight block dimensions
|
| 246 |
+
output_dtype: Desired output dtype
|
| 247 |
+
"""
|
| 248 |
+
batch_size, seq_len, hidden_dim = input_q.shape if input_q.ndim == 3 else (1, input_q.shape[0], input_q.shape[1])
|
| 249 |
+
out_features = weight_q.shape[0]
|
| 250 |
+
|
| 251 |
+
# Reshape input for batched matmul
|
| 252 |
+
input_reshaped = input_q.view(-1, hidden_dim) # [batch*seq_len, hidden_dim]
|
| 253 |
+
input_scale_reshaped = input_scale.view(input_scale.shape[0], -1) # [batch*seq_len, 1]
|
| 254 |
+
# Calculate number of blocks
|
| 255 |
+
num_weight_blocks_m = out_features // block_size[0]
|
| 256 |
+
num_weight_blocks_n = hidden_dim // block_size[1]
|
| 257 |
+
|
| 258 |
+
output = torch.zeros((batch_size * seq_len, out_features), dtype=torch.float32, device=input_q.device)
|
| 259 |
+
|
| 260 |
+
for i in range(num_weight_blocks_m):
|
| 261 |
+
m_start = i * block_size[0]
|
| 262 |
+
m_end = m_start + block_size[0]
|
| 263 |
+
|
| 264 |
+
for j in range(num_weight_blocks_n):
|
| 265 |
+
n_start = j * block_size[1]
|
| 266 |
+
n_end = n_start + block_size[1]
|
| 267 |
+
|
| 268 |
+
# Extract current blocks
|
| 269 |
+
input_block = input_reshaped[:, n_start:n_end]
|
| 270 |
+
weight_block = weight_q[m_start:m_end, n_start:n_end]
|
| 271 |
+
|
| 272 |
+
# Get corresponding scales
|
| 273 |
+
curr_input_scale = input_scale_reshaped[:, j : j + 1] # [batch*seq_len, 1]
|
| 274 |
+
curr_weight_scale = weight_scale[i, j] # scalar
|
| 275 |
+
|
| 276 |
+
block_result = (
|
| 277 |
+
torch._scaled_mm(
|
| 278 |
+
input_block,
|
| 279 |
+
weight_block.t(),
|
| 280 |
+
scale_a=torch.tensor(1, dtype=torch.float32, device=input_q.device),
|
| 281 |
+
scale_b=curr_weight_scale,
|
| 282 |
+
out_dtype=output_dtype,
|
| 283 |
+
)
|
| 284 |
+
* curr_input_scale
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
output[:, m_start:m_end] += block_result
|
| 288 |
+
|
| 289 |
+
output = output.view(batch_size, seq_len, out_features)
|
| 290 |
+
|
| 291 |
+
return output.to(output_dtype)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class FP8Linear(nn.Linear):
|
| 295 |
+
dtype = torch.float8_e4m3fn
|
| 296 |
+
|
| 297 |
+
def __init__(
|
| 298 |
+
self,
|
| 299 |
+
in_features: int,
|
| 300 |
+
out_features: int,
|
| 301 |
+
bias: bool = False,
|
| 302 |
+
dtype=None,
|
| 303 |
+
block_size: Optional[Tuple[int, int]] = None,
|
| 304 |
+
device=None,
|
| 305 |
+
activation_scheme="dynamic",
|
| 306 |
+
):
|
| 307 |
+
super().__init__(in_features, out_features)
|
| 308 |
+
self.in_features = in_features
|
| 309 |
+
self.out_features = out_features
|
| 310 |
+
|
| 311 |
+
self.weight = torch.nn.Parameter(torch.empty(out_features, in_features, dtype=FP8Linear.dtype, device=device))
|
| 312 |
+
|
| 313 |
+
if self.weight.element_size() == 1:
|
| 314 |
+
scale_out_features = (out_features + block_size[0] - 1) // block_size[0]
|
| 315 |
+
scale_in_features = (in_features + block_size[1] - 1) // block_size[1]
|
| 316 |
+
self.weight_scale_inv = nn.Parameter(
|
| 317 |
+
torch.empty(scale_out_features, scale_in_features, dtype=torch.float32, device=device)
|
| 318 |
+
)
|
| 319 |
+
else:
|
| 320 |
+
self.register_parameter("weight_scale_inv", None)
|
| 321 |
+
|
| 322 |
+
self.block_size = block_size
|
| 323 |
+
|
| 324 |
+
self.activation_scheme = activation_scheme
|
| 325 |
+
|
| 326 |
+
if bias:
|
| 327 |
+
self.bias = nn.Parameter(torch.empty(self.out_features))
|
| 328 |
+
else:
|
| 329 |
+
self.register_parameter("bias", None)
|
| 330 |
+
|
| 331 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 332 |
+
if self.weight.element_size() > 1:
|
| 333 |
+
return F.linear(input, self.weight, self.bias)
|
| 334 |
+
else:
|
| 335 |
+
# Context manager used to switch among the available cuda devices
|
| 336 |
+
# with torch.cuda.device(input.device):
|
| 337 |
+
qinput, scale = act_quant(input, self.block_size[1])
|
| 338 |
+
# Blocks the CPU until all CUDA operations on the specified device are complete. It is used to ensure that the results of the
|
| 339 |
+
# preceding operations are ready before proceeding
|
| 340 |
+
# torch.cuda.synchronize(device=self.weight.device)
|
| 341 |
+
with torch.cuda.device(input.device):
|
| 342 |
+
output = w8a8_block_fp8_matmul_triton(
|
| 343 |
+
qinput,
|
| 344 |
+
self.weight,
|
| 345 |
+
scale,
|
| 346 |
+
self.weight_scale_inv,
|
| 347 |
+
self.block_size,
|
| 348 |
+
output_dtype=input.dtype,
|
| 349 |
+
)
|
| 350 |
+
torch.cuda.synchronize()
|
| 351 |
+
if self.bias is not None:
|
| 352 |
+
output = output + self.bias
|
| 353 |
+
return output.to(dtype=input.dtype)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def _replace_with_fp8_linear(
|
| 357 |
+
model,
|
| 358 |
+
tp_plan=None,
|
| 359 |
+
modules_to_not_convert=None,
|
| 360 |
+
current_key_name=None,
|
| 361 |
+
quantization_config=None,
|
| 362 |
+
has_been_replaced=False,
|
| 363 |
+
):
|
| 364 |
+
"""Replace Linear layers with FP8Linear."""
|
| 365 |
+
if current_key_name is None:
|
| 366 |
+
current_key_name = []
|
| 367 |
+
|
| 368 |
+
for name, module in model.named_children():
|
| 369 |
+
current_key_name.append(name)
|
| 370 |
+
|
| 371 |
+
if isinstance(module, nn.Linear) and name not in (modules_to_not_convert or []):
|
| 372 |
+
current_key_name_str = ".".join(current_key_name)
|
| 373 |
+
if not any(key in current_key_name_str for key in (modules_to_not_convert or [])):
|
| 374 |
+
with init_empty_weights():
|
| 375 |
+
model._modules[name] = FP8Linear(
|
| 376 |
+
in_features=module.in_features,
|
| 377 |
+
out_features=module.out_features,
|
| 378 |
+
bias=module.bias is not None,
|
| 379 |
+
device=module.weight.device,
|
| 380 |
+
dtype=module.weight.dtype,
|
| 381 |
+
activation_scheme=quantization_config.activation_scheme,
|
| 382 |
+
block_size=quantization_config.weight_block_size,
|
| 383 |
+
)
|
| 384 |
+
has_been_replaced = True
|
| 385 |
+
# when changing a layer the TP PLAN for that layer should be updated. TODO
|
| 386 |
+
|
| 387 |
+
if len(list(module.children())) > 0:
|
| 388 |
+
_, has_been_replaced = _replace_with_fp8_linear(
|
| 389 |
+
module,
|
| 390 |
+
tp_plan,
|
| 391 |
+
modules_to_not_convert,
|
| 392 |
+
current_key_name,
|
| 393 |
+
quantization_config,
|
| 394 |
+
has_been_replaced=has_been_replaced,
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
current_key_name.pop(-1)
|
| 398 |
+
|
| 399 |
+
return model, has_been_replaced
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def replace_with_fp8_linear(
|
| 403 |
+
model,
|
| 404 |
+
modules_to_not_convert=None,
|
| 405 |
+
quantization_config=None,
|
| 406 |
+
):
|
| 407 |
+
"""Helper function to replace model layers with FP8 versions."""
|
| 408 |
+
modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
|
| 409 |
+
|
| 410 |
+
if quantization_config.modules_to_not_convert is not None:
|
| 411 |
+
modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
|
| 412 |
+
modules_to_not_convert = list(set(modules_to_not_convert))
|
| 413 |
+
model, has_been_replaced = _replace_with_fp8_linear(
|
| 414 |
+
model,
|
| 415 |
+
tp_plan=model._tp_plan,
|
| 416 |
+
modules_to_not_convert=modules_to_not_convert,
|
| 417 |
+
quantization_config=quantization_config,
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
if not has_been_replaced:
|
| 421 |
+
logger.warning(
|
| 422 |
+
"You are loading your model using fp8 but no linear modules were found in your model."
|
| 423 |
+
" Please double check your model architecture."
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
return model
|